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
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Post/Preview/PreviewNonceHandler.swift
2
2772
struct PreviewNonceHandler { static func nonceURL(post: AbstractPost, previewURL: URL?) -> URL? { let permalink = post.permaLink.flatMap(URL.init(string:)) guard var url = previewURL ?? permalink else { return nil } if shouldComposePreviewURL(post: post) { url = addPreviewIfNecessary(url: url) ?? url url = unmapURL(post: post, url: url) ?? url url = addNonceIfNecessary(post: post, url: url) ?? url } return url } private static func addNonceIfNecessary(post: AbstractPost, url: URL) -> URL? { guard post.blog.supports(.noncePreviews), let nonce = post.blog.getOptionValue("frame_nonce") as? String, var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return url } var queryItems = components.queryItems ?? [] queryItems.append(URLQueryItem(name: "frame-nonce", value: nonce)) components.queryItems = queryItems return components.url } private static func unmapURL(post: AbstractPost, url: URL) -> URL? { guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false), let unmappedSite = post.blog.getOptionValue("unmapped_url") as? String, let unmappedSiteURL = URL(string: unmappedSite) else { return url } components.scheme = unmappedSiteURL.scheme components.host = unmappedSiteURL.host return components.url } private static func shouldComposePreviewURL(post: AbstractPost) -> Bool { // If the post is not published, add the preview param. if post.status!.rawValue != PostStatusPublish { return true } // If the post is published, but has changes, add the preview param. if post.hasUnsavedChanges() || post.hasRemoteChanges() { return true } return false } private static func addPreviewIfNecessary(url: URL) -> URL? { guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return url } let queryItems = components.queryItems ?? [] components.queryItems = addPreviewIfNecessary(items: queryItems) return components.url } private static func addPreviewIfNecessary(items: [URLQueryItem]) -> [URLQueryItem] { var queryItems = items // Only add the preview query param if it doesn't exist. if !(queryItems.map { $0.name }).contains("preview") { queryItems.append(URLQueryItem(name: "preview", value: "true")) } return queryItems } }
gpl-2.0
4961615568abb57c72295c7751350180
33.222222
88
0.609307
4.795848
false
false
false
false
khoren93/SwiftHub
SwiftHub/Models/Language.swift
1
2455
// // Language.swift // SwiftHub // // Created by Sygnoos9 on 12/17/18. // Copyright © 2018 Khoren Markosyan. All rights reserved. // import Foundation import ObjectMapper private let languageKey = "CurrentLanguageKey" struct Language: Mappable { var urlParam: String? var name: String? init?(map: Map) {} init() {} mutating func mapping(map: Map) { urlParam <- map["urlParam"] name <- map["name"] } func displayName() -> String { return (name.isNilOrEmpty == false ? name: urlParam) ?? "" } } extension Language { func save() { if let json = self.toJSONString() { UserDefaults.standard.set(json, forKey: languageKey) } else { logError("Language can't be saved") } } static func currentLanguage() -> Language? { if let json = UserDefaults.standard.string(forKey: languageKey), let language = Language(JSONString: json) { return language } return nil } static func removeCurrentLanguage() { UserDefaults.standard.removeObject(forKey: languageKey) } } extension Language: Equatable { static func == (lhs: Language, rhs: Language) -> Bool { return lhs.urlParam == rhs.urlParam } } struct Languages { var totalCount: Int = 0 var totalSize: Int = 0 var languages: [RepoLanguage] = [] init(graph: RepositoryQuery.Data.Repository.Language?) { totalCount = graph?.totalCount ?? 0 totalSize = graph?.totalSize ?? 0 languages = (graph?.edges?.map { RepoLanguage(graph: $0) } ?? []) languages.sort { (lhs, rhs) -> Bool in lhs.size > rhs.size } } } struct RepoLanguage { var size: Int = 0 var name: String? var color: String? init(graph: RepositoryQuery.Data.Repository.Language.Edge?) { size = graph?.size ?? 0 name = graph?.node.name color = graph?.node.color } } struct LanguageLines: Mappable { var language: String? var files: Int? var lines: Int? var blanks: Int? var comments: Int? var linesOfCode: Int? init?(map: Map) {} init() {} mutating func mapping(map: Map) { language <- map["language"] files <- map["files"] lines <- map["lines"] blanks <- map["blanks"] comments <- map["comments"] linesOfCode <- map["linesOfCode"] } }
mit
f590cb6781186268affac9209238a5d8
21.309091
73
0.585167
4.049505
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Game/GameMainNavigationViewController.swift
1
1425
// // GameMainNavigationViewController.swift // Whereami // // Created by WuQifei on 16/2/17. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit class GameMainNavigationViewController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationBar.backgroundColor = UIColor.getGameColor() // self.navigationBar.setBackgroundImage(UIImage.imageWithColor(UIColor(red: 81/255.0, green: 136/255.0, blue: 199/255.0, alpha: 1.0)), forBarMetrics: UIBarMetrics.Default) self.navigationBar.shadowImage = UIImage.imageWithColor(UIColor.clearColor()) self.navigationBar.tintColor = UIColor.whiteColor() self.navigationBar.barTintColor = UIColor.getGameColor() self.navigationBar.translucent = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
356af7d01edfe38d9212278445878db1
32.857143
187
0.697609
4.954704
false
false
false
false
shyamalschandra/swix
swix_ios_app/swix_ios_app/swix/matrix/m-image.swift
3
5664
// // twoD-image.swift // swix // // Created by Scott Sievert on 7/30/14. // Copyright (c) 2014 com.scott. All rights reserved. // /* * some other useful tips that need an iOS app to use: * 1. UIImage to raw array[0]: * 2. raw array to UIImage[1]: * * for a working implementation, see[2] (to be published shortly) * * [0]:http://stackoverflow.com/a/1262893/1141256 * [1]:http://stackoverflow.com/a/12868860/1141256 * [2]:https://github.com/scottsievert/saliency/blob/master/AVCam/AVCam/saliency/imageToRawArray.m * * */ import Foundation import UIKit // for iOS use func rgb2hsv_pixel(R:Double, G:Double, B:Double)->(Double, Double, Double){ // tested against wikipedia/HSL_and_HSV. returns (H, S_hsv, V) let M = max(array(R, G, B)) let m = min(array(R, G, B)) let C = M - m var Hp:Double = 0 if M==R {Hp = ((G-B)/C) % 6} else if M==G {Hp = ((B-R)/C) + 2} else if M==B {Hp = ((R-G)/C) + 4} let H = 60 * Hp let V = M var S = 0.0 if !(V==0) {S = C/V} return (H, S, V) } func rgb2hsv(r:matrix, g:matrix, b:matrix)->(matrix, matrix, matrix){ assert(r.shape.0 == g.shape.0) assert(b.shape.0 == g.shape.0) assert(r.shape.1 == g.shape.1) assert(b.shape.1 == g.shape.1) var h = zeros_like(r) var s = zeros_like(g) var v = zeros_like(b) for i in 0..<r.shape.0{ for j in 0..<r.shape.1{ let (h_p, s_p, v_p) = rgb2hsv_pixel(r[i,j], G: g[i,j], B: b[i,j]) h[i,j] = h_p s[i,j] = s_p v[i,j] = v_p } } return (h, s, v) } func rgb2_hsv_vplane(r:matrix, g:matrix, b:matrix)->matrix{ return max(max(r, y: g), y: b) } func savefig(x:matrix, filename:String, save:Bool=true, show:Bool=false){ // assumes Python is on your $PATH and pylab/etc are installed // prefix should point to the swix folder! // prefix is defined in numbers.swift // assumes python is on your path write_csv(x, filename:"swix/temp.csv") system("cd "+S2_PREFIX+"; "+PYTHON_PATH + " imshow.py \(filename) \(save) \(show)") system("rm "+S2_PREFIX+"temp.csv") } func imshow(x: matrix){ savefig(x, filename: "junk", save:false, show:true) } func UIImageToRGBA(image:UIImage)->(matrix, matrix, matrix, matrix){ // returns red, green, blue and alpha channels // init'ing var imageRef = image.CGImage var width = CGImageGetWidth(imageRef) var height = CGImageGetHeight(imageRef) var colorSpace = CGColorSpaceCreateDeviceRGB() var bytesPerPixel = 4 var bytesPerRow:UInt = UInt(bytesPerPixel) * UInt(width) var bitsPerComponent:UInt = 8 var pix = Int(width) * Int(height) var count:Int = 4*Int(pix) // pulling the color out of the image var rawData = UnsafeMutablePointer<UInt8>.alloc(4 * width * height) var temp = CGImageAlphaInfo.PremultipliedLast.rawValue var bitmapInfo = CGBitmapInfo(rawValue:temp) var context = CGBitmapContextCreate(rawData, Int(width), Int(height), Int(bitsPerComponent), Int(bytesPerRow), colorSpace, temp) CGContextDrawImage(context, CGRectMake(0,0,CGFloat(width), CGFloat(height)), imageRef) // unsigned char to double conversion var rawDataArray = zeros(count)-1 vDSP_vfltu8D(rawData, 1.stride, !(rawDataArray), 1, count.length) // pulling the RGBA channels out of the color var i = arange(pix) var r = zeros((Int(height), Int(width)))-1; r.flat = rawDataArray[4*i+0] var g = zeros((Int(height), Int(width))); g.flat = rawDataArray[4*i+1] var b = zeros((Int(height), Int(width))); b.flat = rawDataArray[4*i+2] var a = zeros((Int(height), Int(width))); a.flat = rawDataArray[4*i+3] return (r, g, b, a) } func RGBAToUIImage(r:matrix, g:matrix, b:matrix, a:matrix)->UIImage{ // might be useful! [1] // [1]:http://stackoverflow.com/questions/30958427/pixel-array-to-uiimage-in-swift // setup var height = r.shape.0 var width = r.shape.1 var area = height * width var componentsPerPixel = 4 // rgba var compressedPixelData = zeros(4*area) var N = width * height // double to unsigned int var i = arange(N) compressedPixelData[4*i+0] = r.flat compressedPixelData[4*i+1] = g.flat compressedPixelData[4*i+2] = b.flat compressedPixelData[4*i+3] = a.flat var pixelData:[CUnsignedChar] = Array(count:area*componentsPerPixel, repeatedValue:0) vDSP_vfixu8D(&compressedPixelData.grid, 1, &pixelData, 1, vDSP_Length(componentsPerPixel*area)) // creating the bitmap context var colorSpace = CGColorSpaceCreateDeviceRGB() var bitsPerComponent = 8 var bytesPerRow = ((bitsPerComponent * width) / 8) * componentsPerPixel var temp = CGImageAlphaInfo.PremultipliedLast.rawValue var bitmapInfo = CGBitmapInfo(rawValue:temp) var context = CGBitmapContextCreate(&pixelData, Int(width), Int(height), Int(bitsPerComponent), Int(bytesPerRow), colorSpace, temp) // creating the image var toCGImage = CGBitmapContextCreateImage(context)! var image:UIImage = UIImage.init(CGImage:toCGImage) return image } func resizeImage(image:UIImage, shape:(Int, Int)) -> UIImage{ // nice variables var (height, width) = shape var cgSize = CGSizeMake(CGFloat(width), CGFloat(height)) // draw on new CGSize UIGraphicsBeginImageContextWithOptions(cgSize, false, 0.0) image.drawInRect(CGRectMake(CGFloat(0), CGFloat(0), CGFloat(width), CGFloat(height))) var newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage }
mit
42ef4c80cbff50e8f0a241bf053fec57
33.327273
135
0.643362
3.36342
false
false
false
false
anzfactory/QiitaCollection
QiitaCollection/QCPathMenuItem.swift
1
914
// // QCPathMenuItem.swift // QiitaCollection // // Created by ANZ on 2015/02/24. // Copyright (c) 2015年 anz. All rights reserved. // import UIKit class QCPathMenuItem: PathMenuItem { typealias TapAction = (sender: QCPathMenuItem) -> Void // MARK: プロパティ var action: TapAction? = nil // MARK: イニシャライザ required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } convenience init(mainImage: UIImage) { self.init(frame: CGRectZero) self.image = mainImage self.highlightedImage = mainImage self.userInteractionEnabled = true self.contentImageView = UIImageView(image: mainImage) self.contentImageView?.highlightedImage = mainImage self.addSubview(self.contentImageView!) } }
mit
e9ed6fd0e0ded316a7a058971c8bf697
22.368421
61
0.638514
4.149533
false
false
false
false
rustedivan/tapmap
geobaketool/Operations/OperationTintRegions.swift
1
2986
// // OperationTintRegions.swift // geobaketool // // Created by Ivan Milles on 2020-10-31. // Copyright © 2020 Wildbrain. All rights reserved. // import Foundation import AppKit.NSImage class OperationTintRegions : Operation { let input : ToolGeoFeatureMap var output : ToolGeoFeatureMap let report : ProgressReport let colorMap : NSBitmapImageRep init(features: ToolGeoFeatureMap, colorMap image: NSBitmapImageRep, reporter: @escaping ProgressReport) { input = features report = reporter colorMap = image output = [:] super.init() } override func main() { guard !isCancelled else { print("Cancelled before starting"); return } for (key, feature) in input { let h = Float((feature.tessellations[0].visualCenter.x + 180.0) / 360.0) let l = Float((feature.tessellations[0].visualCenter.y + 90.0) / 180.0) let u = Int(h * Float(colorMap.pixelsWide)) let v = Int((1.0 - l) * Float(colorMap.pixelsHigh)) // Pick geoColor let pickedColor = colorMap.colorAt(x: u, y: v)! var components: (r: CGFloat, g: CGFloat, b: CGFloat) = (0.0, 0.0, 0.0) pickedColor.getRed(&components.r, green: &components.g, blue: &components.b, alpha: nil) let tessColor = GeoColor(r: Float(components.r), g: Float(components.g), b: Float(components.b)) let tintedTessellations = feature.tessellations.map { return GeoTessellation(vertices: $0.vertices, indices: $0.indices, contours: $0.contours, aabb: $0.aabb, visualCenter: $0.visualCenter, color: tessColor) } let updatedFeature = ToolGeoFeature(level: feature.level, polygons: feature.polygons, tessellations: tintedTessellations, places: feature.places, children: feature.children, stringProperties: feature.stringProperties, valueProperties: feature.valueProperties) output[key] = updatedFeature if (output.count > 0) { let reportLine = "\(feature.name) colored" report((Double(output.count) / Double(input.count)), reportLine, false) } } } static func storeNewColorMap() { guard let inputPath = PipelineConfig.shared.inputColorMapPath, let outputPath = PipelineConfig.shared.storedColorMapPath else { return } do { try FileManager.default.replaceItem(at: outputPath, withItemAt: inputPath, backupItemName: nil, resultingItemURL: nil) } catch { print("Could not copy new color map to pipeline storage") } } static func loadColorMap() -> NSImage { guard let colorMapPath = PipelineConfig.shared.storedColorMapPath else { fatalError("No color map found in pipeline storage.") } let colorMap = NSImage(byReferencing: colorMapPath) if colorMap.isValid { print("Loaded color map...") } else { fatalError("Could not load color map from \(colorMapPath.absoluteString)") } return colorMap } }
mit
bea1523f85d803b0c97c004174741c89
30.755319
130
0.665327
3.662577
false
false
false
false
robinckanatzar/mcw
my-core-wellness/my-core-wellness/PositiveThoughtsVC.swift
1
4488
// // PositiveThoughtsVC.swift // my-core-wellness // // Created by Robin Kanatzar on 3/4/17. // Copyright © 2017 Robin Kanatzar. All rights reserved. // import Foundation import UIKit import CoreData class PositiveThoughtsVC : UIViewController { @IBOutlet weak var editText: UITextView! @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var back: UIBarButtonItem! @IBOutlet weak var buttonBackground: UIView! override func viewDidLoad() { self.view.backgroundColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0) self.navigationItem.title = "Positive Thoughts" navigationItem.leftBarButtonItem = back back.action = #selector(SWRevealViewController.revealToggle(_:)) self.navigationItem.title = "Positive Thoughts" navigationBar.topItem?.title = "Positive Thoughts" editText.layer.masksToBounds = false editText.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor editText.layer.shadowOffset = CGSize(width: 0, height: 0) editText.layer.shadowOpacity = 0.8 editText.layer.cornerRadius = 3.0 buttonBackground.layer.cornerRadius = 15.0 loadOldEntries() setUpKeyboard() } func setUpKeyboard() { // --- keyboard dismiss when you tap outside //Looks for single or multiple taps. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard") //Uncomment the line below if you want the tap not not interfere and cancel other interactions. //tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } //Calls this function when the tap is recognized. func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } @IBAction func button(_ sender: Any) { // save to core data let appDelegate = UIApplication.shared.delegate as! AppDelegate // UIApplication.shared().delegate as! AppDelegate is now UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext // delete all old entries let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "PositiveThoughts") let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) do { try context.execute(batchDeleteRequest) print("deleted old positive thoughts") } catch { // Error Handling print("error deleting old positive thoughts") } let newEntry = NSEntityDescription.insertNewObject(forEntityName: "PositiveThoughts", into: context) let date = Date() let content = editText.text! newEntry.setValue(date, forKey: "date") newEntry.setValue(content, forKey: "content") do { try context.save() print("Saved") } catch { print("There was an error") } } func loadOldEntries() { // load old journal entries let appDelegate = UIApplication.shared.delegate as! AppDelegate // UIApplication.shared().delegate as! AppDelegate is now UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "PositiveThoughts") request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)] request.fetchLimit = 1 request.returnsObjectsAsFaults = false do { let results = try context.fetch(request) print("results.count = " + String(results.count)) if results.count > 0 { for result in results as! [NSManagedObject] { if let content = result.value(forKey: "content") as? String { print(content) editText.text = content } } } else { print("No results") editText.text = "You have nothing saved in positive thoughts" } } catch { print("Couldn't fetch results") } } }
apache-2.0
12022554c5e99480295c0457a01cb8b6
34.611111
175
0.618676
5.193287
false
false
false
false
cybersamx/FotoBox
iOS/FotoBox/AppDelegate.swift
1
2602
// // AppDelegate.swift // FotoBox // // Created by Samuel Chow on 7/4/16. // Copyright © 2016 Cybersam. All rights reserved. // import UIKit import BoxContentSDK @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var config: NSDictionary? func initBoxClient() -> Bool { guard let path = NSBundle.mainBundle().pathForResource("box", ofType: "plist") else { print("box.plist is missing") return false } config = NSDictionary(contentsOfFile: path) guard let clientID = config?["ClientID"] as? String, let clientSecret = config?["ClientSecret"] as? String else { return false } BOXContentClient.setClientID(clientID, clientSecret: clientSecret) return true } func getBoxUser() -> BOXUserMini? { return BOXContentClient.users().first as? BOXUserMini } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { guard initBoxClient() else { // Can't initialize box client. print("Can't initialize Box client. Please check settings.") return false } let navController = window?.rootViewController as! UINavigationController let storyboard = UIStoryboard.init(name: "Main", bundle: nil) if let user = getBoxUser() { // User already logged in. print(user.name) let folderViewController = storyboard.instantiateViewControllerWithIdentifier("FolderViewController") navController.pushViewController(folderViewController, animated: true) } else { // Let the user logs in. // Only OAuth user is supported (for now). let client = BOXContentClient.clientForNewSession() client.authenticateWithCompletionBlock { (user, error) in if error != nil && error.code == Int(BOXContentSDKAPIUserCancelledError.rawValue) { // It's ok to cancel. print("User canceled authentication") } else if error != nil { print("Error") } else { print(user.name) } } } window?.makeKeyWindow() return true } func applicationWillResignActive(application: UIApplication) { } func applicationDidEnterBackground(application: UIApplication) { } func applicationWillEnterForeground(application: UIApplication) { } func applicationDidBecomeActive(application: UIApplication) { } func applicationWillTerminate(application: UIApplication) { } }
mit
37b25c38c09caa839683a4167fa55d25
24.752475
125
0.662053
5.011561
false
false
false
false
Baddaboo/EasyLayout
Framework/Core Layout/EasyLayoutConstraintExtension.swift
1
1256
// // EasyLayoutConstraintExtension.swift // EasyLayout // // Created by Blake Tsuzaki on 7/30/17. // Copyright © 2017 Modoki. All rights reserved. // #if os(iOS) import UIKit public typealias LayoutPriority = UILayoutPriority #elseif os(OSX) import AppKit public typealias LayoutPriority = NSLayoutConstraint.Priority #endif precedencegroup EasyLayoutPriorityPrecedence { higherThan: AssignmentPrecedence } infix operator ~: EasyLayoutPriorityPrecedence extension NSLayoutConstraint { #if os(iOS) public static func ~ (left: NSLayoutConstraint, right: LayoutPriority) -> NSLayoutConstraint { let constraint = left constraint.priority = right return constraint } public static func ~ (left: LayoutPriority, right: NSLayoutConstraint) -> NSLayoutConstraint { return right ~ left } #elseif os(OSX) public static func ~ (left: NSLayoutConstraint, right: NSLayoutConstraint.Priority) -> NSLayoutConstraint { let constraint = left constraint.priority = right return constraint } public static func ~ (left: NSLayoutConstraint.Priority, right: NSLayoutConstraint) -> NSLayoutConstraint { return right ~ left } #endif }
mit
a6863beb1abd6cedd035e8fe225c6096
28.186047
111
0.704382
5.02
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/controller/TKUIAutocompletionViewController.swift
1
4750
// // TKUIAutocompletionViewController.swift // TripKitUI-iOS // // Created by Adrian Schönig on 05.07.18. // Copyright © 2018 SkedGo Pty Ltd. All rights reserved. // import UIKit import MapKit import RxCocoa import RxSwift import TripKit public protocol TKUIAutocompletionViewControllerDelegate: AnyObject { func autocompleter(_ controller: TKUIAutocompletionViewController, didSelect selection: TKAutocompletionSelection) func autocompleter(_ controller: TKUIAutocompletionViewController, didSelectAccessoryFor selection: TKAutocompletionSelection) } /// Displays autocompletion results from search /// /// Typically used as a `searchResultsController` being passed /// to a `UISearchController` and assigned to that search /// controller's `searchResultsUpdater` property. public class TKUIAutocompletionViewController: UITableViewController { public let providers: [TKAutocompleting] public weak var delegate: TKUIAutocompletionViewControllerDelegate? public var showAccessoryButtons = true public var biasMapRect: MKMapRect = .null private var viewModel: TKUIAutocompletionViewModel! private let disposeBag = DisposeBag() private let searchText = PublishSubject<(String, forced: Bool)>() private let accessoryTapped = PublishSubject<TKUIAutocompletionViewModel.Item>() public init(providers: [TKAutocompleting]) { self.providers = providers super.init(style: .plain) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { super.viewDidLoad() let dataSource = RxTableViewSectionedAnimatedDataSource<TKUIAutocompletionViewModel.Section>( configureCell: { [weak self] _, tv, ip, item in guard let self = self else { // Shouldn't but can happen on dealloc return UITableViewCell(style: .default, reuseIdentifier: nil) } guard let cell = tv.dequeueReusableCell(withIdentifier: TKUIAutocompletionResultCell.reuseIdentifier, for: ip) as? TKUIAutocompletionResultCell else { preconditionFailure("Couldn't dequeue TKUIAutocompletionResultCell") } cell.configure( with: item, onAccessoryTapped: self.showAccessoryButtons ? { self.accessoryTapped.onNext($0) } : nil ) return cell }, titleForHeaderInSection: { ds, index in return ds.sectionModels[index].title } ) // Reset to `nil` as we'll overwrite these tableView.delegate = nil tableView.dataSource = nil tableView.register(TKUIAutocompletionResultCell.self, forCellReuseIdentifier: TKUIAutocompletionResultCell.reuseIdentifier) viewModel = TKUIAutocompletionViewModel( providers: providers, searchText: searchText, selected: tableView.rx.itemSelected.map { dataSource[$0] }.asSignal(onErrorSignalWith: .empty()), accessorySelected: accessoryTapped.asSignal(onErrorSignalWith: .empty()), biasMapRect: .just(biasMapRect) ) viewModel.sections .drive(tableView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) viewModel.selection .emit(onNext: { [weak self] annotation in guard let self = self else { return } self.delegate?.autocompleter(self, didSelect: annotation) }) .disposed(by: disposeBag) viewModel.accessorySelection .emit(onNext: { [weak self] annotation in guard let self = self else { return } self.delegate?.autocompleter(self, didSelectAccessoryFor: annotation) }) .disposed(by: disposeBag) viewModel.triggerAction .asObservable() .flatMapLatest { [weak self] provider -> Observable<Bool> in guard let self = self else { return .empty() } return provider.triggerAdditional(presenter: self).asObservable() } .subscribe() .disposed(by: disposeBag) viewModel.error .emit(onNext: { [weak self] in self?.showErrorAsAlert($0) }) .disposed(by: disposeBag) tableView.rx.setDelegate(self) .disposed(by: disposeBag) } } extension TKUIAutocompletionViewController { public override func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.contentOffset.y > 40, !scrollView.isDecelerating { // we are actively scrolling a fair bit => disable the keyboard (parent as? UISearchController)?.searchBar.resignFirstResponder() } } } extension TKUIAutocompletionViewController: UISearchResultsUpdating { public func updateSearchResults(for searchController: UISearchController) { searchText.onNext((searchController.searchBar.text ?? "", forced: false)) } }
apache-2.0
4b14757d3ff2678f6a3ab6dd3eefb210
31.972222
158
0.713353
5.029661
false
false
false
false
IvanVorobei/TwitterLaunchAnimation
TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/ui/controls/buttons/SPRoundButton.swift
2
2572
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([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 public class SPRoundButton: SPRoundFrameButton { override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } private func commonInit() { self.backgroundColor = UIColor.white self.layer.borderWidth = 0 } } public class SPRoundLineButton: SPRoundFrameButton { override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } private func commonInit() { self.backgroundColor = UIColor.clear self.layer.borderWidth = 2 self.layer.borderColor = UIColor(hue: 0, saturation: 0, brightness: 100, alpha: 0.5).cgColor self.layer.borderColor = UIColor.init(white: 1, alpha: 0.5).cgColor } } public class SPRoundFrameButton: UIButton { override public func layoutSubviews() { super.layoutSubviews() let minSide = min(self.frame.width, self.frame.height) self.layer.cornerRadius = minSide / 2 self.clipsToBounds = true } }
mit
a43de6017e82aee5297f3df00f886bd7
33.743243
81
0.656943
4.607527
false
false
false
false
sovereignshare/fly-smuthe
Fly Smuthe/Fly Smuthe/IntensityRatingConstants.swift
1
349
// // IntensityRatingConstants.swift // Fly Smuthe // // Created by Adam M Rivera on 9/5/15. // Copyright (c) 2015 Adam M Rivera. All rights reserved. // import Foundation struct IntensityRatingConstants{ static let Smooth = 1; static let Light = 2; static let Moderate = 3; static let Severe = 4; static let Extreme = 5; }
gpl-3.0
6528a503faf60096927c2966aecef4a1
19.588235
58
0.670487
3.38835
false
false
false
false
Piwigo/Piwigo-Mobile
piwigo/Album/Headers & Footers/NberImagesFooterCollectionReusableView.swift
1
1555
// // NberImagesFooterCollectionReusableView.swift // piwigo // // Created by Eddy Lelièvre-Berna on 02/04/2018. // Copyright © 2018 Piwigo.org. All rights reserved. // // Converted to Swift 5.1 by Eddy Lelièvre-Berna on 14/04/2020 // import UIKit class NberImagesFooterCollectionReusableView: UICollectionReusableView { var noImagesLabel: UILabel? override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear noImagesLabel = UILabel() noImagesLabel?.backgroundColor = UIColor.clear noImagesLabel?.translatesAutoresizingMaskIntoConstraints = false noImagesLabel?.numberOfLines = 0 noImagesLabel?.adjustsFontSizeToFitWidth = false noImagesLabel?.lineBreakMode = .byWordWrapping noImagesLabel?.textAlignment = .center noImagesLabel?.font = .piwigoFontLight() noImagesLabel?.text = NSLocalizedString("categoryMainEmtpy", comment: "No albums in your Piwigo yet.\rYou may pull down to refresh or re-login.") if let noImagesLabel = noImagesLabel { addSubview(noImagesLabel) addConstraints(NSLayoutConstraint.constraintCenter(noImagesLabel)!) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func prepareForReuse() { super.prepareForReuse() noImagesLabel?.text = NSLocalizedString("categoryMainEmtpy", comment: "No albums in your Piwigo yet.\rYou may pull down to refresh or re-login.") } }
mit
dfd01d57de702613849ddf87bc871126
34.272727
153
0.697165
5.088525
false
false
false
false
alltheflow/iCopyPasta
iCopyPasta/PasteboardItem.swift
1
1075
// // PasteboardItem.swift // iCopyPasta // // Created by Agnes Vasarhelyi on 05/01/16. // Copyright © 2016 Agnes Vasarhelyi. All rights reserved. // import UIKit extension UIImage { public override func isEqual(object: AnyObject?) -> Bool { guard let otherImage = object as? UIImage else { return false } guard let lhsiTiff = UIImagePNGRepresentation(self), let rhsiTiff = UIImagePNGRepresentation(otherImage) else { return false } return lhsiTiff.isEqualToData(rhsiTiff) } } func ==(lhs: PasteboardItem, rhs: PasteboardItem) -> Bool { switch (lhs, rhs) { case (.Text(let str1), .Text(let str2)): return str1 == str2 case (.Image(let img1), .Image(let img2)): return img1.isEqual(img2) case (.URL(let str1), .URL(let str2)): return str1 == str2 default: return false } } func !=(lhs: PasteboardItem, rhs: PasteboardItem) -> Bool { return !(lhs == rhs) } enum PasteboardItem { case Text(String) case URL(NSURL) case Image(UIImage) }
mit
8af9b96657b4314d5587adc54e42a358
22.866667
72
0.630354
3.640678
false
false
false
false
vbudhram/firefox-ios
SyncTests/MockSyncServerTests.swift
5
9141
/* 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 Shared import Storage @testable import Sync import UIKit import XCTest class MockSyncServerTests: XCTestCase { var server: MockSyncServer! var client: Sync15StorageClient! override func setUp() { server = MockSyncServer(username: "1234567") server.start() client = getClient(server: server) } private func getClient(server: MockSyncServer) -> Sync15StorageClient? { guard let url = server.baseURL.asURL else { XCTFail("Couldn't get URL.") return nil } let authorizer: Authorizer = identity let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass) return Sync15StorageClient(serverURI: url, authorizer: authorizer, workQueue: queue, resultQueue: queue, backoff: MockBackoffStorage()) } func testDeleteSpec() { // Deletion of a collection path itself, versus trailing slash, sets the right flags. let all = SyncDeleteRequestSpec.fromPath(path: "/1.5/123456/storage/bookmarks", withQuery: [:])! XCTAssertTrue(all.wholeCollection) XCTAssertNil(all.ids) let some = SyncDeleteRequestSpec.fromPath(path: "/1.5/123456/storage/bookmarks", withQuery: ["ids": "123456,abcdef" as AnyObject])! XCTAssertFalse(some.wholeCollection) XCTAssertEqual(["123456", "abcdef"], some.ids!) let one = SyncDeleteRequestSpec.fromPath(path: "/1.5/123456/storage/bookmarks/123456", withQuery: [:])! XCTAssertFalse(one.wholeCollection) XCTAssertNil(one.ids) } func testInfoCollections() { server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326251111000) server.storeRecords(records: [], inCollection: "tabs", now: 1326252222500) server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326252222000) server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: Bytes.generateGUID(), modified: 0)], inCollection: "clients", now: 1326253333000) let expectation = self.expectation(description: "Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! client.getInfoCollections().upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! // JSON contents. XCTAssertEqual(response.value.collectionNames().sorted(), ["bookmarks", "clients", "tabs"]) XCTAssertEqual(response.value.modified("bookmarks"), 1326252222000) XCTAssertEqual(response.value.modified("clients"), 1326253333000) // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertEqual(response.metadata.records, 3) // bookmarks, clients, tabs. // X-Last-Modified, max of all collection modified timestamps. XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326253333000) expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testGet() { server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "guid", modified: 0)], inCollection: "bookmarks", now: 1326251111000) let collectionClient = client.clientForCollection("bookmarks", encrypter: getEncrypter()) let expectation = self.expectation(description: "Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! collectionClient.get("guid").upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! // JSON contents. XCTAssertEqual(response.value.id, "guid") XCTAssertEqual(response.value.modified, 1326251111000) // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertNil(response.metadata.records) // X-Last-Modified. XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326251111000) expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) // And now a missing record, which should produce a 404. collectionClient.get("missing").upon { result in XCTAssertNotNil(result.failureValue) guard let response = result.failureValue else { expectation.fulfill() return } XCTAssertNotNil(response as? NotFound<HTTPURLResponse>) } } func testWipeStorage() { server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "a", modified: 0)], inCollection: "bookmarks", now: 1326251111000) server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "b", modified: 0)], inCollection: "bookmarks", now: 1326252222000) server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "c", modified: 0)], inCollection: "clients", now: 1326253333000) server.storeRecords(records: [], inCollection: "tabs") // For now, only testing wiping the storage root, which is the only thing we use in practice. let expectation = self.expectation(description: "Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! client.wipeStorage().upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! // JSON contents: should be the empty object. let jsonData = try! response.value.rawData() let jsonString = String(data: jsonData, encoding: .utf8)! XCTAssertEqual(jsonString, "{}") // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertNil(response.metadata.records) // X-Last-Modified. XCTAssertNil(response.metadata.lastModifiedMilliseconds) // And we really wiped the data. XCTAssertTrue(self.server.collections.isEmpty) expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testPut() { // For now, only test uploading crypto/keys. There's nothing special about this PUT, however. let expectation = self.expectation(description: "Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: KeyBundle.random(), ifUnmodifiedSince: nil).upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! // Contents: should be just the record timestamp. XCTAssertLessThanOrEqual(before, response.value) XCTAssertLessThanOrEqual(response.value, after) // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertNil(response.metadata.records) // X-Last-Modified. XCTAssertNil(response.metadata.lastModifiedMilliseconds) // And we really uploaded the record. XCTAssertNotNil(self.server.collections["crypto"]) XCTAssertNotNil(self.server.collections["crypto"]?.records["keys"]) expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } }
mpl-2.0
8d8c5319912078d351d9374fcfeab272
46.118557
160
0.66612
5.437835
false
true
false
false
SomeSimpleSolutions/MemorizeItForever
MemorizeItForeverCore/MemorizeItForeverCore/DataAccess/DataAccess/DepotPhraseDataAccess.swift
1
2714
// // DepotPhraseDataAccess.swift // MemorizeItForeverCore // // Created by Hadi Zamani on 11/8/19. // Copyright © 2019 SomeSimpleSolutions. All rights reserved. // import BaseLocalDataAccess class DepotPhraseDataAccess: DepotPhraseDataAccessProtocol { private var genericDataAccess: GenericDataAccess<DepotPhraseEntity>! init(genericDataAccess: GenericDataAccess<DepotPhraseEntity>) { self.genericDataAccess = genericDataAccess } func save(depotPhraseModel: DepotPhraseModel) throws { do{ let depotPhraseEntity = try genericDataAccess.createNewInstance() depotPhraseEntity.id = genericDataAccess.generateId() depotPhraseEntity.phrase = depotPhraseModel.phrase try genericDataAccess.saveEntity() } catch EntityCRUDError.failNewEntity(let entityName){ throw EntityCRUDError.failNewEntity(entityName) } catch{ throw EntityCRUDError.failSaveEntity(genericDataAccess.getEntityName()) } } func save(depotPhraseModels: [DepotPhraseModel]) throws { do{ for model in depotPhraseModels { let depotPhraseEntity = try genericDataAccess.createNewInstance() depotPhraseEntity.id = genericDataAccess.generateId() depotPhraseEntity.phrase = model.phrase } try genericDataAccess.saveEntity() } catch EntityCRUDError.failNewEntity(let entityName){ throw EntityCRUDError.failNewEntity(entityName) } catch{ throw EntityCRUDError.failSaveEntity(genericDataAccess.getEntityName()) } } func fetchAll() throws -> [DepotPhraseModel] { do{ return try genericDataAccess.fetchModels(predicate: nil, sort: nil) } catch let error as NSError{ throw DataAccessError.failFetchData(error.localizedDescription) } } func delete(_ depotPhraseModel: DepotPhraseModel) throws{ do{ guard let id = depotPhraseModel.id else{ throw EntityCRUDError.failDeleteEntity(genericDataAccess.getEntityName()) } if let depotPhraseEntity = try genericDataAccess.fetchEntity(withId: id){ try genericDataAccess.deleteEntity(depotPhraseEntity) } else{ throw DataAccessError.failFetchData("There is no depotPhrase entity with id: \(id)") } } catch let error as NSError{ throw DataAccessError.failDeleteData(error.localizedDescription) } } }
mit
855c3c9d865201a09f9d19310ee17fbc
32.9125
100
0.63509
5.128544
false
false
false
false
billdonner/sheetcheats9
CircleMenuLib/CircleMenuLoader/CircleMenuLoader.swift
1
5539
// // CircleMenuLoader.swift // CircleMenu // // Copyright (c) 18/01/16. Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit internal class CircleMenuLoader: UIView { // MARK: properties var circle: CAShapeLayer? // MARK: life cycle internal init(radius: CGFloat, strokeWidth: CGFloat, platform: UIView, color: UIColor?) { super.init(frame: CGRect(x: 0, y: 0, width: radius, height: radius)) platform.addSubview(self) circle = createCircle(radius, strokeWidth: strokeWidth, color: color) createConstraints(platform: platform, radius: radius) let circleFrame = CGRect( x: radius * 2 - strokeWidth, y: radius - strokeWidth / 2, width: strokeWidth, height: strokeWidth) createRoundView(circleFrame, color: color) backgroundColor = UIColor.clear } required internal init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: create fileprivate func createCircle(_ radius: CGFloat, strokeWidth: CGFloat, color: UIColor?) -> CAShapeLayer { let circlePath = UIBezierPath( arcCenter: CGPoint(x: radius, y: radius), radius: CGFloat(radius) - strokeWidth / 2.0, startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true) let circle = Init(CAShapeLayer()) { $0.path = circlePath.cgPath $0.fillColor = UIColor.clear.cgColor $0.strokeColor = color?.cgColor $0.lineWidth = strokeWidth } self.layer.addSublayer(circle) return circle } fileprivate func createConstraints(platform: UIView, radius: CGFloat) { translatesAutoresizingMaskIntoConstraints = false // added constraints let sizeConstraints = [NSLayoutAttribute.width, .height].map { NSLayoutConstraint(item: self, attribute: $0, relatedBy: .equal, toItem: nil, attribute: $0, multiplier: 1, constant: radius * 2.0) } addConstraints(sizeConstraints) let centerConstaraints = [NSLayoutAttribute.centerY, .centerX].map { NSLayoutConstraint(item: platform, attribute: $0, relatedBy: .equal, toItem: self, attribute: $0, multiplier: 1, constant:0) } platform.addConstraints(centerConstaraints) } internal func createRoundView(_ rect: CGRect, color: UIColor?) { let roundView = Init(UIView(frame: rect)) { $0.backgroundColor = UIColor.black $0.layer.cornerRadius = rect.size.width / 2.0 $0.backgroundColor = color } addSubview(roundView) } // MARK: animations internal func fillAnimation(_ duration: Double, startAngle: Float, completion: @escaping () -> Void) { guard circle != nil else { return } let rotateTransform = CATransform3DMakeRotation(CGFloat(startAngle.degrees), 0, 0, 1) layer.transform = rotateTransform CATransaction.begin() CATransaction.setCompletionBlock(completion) let animation = Init(CABasicAnimation(keyPath: "strokeEnd")) { $0.duration = CFTimeInterval(duration) $0.fromValue = (0) $0.toValue = (1) $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } circle?.add(animation, forKey: nil) CATransaction.commit() } internal func hideAnimation(_ duration: CGFloat, delay: Double, completion: @escaping () -> Void) { let scale = Init(CABasicAnimation(keyPath: "transform.scale")) { $0.toValue = 1.2 $0.duration = CFTimeInterval(duration) $0.fillMode = kCAFillModeForwards $0.isRemovedOnCompletion = false $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) $0.beginTime = CACurrentMediaTime() + delay } layer.add(scale, forKey: nil) UIView.animate( withDuration: CFTimeInterval(duration), delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in self.alpha = 0 }, completion: { (success) -> Void in self.removeFromSuperview() completion() }) } }
apache-2.0
0e8c55c1af75b1896d5cdcea23ac05b5
33.836478
107
0.641271
4.742295
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/BuySellKit/Analytics/NewAnalyticsEvents+Swap.swift
1
2481
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import Foundation extension AnalyticsEvents.New { public enum Swap: AnalyticsEvent { public var type: AnalyticsEventType { .nabu } case swapClicked(origin: Origin) case swapViewed case swapAmountEntered( inputAmount: Double, inputCurrency: String, inputType: AccountType, outputAmount: Double, outputCurrency: String, outputType: AccountType ) case swapAmountMinClicked( amountCurrency: String?, inputCurrency: String, inputType: AccountType, outputCurrency: String, outputType: AccountType ) case swapAmountMaxClicked( amountCurrency: String?, inputCurrency: String, inputType: AccountType, outputCurrency: String, outputType: AccountType ) case swapFromSelected( inputCurrency: String, inputType: AccountType ) case swapReceiveSelected( outputCurrency: String, outputType: AccountType ) case swapAccountsSelected( inputCurrency: String, inputType: AccountType, outputCurrency: String, outputType: AccountType, wasSuggested: Bool ) case swapRequested( exchangeRate: Double, inputAmount: Double, inputCurrency: String, inputType: AccountType, networkFeeInputAmount: Double, networkFeeInputCurrency: String, networkFeeOutputAmount: Double, networkFeeOutputCurrency: String, outputAmount: Double, outputCurrency: String, outputType: AccountType ) } public enum Origin: String, StringRawRepresentable { case dashboardPromo = "DASHBOARD_PROMO" case navigation = "NAVIGATION" case currencyPage = "CURRENCY_PAGE" } public enum AccountType: String, StringRawRepresentable { case trading = "TRADING" case userKey = "USERKEY" public init(_ account: BlockchainAccount) { switch account { case is CryptoNonCustodialAccount: self = .userKey default: self = .trading } } } }
lgpl-3.0
1c6c2fe918aff9f7051c7e649fa4b658
28.52381
62
0.574194
5.486726
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionUI/Send/Router/SendRootViewController.swift
1
2369
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import PlatformUIKit import RIBs import RxSwift import ToolKit import UIComponentsKit protocol SendRootViewControllable: ViewControllable { func replaceRoot(viewController: ViewControllable?) func replaceRoot(viewController: ViewControllable?, animated: Bool) func present(viewController: ViewControllable?) func present(viewController: ViewControllable?, animated: Bool) } extension SendRootViewControllable { func replaceRoot(viewController: ViewControllable?) { replaceRoot(viewController: viewController, animated: true) } func present(viewController: ViewControllable?) { present(viewController: viewController, animated: true) } } final class SendRootViewController: UINavigationController, SendRootViewControllable { // MARK: - Public weak var listener: SendRootListener? // MARK: - Private Properties private let topMostViewControllerProvider: TopMostViewControllerProviding private var hideNavigationBar: Bool = true private var hideNavigationBarSubscription: AnyCancellable? @LazyInject var featureFlagsService: FeatureFlagsServiceAPI // MARK: - Init init(topMostViewControllerProvider: TopMostViewControllerProviding = resolve()) { self.topMostViewControllerProvider = topMostViewControllerProvider super.init(nibName: nil, bundle: nil) view.backgroundColor = .white } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() setNavigationBarHidden(hideNavigationBar, animated: false) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { unimplemented() } // MARK: - Public Functions (SendRootViewControllable) func replaceRoot(viewController: ViewControllable?, animated: Bool) { guard let viewController = viewController else { return } setViewControllers([viewController.uiviewController], animated: animated) } func present(viewController: ViewControllable?, animated: Bool) { guard let viewController = viewController else { return } topMostViewControllerProvider.topMostViewController? .present(viewController.uiviewController, animated: animated) } }
lgpl-3.0
9b92c2d295ef78d9c2ce8b6d37b8b2a7
30.157895
86
0.734797
5.803922
false
false
false
false
RushingTwist/SwiftExamples
Swifttttt/Pods/Moya/Sources/Moya/Response.swift
4
6964
import Foundation /// Represents a response to a `MoyaProvider.request`. public final class Response: CustomDebugStringConvertible, Equatable { /// The status code of the response. public let statusCode: Int /// The response data. public let data: Data /// The original URLRequest for the response. public let request: URLRequest? /// The HTTPURLResponse object. public let response: HTTPURLResponse? public init(statusCode: Int, data: Data, request: URLRequest? = nil, response: HTTPURLResponse? = nil) { self.statusCode = statusCode self.data = data self.request = request self.response = response } /// A text description of the `Response`. public var description: String { return "Status Code: \(statusCode), Data Length: \(data.count)" } /// A text description of the `Response`. Suitable for debugging. public var debugDescription: String { return description } public static func == (lhs: Response, rhs: Response) -> Bool { return lhs.statusCode == rhs.statusCode && lhs.data == rhs.data && lhs.response == rhs.response } } public extension Response { /** Returns the `Response` if the `statusCode` falls within the specified range. - parameters: - statusCodes: The range of acceptable status codes. - throws: `MoyaError.statusCode` when others are encountered. */ public func filter(statusCodes: ClosedRange<Int>) throws -> Response { guard statusCodes.contains(statusCode) else { throw MoyaError.statusCode(self) } return self } /** Returns the `Response` if it has the specified `statusCode`. - parameters: - statusCode: The acceptable status code. - throws: `MoyaError.statusCode` when others are encountered. */ public func filter(statusCode: Int) throws -> Response { return try filter(statusCodes: statusCode...statusCode) } /** Returns the `Response` if the `statusCode` falls within the range 200 - 299. - throws: `MoyaError.statusCode` when others are encountered. */ public func filterSuccessfulStatusCodes() throws -> Response { return try filter(statusCodes: 200...299) } /** Returns the `Response` if the `statusCode` falls within the range 200 - 399. - throws: `MoyaError.statusCode` when others are encountered. */ public func filterSuccessfulStatusAndRedirectCodes() throws -> Response { return try filter(statusCodes: 200...399) } /// Maps data received from the signal into a UIImage. func mapImage() throws -> Image { guard let image = Image(data: data) else { throw MoyaError.imageMapping(self) } return image } /// Maps data received from the signal into a JSON object. /// /// - parameter failsOnEmptyData: A Boolean value determining /// whether the mapping should fail if the data is empty. func mapJSON(failsOnEmptyData: Bool = true) throws -> Any { do { return try JSONSerialization.jsonObject(with: data, options: .allowFragments) } catch { if data.count < 1 && !failsOnEmptyData { return NSNull() } throw MoyaError.jsonMapping(self) } } /// Maps data received from the signal into a String. /// /// - parameter atKeyPath: Optional key path at which to parse string. public func mapString(atKeyPath keyPath: String? = nil) throws -> String { if let keyPath = keyPath { // Key path was provided, try to parse string at key path guard let jsonDictionary = try mapJSON() as? NSDictionary, let string = jsonDictionary.value(forKeyPath: keyPath) as? String else { throw MoyaError.stringMapping(self) } return string } else { // Key path was not provided, parse entire response as string guard let string = String(data: data, encoding: .utf8) else { throw MoyaError.stringMapping(self) } return string } } /// Maps data received from the signal into a Decodable object. /// /// - parameter atKeyPath: Optional key path at which to parse object. /// - parameter using: A `JSONDecoder` instance which is used to decode data to an object. func map<D: Decodable>(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder(), failsOnEmptyData: Bool = true) throws -> D { let serializeToData: (Any) throws -> Data? = { (jsonObject) in guard JSONSerialization.isValidJSONObject(jsonObject) else { return nil } do { return try JSONSerialization.data(withJSONObject: jsonObject) } catch { throw MoyaError.jsonMapping(self) } } let jsonData: Data keyPathCheck: if let keyPath = keyPath { guard let jsonObject = (try mapJSON(failsOnEmptyData: failsOnEmptyData) as? NSDictionary)?.value(forKeyPath: keyPath) else { if failsOnEmptyData { throw MoyaError.jsonMapping(self) } else { jsonData = data break keyPathCheck } } if let data = try serializeToData(jsonObject) { jsonData = data } else { let wrappedJsonObject = ["value": jsonObject] let wrappedJsonData: Data if let data = try serializeToData(wrappedJsonObject) { wrappedJsonData = data } else { throw MoyaError.jsonMapping(self) } do { return try decoder.decode(DecodableWrapper<D>.self, from: wrappedJsonData).value } catch let error { throw MoyaError.objectMapping(error, self) } } } else { jsonData = data } do { if jsonData.count < 1 && !failsOnEmptyData { if let emptyJSONObjectData = "{}".data(using: .utf8), let emptyDecodableValue = try? decoder.decode(D.self, from: emptyJSONObjectData) { return emptyDecodableValue } else if let emptyJSONArrayData = "[{}]".data(using: .utf8), let emptyDecodableValue = try? decoder.decode(D.self, from: emptyJSONArrayData) { return emptyDecodableValue } } return try decoder.decode(D.self, from: jsonData) } catch let error { throw MoyaError.objectMapping(error, self) } } } private struct DecodableWrapper<T: Decodable>: Decodable { let value: T }
apache-2.0
ee62bec2b6bb41be5dbc4a38cebc8de4
35.270833
165
0.594917
5.116826
false
false
false
false
maximbilan/UIAlertController-Customization
AlertControllerCustomization/Sources/ViewController.swift
1
1883
// // ViewController.swift // AlertControllerCustomization // // Created by Maxim on 2/18/16. // Copyright © 2016 Maxim Bilan. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let rightBarButton = UIBarButtonItem(title: "Press", style: UIBarButtonItem.Style.done, target: self, action: #selector(ViewController.pressAction)) self.navigationItem.rightBarButtonItem = rightBarButton } @objc func pressAction() { let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertController.Style.actionSheet) let alertAction1 = UIAlertAction(title: "One", style: UIAlertAction.Style.default, handler: nil) let alertAction2 = UIAlertAction(title: "Two", style: UIAlertAction.Style.default, handler: nil) let alertAction3 = UIAlertAction(title: "Three", style: UIAlertAction.Style.default, handler: nil) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil) alertAction1.setValue(UIImage(named: "image1.png")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), forKey: "image") alertAction3.setValue(UIImage(named: "image3.png")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), forKey: "image") let switchAlert = SwitchAlertActionViewController() switchAlert.isSwitchOn = true alertAction2.setValue(switchAlert, forKey: "contentViewController") alertController.addAction(alertAction1) alertController.addAction(alertAction2) alertController.addAction(alertAction3) alertController.addAction(cancelAction) let popPresenter = alertController.popoverPresentationController popPresenter?.sourceView = self.view popPresenter?.barButtonItem = self.navigationItem.rightBarButtonItem self.present(alertController, animated: true, completion: nil) } }
mit
8ccb7b5a9998446d89c3a732d38df1e3
39.913043
150
0.783741
4.407494
false
false
false
false
StYaphet/firefox-ios
Client/Frontend/Browser/TabToolbar.swift
2
14286
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Shared protocol TabToolbarProtocol: AnyObject { var tabToolbarDelegate: TabToolbarDelegate? { get set } var tabsButton: TabsButton { get } var appMenuButton: ToolbarButton { get } var libraryButton: ToolbarButton { get } var forwardButton: ToolbarButton { get } var backButton: ToolbarButton { get } var stopReloadButton: ToolbarButton { get } var actionButtons: [Themeable & UIButton] { get } func updateBackStatus(_ canGoBack: Bool) func updateForwardStatus(_ canGoForward: Bool) func updateReloadStatus(_ isLoading: Bool) func updatePageStatus(_ isWebPage: Bool) func updateTabCount(_ count: Int, animated: Bool) func privateModeBadge(visible: Bool) func appMenuBadge(setVisible: Bool) func warningMenuBadge(setVisible: Bool) } protocol TabToolbarDelegate: AnyObject { func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressLibrary(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) func tabToolbarDidLongPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) } @objcMembers open class TabToolbarHelper: NSObject { let toolbar: TabToolbarProtocol let ImageReload = UIImage.templateImageNamed("nav-refresh") let ImageStop = UIImage.templateImageNamed("nav-stop") var loading: Bool = false { didSet { if loading { toolbar.stopReloadButton.setImage(ImageStop, for: .normal) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Stop", comment: "Accessibility Label for the tab toolbar Stop button") } else { toolbar.stopReloadButton.setImage(ImageReload, for: .normal) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the tab toolbar Reload button") } } } fileprivate func setTheme(forButtons buttons: [Themeable]) { buttons.forEach { $0.applyTheme() } } init(toolbar: TabToolbarProtocol) { self.toolbar = toolbar super.init() toolbar.backButton.setImage(UIImage.templateImageNamed("nav-back"), for: .normal) toolbar.backButton.accessibilityLabel = NSLocalizedString("Back", comment: "Accessibility label for the Back button in the tab toolbar.") let longPressGestureBackButton = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressBack)) toolbar.backButton.addGestureRecognizer(longPressGestureBackButton) toolbar.backButton.addTarget(self, action: #selector(didClickBack), for: .touchUpInside) toolbar.forwardButton.setImage(UIImage.templateImageNamed("nav-forward"), for: .normal) toolbar.forwardButton.accessibilityLabel = NSLocalizedString("Forward", comment: "Accessibility Label for the tab toolbar Forward button") let longPressGestureForwardButton = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressForward)) toolbar.forwardButton.addGestureRecognizer(longPressGestureForwardButton) toolbar.forwardButton.addTarget(self, action: #selector(didClickForward), for: .touchUpInside) toolbar.stopReloadButton.setImage(UIImage.templateImageNamed("nav-refresh"), for: .normal) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the tab toolbar Reload button") let longPressGestureStopReloadButton = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressStopReload)) toolbar.stopReloadButton.addGestureRecognizer(longPressGestureStopReloadButton) toolbar.stopReloadButton.addTarget(self, action: #selector(didClickStopReload), for: .touchUpInside) toolbar.tabsButton.addTarget(self, action: #selector(didClickTabs), for: .touchUpInside) let longPressGestureTabsButton = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressTabs)) toolbar.tabsButton.addGestureRecognizer(longPressGestureTabsButton) toolbar.appMenuButton.contentMode = .center toolbar.appMenuButton.setImage(UIImage.templateImageNamed("nav-menu"), for: .normal) toolbar.appMenuButton.accessibilityLabel = Strings.AppMenuButtonAccessibilityLabel toolbar.appMenuButton.addTarget(self, action: #selector(didClickMenu), for: .touchUpInside) toolbar.appMenuButton.accessibilityIdentifier = "TabToolbar.menuButton" toolbar.libraryButton.contentMode = .center toolbar.libraryButton.setImage(UIImage.templateImageNamed("menu-library"), for: .normal) toolbar.libraryButton.accessibilityLabel = Strings.AppMenuButtonAccessibilityLabel toolbar.libraryButton.addTarget(self, action: #selector(didClickLibrary), for: .touchUpInside) toolbar.libraryButton.accessibilityIdentifier = "TabToolbar.libraryButton" setTheme(forButtons: toolbar.actionButtons) } func didClickBack() { toolbar.tabToolbarDelegate?.tabToolbarDidPressBack(toolbar, button: toolbar.backButton) } func didLongPressBack(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressBack(toolbar, button: toolbar.backButton) } } func didClickTabs() { toolbar.tabToolbarDelegate?.tabToolbarDidPressTabs(toolbar, button: toolbar.tabsButton) } func didLongPressTabs(_ recognizer: UILongPressGestureRecognizer) { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressTabs(toolbar, button: toolbar.tabsButton) } func didClickForward() { toolbar.tabToolbarDelegate?.tabToolbarDidPressForward(toolbar, button: toolbar.forwardButton) } func didLongPressForward(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressForward(toolbar, button: toolbar.forwardButton) } } func didClickMenu() { toolbar.tabToolbarDelegate?.tabToolbarDidPressMenu(toolbar, button: toolbar.appMenuButton) } func didClickLibrary() { toolbar.tabToolbarDelegate?.tabToolbarDidPressLibrary(toolbar, button: toolbar.appMenuButton) } func didClickStopReload() { if loading { toolbar.tabToolbarDelegate?.tabToolbarDidPressStop(toolbar, button: toolbar.stopReloadButton) } else { toolbar.tabToolbarDelegate?.tabToolbarDidPressReload(toolbar, button: toolbar.stopReloadButton) } } func didLongPressStopReload(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began && !loading { toolbar.tabToolbarDelegate?.tabToolbarDidLongPressReload(toolbar, button: toolbar.stopReloadButton) } } func updateReloadStatus(_ isLoading: Bool) { loading = isLoading } } class ToolbarButton: UIButton { var selectedTintColor: UIColor! var unselectedTintColor: UIColor! var disabledTintColor = UIColor.Photon.Grey50 // Optionally can associate a separator line that hide/shows along with the button weak var separatorLine: UIView? override init(frame: CGRect) { super.init(frame: frame) adjustsImageWhenHighlighted = false selectedTintColor = tintColor unselectedTintColor = tintColor imageView?.contentMode = .scaleAspectFit } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open var isHighlighted: Bool { didSet { self.tintColor = isHighlighted ? selectedTintColor : unselectedTintColor } } override open var isEnabled: Bool { didSet { self.tintColor = isEnabled ? unselectedTintColor : disabledTintColor } } override var tintColor: UIColor! { didSet { self.imageView?.tintColor = self.tintColor } } override var isHidden: Bool { didSet { separatorLine?.isHidden = isHidden } } } extension ToolbarButton: Themeable { func applyTheme() { selectedTintColor = UIColor.theme.toolbarButton.selectedTint disabledTintColor = UIColor.theme.toolbarButton.disabledTint unselectedTintColor = UIColor.theme.browser.tint tintColor = isEnabled ? unselectedTintColor : disabledTintColor imageView?.tintColor = tintColor } } class TabToolbar: UIView { weak var tabToolbarDelegate: TabToolbarDelegate? let tabsButton = TabsButton() let appMenuButton = ToolbarButton() let libraryButton = ToolbarButton() let forwardButton = ToolbarButton() let backButton = ToolbarButton() let stopReloadButton = ToolbarButton() let actionButtons: [Themeable & UIButton] fileprivate let privateModeBadge = BadgeWithBackdrop(imageName: "privateModeBadge", backdropCircleColor: UIColor.Defaults.MobilePrivatePurple) fileprivate let appMenuBadge = BadgeWithBackdrop(imageName: "menuBadge") fileprivate let warningMenuBadge = BadgeWithBackdrop(imageName: "menuWarning", imageMask: "warning-mask") var helper: TabToolbarHelper? private let contentView = UIStackView() fileprivate override init(frame: CGRect) { actionButtons = [backButton, forwardButton, stopReloadButton, tabsButton, appMenuButton] super.init(frame: frame) setupAccessibility() addSubview(contentView) helper = TabToolbarHelper(toolbar: self) addButtons(actionButtons) privateModeBadge.add(toParent: contentView) appMenuBadge.add(toParent: contentView) warningMenuBadge.add(toParent: contentView) contentView.axis = .horizontal contentView.distribution = .fillEqually } override func updateConstraints() { privateModeBadge.layout(onButton: tabsButton) appMenuBadge.layout(onButton: appMenuButton) warningMenuBadge.layout(onButton: appMenuButton) contentView.snp.makeConstraints { make in make.leading.trailing.top.equalTo(self) make.bottom.equalTo(self.safeArea.bottom) } super.updateConstraints() } private func setupAccessibility() { backButton.accessibilityIdentifier = "TabToolbar.backButton" forwardButton.accessibilityIdentifier = "TabToolbar.forwardButton" stopReloadButton.accessibilityIdentifier = "TabToolbar.stopReloadButton" tabsButton.accessibilityIdentifier = "TabToolbar.tabsButton" appMenuButton.accessibilityIdentifier = "TabToolbar.menuButton" accessibilityNavigationStyle = .combined accessibilityLabel = NSLocalizedString("Navigation Toolbar", comment: "Accessibility label for the navigation toolbar displayed at the bottom of the screen.") } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addButtons(_ buttons: [UIButton]) { buttons.forEach { contentView.addArrangedSubview($0) } } override func draw(_ rect: CGRect) { if let context = UIGraphicsGetCurrentContext() { drawLine(context, start: .zero, end: CGPoint(x: frame.width, y: 0)) } } fileprivate func drawLine(_ context: CGContext, start: CGPoint, end: CGPoint) { context.setStrokeColor(UIColor.black.withAlphaComponent(0.05).cgColor) context.setLineWidth(2) context.move(to: CGPoint(x: start.x, y: start.y)) context.addLine(to: CGPoint(x: end.x, y: end.y)) context.strokePath() } } extension TabToolbar: TabToolbarProtocol { func privateModeBadge(visible: Bool) { privateModeBadge.show(visible) } func appMenuBadge(setVisible: Bool) { // Warning badges should take priority over the standard badge guard warningMenuBadge.badge.isHidden else { return } appMenuBadge.show(setVisible) } func warningMenuBadge(setVisible: Bool) { // Disable other menu badges before showing the warning. if !appMenuBadge.badge.isHidden { appMenuBadge.show(false) } warningMenuBadge.show(setVisible) } func updateBackStatus(_ canGoBack: Bool) { backButton.isEnabled = canGoBack } func updateForwardStatus(_ canGoForward: Bool) { forwardButton.isEnabled = canGoForward } func updateReloadStatus(_ isLoading: Bool) { helper?.updateReloadStatus(isLoading) } func updatePageStatus(_ isWebPage: Bool) { stopReloadButton.isEnabled = isWebPage } func updateTabCount(_ count: Int, animated: Bool) { tabsButton.updateTabCount(count, animated: animated) } } extension TabToolbar: Themeable, PrivateModeUI { func applyTheme() { backgroundColor = UIColor.theme.browser.background helper?.setTheme(forButtons: actionButtons) privateModeBadge.badge.tintBackground(color: UIColor.theme.browser.background) appMenuBadge.badge.tintBackground(color: UIColor.theme.browser.background) warningMenuBadge.badge.tintBackground(color: UIColor.theme.browser.background) } func applyUIMode(isPrivate: Bool) { privateModeBadge(visible: isPrivate) } }
mpl-2.0
d36b87aec943c95f24915d6002457f0f
39.817143
166
0.719236
5.324637
false
false
false
false
touchvie/sdk-front-ios
SDKFrontiOS/SDKFrontiOS/PhotoAndTitleView.swift
1
1243
// // PhotoAndTitleView.swift // SDKFrontiOS // // Created by Carlos Bailon Perez on 27/9/16. // Copyright © 2016 Tagsonomy. All rights reserved. // import UIKit class PhotoAndTitleView: CarouselView { @IBOutlet weak var title: UILabel! @IBOutlet weak var imageView: UIImageView! override func setView(_data : CarouselCard) { super.setView(_data); self.title.text = _data.data.title; self.imageView.image = nil; if (_data.data.image != nil && !_data.data.image!.isEmpty) { var urlArray = _data.data.image!.componentsSeparatedByString("."); urlArray[0] += "_s_@3x" let touchvieUrl = "https://card.touchvie.com/" + urlArray[0] + "." + urlArray[1]; let url = NSURL(string: touchvieUrl) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { if let data = NSData(contentsOfURL: url!) { dispatch_async(dispatch_get_main_queue(), { self.imageView.image = UIImage(data: data); }); } } } } }
apache-2.0
839779c09357f564b7c11a98d6156bc1
27.883721
93
0.52496
4.327526
false
false
false
false
cwaffles/Soulcast
to-be-integrated/DeviceManager.swift
1
3295
import Foundation import Alamofire import AWSSNS let deviceManager = DeviceManager() class DeviceManager: NSObject { var tempDevice: Device! private func registerDeviceLocally(device: Device) { NSUserDefaults.standardUserDefaults().setValue(device.token, forKey: "token") } func register(device: Device) { //do once per lifetime. registerDeviceLocally(device) tempDevice = device AWSSNS.defaultSNS().createPlatformEndpoint(self.createPlatformEndpointInput(device)).continueWithBlock { (task:AWSTask!) -> AnyObject! in if task.error == nil { let endpointResponse = task.result as! AWSSNSCreateEndpointResponse self.tempDevice.arn = endpointResponse.endpointArn self.registerWithServer(self.tempDevice) } else if task.error!.domain == AWSSNSErrorDomain{ if let errorInfo = task.error!.userInfo as NSDictionary! { if errorInfo["Code"] as! String == "InvalidParameter" { // } } } else { self.registerWithServer(self.tempDevice) //!! assert(false, "AWSSNS is complaining! To investigate: \(task.error!.description)") } return nil } } func registerWithServer(device:Device) { request(.POST, serverURL + newDeviceSuffix, parameters: (device.toParams() as! [String : AnyObject])).responseJSON { (response: Response<AnyObject, NSError>) in switch response.result { case .Success: print("registerWithServer success") // get ID and update to device case .Failure: print("registerWithServer failure!") } } } func createPlatformEndpointInput(device:Device) -> AWSSNSCreatePlatformEndpointInput{ let input = AWSSNSCreatePlatformEndpointInput() input.token = device.token input.platformApplicationArn = SNSPlatformARN return input } func updateLocalDeviceID(id:Int) { let updatingDevice = Device.localDevice updatingDevice.id = id Device.localDevice = updatingDevice } func updateDeviceRegion(latitude:Double, longitude:Double, radius:Double) { let updatingDevice = Device.localDevice updatingDevice.latitude = latitude updatingDevice.longitude = longitude updatingDevice.radius = radius Device.localDevice = updatingDevice if let deviceID = updatingDevice.id { let patchURLString = serverURL + "/api/devices/" + String(deviceID) + ".json" request(.PATCH, patchURLString, parameters: (updatingDevice.toParams() as! [String : AnyObject])).responseJSON(completionHandler: { (response:Response<AnyObject, NSError>) in // switch response.result { case .Success: print("updateDeviceRegion success!") case .Failure: assert(false) } }) } } func getNearbyDevices(completion:([String:AnyObject])->()) { request(.GET, serverURL + othersQuerySuffix, parameters: (Device.localDevice.toParams() as! [String : AnyObject])).responseJSON(completionHandler: { (response: Response<AnyObject, NSError>) in // switch response.result{ case .Success: completion(response.result.value as! [String:AnyObject]) case .Failure: print("nay") } }) } }
mit
a585b5f3a1014e059294df9dbf62d2f7
30.380952
196
0.668589
4.614846
false
false
false
false
zaneswafford/ProjectEulerSwift
ProjectEuler/Problem17.swift
1
794
// // Problem17.swift // ProjectEuler // // Created by Zane Swafford on 7/10/15. // Copyright (c) 2015 Zane Swafford. All rights reserved. // import Foundation func problem17() -> Int { var formatter = NSNumberFormatter() formatter.numberStyle = .SpellOutStyle var numberString = "" for i in (1...1000) { // SpellOutStyle does not use British "and" in // numbers greater than 100 so we have to add it in manually var iSpelledOut = formatter.stringFromNumber(i)! if i > 100 && i % 100 != 0 { iSpelledOut += "and" } numberString += iSpelledOut } // Remove dashes and spaces let filteredCharArray = filter(numberString) {!contains("- ", $0)} return count(filteredCharArray) }
bsd-2-clause
610d1dac660f534cd53389f2254b23b3
24.645161
70
0.607053
4.092784
false
false
false
false
chuhlomin/football
football/Game.swift
1
4928
// // Game.swift // football // // Created by Konstantin Chukhlomin on 14/02/15. // Copyright (c) 2015 Konstantin Chukhlomin. All rights reserved. // import Foundation class Game { let PLAYER_ALICE = 1 let PLAYER_BOB = 2 var isRun: Bool var board: Board var lastDot: (Int, Int) var currentPlayer: Int var possibleMoves: [(Int, Int)] = [] init(board: Board) { self.board = board currentPlayer = PLAYER_ALICE lastDot = board.getMiddleDotIndex() board.board[lastDot.0][lastDot.1] = currentPlayer self.isRun = false possibleMoves = getPossibleMoves() } func start() { isRun = true } func stop() { isRun = false } func makeMove(location: (Int, Int)) -> Bool { if !isRun { return false } let filtered = possibleMoves.filter { self.board.compareTuples($0, tupleTwo: location)} if (filtered.count > 0) { board.addLine(lastDot, locationTo: location, player: currentPlayer) board.board[location.0][location.1] = currentPlayer lastDot = location possibleMoves = getPossibleMoves() return true } return false } func isMovePossible(pointFrom: (Int, Int), pointTo: (Int, Int)) -> Bool { if (destinationIsReachable(pointTo) == false) { return false } if (moveHasCorrectLenght(pointFrom, pointTo: pointTo) == false) { return false } if (isLineExist(pointFrom, pointTo: pointTo) == true) { return false } return true } func moveHasCorrectLenght(pointFrom: (Int, Int), pointTo: (Int, Int)) -> Bool { if abs(pointFrom.0 - pointTo.0) > 1 { return false } if abs(pointFrom.1 - pointTo.1) > 1 { return false } if (pointFrom.0 - pointTo.0 == 0 && pointFrom.1 - pointTo.1 == 0) { return false } return true } func isLineExist(pointFrom: (Int, Int), pointTo: (Int, Int)) -> Bool { if let line = board.searchLine(pointFrom, pointTo: pointTo) { return true } return false } func getPossibleMoves() -> [(Int, Int)] { var result: [(Int, Int)] = [] for dX in -1...1 { for dY in -1...1 { if dX == 0 && dY == 0 { continue } let nextDot = (lastDot.0 + dX, lastDot.1 + dY) if (isMovePossible(lastDot, pointTo: nextDot) == true) { result.append(nextDot) if (dX > 0 && dY > 0) { print("↗︎") } if (dX > 0 && dY < 0) { print("↘︎") } if (dX > 0 && dY == 0) { print("→") } if (dX == 0 && dY > 0) { print("↑") } if (dX == 0 && dY < 0) { print("↓") } if (dX < 0 && dY > 0) { print("↖︎") } if (dX < 0 && dY < 0) { print("↙︎") } if (dX < 0 && dY == 0) { print("←") } } } } println("") return result } func destinationIsReachable(destination: (Int, Int)) -> Bool { if (board.getDot(destination) == board.UNREACHABLE) { return false } return true } func isMoveOver(dot: Int) -> Bool { if (dot == board.EMPTY || dot == board.GOAL_ALICE || dot == board.GOAL_BOB) { return true } return false } func getWinner(dot: Int) -> Int? { if dot == board.GOAL_ALICE { return PLAYER_BOB } if dot == board.GOAL_BOB { return PLAYER_ALICE } return nil } func switchPlayer() -> Int { if currentPlayer == PLAYER_ALICE { currentPlayer = PLAYER_BOB } else { currentPlayer = PLAYER_ALICE } return currentPlayer } func restart() -> Void { currentPlayer = PLAYER_ALICE lastDot = board.getMiddleDotIndex() board.board[lastDot.0][lastDot.1] = currentPlayer possibleMoves = getPossibleMoves() self.isRun = true } }
mit
20d7535ecae2574229800c8ef6a8e0b3
24.952381
95
0.429241
4.442029
false
false
false
false
bhyzy/Ripped
Ripped/Ripped/Data/Week.swift
1
907
// // Week.swift // Ripped // // Created by Bartlomiej Hyzy on 12/28/16. // Copyright © 2016 Bartlomiej Hyzy. All rights reserved. // import Foundation import RealmSwift class Week { weak var program: Program? let number: Int let completed: Bool let days: [Day] init(number: Int, completed: Bool, days: [Day]) { self.number = number self.completed = completed self.days = days days.forEach { $0.week = self } } } extension Week { var name: String { return "Week \(number)" } } extension Week: CellTitleProviding { var cellTitle: String { return name + (completed ? " ✓" : "") } } final class ManagedWeek: Object { dynamic var program: ManagedProgram? dynamic var number = 0 dynamic var completed = false let days = LinkingObjects(fromType: ManagedDay.self, property: "week") }
mit
d1f06c6d2a8b4b855b5bc64d1b1a6308
19.545455
74
0.61615
3.720165
false
false
false
false
silence0201/Swift-Study
SimpleProject/KeyBoardDemo/KeyBoardDemo/EmoticonCell.swift
1
4005
// // EmoticonCell.swift // KeyBoardDemo // // Created by 杨晴贺 on 2017/3/17. // Copyright © 2017年 Silence. All rights reserved. // import UIKit @objc protocol EmoticonCellDelegate: NSObjectProtocol{ func emoticonCellDidSelectedEmoticon(cell: EmoticonCell,em: Emoticon?) ; } class EmoticonCell: UICollectionViewCell { weak var delegate: EmoticonCellDelegate? /// 当前页面的表情模型数组,`最多` 20 个 var emoticons: [Emoticon]? { didSet { print("表情包的数量 \(emoticons?.count)") // 1. 隐藏所有的按钮 for v in contentView.subviews { v.isHidden = true } // 显示删除按钮 contentView.subviews.last?.isHidden = false // 2. 遍历表情模型数组,设置按钮图像 for (i, em) in (emoticons ?? []).enumerated() { // 1> 取出按钮 if let btn = contentView.subviews[i] as? UIButton { // 设置图像 - 如果图像为 nil 会清空图像,避免复用 btn.setImage(em.image, for: []) // 设置 emoji 的字符串 - 如果 emoji 为 nil 会清空 title,避免复用 btn.setTitle(em.emoji, for: []) btn.isHidden = false } } } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension EmoticonCell{ // - 从 XIB 加载,bounds 是 XIB 中定义的大小,不是 size 的大小 // - 从纯代码创建,bounds 是就是布局属性中设置的 itemSize fileprivate func setupUI(){ let rowCount = 3 let colCount = 7 // 左右间距 let leftMargin: CGFloat = 8 // 底部间距,为分页控件预留空间 let bottomMargin: CGFloat = 16 let w = (bounds.width - 2 * leftMargin) / CGFloat(colCount) let h = (bounds.height - bottomMargin) / CGFloat(rowCount) // 连续创建 21 个按钮 for i in 0..<21 { let row = i / colCount let col = i % colCount let btn = UIButton() // 设置按钮的大小 let x = leftMargin + CGFloat(col) * w let y = CGFloat(row) * h btn.frame = CGRect(x: x, y: y, width: w, height: h) contentView.addSubview(btn) // 设置按钮的字体大小,lineHeight 基本上和图片的大小差不多! btn.titleLabel?.font = UIFont.systemFont(ofSize: 32) // 设置按钮的 tag btn.tag = i // 添加监听方法 btn.addTarget(self, action: #selector(selectedEmoticonButton), for: .touchUpInside) } // 取出末尾的删除按钮 let removeButton = contentView.subviews.last as! UIButton // 设置图像 let image = UIImage(named: "compose_emotion_delete_highlighted", in: EmoticonManager.bundle, compatibleWith: nil) removeButton.setImage(image, for: []) // 添加长按手势 //let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longGesture)) //longPress.minimumPressDuration = 0.1 //addGestureRecognizer(longPress) } } extension EmoticonCell{ @objc fileprivate func selectedEmoticonButton(button: UIButton){ // 取tag let tag = button.tag // 根据tag判断是否是删除按钮,如果不是删除按钮,取得表情 var em: Emoticon? if tag < emoticons?.count ?? 0 { em = emoticons?[tag] } delegate?.emoticonCellDidSelectedEmoticon(cell: self, em: em) } }
mit
8a8c28a44231aa4c7081f9502fbc6fef
28.915254
121
0.536544
4.358025
false
false
false
false
djnivek/iBeacon
GemTotSDK/GemTotSDK/Views/GTBeaconTableViewController.swift
1
26135
// // GTBeaconTableViewController.swift // GemTotSDK // // Copyright (c) 2014 PassKit, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import UIKit class GTBeaconTableViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate { // Constants - form elements let _toggleSwitch : UISwitch = UISwitch() let _dbPicker : UIPickerView = UIPickerView() let _numberToolbar : UIToolbar = UIToolbar(frame: CGRectMake(0.0,0.0,320.0,50.0)) // Shared objects let _iBeaconConfig : GTStorage = GTStorage.sharedGTStorage // Dictionary containing beacon config parameters let _beacon : GTBeaconBroadcaster = GTBeaconBroadcaster.sharedGTBeaconBroadcaster // Shared instance to allow continuous broadcasting after this view is dismissed required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Preserve selection between presentations self.clearsSelectionOnViewWillAppear = false // Subscribe to notifications on toggle changes NSNotificationCenter.defaultCenter().addObserver(self, selector: "toggleStatus:", name: "iBeaconBroadcastStatus", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "onKeyboardHide:", name: UIKeyboardDidHideNotification, object: nil) // Conifgure the toolbar and pickerview configureToolbarToggleAndPicker() // Add a gesture recognizer to make dismissing the keyboard easier addTapGestureRecognizers() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /************************************************************************************** * * Helper Functions * **************************************************************************************/ // Configures the view components ready for viewing func configureToolbarToggleAndPicker() { // Configure the toolbar that sits above the numeric keypad let toolbarButtonItems = [ UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil), UIBarButtonItem(title: NSLocalizedString("Done", comment: "Button to accept the iBeacon paramaters and dismiss the keyboard"), style: .Plain, target: self, action: "dismissKeyboard:") ] _numberToolbar.setItems(toolbarButtonItems, animated:false) _numberToolbar.barStyle = UIBarStyle.Default _numberToolbar.translucent = true _numberToolbar.sizeToFit() // Configure the date picker _dbPicker.dataSource = self; _dbPicker.delegate = self; _dbPicker.backgroundColor = UIColor.whiteColor() // Configure the toggle _toggleSwitch.setOn(_beacon.beaconStatus(), animated: false) _toggleSwitch.addTarget(self, action: "toggleBeacon:", forControlEvents: UIControlEvents.ValueChanged) } // Adds a tap gesture to the background to dismiss the keyboard if users click outside of the keyboard of input cells and a tap gesture to the table footer to copy the UUID to the clipboard func addTapGestureRecognizers() { let tapBackground : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard:") self.view.addGestureRecognizer(tapBackground) } // Copy the UUID to the clipboard func copyUUID(sender: AnyObject) { let UUID = _iBeaconConfig.getValue("UUID", fromStore:"iBeacon") as String let pasteBoard: UIPasteboard = UIPasteboard.generalPasteboard() pasteBoard.string = UUID let alert = UIAlertController(title: NSLocalizedString("UUID copied clipboard", comment:"Alert UUID Copied to Clipboard"), message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.message = "\n" + UUID alert.addAction(UIAlertAction(title: NSLocalizedString("Okay", comment:"OK button used to dismiss alerts"), style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } // callback funciton called whenever the toggle changes state func toggleBeacon(sender :AnyObject!) { let state = sender.isOn if (state == true) { let beaconStarted = _beacon.startBeacon() if (beaconStarted.success == false) { _toggleSwitch.setOn(false, animated: false) let alert = UIAlertController(title: NSLocalizedString("Error Starting Beacon", comment:"Alert title for problemn starting beacon"), message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.message = beaconStarted.error alert.addAction(UIAlertAction(title: NSLocalizedString("Okay", comment:"OK button used to dismiss alerts"), style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } else { _beacon.stopBeacon() } // Reload the table to update the table footer message self.tableView.reloadData() } func toggleStatus(notification: NSNotification) { let packageContents : NSDictionary = notification.userInfo! as Dictionary _toggleSwitch.setOn(packageContents.objectForKey("broadcastStatus") as Bool, animated: false) if (packageContents.objectForKey("broadcastStatus") as Bool) { if (!_beacon.beaconStatus()) { _beacon.startBeacon() } } self.tableView.reloadData() } // Utility function to construct the footer message containin the advertising paramaters func footerString() -> String { let UUID = _iBeaconConfig.getValue("UUID", fromStore:"iBeacon") as String // Hack to ensure toggle is correctly set on first startup _toggleSwitch.setOn(_beacon.beaconStatus(), animated: false) // If the device is broadcasting, construct a string containing the advertising paramaters if (_beacon.beaconStatus() == true) { // retrieve the current values from the config dictionary let major = _iBeaconConfig.getValue("major", fromStore:"iBeacon") as NSNumber let minor = _iBeaconConfig.getValue("minor", fromStore:"iBeacon") as NSNumber let power = _iBeaconConfig.getValue("power", fromStore: "iBeacon") as NSNumber // Construct a readable string from the power value var powerString : String if (power.integerValue == 127) { powerString = NSLocalizedString("Device Default", comment:"Label shown in table cell to indicate deivce will broadcast the default measured power") } else { let sign = (power.integerValue <= 0 ? "" : "+") powerString = "\(sign)\(power)dB" } // Put it all together let footerString = String.localizedStringWithFormat(NSLocalizedString("Broadcasting beacon signal\n\nUUID: %@\nMajor: %@; Minor: %@\nMeasured Power: %@", comment:"Structured message to display the paramaters of the beacon signal that is currently being broadcast"), UUID, major, minor, powerString) return footerString } else { let footerString = String.localizedStringWithFormat(NSLocalizedString("UUID: %@\n\nThis device is not broadcasting a beacon signal", comment:"Text at bottom of iBeacon view when not broadcasting an iBeacon signal"), UUID) return footerString } } func dismissKeyboard(sender: AnyObject) { self.view.endEditing(true) } // Reloads the table to update the footer message whenever the keyboard is dismissed func onKeyboardHide(notification: NSNotification!) { self.tableView.reloadData() } // Function to check if string is a UUID, or to generate a constant UUID from a string func UUIDforString(UUIDNameOrString: String) -> String { // Test if UUIDNameOrString is a valid UUID, and if so, set the return it let range = UUIDNameOrString.rangeOfString("^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$", options: .RegularExpressionSearch) if (range != nil && countElements(UUIDNameOrString) == 36) { return UUIDNameOrString } else { var ccount: UInt16 = 16 + countElements(UUIDNameOrString) // Variable to hold the hashed namespace var hashString = NSMutableData() // Unique seed namespace - keep to generate UUIDs compatible with PassKit, or change to avoid conflicts // Needs to be a hexadecimal value - ideally a UUID let nameSpace: String = "b8672a1f84f54e7c97bdff3e9cea6d7a" // Convert each byte of the seed namespace to a character value and append the character byte for var i = 0; i < countElements(nameSpace); i+=2 { var charValue: UInt32 = 0 let s = "0x" + String(Array(nameSpace)[i]) + String(Array(nameSpace)[i+1]) NSScanner(string: s).scanHexInt(&charValue) hashString.appendBytes(&charValue, length: 1) } // Append the UUID String bytes to the hash input let uuidString: NSData = NSString(format:UUIDNameOrString, NSUTF8StringEncoding).dataUsingEncoding(NSUTF8StringEncoding)! hashString.appendBytes(uuidString.bytes, length: uuidString.length) // SHA1 hash the input let rawUUIDString = String(hashString.sha1()) // Build the UUID string as defined in RFC 4122 var part3: UInt32 = 0 var part4: UInt32 = 0 NSScanner(string: (rawUUIDString as NSString).substringWithRange(NSMakeRange(12, 4))).scanHexInt(&part3) NSScanner(string: (rawUUIDString as NSString).substringWithRange(NSMakeRange(16, 4))).scanHexInt(&part4) let uuidPart3 = String(NSString(format:"%2X", (part3 & 0x0FFF) | 0x5000)) let uuidPart4 = String(NSString(format:"%2X", (part4 & 0x3FFF) | 0x8000)) return "\((rawUUIDString as NSString).substringWithRange(NSMakeRange(0, 8)))-" + "\((rawUUIDString as NSString).substringWithRange(NSMakeRange(8, 4)))-" + "\(uuidPart3.lowercaseString)-" + "\(uuidPart4.lowercaseString)-" + "\((rawUUIDString as NSString).substringWithRange(NSMakeRange(20, 12)))" } } /************************************************************************************** * * UITable View Delegate Functions * **************************************************************************************/ override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return 2 } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { if (section == 0) { return 1 } else { return 4 } } override func tableView(tableView: UITableView?, didSelectRowAtIndexPath indexPath: NSIndexPath?) { tableView!.userInteractionEnabled = false } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if (indexPath.section == 0) { var cell :UITableViewCell? = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "iBeaconToggle") // Add the image to the table cell let cellImage = UIImage(named:"iBeaconTableCell") if let imageView = cell?.imageView { imageView.image = cellImage } else { NSLog("imageView is nil") } // Set the cell label if let textLabel = cell?.textLabel { textLabel.text = NSLocalizedString("Broadcast Signal", comment:"Label of iBeacon Toggle to start or stop broadcasting as an iBeacon") as String textLabel.font = UIFont.systemFontOfSize(16.0) } else { NSLog("textLabel is nil") } // Add the toggle to the table cell and cell?.accessoryView = UIView(frame: _toggleSwitch.frame) if let accessoryView = cell?.accessoryView { accessoryView.addSubview(_toggleSwitch) } else { NSLog("accessoryView is nil") } // Make the cell non-selectable (only the toggle will be active) cell?.selectionStyle = UITableViewCellSelectionStyle.None return cell! } else { var cell :UITableViewCell? = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "iBeaconCell") let iBeaconParamsLabels = [ NSLocalizedString("Name or UUID", comment:"Tabel cell label for beacon name or UUID value"), NSLocalizedString("Major Value", comment:"Table cell label for beacon major value"), NSLocalizedString("Minor Value", comment:"Table cell label for beacon minor value"), NSLocalizedString("Measured Power", comment:"Table cell label for beacon measured power value") ] // Set the cell label if let textLabel = cell?.textLabel { textLabel.text = iBeaconParamsLabels[indexPath.row] textLabel.font = UIFont.systemFontOfSize(16.0) } else { NSLog("textLabel is nil") } // Create and add a text field to the cell that will contain the value let optionalMargin: CGFloat = 10.0 var valueField = UITextField(frame: CGRectMake(170, 10, cell!.contentView.frame.size.width - 170 - optionalMargin, cell!.contentView.frame.size.height - 10 - optionalMargin)) valueField.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight valueField.delegate = self valueField.returnKeyType = UIReturnKeyType.Done valueField.clearButtonMode = UITextFieldViewMode.WhileEditing valueField.font = UIFont.systemFontOfSize(16.0) cell?.contentView.addSubview(valueField) switch (indexPath.row) { // Populate the value for each cell and configure the field UI as apporpriate for each value type case 0: valueField.text = _iBeaconConfig.getValue("beaconName", fromStore: "iBeacon") as String valueField.placeholder = NSLocalizedString("Name or UUID", comment:"Placehoder text for iBeacon name field") valueField.tag = 1 case 1: valueField.text = (_iBeaconConfig.getValue("major", fromStore: "iBeacon") as NSNumber).stringValue valueField.placeholder = NSLocalizedString("0 - 65,535", comment:"iBeacon Major and Minor placehoder (represents min and max values)") valueField.keyboardType = UIKeyboardType.NumberPad valueField.inputAccessoryView = _numberToolbar valueField.tag = 2 case 2: valueField.text = (_iBeaconConfig.getValue("minor", fromStore: "iBeacon") as NSNumber).stringValue valueField.placeholder = NSLocalizedString("0 - 65,535", comment:"iBeacon Major and Minor placehoder (represents min and max values)") valueField.keyboardType = UIKeyboardType.NumberPad valueField.inputAccessoryView = _numberToolbar valueField.tag = 3 case 3: let powerValue = _iBeaconConfig.getValue("power", fromStore: "iBeacon") as Int if (powerValue == 127) { valueField.text = NSLocalizedString("Device Default", comment:"Label shown in table cell to indicate deivce will broadcast the default measured power") } else { let sign = (powerValue <= 0 ? "" : "+") valueField.text = "\(sign)\(powerValue)dB" } valueField.tag = 4 valueField.inputView = _dbPicker valueField.inputAccessoryView = _numberToolbar valueField.clearButtonMode = UITextFieldViewMode.Never valueField.tintColor = UIColor.clearColor() // This will hide the flashing cursor default: break } return cell! } } //Override to support conditional editing of the table view. override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool { return false } //Override to support custom section headers. override func tableView(tableView: UITableView?, titleForHeaderInSection section: Int) -> String? { if (section == 0) { return NSLocalizedString("Beacon Status", comment: "Header of first section of iBeacon view") } else if (section == 1) { return NSLocalizedString("Beacon Paramaers", comment: "Header of second section of iBeacon view") } return nil } override func tableView(tableView: UITableView?, viewForFooterInSection section: Int) -> UIView? { if (section == 1) { let label: UILabel = UILabel() label.userInteractionEnabled = true label.text = footerString() label.baselineAdjustment = UIBaselineAdjustment.AlignBaselines; label.font = UIFont.systemFontOfSize(UIFont.smallSystemFontSize()) label.textColor = UIColor.grayColor() label.numberOfLines = 0 label.sizeToFit() var frame: CGRect = label.frame let view: UIView = UIView() view.frame = frame // Add padding to align label to Table View frame.origin.x = 15; frame.origin.y = 5; frame.size.width = self.view.bounds.size.width - frame.origin.x; frame.size.height = frame.size.height + frame.origin.y; label.frame = frame; view.addSubview(label) view.sizeToFit() // Add a Gesture Recognizer to copy the UUID to the Clipboard let tapTableFooter : UITapGestureRecognizer = UITapGestureRecognizer (target: self, action: "copyUUID:") tapTableFooter.numberOfTapsRequired = 1 label.addGestureRecognizer(tapTableFooter) return view } return nil } override func tableView(tableView: UITableView?, heightForFooterInSection section: Int) -> CGFloat { if (section == 1) { return 100; } return 0; } // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView?, canMoveRowAtIndexPath indexPath: NSIndexPath?) -> Bool { return false } /************************************************************************************** * * UIPickerView Data Source and Delegate Functions * **************************************************************************************/ func pickerView(_: UIPickerView?, titleForRow row: Int, forComponent component: Int) -> String! { if (row == 0) { // Set the first row of the picker view as an option to select the device default measured power return NSLocalizedString("Use Device Default Value", comment:"Description for selecting the device default power, shown on the pickser wheel. Should be kept concise") } else { // Construct the a string to return. Negative values will already be prexied with a minus sign let sign = (row < 102 ? "" : "+") return "\(sign)\(row - 101)dB" } } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { // -100dB to +100dB inclusive plus an option to select device default measured power return 202 } /************************************************************************************** * * UITextField Delegate Functions * **************************************************************************************/ func textFieldShouldReturn(textField: UITextField!) -> Bool { // Dismiss the keyboard textField.resignFirstResponder() return true } func textFieldShouldEndEditing(textField: UITextField!) -> Bool { switch (textField.tag) { case 1: // Replace empty string with a default value if (textField.text == "") { textField.text = "GemTot iOS" } case 2...3: // Validate the major and minor values before accepting. If invalid, throw an alert and empty the field if (textField.text.toInt() > 0xFFFF) { let alert = UIAlertController(title: NSLocalizedString("Invalid Value", comment:"Alert title for invalid values"), message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.message = NSLocalizedString("Major and Minor keys can only accept a value between 0 and 65,535", comment:"Alert message to show if user enters an invalid Major or Minor value") alert.addAction(UIAlertAction(title: NSLocalizedString("Okay", comment:"OK button used to dismiss alerts"), style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) textField.text = "" return false } // If an empty filed is submitted, replace with a 0 value if (textField.text == "") { textField.text = "0" return true } case 4: // Check if the picker view value is different to the field value and if so, update the field value and the config dictionary let row = _dbPicker.selectedRowInComponent(0) var targetText = "" if (row == 0) { targetText = NSLocalizedString("Device Default", comment:"Label shown in table cell to indicate deivce will broadcast the default measured power") } else { targetText = self.pickerView(_dbPicker, titleForRow: row, forComponent: 0) } if (textField.text != targetText) { textField.text = targetText let dBValue: NSNumber = (row == 0 ? 127 : row - 101) _iBeaconConfig.writeValue(dBValue as NSNumber, forKey: "power", toStore: "iBeacon") } default: return true } return true } func textFieldDidEndEditing(textField: UITextField!) { // Store the updated values in the config dictionary switch (textField.tag) { case 1: _iBeaconConfig.writeValue(textField.text as NSString, forKey:"beaconName", toStore:"iBeacon") _iBeaconConfig.writeValue(UUIDforString(textField.text) as NSString, forKey:"UUID", toStore:"iBeacon") case 2: _iBeaconConfig.writeValue(textField.text.toInt()! as NSNumber, forKey: "major", toStore: "iBeacon") case 3: _iBeaconConfig.writeValue(textField.text.toInt()! as NSNumber, forKey: "minor", toStore: "iBeacon") default: break } // If the beacon is broadcasting - dispatch a job to restart the beacon which will pick up the new values if (_toggleSwitch.on) { dispatch_async(dispatch_get_main_queue(), {var beacon = self._beacon.startBeacon()}) } // Dismiss the keyboard textField.resignFirstResponder() } @IBAction func openSourceCode(sender: AnyObject) { UIApplication.sharedApplication().openURL(NSURL(string: "http://github.com/gemtot")!) } @IBAction func buyBeacons(sender: AnyObject) { UIApplication.sharedApplication().openURL(NSURL(string: "http://gemtot.com/")!) } }
gpl-3.0
463fa2d07002bbc517f30b50d1096bcd
42.705686
310
0.594414
5.507903
false
false
false
false
alitan2014/swift
Heath/Heath/views/GuideViewCell.swift
1
1838
// // GuideViewCell.swift // Heath // // Created by TCL on 15/8/22. // Copyright (c) 2015年 Mac. All rights reserved. // import UIKit typealias senderButtonClickBlock=(UIButton)->Void class GuideViewCell: UITableViewCell { var sendButtonClick:senderButtonClickBlock! @IBOutlet weak var headImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var doctorTitleLabel: UILabel! @IBOutlet weak var orderButton: UIButton! @IBOutlet weak var outTimeLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code self.nameLabel.textColor=UIColor(red: 251/255.0, green: 78/255.0, blue: 10/255.0, alpha: 1) self.orderButton.setTitleColor(UIColor(red: 251/255.0, green: 78/255.0, blue: 10/255.0, alpha: 1), forState: UIControlState.Normal) self.headImageView.layer.cornerRadius=8 self.headImageView.contentMode=UIViewContentMode.ScaleAspectFill self.headImageView.clipsToBounds=true self.orderButton.addTarget(self, action: Selector("btnClick:"), forControlEvents: UIControlEvents.TouchUpInside) } func refreshCellWihtDoctorModel(model:DoctorModel) { var url=NSURL(string: model.expertpicpath) self.headImageView.sd_setImageWithURL(url) self.nameLabel.text=model.expertname self.doctorTitleLabel.text=model.experttitle self.outTimeLabel.text=model.expertvisittime } @IBAction func btnClick(sender: AnyObject) { if (self.sendButtonClick != nil) { self.sendButtonClick(sender as! UIButton) } } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-2.0
af1a3d435ecf2d57a52339c9141a15bf
35
139
0.6939
4.259861
false
false
false
false
zambelz48/swift-sample-dependency-injection
SampleDI/Core/Reusables/NavigationBar/Entities/NavigationBarTextItem.swift
1
647
// // NavigationBarTextItem.swift // My Blue Bird // // Created by Nanda Julianda Akbar on 8/23/17. // Copyright © 2017 Nanda Julianda Akbar. All rights reserved. // import Foundation import UIKit struct NavigationBarTextItem: NavigationBarItem { var title: String var color: UIColor? var enabled: Bool var font: UIFont? var onTapEvent: (() -> Void)? init(_ title: String = "", color: UIColor? = nil, enabled: Bool = true, font: UIFont? = nil, onTapEvent: (() -> Void)? = nil) { self.title = title self.color = color self.enabled = enabled self.font = font self.onTapEvent = onTapEvent } }
mit
dbf95f65efbe02ffc125aeaf1211bea3
18.575758
63
0.648607
3.34715
false
false
false
false
google/swift-benchmark
Sources/Benchmark/BenchmarkState.swift
1
3549
// Copyright 2020 Google LLC // // 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. /// Benchmark state is used to collect the /// benchmark measurements and view the settings it /// was configured with. /// /// Apart from the standard benchmark loop, you can also use /// it with customized benchmark measurement sections via either /// `start`/`end` or `measure` functions. public struct BenchmarkState { var startTime: UInt64 var endTime: UInt64 var measurements: [Double] /// A mapping from counters to their corresponding values. public var counters: [String: Double] /// Number of iterations to be run. public let iterations: Int /// Aggregated settings for the current benchmark run. public let settings: BenchmarkSettings @inline(__always) init() { self.init(iterations: 0, settings: BenchmarkSettings()) } @inline(__always) init(iterations: Int, settings: BenchmarkSettings) { self.startTime = 0 self.endTime = 0 self.measurements = [] self.measurements.reserveCapacity(iterations) self.counters = [:] self.iterations = iterations self.settings = settings } /// Explicitly marks the start of the measurement section. @inline(__always) public mutating func start() { self.endTime = 0 self.startTime = now() } /// Explicitly marks the end of the measurement section /// and records the time since start of the benchmark. @inline(__always) public mutating func end() throws { let value = now() if self.endTime == 0 { self.endTime = value try record() } } @inline(__always) mutating func record() throws { if measurements.count < iterations { measurements.append(self.duration) } else { throw BenchmarkTermination() } } @inline(__always) var duration: Double { return Double(self.endTime - self.startTime) } @inline(__always) mutating func loop(_ benchmark: AnyBenchmark) throws { while measurements.count < iterations { benchmark.setUp() start() try benchmark.run(&self) try end() benchmark.tearDown() } } /// Run the closure within within benchmark measurement section. /// It may throw errors to propagate early termination to /// the outer benchmark loop. @inline(__always) public mutating func measure(f: () -> Void) throws { start() f() try end() } /// Increment a counter by a given value (with a default of 1). /// If counter has never been set before, it starts with zero as the /// initial value. @inline(__always) public mutating func increment(counter name: String, by value: Double = 1) { if let oldValue = counters[name] { counters[name] = oldValue + value } else { counters[name] = value } } }
apache-2.0
4e7497e4ff32698739d0d733452e0540
29.594828
80
0.629191
4.669737
false
false
false
false
smartystreets/smartystreets-ios-sdk
Tests/SmartyStreetsTests/LicenseSenderTests.swift
1
1132
import XCTest @testable import SmartyStreets class LicenseSenderTests: XCTestCase { var request:SmartyRequest! var mockSender:MockSender! var error:NSError! override func setUp() { super.setUp() self.request = SmartyRequest() self.mockSender = MockSender() self.error = nil } override func tearDown() { super.tearDown() self.request = nil self.mockSender = nil self.error = nil } func testLicenseParameterSet() { let licenses = ["one", "two", "three"] let licenseSender = LicenseSender(licenses: licenses, inner: self.mockSender!) let _ = licenseSender.sendRequest(request: self.request!, error: &self.error) XCTAssertEqual("one,two,three", self.mockSender.request.parameters["license"]) } func testLicenseParameterNotSet() { let licenseSender = LicenseSender(licenses: nil, inner: self.mockSender!) let _ = licenseSender.sendRequest(request: self.request!, error: &self.error) XCTAssertEqual(0, self.mockSender.request.parameters.count) } }
apache-2.0
279d0c744cc839e6e7378deea9758533
30.444444
86
0.644876
4.287879
false
true
false
false
KyoheiG3/RxSwift
RxExample/RxExample/Services/Randomizer.swift
11
6761
// // Randomizer.swift // RxExample // // Created by Krunoslav Zaher on 6/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation typealias NumberSection = AnimatableSectionModel<String, Int> let insertItems = true let deleteItems = true let moveItems = true let reloadItems = true let deleteSections = true let insertSections = true let explicitlyMoveSections = true let reloadSections = true class Randomizer { var sections: [NumberSection] var rng: PseudoRandomGenerator var unusedItems: [Int] var unusedSections: [String] init(rng: PseudoRandomGenerator, sections: [NumberSection]) { self.rng = rng self.sections = sections self.unusedSections = [] self.unusedItems = [] } func countTotalItemsInSections(_ sections: [NumberSection]) -> Int { return sections.reduce(0) { p, s in return p + s.items.count } } func randomize() { var nextUnusedSections = [String]() var nextUnusedItems = [Int]() let sectionCount = sections.count let itemCount = countTotalItemsInSections(sections) let startItemCount = itemCount + unusedItems.count let startSectionCount = sections.count + unusedSections.count // insert sections for section in unusedSections { let index = rng.get_random() % (sections.count + 1) if insertSections { sections.insert(NumberSection(model: section, items: []), at: index) } else { nextUnusedSections.append(section) } } // insert/reload items for unusedValue in unusedItems { let sectionIndex = rng.get_random() % sections.count let section = sections[sectionIndex] let itemCount = section.items.count // insert if rng.get_random() % 2 == 0 { let itemIndex = rng.get_random() % (itemCount + 1) if insertItems { sections[sectionIndex].items.insert(unusedValue, at: itemIndex) } else { nextUnusedItems.append(unusedValue) } } // update else { if itemCount == 0 { sections[sectionIndex].items.insert(unusedValue, at: 0) continue } let itemIndex = rng.get_random() % itemCount if reloadItems { nextUnusedItems.append(sections[sectionIndex].items.remove(at: itemIndex)) sections[sectionIndex].items.insert(unusedValue, at: itemIndex) } else { nextUnusedItems.append(unusedValue) } } } assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount) assert(sections.count + nextUnusedSections.count == startSectionCount) let itemActionCount = itemCount / 7 let sectionActionCount = sectionCount / 3 // move items for _ in 0 ..< itemActionCount { if self.sections.count == 0 { continue } let sourceSectionIndex = rng.get_random() % self.sections.count let destinationSectionIndex = rng.get_random() % self.sections.count let sectionItemCount = sections[sourceSectionIndex].items.count if sectionItemCount == 0 { continue } let sourceItemIndex = rng.get_random() % sectionItemCount let nextRandom = rng.get_random() if moveItems { let item = sections[sourceSectionIndex].items.remove(at: sourceItemIndex) let targetItemIndex = nextRandom % (self.sections[destinationSectionIndex].items.count + 1) sections[destinationSectionIndex].items.insert(item, at: targetItemIndex) } } assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount) assert(sections.count + nextUnusedSections.count == startSectionCount) // delete items for _ in 0 ..< itemActionCount { if self.sections.count == 0 { continue } let sourceSectionIndex = rng.get_random() % self.sections.count let sectionItemCount = sections[sourceSectionIndex].items.count if sectionItemCount == 0 { continue } let sourceItemIndex = rng.get_random() % sectionItemCount if deleteItems { nextUnusedItems.append(sections[sourceSectionIndex].items.remove(at: sourceItemIndex)) } } assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount) assert(sections.count + nextUnusedSections.count == startSectionCount) // move sections for _ in 0 ..< sectionActionCount { if sections.count == 0 { continue } let sectionIndex = rng.get_random() % sections.count let targetIndex = rng.get_random() % sections.count if explicitlyMoveSections { let section = sections.remove(at: sectionIndex) sections.insert(section, at: targetIndex) } } assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount) assert(sections.count + nextUnusedSections.count == startSectionCount) // delete sections for _ in 0 ..< sectionActionCount { if sections.count == 0 { continue } let sectionIndex = rng.get_random() % sections.count if deleteSections { let section = sections.remove(at: sectionIndex) for item in section.items { nextUnusedItems.append(item) } nextUnusedSections.append(section.model) } } assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount) assert(sections.count + nextUnusedSections.count == startSectionCount) unusedSections = nextUnusedSections unusedItems = nextUnusedItems } }
mit
3c97e65f43ab88323ad436682de6dad4
32.137255
107
0.551036
5.360825
false
false
false
false
SmallElephant/FESwiftDemo
3-GrayImage/3-GrayImage/FEExtension.swift
1
1943
// // FEExtension.swift // 3-GrayImage // // Created by FlyElephant on 17/1/18. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation import UIKit extension UIImage { func grayImage() -> UIImage { let imageRef:CGImage = self.cgImage! let width:Int = imageRef.width let height:Int = imageRef.height let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceGray() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue) let context:CGContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)! let rect:CGRect = CGRect.init(x: 0, y: 0, width: width, height: height) context.draw(imageRef, in: rect) let outPutImage:CGImage = context.makeImage()! let newImage:UIImage = UIImage.init(cgImage: outPutImage, scale: self.scale, orientation: self.imageOrientation) return newImage } func grayImage0() -> UIImage { let imageRef:CGImage = self.cgImage! let width:Int = imageRef.width let height:Int = imageRef.height let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceGray() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue) let context:CGContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 4 * width, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)! let rect:CGRect = CGRect.init(x: 0, y: 0, width: width, height: height) context.draw(imageRef, in: rect) let outPutImage:CGImage = context.makeImage()! let newImage:UIImage = UIImage.init(cgImage: outPutImage, scale: self.scale, orientation: self.imageOrientation) return newImage } }
mit
9584a5fc4c92994283979eea9710cd56
35.603774
180
0.650515
4.630072
false
false
false
false
SwiftKickMobile/SwiftMessages
SwiftMessages/MessageView.swift
1
16345
// // MessageView.swift // SwiftMessages // // Created by Timothy Moose on 7/30/16. // Copyright © 2016 SwiftKick Mobile LLC. All rights reserved. // import UIKit /* */ open class MessageView: BaseView, Identifiable, AccessibleMessage { /* MARK: - Button tap handler */ /// An optional button tap handler. The `button` is automatically /// configured to call this tap handler on `.TouchUpInside`. open var buttonTapHandler: ((_ button: UIButton) -> Void)? @objc func buttonTapped(_ button: UIButton) { buttonTapHandler?(button) } /* MARK: - Touch handling */ open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { // Only accept touches within the background view. Anything outside of the // background view's bounds should be transparent and does not need to receive // touches. This helps with tap dismissal when using `DimMode.gray` and `DimMode.color`. return backgroundView == self ? super.point(inside: point, with: event) : backgroundView.point(inside: convert(point, to: backgroundView), with: event) } /* MARK: - IB outlets */ /// An optional title label. @IBOutlet open var titleLabel: UILabel? /// An optional body text label. @IBOutlet open var bodyLabel: UILabel? /// An optional icon image view. @IBOutlet open var iconImageView: UIImageView? /// An optional icon label (e.g. for emoji character, icon font, etc.). @IBOutlet open var iconLabel: UILabel? /// An optional button. This buttons' `.TouchUpInside` event will automatically /// invoke the optional `buttonTapHandler`, but its fine to add other target /// action handlers can be added. @IBOutlet open var button: UIButton? { didSet { if let old = oldValue { old.removeTarget(self, action: #selector(MessageView.buttonTapped(_:)), for: .touchUpInside) } if let button = button { button.addTarget(self, action: #selector(MessageView.buttonTapped(_:)), for: .touchUpInside) } } } /* MARK: - Identifiable */ open var id: String { get { return customId ?? "MessageView:title=\(String(describing: titleLabel?.text)), body=\(String(describing: bodyLabel?.text))" } set { customId = newValue } } private var customId: String? /* MARK: - AccessibleMessage */ /** An optional prefix for the `accessibilityMessage` that can be used to further clarify the message for VoiceOver. For example, the view's background color or icon might convey that a message is a warning, in which case one may specify the value "warning". */ open var accessibilityPrefix: String? open var accessibilityMessage: String? { #if swift(>=4.1) let components = [accessibilityPrefix, titleLabel?.text, bodyLabel?.text].compactMap { $0 } #else let components = [accessibilityPrefix, titleLabel?.text, bodyLabel?.text].flatMap { $0 } #endif guard components.count > 0 else { return nil } return components.joined(separator: ", ") } public var accessibilityElement: NSObject? { return backgroundView } open var additionalAccessibilityElements: [NSObject]? { var elements: [NSObject] = [] func getAccessibleSubviews(view: UIView) { for subview in view.subviews { if subview.isAccessibilityElement { elements.append(subview) } else { // Only doing this for non-accessible `subviews`, which avoids // including button labels, etc. getAccessibleSubviews(view: subview) } } } getAccessibleSubviews(view: self.backgroundView) return elements } } /* MARK: - Creating message views This extension provides several convenience functions for instantiating `MessageView` from the included nib files in a type-safe way. These nib files can be found in the Resources folder and can be drag-and-dropped into a project and modified. You may still use these APIs if you've copied the nib files because SwiftMessages looks for them in the main bundle first. See `SwiftMessages` for additional nib loading options. */ extension MessageView { /** Specifies one of the nib files included in the Resources folders. */ public enum Layout: String { /** The standard message view that stretches across the full width of the container view. */ case messageView = "MessageView" /** A floating card-style view with rounded corners. */ case cardView = "CardView" /** Like `CardView` with one end attached to the super view. */ case tabView = "TabView" /** A 20pt tall view that can be used to overlay the status bar. Note that this layout will automatically grow taller if displayed directly under the status bar (see the `ContentInsetting` protocol). */ case statusLine = "StatusLine" /** A floating card-style view with elements centered and arranged vertically. This view is typically used with `.center` presentation style. */ case centeredView = "CenteredView" } /** Loads the nib file associated with the given `Layout` and returns the first view found in the nib file with the matching type `T: MessageView`. - Parameter layout: The `Layout` option to use. - Parameter filesOwner: An optional files owner. - Returns: An instance of generic view type `T: MessageView`. */ public static func viewFromNib<T: MessageView>(layout: Layout, filesOwner: AnyObject = NSNull.init()) -> T { return try! SwiftMessages.viewFromNib(named: layout.rawValue) } /** Loads the nib file associated with the given `Layout` from the given bundle and returns the first view found in the nib file with the matching type `T: MessageView`. - Parameter layout: The `Layout` option to use. - Parameter bundle: The name of the bundle containing the nib file. - Parameter filesOwner: An optional files owner. - Returns: An instance of generic view type `T: MessageView`. */ public static func viewFromNib<T: MessageView>(layout: Layout, bundle: Bundle, filesOwner: AnyObject = NSNull.init()) -> T { return try! SwiftMessages.viewFromNib(named: layout.rawValue, bundle: bundle, filesOwner: filesOwner) } } /* MARK: - Layout adjustments This extension provides a few convenience functions for adjusting the layout. */ extension MessageView { /** Constrains the image view to a specified size. By default, the size of the image view is determined by its `intrinsicContentSize`. - Parameter size: The size to be translated into Auto Layout constraints. - Parameter contentMode: The optional content mode to apply. */ public func configureIcon(withSize size: CGSize, contentMode: UIView.ContentMode? = nil) { var views: [UIView] = [] if let iconImageView = iconImageView { views.append(iconImageView) } if let iconLabel = iconLabel { views.append(iconLabel) } views.forEach { let constraints = [$0.heightAnchor.constraint(equalToConstant: size.height), $0.widthAnchor.constraint(equalToConstant: size.width)] constraints.forEach { $0.priority = UILayoutPriority(999.0) } $0.addConstraints(constraints) if let contentMode = contentMode { $0.contentMode = contentMode } } } } /* MARK: - Theming This extension provides a few convenience functions for setting styles, colors and icons. You are encouraged to write your own such functions if these don't exactly meet your needs. */ extension MessageView { /** A convenience function for setting some pre-defined colors and icons. - Parameter theme: The theme type to use. - Parameter iconStyle: The icon style to use. Defaults to `.Default`. */ public func configureTheme(_ theme: Theme, iconStyle: IconStyle = .default) { let iconImage = iconStyle.image(theme: theme) let backgroundColor: UIColor let foregroundColor: UIColor let defaultBackgroundColor: UIColor let defaultForegroundColor: UIColor switch theme { case .info: defaultBackgroundColor = UIColor(red: 225.0/255.0, green: 225.0/255.0, blue: 225.0/255.0, alpha: 1.0) defaultForegroundColor = UIColor.darkText case .success: defaultBackgroundColor = UIColor(red: 97.0/255.0, green: 161.0/255.0, blue: 23.0/255.0, alpha: 1.0) defaultForegroundColor = UIColor.white case .warning: defaultBackgroundColor = UIColor(red: 246.0/255.0, green: 197.0/255.0, blue: 44.0/255.0, alpha: 1.0) defaultForegroundColor = UIColor.white case .error: defaultBackgroundColor = UIColor(red: 249.0/255.0, green: 66.0/255.0, blue: 47.0/255.0, alpha: 1.0) defaultForegroundColor = UIColor.white } if #available(iOS 13.0, *) { switch theme { case .info: backgroundColor = UIColor { switch $0.userInterfaceStyle { case .dark, .unspecified: return UIColor(red: 125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0) case .light: fallthrough @unknown default: return defaultBackgroundColor } } foregroundColor = .label case .success: backgroundColor = UIColor { switch $0.userInterfaceStyle { case .dark, .unspecified: return UIColor(red: 55/255.0, green: 122/255.0, blue: 0/255.0, alpha: 1.0) case .light: fallthrough @unknown default: return defaultBackgroundColor } } foregroundColor = .white case .warning: backgroundColor = UIColor { switch $0.userInterfaceStyle { case .dark, .unspecified: return UIColor(red: 239/255.0, green: 184/255.0, blue: 10/255.0, alpha: 1.0) case .light: fallthrough @unknown default: return defaultBackgroundColor } } foregroundColor = .white case .error: backgroundColor = UIColor { switch $0.userInterfaceStyle { case .dark, .unspecified: return UIColor(red: 195/255.0, green: 12/255.0, blue: 12/255.0, alpha: 1.0) case .light: fallthrough @unknown default: return defaultBackgroundColor } } foregroundColor = .white } } else { backgroundColor = defaultBackgroundColor foregroundColor = defaultForegroundColor } configureTheme(backgroundColor: backgroundColor, foregroundColor: foregroundColor, iconImage: iconImage) } /** A convenience function for setting a foreground and background color. Note that images will only display the foreground color if they're configured with UIImageRenderingMode.AlwaysTemplate. - Parameter backgroundColor: The background color to use. - Parameter foregroundColor: The foreground color to use. */ public func configureTheme(backgroundColor: UIColor, foregroundColor: UIColor, iconImage: UIImage? = nil, iconText: String? = nil) { iconImageView?.image = iconImage iconLabel?.text = iconText iconImageView?.tintColor = foregroundColor let backgroundView = self.backgroundView ?? self backgroundView.backgroundColor = backgroundColor iconLabel?.textColor = foregroundColor titleLabel?.textColor = foregroundColor bodyLabel?.textColor = foregroundColor button?.backgroundColor = foregroundColor button?.tintColor = backgroundColor button?.contentEdgeInsets = UIEdgeInsets(top: 7.0, left: 7.0, bottom: 7.0, right: 7.0) button?.layer.cornerRadius = 5.0 iconImageView?.isHidden = iconImageView?.image == nil iconLabel?.isHidden = iconLabel?.text == nil } } /* MARK: - Configuring the content This extension provides a few convenience functions for configuring the message content. You are encouraged to write your own such functions if these don't exactly meet your needs. SwiftMessages does not try to be clever by adjusting the layout based on what content you configure. All message elements are optional and it is up to you to hide or remove elements you don't need. The easiest way to remove unwanted elements is to drag-and-drop one of the included nib files into your project as a starting point and make changes. */ extension MessageView { /** Sets the message body text. - Parameter body: The message body text to use. */ public func configureContent(body: String) { bodyLabel?.text = body } /** Sets the message title and body text. - Parameter title: The message title to use. - Parameter body: The message body text to use. */ public func configureContent(title: String, body: String) { configureContent(body: body) titleLabel?.text = title } /** Sets the message title, body text and icon image. Also hides the `iconLabel`. - Parameter title: The message title to use. - Parameter body: The message body text to use. - Parameter iconImage: The icon image to use. */ public func configureContent(title: String, body: String, iconImage: UIImage) { configureContent(title: title, body: body) iconImageView?.image = iconImage iconImageView?.isHidden = false iconLabel?.text = nil iconLabel?.isHidden = true } /** Sets the message title, body text and icon text (e.g. an emoji). Also hides the `iconImageView`. - Parameter title: The message title to use. - Parameter body: The message body text to use. - Parameter iconText: The icon text to use (e.g. an emoji). */ public func configureContent(title: String, body: String, iconText: String) { configureContent(title: title, body: body) iconLabel?.text = iconText iconLabel?.isHidden = false iconImageView?.isHidden = true iconImageView?.image = nil } /** Sets all configurable elements. - Parameter title: The message title to use. - Parameter body: The message body text to use. - Parameter iconImage: The icon image to use. - Parameter iconText: The icon text to use (e.g. an emoji). - Parameter buttonImage: The button image to use. - Parameter buttonTitle: The button title to use. - Parameter buttonTapHandler: The button tap handler block to use. */ public func configureContent(title: String?, body: String?, iconImage: UIImage?, iconText: String?, buttonImage: UIImage?, buttonTitle: String?, buttonTapHandler: ((_ button: UIButton) -> Void)?) { titleLabel?.text = title bodyLabel?.text = body iconImageView?.image = iconImage iconLabel?.text = iconText button?.setImage(buttonImage, for: .normal) button?.setTitle(buttonTitle, for: .normal) self.buttonTapHandler = buttonTapHandler iconImageView?.isHidden = iconImageView?.image == nil iconLabel?.isHidden = iconLabel?.text == nil } }
mit
7a075f51e8a58f099d027591964d236e
36.145455
201
0.622063
5.021198
false
false
false
false
drewag/Swiftlier
Sources/Swiftlier/FileSystem/FileSystem.swift
1
10330
// // FileSystem.swift // ResourceReferences // // Created by Andrew J Wagner on 8/30/15. // Copyright © 2015 Drewag LLC. All rights reserved. // import Foundation public protocol FileSystemReference { var path: String {get} var fileSystem: FileSystem {get} } public struct FileSystem { public static let `default` = FileSystem() public var workingDirectory: DirectoryPath { let path = self.path(from: URL(fileURLWithPath: "")) return path as! DirectoryPath } public var rootDirectory: DirectoryPath { let path = self.path(from: URL(fileURLWithPath: "/")) return path as! DirectoryPath } enum ItemKind { case none case file case directory } let manager = FileManager.default public func path(from url: URL, resolvingSymLinks: Bool = false) -> Path { switch self.itemKind(at: url) { case .directory: return ConcreteDirectoryPath(url: url) case .file: if resolvingSymLinks , let newPath = try? self.manager.destinationOfSymbolicLink(atPath: url.relativePath) { return self.path(from: URL(fileURLWithPath: newPath), resolvingSymLinks: resolvingSymLinks) } return ConcreteFilePath(url: url) case .none: return ConcreteNonExistentPath(url: url) } } func itemKind(at url: URL) -> ItemKind { var isDirectory = ObjCBool(false) guard FileManager.default.fileExists(atPath: url.relativePath, isDirectory: &isDirectory) else { return .none } return isDirectory.boolValue ? .directory : .file } func contentsOfDirectory(at url: URL) throws -> [ExistingPath] { switch self.itemKind(at: url) { case .file: throw GenericSwiftlierError(while: "loading contents of directory", reason: "A file was found instead.", details: "Path was '\(url.relativePath)'") case .none: throw GenericSwiftlierError(while: "loading contents of directory", reason: "No directory was found.", details: "Path was '\(url.relativePath)'") case .directory: break } guard let enumerator = self.manager.enumerator(at: url.resolvingSymlinksInPath(), includingPropertiesForKeys: nil) else { throw GenericSwiftlierError(while: "loading contents of directory", reason: "No directory was found.", details: "Path was '\(url.relativePath)'") } var contents = [ExistingPath]() while let possible = enumerator.nextObject() as? URL { enumerator.skipDescendants() guard let existing = self.path(from: possible) as? ExistingPath else { continue } contents.append(existing) } return contents } func createFile(at url: URL, with data: Data?, canOverwrite: Bool, options: NSData.WritingOptions) throws -> FilePath { switch (self.itemKind(at: url), canOverwrite) { case (.file, false): throw GenericSwiftlierError(while: "creating file", reason: "A file already exists.", details: "Path was '\(url.relativePath)'") case (.directory, _): throw GenericSwiftlierError(while: "creating file", reason: "A directory already exists there.", details: "Path was '\(url.relativePath)'") case (.file, true): try self.manager.removeItem(at: url) fallthrough default: let data = data ?? Data() try data.write(to: url, options: options) guard let filePath = self.path(from: url) as? FilePath else { throw GenericSwiftlierError(while: "creating file", reason: "The newly created file could not be found.", details: "Path was '\(url.relativePath)'") } return filePath } } func createLink(at: URL, to: URL, canOverwrite: Bool) throws -> FilePath { switch (self.itemKind(at: at), canOverwrite) { case (.file, false): throw GenericSwiftlierError(while: "creating link", reason: "A file already exists there.", details: "Path was '\(at.relativePath)'") case (.directory, false): throw GenericSwiftlierError(while: "creating link", reason: "A directory already exists there.", details: "Path was '\(at.relativePath)'") case (.file, true), (.directory, true): try self.manager.removeItem(at: at) fallthrough default: switch self.itemKind(at: to) { case .file: try self.manager.createSymbolicLink(at: at, withDestinationURL: to) case .none: throw GenericSwiftlierError(while: "creating link", reason: "The destination does not exist.", details: "Path was '\(to.relativePath)'") case .directory: throw GenericSwiftlierError(while: "creating link", reason: "The destination is a directory.", details: "Path was '\(to.relativePath)'") } guard let filePath = self.path(from: at) as? FilePath else { throw GenericSwiftlierError(while: "creating link", reason: "The newly created link could not be found", details: "Path was '\(at.relativePath)'") } return filePath } } func moveItem(at: URL, to: URL, canOverwrite: Bool) throws -> ExistingPath { switch self.itemKind(at: at) { case .file, .directory: switch (self.itemKind(at: to), canOverwrite) { case (.file, false): throw GenericSwiftlierError(while: "moving item", reason: "A file already exists there.", details: "Path was '\(to.relativePath)'") case (.directory, false): throw GenericSwiftlierError(while: "moving item", reason: "A directory already exists there.", details: "Path was '\(to.relativePath)'") case (.file, true), (.directory, true): try self.manager.removeItem(at: to) fallthrough default: try self.manager.moveItem(at: at, to: to) } guard let existingPath = self.path(from: to) as? ExistingPath else { throw GenericSwiftlierError(while: "moving item", reason: "The item at the new location could not be found.", details: "Path was '\(to.relativePath)'") } return existingPath case .none: throw GenericSwiftlierError(while: "moving item", reason: "An item does not exist there.", details: "Path was '\(at.relativePath)'") } } func copyFile(at: URL, to: URL, canOverwrite: Bool) throws -> ExistingPath { switch self.itemKind(at: at) { case .directory: throw GenericSwiftlierError(while: "copying file", reason: "It is a directory.", details: "Path was '\(at.relativePath)'") case .none: throw GenericSwiftlierError(while: "copying file", reason: "It does not exist.", details: "Path was '\(at.relativePath)'") case .file: switch (self.itemKind(at: to), canOverwrite) { case (.file, false): throw GenericSwiftlierError(while: "copying file", reason: "A file at the destination already exists.", details: "Destination was '\(to.relativePath)'") case (.directory, _): throw GenericSwiftlierError(while: "copying file", reason: "The destination is a directory.", details: "Destination was '\(to.relativePath)'") case (.file, true): try self.manager.removeItem(at: to) fallthrough default: try self.manager.copyItem(at: at, to: to) } guard let existingPath = self.path(from: to) as? ExistingPath else { throw GenericSwiftlierError(while: "copying file", reason: "The copy could not be found.", details: "Path was '\(at.relativePath)'") } return existingPath } } func createDirectoryIfNotExists(at url: URL) throws -> DirectoryPath { switch self.itemKind(at: url) { case .none: try self.manager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) case .file: throw GenericSwiftlierError(while: "creating directory", reason: "It is already a file.", details: "Path was '\(url.relativePath)'") case .directory: break } guard let directoryPath = self.path(from: url) as? DirectoryPath else { throw GenericSwiftlierError(while: "creating directory", reason: "The newly created directory could not be found.", details: "Path was '\(url.relativePath)'") } return directoryPath } func deleteItem(at url: URL) throws -> NonExistingPath { switch self.itemKind(at: url) { case .none: throw GenericSwiftlierError(while: "deleting item", reason: "It does not exist.", details: "Path was '\(url.relativePath)'") case .file, .directory: try self.manager.removeItem(at: url) } guard let nonExistingPath = self.path(from: url) as? NonExistingPath else { throw GenericSwiftlierError(while: "deleting item", reason: "It still exists after being deleted.", details: "Path was '\(url.relativePath)'") } return nonExistingPath } func lastModified(at url: URL) throws -> Date { let attributes = try self.manager.attributesOfItem(atPath: url.relativePath) return attributes[.modificationDate] as? Date ?? Date.now } func size(at url: URL) throws -> Int { let attributes = try self.manager.attributesOfItem(atPath: url.relativePath) return attributes[.size] as? Int ?? 0 } } struct ConcreteFilePath: FilePath { static func build(_ url: URL) -> Path { return FileSystem.default.path(from: url) } let url: URL } struct ConcreteDirectoryPath: DirectoryPath { static func build(_ url: URL) -> Path { return FileSystem.default.path(from: url) } let url: URL } struct ConcreteNonExistentPath: NonExistingPath { static func build(_ url: URL) -> Path { return FileSystem.default.path(from: url) } let url: URL }
mit
a7fa3468c72a638b520f9056e2527f7f
41.159184
170
0.613903
4.55022
false
false
false
false
trident10/TDMediaPicker
TDMediaPicker/Classes/Model/DataModel/Config/TDConfigNavigationBar.swift
1
890
// // TDConfigAlbumScreen.swift // Pods // // Created by abhimanyujindal10 on 07/19/2017. // Copyright (c) 2017 abhimanyujindal10. All rights reserved. // import Foundation open class TDConfigNavigationBar: NSObject{ open var navigationBarView: TDConfigViewStandard? open var screenTitle: TDConfigLabel? open var backButton: TDConfigButton? open var nextButton: TDConfigButton? open var otherButton: TDConfigButton? public init(navigationBarView: TDConfigViewStandard? = nil, screenTitle: TDConfigLabel? = nil, backButton: TDConfigButton? = nil, nextButton: TDConfigButton? = nil, otherButton: TDConfigButton? = nil){ super.init() self.navigationBarView = navigationBarView self.screenTitle = screenTitle self.backButton = backButton self.nextButton = nextButton self.otherButton = otherButton } }
mit
82d1b87677dde25e581b285395315fbb
31.962963
205
0.720225
4.472362
false
true
false
false
MHaubenstock/Endless-Dungeon
EndlessDungeon/EndlessDungeon/NPCTurnState.swift
1
4679
// // NPCDungeonState.swift // EndlessDungeon // // Created by Michael Haubenstock on 10/16/14. // Copyright (c) 2014 Michael Haubenstock. All rights reserved. // import Foundation class NPCTurnState { var movementRemaining : Int var npcTilePosition : (Int, Int) var weaponRange : Int var tileCellStates : [[Int]] var stateValue : Int var moveDirection : Dungeon.Direction? var fromState : NPCTurnState? init(movementRem : Int, tilePos : (Int, Int), weapRange : Int, cellState : [[Int]], fState : NPCTurnState?) { movementRemaining = movementRem npcTilePosition = tilePos weaponRange = weapRange tileCellStates = cellState if fState != nil { fromState = fState } //Evaluate the state stateValue = 0 var foundPlayer : Bool = false //State value equals movementRemaining + whether enemy is in range to attack player for x in 0...(tileCellStates[0].count - 1) { for y in 0...(tileCellStates.count - 1) { if(tileCellStates[y][x] == 1) { stateValue += Dungeon.distanceBetweenCellsByIndex((y, x), toIndex: npcTilePosition) //If within range to attack player if Dungeon.distanceBetweenCellsByIndex(npcTilePosition, toIndex: (x, y)) <= weaponRange { //stateValue += (movementRemaining + 1) * 2 //Maybe increase the 2 later stateValue += 20 } foundPlayer = true break } } if foundPlayer { break } } } /* func evaluateState() -> Int { var stateValue : Int = movementRemaining var foundPlayer : Bool = false //State value equals movementRemaining + whether enemy is in range to attack player for x in 0...(tileCellStates.count - 1) { for y in 0...(tileCellStates[0].count - 1) { //If within range to attack player if(tileCellStates[y][x] == 1 && Dungeon.distanceBetweenCellsByIndex(npcTilePosition, toIndex: (x, y)) <= weaponRange) { stateValue += (movementRemaining + 1) * 2 //Maybe increase the 2 later foundPlayer = true break } } if foundPlayer { break } } return stateValue } */ func getNextStates() -> [NPCTurnState] { var nextStates : [NPCTurnState] = [] var nextPossiblePositions : [((Int, Int), Dungeon.Direction)] = [((npcTilePosition.0, npcTilePosition.1 - 1), Dungeon.Direction.South), ((npcTilePosition.0, npcTilePosition.1 + 1), Dungeon.Direction.North), ((npcTilePosition.0 + 1, npcTilePosition.1), Dungeon.Direction.East), ((npcTilePosition.0 - 1, npcTilePosition.1), Dungeon.Direction.West)] var dungeon : Dungeon = Dungeon.sharedInstance for p in nextPossiblePositions { var cellType : Cell.CellType = dungeon.getCurrentTile().cells[p.0.1][p.0.0].cellType if(isValidIndex(p.0) && cellType != Cell.CellType.Wall && cellType != Cell.CellType.Exit && cellType != Cell.CellType.Entrance) { //If the cell is empty then this is a possible move if(tileCellStates[p.0.1][p.0.0] == 3) { var newCellState : [[Int]] = tileCellStates //Swap enemy position to new position tileCellStates[p.0.1][p.0.0] = 4 //Make old position empty tileCellStates[npcTilePosition.1][npcTilePosition.0] = 3 var turnState : NPCTurnState = NPCTurnState(movementRem: movementRemaining - 1, tilePos: p.0, weapRange: weaponRange, cellState: newCellState, fState: self) turnState.moveDirection = p.1 nextStates.append(turnState) } } } return nextStates } func isValidIndex(index : (Int, Int)) -> Bool { return (index.0 >= 0 && index.1 >= 0 && index.0 < tileCellStates[0].count && index.1 < tileCellStates.count) } }
mit
302a637f408f8948df6795c6d5041420
34.18797
354
0.516136
4.529526
false
false
false
false
kylef/JSONSchema.swift
Sources/JSONSchema.swift
1
2799
import Foundation public enum Type: Swift.String { case object = "object" case array = "array" case string = "string" case integer = "integer" case number = "number" case boolean = "boolean" case null = "null" } extension String { func stringByRemovingPrefix(_ prefix: String) -> String? { if hasPrefix(prefix) { let index = self.index(startIndex, offsetBy: prefix.count) return String(self[index...]) } return nil } } public struct Schema { public let title: String? public let description: String? public let type: [Type]? let schema: [String: Any] public init(_ schema: [String: Any]) { title = schema["title"] as? String description = schema["description"] as? String if let type = schema["type"] as? String { if let type = Type(rawValue: type) { self.type = [type] } else { self.type = [] } } else if let types = schema["type"] as? [String] { self.type = types.map { Type(rawValue: $0) }.filter { $0 != nil }.map { $0! } } else { self.type = [] } self.schema = schema } public func validate(_ data: Any) throws -> ValidationResult { let validator = try JSONSchema.validator(for: schema) return try validator.validate(instance: data) } public func validate(_ data: Any) throws -> AnySequence<ValidationError> { let validator = try JSONSchema.validator(for: schema) return try validator.validate(instance: data) } } func validator(for schema: [String: Any]) throws -> Validator { guard schema.keys.contains("$schema") else { // Default schema return Draft202012Validator(schema: schema) } guard let schemaURI = schema["$schema"] as? String else { throw ReferenceError.notFound } if let id = DRAFT_2020_12_META_SCHEMA["$id"] as? String, urlEqual(schemaURI, id) { return Draft202012Validator(schema: schema) } if let id = DRAFT_2019_09_META_SCHEMA["$id"] as? String, urlEqual(schemaURI, id) { return Draft201909Validator(schema: schema) } if let id = DRAFT_07_META_SCHEMA["$id"] as? String, urlEqual(schemaURI, id) { return Draft7Validator(schema: schema) } if let id = DRAFT_06_META_SCHEMA["$id"] as? String, urlEqual(schemaURI, id) { return Draft6Validator(schema: schema) } if let id = DRAFT_04_META_SCHEMA["id"] as? String, urlEqual(schemaURI, id) { return Draft4Validator(schema: schema) } throw ReferenceError.notFound } public func validate(_ value: Any, schema: [String: Any]) throws -> ValidationResult { return try validator(for: schema).validate(instance: value) } public func validate(_ value: Any, schema: Bool) throws -> ValidationResult { let validator = Draft4Validator(schema: schema) return try validator.validate(instance: value) }
bsd-3-clause
3ec4579731db8b8b0c0f431353a3c968
24.916667
86
0.661665
3.620957
false
false
false
false
HongliYu/firefox-ios
Client/Frontend/Extensions/InstructionsViewController.swift
1
3736
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Shared private struct InstructionsViewControllerUX { static let TopPadding = CGFloat(20) static let TextFont = UIFont.systemFont(ofSize: UIFont.labelFontSize) static let TextColor = UIColor.Photon.Grey60 static let LinkColor = UIColor.Photon.Blue60 } protocol InstructionsViewControllerDelegate: AnyObject { func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) } private func highlightLink(_ s: NSString, withColor color: UIColor) -> NSAttributedString { let start = s.range(of: "<") if start.location == NSNotFound { return NSAttributedString(string: s as String) } var s: NSString = s.replacingCharacters(in: start, with: "") as NSString let end = s.range(of: ">") s = s.replacingCharacters(in: end, with: "") as NSString let a = NSMutableAttributedString(string: s as String) let r = NSRange(location: start.location, length: end.location-start.location) a.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: r) return a } func setupHelpView(_ view: UIView, introText: String, showMeText: String) { let imageView = UIImageView() imageView.image = UIImage(named: "emptySync") view.addSubview(imageView) imageView.snp.makeConstraints { (make) -> Void in make.top.equalTo(view).offset(InstructionsViewControllerUX.TopPadding) make.centerX.equalTo(view) } let label1 = UILabel() view.addSubview(label1) label1.text = introText label1.numberOfLines = 0 label1.lineBreakMode = .byWordWrapping label1.font = InstructionsViewControllerUX.TextFont label1.textColor = InstructionsViewControllerUX.TextColor label1.textAlignment = .center label1.snp.makeConstraints { (make) -> Void in make.width.equalTo(250) make.top.equalTo(imageView.snp.bottom).offset(InstructionsViewControllerUX.TopPadding) make.centerX.equalTo(view) } let label2 = UILabel() view.addSubview(label2) label2.numberOfLines = 0 label2.lineBreakMode = .byWordWrapping label2.font = InstructionsViewControllerUX.TextFont label2.textColor = InstructionsViewControllerUX.TextColor label2.textAlignment = .center label2.attributedText = highlightLink(showMeText as NSString, withColor: InstructionsViewControllerUX.LinkColor) label2.snp.makeConstraints { (make) -> Void in make.width.equalTo(250) make.top.equalTo(label1.snp.bottom).offset(InstructionsViewControllerUX.TopPadding) make.centerX.equalTo(view) } } class InstructionsViewController: UIViewController { weak var delegate: InstructionsViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = [] view.backgroundColor = UIColor.Photon.White100 navigationItem.leftBarButtonItem = UIBarButtonItem(title: Strings.SendToCloseButton, style: .done, target: self, action: #selector(close)) navigationItem.leftBarButtonItem?.accessibilityIdentifier = "InstructionsViewController.navigationItem.leftBarButtonItem" setupHelpView(view, introText: Strings.SendToNotSignedInText, showMeText: Strings.SendToNotSignedInMessage) } @objc func close() { delegate?.instructionsViewControllerDidClose(self) } func showMeHow() { print("Show me how") // TODO Not sure what to do or if to keep this. Waiting for UX feedback. } }
mpl-2.0
e10d9300388d6dabfb21036927b0862a
37.916667
146
0.726981
4.528485
false
false
false
false
bmichotte/HSTracker
HSTracker/Utility/Automation.swift
1
8591
// // Automation.swift // HSTracker // // Created by Benjamin Michotte on 3/08/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import CleanroomLogger import RealmSwift struct Automation { private var queue: DispatchQueue = DispatchQueue(label: "export.hstracker", attributes: []) func exportDeckToHearthstone(deck: Deck, callback: @escaping (String) -> Void) { let cards = CollectionManager.default.collection() if cards.count == 0 { callback(NSLocalizedString("Can't get card collection", comment: "")) return } let deckId = deck.deckId queue.async { CoreManager.bringHSToFront() let searchLocation = SizeHelper.searchLocation() let firstCardLocation = SizeHelper.firstCardLocation() let secondCardLocation = SizeHelper.secondCardLocation() let preferGoldenCards = Settings.preferGoldenCards var missingCards: [Card] = [] // click a first time to be sure we have the focus on hearthstone self.leftClick(at: searchLocation) Thread.sleep(forTimeInterval: 0.5) for deckCard in deck.sortedCards { guard let card = cards[deckCard.id] else { for _ in 1...deckCard.count { missingCards.append(deckCard) } continue } var goldenCount = card[true] ?? 0 var normalCount = card[false] ?? 0 if goldenCount + normalCount < deckCard.count { for _ in 1...(deckCard.count - (goldenCount + normalCount)) { missingCards.append(deckCard) } } self.leftClick(at: searchLocation) Thread.sleep(forTimeInterval: 0.3) self.write(string: self.searchText(card: deckCard)) Thread.sleep(forTimeInterval: 0.3) var takeGolden: Bool = false for _ in 1...deckCard.count { takeGolden = (preferGoldenCards && goldenCount > 0) || normalCount == 0 if takeGolden { self.doubleClick(at: normalCount == 0 ? firstCardLocation : secondCardLocation) goldenCount -= 1 takeGolden = preferGoldenCards && goldenCount > 0 } else { normalCount -= 1 self.doubleClick(at: firstCardLocation) } Thread.sleep(forTimeInterval: 0.3) } } Thread.sleep(forTimeInterval: 1) guard let editedDeck = MirrorHelper.getEditedDeck(), let hsDeckId = editedDeck.id as? Int64 else { callback(NSLocalizedString("Can't get edited deck", comment: "")) return } RealmHelper.set(hsDeckId: hsDeckId, for: deckId) DispatchQueue.main.async { var message = NSLocalizedString("Export done", comment: "") if let msg = CollectionManager.default .checkMissingCards(missingCards: missingCards) { message = msg } callback(message) } } } private func leftClick(at location: NSPoint) { let source = CGEventSource(stateID: .privateState) let click = CGEvent(mouseEventSource: source, mouseType: .leftMouseDown, mouseCursorPosition: location, mouseButton: .left) click?.post(tap: .cghidEventTap) let release = CGEvent(mouseEventSource: source, mouseType: .leftMouseUp, mouseCursorPosition: location, mouseButton: .left) release?.post(tap: .cghidEventTap) } private func doubleClick(at location: NSPoint) { let source = CGEventSource(stateID: .privateState) var click = CGEvent(mouseEventSource: source, mouseType: .leftMouseDown, mouseCursorPosition: location, mouseButton: .left) click?.setIntegerValueField(.mouseEventClickState, value: 1) click?.post(tap: .cghidEventTap) var release = CGEvent(mouseEventSource: source, mouseType: .leftMouseUp, mouseCursorPosition: location, mouseButton: .left) release?.setIntegerValueField(.mouseEventClickState, value: 1) release?.post(tap: .cghidEventTap) click = CGEvent(mouseEventSource: source, mouseType: .leftMouseDown, mouseCursorPosition: location, mouseButton: .left) click?.setIntegerValueField(.mouseEventClickState, value: 2) click?.post(tap: .cghidEventTap) release = CGEvent(mouseEventSource: source, mouseType: .leftMouseUp, mouseCursorPosition: location, mouseButton: .left) release?.setIntegerValueField(.mouseEventClickState, value: 2) release?.post(tap: .cghidEventTap) } private func write(string: String) { let source = CGEventSource(stateID: .hidSystemState) if let source = CGEventSource(stateID: .hidSystemState) { for letter in string.utf16 { pressAndReleaseChar(char: letter, eventSource: source) } } // finish by ENTER if let event = CGEvent(keyboardEventSource: source, virtualKey: 0x24, keyDown: true) { event.post(tap: CGEventTapLocation.cghidEventTap) } if let event = CGEvent(keyboardEventSource: source, virtualKey: 0x24, keyDown: false) { event.post(tap: CGEventTapLocation.cghidEventTap) } } private func pressAndReleaseChar(char: UniChar, eventSource es: CGEventSource) { pressChar(char: char, eventSource: es) releaseChar(char: char, eventSource: es) } private func pressChar(char: UniChar, keyDown: Bool = true, eventSource es: CGEventSource) { let event = CGEvent(keyboardEventSource: es, virtualKey: 0, keyDown: keyDown) var char = char event?.keyboardSetUnicodeString(stringLength: 1, unicodeString: &char) event?.post(tap: CGEventTapLocation.cghidEventTap) } private func releaseChar(char: UniChar, eventSource es: CGEventSource) { pressChar(char: char, keyDown: false, eventSource: es) } private func searchText(card: Card) -> String { var str = card.name guard let lang = Settings.hearthstoneLanguage else { return str } if let text = artistDict[lang.rawValue], let artist = card.artist.components(separatedBy: " ").last { str += " \(text):\(artist)" } if let text = manaDict[lang.rawValue] { str += " \(text):\(card.cost)" } if let text = attackDict[lang.rawValue], attackIds.contains(card.id) { str += " \(text):\(card.attack)" } return str } private let attackIds = [ CardIds.Collectible.Neutral.Feugen, CardIds.Collectible.Neutral.Stalagg ] private let artistDict = [ "enUS": "artist", "zhCN": "画家", "zhTW": "畫家", "enGB": "artist", "frFR": "artiste", "deDE": "künstler", "itIT": "artista", "jaJP": "アーティスト", "koKR": "아티스트", "plPL": "grafik", "ptBR": "artista", "ruRU": "художник", "esMX": "artista", "esES": "artista" ] private let manaDict = [ "enUS": "mana", "zhCN": "法力值", "zhTW": "法力", "enGB": "mana", "frFR": "mana", "deDE": "mana", "itIT": "mana", "jaJP": "マナ", "koKR": "마나", "plPL": "mana", "ptBR": "mana", "ruRU": "мана", "esMX": "maná", "esES": "maná" ] private let attackDict = [ "enUS": "attack", "zhCN": "攻击力", "zhTW": "攻擊力", "enGB": "attack", "frFR": "attaque", "deDE": "angriff", "itIT": "attacco", "jaJP": "攻撃", "koKR": "공격력", "plPL": "atak", "ptBR": "ataque", "ruRU": "атака", "esMX": "ataque", "esES": "ataque" ] }
mit
907ae97dd85363b7afc7ffa28e4ad15d
34.425
103
0.54893
4.357765
false
false
false
false
gregomni/swift
test/SILGen/inlinable_attribute.swift
4
8253
// RUN: %target-swift-emit-silgen -module-name inlinable_attribute -emit-verbose-sil -warnings-as-errors %s | %FileCheck %s // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute15fragileFunctionyyF : $@convention(thin) () -> () @inlinable public func fragileFunction() { } public struct MySt { // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStV6methodyyF : $@convention(method) (MySt) -> () @inlinable public func method() {} // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStV8propertySivg : $@convention(method) (MySt) -> Int @inlinable public var property: Int { return 5 } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStVyS2icig : $@convention(method) (Int, MySt) -> Int @inlinable public subscript(x: Int) -> Int { return x } } public class MyCls { // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute5MyClsCfD : $@convention(method) (@owned MyCls) -> () @inlinable deinit {} // Allocating entry point is [serialized] // CHECK-LABEL: sil [serialized] [exact_self_class] [ossa] @$s19inlinable_attribute5MyClsC14designatedInitACyt_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls public init(designatedInit: ()) {} // Note -- convenience init is intentionally not [serialized] // CHECK-LABEL: sil [ossa] @$s19inlinable_attribute5MyClsC15convenienceInitACyt_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls public convenience init(convenienceInit: ()) { self.init(designatedInit: ()) } } // Make sure enum case constructors for public and versioned enums are // [serialized]. @usableFromInline enum MyEnum { case c(MySt) } // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute16referencesMyEnumyyFAA0dE0OAA0D2StVcADmcfu_ : $@convention(thin) (@thin MyEnum.Type) -> @owned @callee_guaranteed (MySt) -> MyEnum { // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute16referencesMyEnumyyFAA0dE0OAA0D2StVcADmcfu_AdFcfu0_ : $@convention(thin) (MySt, @thin MyEnum.Type) -> MyEnum { @inlinable public func referencesMyEnum() { _ = MyEnum.c } // CHECK-LABEL: sil non_abi [transparent] [serialized] [ossa] @$s19inlinable_attribute15HasInitializersV1xSivpfi : $@convention(thin) () -> Int // CHECK-LABEL: sil non_abi [transparent] [serialized] [ossa] @$s19inlinable_attribute15HasInitializersV1ySivpfi : $@convention(thin) () -> Int @frozen public struct HasInitializers { public let x = 1234 internal let y = 4321 @inlinable public init() {} } public class Horse { public func gallop() {} } // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute15talkAboutAHorse1hyAA5HorseC_tFyycAEcfu_ : $@convention(thin) (@guaranteed Horse) -> @owned @callee_guaranteed () -> () { // CHECK: function_ref @$s19inlinable_attribute15talkAboutAHorse1hyAA5HorseC_tFyycAEcfu_yycfu0_ // CHECK: return // CHECK: } // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute15talkAboutAHorse1hyAA5HorseC_tFyycAEcfu_yycfu0_ : $@convention(thin) (@guaranteed Horse) -> () { // CHECK: class_method %0 : $Horse, #Horse.gallop : (Horse) -> () -> (), $@convention(method) (@guaranteed Horse) -> () // CHECK: return // CHECK: } @inlinable public func talkAboutAHorse(h: Horse) { _ = h.gallop } @_fixed_layout public class PublicBase { @inlinable public init(horse: Horse) {} } @usableFromInline @_fixed_layout class UFIBase { @usableFromInline @inlinable init(horse: Horse) {} } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0Cfd : $@convention(method) (@guaranteed PublicDerivedFromPublic) -> @owned Builtin.NativeObject // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0CfD : $@convention(method) (@owned PublicDerivedFromPublic) -> () // Make sure the synthesized delegating initializer is inlinable also // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0C5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PublicDerivedFromPublic) -> @owned PublicDerivedFromPublic @_fixed_layout public class PublicDerivedFromPublic : PublicBase { // Allow @inlinable deinits @inlinable deinit {} } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute20UFIDerivedFromPublicC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned UFIDerivedFromPublic) -> @owned UFIDerivedFromPublic @usableFromInline @_fixed_layout class UFIDerivedFromPublic : PublicBase { } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute17UFIDerivedFromUFIC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned UFIDerivedFromUFI) -> @owned UFIDerivedFromUFI @usableFromInline @_fixed_layout class UFIDerivedFromUFI : UFIBase { // Allow @inlinable deinits @inlinable deinit {} } // CHECK-LABEL: sil hidden [ossa] @$s19inlinable_attribute25InternalDerivedFromPublicC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned InternalDerivedFromPublic) -> @owned InternalDerivedFromPublic class InternalDerivedFromPublic : PublicBase {} // CHECK-LABEL: sil hidden [ossa] @$s19inlinable_attribute22InternalDerivedFromUFIC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned InternalDerivedFromUFI) -> @owned InternalDerivedFromUFI class InternalDerivedFromUFI : UFIBase {} // CHECK-LABEL: sil private [ossa] @$s19inlinable_attribute24PrivateDerivedFromPublic{{.+}}LLC5horseAdA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PrivateDerivedFromPublic) -> @owned PrivateDerivedFromPublic private class PrivateDerivedFromPublic : PublicBase {} // CHECK-LABEL: sil private [ossa] @$s19inlinable_attribute21PrivateDerivedFromUFI{{.+}}LLC5horseAdA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PrivateDerivedFromUFI) -> @owned PrivateDerivedFromUFI private class PrivateDerivedFromUFI : UFIBase {} // Make sure that nested functions are also serializable. // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute3basyyF @inlinable public func bas() { // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute3basyyF3zimL_yyF func zim() { // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute3basyyF3zimL_yyF4zangL_yyF func zang() { } } // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute3bas{{[_0-9a-zA-Z]*}}U_ let _ = { // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute3basyyFyycfU_7zippityL_yyF func zippity() { } } } // CHECK-LABEL: sil [ossa] @$s19inlinable_attribute6globalyS2iF : $@convention(thin) (Int) -> Int public func global(_ x: Int) -> Int { return x } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF : $@convention(thin) () -> () @inlinable func cFunctionPointer() { // CHECK: function_ref @$s19inlinable_attribute6globalyS2iFTo let _: @convention(c) (Int) -> Int = global // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_To let _: @convention(c) (Int) -> Int = { return $0 } func local(_ x: Int) -> Int { return x } // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iFTo let _: @convention(c) (Int) -> Int = local } // CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$s19inlinable_attribute6globalyS2iFTo : $@convention(c) (Int) -> Int // CHECK: function_ref @$s19inlinable_attribute6globalyS2iF // CHECK: return // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_ : $@convention(thin) (Int) -> Int { // CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_To : $@convention(c) (Int) -> Int { // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_ // CHECK: return // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iF : $@convention(thin) (Int) -> Int { // CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iFTo : $@convention(c) (Int) -> Int { // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iF // CHECK: return
apache-2.0
4b25d21e7c519c4faca61c980a3ad8a3
43.610811
221
0.739973
3.472024
false
false
false
false
juancruzmdq/NLService
NLService/Classes/NLSession.swift
1
4043
// // Session.swift // //Copyright (c) 2016 Juan Cruz Ghigliani <[email protected]> www.juancruzmdq.com.ar // //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. //////////////////////////////////////////////////////////////////////////////// // MARK: Imports import Foundation /** * Class that handle and persist the session info */ public class NLSession : NSObject, NSCoding { //////////////////////////////////////////////////////////////////////////////// // MARK: Public Properties public var id: String //////////////////////////////////////////////////////////////////////////////// // MARK: Private Properties private var sessionData:Dictionary<String, AnyObject> /** Access session data with dictionary sintax ( session["key"] = .... ) */ subscript(key: String) -> AnyObject? { get { return sessionData[key] } set(newValue) { sessionData[key] = newValue } } //////////////////////////////////////////////////////////////////////////////// // MARK: Setup & Teardown public init(uniqueID:String){ id = uniqueID sessionData = [:] } //////////////////////////////////////////////////////////////////////////////// // MARK: Class Methods static func restoreOrCreate(uniqueID:String) -> NLSession{ let userDefaults = NSUserDefaults.standardUserDefaults() if let encodedObject:NSData = userDefaults.objectForKey(uniqueID) as? NSData{ return (NSKeyedUnarchiver.unarchiveObjectWithData(encodedObject) as? NLSession)! } return NLSession(uniqueID: uniqueID) } //////////////////////////////////////////////////////////////////////////////// // MARK: NSCoder implementation public func encodeWithCoder(aCoder: NSCoder){ aCoder.encodeObject(sessionData, forKey: "session_data") aCoder.encodeObject(id, forKey: "session_id") } convenience required public init?(coder aDecoder: NSCoder) { let sessionData = aDecoder.decodeObjectForKey("session_data") let id = aDecoder.decodeObjectForKey("session_id") self.init(uniqueID: id as! String) if (sessionData != nil){ self.sessionData = sessionData as! Dictionary } } //////////////////////////////////////////////////////////////////////////////// // MARK: public Methods public func save(){ let encodedObject:NSData = NSKeyedArchiver.archivedDataWithRootObject(self as AnyObject); let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setObject(encodedObject, forKey: self.id) userDefaults.synchronize() } public func delete(){ let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.removeObjectForKey(self.id) userDefaults.synchronize() } public func clean() { self.sessionData = [:] } }
mit
b87600c681b1548ae7a58e978e6b30ed
35.107143
97
0.57581
5.576552
false
false
false
false
novastorm/Udacity-On-The-Map
On the Map/LoginViewController.swift
1
8391
// // LoginViewController.swift // On the Map // // Created by Adland Lee on 3/24/16. // Copyright © 2016 Adland Lee. All rights reserved. // import FBSDKLoginKit import UIKit // MARK: LoginViewController: UIViewController class LoginViewController: UIViewController { // MARK: Outlets @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var facebookLoginButton: FBSDKLoginButton! // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() self.emailField.delegate = self self.passwordField.delegate = self } override func viewWillAppear(_ animated: Bool) { // ensure password field is cleared passwordField.text = "" } override func viewDidAppear(_ animated: Bool) { checkNetworkConnection(nil) { (success, error) in if let _ = error { showNetworkAlert(self) return } if let currentAccessToken = FBSDKAccessToken.current() { ProgressOverlay.start(self, message: "Logging in") { guard let tokenString = currentAccessToken.tokenString else { return } UdacityClient.sharedInstance.authenticateViaFacebook(tokenString) { (success, error) in performUIUpdatesOnMain { ProgressOverlay.stop() { if let error = error { if error.code == NSURLErrorNotConnectedToInternet { self.displayError(error.localizedDescription) } else if error.code == NSURLErrorTimedOut { self.displayError(error.localizedDescription) } else if error.code == ErrorCodes.httpUnsucessful.rawValue { let response = error.userInfo["http_response"] as! HTTPURLResponse if response.statusCode == 403 { self.displayError("Check facebook account is linked", title: "Authorization error." ) FBSDKLoginManager().logOut() } else { self.displayError("Recieved unexpected response code: \(response.statusCode)") } } else { self.displayError("Received unexpected error code: \(error.code) \(error.localizedDescription)") } return } self.completeLogin() } } } } } } } override func viewDidDisappear(_ animated: Bool) { // clear password field passwordField.text = "" } // MARK: Actions @IBAction func udacityLogin(_ sender: AnyObject) { view.endEditing(true) if emailField.text!.isEmpty { setTextFieldBorderToDanger(emailField) } if passwordField.text!.isEmpty { setTextFieldBorderToDanger(passwordField) } if emailField.text!.isEmpty || passwordField.text!.isEmpty { displayError("E-mail and password field required.", title: "Login Error") return } let email = emailField.text! let password = passwordField.text! checkNetworkConnection(UdacityClient.Constants.APIHost) { (success, error) in if let _ = error { showNetworkAlert(self) return } ProgressOverlay.start(self, message: "Logging in") { UdacityClient.sharedInstance.authenticateViaUdacity(username: email, password: password) { (success, error) in performUIUpdatesOnMain { ProgressOverlay.stop() { if let error = error { if error.code == NSURLErrorNotConnectedToInternet { self.displayError(error.localizedDescription) } else if error.code == NSURLErrorTimedOut { self.displayError(error.localizedDescription) } else if error.code == ErrorCodes.httpUnsucessful.rawValue { let response = error.userInfo["http_response"] as! HTTPURLResponse if response.statusCode == 403 { self.displayError("Check username and password", title: "Authorization error.") self.setTextFieldBorderToDanger(self.emailField) self.setTextFieldBorderToDanger(self.passwordField) } else { self.displayError("Recieved unexpected response code: \(response.statusCode)") } } else { self.displayError("Received unexpected error code: \(error.code) \(error.localizedDescription)") } return } self.completeLogin() } } } } } } @IBAction func signUp(_ sender: AnyObject) { let signUpURL = "https://www.udacity.com/account/auth#!/signup" let url = URL(string: signUpURL)! UIApplication.shared.open(url, options: [:], completionHandler: nil) } // MARK: Login fileprivate func completeLogin() { let controller = storyboard!.instantiateViewController(withIdentifier: "OnTheMapNavigationController") as! UINavigationController self.present(controller, animated: true, completion: nil) } // MARK: Helper Utilities func displayError(_ message: String?, title: String? = nil) { showAlert(self, title: title, message: message) ProgressOverlay.stop() {} } func setTextFieldBorderToDanger(_ textField: UITextField) { textField.layer.borderColor = UIColor.red.cgColor textField.layer.borderWidth = 1.0 textField.layer.cornerRadius = 5.0 } func setTextFieldBorderToDefault(_ textField: UITextField) { textField.layer.borderColor = nil textField.layer.borderWidth = 0 textField.layer.cornerRadius = 5.0 } } // MARK: - LoginViewController: UITextFieldDelegate extension LoginViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { setTextFieldBorderToDefault(textField) } } // MARK: - LoginViewController: FBSDKLoginButtonDelegate extension LoginViewController: FBSDKLoginButtonDelegate { func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { view.endEditing(true) if let _ = error { displayError(error.localizedDescription, title: "Login Failed") return } if ((result == nil) || result.isCancelled) { displayError("User cancelled login", title: "Login Cancelled") return } } func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {} }
mit
0cfc3bbb537beec854f791fdc41b7625
36.623318
137
0.500596
6.554688
false
false
false
false
mondok/jqui
jqui/classes/JQDocument.swift
1
2742
// // JQDocument.swift // jqui // // Created by Matthew Mondok on 9/27/15. // Copyright © 2015 Matthew Mondok. All rights reserved. // import Cocoa class JQDocument: NSDocument { var savedName:String = "" var originalJson:String = "" var query:String = "" var queryResult:String = "" var _contentViewControler:JQViewController? override init() { super.init() } override func windowControllerDidLoadNib(aController: NSWindowController) { super.windowControllerDidLoadNib(aController) } override class func autosavesInPlace() -> Bool { return true } override func makeWindowControllers() { let storyboard = NSStoryboard(name: "Main", bundle: nil) let windowController = storyboard.instantiateControllerWithIdentifier("Document Window Controller") as! NSWindowController _contentViewControler = windowController.contentViewController as? JQViewController self.addWindowController(windowController) } override func dataOfType(typeName: String) throws -> NSData { var obj = [String: String]() if _contentViewControler != nil{ obj = ["s": _contentViewControler!.nameTextField.stringValue, "o": safeString(_contentViewControler!.jsonInputTextView.string!), "q": _contentViewControler!.jqQueryTextField.stringValue, "qr": safeString(_contentViewControler!.jqOutputTextView.string!)] } let json = JQJsonUtils.jsonStringify(obj) return json.dataUsingEncoding(NSUTF8StringEncoding)! } override func readFromData(data: NSData, ofType typeName: String) throws { var obj:[String:String] if let json = NSString(data: data, encoding: NSUTF8StringEncoding){ let str = String(json) obj = convertStringToDictionary(str)! savedName = obj["s"]! originalJson = obj["o"]! query = obj["q"]! queryResult = obj["qr"]! } } func safeString(str: String?) -> String{ if str == nil{ return "" } return str! } func convertStringToDictionary(jsonStr: String) -> [String:String]? { let data = jsonStr.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false) do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) if let dict = json as? [String: String] { return dict } } catch { print(error) } return nil } }
mit
034004ce4a5f40d1d5260e301b554885
29.120879
130
0.606348
5.152256
false
false
false
false
slavapestov/swift
test/SILGen/enum.swift
2
6842
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen -module-name Swift %s | FileCheck %s public enum Optional<T> { case Some(T), None } enum Boolish { case falsy case truthy } // CHECK-LABEL: sil hidden @_TFs13Boolish_casesFT_T_ func Boolish_cases() { // CHECK: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type // CHECK-NEXT: [[FALSY:%[0-9]+]] = enum $Boolish, #Boolish.falsy!enumelt _ = Boolish.falsy // CHECK-NEXT: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type // CHECK-NEXT: [[TRUTHY:%[0-9]+]] = enum $Boolish, #Boolish.truthy!enumelt _ = Boolish.truthy } struct Int {} enum Optionable { case nought case mere(Int) } // CHECK-LABEL: sil hidden @_TFs16Optionable_casesFSiT_ func Optionable_cases(x: Int) { // CHECK: [[FN:%.*]] = function_ref @_TFOs10Optionable4mereFMS_FSiS_ // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type // CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]]) // CHECK-NEXT: strong_release [[CTOR]] _ = Optionable.mere // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type // CHECK-NEXT: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int _ = Optionable.mere(x) } // CHECK-LABEL: sil shared [transparent] @_TFOs10Optionable4mereFMS_FSiS_ // CHECK: [[FN:%.*]] = function_ref @_TFOs10Optionable4merefMS_FSiS_ // CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]](%0) // CHECK-NEXT: return [[METHOD]] // CHECK-NEXT: } // CHECK-LABEL: sil shared [transparent] @_TFOs10Optionable4merefMS_FSiS_ // CHECK: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int // CHECK-NEXT: return [[RES]] : $Optionable // CHECK-NEXT: } protocol P {} struct S : P {} enum AddressOnly { case nought case mere(P) case phantom(S) } // CHECK-LABEL: sil hidden @_TFs17AddressOnly_casesFVs1ST_ func AddressOnly_cases(s: S) { // CHECK: [[FN:%.*]] = function_ref @_TFOs11AddressOnly4mereFMS_FPs1P_S_ // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]]) // CHECK-NEXT: strong_release [[CTOR]] _ = AddressOnly.mere // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $AddressOnly // CHECK-NEXT: inject_enum_addr [[NOUGHT]] // CHECK-NEXT: destroy_addr [[NOUGHT]] // CHECK-NEXT: dealloc_stack [[NOUGHT]] _ = AddressOnly.nought // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[MERE:%.*]] = alloc_stack $AddressOnly // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]] // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[PAYLOAD]] // CHECK-NEXT: store %0 to [[PAYLOAD_ADDR]] // CHECK-NEXT: inject_enum_addr [[MERE]] // CHECK-NEXT: destroy_addr [[MERE]] // CHECK-NEXT: dealloc_stack [[MERE]] _ = AddressOnly.mere(s) // Address-only enum vs loadable payload // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[PHANTOM:%.*]] = alloc_stack $AddressOnly // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[PHANTOM]] : $*AddressOnly, #AddressOnly.phantom!enumelt.1 // CHECK-NEXT: store %0 to [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[PHANTOM]] : $*AddressOnly, #AddressOnly.phantom!enumelt.1 // CHECK-NEXT: destroy_addr [[PHANTOM]] // CHECK-NEXT: dealloc_stack [[PHANTOM]] _ = AddressOnly.phantom(s) // CHECK: return } // CHECK-LABEL: sil shared [transparent] @_TFOs11AddressOnly4mereFMS_FPs1P_S_ // CHECK: [[FN:%.*]] = function_ref @_TFOs11AddressOnly4merefMS_FPs1P_S_ // CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]](%0) // CHECK-NEXT: return [[METHOD]] : $@callee_owned (@out AddressOnly, @in P) -> () // CHECK-NEXT: } // CHECK-LABEL: sil shared [transparent] @_TFOs11AddressOnly4merefMS_FPs1P_S_ // CHECK: [[RET_DATA:%.*]] = init_enum_data_addr %0 : $*AddressOnly, #AddressOnly.mere!enumelt.1 // CHECK-NEXT: copy_addr [take] %1 to [initialization] [[RET_DATA]] : $*P // CHECK-NEXT: inject_enum_addr %0 : $*AddressOnly, #AddressOnly.mere!enumelt.1 // CHECK: return // CHECK-NEXT: } enum PolyOptionable<T> { case nought case mere(T) } // CHECK-LABEL: sil hidden @_TFs20PolyOptionable_casesurFxT_ func PolyOptionable_cases<T>(t: T) { // CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type // CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $PolyOptionable<T> // CHECK-NEXT: inject_enum_addr [[NOUGHT]] // CHECK-NEXT: destroy_addr [[NOUGHT]] // CHECK-NEXT: dealloc_stack [[NOUGHT]] _ = PolyOptionable<T>.nought // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type // CHECK-NEXT: [[MERE:%.*]] = alloc_stack $PolyOptionable<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]] // CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[MERE]] // CHECK-NEXT: destroy_addr [[MERE]] // CHECK-NEXT: dealloc_stack [[MERE]] _ = PolyOptionable<T>.mere(t) // CHECK-NEXT: destroy_addr %0 // CHECK: return } // The substituted type is loadable and trivial here // CHECK-LABEL: sil hidden @_TFs32PolyOptionable_specialized_casesFSiT_ func PolyOptionable_specialized_cases(t: Int) { // CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type // CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.nought!enumelt _ = PolyOptionable<Int>.nought // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type // CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.mere!enumelt.1, %0 _ = PolyOptionable<Int>.mere(t) // CHECK: return } // Regression test for a bug where temporary allocations created as a result of // tuple implosion were not deallocated in enum constructors. struct String { var ptr: Builtin.NativeObject } enum Foo { case A(P, String) } // CHECK-LABEL: sil shared [transparent] @_TFOs3Foo1AFMS_FTPs1P_SS_S_ // CHECK: [[FN:%.*]] = function_ref @_TFOs3Foo1AfMS_FTPs1P_SS_S_ // CHECK-NEXT: [[METHOD:%.*]] = partial_apply [[FN]](%0) // CHECK-NEXT: return [[METHOD]] // CHECK-NEXT: } // CHECK-LABEL: sil shared [transparent] @_TFOs3Foo1AfMS_FTPs1P_SS_S_ // CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Foo, #Foo.A!enumelt.1 // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 1 // CHECK-NEXT: copy_addr [take] %1 to [initialization] [[LEFT]] : $*P // CHECK-NEXT: store %2 to [[RIGHT]] // CHECK-NEXT: inject_enum_addr %0 : $*Foo, #Foo.A!enumelt.1 // CHECK: return // CHECK-NEXT: } func Foo_cases() { _ = Foo.A }
apache-2.0
757eb8d66962d753d8a1434d7c73a83a
35.201058
115
0.628033
3.066786
false
false
false
false
PiXeL16/BudgetShare
BudgetShareTests/Modules/SignUp/Wireframe/Mock/MockSignUpWireframe.swift
1
1385
// // MockSignUpWireframe.swift // BudgetShareTests // // Created by Chris Jimenez on 9/23/17. // Copyright © 2017 Chris Jimenez. All rights reserved. // import UIKit @testable import BudgetShare class MockSignUpWireframe: SignUpWireframe { var view: SignUpView var root: RootWireframeInterface? var createViewControllerCalled = false var attachRootCalled = false var showErrorCalled = false var pushLoginCalled = false var pushBudgetDetailCalled = false var pushCreateBudgetCalled = false required init(root: RootWireframeInterface?, view: SignUpView) { self.root = root self.view = view } static func createViewController() -> SignUpViewController { return SignUpViewController() } func attachRoot(with controller: UIViewController, in window: UIWindow) { self.attachRootCalled = true } func showErrorAlert(title: String, message: String, from controller: UIViewController?) { self.showErrorCalled = true } func pushLogin(from controller: UIViewController?) { self.pushLoginCalled = true } func pushBudgetDetail(from controller: UIViewController?) { self.pushBudgetDetailCalled = true } func pushCreateBudget(from controller: UIViewController?) { self.pushCreateBudgetCalled = true } }
mit
51fa14f266f0d09ab3d59797fe1eab2f
25.615385
93
0.687861
4.907801
false
false
false
false
avario/ChainKit
ChainKit/ChainKit/UITextView+ChainKit.swift
1
3777
// // UITextView+ChainKit.swift // ChainKit // // Created by Avario. // import UIKit public extension UITextView { public func text(_ text: String?) -> Self { self.text = text return self } public func font(_ font: UIFont) -> Self { self.font = font return self } public func textColor(_ textColor: UIColor?) -> Self { self.textColor = textColor return self } public func textAlignment(_ textAlignment: NSTextAlignment) -> Self { self.textAlignment = textAlignment return self } public func selectedRange(_ selectedRange: NSRange) -> Self { self.selectedRange = selectedRange return self } public func isEditable(_ isEditable: Bool) -> Self { self.isEditable = isEditable return self } public func isSelectable(_ isSelectable: Bool) -> Self { self.isSelectable = isSelectable return self } public func dataDetectorTypes(_ dataDetectorTypes: UIDataDetectorTypes) -> Self { self.dataDetectorTypes = dataDetectorTypes return self } public func allowsEditingTextAttributes(_ allowsEditingTextAttributes: Bool) -> Self { self.allowsEditingTextAttributes = allowsEditingTextAttributes return self } public func attributedText(_ attributedText: NSAttributedString?) -> Self { self.attributedText = attributedText return self } public func inputView(_ inputView: UIView?) -> Self { self.inputView = inputView return self } public func inputAccessoryView(_ inputAccessoryView: UIView?) -> Self { self.inputAccessoryView = inputAccessoryView return self } public func clearsOnInsertion(_ clearsOnInsertion: Bool) -> Self { self.clearsOnInsertion = clearsOnInsertion return self } public func textContainerInset(_ textContainerInset: UIEdgeInsets) -> Self { self.textContainerInset = textContainerInset return self } public func linkTextAttributes(_ linkTextAttributes: [String: Any]?) -> Self { self.linkTextAttributes = linkTextAttributes return self } public func autocapitalizationType(_ autocapitalizationType: UITextAutocapitalizationType) -> Self { self.autocapitalizationType = autocapitalizationType return self } public func autocorrectionType(_ autocorrectionType: UITextAutocorrectionType) -> Self { self.autocorrectionType = autocorrectionType return self } public func spellCheckingType(_ spellCheckingType: UITextSpellCheckingType) -> Self { self.spellCheckingType = spellCheckingType return self } public func keyboardType(_ keyboardType: UIKeyboardType) -> Self { self.keyboardType = keyboardType return self } public func keyboardAppearance(_ keyboardAppearance: UIKeyboardAppearance) -> Self { self.keyboardAppearance = keyboardAppearance return self } public func returnKeyType(_ returnKeyType: UIReturnKeyType) -> Self { self.returnKeyType = returnKeyType return self } public func enablesReturnKeyAutomatically(_ enablesReturnKeyAutomatically: Bool) -> Self { self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically return self } public func isSecureTextEntry(_ isSecureTextEntry: Bool) -> Self { self.isSecureTextEntry = isSecureTextEntry return self } @available(iOS 10.0, *) public func textContentType(_ textContentType: UITextContentType) -> Self { self.textContentType = textContentType return self } }
mit
3163d4e0db7ae80b4aa2e456315be3b5
27.398496
104
0.662166
6.151466
false
false
false
false
duliodenis/HipsterWeather
Hipster/Hipster/CurrentWeather.swift
1
2326
// // CurrentWeather.swift // Hipster // // Created by Dulio Denis on 6/14/15. // Copyright (c) 2015 Dulio Denis. All rights reserved. // import Foundation import UIKit enum Icon: String { // the ten different values possible case ClearDay = "clear-day" case ClearNight = "clear-night" case Rain = "rain" case Snow = "snow" case Sleet = "sleet" case Wind = "wind" case Fog = "fog" case Cloudy = "cloudy" case PartlyCloudyDay = "partly-cloudy-day" case PartlyCloudyNight = "partly-cloudy-night" func toImage() -> UIImage? { var imageName: String switch self { case .ClearDay: imageName = "clear-day.png" case .ClearNight: imageName = "clear-night.png" case .Rain: imageName = "rain.png" case .Snow: imageName = "snow.png" case .Sleet: imageName = "sleet.png" case .Wind: imageName = "wind.png" case .Fog: imageName = "fog.png" case .Cloudy: imageName = "cloudy.png" case .PartlyCloudyDay: imageName = "cloudy-day.png" case .PartlyCloudyNight: imageName = "cloudy-night.png" } return UIImage(named: imageName) } } struct CurrentWeather { let temperature: Int? let humidity: Int? let precipProbability: Int? let summary: String? var icon: UIImage? = UIImage(named: "default.png") init(weatherDictionary: [String: AnyObject]) { temperature = weatherDictionary["temperature"] as? Int if let humidityFloat = weatherDictionary["humidity"] as? Double { humidity = Int(humidityFloat * 100) } else { humidity = nil } if let precipitationProbabilityFloat = weatherDictionary["precipProbability"] as? Double { precipProbability = Int(precipitationProbabilityFloat * 100) } else { precipProbability = nil } summary = weatherDictionary["summary"] as? String if let iconString = weatherDictionary["icon"] as? String, let weatherIcon: Icon = Icon(rawValue: iconString) { icon = weatherIcon.toImage() } } }
mit
5cd19fdd7ba217f909d757794803ad86
30.026667
98
0.569218
4.37218
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/CustomPaging/Collection/CollectionCell.swift
1
1238
// // CollectionCell.swift // CustomPaging // // Created by Ilya Lobanov on 26/08/2018. // Copyright © 2018 Ilya Lobanov. All rights reserved. // import UIKit final class CollectionCell: UICollectionViewCell { struct Info { var text: String var textColor: UIColor var bgColor: UIColor var size: CGSize } override init(frame: CGRect) { super.init(frame: frame) contentView.layer.masksToBounds = true contentView.addSubview(textLabel) textLabel.font = .systemFont(ofSize: 16, weight: .bold) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(with info: Info) { textLabel.textAlignment = .center textLabel.text = info.text textLabel.textColor = info.textColor contentView.backgroundColor = info.bgColor } // MARK: - UIView override func layoutSubviews() { super.layoutSubviews() textLabel.frame = contentView.bounds contentView.layer.cornerRadius = contentView.bounds.height / 2 } // MARK: - Private private let textLabel = UILabel() }
mit
d078804033f87edf386863b8bdcbb428
22.788462
70
0.615198
4.794574
false
false
false
false
mightydeveloper/swift
test/SILPasses/inout_deshadow_integration.swift
12
3045
// RUN: %target-swift-frontend %s -emit-sil | FileCheck %s // This is an integration check for the inout-deshadow pass, verifying that it // deshadows the inout variables in certain cases. These test should not be // very specific (as they are running the parser, silgen and other sil // diagnostic passes), they should just check the inout shadow got removed. // CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_dead // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_trivial_type_dead(inout a: Int) { } // CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_returned // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_trivial_type_returned(inout a: Int) -> Int { return a } // CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_trivial_type_stored(inout a: Int) { a = 12 } // CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored_returned // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_trivial_type_stored_returned(inout a: Int) -> Int { a = 12 return a } // CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_dead // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_nontrivial_type_dead(inout a: String) { } // CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_returned // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_nontrivial_type_returned(inout a: String) -> String { return a } // CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_nontrivial_type_stored(inout a: String) { a = "x" } // CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored_returned // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } func exploded_nontrivial_type_stored_returned(inout a: String) -> String { a = "x" return a } // Use an external function so inout deshadowing cannot see its body. @_silgen_name("takesNoEscapeClosure") func takesNoEscapeClosure(@noescape fn : () -> Int) struct StructWithMutatingMethod { var x = 42 // We should be able to deshadow this. The closure is capturing self, but it // is itself noescape. mutating func mutatingMethod() { takesNoEscapeClosure { x = 42; return x } } mutating func testStandardLibraryOperators() { if x != 4 || x != 0 { testStandardLibraryOperators() } } } // CHECK-LABEL: sil hidden @_TFV26inout_deshadow_integration24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(method) (@inout StructWithMutatingMethod) -> () { // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack // CHECK: } // CHECK-LABEL: sil hidden @_TFV26inout_deshadow_integration24StructWithMutatingMethod28testStandardLibraryOperators{{.*}} : $@convention(method) (@inout StructWithMutatingMethod) -> () { // CHECK-NOT: alloc_box $StructWithMutatingMethod // CHECK-NOT: alloc_stack $StructWithMutatingMethod // CHECK: }
apache-2.0
94d028989762756f3d59a95aef1195cc
28
187
0.702463
3.625
false
false
false
false
SuPair/firefox-ios
Client/Frontend/Browser/FormPostHelper.swift
4
3152
/* 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 WebKit struct FormPostData { let action: URL let method: String let target: String let enctype: String let requestBody: Data init?(messageBody: Any) { guard let messageBodyDict = messageBody as? [String: String], let actionString = messageBodyDict["action"], let method = messageBodyDict["method"], let target = messageBodyDict["target"], let enctype = messageBodyDict["enctype"], let requestBodyString = messageBodyDict["requestBody"], let action = URL(string: actionString), let requestBody = requestBodyString.data(using: .utf8) else { return nil } self.action = action self.method = method self.target = target self.enctype = enctype self.requestBody = requestBody } func matchesNavigationAction(_ navigationAction: WKNavigationAction) -> Bool { let request = navigationAction.request let headers = request.allHTTPHeaderFields ?? [:] if self.action == request.url, self.method == request.httpMethod, self.enctype == headers["Content-Type"] { return true } return false } func urlRequestWithHeaders(_ headers: [String: String]?) -> URLRequest { var urlRequest = URLRequest(url: action) urlRequest.httpMethod = method urlRequest.allHTTPHeaderFields = headers ?? [:] urlRequest.setValue(enctype, forHTTPHeaderField: "Content-Type") urlRequest.httpBody = requestBody return urlRequest } } class FormPostHelper: TabContentScript { fileprivate weak var tab: Tab? fileprivate var blankTargetFormPosts: [FormPostData] = [] required init(tab: Tab) { self.tab = tab } static func name() -> String { return "FormPostHelper" } func scriptMessageHandlerName() -> String? { return "formPostHelper" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { guard let formPostData = FormPostData(messageBody: message.body) else { print("Unable to parse FormPostData from script message body.") return } blankTargetFormPosts.append(formPostData) } func urlRequestForNavigationAction(_ navigationAction: WKNavigationAction) -> URLRequest { guard let formPostData = blankTargetFormPosts.first(where: { $0.matchesNavigationAction(navigationAction) }) else { return navigationAction.request } let request = formPostData.urlRequestWithHeaders(navigationAction.request.allHTTPHeaderFields) if let index = blankTargetFormPosts.index(where: { $0.matchesNavigationAction(navigationAction) }) { blankTargetFormPosts.remove(at: index) } return request } }
mpl-2.0
80d8a1f10ae37edcf70db7371414f699
32.178947
132
0.651967
5.083871
false
false
false
false
ZhiQiang-Yang/pppt
v2exProject 2/Pods/Alamofire/Source/Upload.swift
272
15860
// Upload.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension Manager { private enum Uploadable { case Data(NSURLRequest, NSData) case File(NSURLRequest, NSURL) case Stream(NSURLRequest, NSInputStream) } private func upload(uploadable: Uploadable) -> Request { var uploadTask: NSURLSessionUploadTask! var HTTPBodyStream: NSInputStream? switch uploadable { case .Data(let request, let data): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithRequest(request, fromData: data) } case .File(let request, let fileURL): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL) } case .Stream(let request, let stream): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithStreamedRequest(request) } HTTPBodyStream = stream } let request = Request(session: session, task: uploadTask) if HTTPBodyStream != nil { request.delegate.taskNeedNewBodyStream = { _, _ in return HTTPBodyStream } } delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: File /** Creates a request for uploading a file to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - parameter file: The file to upload - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return upload(.File(URLRequest.URLRequest, file)) } /** Creates a request for uploading a file to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, file: NSURL) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, file: file) } // MARK: Data /** Creates a request for uploading data to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return upload(.Data(URLRequest.URLRequest, data)) } /** Creates a request for uploading data to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, data: data) } // MARK: Stream /** Creates a request for uploading a stream to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return upload(.Stream(URLRequest.URLRequest, stream)) } /** Creates a request for uploading a stream to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, stream: stream) } // MARK: MultipartFormData /// Default memory threshold used when encoding `MultipartFormData`. public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024 /** Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as associated values. - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with streaming information. - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding error. */ public enum MultipartFormDataEncodingResult { case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?) case Failure(ErrorType) } /** Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative payload is small, encoding the data in-memory and directly uploading to a server is the by far the most efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be used for larger payloads such as video content. The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding technique was used. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload( mutableURLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative payload is small, encoding the data in-memory and directly uploading to a server is the by far the most efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be used for larger payloads such as video content. The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding technique was used. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let formData = MultipartFormData() multipartFormData(formData) let URLRequestWithContentType = URLRequest.URLRequest URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") let isBackgroundSession = self.session.configuration.identifier != nil if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { do { let data = try formData.encode() let encodingResult = MultipartFormDataEncodingResult.Success( request: self.upload(URLRequestWithContentType, data: data), streamingFromDisk: false, streamFileURL: nil ) dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(encodingResult) } } catch { dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(.Failure(error as NSError)) } } } else { let fileManager = NSFileManager.defaultManager() let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data") let fileName = NSUUID().UUIDString let fileURL = directoryURL.URLByAppendingPathComponent(fileName) do { try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil) try formData.writeEncodedDataToDisk(fileURL) dispatch_async(dispatch_get_main_queue()) { let encodingResult = MultipartFormDataEncodingResult.Success( request: self.upload(URLRequestWithContentType, file: fileURL), streamingFromDisk: true, streamFileURL: fileURL ) encodingCompletion?(encodingResult) } } catch { dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(.Failure(error as NSError)) } } } } } } // MARK: - extension Request { // MARK: - UploadTaskDelegate class UploadTaskDelegate: DataTaskDelegate { var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } var uploadProgress: ((Int64, Int64, Int64) -> Void)! // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? // MARK: Delegate Methods func URLSession( session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { progress.totalUnitCount = totalBytesExpectedToSend progress.completedUnitCount = totalBytesSent uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) } } } }
apache-2.0
84bd08a71b16644bc1c38f5cba6b5a7b
41.629032
124
0.649767
5.751904
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/ATTWriteCommand.swift
1
1548
// // ATTWriteCommand.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// Write Command /// /// The *Write Command* is used to request the server to write the value of an attribute, typically into a control-point attribute. @frozen public struct ATTWriteCommand: ATTProtocolDataUnit, Equatable { public static var attributeOpcode: ATTOpcode { return .writeCommand } /// The handle of the attribute to be set. public var handle: UInt16 /// The value of be written to the attribute. public var value: Data public init(handle: UInt16, value: Data) { self.handle = handle self.value = value } } public extension ATTWriteCommand { init?(data: Data) { guard data.count >= 3, type(of: self).validateOpcode(data) else { return nil } self.handle = UInt16(littleEndian: UInt16(bytes: (data[1], data[2]))) self.value = data.suffixCheckingBounds(from: 3) } var data: Data { return Data(self) } } // MARK: - DataConvertible extension ATTWriteCommand: DataConvertible { var dataLength: Int { return 3 + value.count } static func += <T: DataContainer> (data: inout T, value: ATTWriteCommand) { data += attributeOpcode.rawValue data += value.handle.littleEndian data += value.value } }
mit
bcb8656bcc7a926a20ab9b1b7d2fc173
22.439394
131
0.605042
4.297222
false
false
false
false
daisukenagata/BLEView
BLEView/Classes/BLTimeCount.swift
1
1018
// // BLTimeCount.swift // Pods // // Created by 永田大祐 on 2017/02/04. // // import Foundation class BLTimeCount { var timer = Timer() class func stringFromDate(date: NSDate, format: String) -> String { let formatter: DateFormatter = DateFormatter() formatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale? formatter.dateStyle = DateFormatter.Style.full formatter.timeStyle = DateFormatter.Style.short formatter.dateFormat = format return formatter.string(from: date as Date) } @objc func timerSetting(){ timer.fire() timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(update(tm:)), userInfo: nil, repeats: true) } @objc func update(tm: Timer){ BlModel.sharedBLEView.setCut() BlModel.sharedBLEView.setVoice(ddd: "接続しました") } func stopTimer(){ timer.invalidate() } }
mit
f16854aaa3cdf84530c314101580c5be
22.761905
133
0.60521
4.246809
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Compose/AAComposeController.swift
2
1776
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit public class AAComposeController: AAContactsListContentController, AAContactsListContentControllerDelegate { public override init() { super.init() self.delegate = self self.isSearchAutoHide = false self.navigationItem.title = AALocalized("ComposeTitle") if AADevice.isiPad { self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: AALocalized("NavigationCancel"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(AAViewController.dismiss)) } } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func willAddContacts(controller: AAContactsListContentController, section: AAManagedSection) { section.custom { (r:AACustomRow<AAContactActionCell>) -> () in r.height = 56 r.closure = { (cell) -> () in cell.bind("ic_add_user", actionTitle: AALocalized("CreateGroup")) } r.selectAction = { () -> Bool in self.navigateNext(AAGroupCreateViewController(), removeCurrent: true) return false } } } public func contactDidTap(controller: AAContactsListContentController, contact: ACContact) -> Bool { if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer_userWithInt_(contact.uid)) { navigateDetail(customController) } else { navigateDetail(ConversationViewController(peer: ACPeer_userWithInt_(contact.uid))) } return false } }
agpl-3.0
606650f5370b7aca3604aacbe6ba73b8
34.54
201
0.630068
5.103448
false
false
false
false
luongtsu/MHCalendar
MHCalendar/UINibView.swift
1
1044
// // UINibView.swift // MHCalendarDemo // // Created by Luong Minh Hiep on 9/12/17. // Copyright © 2017 Luong Minh Hiep. All rights reserved. // import UIKit class UINibView: UIView { private var view: UIView! // MARK: - Inits override init(frame: CGRect) { super.init(frame: frame) self.loadFromNib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.loadFromNib() } // MARK: - Private Methods private func loadFromNib() { let nibName = String(describing: type(of: self)) let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: nibName, bundle: bundle) guard let view = nib.instantiate(withOwner: self, options: nil).first as? UIView else { return } view.frame = bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.view = view self.addSubview(view) } }
mit
d8c240368b37465c47dc6fae8e3d8926
21.673913
95
0.566635
4.239837
false
false
false
false
h0lyalg0rithm/Appz
Appz/Appz/Entity/ApplicationCaller.swift
1
1227
// // ApplicationCaller.swift // Appz // // Created by Mazyad Alabduljaleel on 11/10/15. // Copyright © 2015 kitz. All rights reserved. // import Foundation /** Encapsulate the object which launches the apps. Useful for UIApplication, NSExtensionContext, and testing. */ public protocol ApplicationCaller { func canOpenURL(url: NSURL) -> Bool func openURL(url: NSURL) -> Bool } public extension ApplicationCaller { public var open: AvailableApplications { return AvailableApplications(appCaller: self) } func launch(externalApp: ExternalApplication, action: ExternalApplicationAction) -> Bool { let fallbackPath = action.fallbackPath ?? action.path let scheme = (externalApp.scheme ?? "") + "//" let baseURL = NSURL(string: scheme) if let url = baseURL where canOpenURL(url), let fullURL = NSURL(string: scheme + action.path) { return openURL(fullURL) } if let fallbackURL = externalApp.fallbackURL, let url = NSURL(string: fallbackURL + fallbackPath) { return openURL(url) } return false } }
mit
b38b1f4569cdab48cc974c1b2280d290
24.541667
94
0.615008
4.826772
false
false
false
false
mbalex99/RippleEffectView
Demo/RippleEffectDemo/RippleEffectView.swift
1
10025
// // RippleEffectView.swift // RippleEffectView // // Created by Alex Sergeev on 8/14/16. // Copyright © 2016 ALSEDI Group. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit enum RippleType { case OneWave case Heartbeat } @IBDesignable class RippleEffectView: UIView { typealias CustomizationClosure = (totalRows:Int, totalColumns:Int, currentRow:Int, currentColumn:Int, originalImage:UIImage)->(UIImage) typealias VoidClosure = () -> () var cellSize:CGSize? var rippleType: RippleType = .OneWave var tileImage:UIImage! var magnitude: CGFloat = -0.6 var animationDuration: Double = 3.5 var isAnimating: Bool = false private var tiles = [GridItemView]() private var isGridRendered: Bool = false var tileImageCustomizationClosure: CustomizationClosure? = nil { didSet { stopAnimating() removeGrid() renderGrid() } } var animationDidStop: VoidClosure? func setupView() { if isAnimating { stopAnimating() } removeGrid() renderGrid() } } // MARK: View operations extension RippleEffectView { override func willMoveToSuperview(newSuperview: UIView?) { if let parent = newSuperview where newSuperview != nil { self.frame = CGRect(x: 0, y: 0, width: parent.frame.width, height: parent.frame.height) } } override func layoutSubviews() { guard let parent = superview else { return } self.frame = CGRect(x: 0, y: 0, width: parent.frame.width, height: parent.frame.height) setupView() } } //MARK: Animations extension RippleEffectView { func stopAnimating() { isAnimating = false layer.removeAllAnimations() } func simulateAnimationEnd() { waitAndRun(animationDuration){ if let callback = self.animationDidStop { callback() } if self.isAnimating { self.simulateAnimationEnd() } } } func startAnimating() { guard superview != nil else { return } if isGridRendered == false { renderGrid() } isAnimating = true layer.shouldRasterize = true simulateAnimationEnd() for tile in tiles { let distance = self.distance(fromPoint:tile.position, toPoint:self.center) var vector = self.normalizedVector(fromPoint:tile.position, toPoint:self.center) vector = CGPoint(x:vector.x * magnitude * distance, y: vector.y * magnitude * distance) tile.startAnimatingWithDuration(animationDuration, rippleDelay: animationDuration - 0.0006666 * NSTimeInterval(distance), rippleOffset: vector) } } } //MARK: Grid operations extension RippleEffectView { func removeGrid() { for tile in tiles { tile.removeAllAnimations() tile.removeFromSuperlayer() } tiles.removeAll() isGridRendered = false } func renderGrid() { guard isGridRendered == false else { return } guard tileImage != nil else { return } isGridRendered = true let itemWidth = (cellSize == nil) ? tileImage.size.width : cellSize!.width let itemHeight = (cellSize == nil) ? tileImage.size.height : cellSize!.height let rows = ((self.rows % 2 == 0) ? self.rows + 3 : self.rows + 2) let columns = ((self.columns % 2 == 0) ? self.columns + 3 : self.columns + 2) let offsetX = columns / 2 let offsetY = rows / 2 let startPoint = CGPoint(x: center.x - (CGFloat(offsetX) * itemWidth), y: center.y - (CGFloat(offsetY) * itemHeight)) for row in 0..<rows { for column in 0..<columns { let tileLayer = GridItemView() if let imageCustomization = tileImageCustomizationClosure { tileLayer.tileImage = imageCustomization(totalRows: self.rows, totalColumns: self.columns, currentRow: row, currentColumn: column, originalImage: (tileLayer.tileImage == nil) ? tileImage : tileLayer.tileImage!) tileLayer.contents = tileLayer.tileImage?.CGImage } else { tileLayer.contents = tileImage.CGImage } tileLayer.rippleType = rippleType tileLayer.frame.size = CGSize(width: itemWidth, height: itemHeight) tileLayer.contentsScale = contentScaleFactor tileLayer.contentsGravity = kCAGravityResize tileLayer.position = startPoint tileLayer.position.x = tileLayer.position.x + (CGFloat(column) * itemWidth) tileLayer.position.y = tileLayer.position.y + (CGFloat(row) * itemHeight) tileLayer.shouldRasterize = true layer.addSublayer(tileLayer) tiles.append(tileLayer) } } } var rows: Int { var size = tileImage.size if let _ = cellSize { size = cellSize! } return Int(self.frame.height / size.height) } var columns: Int { var size = tileImage.size if let _ = cellSize { size = cellSize! } return Int(self.frame.width / size.width) } } //MARK: Helper methods private extension UIView { func distance(fromPoint fromPoint:CGPoint,toPoint:CGPoint)->CGFloat { let nX = (fromPoint.x - toPoint.x) let nY = (fromPoint.y - toPoint.y) return sqrt(nX*nX + nY*nY) } func normalizedVector(fromPoint fromPoint:CGPoint,toPoint:CGPoint)->CGPoint { let length = distance(fromPoint:fromPoint, toPoint:toPoint) guard length > 0 else { return CGPoint.zero } return CGPoint(x:(fromPoint.x - toPoint.x)/length, y:(fromPoint.y - toPoint.y)/length) } } private class GridItemView: CALayer { var tileImage:UIImage? var rippleType:RippleType = .OneWave func startAnimatingWithDuration(duration: NSTimeInterval, rippleDelay: NSTimeInterval, rippleOffset: CGPoint) { let timingFunction = CAMediaTimingFunction(controlPoints: 0.25, 0, 0.2, 1) let linearFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) let zeroPointValue = NSValue(CGPoint: CGPointZero) var animations = [CAAnimation]() let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") if rippleType == .Heartbeat { scaleAnimation.keyTimes = [0, 0.3, 0.4, 0.5, 0.6, 0.69, 0.735, 1] scaleAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, timingFunction, timingFunction, timingFunction] scaleAnimation.values = [1, 1, 1.35, 1.05, 1.20, 0.95, 1, 1] } else { scaleAnimation.keyTimes = [0, 0.5, 0.6, 1] scaleAnimation.values = [1, 1, 1.15, 1] scaleAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction] } scaleAnimation.beginTime = 0.0 scaleAnimation.duration = duration animations.append(scaleAnimation) let positionAnimation = CAKeyframeAnimation(keyPath: "position") positionAnimation.duration = duration if rippleType == .Heartbeat { let secondBeat = CGPoint(x:rippleOffset.x, y:rippleOffset.y) positionAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, timingFunction, timingFunction, linearFunction] positionAnimation.keyTimes = [0, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 1] positionAnimation.values = [zeroPointValue, zeroPointValue, NSValue(CGPoint:rippleOffset), zeroPointValue, NSValue(CGPoint:secondBeat), NSValue(CGPoint:CGPoint(x:-rippleOffset.x*0.3,y:-rippleOffset.y*0.3)),zeroPointValue, zeroPointValue] } else { positionAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction] positionAnimation.keyTimes = [0, 0.5, 0.6, 1] positionAnimation.values = [zeroPointValue, zeroPointValue, NSValue(CGPoint:rippleOffset), zeroPointValue] } positionAnimation.additive = true animations.append(positionAnimation) let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.duration = duration if rippleType == .Heartbeat { opacityAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, linearFunction] opacityAnimation.keyTimes = [0, 0.3, 0.4, 0.5, 0.6, 0.69, 1] opacityAnimation.values = [1, 1, 0.85, 0.75, 0.90, 1, 1] } else { opacityAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, linearFunction] opacityAnimation.keyTimes = [0, 0.5, 0.6, 0.94, 1] opacityAnimation.values = [1, 1, 0.45, 1, 1] } animations.append(opacityAnimation) let groupAnimation = CAAnimationGroup() groupAnimation.repeatCount = Float.infinity groupAnimation.fillMode = kCAFillModeBackwards groupAnimation.duration = duration groupAnimation.beginTime = rippleDelay groupAnimation.removedOnCompletion = false groupAnimation.animations = animations groupAnimation.timeOffset = 0.35 * duration shouldRasterize = true addAnimation(groupAnimation, forKey: "ripple") } func stopAnimating() { removeAllAnimations() } } func waitAndRun(delay:Double, closure:()->()) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure) }
mit
10d9cbd5fc74997ce64858e386642d87
34.672598
243
0.694433
4.386871
false
false
false
false
cubixlabs/GIST-Framework
GISTFramework/Classes/GISTSocial/CoreData/DataManager.swift
1
11528
// // DataManager.swift // E-Grocery // // Created by Muneeba on 1/14/15. // Copyright (c) 2015 cubixlabs. All rights reserved. // import UIKit import CoreData public var DATA_MANAGER:DataManager { get { return DataManager.sharedManager; } } //P.E. public var MANAGED_CONTEXT:NSManagedObjectContext { get { return DataManager.sharedManager.managedObjectContext; } } //P.E. public class DataManager: NSObject { private var _dataBaseModel:String? = nil; private var dataBaseModel:String { if (_dataBaseModel == nil) { _dataBaseModel = SyncedConstants.constant(forKey: "databaseFileName") ?? "CoreData"; } return _dataBaseModel!; // momd file } //F.E. private var _dataBaseName:String? = nil; private var dataBaseName:String { if (_dataBaseName == nil) { let modFile:String = self.dataBaseModel; let version:String = AppInfo.versionNBuildNumber;//SyncedConstants.constant(forKey: "databaseVersion") ?? "V1.0"; _dataBaseName = "\(modFile)_\(version).sqlite"; } return _dataBaseName!; } //F.E. public static var sharedManager: DataManager = DataManager(); // MARK: - Core Data stack lazy var applicationDocumentsDirectory: URL = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = Bundle.main.url(forResource: self.dataBaseModel, withExtension: "momd")! return NSManagedObjectModel(contentsOf: 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.appendingPathComponent(self.dataBaseName); let failureReason = "There was an error creating or loading the application's saved data." // MAIN LINE OF CODE TO ADD let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: mOptions); } catch { var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support public 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() } } } // F.E. public func checkIfObjectExists(_ entityName:String, key:String, value:String)-> Bool { let count:Int = self.fetchObjectsCountForEntity(entityName, queryString: "\(key)==\(value)"); //-- return (count>0); } //F.E public func fetchObjectsCountForEntity(_ entityName:String, queryString:String?)-> Int { let predicate:NSPredicate? = (queryString == nil) ? nil: NSPredicate(format: queryString!, argumentArray: nil); //-- return self.fetchObjectsCountForEntity(entityName, predicate:predicate); } //F.E. public func fetchObjectsCountForEntity(_ entityName:String, predicate:NSPredicate?)-> Int { let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest<NSFetchRequestResult>(); //--setting entity to fetch request let entity:NSEntityDescription = NSEntityDescription.entity(forEntityName: entityName, in: self.managedObjectContext)! fetchRequest.entity = entity //--- predicate for fetch request fetchRequest.predicate = predicate fetchRequest.includesPropertyValues = false; fetchRequest.includesSubentities = false; var count:Int = 0; do { count = try self.managedObjectContext.count(for: fetchRequest) } catch { print(error.localizedDescription); } return count } //F.E. public func fetchObjectsForEntityName<T:NSFetchRequestResult>(_ entityName:String, predicate:NSPredicate?, descriptor:NSSortDescriptor?)->[T] { return fetchObjectsForEntityName(entityName, predicate:predicate, descriptors: (descriptor == nil) ?nil:[descriptor!]); } //F.E. public func fetchObjectsForEntityName<T:NSFetchRequestResult>(_ entityName:String, predicate:NSPredicate?, descriptors:[NSSortDescriptor]?)->[T] { var rtnArr:[T]? let fetchRequest:NSFetchRequest<T> = NSFetchRequest<T>(entityName:entityName); // setting sort descriptor to fetch request fetchRequest.sortDescriptors = descriptors ;//[descriptor!] // predicate for fetch request fetchRequest.predicate = predicate do { rtnArr = try self.managedObjectContext.fetch(fetchRequest) } catch{ print(error.localizedDescription); } return rtnArr!; } //F.E. public func fetchObjectsForEntityNameWithSection(_ entityName:String, predicate:NSPredicate?, descriptors:[NSSortDescriptor]?, sectionName: String)->NSFetchedResultsController<NSFetchRequestResult> { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName) // setting sort descriptor to fetch request fetchRequest.sortDescriptors = descriptors ;//[descriptor!] // predicate for fetch request fetchRequest.predicate = predicate let fetchRequestController:NSFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: sectionName, cacheName: nil) do { try fetchRequestController.performFetch() } catch { print("An error occurred") } return fetchRequestController; } //F.E. public func insertSingleObjectForEntityName<T:NSManagedObject>(_ entityName: String, uniquekey key:String, uniquekeyValue value:Any) -> T { var managedObj:NSManagedObject?; let predicate:NSPredicate if value is String { predicate = NSPredicate(format: "\(key)=='\(value)'"); } else { predicate = NSPredicate(format: "\(key)==\(value)"); } let arr :[T] = DATA_MANAGER.fetchObjectsForEntityName(entityName, predicate: predicate, descriptor: nil); managedObj = arr.first; if(managedObj == nil){ managedObj = NSEntityDescription.insertNewObject(forEntityName: entityName, into: self.managedObjectContext); //-- managedObj?.setValue(value, forKey: key); } return managedObj as! T; } //F.E. public func deleteObjectsForEntityName(_ entityName:String, predicate:NSPredicate?){ let arr:[NSManagedObject] = self.fetchObjectsForEntityName(entityName, predicate: predicate, descriptor: nil); for item in arr { self.managedObjectContext.delete(item); } self.saveContext(); } //F.E. @available(iOS 9.0, *) public func deleteAllObjectsForEntityName(_ entityName:String) { let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest<NSFetchRequestResult>(entityName:entityName); let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) do { try self.persistentStoreCoordinator.execute(deleteRequest, with: self.managedObjectContext); } catch let error as NSError { print(error.localizedDescription); } } //F.E. public func deleteAllData() { let entities:[NSEntityDescription] = self.managedObjectModel.entities; for entity in entities { if #available(iOS 9.0, *) { self.deleteAllObjectsForEntityName(entity.name!) } else { // Fallback on earlier versions }; } } //F.E. } //CLS END @objc public protocol ManagedProtocol { static var entityName:String {get}; static var uniqueKey:String {get}; static func addEntry(_ data:[String:Any], saveContext:Bool) -> ManagedProtocol; } public extension ManagedProtocol { static func addEntries<T:ManagedProtocol>(_ objectArray: NSArray, cleanup:Bool = false) -> [T]? { guard objectArray.count > 0 else { if (cleanup) { self.cleanup(); } return []; } var rtnArr:[AnyObject] = []; var uniqueValues:[Int] = []; for i in 0 ..< objectArray.count{ let mObj:ManagedProtocol = self.addEntry(objectArray[i] as! [String:Any], saveContext: false) if cleanup == true, let uValue:Int = (mObj as? NSManagedObject)?.value(forKey: self.uniqueKey) as? Int { uniqueValues.append(uValue); } rtnArr.append(mObj); } DATA_MANAGER.saveContext(); if (uniqueValues.count > 0) { DATA_MANAGER.deleteObjectsForEntityName(self.entityName, predicate: NSPredicate(format: "NOT (\(self.uniqueKey) IN %@)", uniqueValues)) } return (rtnArr as? [T]) } //F.E. static func cleanup() { if #available(iOS 9.0, *) { DATA_MANAGER.deleteAllObjectsForEntityName(self.entityName) } else { // Fallback on earlier versions }; } }
agpl-3.0
068c686019fd2651429ea9c01ed1b255
36.796721
291
0.626648
5.466098
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/DataZoom/DataZoom.swift
1
6300
// // DataZoom.swift // SwiftyEcharts // // Created by Pluto-Y on 17/01/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// DataZoom 控件的接口,如果是 DataZoom控件需要实现这个接口 public protocol DataZoom { var xAxisIndex: OneOrMore<UInt8>? { get set } var yAxisIndex: OneOrMore<UInt8>? { get set } } // MARK: - Actions /// 数据区域缩放组件相关的行为,必须引入数据区域缩放组件后才能使用。 public final class DataZoomAction: EchartsAction { public var type: EchartsActionType { return .dataZoom } /// 可选,dataZoom 组件的 index,多个 dataZoom 组件时有用,默认为 0 public var dataZoomIndex: Int? /// 开始位置的百分比,0 - 100 public var start: Float? /// 结束位置的百分比,0 - 100 public var end: Float? /// 开始位置的数值 public var startValue: Jsonable? /// 结束位置的数值 public var endValue: Jsonable? } extension DataZoomAction: Enumable { public enum Enums { case dataZoomIndex(Int), start(Float), end(Float), startValue(Jsonable), endValue(Jsonable) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .dataZoomIndex(dataZoomIndex): self.dataZoomIndex = dataZoomIndex case let .start(start): self.start = start case let .end(end): self.end = end case let .startValue(startValue): self.startValue = startValue case let .endValue(endValue): self.endValue = endValue } } } } extension DataZoomAction: Mappable { public func mapping(_ map: Mapper) { map["type"] = type map["dataZoomIndex"] = dataZoomIndex map["start"] = start map["end"] = end map["startValue"] = startValue map["endValue"] = endValue } } /// dataZoom 的运行原理是通过 数据过滤 来达到 数据窗口缩放 的效果。数据过滤模式的设置不同,效果也不同。 /// 可选值为: /// - filter: 当前数据窗口外的数据,被 过滤掉。即会影响其他轴的数据范围。 /// - empty: 当前数据窗口外的数据,被 设置为空。即不会影响其他轴的数据范围。 /// /// 如何设置,由用户根据场景和需求自己决定。经验来说: /// /// - 当『只有 X 轴 或 只有 Y 轴受 dataZoom 组件控制』时,常使用 filterMode: 'filter',这样能使另一个轴自适应过滤后的数值范围。 /// - 当『X 轴 Y 轴分别受 dataZoom 组件控制』时: /// - 如果 X 轴和 Y 轴是『同等地位的、不应互相影响的』,比如在『双数值轴散点图』中,那么两个轴可都设为 fiterMode: 'empty'。 /// - 如果 X 轴为主,Y 轴为辅,比如在『柱状图』中,需要『拖动 dataZoomX 改变 X 轴过滤柱子时,Y 轴的范围也自适应剩余柱子的高度』,『拖动 dataZoomY 改变 Y 轴过滤柱子时,X 轴范围不受影响』,那么就 X轴设为 fiterMode: 'filter',Y 轴设为 fiterMode: 'empty',即主轴 'filter',辅轴 'empty'。 /// /// 下面是个具体例子: /// /// option = { /// dataZoom: [ /// { /// id: 'dataZoomX', /// type: 'slider', /// xAxisIndex: [0], /// filterMode: 'filter' /// }, /// { /// id: 'dataZoomY', /// type: 'slider', /// yAxisIndex: [0], /// filterMode: 'empty' /// } /// ], /// xAxis: {type: 'value'}, /// yAxis: {type: 'value'}, /// series{ /// type: 'bar', /// data: [ /// // 第一列对应 X 轴,第二列对应 Y 轴。 /// [12, 24, 36], /// [90, 80, 70], /// [3, 9, 27], /// [1, 11, 111] /// ] /// } /// } /// /// 上例中,dataZoomX 的 filterMode 设置为 'filter'。于是,假设当用户拖拽 dataZoomX(不去动 dataZoomY)导致其 valueWindow 变为 [2, 50] 时,dataZoomX 对 series.data 的第一列进行遍历,窗口外的整项去掉,最终得到的 series.data 为: /// /// [ /// // 第一列对应 X 轴,第二列对应 Y 轴。 /// [12, 24, 36], /// // [90, 80, 70] 整项被过滤掉,因为 90 在 dataWindow 之外。 /// [3, 9, 27] /// // [1, 11, 111] 整项被过滤掉,因为 1 在 dataWindow 之外。 /// ] /// /// 过滤前,series.data 中对应 Y 轴的值有 24、80、9、11,过滤后,只剩下 24 和 9,那么 Y 轴的显示范围就会自动改变以适应剩下的这两个值的显示(如果 Y 轴没有被设置 min、max 固定其显示范围的话)。 /// 所以,filterMode: 'filter' 的效果是:过滤数据后使另外的轴也能自动适应当前数据的范围。 /// 再从头来,上例中 dataZoomY 的 filterMode 设置为 'empty'。于是,假设当用户拖拽 dataZoomY(不去动 dataZoomX)导致其 dataWindow 变为 [10, 60] 时,dataZoomY 对 series.data 的第二列进行遍历,窗口外的值被设置为 empty (即替换为 NaN,这样设置为空的项,其所对应柱形,在 X 轴还有占位,只是不显示出来)。最终得到的 series.data 为: /// [ /// // 第一列对应 X 轴,第二列对应 Y 轴。 /// [12, 24, 36], /// [90, NaN, 70], // 设置为 empty (NaN) /// [3, NaN, 27], // 设置为 empty (NaN) /// [1, 11, 111] /// ] /// 这时,series.data 中对应于 X 轴的值仍然全部保留不受影响,为 12、90、3、1。那么用户对 dataZoomY 的拖拽操作不会影响到 X 轴的范围。这样的效果,对于离群点(outlier)过滤功能,比较清晰。 /// /// 如下面的例子: /// /// http://echarts.baidu.com/gallery/editor.html?c=doc-example/bar-dataZoom-filterMode public enum FilterMode: String, Jsonable{ case filter = "filter" case empty = "empty" public var jsonString: String { return self.rawValue.jsonString } }
mit
ba1c521ffc48c34809a553f33c14321b
30.582192
226
0.563869
2.929479
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEchartsTest_iOS/PairSpec.swift
1
1410
// // PairSpec.swift // SwiftyEcharts // // Created by Pluto Y on 15/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // import Quick import Nimble import SwiftyEcharts class PairSpec: QuickSpec { override func spec() { describe("Testing for type named 'SECTwoElement'") { it(" needs to check constructor and jsonString ") { let errorJsonString = "null" let noArgElements = Pair<LengthValue>() expect(noArgElements.jsonString).to(equal(errorJsonString)) let percentValue: Float = 3 let floatValue: Float = 2.1 let twoElements: Pair<LengthValue> = [floatValue, percentValue%] expect(twoElements.jsonString).to(equal([floatValue, percentValue%].jsonString)) let toMuchElements: Pair<LengthValue> = [3, 4, 5, 6%] expect(toMuchElements.jsonString).to(equal(errorJsonString)) let errorElements = Pair([floatValue]) expect(errorElements.jsonString).to(equal(errorJsonString)) // 如果不是 LengthValue 的话,就会产生编译错误 // let errorType: Pair = ["hello", 4] } } } }
mit
13d5e6afe489f00965a5751d969cb2c0
29.644444
96
0.526468
4.907473
false
false
false
false
xiawuacha/DouYuzhibo
DouYuzhibo/DouYuzhibo/Classses/Home/Views/CollectionNormalCell.swift
1
1453
// // CollectionNormalCell.swift // DouYuzhibo // // Created by 汪凯 on 2016/11/2. // Copyright © 2016年 汪凯. All rights reserved. // import UIKit import Kingfisher class CollectionNormalCell: UICollectionViewCell { //:MARK 属性 @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var anchorNameBtn: UIButton! @IBOutlet weak var image: UIImageView! @IBOutlet weak var countBtn: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } // MARK:- 定义模型属性 var anchor : AnchorModel? { didSet { // 0.校验模型是否有值 guard let anchor = anchor else { return } // 2.房间名称 titleLabel.text = anchor.room_name anchorNameBtn.setTitle(anchor.nickname, for: .normal) // 1.取出在线人数显示的文字 var onlineStr : String = "" if anchor.online >= 10000 { onlineStr = "\(Int(anchor.online) / 10000)万" } else { onlineStr = "\(anchor.online)在线" } countBtn.setTitle(onlineStr, for: UIControlState()) // 3.设置封面图片 guard let iconURL = URL(string: anchor.vertical_src) else { return } image.kf.setImage(with: iconURL) } } }
mit
b66f6f68ecb49d0e3996f3b937f6d1fc
24.698113
80
0.542584
4.648464
false
false
false
false
AndrewBennet/readinglist
ReadingList/ViewControllers/Edit/EditBookMetadata.swift
1
22056
import Foundation import Eureka import ImageRow import UIKit import CoreData import SVProgressHUD final class EditBookMetadata: FormViewController { private var editBookContext: NSManagedObjectContext! private var book: Book! private var isAddingNewBook: Bool! var isInNavigationFlow = false let googleBooksApi = GoogleBooksApi() private var shouldPrepopulateLastLanguageSelection: Bool { // We want to prepopulate the last selected language only if we are adding a new manual book: we don't want to // automatically alter the metadata of a Google Search result, or set the language of a book being edited which // happens to not have a language set. return GeneralSettings.prepopulateLastLanguageSelection && isAddingNewBook && book.googleBooksId == nil } convenience init(bookToEditID: NSManagedObjectID) { self.init() self.isAddingNewBook = false self.editBookContext = PersistentStoreManager.container.viewContext.childContext() self.book = (editBookContext.object(with: bookToEditID) as! Book) } convenience init(bookToCreateReadState: BookReadState) { self.init() self.editBookContext = PersistentStoreManager.container.viewContext.childContext() self.book = Book(context: editBookContext) self.book.manualBookId = UUID().uuidString self.book.setDefaultReadDates(for: bookToCreateReadState) self.isAddingNewBook = true } convenience init(bookToCreate: Book, scratchpadContext: NSManagedObjectContext) { self.init() self.isAddingNewBook = true self.editBookContext = scratchpadContext self.book = bookToCreate // If we are editing the metadata of a book we have already created in a temporary context, we must be // within a navigation flow. Remember this, so we don't set the left bar button to be a Cancel button self.isInNavigationFlow = true } override func viewDidLoad() { //swiftlint:disable:this cyclomatic_complexity super.viewDidLoad() configureNavigationItem() // Watch the book object for changes and validate the form NotificationCenter.default.addObserver(self, selector: #selector(validateBook), name: .NSManagedObjectContextObjectsDidChange, object: editBookContext) // Prepopulate last selected language, if appropriate to do so. Do this before the configuration of the form so that the form is accurate if shouldPrepopulateLastLanguageSelection { book.language = LightweightDataStore.lastSelectedLanguage } // General approach regarding capturing references to `self`: // initialization functions are run once, not stored, so we don't need to capture self weakly. // Stored closures, such as onChange, cellUpdate, etc, should capture `self` weakly to avoid a reference cycle // causing a memory leak. We use `weak self` references rather than `unowned self` references, in case there are some // specific timing issues whereby the closure runs after the view controller is deallocated (though unlikely). form +++ Section(header: "Title", footer: "") <<< TextRow { $0.cell.textField.autocapitalizationType = .words $0.placeholder = "Title" $0.value = self.book.title $0.onChange { [weak self] cell in guard let `self` = self else { return } if let cellValue = cell.value { self.book.title = cellValue } else { self.book.setValue(nil, forKey: #keyPath(Book.title)) } } } +++ AuthorSection(book: book, navigationController: navigationController!) +++ Section(header: "Additional Information", footer: "Note: if provided, ISBN-13 must be a valid, 13 digit ISBN.") <<< TextRow { $0.cell.textField.autocapitalizationType = .words $0.title = "Subtitle" $0.value = book.subtitle $0.onChange { [weak self] cell in guard let `self` = self else { return } self.book.subtitle = cell.value } } <<< Int32Row { $0.title = "Page Count" $0.value = book.pageCount $0.onChange { [weak self] cell in guard let `self` = self else { return } guard let pageCount = cell.value, pageCount >= 0 else { self.book.pageCount = nil return } self.book.pageCount = pageCount } } <<< PickerInlineRow<LanguageSelection> { $0.title = "Language" $0.value = { if let language = self.book.language { return .some(language) } else { return .blank } }() $0.options = [.blank] + LanguageIso639_1.allCases.map { .some($0) } $0.onChange { [weak self] cell in guard let `self` = self else { return } if let selection = cell.value, case let .some(language) = selection { self.book.language = language } else { self.book.language = nil } } } <<< DateInlineRow { $0.title = "Publication Date" $0.value = book.publicationDate $0.onChange { [weak self] cell in guard let `self` = self else { return } self.book.publicationDate = cell.value } } <<< TextRow { $0.cell.textField.autocapitalizationType = .words $0.title = "Publisher" $0.value = book.publisher $0.onChange { [weak self] cell in guard let `self` = self else { return } self.book.publisher = cell.value } } <<< ButtonRow { $0.title = "Subjects" $0.cellStyle = .value1 $0.cellUpdate { [weak self] cell, _ in guard let `self` = self else { return } cell.textLabel!.textAlignment = .left cell.textLabel!.textColor = .label cell.accessoryType = .disclosureIndicator cell.detailTextLabel?.text = self.book.subjects.map { $0.name }.sorted().joined(separator: ", ") } $0.onCellSelection { [weak self] _, row in guard let `self` = self else { return } self.navigationController!.pushViewController(EditBookSubjectsForm(book: self.book, sender: row), animated: true) } } <<< ImageRow { $0.title = "Cover Image" $0.cell.height = { 100 } $0.sourceTypes = [.Camera, .PhotoLibrary] $0.value = UIImage(optionalData: self.book.coverImage) $0.onChange { [weak self] cell in guard let `self` = self else { return } self.book.coverImage = cell.value?.jpegData(compressionQuality: 0.7) } } <<< Int64Row { $0.title = "ISBN-13" $0.value = book.isbn13 $0.formatter = nil $0.onChange { [weak self] cell in guard let `self` = self else { return } self.book.isbn13 = cell.value } } +++ Section(header: "Description", footer: "") <<< TextAreaRow { $0.placeholder = "Description" $0.value = book.bookDescription $0.onChange { [weak self] cell in guard let `self` = self else { return } self.book.bookDescription = cell.value } $0.cellSetup { [weak self] cell, _ in guard let `self` = self else { return } cell.height = { [weak self] in // Just return some default value if self has been deallocated by the time this block is called guard let `self` = self else { return 100 } return (self.view.frame.height / 3) - 10 } } } // Update and delete buttons +++ Section() <<< ButtonRow { $0.title = "Update from Google Books" $0.hidden = Condition(booleanLiteral: isAddingNewBook || book.isbn13 == nil) $0.onCellSelection { [weak self] cell, row in guard let `self` = self else { return } self.updateFromGooglePressed(cell: cell, row: row) } } <<< ButtonRow { $0.title = "Delete" $0.cellSetup { cell, _ in cell.tintColor = .systemRed } $0.onCellSelection { [weak self] cell, _ in guard let `self` = self else { return } self.deletePressed(sender: cell) } $0.hidden = Condition(booleanLiteral: isAddingNewBook) } #if DEBUG form +++ Section("Debug") <<< Int32Row { $0.title = "Sort" $0.value = book.sort $0.onChange { [weak self] cell in guard let `self` = self else { return } self.book.sort = cell.value ?? 0 } } <<< LabelRow { $0.title = "Core Data ID" $0.value = book.objectID.uriRepresentation().absoluteString } <<< LabelRow { $0.title = "Manual Book ID" $0.value = book.manualBookId } <<< TextRow { $0.title = "Google Books ID" $0.value = book.googleBooksId $0.onChange { [weak self] cell in guard let `self` = self else { return } self.book.googleBooksId = cell.value } } #endif // Validate on start validateBook() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Prevent the default behaviour of allowing a swipe-down to dismiss the modal presentation. This would // not give a confirmation alert before discarding a user's unsaved changes. By handling the dismiss event // ourselves we can present a confirmation dialog. isModalInPresentation = true navigationController?.presentationController?.delegate = self } func configureNavigationItem() { if !isInNavigationFlow { navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(userDidCancel)) } if isAddingNewBook { navigationItem.title = "Add Book" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(presentEditReadingState)) } else { navigationItem.title = "Edit Book" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed)) } } func deletePressed(sender deleteCell: UITableViewCell) { guard !isAddingNewBook else { return } let confirmDeleteAlert = UIAlertController(title: "Confirm deletion", message: nil, preferredStyle: .actionSheet) confirmDeleteAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) confirmDeleteAlert.addAction(UIAlertAction(title: "Delete", style: .destructive) { _ in // Delete the book, log the event, and dismiss this modal view self.editBookContext.performAndSave { self.book.delete() } UserEngagement.logEvent(.deleteBook) self.dismiss(animated: true) }) confirmDeleteAlert.popoverPresentationController?.setSourceCell(deleteCell, inTableView: tableView) self.present(confirmDeleteAlert, animated: true, completion: nil) } private func confirmUpdateAlert(updateHandler: ((UIAlertAction) -> Void)?) -> UIAlertController { let areYouSure = UIAlertController(title: "Confirm Update", message: "Updating from Google Books will overwrite any book metadata changes you have made manually. Are you sure you wish to proceed?", preferredStyle: .alert) areYouSure.addAction(UIAlertAction(title: "Update", style: .default, handler: updateHandler)) areYouSure.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) return areYouSure } func updateFromGooglePressed(cell: ButtonCellOf<String>, row: _ButtonRowOf<String>) { if self.book.googleBooksId != nil { present(confirmUpdateAlert(updateHandler: updateBookFromGoogleHandler(_:)), animated: true) } else if let isbn = book.isbn13 { SVProgressHUD.show(withStatus: "Searching...") UserEngagement.logEvent(.searchForExistingBookByIsbn) googleBooksApi.fetch(isbn: isbn.string) .always(on: .main) { SVProgressHUD.dismiss() } .catch(on: .main) { switch $0 { case GoogleBooksApi.ResponseError.noResult: SVProgressHUD.showInfo(withStatus: "No results found online") default: SVProgressHUD.showError(withStatus: "An error occurred searching online") } } .then(on: .main) { [weak self] fetchResult in guard let `self` = self else { return } self.present(self.confirmUpdateAlert { _ in self.updateBookFromGoogle(fetchResult: fetchResult) }, animated: true) } } } func updateBookFromGoogleHandler(_: UIAlertAction) { guard let googleBooksId = book.googleBooksId else { return } SVProgressHUD.show(withStatus: "Downloading...") UserEngagement.logEvent(.updateBookFromGoogle) googleBooksApi.fetch(googleBooksId: googleBooksId) .always(on: .main) { SVProgressHUD.dismiss() } .catch(on: .main) { _ in SVProgressHUD.showError(withStatus: "Could not update book details") } .then(on: .main, updateBookFromGoogle) } func updateBookFromGoogle(fetchResult: GoogleBooksApi.FetchResult) { book.populate(fromFetchResult: fetchResult) if book.isValidForUpdate() { editBookContext.saveIfChanged() dismiss(animated: true) { // FUTURE: Would be nice to display whether any changes were made SVProgressHUD.showInfo(withStatus: "Book updated") } } else { SVProgressHUD.showError(withStatus: "Could not update book details") } } @objc func validateBook() { navigationItem.rightBarButtonItem!.isEnabled = book.isValidForUpdate() } @objc func userDidCancel() { let noConfirmationNeeded: Bool if self.isAddingNewBook { let trivialChanges = [ #keyPath(Book.addedWhen), #keyPath(Book.manualBookId) ] noConfirmationNeeded = book.changedValues() .filter { !trivialChanges.contains($0.key) } .isEmpty } else { noConfirmationNeeded = book.changedValues().isEmpty } guard noConfirmationNeeded else { // Confirm exit dialog let confirmExit = UIAlertController(title: "Unsaved changes", message: "Are you sure you want to discard your unsaved changes?", preferredStyle: .actionSheet) confirmExit.addAction(UIAlertAction(title: "Discard", style: .destructive) { _ in self.dismiss(animated: true) }) confirmExit.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) if let popover = confirmExit.popoverPresentationController { guard let barButtonItem = navigationItem.leftBarButtonItem ?? navigationItem.rightBarButtonItem else { preconditionFailure("Missing navigation bar button item") } popover.barButtonItem = barButtonItem } present(confirmExit, animated: true, completion: nil) return } dismiss(animated: true, completion: nil) } @objc func donePressed() { guard book.isValidForUpdate() else { return } if book.changedValues().keys.contains(Book.Key.languageCode.rawValue) { LightweightDataStore.lastSelectedLanguage = book.language } editBookContext.saveIfChanged() dismiss(animated: true) { UserEngagement.onReviewTrigger() } } @objc func presentEditReadingState() { guard book.isValidForUpdate() else { return } UserEngagement.logEvent(.addManualBook) navigationController!.pushViewController(EditBookReadState(newUnsavedBook: book, scratchpadContext: editBookContext), animated: true) } } extension EditBookMetadata: UIAdaptivePresentationControllerDelegate { func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) { // If the user swipes down, we either dismiss or present a confirmation dialog userDidCancel() } } final class AuthorSection: MultivaluedSection { // This form is only presented by a metadata form, so does not need to maintain // a strong reference to the book's object context var book: Book! var isInitialising = true weak var navigationController: UINavigationController! required init(book: Book, navigationController: UINavigationController) { super.init(multivaluedOptions: [.Insert, .Delete, .Reorder], header: "Authors", footer: "Note: at least one author is required") { for author in book.authors { $0 <<< AuthorRow(author: author) } $0.addButtonProvider = { _ in ButtonRow { $0.title = "Add Author" $0.cellUpdate { cell, _ in cell.textLabel!.textAlignment = .left } } } } self.navigationController = navigationController self.multivaluedRowToInsertAt = { [unowned self] _ in let authorRow = AuthorRow() self.navigationController.pushViewController(AddAuthorForm(authorRow), animated: true) return authorRow } self.book = book isInitialising = false } required init() { super.init(multivaluedOptions: [], header: "", footer: "") { _ in } } required init(multivaluedOptions: MultivaluedOptions, header: String?, footer: String?, _ initializer: (GenericMultivaluedSection<ButtonRow>) -> Void) { super.init(multivaluedOptions: multivaluedOptions, header: header, footer: footer, initializer) } required init<S>(_ elements: S) where S: Sequence, S.Element == BaseRow { super.init(elements) } func rebuildAuthors() { // It's a bit tricky with Eureka to manage an ordered set: the reordering comes through rowsHaveBeenRemoved // and rowsHaveBeenAdded, so we can't delete books on removal, since they might need to come back. // Instead, we take the brute force approach of deleting all authors and rebuilding the set each time // something changes. We can check whether there are any meaningful differences before we embark on this though. let newAuthors: [(String, String?)] = self.compactMap { guard let authorRow = $0 as? AuthorRow else { return nil } guard let lastName = authorRow.lastName else { return nil } return (lastName, authorRow.firstNames) } if book.authors.map({ ($0.lastName, $0.firstNames) }).elementsEqual(newAuthors, by: { $0.0 == $1.0 && $0.1 == $1.1 }) { return } book.authors = newAuthors.map { Author(lastName: $0.0, firstNames: $0.1) } } override func rowsHaveBeenRemoved(_ rows: [BaseRow], at: IndexSet) { super.rowsHaveBeenRemoved(rows, at: at) guard !isInitialising else { return } rebuildAuthors() } override func rowsHaveBeenAdded(_ rows: [BaseRow], at: IndexSet) { super.rowsHaveBeenAdded(rows, at: at) guard !isInitialising else { return } rebuildAuthors() } } final class AuthorRow: _LabelRow, RowType { var lastName: String? var firstNames: String? convenience init(tag: String? = nil, author: Author? = nil) { self.init(tag: tag) lastName = author?.lastName firstNames = author?.firstNames reload() } required init(tag: String?) { super.init(tag: tag) cellStyle = .value1 cellUpdate { [unowned self] cell, _ in cell.textLabel!.textAlignment = .left cell.textLabel!.text = [self.firstNames, self.lastName].compactMap { $0 }.joined(separator: " ") } } }
gpl-3.0
33109cd3fe5fda2ce264268dc5264062
42.078125
229
0.57481
5.041371
false
false
false
false
yonekawa/SwiftFlux
SwiftFluxTests/StoreSpec.swift
1
2226
// // StoreSpec.swift // SwiftFlux // // Created by Kenichi Yonekawa on 8/2/15. // Copyright (c) 2015 mog2dev. All rights reserved. // import Quick import Nimble import Result import SwiftFlux class StoreSpec: QuickSpec { final class TestStore1: Store {} final class TestStore2: Store {} override func spec() { let store1 = TestStore1() let store2 = TestStore2() describe("emitChange") { var results = [String]() beforeEach { () in results = [] store1.subscribe { () in results.append("store1") } store2.subscribe { () in results.append("store2") } } afterEach { () in store1.unsubscribeAll() store2.unsubscribeAll() } it("should fire event correctly") { store1.emitChange() expect(results.count).to(equal(1)) expect(results).to(contain("store1")) store1.emitChange() expect(results.count).to(equal(2)) expect(results).to(contain("store1")) store2.emitChange() expect(results.count).to(equal(3)) expect(results).to(contain("store2")) } } describe("unsubscribe") { var results = [String]() var token = "" beforeEach { () in results = [] token = store1.subscribe { () in results.append("store1") } } afterEach { () in store1.unsubscribeAll() store2.unsubscribeAll() } it("should unsubscribe collectly") { store1.emitChange() expect(results.count).to(equal(1)) expect(results).to(contain("store1")) results = [] store1.unsubscribe(token) store1.emitChange() expect(results.count).to(equal(0)) expect(results).toNot(contain("store1")) } } } }
mit
d83856051c046f83994853406563e09b
25.188235
56
0.46451
4.797414
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/Comments/Controllers/CommentsViewControllerTests.swift
1
9736
@testable import Kickstarter_Framework @testable import KsApi import Library import Prelude import XCTest internal final class CommentsViewControllerTests: TestCase { override func setUp() { super.setUp() AppEnvironment.pushEnvironment(mainBundle: Bundle.framework) UIView.setAnimationsEnabled(false) } override func tearDown() { UIView.setAnimationsEnabled(true) super.tearDown() } func testView_WithFailedRemovedAndSuccessfulComments_ShouldDisplayAll_Success() { let mockService = MockService(fetchProjectCommentsEnvelopeResult: .success(CommentsEnvelope .failedRemovedSuccessfulCommentsTemplate)) combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in withEnvironment(apiService: mockService, currentUser: .template, language: language) { let controller = CommentsViewController.configuredWith(project: .template) let (parent, _) = traitControllers( device: device, orientation: .portrait, child: controller ) parent.view.frame.size.height = 1_100 self.scheduler.run() FBSnapshotVerifyView(parent.view, identifier: "Comments - lang_\(language)_device_\(device)") } } } func testView_WithSuccessFailedRetryingRetrySuccessComments_ShouldDisplayAll() { let mockService = MockService(fetchProjectCommentsEnvelopeResult: .success(CommentsEnvelope .successFailedRetryingRetrySuccessCommentsTemplate)) combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in withEnvironment(apiService: mockService, currentUser: .template, language: language) { let controller = CommentsViewController.configuredWith(project: Project.template) let (parent, _) = traitControllers( device: device, orientation: .portrait, child: controller ) parent.view.frame.size.height = 1_100 self.scheduler.run() FBSnapshotVerifyView(parent.view, identifier: "Comments - lang_\(language)_device_\(device)") } } } func testView_CurrentUser_LoggedOut() { let mockService = MockService(fetchProjectCommentsEnvelopeResult: .success(CommentsEnvelope.multipleCommentTemplate)) combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in withEnvironment(apiService: mockService, currentUser: nil, language: language) { let controller = CommentsViewController.configuredWith(project: .template) let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller) parent.view.frame.size.height = 1_100 self.scheduler.run() FBSnapshotVerifyView(parent.view, identifier: "Comments - lang_\(language)_device_\(device)") } } } func testView_CurrentUser_LoggedIn_IsBacking_True() { let mockService = MockService(fetchProjectCommentsEnvelopeResult: .success(CommentsEnvelope.multipleCommentTemplate)) let project = Project.template |> \.personalization.isBacking .~ true combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in withEnvironment(apiService: mockService, currentUser: .template, language: language) { let controller = CommentsViewController.configuredWith(project: project) let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller) parent.view.frame.size.height = 1_100 self.scheduler.run() FBSnapshotVerifyView(parent.view, identifier: "Comments - lang_\(language)_device_\(device)") } } } func testView_CurrentUser_LoggedIn_IsBacking_False() { let mockService = MockService(fetchProjectCommentsEnvelopeResult: .success(CommentsEnvelope.multipleCommentTemplate)) combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in withEnvironment(apiService: mockService, currentUser: .template, language: language) { let controller = CommentsViewController.configuredWith(project: .template) let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller) parent.view.frame.size.height = 1_100 self.scheduler.run() FBSnapshotVerifyView(parent.view, identifier: "Comments - lang_\(language)_device_\(device)") } } } func testView_CurrentUser_LoggedIn_PagingError() { let mockService = MockService(fetchProjectCommentsEnvelopeResult: .success(CommentsEnvelope.multipleCommentTemplate)) combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in withEnvironment(apiService: mockService, currentUser: .template, language: language) { let controller = CommentsViewController.configuredWith(project: .template) let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller) parent.view.frame.size.height = 600 self.scheduler.advance() withEnvironment(apiService: MockService(fetchProjectCommentsEnvelopeResult: .failure(.couldNotParseJSON))) { controller.viewModel.inputs.willDisplayRow(3, outOf: 4) self.scheduler.advance() FBSnapshotVerifyView(parent.view, identifier: "Comments - lang_\(language)_device_\(device)") } } } } func testView_CurrentUser_LoggedIn_IsBacking_CommentFlaggingEnabledFeatureFlag_True() { let mockOptimizelyClient = MockOptimizelyClient() |> \.features .~ [OptimizelyFeature.commentFlaggingEnabled.rawValue: true] let mockService = MockService(fetchProjectCommentsEnvelopeResult: .success(CommentsEnvelope.multipleCommentTemplate)) let project = Project.template |> \.personalization.isBacking .~ true combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in withEnvironment( apiService: mockService, currentUser: .template, language: language, optimizelyClient: mockOptimizelyClient ) { let controller = CommentsViewController.configuredWith(project: project) let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller) parent.view.frame.size.height = 1_100 self.scheduler.run() FBSnapshotVerifyView(parent.view, identifier: "Comments - lang_\(language)_device_\(device)") } } } func testView_CurrentUser_LoggedIn_IsBacking_CommentFlaggingEnabledFeatureFlag_False() { let mockOptimizelyClient = MockOptimizelyClient() |> \.features .~ [OptimizelyFeature.commentFlaggingEnabled.rawValue: false] let mockService = MockService(fetchProjectCommentsEnvelopeResult: .success(CommentsEnvelope.multipleCommentTemplate)) let project = Project.template |> \.personalization.isBacking .~ true combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in withEnvironment( apiService: mockService, currentUser: .template, language: language, optimizelyClient: mockOptimizelyClient ) { let controller = CommentsViewController.configuredWith(project: project) let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller) parent.view.frame.size.height = 1_100 self.scheduler.run() FBSnapshotVerifyView(parent.view, identifier: "Comments - lang_\(language)_device_\(device)") } } } func testView_NoComments_ShouldShowEmptyState() { AppEnvironment.pushEnvironment( apiService: MockService( fetchProjectCommentsEnvelopeResult: .success(CommentsEnvelope.emptyCommentsTemplate) ), currentUser: User.template, mainBundle: Bundle.framework ) combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in withEnvironment(currentUser: .template, language: language) { let controller = CommentsViewController.configuredWith(project: .template) let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller) parent.view.frame.size.height = 1_100 self.scheduler.run() FBSnapshotVerifyView(parent.view, identifier: "Comments - lang_\(language)_device_\(device)") } } } func testView_NoComments_ShouldShowErrorState() { AppEnvironment.pushEnvironment( apiService: MockService( fetchProjectCommentsEnvelopeResult: .failure(.couldNotParseJSON) ), currentUser: User.template, mainBundle: Bundle.framework ) combos(Language.allLanguages, [Device.phone4_7inch, Device.pad]).forEach { language, device in withEnvironment(currentUser: .template, language: language) { let controller = CommentsViewController.configuredWith(project: .template) let (parent, _) = traitControllers(device: device, orientation: .portrait, child: controller) self.scheduler.run() FBSnapshotVerifyView(parent.view, identifier: "Comments - lang_\(language)_device_\(device)") } } } func testCommentsViewControllerCreation_Success() { let mockOptimizelyClient = MockOptimizelyClient() let mockService = MockService(fetchProjectResult: .success(.template)) withEnvironment( apiService: mockService, optimizelyClient: mockOptimizelyClient ) { XCTAssert(commentsViewController(for: .template).isKind(of: CommentsViewController.self)) } } }
apache-2.0
c6f5430b1dca79469817e0928dac45ca
35.739623
116
0.706861
4.836562
false
true
false
false
nathawes/swift
test/Parse/c_function_pointers.swift
23
2659
// RUN: %target-swift-frontend -typecheck -verify -module-name main %s func global() -> Int { return 0 } struct S { static func staticMethod() -> Int { return 0 } } class C { static func staticMethod() -> Int { return 0 } class func classMethod() -> Int { return 0 } } if true { func local() -> Int { return 0 } let a: @convention(c) () -> Int = global let _: @convention(c) () -> Int = main.global let _: @convention(c) () -> Int = { 0 } let _: @convention(c) () -> Int = local // Can't convert a closure value to a C function pointer let global2 = global let _: @convention(c) () -> Int = global2 // expected-error{{can only be formed from a reference to a 'func' or a literal closure}} let globalBlock: @convention(block) () -> Int = global let _: @convention(c) () -> Int = globalBlock // expected-error{{can only be formed from a reference to a 'func' or a literal closure}} // Can convert a function pointer to a block or closure, or assign to another // C function pointer let _: @convention(c) () -> Int = a let _: @convention(block) () -> Int = a let _: () -> Int = a // Can't convert a C function pointer from a method. // TODO: Could handle static methods. let _: @convention(c) () -> Int = S.staticMethod // expected-error{{}} let _: @convention(c) () -> Int = C.staticMethod // expected-error{{}} let _: @convention(c) () -> Int = C.classMethod // expected-error{{}} // <rdar://problem/22181714> Crash when typing "signal" let iuo_global: (() -> Int)! = global let _: (@convention(c) () -> Int)! = iuo_global // expected-error{{a C function pointer can only be formed from a reference to a 'func' or a literal closure}} func handler(_ callback: (@convention(c) () -> Int)!) {} handler(iuo_global) // expected-error{{a C function pointer can only be formed from a reference to a 'func' or a literal closure}} } func genericFunc<T>(_ t: T) -> T { return t } let f: @convention(c) (Int) -> Int = genericFunc // expected-error{{cannot be formed from a reference to a generic function}} func ct1() -> () { print("") } let ct1ref0 : @convention(c, cType: "void (*)(void)") () -> () = ct1 let ct1ref1 : @convention(c, cType: "void (*)(void)") = ct1 // expected-error{{expected type}} let ct1ref2 : @convention(c, ) () -> () = ct1 // expected-error{{expected 'cType' label in 'convention' attribute}} let ct1ref3 : @convention(c, cType) () -> () = ct1 // expected-error{{expected ':' after 'cType' for 'convention' attribute}} let ct1ref4 : @convention(c, cType: ) () -> () = ct1 // expected-error{{expected string literal containing clang type for 'cType' in 'convention' attribute}}
apache-2.0
0aa292eb5bb411119e47969b72a49ce6
45.649123
160
0.636706
3.545333
false
false
false
false
crazypoo/PTools
Pods/LXFProtocolTool/LXFProtocolTool/Classes/LXFEmptyDataSetable/LXFEmptyDataSetable.swift
1
5043
// // LXFEmptyDataSetable.swift // LXFProtocolTool // // Created by 林洵锋 on 2018/4/6. // Copyright © 2018年 CocoaPods. All rights reserved. // import UIKit import DZNEmptyDataSet public typealias LXFTapEmptyBlock = ((UIView)->()) public enum LXFEmptyDataSetAttributeKeyType { /// 纵向偏移(-50) CGFloat case verticalOffset /// 提示语(暂无数据) String case tipStr /// 提示语的font(system15) UIFont case tipFont /// 提示语颜色(D2D2D2) UIColor case tipColor /// 提示图(LXFEmptyDataPic) UIImage case tipImage /// 允许滚动(true) Bool case allowScroll } extension UIScrollView { private struct AssociatedKeys { static var lxf_emptyAttributeDictKey = "lxf_emptyAttributeDictKey" static var lxf_emptyTapBlockKey = "lxf_emptyTapBlockKey" } // 专门存放闭包属性 private class BlockContainer: NSObject, NSCopying { func copy(with zone: NSZone? = nil) -> Any { return self } var rearrange_lxf_emptyTapBlock : LXFTapEmptyBlock? } /// 属性字典 var lxf_emptyAttributeDict: [LXFEmptyDataSetAttributeKeyType : Any]? { get { return objc_getAssociatedObject(self, &AssociatedKeys.lxf_emptyAttributeDictKey) as? [LXFEmptyDataSetAttributeKeyType : Any] } set { objc_setAssociatedObject(self, &AssociatedKeys.lxf_emptyAttributeDictKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var lxf_emptyTapBlock : LXFTapEmptyBlock? { get { return objc_getAssociatedObject(self, &AssociatedKeys.lxf_emptyTapBlockKey) as? LXFTapEmptyBlock } set { objc_setAssociatedObject(self, &AssociatedKeys.lxf_emptyTapBlockKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) } } } // MARK:- 空视图占位协议 public protocol LXFEmptyDataSetable { } // MARK:- UIViewController - 空视图占位协议 public extension LXFEmptyDataSetable where Self : NSObject { // MARK: 初始化数据 func lxf_EmptyDataSet(_ scrollView: UIScrollView, attributeBlock: (()->([LXFEmptyDataSetAttributeKeyType : Any]))? = nil) { scrollView.lxf_emptyAttributeDict = attributeBlock != nil ? attributeBlock!() : nil scrollView.emptyDataSetDelegate = self scrollView.emptyDataSetSource = self } // MARK:- 更新数据 func lxf_updateEmptyDataSet(_ scrollView: UIScrollView, attributeBlock: (()->([LXFEmptyDataSetAttributeKeyType : Any]))) { let dict = attributeBlock() if scrollView.lxf_emptyAttributeDict == nil { scrollView.lxf_emptyAttributeDict = dict } else { for key in dict.keys { scrollView.lxf_emptyAttributeDict![key] = dict[key] } } scrollView.reloadEmptyDataSet() } // MARK: 点击回调 func lxf_tapEmptyView(_ scrollView: UIScrollView, block: @escaping LXFTapEmptyBlock) { scrollView.lxf_emptyTapBlock = block } } extension NSObject : DZNEmptyDataSetDelegate, DZNEmptyDataSetSource { public func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! { guard let tipImg = scrollView.lxf_emptyAttributeDict?[.tipImage] as? UIImage else { return UIImage(named: "LXFEmptyDataPic") } return tipImg } public func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { let defaultColor = UIColor(red: 210/255, green: 210/255, blue: 210/255, alpha: 1.0) // 0xD2D2D2 let tipText = (scrollView.lxf_emptyAttributeDict?[.tipStr] as? String) ?? "暂无数据" let tipFont = (scrollView.lxf_emptyAttributeDict?[.tipFont] as? UIFont) ?? UIFont.systemFont(ofSize: 15) let tipColor = (scrollView.lxf_emptyAttributeDict?[.tipColor] as? UIColor) ?? defaultColor let attrStr = NSAttributedString(string: tipText, attributes: [ NSAttributedStringKey.font:tipFont, NSAttributedStringKey.foregroundColor:tipColor ]) return attrStr } public func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat { guard let offset = scrollView.lxf_emptyAttributeDict?[.verticalOffset] as? NSNumber else { return -50 } return CGFloat(truncating: offset) } public func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool { return (scrollView.lxf_emptyAttributeDict?[.allowScroll] as? Bool) ?? true } public func emptyDataSet(_ scrollView: UIScrollView!, didTap view: UIView!) { if scrollView.lxf_emptyTapBlock != nil { scrollView.lxf_emptyTapBlock!(view) } } public func emptyDataSet(_ scrollView: UIScrollView!, didTap button: UIButton!) { if scrollView.lxf_emptyTapBlock != nil { scrollView.lxf_emptyTapBlock!(button) } } }
mit
ace0e04be94430748ce621de0ecdb740
34.722628
153
0.659992
4.30431
false
false
false
false
eljeff/AudioKit
Sources/AudioKit/Nodes/Generators/Physical Models/Shaker.swift
1
3771
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation import CAudioKit #if !os(tvOS) /// Type of shaker to use public enum ShakerType: MIDIByte { /// Maraca case maraca = 0 /// Cabasa case cabasa = 1 /// Sekere case sekere = 2 /// Tambourine case tambourine = 3 /// Sleigh Bells case sleighBells = 4 /// Bamboo Chimes case bambooChimes = 5 /// Using sand paper case sandPaper = 6 /// Soda Can case sodaCan = 7 /// Sticks falling case sticks = 8 /// Crunching sound case crunch = 9 /// Big rocks hitting each other case bigRocks = 10 /// Little rocks hitting each other case littleRocks = 11 /// NeXT Mug case nextMug = 12 /// A penny rattling around a mug case pennyInMug = 13 /// A nickle rattling around a mug case nickleInMug = 14 /// A dime rattling around a mug case dimeInMug = 15 /// A quarter rattling around a mug case quarterInMug = 16 /// A Franc rattling around a mug case francInMug = 17 /// A Peso rattling around a mug case pesoInMug = 18 /// Guiro case guiro = 19 /// Wrench case wrench = 20 /// Water Droplets case waterDrops = 21 /// Tuned Bamboo Chimes case tunedBambooChimes = 22 } /// STK Shaker /// public class Shaker: Node, AudioUnitContainer, Tappable, Toggleable { /// Four letter unique description "shak" public static let ComponentDescription = AudioComponentDescription(instrument: "shak") /// Internal type of audio unit for this node public typealias AudioUnitType = InternalAU /// Internal audio unit public private(set) var internalAU: AudioUnitType? // MARK: - Parameters /// Tells whether the node is processing (ie. started, playing, or active) open var isStarted: Bool { return internalAU?.isStarted ?? false } // MARK: - Internal Audio Unit /// Internal audio unti for shaker public class InternalAU: AudioUnitBase { /// Create shaker DSP /// - Returns: DSP Reference public override func createDSP() -> DSPRef { return akCreateDSP("ShakerDSP") } /// Trigger the shaker /// - Parameters: /// - type: Type of shaker to create /// - amplitude: How hard to shake or velocity public func trigger(type: AUValue, amplitude: AUValue) { if let midiBlock = scheduleMIDIEventBlock { let event = MIDIEvent(noteOn: MIDINoteNumber(type), velocity: MIDIVelocity(amplitude * 127.0), channel: 0) event.data.withUnsafeBufferPointer { ptr in guard let ptr = ptr.baseAddress else { return } midiBlock(AUEventSampleTimeImmediate, 0, event.data.count, ptr) } } } } // MARK: - Initialization /// Initialize the STK Shaker model public init() { super.init(avAudioNode: AVAudioNode()) instantiateAudioUnit { avAudioUnit in self.avAudioUnit = avAudioUnit self.avAudioNode = avAudioUnit self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType } } /// Trigger the sound with an optional set of parameters /// /// - Parameters: /// - type: various shaker types are supported /// - amplitude: how hard to shake public func trigger(type: ShakerType, amplitude: Double = 0.5) { internalAU?.start() internalAU?.trigger(type: AUValue(type.rawValue), amplitude: AUValue(amplitude)) } } #endif
mit
bce58c71ef5ca2bae3f01bd44c1ef743
23.487013
100
0.602493
4.452184
false
false
false
false
lukejmann/FBLA2017
Pods/Hero/Sources/DefaultAnimationPreprocessor.swift
1
12038
// 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. import UIKit public enum HeroDefaultAnimationType { public enum Direction: HeroStringConvertible { case left, right, up, down public static func from(node: ExprNode) -> Direction? { switch node.name { case "left": return .left case "right": return .right case "up": return .up case "down": return .down default: return nil } } } case auto case push(direction: Direction) case pull(direction: Direction) case cover(direction: Direction) case uncover(direction: Direction) case slide(direction: Direction) case zoomSlide(direction: Direction) case pageIn(direction: Direction) case pageOut(direction: Direction) case fade case zoom case zoomOut indirect case selectBy(presenting: HeroDefaultAnimationType, dismissing: HeroDefaultAnimationType) case none public var label: String? { let mirror = Mirror(reflecting: self) if let associated = mirror.children.first { let valuesMirror = Mirror(reflecting: associated.value) if !valuesMirror.children.isEmpty { let parameters = valuesMirror.children.map { ".\($0.value)" }.joined(separator: ",") return ".\(associated.label ?? "")(\(parameters))" } return ".\(associated.label ?? "")(.\(associated.value))" } return ".\(self)" } } extension HeroDefaultAnimationType: HeroStringConvertible { public static func from(node: ExprNode) -> HeroDefaultAnimationType? { let name: String = node.name let parameters: [ExprNode] = (node as? CallNode)?.arguments ?? [] switch name { case "auto": return .auto case "push": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .push(direction: direction) } case "pull": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .pull(direction: direction) } case "cover": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .cover(direction: direction) } case "uncover": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .uncover(direction: direction) } case "slide": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .slide(direction: direction) } case "zoomSlide": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .zoomSlide(direction: direction) } case "pageIn": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .pageIn(direction: direction) } case "pageOut": if let node = parameters.get(0), let direction = Direction.from(node: node) { return .pageOut(direction: direction) } case "fade": return .fade case "zoom": return .zoom case "zoomOut": return .zoomOut case "selectBy": if let presentingNode = parameters.get(0), let presenting = HeroDefaultAnimationType.from(node: presentingNode), let dismissingNode = parameters.get(0), let dismissing = HeroDefaultAnimationType.from(node: dismissingNode) { return .selectBy(presenting: presenting, dismissing: dismissing) } case "none": return .none default: break } return nil } } class DefaultAnimationPreprocessor: BasePreprocessor { weak var hero: Hero? init(hero: Hero) { self.hero = hero } func shift(direction: HeroDefaultAnimationType.Direction, appearing: Bool, size: CGSize? = nil, transpose: Bool = false) -> CGPoint { let size = size ?? context.container.bounds.size let rtn: CGPoint switch direction { case .left, .right: rtn = CGPoint(x: (direction == .right) == appearing ? -size.width : size.width, y: 0) case .up, .down: rtn = CGPoint(x: 0, y: (direction == .down) == appearing ? -size.height : size.height) } if transpose { return CGPoint(x: rtn.y, y: rtn.x) } return rtn } override func process(fromViews: [UIView], toViews: [UIView]) { guard let hero = hero else { return } var defaultAnimation = hero.defaultAnimation let inNavigationController = hero.inNavigationController let inTabBarController = hero.inTabBarController let toViewController = hero.toViewController let fromViewController = hero.fromViewController let presenting = hero.presenting let fromOverFullScreen = hero.fromOverFullScreen let toOverFullScreen = hero.toOverFullScreen let toView = hero.toView let fromView = hero.fromView let animators = hero.animators if case .auto = defaultAnimation { if inNavigationController, let navAnim = toViewController?.navigationController?.heroNavigationAnimationType { defaultAnimation = navAnim } else if inTabBarController, let tabAnim = toViewController?.tabBarController?.heroTabBarAnimationType { defaultAnimation = tabAnim } else if let modalAnim = (presenting ? toViewController : fromViewController)?.heroModalAnimationType { defaultAnimation = modalAnim } } if case .selectBy(let presentAnim, let dismissAnim) = defaultAnimation { defaultAnimation = presenting ? presentAnim : dismissAnim } if case .auto = defaultAnimation { if animators!.contains(where: { $0.canAnimate(view: toView, appearing: true) || $0.canAnimate(view: fromView, appearing: false) }) { defaultAnimation = .none } else if inNavigationController { defaultAnimation = presenting ? .push(direction:.left) : .pull(direction:.right) } else if inTabBarController { defaultAnimation = presenting ? .slide(direction:.left) : .slide(direction:.right) } else { defaultAnimation = .fade } } if case .none = defaultAnimation { return } context[fromView] = [.timingFunction(.standard), .duration(0.35)] context[toView] = [.timingFunction(.standard), .duration(0.35)] let shadowState: [HeroModifier] = [.shadowOpacity(0.5), .shadowColor(.black), .shadowRadius(5), .shadowOffset(.zero), .masksToBounds(false)] switch defaultAnimation { case .push(let direction): context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)), .shadowOpacity(0), .beginWith(modifiers: shadowState), .timingFunction(.deceleration)]) context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false) / 3), .overlay(color: .black, opacity: 0.1), .timingFunction(.deceleration)]) case .pull(let direction): hero.insertToViewFirst = true context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)), .shadowOpacity(0), .beginWith(modifiers: shadowState)]) context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true) / 3), .overlay(color: .black, opacity: 0.1)]) case .slide(let direction): context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false))]) context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true))]) case .zoomSlide(let direction): context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)), .scale(0.8)]) context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)), .scale(0.8)]) case .cover(let direction): context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)), .shadowOpacity(0), .beginWith(modifiers: shadowState), .timingFunction(.deceleration)]) context[fromView]!.append(contentsOf: [.overlay(color: .black, opacity: 0.1), .timingFunction(.deceleration)]) case .uncover(let direction): hero.insertToViewFirst = true context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)), .shadowOpacity(0), .beginWith(modifiers: shadowState)]) context[toView]!.append(contentsOf: [.overlay(color: .black, opacity: 0.1)]) case .pageIn(let direction): context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)), .shadowOpacity(0), .beginWith(modifiers: shadowState), .timingFunction(.deceleration)]) context[fromView]!.append(contentsOf: [.scale(0.7), .overlay(color: .black, opacity: 0.1), .timingFunction(.deceleration)]) case .pageOut(let direction): hero.insertToViewFirst = true context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)), .shadowOpacity(0), .beginWith(modifiers: shadowState)]) context[toView]!.append(contentsOf: [.scale(0.7), .overlay(color: .black, opacity: 0.1)]) case .fade: // TODO: clean up this. overFullScreen logic shouldn't be here if !(fromOverFullScreen && !presenting) { context[toView] = [.fade] } #if os(tvOS) context[fromView] = [.fade] #else if (!presenting && toOverFullScreen) || !fromView.isOpaque || (fromView.backgroundColor?.alphaComponent ?? 1) < 1 { context[fromView] = [.fade] } #endif context[toView]!.append(.durationMatchLongest) context[fromView]!.append(.durationMatchLongest) case .zoom: hero.insertToViewFirst = true context[fromView]!.append(contentsOf: [.scale(1.3), .fade]) context[toView]!.append(contentsOf: [.scale(0.7)]) case .zoomOut: context[toView]!.append(contentsOf: [.scale(1.3), .fade]) context[fromView]!.append(contentsOf: [.scale(0.7)]) default: fatalError("Not implemented") } } }
mit
9a1e9d5bac2db660a09e5a0040eaf889
42.615942
138
0.620535
4.69684
false
false
false
false
SwiftGFX/SwiftMath
Sources/Matrix3x3+simd.swift
1
2710
// Copyright 2016 Stuart Carnie. // License: https://github.com/SwiftGFX/SwiftMath#license-bsd-2-clause // #if !NOSIMD import simd /// Represents a standard 4x4 transformation matrix. /// - remark: /// Matrices are stored in column-major order @frozen public struct Matrix3x3f: Codable, Equatable { internal var d: matrix_float3x3 // MARK: - initializers /// Creates an instance initialized with either existing simd matrix or zeros public init(simdMatrix: matrix_float3x3 = .init()) { self.d = simdMatrix } /// Convenience initializer for type casting public init(_ simdMatrix: matrix_float3x3) { self.init(simdMatrix: simdMatrix) } /// Creates an instance using the vector to initialize the diagonal elements public init(diagonal v: Vector3f) { self.d = matrix_float3x3(diagonal: v.d) } /// Creates an instance with the specified columns /// /// - parameter c0: a vector representing column 0 /// - parameter c1: a vector representing column 1 /// - parameter c2: a vector representing column 2 public init(_ c0: Vector3f, _ c1: Vector3f, _ c2: Vector3f) { self.d = matrix_float3x3(columns: (c0.d, c1.d, c2.d)) } // MARK:- properties public var inversed: Matrix3x3f { return unsafeBitCast(d.inverse, to: Matrix3x3f.self) } public var transposed: Matrix3x3f { return unsafeBitCast(d.transpose, to: Matrix3x3f.self) } // MARK:- operators public static prefix func -(lhs: Matrix3x3f) -> Matrix3x3f { return unsafeBitCast(-lhs.d, to: Matrix3x3f.self) } public static func *(lhs: Matrix3x3f, rhs: Float) -> Matrix3x3f { return unsafeBitCast(lhs.d * rhs, to: Matrix3x3f.self) } public static func *(lhs: Matrix3x3f, rhs: Matrix3x3f) -> Matrix3x3f { return unsafeBitCast(lhs.d * rhs.d, to: Matrix3x3f.self) } public static func == (lhs: Matrix3x3f, rhs: Matrix3x3f) -> Bool { lhs.d == rhs.d } // MARK: - subscript operations /// Access the `col`th column vector public subscript(col: Int) -> Vector3f { get { return unsafeBitCast(d[col], to: Vector3f.self) } set { d[col] = newValue.d } } /// Access the `col`th column vector and then `row`th element public subscript(col: Int, row: Int) -> Float { get { return d[col, row] } set { d[col, row] = newValue } } } public extension matrix_float3x3 { init(_ mat3x3f: Matrix3x3f) { self = mat3x3f.d } } #endif
bsd-2-clause
4ff07ce651a0c694ecceabb6a080abca
26.373737
81
0.601476
3.598938
false
false
false
false
vhesener/Closures
Xcode/Closures/Source/UIImagePickerController.swift
2
15591
/** The MIT License (MIT) Copyright (c) 2017 Vincent Hesener Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import MobileCoreServices import PhotosUI @available(iOS 9.0, *) fileprivate final class ImagePickerControllerDelegate: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate, DelegateProtocol { static var delegates = Set<DelegateWrapper<UIImagePickerController, ImagePickerControllerDelegate>>() fileprivate var didFinishPickingMedia: ((_ withInfo: [UIImagePickerController.InfoKey: Any]) -> Void)? fileprivate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { didFinishPickingMedia?(info) } fileprivate var didCancel: (() -> Void)? fileprivate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { didCancel?() } override func responds(to aSelector: Selector!) -> Bool { switch aSelector { case #selector(ImagePickerControllerDelegate.imagePickerController(_:didFinishPickingMediaWithInfo:)): return didFinishPickingMedia != nil case #selector(ImagePickerControllerDelegate.imagePickerControllerDidCancel(_:)): return didCancel != nil default: return super.responds(to: aSelector) } } } @available(iOS 9.0, *) extension UIImagePickerController { // MARK: Convenient Presenting /** This is a convenience initializer that allows you to setup your UIImagePickerController with some commonly used default settings. In addition, it provides a default handler for a cancelled picker, but you are free to provide your own `didCancel` implementation using the `didCancel` parameter. The only required parameter is the `didPick` closure, which will be called when the user picks a medium. * important: The picker will not be attempted to be dismissed after this closure is called, unless you use the `present(from:animation:)` method. * * * * #### An example of initializing with this method: ```swift let picker = UIImagePickerController( source: .camera, allow: [.image, .movie]) { [weak self] result,picker in myImageView.image = result.originalImage self?.dismiss(animated: animation.animate) } } ``` * parameter source: The `UIImagePickerControllerSourceType` that UIImagePickerController expects to determine where the content should be obtained from. This value will be applied to the picker's `sourceType` property. * parameter allow: A convenience `OptionSet` filter based on `kUTType` Strings. These types will be applied to the picker's mediaTypes property. * parameter cameraOverlay: This is equivalent to `UIImagePickerController`'s `cameraOverlayView` property and will be applied as such. * parameter showsCameraControls: This is equivalent to `UIImagePickerController`'s `showsCameraControls` property and will be applied as such. * parameter didCancel: The closure that is called when the `didCancel` delegate method is called. The default is to attempt to dismiss the picker. * parameter didPick: The closure that is called when the imagePickerController(_:didFinishPickingMediaWithInfo:) is called. The closure conveniently wraps the Dictionary obtained from this delegate call in a `Result` struct. The original Dictionary can be found in the `rawInfo` property. */ public convenience init(source: UIImagePickerController.SourceType = .photoLibrary, allow: UIImagePickerController.MediaFilter = .image, cameraOverlay: UIView? = nil, showsCameraControls: Bool = true, didCancel: @escaping ( _ picker: UIImagePickerController) -> Void = dismissFromPresenting, didPick: @escaping (_ result: UIImagePickerController.Result, _ picker: UIImagePickerController) -> Void) { self.init() sourceType = source /** From UIImagePickerController docs: "You can access this property only when the source type of the image picker is set to camera. Attempting to access this property for other source types results in throwing an invalidArgumentException exception" */ if source == .camera { cameraOverlayView = cameraOverlay self.showsCameraControls = showsCameraControls } mediaTypes = UIImagePickerController.MediaFilter.allTypes.compactMap { allow.contains($0) ? $0.mediaType : nil } didFinishPickingMedia { [unowned self] in didPick(UIImagePickerController.Result(rawInfo: $0), self) } } public static func dismissFromPresenting(_ picker: UIImagePickerController) { picker.presentingViewController?.dismiss(animated: true) } /** A convenience method that will present the UIImagePickerController. It will also do the following as default behavior, which can be overriden at anytime: 1. Default the didCancel callback to dismiss the picker. 1. Call the didFinishPickingMedia handler if one was set previously, usually from the convenience initiaizer's `didPick` parameter or by calling the `didFinishPickingMedia(_:)` method. 1. Dismiss the picker after calling the `didFinishPickingMedia` handler. * * * * #### An example of calling this method using the convenience initializer: ```swift let picker = UIImagePickerController( source: .photoLibrary, allow: .image) { result,_ in myImageView.image = result.originalImage }.present(from: self) ``` * parameter viewController: The view controller that is able to present the picker. This view controller is also used to dismiss the picker for the default dismissing behavior. * parameter animation: An animation info tuple that describes whether to animate the presenting and what to do after the animation is complete. * returns: itself so you can daisy chain the other delegate calls */ @discardableResult public func present(from viewController: UIViewController, animation: (animate: Bool, onComplete: (() -> Void)?) = (true, nil)) -> Self { didCancel { [weak viewController] in viewController?.dismiss(animated: animation.animate) } update { [weak viewController] delegate in let finishedPickingCopy = delegate.didFinishPickingMedia delegate.didFinishPickingMedia = { finishedPickingCopy?($0) viewController?.dismiss(animated: animation.animate) } } viewController.present(self, animated: animation.animate, completion: animation.onComplete) return self } } @available(iOS 9.0, *) extension UIImagePickerController { // MARK: Delegate Overrides /** Equivalent to implementing UIImagePickerControllerDelegate's imagePickerController(_:didFinishPickingMediaWithInfo:) method * parameter handler: The closure that will be called in place of its equivalent delegate method * returns: itself so you can daisy chain the other delegate calls */ @discardableResult public func didFinishPickingMedia(handler: @escaping (_ withInfo: [UIImagePickerController.InfoKey: Any]) -> Void) -> Self { return update { $0.didFinishPickingMedia = handler } } /** Equivalent to implementing UIImagePickerControllerDelegate's imagePickerControllerDidCancel(_:) method * parameter handler: The closure that will be called in place of its equivalent delegate method * returns: itself so you can daisy chain the other delegate calls */ @discardableResult public func didCancel(handler: @escaping () -> Void) -> Self { return update { $0.didCancel = handler } } } @available(iOS 9.0, *) extension UIImagePickerController { // MARK: Helper Types /** A wrapper around `kUTType`. Eventually these will be replaced by Apple with a Swifty enum, but until then, this simply wraps these values in a strongly typed `OptionSet`. You can use these when deciding which media types you want the user to select from the `UIImagePickerController` using the `init(source:allow:cameraOverlay:showsCameraControls:didPick:)` initializer. Since it is an `OptionSet`, you can use array literal syntax to describe more than one media type. ```swift let picker = UIImagePickerController(allow: [.image, .movie]) {_,_ in // ... } ``` */ public struct MediaFilter: OptionSet { /// :nodoc: public let rawValue: Int /// :nodoc: public init(rawValue: Int) { self.rawValue = rawValue } /** Tells the UIImagePickerController to allow images to be seleced. */ public static let image: MediaFilter = 1 /** Tells the UIImagePickerController to allow movies to be seleced. */ public static let movie: MediaFilter = 2 /** Tells the UIImagePickerController to allow all explicitly supported `MediaFilter` types to be seleced. */ public static let all: MediaFilter = [.image, .movie] fileprivate static let allTypes: [MediaFilter] = [.image, .movie] fileprivate var mediaType: String { switch self { case .image: return kUTTypeImage as String case .movie: return kUTTypeMovie as String default: return kUTTypeImage as String } } } /** This result object is a only a wrapper around the loosely typed Dictionary returned from `UIImagePickerController`'s `-imagePickerController:didFinishPickingMediaWithInfo:` delegate method. When using the `init(source:allow:cameraOverlay:showsCameraControls:didPick:)` initializer, the `didPick` closure passes this convenience struct. If the original Dictionary is needed, it can be found in the `rawInfo` property. */ public struct Result { /** The original Dictionary received from UIPickerController's `-imagePickerController:didFinishPickingMediaWithInfo:` delegate method. */ public let rawInfo: [UIImagePickerController.InfoKey: Any] /** The type of media picked by the user, converted to a MediaFilter option. This is equivalent to the `UIImagePickerControllerOriginalImage` key value from `rawInfo`. */ public let type: MediaFilter /** The original UIImage that the user selected from their source. This is equivalent to the `UIImagePickerControllerOriginalImage` key value from `rawInfo`. */ public let originalImage: UIImage? /** The edited image after any croping, resizing, etc has occurred. This is equivalent to the `UIImagePickerControllerEditedImage` key value from `rawInfo`. */ public let editedImage: UIImage? /** This is equivalent to the `UIImagePickerControllerCropRect` key value from `rawInfo`. */ public let cropRect: CGRect? /** The fileUrl of the movie that was picked. This is equivalent to the `UIImagePickerControllerMediaURL` key value from `rawInfo`. */ public let movieUrl: URL? /** This is equivalent to the `UIImagePickerControllerMediaMetadata` key value from `rawInfo`. */ public let metaData: NSDictionary? init(rawInfo: [UIImagePickerController.InfoKey: Any]) { self.rawInfo = rawInfo type = (rawInfo[UIImagePickerController.InfoKey.mediaType] as! CFString).mediaFilter originalImage = rawInfo[UIImagePickerController.InfoKey.originalImage] as? UIImage editedImage = rawInfo[UIImagePickerController.InfoKey.editedImage] as? UIImage cropRect = rawInfo[UIImagePickerController.InfoKey.cropRect] as? CGRect movieUrl = rawInfo[UIImagePickerController.InfoKey.mediaURL] as? URL metaData = rawInfo[UIImagePickerController.InfoKey.mediaMetadata] as? NSDictionary } } } @available(iOS 9.0, *) extension UIImagePickerController.MediaFilter: ExpressibleByIntegerLiteral { /// :nodoc: public init(integerLiteral value: Int) { self.init(rawValue: value) } } @available(iOS 9.0, *) fileprivate extension CFString { var mediaFilter: UIImagePickerController.MediaFilter { switch self { case kUTTypeImage: return .image case kUTTypeMovie: return .movie default: return .image } } } @available(iOS 9.0, *) extension UIImagePickerController: DelegatorProtocol { @discardableResult fileprivate func update(handler: (_ delegate: ImagePickerControllerDelegate) -> Void) -> Self { DelegateWrapper.update(self, delegate: ImagePickerControllerDelegate(), delegates: &ImagePickerControllerDelegate.delegates, bind: UIImagePickerController.bind) { handler($0.delegate) } return self } // MARK: Reset /** Clears any delegate closures that were assigned to this `UIImagePickerController`. This cleans up memory as well as sets the `delegate` property to nil. This is typically only used for explicit cleanup. You are not required to call this method. */ @objc public func clearClosureDelegates() { DelegateWrapper.remove(delegator: self, from: &ImagePickerControllerDelegate.delegates) UIImagePickerController.bind(self, nil) } fileprivate static func bind(_ delegator: UIImagePickerController, _ delegate: ImagePickerControllerDelegate?) { delegator.delegate = nil delegator.delegate = delegate } }
mit
82b871a0d746a9f0d6e49bb98bd7d9a2
40.576
148
0.667885
5.554328
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/AccountUtils.swift
1
2407
// // AccountUtils.swift // Telegram // // Created by Mikhail Filimonov on 02.12.2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import SwiftSignalKit import Postbox import TelegramCore import InAppSettings let maximumNumberOfAccounts = 3 func activeAccountsAndPeers(context: AccountContext, includePrimary: Bool = false) -> Signal<((Account, Peer)?, [(Account, Peer, Int32)]), NoError> { let sharedContext = context.sharedContext return context.sharedContext.activeAccounts |> mapToSignal { primary, activeAccounts, _ -> Signal<((Account, Peer)?, [(Account, Peer, Int32)]), NoError> in var accounts: [Signal<(Account, Peer, Int32)?, NoError>] = [] func accountWithPeer(_ account: Account) -> Signal<(Account, Peer, Int32)?, NoError> { return combineLatest(account.postbox.peerView(id: account.peerId), renderedTotalUnreadCount(accountManager: sharedContext.accountManager, postbox: account.postbox)) |> map { view, totalUnreadCount -> (Peer?, Int32) in return (view.peers[view.peerId], totalUnreadCount.0) } |> distinctUntilChanged { lhs, rhs in return arePeersEqual(lhs.0, rhs.0) && lhs.1 == rhs.1 } |> map { peer, totalUnreadCount -> (Account, Peer, Int32)? in if let peer = peer { return (account, peer, totalUnreadCount) } else { return nil } } } for (_, account, _) in activeAccounts { accounts.append(accountWithPeer(account)) } return combineLatest(accounts) |> map { accounts -> ((Account, Peer)?, [(Account, Peer, Int32)]) in var primaryRecord: (Account, Peer)? if let first = accounts.filter({ $0?.0.id == primary?.id }).first, let (account, peer, _) = first { primaryRecord = (account, peer) } let accountRecords: [(Account, Peer, Int32)] = (includePrimary ? accounts : accounts.filter({ $0?.0.id != primary?.id })).compactMap({ $0 }) return (primaryRecord, accountRecords) } } }
gpl-2.0
7367ddee4492d72c82a3040ee8150a52
44.396226
180
0.546966
4.900204
false
false
false
false
mjarvis/Mockingjay
MockingjayTests/MockingjayProtocolTests.swift
2
2480
// // MockingjayURLProtocolTests.swift // Mockingjay // // Created by Kyle Fuller on 28/02/2015. // Copyright (c) 2015 Cocode. All rights reserved. // import Foundation import XCTest import Mockingjay class MockingjayProtocolTests : XCTestCase { func testCannotInitWithUnknownRequest() { let request = NSURLRequest(URL: NSURL(string: "https://kylefuller.co.uk/")!) let canInitWithRequest = MockingjayProtocol.canInitWithRequest(request) XCTAssertFalse(canInitWithRequest) } func testCanInitWithKnownRequestUsingMatcher() { let request = NSURLRequest(URL: NSURL(string: "https://kylefuller.co.uk/")!) MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in return true }) { (request) -> (Response) in return Response.Failure(NSError()) } let canInitWithRequest = MockingjayProtocol.canInitWithRequest(request) XCTAssertTrue(canInitWithRequest) } func testProtocolReturnsErrorWithRegisteredStubError() { let request = NSURLRequest(URL: NSURL(string: "https://kylefuller.co.uk/")!) let stubError = NSError(domain: "Mockingjay Tests", code: 0, userInfo: nil) MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in return true }) { (request) -> (Response) in return Response.Failure(stubError) } var response:NSURLResponse? var error:NSError? let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) XCTAssertNil(response) XCTAssertNil(data) XCTAssertEqual(error!.domain, "Mockingjay Tests") } func testProtocolReturnsResponseWithRegisteredStubError() { let request = NSURLRequest(URL: NSURL(string: "https://kylefuller.co.uk/")!) let stubResponse = NSURLResponse(URL: request.URL!, MIMEType: "text/plain", expectedContentLength: 5, textEncodingName: "utf-8") let stubData = "Hello".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)! MockingjayProtocol.addStub({ (requestedRequest) -> (Bool) in return true }) { (request) -> (Response) in return Response.Success(stubResponse, stubData) } var response:NSURLResponse? var error:NSError? let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) XCTAssertEqual(response!.URL!, stubResponse.URL!) XCTAssertEqual(response!.textEncodingName!, "utf-8") XCTAssertEqual(data!, stubData) XCTAssertNil(error) } }
bsd-3-clause
0de3ba34cc02a53e5e604bd75451fc9a
32.066667
132
0.721371
4.381625
false
true
false
false
chenzhe555/core-ios-swift
core-ios-swift/Framework_swift/CustomView/custom/ScrollView/BaseSlipTopView_s.swift
1
3261
// // BaseSlipTopView_s.swift // core-ios-swift // // Created by mc962 on 16/3/1. // Copyright © 2016年 陈哲是个好孩子. All rights reserved. // import UIKit /*item底部左右额外加的间隙 默认15*/ let kBaseSlideScrollViewDefaultSpace: CGFloat = 10.0 class BaseSlipTopView_s: UITableView { //MARK: *************** .h(Protocal Enum ...) enum BaseSlipTopScrollViewItemAreaType: Int { case Regulation = 99, //根据文字宽度最大均等分配 NotRegulation, //根据文字宽度不均等分配 ByScreenWidth //根据屏幕大小平均分配 } //MARK: *************** .h(Property Method ...) //MARK: 供外部实现 /** * 显示文字的数据源 */ var dataArray: NSMutableArray = [] { didSet{ self.maxHeight = self.calculateMaxWidth(); } }; //MARK: 共外部可选实现 /** * 缓存的高度数组 */ var heightArray:NSMutableArray = []; /** * 顶部视图高度(默认40) */ var topScrollHeight:CGFloat = 40.0; /** * 当前文本最大宽 */ var maxHeight: CGFloat = 0.0; /** * label宽度分布类型(默认 BaseSlipTopScrollViewItemAreaTypeByScreenWidth) */ var areaType: BaseSlipTopScrollViewItemAreaType = .ByScreenWidth; //MARK: *************** .m(Category ...) //MARK: *************** .m(Method ...) override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style); self.showsVerticalScrollIndicator = false; self.showsHorizontalScrollIndicator = false; self.separatorStyle = .None; } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } /** 计算最大宽度 - returns: */ private func calculateMaxWidth() -> CGFloat { var maxWidth: CGFloat = 0.0; var labelSize = CGSizeZero; for (var i = 0; i < self.dataArray.count; i++) { labelSize = MCViewTool_s.getLabelActualSize(self.dataArray[i] as! String, fontSize: kBaseScrollTopTitleFont, labelWidth: SCREENW); maxWidth = max(labelSize.width, maxWidth); self.heightArray.addObject(NSNumber(float: Float((labelSize.width + kBaseSlideScrollViewDefaultSpace*2.0)))); } switch (self.areaType) { case .Regulation: self.heightArray.removeAllObjects(); for(var i = 0; i < self.dataArray.count; i++) { self.heightArray.addObject(NSNumber(float: Float((maxWidth + kBaseSlideScrollViewDefaultSpace*2.0)))) } break; case .ByScreenWidth: let width: CGFloat = SCREENW/CGFloat(self.dataArray.count); self.heightArray.removeAllObjects(); for(var i = 0; i < self.dataArray.count; i++) { self.heightArray.addObject(NSNumber(float: Float(width))); } break; default: break; } return (maxWidth + kBaseSlideScrollViewDefaultSpace * 2); } }
mit
c0fa0186d572325b3f0512760341febc
25.684211
142
0.54931
4.133152
false
false
false
false
hgl888/ios-extensions-crosswalk
extensions/Presentation/Presentation/Presentation.swift
2
3447
// Copyright (c) 2015 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Foundation import XWalkView public class Presentation: XWalkExtension { var remoteWindow: UIWindow? = nil var remoteViewController: RemoteViewController? = nil var sessions: Dictionary<String, PresentationSessionHost> = [:] override init() { super.init() if UIScreen.screens().count == 2 { println("external display connected. count:\(UIScreen.screens().count)") var remoteScreen: UIScreen = UIScreen.screens()[1] as! UIScreen; createWindowForScreen(remoteScreen) sendAvailableChangeEvent(true) } NSNotificationCenter.defaultCenter().addObserver(self, selector: "screenDidConnect:", name: UIScreenDidConnectNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "screenDidDisconnect:", name: UIScreenDidDisconnectNotification, object: nil) } public override func didBindExtension(channel: XWalkChannel!, instance: Int) { super.didBindExtension(channel, instance: instance) let extensionName = "navigator.presentation.PresentationSession" PresentationSessionHost.presentation = self if let ext: PresentationSessionHost = XWalkExtensionFactory.createExtension(extensionName) as? PresentationSessionHost { channel.webView?.loadExtension(ext, namespace: extensionName) } } func createWindowForScreen(screen: UIScreen) { assert(remoteWindow == nil, "remoteWindow should be nil before it is created.") remoteWindow = UIWindow(frame: screen.bounds) remoteWindow?.screen = screen remoteViewController = RemoteViewController() remoteWindow?.rootViewController = remoteViewController remoteWindow?.hidden = false } func sendAvailableChangeEvent(isAvailable: Bool) { var js = "var ev = new Event(\"change\"); ev.value = \(isAvailable);"; js += " dispatchEvent(ev);"; self.evaluateJavaScript(js) } func screenDidConnect(notification: NSNotification) { if let screen = notification.object as? UIScreen { createWindowForScreen(screen) sendAvailableChangeEvent(true) } } func screenDidDisconnect(notification: NSNotification) { if let screen = notification.object as? UIScreen { sendAvailableChangeEvent(false) remoteWindow?.hidden = true remoteViewController?.willDisconnect() remoteViewController = nil remoteWindow = nil } } func registerSession(sessionHost: PresentationSessionHost, id: String) { sessions[id] = sessionHost } func unregisterSession(id: String) { sessions[id] = nil } func jsfunc_startSession(cid: UInt32, url: String, presentationId: String, _Promise: UInt32) { if let sessionHost = sessions[presentationId] { remoteViewController?.attachSession(sessionHost) } } func jsfunc_joinSession(cid: UInt32, url: String, presentationId: String, _Promise: UInt32) { } func jsfunc_getAvailability(cid: UInt32, _Promise: UInt32) { invokeCallback(_Promise, key: "resolve", arguments: [UIScreen.screens().count == 2]); } }
bsd-3-clause
765adb6a496d7a3a539e115d63bfafdb
36.467391
128
0.67595
5.032117
false
false
false
false
gerardogrisolini/Webretail
Sources/Webretail/Models/File.swift
1
2546
// // File.swift // Webretail // // Created by Gerardo Grisolini on 13/05/18. // import Foundation import StORM enum MediaSize { case small case big } class File: PostgresSqlORM { public var fileId : Int = 0 public var fileName : String = "" public var fileContentType : String = "" public var fileData : String = "" public var fileSize : Int = 0 public var fileCreated : Int = Int.now() open override func table() -> String { return "files" } open override func to(_ this: StORMRow) { fileId = this.data["fileid"] as? Int ?? 0 fileName = this.data["filename"] as? String ?? "" fileContentType = this.data["filecontenttype"] as? String ?? "" fileData = this.data["filedata"] as? String ?? "" fileSize = this.data["filesize"] as? Int ?? 0 fileCreated = this.data["filecreated"] as? Int ?? 0 } func rows() -> [File] { var rows = [File]() for i in 0..<self.results.rows.count { let row = File() row.to(self.results.rows[i]) rows.append(row) } return rows } func getData(filename: String, size: MediaSize) throws -> Data? { let order = size == .big ? "DESC" : "ASC" try query(whereclause: "filename = $1", params: [filename], orderby: ["filesize \(order)"], cursor: StORMCursor(limit: 1, offset: 0)) if self.fileId > 0 { return Data(base64Encoded: self.fileData, options: .ignoreUnknownCharacters) } return nil } func setData(data: Data) { self.fileSize = data.count self.fileData = data.base64EncodedString(options: .lineLength64Characters) } func setupShippingCost() throws { let fileNames = ["logo.png", "shippingcost.csv", "shippingcost_express.csv"] for fileName in fileNames { try self.query(whereclause: "filename = $1", params: [fileName], orderby: [], cursor: StORMCursor(limit: 1, offset: 0)) if self.results.rows.count == 0 { if let data = FileManager.default.contents(atPath: "./webroot/media/\(fileName)") { let file = File() _ = try file.getData(filename: fileName, size: .big) file.fileName = fileName file.fileContentType = fileName.hasSuffix(".csv") ? "text/csv" : "image/png" file.setData(data: data) try file.save() } } } } }
apache-2.0
e1eb66df936f7d2a376339eec0b24204
32.5
141
0.560094
4.05414
false
false
false
false
SpectralDragon/LightRoute
Sources/StoryboardFactory.swift
1
3627
// // StoryboardFactory.swift // LiteRoute // // Copyright © 2016-2020 Vladislav Prusakov <[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 /// This factory class a performs `StoryboardFactoryProtocol` and the instantiate transition view controller. public struct StoryboardFactory: StoryboardFactoryProtocol { // MARK: - // MARK: Properties // MARK: Public /// Instantiate transition view controller. public func instantiateTransitionHandler() throws -> UIViewController { let controller = self.restorationId.isEmpty ? self.storyboard.instantiateInitialViewController() : self.storyboard.instantiateViewController(withIdentifier: self.restorationId) // If destination controller is nil then return error. guard let destination = controller else { throw LiteRouteError.restorationId(self.restorationId) } return destination } // MARK: Private private var storyboard: UIStoryboard private var restorationId: String // MARK: - // MARK: Initialize /// /// Initialize Storyboard factory from `UIStoryboard` instance. /// /// - note: By default this init call `instantiateInitialViewController` instead `instantiateViewController(withIdentifier:)` /// if restorationId is empty. /// /// - parameter storyboard: Storyboard instance. /// - parameter restorationId: Restiration identifier for destination view controller. /// public init(storyboard: UIStoryboard, restorationId: String = "") { self.storyboard = storyboard self.restorationId = restorationId } /// /// Initialize Storyboard factory from Storyboard name. /// /// - note: By default this init call `instantiateInitialViewController` instead `instantiateViewController(withIdentifier:)` /// if restorationId is empty. /// /// - parameter storyboardName: The name of the storyboard resource file without the filename extension. /// - parameter bundle: The bundle containing the storyboard file and its related resources. /// If you specify nil, this method looks in the main bundle of the current application. /// - parameter restorationId: Restiration identifier for destination view controller. /// public init(storyboardName name: String, bundle: Bundle? = nil, restorationId: String = "") { self.storyboard = UIStoryboard(name: name, bundle: bundle) self.restorationId = restorationId } }
mit
153056a04cd248117a67be9db25ddbbf
42.166667
129
0.712355
5.050139
false
false
false
false
iccub/freestyle-timer-ios
freestyle-timer-ios/audio/AudioPlayer.swift
1
3349
/* Copyright © 2017 Michał Buczek. This file is part of Freestyle Timer. Freestyle Timer 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. Freestyle Timer 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 Freestyle Timer. If not, see <http://www.gnu.org/licenses/>. */ import Foundation import AVFoundation import AudioToolbox import CoreMedia import os.log /** This class holds all audio players used by app. The app uses separate players for playing music and interval sounds. AVQueuePlayer is used for music player, which allows multiple tracks to be played. This is used in case when timer length is longer than song duration which causes timer to stop while in background(app uses backgroud audio permission to run in background). */ class AudioPlayer { static let log = OSLog(subsystem: "com.michalbuczek.freestyle_timer_ios.logs", category: "AudioPlayer") private var music: AVQueuePlayer? private let switchSound: AVAudioPlayer private let endSound: AVAudioPlayer /** We hold reference to all songs to reset them after user presses stop button or timer has finished. */ private var songUrlsList: [URL]? init(timerMode: TimerMode) throws { guard let switchSoundURL = timerMode.switchSoundUrl, let endSoundURL = timerMode.endSoundUrl else { os_log("Could not find interval sound resources", log: AudioPlayer.log, type: .error) throw NSError() } do { switchSound = try AVAudioPlayer(contentsOf: switchSoundURL) switchSound.prepareToPlay() endSound = try AVAudioPlayer(contentsOf: endSoundURL) endSound.prepareToPlay() } catch { os_log("Failed to initialize interval sounds", log: AudioPlayer.log, type: .error) throw error } } func setSongs(urls: [URL]) { let items = urls.map { return AVPlayerItem(url: $0) } songUrlsList = urls music = AVQueuePlayer(items: items) os_log("Music player set with %i song/s", log: AudioPlayer.log, type: .info, items.count) } /** Check if music player was set. */ func isMusicSet() -> Bool { return music != nil } // MARK: - Interval sounds func playSwitchSound() { os_log("Play switch sound", log: AudioPlayer.log, type: .info) switchSound.play() } func playEndSound() { os_log("Play end sound", log: AudioPlayer.log, type: .info) endSound.play() } // MARK: - Song controls func play() { music?.play() } func pause() { music?.pause() } func stop() { music?.pause() // Stopping should reset the playback queue, setting songs again is needed for that. if let urls = songUrlsList { setSongs(urls: urls) } } }
gpl-3.0
73ac676258d5a6e3b63106b38ba0ce72
32.47
117
0.656707
4.474599
false
false
false
false
benlangmuir/swift
test/decl/protocol/special/coding/enum_codable_simple_extension_flipped.swift
13
1413
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown -swift-version 4 // Simple enums where Codable conformance is added in extensions should derive // conformance, no matter which order the extension and type occur in. extension SimpleEnum : Codable {} enum SimpleEnum { case a(x: Int, y: Double) case b(z: String) func foo() { // They should receive a synthesized CodingKeys enum. let _ = SimpleEnum.CodingKeys.self let _ = SimpleEnum.ACodingKeys.self let _ = SimpleEnum.BCodingKeys.self // The enum should have a case for each of the cases. let _ = SimpleEnum.CodingKeys.a let _ = SimpleEnum.CodingKeys.b // The enum should have a case for each of the vars. let _ = SimpleEnum.ACodingKeys.x let _ = SimpleEnum.ACodingKeys.y let _ = SimpleEnum.BCodingKeys.z } } // They should receive synthesized init(from:) and an encode(to:). let _ = SimpleEnum.init(from:) let _ = SimpleEnum.encode(to:) // The synthesized CodingKeys type should not be accessible from outside the // enum. let _ = SimpleEnum.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}} let _ = SimpleEnum.ACodingKeys.self // expected-error {{'ACodingKeys' is inaccessible due to 'private' protection level}} let _ = SimpleEnum.BCodingKeys.self // expected-error {{'BCodingKeys' is inaccessible due to 'private' protection level}}
apache-2.0
6368a06bd9a348c5902b7f892291a558
36.184211
121
0.719745
4.095652
false
false
false
false
loudnate/LoopKit
LoopKitUI/CarbKit/DateAndDurationTableViewCell.swift
1
1692
// // DateAndDurationTableViewCell.swift // LoopKitUI // // Copyright © 2018 LoopKit Authors. All rights reserved. // import UIKit public class DateAndDurationTableViewCell: DatePickerTableViewCell { public weak var delegate: DatePickerTableViewCellDelegate? @IBOutlet public weak var titleLabel: UILabel! @IBOutlet public weak var dateLabel: UILabel! { didSet { // Setting this color in code because the nib isn't being applied correctly if #available(iOSApplicationExtension 13.0, *) { dateLabel.textColor = .secondaryLabel } } } private lazy var durationFormatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.allowedUnits = [.hour, .minute] formatter.unitsStyle = .short return formatter }() public override func updateDateLabel() { switch datePicker.datePickerMode { case .countDownTimer: dateLabel.text = durationFormatter.string(from: duration) case .date: dateLabel.text = DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .none) case .dateAndTime: dateLabel.text = DateFormatter.localizedString(from: date, dateStyle: .short, timeStyle: .short) case .time: dateLabel.text = DateFormatter.localizedString(from: date, dateStyle: .none, timeStyle: .medium) @unknown default: break // Do nothing } } public override func dateChanged(_ sender: UIDatePicker) { super.dateChanged(sender) delegate?.datePickerTableViewCellDidUpdateDate(self) } }
mit
64f84acc5608b4a867e983962c918093
30.314815
108
0.659965
5.30094
false
true
false
false
tsolomko/SWCompression
Sources/TAR/TarWriter.swift
1
6569
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation /** A type that allows to iteratively create TAR containers with the output being written into a `FileHandle`. The `TarWriter` may be helpful in reducing the peak memory usage on certain platforms. However, to achieve this both the creation of TAR entries and the calls to `TarWriter` should be wrapped inside the `autoreleasepool`. Since the `autoreleasepool` is available only on Darwin platforms, the memory reducing effect may be not as significant on non-Darwin platforms (such as Linux or Windows). The following code demonstrates an example usage of the `TarWriter`: ```swift let handle: FileHandle = ... let writer = TarWriter(fileHandle: handle) try autoreleasepool { let entry: TarEntry = ... try writer.append(entry) } try writer.finalize() try handle.close() ``` Note that `TarWriter.finalize()` must be called after finishing appending entries to the container. In addition, closing the `FileHandle` remains the responsibility of the caller. - Important: Due to the API availability limitations of Foundation's `FileHandle`, on certain platforms errors in `FileHandle` operations may result in unrecoverable runtime failures due to unhandled Objective-C exceptions (which are impossible to correctly handle in Swift code). As such, it is not recommended to use `TarWriter` on those platforms. The following platforms are _unaffected_ by this issue: macOS 10.15.4+, iOS 13.4+, watchOS 6.2+, tvOS 13.4+, and any other platforms without Objective-C runtime. */ public struct TarWriter { private let format: TarContainer.Format private let handle: FileHandle private var longNameCounter: UInt private var longLinkNameCounter: UInt private var localPaxHeaderCounter: UInt /** Creates a new instance for writing TAR entries using the specified `format` into the provided `fileHandle`. The `TarWriter` will be forced to use the provided `format`, meaning that certain properties of the `entries` may be missing from the output data if the chosen format does not support corresponding features. The default `.pax` format supports the largest set of features. Other (non-PAX) formats should only be used if you have a specific need for them and you understand limitations of those formats. - Parameter fileHandle: A handle into which the output will be written. Note that the `TarWriter` does not close the `fileHandle` and this remains the responsibility of the caller. - Parameter force: Force the usage of the specified format. - Important: `TarWriter.finalize()` must be called after all entries have been appended. */ public init(fileHandle: FileHandle, force format: TarContainer.Format = .pax) { self.handle = fileHandle self.format = format self.longNameCounter = 0 self.longLinkNameCounter = 0 self.localPaxHeaderCounter = 0 } /** Adds a new TAR entry at the end of the TAR container. On Darwin platforms it is recommended to wrap both the initialization of a `TarEntry` and the call to this function inside the `autoreleasepool` in order to reduce the peak memory usage. - Throws: Errors from the `FileHandle` operations. */ public mutating func append(_ entry: TarEntry) throws { var out = Data() if format == .gnu { if entry.info.name.utf8.count > 100 { let nameData = Data(entry.info.name.utf8) let longNameHeader = TarHeader(specialName: "SWC_LongName_\(longNameCounter)", specialType: .longName, size: nameData.count, uid: entry.info.ownerID, gid: entry.info.groupID) out.append(longNameHeader.generateContainerData(.gnu)) assert(out.count % 512 == 0) out.appendAsTarBlock(nameData) longNameCounter &+= 1 } if entry.info.linkName.utf8.count > 100 { let linkNameData = Data(entry.info.linkName.utf8) let longLinkNameHeader = TarHeader(specialName: "SWC_LongLinkName_\(longLinkNameCounter)", specialType: .longLinkName, size: linkNameData.count, uid: entry.info.ownerID, gid: entry.info.groupID) out.append(longLinkNameHeader.generateContainerData(.gnu)) assert(out.count % 512 == 0) out.appendAsTarBlock(linkNameData) longLinkNameCounter &+= 1 } } else if format == .pax { let extHeader = TarExtendedHeader(entry.info) let extHeaderData = extHeader.generateContainerData() if !extHeaderData.isEmpty { let extHeaderHeader = TarHeader(specialName: "SWC_LocalPaxHeader_\(localPaxHeaderCounter)", specialType: .localExtendedHeader, size: extHeaderData.count, uid: entry.info.ownerID, gid: entry.info.groupID) out.append(extHeaderHeader.generateContainerData(.pax)) assert(out.count % 512 == 0) out.appendAsTarBlock(extHeaderData) localPaxHeaderCounter &+= 1 } } let header = TarHeader(entry.info) out.append(header.generateContainerData(format)) assert(out.count % 512 == 0) try write(out) if let data = entry.data { try write(data) let paddingSize = data.count.roundTo512() - data.count try write(Data(count: paddingSize)) } } /** Finalizes the TAR container by adding an EOF marker. - Throws: Errors from the `FileHandle` operations. */ public func finalize() throws { // First, we append two 512-byte blocks consisting of zeros as an EOF marker. try write(Data(count: 1024)) // The synchronization is performed by the write(_:) function automatically. } private func write(_ data: Data) throws { if #available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *) { try handle.write(contentsOf: data) try handle.synchronize() } else { handle.write(data) handle.synchronizeFile() } } }
mit
516eef1c13f830b00890453bc88ceacb
44.618056
120
0.643325
4.698856
false
false
false
false
gottesmm/swift
test/SILGen/accessors.swift
2
9833
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s // Hold a reference to do to magically become non-POD. class Reference {} // A struct with a non-mutating getter and a mutating setter. struct OrdinarySub { var ptr = Reference() subscript(value: Int) -> Int { get { return value } set {} } } class A { var array = OrdinarySub() } func index0() -> Int { return 0 } func index1() -> Int { return 1 } func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } // Verify that there is no unnecessary extra copy_value of ref.array. // rdar://19002913 func test0(_ ref: A) { ref.array[index0()] = ref.array[index1()] } // CHECK: sil hidden @_T09accessors5test0yAA1ACF : $@convention(thin) (@owned A) -> () { // CHECK: bb0(%0 : $A): // CHECK-NEXT: debug_value // Formal evaluation of LHS. // CHECK-NEXT: // function_ref accessors.index0 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index0SiyF // CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]() // Formal evaluation of RHS. // CHECK-NEXT: // function_ref accessors.index1 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index1SiyF // CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]() // Formal access to RHS. // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $OrdinarySub // CHECK-NEXT: [[T0:%.*]] = class_method %0 : $A, #A.array!getter.1 // CHECK-NEXT: [[T1:%.*]] = apply [[T0]](%0) // CHECK-NEXT: store [[T1]] to [init] [[TEMP]] // CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]] // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.getter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T1:%.*]] = function_ref @_T09accessors11OrdinarySubV9subscriptSiSicfg // CHECK-NEXT: [[VALUE:%.*]] = apply [[T1]]([[INDEX1]], [[T0]]) // CHECK-NEXT: destroy_value [[T0]] // Formal access to LHS. // CHECK-NEXT: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER:%.*]] = alloc_stack $OrdinarySub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER]] // CHECK-NEXT: [[T1:%.*]] = class_method %0 : $A, #A.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE]], %0) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*OrdinarySub on %0 : $A // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.setter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors11OrdinarySubV9subscriptSiSicfs // CHECK-NEXT: apply [[T0]]([[VALUE]], [[INDEX0]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]] // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout A, @thick A.Type) -> () // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $A // CHECK-NEXT: store %0 to [init] [[TEMP2]] : $*A // CHECK-NEXT: [[T0:%.*]] = metatype $@thick A.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*OrdinarySub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // CHECK: [[CONT]]: // CHECK-NEXT: dealloc_stack [[BUFFER]] // CHECK-NEXT: dealloc_stack [[STORAGE]] // CHECK-NEXT: dealloc_stack [[TEMP]] // Balance out the +1 from the function parameter. // CHECK-NEXT: destroy_value %0 // CHECK-NEXT: tuple () // CHECK-NEXT: return // A struct with a mutating getter and a mutating setter. struct MutatingSub { var ptr = Reference() subscript(value: Int) -> Int { mutating get { return value } set {} } } class B { var array = MutatingSub() } func test1(_ ref: B) { ref.array[index0()] = ref.array[index1()] } // CHECK-LABEL: sil hidden @_T09accessors5test1yAA1BCF : $@convention(thin) (@owned B) -> () { // CHECK: bb0(%0 : $B): // CHECK-NEXT: debug_value // Formal evaluation of LHS. // CHECK-NEXT: // function_ref accessors.index0 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index0SiyF // CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]() // Formal evaluation of RHS. // CHECK-NEXT: // function_ref accessors.index1 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index1SiyF // CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]() // Formal access to RHS. // CHECK-NEXT: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER:%.*]] = alloc_stack $MutatingSub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER]] // CHECK-NEXT: [[T1:%.*]] = class_method %0 : $B, #B.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE]], %0) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on %0 : $B // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.getter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors11MutatingSubV9subscriptSiSicfg : $@convention(method) (Int, @inout MutatingSub) -> Int // CHECK-NEXT: [[VALUE:%.*]] = apply [[T0]]([[INDEX1]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]] // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout B, @thick B.Type) -> () // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B // CHECK-NEXT: store %0 to [init] [[TEMP2]] : $*B // CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*MutatingSub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // CHECK: [[CONT]]: // Formal access to LHS. // CHECK-NEXT: [[STORAGE2:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER2:%.*]] = alloc_stack $MutatingSub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER2]] // CHECK-NEXT: [[T1:%.*]] = class_method %0 : $B, #B.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE2]], %0) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on %0 : $B // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.setter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors11MutatingSubV9subscriptSiSicfs : $@convention(method) (Int, Int, @inout MutatingSub) -> () // CHECK-NEXT: apply [[T0]]([[VALUE]], [[INDEX0]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]] // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout B, @thick B.Type) -> () // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B // CHECK-NEXT: store %0 to [init] [[TEMP2]] : $*B // CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*MutatingSub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE2]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // CHECK: [[CONT]]: // CHECK-NEXT: dealloc_stack [[BUFFER2]] // CHECK-NEXT: dealloc_stack [[STORAGE2]] // CHECK-NEXT: dealloc_stack [[BUFFER]] // CHECK-NEXT: dealloc_stack [[STORAGE]] // Balance out the +1 from the function parameter. // CHECK-NEXT: destroy_value %0 // CHECK-NEXT: tuple () // CHECK-NEXT: return struct RecInner { subscript(i: Int) -> Int { get { return i } } } struct RecOuter { var inner : RecInner { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } func test_rec(_ outer: inout RecOuter) -> Int { return outer.inner[0] } // This uses the immutable addressor. // CHECK: sil hidden @_T09accessors8test_recSiAA8RecOuterVzF : $@convention(thin) (@inout RecOuter) -> Int { // CHECK: function_ref @_T09accessors8RecOuterV5innerAA0B5InnerVflu : $@convention(method) (RecOuter) -> UnsafePointer<RecInner> struct Rec2Inner { subscript(i: Int) -> Int { mutating get { return i } } } struct Rec2Outer { var inner : Rec2Inner { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } func test_rec2(_ outer: inout Rec2Outer) -> Int { return outer.inner[0] } // This uses the mutable addressor. // CHECK: sil hidden @_T09accessors9test_rec2SiAA9Rec2OuterVzF : $@convention(thin) (@inout Rec2Outer) -> Int { // CHECK: function_ref @_T09accessors9Rec2OuterV5innerAA0B5InnerVfau : $@convention(method) (@inout Rec2Outer) -> UnsafeMutablePointer<Rec2Inner>
apache-2.0
30234e3e8db6e61da1a698d8455a5655
49.168367
206
0.632666
3.213399
false
false
false
false
DopamineLabs/DopamineKit-iOS
BoundlessKit/Classes/Extensions/UIViewControllerExtensions.swift
1
1743
// // UIViewControllerExtensions.swift // BoundlessKit // // Created by Akash Desai on 4/9/18. // import Foundation internal class Application { static var shared: UIApplication? { let sharedSelector = NSSelectorFromString("sharedApplication") guard UIApplication.responds(to: sharedSelector) else { return nil } return UIApplication.perform(sharedSelector)?.takeUnretainedValue() as? UIApplication } } internal extension UIViewController { static func getViewControllers(ofType aClass: AnyClass) -> [UIViewController] { return Application.shared?.windows.reversed().compactMap({$0.rootViewController?.getChildViewControllers(ofType: aClass)}).flatMap({$0}) ?? [] } func getChildViewControllers(ofType aClass: AnyClass) -> [UIViewController] { var vcs = [UIViewController]() if aClass == type(of: self) { vcs.append(self) } if let tabController = self as? UITabBarController, let tabVCs = tabController.viewControllers { for vc in tabVCs.reversed() { vcs += vc.getChildViewControllers(ofType: aClass) } } else if let navController = self as? UINavigationController { for vc in navController.viewControllers.reversed() { vcs += vc.getChildViewControllers(ofType: aClass) } } else { if let vc = self.presentedViewController { vcs += vc.getChildViewControllers(ofType: aClass) } for vc in children.reversed() { vcs += vc.getChildViewControllers(ofType: aClass) } } return vcs } }
mit
248ac74de56b806ff26631f46779fb31
32.519231
150
0.611015
5.330275
false
false
false
false
AdeptusAstartes/AlamofireRSSParser
Pod/Classes/AlamofireRSSParser.swift
1
12742
// // AlamofireRSSParser.swift // Pods // // Created by Donald Angelillo on 3/2/16. // // import Foundation import Alamofire extension DataRequest { @discardableResult public func responseRSS(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse<RSSFeed>) -> Void) -> Self { response(queue: queue, responseSerializer: RSSResponseSerializer(), completionHandler: completionHandler) } @available(iOS 13, *) public func serializingRSS(automaticallyCancelling shouldAutomaticallyCancel: Bool = false, dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes, emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DataTask<RSSFeed> { serializingResponse(using: RSSResponseSerializer(dataPreprocessor: dataPreprocessor, emptyResponseCodes: emptyResponseCodes, emptyRequestMethods: emptyRequestMethods), automaticallyCancelling: shouldAutomaticallyCancel) } } public final class RSSResponseSerializer: ResponseSerializer { public let dataPreprocessor: DataPreprocessor public let emptyResponseCodes: Set<Int> public let emptyRequestMethods: Set<HTTPMethod> public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes, emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) { self.dataPreprocessor = dataPreprocessor self.emptyResponseCodes = emptyResponseCodes self.emptyRequestMethods = emptyRequestMethods } public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> RSSFeed { guard error == nil else { throw error! } guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." let error = NSError(domain: "com.alamofirerssparser", code: -6004, userInfo: [NSLocalizedFailureReasonErrorKey: failureReason]) throw error } let parser = AlamofireRSSParser(data: validData) let parsedResults: (feed: RSSFeed?, error: NSError?) = parser.parse() if let feed = parsedResults.feed { return feed } else { let failureReason = "Data could not be serialized." let error = NSError(domain: "com.alamofirerssparser", code: -6004, userInfo: [NSLocalizedFailureReasonErrorKey: failureReason]) throw error } } } /** This class does the bulk of the work. Implements the `NSXMLParserDelegate` protocol. Unfortunately due to this it's also required to implement the `NSObject` protocol. And unfortunately due to that there doesn't seem to be any way to make this class have a valid public initializer, despite it being marked public. I would love to have it be publicly accessible because I would like to able to pass a custom-created instance of this class with configuration properties set into `responseRSS` (see the commented out overload above) */ open class AlamofireRSSParser: NSObject, XMLParserDelegate { var parser: XMLParser? = nil var feed: RSSFeed? = nil var parsingItems: Bool = false var currentItem: RSSItem? = nil var currentString: String! var currentAttributes: [String: String]? = nil var parseError: NSError? = nil open var data: Data? = nil { didSet { if let data = data { self.parser = XMLParser(data: data) self.parser?.delegate = self } } } override init() { self.parser = XMLParser(); super.init() } init(data: Data) { self.parser = XMLParser(data: data) super.init() self.parser?.delegate = self } /** Kicks off the RSS parsing. - Returns: A tuple containing an `RSSFeed` object if parsing was successful (`nil` otherwise) and an `NSError` object if an error occurred (`nil` otherwise). */ func parse() -> (feed: RSSFeed?, error: NSError?) { self.feed = RSSFeed() self.currentItem = nil self.currentAttributes = nil self.currentString = String() self.parser?.parse() return (feed: self.feed, error: self.parseError) } //MARK: - NSXMLParserDelegate open func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { self.currentString = String() self.currentAttributes = attributeDict if ((elementName == "item") || (elementName == "entry")) { self.currentItem = RSSItem() } } open func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { //if we're at the item level if let currentItem = self.currentItem { if ((elementName == "item") || (elementName == "entry")) { self.feed?.items.append(currentItem) return } if (elementName == "title") { currentItem.title = self.currentString } if (elementName == "description") { currentItem.itemDescription = self.currentString } if ((elementName == "content:encoded") || (elementName == "content")) { currentItem.content = self.currentString } if (elementName == "link") { currentItem.link = self.currentString } if (elementName == "guid") { currentItem.guid = self.currentString } if (elementName == "author") { currentItem.author = self.currentString } if (elementName == "comments") { currentItem.comments = self.currentString } if (elementName == "source") { currentItem.source = self.currentString } if (elementName == "pubDate") { if let date = RSSDateFormatter.rfc822DateFormatter().date(from: self.currentString) { currentItem.pubDate = date } else if let date = RSSDateFormatter.rfc822DateFormatter2().date(from: self.currentString) { currentItem.pubDate = date } } if (elementName == "published") { if let date = RSSDateFormatter.publishedDateFormatter().date(from: self.currentString) { currentItem.pubDate = date } else if let date = RSSDateFormatter.publishedDateFormatter2().date(from: self.currentString) { currentItem.pubDate = date } } if (elementName == "media:thumbnail") { if let attributes = self.currentAttributes { if let url = attributes["url"] { currentItem.mediaThumbnail = url } } } if (elementName == "media:content") { if let attributes = self.currentAttributes { if let url = attributes["url"] { currentItem.mediaContent = url } } } if (elementName == "enclosure") { if let attributes = self.currentAttributes { currentItem.enclosures = (currentItem.enclosures ?? []) + [attributes] } } if (elementName == "category") { if ((self.currentString != nil) && (!self.currentString.isEmpty)) { self.currentItem?.categories.append(self.currentString) } } //if we're at the top level } else { if (elementName == "title") { self.feed?.title = self.currentString } if (elementName == "description") { self.feed?.feedDescription = self.currentString } if (elementName == "link") { self.feed?.link = self.currentString } if (elementName == "language") { self.feed?.language = self.currentString } if (elementName == "copyright") { self.feed?.copyright = self.currentString } if (elementName == "managingEditor") { self.feed?.managingEditor = self.currentString } if (elementName == "webMaster") { self.feed?.webMaster = self.currentString } if (elementName == "generator") { self.feed?.generator = self.currentString } if (elementName == "docs") { self.feed?.docs = self.currentString } if (elementName == "ttl") { if let ttlInt = Int(currentString) { self.feed?.ttl = NSNumber(value: ttlInt) } } if (elementName == "pubDate") { if let date = RSSDateFormatter.rfc822DateFormatter().date(from: self.currentString) { self.feed?.pubDate = date } else if let date = RSSDateFormatter.rfc822DateFormatter2().date(from: self.currentString) { self.feed?.pubDate = date } } if (elementName == "published") { if let date = RSSDateFormatter.publishedDateFormatter().date(from: self.currentString) { self.feed?.pubDate = date } else if let date = RSSDateFormatter.publishedDateFormatter2().date(from: self.currentString) { self.feed?.pubDate = date } } if (elementName == "lastBuildDate") { if let date = RSSDateFormatter.rfc822DateFormatter().date(from: self.currentString) { self.feed?.lastBuildDate = date } else if let date = RSSDateFormatter.rfc822DateFormatter2().date(from: self.currentString) { self.feed?.lastBuildDate = date } } } } open func parser(_ parser: XMLParser, foundCharacters string: String) { self.currentString.append(string) } open func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { self.parseError = parseError as NSError? self.parser?.abortParsing() } } /** Struct containing various `NSDateFormatter` s */ struct RSSDateFormatter { static func rfc822DateFormatter() -> DateFormatter { let dateFormatter: DateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US") dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z" return dateFormatter } static func rfc822DateFormatter2() -> DateFormatter { let dateFormatter: DateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US") dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z" return dateFormatter } static func publishedDateFormatter() -> DateFormatter { let dateFormatter: DateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return dateFormatter } static func publishedDateFormatter2() -> DateFormatter { let dateFormatter: DateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssz" return dateFormatter } }
mit
eb9d0ab90b6f97ac7f3c00314e8ec2dc
37.495468
273
0.561529
5.378641
false
false
false
false
grandiere/box
box/Model/Help/Release/MHelpReleaseIntro.swift
1
1361
import UIKit class MHelpReleaseIntro:MHelpProtocol { private let attributedString:NSAttributedString init() { let attributesTitle:[String:AnyObject] = [ NSFontAttributeName:UIFont.bold(size:20), NSForegroundColorAttributeName:UIColor.white] let attributesDescription:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:18), NSForegroundColorAttributeName:UIColor(white:1, alpha:0.8)] let stringTitle:NSAttributedString = NSAttributedString( string:NSLocalizedString("MHelpReleaseIntro_title", comment:""), attributes:attributesTitle) let stringDescription:NSAttributedString = NSAttributedString( string:NSLocalizedString("MHelpReleaseIntro_description", comment:""), attributes:attributesDescription) let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(stringTitle) mutableString.append(stringDescription) attributedString = mutableString } var message:NSAttributedString { get { return attributedString } } var image:UIImage { get { return #imageLiteral(resourceName: "assetHelpBasicRelease") } } }
mit
35c6d679204576df39b2b2623d8d5989
29.931818
82
0.650992
6.048889
false
false
false
false
BenEmdon/swift-algorithm-club
Counting Sort/CountingSort.swift
1
1061
// // Sort.swift // test // // Created by Kauserali on 11/04/16. // Copyright © 2016 Ali Hafizji. All rights reserved. // enum CountingSortError: ErrorType { case ArrayEmpty } func countingSort(array: [Int]) throws -> [Int] { guard array.count > 0 else { throw CountingSortError.ArrayEmpty } // Step 1 // Create an array to store the count of each element let maxElement = array.maxElement() ?? 0 var countArray = [Int](count: Int(maxElement + 1), repeatedValue: 0) for element in array { countArray[element] += 1 } // Step 2 // Set each value to be the sum of the previous two values for index in 1 ..< countArray.count { let sum = countArray[index] + countArray[index - 1] countArray[index] = sum } print(countArray) // Step 3 // Place the element in the final array as per the number of elements before it var sortedArray = [Int](count: array.count, repeatedValue: 0) for element in array { countArray[element] -= 1 sortedArray[countArray[element]] = element } return sortedArray }
mit
bddedaf42f39bcf6b10c812e2fd903ea
23.090909
81
0.671698
3.630137
false
false
false
false
odigeoteam/TableViewKit
TableViewKitTests/TableViewDelegateTests.swift
1
10943
import XCTest import TableViewKit import Nimble class NoHeaderFooterSection: TableSection { var items: ObservableArray<TableItem> = [] convenience init(items: [TableItem]) { self.init() self.items.insert(contentsOf: items, at: 0) } } class CustomHeaderFooterView: UITableViewHeaderFooterView { var label: UILabel = UILabel() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CustomHeaderDrawer: HeaderFooterDrawer { static public var type = HeaderFooterType.class(CustomHeaderFooterView.self) static public func draw(_ view: CustomHeaderFooterView, with item: ViewHeaderFooter) { view.label.text = item.title } } class ViewHeaderFooter: HeaderFooter { public var title: String? public var height: Height? = .dynamic(44.0) static public var drawer = AnyHeaderFooterDrawer(CustomHeaderDrawer.self) public init() { } public convenience init(title: String) { self.init() self.title = title } } class ViewHeaderFooterSection: TableSection { var items: ObservableArray<TableItem> = [] internal var header: HeaderFooterView = .view(ViewHeaderFooter(title: "First Section")) internal var footer: HeaderFooterView = .view(ViewHeaderFooter(title: "Section Footer\nHola")) convenience init(items: [TableItem]) { self.init() self.items.insert(contentsOf: items, at: 0) } } class NoHeigthItem: TableItem { static internal var drawer = AnyCellDrawer(TestDrawer.self) internal var height: Height? } class StaticHeigthItem: TableItem { static let testStaticHeightValue: CGFloat = 20.0 static internal var drawer = AnyCellDrawer(TestDrawer.self) internal var height: Height? = .static(20.0) } class SelectableItem: Selectable, TableItem { static internal var drawer = AnyCellDrawer(TestDrawer.self) public var check: Int = 0 public init() {} func didSelect() { check += 1 } } class ActionableItem: ActionPerformable, TableItem { static internal var drawer = AnyCellDrawer(TestDrawer.self) public var check: Int = 0 public init() {} func canPerformAction(_ action: ItemAction) -> Bool { return true } func performAction(_ action: ItemAction) { check += 1 } } class EditableItem: SelectableItem, Editable { public var actions: [UITableViewRowAction]? public var configuration: UISwipeActionsConfiguration? } class TableViewDelegateTests: XCTestCase { fileprivate var tableViewManager: TableViewManager! fileprivate var delegate: TableViewKitDelegate { return tableViewManager.delegate! } override func setUp() { super.setUp() tableViewManager = TableViewManager(tableView: UITableView()) tableViewManager.sections.append(HeaderFooterTitleSection(items: [TestItem()])) tableViewManager.sections.append(NoHeaderFooterSection(items: [NoHeigthItem(), StaticHeigthItem()])) tableViewManager.sections.append(ViewHeaderFooterSection(items: [NoHeigthItem(), StaticHeigthItem()])) } override func tearDown() { tableViewManager = nil super.tearDown() } func testEstimatedHeightForHeader() { var height: CGFloat height = delegate.tableView(tableViewManager.tableView, estimatedHeightForHeaderInSection: 0) expect(height) > 0.0 height = delegate.tableView(tableViewManager.tableView, estimatedHeightForHeaderInSection: 1) expect(height) == tableViewManager.tableView.estimatedSectionHeaderHeight } func testHeightForHeader() { var height: CGFloat height = delegate.tableView(tableViewManager.tableView, heightForHeaderInSection: 0) expect(height) == UITableView.automaticDimension } func testEstimatedHeightForFooter() { var height: CGFloat height = delegate.tableView(tableViewManager.tableView, estimatedHeightForFooterInSection: 0) expect(height) > 0.0 height = delegate.tableView(tableViewManager.tableView, estimatedHeightForFooterInSection: 1) expect(height) == tableViewManager.tableView.estimatedSectionFooterHeight height = delegate.tableView(tableViewManager.tableView, estimatedHeightForFooterInSection: 2) expect(height) == 44.0 } func testHeightForFooter() { var height: CGFloat height = delegate.tableView(tableViewManager.tableView, heightForFooterInSection: 0) expect(height) == UITableView.automaticDimension height = delegate.tableView(tableViewManager.tableView, heightForFooterInSection: 2) expect(height) == UITableView.automaticDimension } func testEstimatedHeightForRowAtIndexPath() { var height: CGFloat var indexPath: IndexPath indexPath = IndexPath(row: 0, section: 0) height = delegate.tableView(tableViewManager.tableView, estimatedHeightForRowAt: indexPath) expect(height) == 44.0 indexPath = IndexPath(row: 0, section: 1) height = delegate.tableView(tableViewManager.tableView, estimatedHeightForRowAt: indexPath) expect(height) == tableViewManager.tableView.estimatedRowHeight indexPath = IndexPath(row: 1, section: 1) height = delegate.tableView(tableViewManager.tableView, estimatedHeightForRowAt: indexPath) expect(height) == 20.0 } func testHeightForRowAtIndexPath() { var height: CGFloat var indexPath: IndexPath indexPath = IndexPath(row: 0, section: 0) height = delegate.tableView(tableViewManager.tableView, heightForRowAt: indexPath) expect(height) == UITableView.automaticDimension indexPath = IndexPath(row: 0, section: 1) height = delegate.tableView(tableViewManager.tableView, heightForRowAt: indexPath) expect(height) == tableViewManager.tableView.rowHeight indexPath = IndexPath(row: 1, section: 1) height = delegate.tableView(tableViewManager.tableView, heightForRowAt: indexPath) expect(height) == StaticHeigthItem.testStaticHeightValue } func testSelectRow() { var indexPath: IndexPath indexPath = IndexPath(row: 0, section: 0) delegate.tableView(tableViewManager.tableView, didSelectRowAt: indexPath) let section = tableViewManager.sections[0] indexPath = IndexPath(row: section.items.count, section: 0) let item = SelectableItem() section.items.append(item) delegate.tableView(tableViewManager.tableView, didSelectRowAt: indexPath) expect(item.check) == 1 item.select(animated: true) expect(item.check) == 2 item.deselect(animated: true) expect(item.check) == 2 } func testEditableRowsWithActions() { let section = tableViewManager.sections.first! let deleteAction = UITableViewRowAction(style: .normal, title: "Delete", handler: { _, _ in print("DeleteAction") }) let editableItem = EditableItem() editableItem.actions = [deleteAction] section.items.append(editableItem) let indexPath = editableItem.indexPath! let actions = delegate.tableView(tableViewManager.tableView, editActionsForRowAt: indexPath) XCTAssertNotNil(actions) XCTAssert(actions!.count == 1) } func testEditableRowsWithConfiguration() { let section = tableViewManager.sections.first! let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in print("DeleteAction") completionHandler(true) } let editableItem = EditableItem() editableItem.configuration = UISwipeActionsConfiguration(actions: [deleteAction]) section.items.append(editableItem) let indexPath = editableItem.indexPath! let configuration = delegate.tableView(tableViewManager.tableView, trailingSwipeActionsConfigurationForRowAt: indexPath) XCTAssertNotNil(configuration) XCTAssertEqual(configuration?.actions.count, 1) } func testViewForHeaderInSection() { let view = delegate.tableView(self.tableViewManager.tableView, viewForHeaderInSection: 0) expect(view).to(beNil()) } func testViewForFooterInSection() { var view: UIView? view = delegate.tableView(self.tableViewManager.tableView, viewForFooterInSection: 0) expect(view).to(beNil()) view = delegate.tableView(self.tableViewManager.tableView, viewForFooterInSection: 1) expect(view).to(beNil()) view = delegate.tableView(self.tableViewManager.tableView, viewForFooterInSection: 2) expect(view).toNot(beNil()) } func testShouldShowMenuForRow() { let section = tableViewManager.sections.first! let firstRow = IndexPath(row: 0, section: 0) var result = delegate.tableView(tableViewManager.tableView, shouldShowMenuForRowAt: firstRow) expect(result).to(beFalse()) let actionableItem = ActionableItem() section.items.replace(with: [actionableItem]) result = delegate.tableView(tableViewManager.tableView, shouldShowMenuForRowAt: firstRow) expect(result).to(beTrue()) } func testCanPerformActionForRow() { let selector = #selector(UIResponderStandardEditActions.copy(_:)) let section = tableViewManager.sections.first! let firstRow = IndexPath(row: 0, section: 0) var result = delegate.tableView(tableViewManager.tableView, canPerformAction: selector, forRowAt: firstRow, withSender: nil) expect(result).to(beFalse()) let actionableItem = ActionableItem() section.items.replace(with: [actionableItem]) result = delegate.tableView(tableViewManager.tableView, canPerformAction: selector, forRowAt: firstRow, withSender: nil) expect(result).to(beTrue()) } func testPerformActionForRow() { let selector = #selector(UIResponderStandardEditActions.copy(_:)) let section = tableViewManager.sections.first! let firstRow = IndexPath(row: 0, section: 0) let actionableItem = ActionableItem() section.items.replace(with: [actionableItem]) delegate.tableView(tableViewManager.tableView, performAction: selector, forRowAt: firstRow, withSender: nil) expect(actionableItem.check) == 1 } }
mit
7c7fcd14794927c13960b252cf70aaa9
33.090343
128
0.676688
5.113551
false
true
false
false
watson-developer-cloud/ios-sdk
Sources/NaturalLanguageUnderstandingV1/Models/KeywordsResult.swift
1
1645
/** * (C) Copyright IBM Corp. 2017, 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** The important keywords in the content, organized by relevance. */ public struct KeywordsResult: Codable, Equatable { /** Number of times the keyword appears in the analyzed text. */ public var count: Int? /** Relevance score from 0 to 1. Higher values indicate greater relevance. */ public var relevance: Double? /** The keyword text. */ public var text: String? /** Emotion analysis results for the keyword, enabled with the `emotion` option. */ public var emotion: EmotionScores? /** Sentiment analysis results for the keyword, enabled with the `sentiment` option. */ public var sentiment: FeatureSentimentResults? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case count = "count" case relevance = "relevance" case text = "text" case emotion = "emotion" case sentiment = "sentiment" } }
apache-2.0
7737d3869a3038f17eb4291e64d5e00f
27.362069
85
0.676596
4.422043
false
false
false
false
okkhoury/SafeNights_iOS
Pods/JSONHelper/JSONHelper/Extensions/Float.swift
1
597
// // Copyright © 2016 Baris Sencan. All rights reserved. // import Foundation extension Float: Convertible { public static func convert<T>(fromValue value: T?) throws -> Float? { guard let value = value else { return nil } if let floatValue = value as? Float { return floatValue } else if let stringValue = value as? String { return Float(stringValue) } else if let doubleValue = value as? Double { return Float(doubleValue) } else if let intValue = value as? Int { return Float(intValue) } throw ConversionError.unsupportedType } }
mit
91a24790afa6769f2a9cc277f711e095
23.833333
71
0.666107
4.350365
false
false
false
false
attaswift/Attabench
OptimizingCollections.attabench/Sources/BTree3.swift
2
12427
// // BTree3.swift // Attabench // // Copyright © 2017 Károly Lőrentey. // private let internalOrder = 16 public struct BTree3<Element: Comparable> { fileprivate var root: Node<Element> public init(order: Int) { self.root = Node(order: order) } } extension BTree3 { public init() { self.init(order: Swift.max(16, cacheSize / (MemoryLayout<Element>.stride << 2))) } } fileprivate class Node<Element: Comparable> { let order: Int var mutationCount: Int64 = 0 var elementCount: Int = 0 let elements: UnsafeMutablePointer<Element> var children: ContiguousArray<Node> = [] init(order: Int) { self.order = order self.elements = .allocate(capacity: order) } deinit { elements.deinitialize(count: elementCount) elements.deallocate(capacity: order) } } extension BTree3 { public func forEach(_ body: (Element) throws -> Void) rethrows { try root.forEach(body) } } extension Node { func forEach(_ body: (Element) throws -> Void) rethrows { if isLeaf { for i in 0 ..< elementCount { try body(elements[i]) } } else { for i in 0 ..< elementCount { try children[i].forEach(body) try body(elements[i]) } try children[elementCount].forEach(body) } } } extension Node { internal func slot(of element: Element) -> (match: Bool, index: Int) { var start = 0 var end = elementCount while start < end { let mid = start + (end - start) / 2 if elements[mid] < element { start = mid + 1 } else { end = mid } } let match = start < elementCount && elements[start] == element return (match, start) } } extension BTree3 { public func contains(_ element: Element) -> Bool { return root.contains(element) } } extension Node { func contains(_ element: Element) -> Bool { let slot = self.slot(of: element) if slot.match { return true } guard !children.isEmpty else { return false } return children[slot.index].contains(element) } } extension BTree3 { fileprivate mutating func makeRootUnique() -> Node<Element> { if isKnownUniquelyReferenced(&root) { return root } root = root.clone() return root } } extension Node { func clone() -> Node { let node = Node(order: order) node.elementCount = self.elementCount node.elements.initialize(from: self.elements, count: self.elementCount) if !isLeaf { node.children.reserveCapacity(order + 1) node.children += self.children } return node } } extension Node { func makeChildUnique(_ slot: Int) -> Node { guard !isKnownUniquelyReferenced(&children[slot]) else { return children[slot] } let clone = children[slot].clone() children[slot] = clone return clone } } extension Node { var maxChildren: Int { return order } var minChildren: Int { return (maxChildren + 1) / 2 } var maxElements: Int { return maxChildren - 1 } var minElements: Int { return minChildren - 1 } var isLeaf: Bool { return children.isEmpty } var isTooLarge: Bool { return elementCount > maxElements } } private struct Splinter<Element: Comparable> { let separator: Element let node: Node<Element> } extension Node { func split() -> Splinter<Element> { let count = self.elementCount let middle = count / 2 let separator = elements[middle] let node = Node(order: self.order) let c = count - middle - 1 node.elements.moveInitialize(from: self.elements + middle + 1, count: c) node.elementCount = c self.elementCount = middle if !isLeaf { node.children.reserveCapacity(self.order + 1) node.children += self.children[middle + 1 ... count] self.children.removeSubrange(middle + 1 ... count) } return Splinter(separator: separator, node: node) } } extension Node { fileprivate func _insertElement(_ element: Element, at slot: Int) { assert(slot >= 0 && slot <= elementCount) (elements + slot + 1).moveInitialize(from: elements + slot, count: elementCount - slot) (elements + slot).initialize(to: element) elementCount += 1 } } extension Node { func insert(_ element: Element) -> (old: Element?, splinter: Splinter<Element>?) { let slot = self.slot(of: element) if slot.match { // The element is already in the tree. return (self.elements[slot.index], nil) } mutationCount += 1 if self.isLeaf { _insertElement(element, at: slot.index) return (nil, self.isTooLarge ? self.split() : nil) } let (old, splinter) = makeChildUnique(slot.index).insert(element) guard let s = splinter else { return (old, nil) } _insertElement(s.separator, at: slot.index) self.children.insert(s.node, at: slot.index + 1) return (old, self.isTooLarge ? self.split() : nil) } } extension BTree3 { @discardableResult public mutating func insert(_ element: Element) -> (inserted: Bool, memberAfterInsert: Element) { let root = makeRootUnique() let (old, splinter) = root.insert(element) if let s = splinter { let root = Node<Element>(order: internalOrder) root.elementCount = 1 root.elements.initialize(to: s.separator) root.children = [self.root, s.node] self.root = root } return (inserted: old == nil, memberAfterInsert: old ?? element) } } private struct PathElement<Element: Comparable> { unowned(unsafe) let node: Node<Element> var slot: Int init(_ node: Node<Element>, _ slot: Int) { self.node = node self.slot = slot } } extension PathElement { var isLeaf: Bool { return node.isLeaf } var isAtEnd: Bool { return slot == node.elementCount } var value: Element? { guard slot < node.elementCount else { return nil } return node.elements[slot] } var child: Node<Element> { return node.children[slot] } } extension PathElement: Equatable { static func ==(left: PathElement, right: PathElement) -> Bool { return left.node === right.node && left.slot == right.slot } } public struct BTree3Index<Element: Comparable>: Comparable { fileprivate weak var root: Node<Element>? fileprivate let mutationCount: Int64 fileprivate var path: [PathElement<Element>] fileprivate var current: PathElement<Element> init(startOf tree: BTree3<Element>) { self.root = tree.root self.mutationCount = tree.root.mutationCount self.path = [] self.current = PathElement(tree.root, 0) while !current.isLeaf { push(0) } } init(endOf tree: BTree3<Element>) { self.root = tree.root self.mutationCount = tree.root.mutationCount self.path = [] self.current = PathElement(tree.root, tree.root.elementCount) } } extension BTree3Index { fileprivate func validate(for root: Node<Element>) { precondition(self.root === root) precondition(self.mutationCount == root.mutationCount) } fileprivate static func validate(_ left: BTree3Index, _ right: BTree3Index) { precondition(left.root === right.root) precondition(left.mutationCount == right.mutationCount) precondition(left.root != nil) precondition(left.mutationCount == left.root!.mutationCount) } } extension BTree3Index { fileprivate mutating func push(_ slot: Int) { path.append(current) current = PathElement(current.node.children[current.slot], slot) } fileprivate mutating func pop() { current = self.path.removeLast() } } extension BTree3Index { fileprivate mutating func formSuccessor() { precondition(!current.isAtEnd, "Cannot advance beyond endIndex") current.slot += 1 if current.isLeaf { while current.isAtEnd, current.node !== root { pop() } } else { while !current.isLeaf { push(0) } } } } extension BTree3Index { fileprivate mutating func formPredecessor() { if current.isLeaf { while current.slot == 0, current.node !== root { pop() } precondition(current.slot > 0, "Cannot go below startIndex") current.slot -= 1 } else { while !current.isLeaf { let c = current.child push(c.isLeaf ? c.elementCount - 1 : c.elementCount) } } } } extension BTree3Index { public static func ==(left: BTree3Index, right: BTree3Index) -> Bool { BTree3Index.validate(left, right) return left.current == right.current } public static func <(left: BTree3Index, right: BTree3Index) -> Bool { BTree3Index.validate(left, right) switch (left.current.value, right.current.value) { case let (.some(a), .some(b)): return a < b case (.none, _): return false default: return true } } } extension BTree3: SortedSet { public typealias Index = BTree3Index<Element> public var startIndex: Index { return Index(startOf: self) } public var endIndex: Index { return Index(endOf: self) } public subscript(index: Index) -> Element { get { index.validate(for: root) return index.current.value! } } public func formIndex(after i: inout Index) { i.validate(for: root) i.formSuccessor() } public func index(after i: Index) -> Index { i.validate(for: root) var i = i i.formSuccessor() return i } public func formIndex(before i: inout Index) { i.validate(for: root) i.formPredecessor() } public func index(before i: Index) -> Index { i.validate(for: root) var i = i i.formPredecessor() return i } } extension BTree3 { public var count: Int { return root.count } } extension Node { var count: Int { return children.reduce(elementCount) { $0 + $1.count } } } public struct BTree3Iterator<Element: Comparable>: IteratorProtocol { let tree: BTree3<Element> var index: BTree3Index<Element> init(_ tree: BTree3<Element>) { self.tree = tree self.index = tree.startIndex } public mutating func next() -> Element? { guard let result = index.current.value else { return nil } index.formSuccessor() return result } } extension BTree3 { public func makeIterator() -> BTree3Iterator<Element> { return BTree3Iterator(self) } } extension BTree3 { public func validate() { _ = root.validate(level: 0) } } extension Node { func validate(level: Int, min: Element? = nil, max: Element? = nil) -> Int { // Check balance. precondition(!isTooLarge) precondition(level == 0 || elementCount >= minElements) if elementCount == 0 { precondition(children.isEmpty) return 0 } // Check element ordering. var previous = min for i in 0 ..< elementCount { let next = elements[i] precondition(previous == nil || previous! < next) previous = next } if isLeaf { return 0 } // Check children. precondition(children.count == elementCount + 1) let depth = children[0].validate(level: level + 1, min: min, max: elements[0]) for i in 1 ..< elementCount { let d = children[i].validate(level: level + 1, min: elements[i - 1], max: elements[i]) precondition(depth == d) } let d = children[elementCount].validate(level: level + 1, min: elements[elementCount - 1], max: max) precondition(depth == d) return depth + 1 } }
mit
3bc5b89dfd6edf5699734bffc49287d3
26.426049
108
0.586365
4.133067
false
false
false
false
macemmi/HBCI4Swift
HBCI4Swift/HBCI4Swift/Source/Message/HBCITanMediaDialogInitMessage.swift
1
1713
// // HBCITANMediaMessage.swift // HBCI4Swift // // Created by Frank Emminghaus on 14.09.19. // Copyright © 2019 Frank Emminghaus. All rights reserved. // import Foundation class HBCITanMediaDialogInitMessage : HBCIDialogInitMessage { override class func newInstance(_ dialog:HBCIDialog) ->HBCITanMediaDialogInitMessage? { if let md = dialog.syntax.msgs["DialogInit"] { if let msg = md.compose() as? HBCIMessage { if let dialogId = dialog.dialogId { if !msg.setElementValue(dialogId, path: "MsgHead.dialogid") { return nil; } if !msg.setElementValue(dialog.messageNum, path: "MsgHead.msgnum") { return nil; } if !msg.setElementValue(dialog.messageNum, path: "MsgTail.msgnum") { return nil; } return HBCITanMediaDialogInitMessage(msg: msg, dialog: dialog); } else { logInfo("No dialog started yet (dialog ID is missing)"); } } } return nil; } override func addTanOrder(_ order:HBCITanOrder) ->Bool { if !order.finalize(nil) { return false; } if let segment = order.segment { if !segment.setElementValue("HKTAB", path: "ordersegcode") { return false; } if order.tanMediumName == nil { if !segment.setElementValue("noref", path: "tanmedia") { return false; } } return addOrder(order, afterSegmentCode: "HKVVB"); } else { logInfo("Order comes without segment!"); } return false; } }
gpl-2.0
7adb321c86e9fa2966660b61084b4463
33.938776
102
0.553154
4.185819
false
false
false
false
theappbusiness/TABResourceLoader
Tests/TABResourceLoaderTests/Mocks/MockResourceService.swift
1
1160
// // MockResourceService.swift // TABResourceLoaderTests // // Created by Luciano Marisi on 10/09/2016. // Copyright © 2016 Kin + Carta. All rights reserved. // import Foundation @testable import TABResourceLoader class MockSessionThatDoesNothing: URLSessionType { public func perform(request: URLRequest, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask { return URLSessionDataTask() } func invalidateAndCancel() { /* not implemented */ } func cancelAllRequests() { /* not implemented */ } } class MockResourceService: ResourceServiceType { required init() {} typealias Resource = MockResource var capturedResource: Resource? var capturedCompletion: ((Result<Resource.Model, Error>) -> Void)? var fetchCallCount: Int = 0 var mockReturnedCancellable: Cancellable? required init(session: URLSessionType = MockSessionThatDoesNothing()) {} func fetch(resource: Resource, completion: @escaping (Result<Resource.Model, Error>) -> Void) -> Cancellable? { capturedResource = resource capturedCompletion = completion fetchCallCount += 1 return mockReturnedCancellable } }
mit
40f5ac6f99a26bedfbd76cd9569ea9f2
27.268293
127
0.735979
4.61753
false
false
false
false
dbahat/conventions-ios
Conventions/Conventions/AppDelegate.swift
1
14301
// // AppDelegate.swift // Conventions // // Created by David Bahat on 1/24/16. // Copyright © 2016 Amai. All rights reserved. // import UIKit import GoogleMaps import Firebase import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? // Current app state (forground or background). Needed to know how to handle incoming notifications. var isActive = true var currentAuthorizationFlow: OIDExternalUserAgentSession? // The message we got in a remote notification. Needed in case we get push notification while in background private var remoteNotificationMessage: String = "" private var remoteNotificationCategory: String = "" private var remoteNotificationId: String = "" func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() UITabBar.appearance().unselectedItemTintColor = Colors.tabBarUnselectedTabColor UITabBar.appearance().tintColor = Colors.tabBarSelectedTabColor UITextView.appearance().linkTextAttributes = [ .foregroundColor: Colors.icon2022_red1 ] self.window!.tintColor = Colors.black GMSServices.provideAPIKey("AIzaSyBDa-mGOL6WFuXsHsu_0XL5RkuEgqho8a0") if #available(iOS 9.0, *) { // Forcing the app to left-to-right layout, since automatic changing of layout direction only // started in iOS9, and we want to support previous iOS versions. UIView.appearance().semanticContentAttribute = UISemanticContentAttribute.forceLeftToRight } // Initiate an async refresh to the updates when opening the app. Convention.instance.updates.refresh(nil) Convention.instance.events.refresh(nil) if let options = launchOptions { // In case we were launched due to user clicking a notification, handle the notification // now (e.g. navigate to a specific page, show the notification in a larger popup...). // Dispatching the task to the message queue so the UI will finish it's init first. if let localNotification = options[UIApplication.LaunchOptionsKey.localNotification] as? UILocalNotification { DispatchQueue.main.async { self.handleNotificationIfNeeded(localNotification) } } if let remoteNotification = options[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] { DispatchQueue.main.async { // In case we got opened from a remove notification, also navigate to the updates page self.showPushNotificationPopup(remoteNotification, shouldNavigateToUpdates: true) } } } if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() for category in NotificationSettings.instance.categories { Messaging.messaging().subscribe(toTopic: category) } // Before iOS 15, defaut tab bar / navigation bar appearance for extended edges apps was different. // Set up iOS 13+ to behave as close as possible to iOS 15 (it can't be identical, so don't apply the same on iOS 15, which looks better) if #unavailable(iOS 15.0) { if #available(iOS 13.0, *) { let tabBarAppearance = UITabBarAppearance() tabBarAppearance.configureWithTransparentBackground() UITabBar.appearance().standardAppearance = tabBarAppearance let navBarAppearance = UINavigationBarAppearance() navBarAppearance.configureWithTransparentBackground() UINavigationBar.appearance().standardAppearance = navBarAppearance } } return true; } func application(_ application: UIApplication, didReceive notification: UILocalNotification) { // If the app is active, show the user an alert dialog instead of perfoming the action if isActive { let alert = getAlertForNotification(notification) guard let vc = self.window?.rootViewController as? UINavigationController else {return} vc.present(alert, animated: true, completion: nil) return; } handleNotificationIfNeeded(notification) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { showPushNotificationPopup(userInfo, shouldNavigateToUpdates: false /* so we won't interupt the user */) } @available(iOS 10, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo showPushNotificationPopup(userInfo, shouldNavigateToUpdates: false) completionHandler() } func applicationDidBecomeActive(_ application: UIApplication) { isActive = true // Clear the app icon badge, in case it was set by a remote notification UIApplication.shared.applicationIconBadgeNumber = 0 // In case we got push notification while in background, show it to the user in a larger dialog // since some notifications may be too long for the iOS default notification area if remoteNotificationMessage != "" { showNotificationPopup(remoteNotificationMessage, category: remoteNotificationCategory) remoteNotificationMessage = "" } } func applicationDidEnterBackground(_ application: UIApplication) { isActive = false } func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) { // Scheduling the feedback reminder here, since we can only schedule notifications after the // notifications settings were registered (and the user gave his concent) NotificationsSchedualer.scheduleConventionFeedbackIfNeeded() NotificationsSchedualer.scheduleConventionFeedbackLastChanceIfNeeded() } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { if let authorizationFlow = self.currentAuthorizationFlow, authorizationFlow.resumeExternalUserAgentFlow(with: url) { self.currentAuthorizationFlow = nil return true } return false } private func showPushNotificationPopup(_ userInfo: [AnyHashable: Any], shouldNavigateToUpdates: Bool) { guard let rawMessage = userInfo["aps"] as? [String: Any], let alert = rawMessage["alert"] as? [String: Any], let message = alert["body"] as? String else { return; } let category = userInfo["topic"] as? String ?? "" let id = userInfo["id"] as? String ?? "" // When the app isn't active we want to allow iOS to show the notification, and only present it // to the user if he clicked the notification if !isActive { remoteNotificationMessage = message remoteNotificationCategory = category remoteNotificationId = id return; } if shouldNavigateToUpdates { guard let vc = self.window?.rootViewController as? UINavigationController else {return} if let updatesVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: String(describing: UpdatesViewController.self)) as? UpdatesViewController { vc.pushViewController(updatesVc, animated: true) } } showNotificationPopup(message, category: category) } private func showNotificationPopup(_ message: String, category: String) { let alert = UIAlertController(title: categoryIdToName(category), message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "שנה הגדרות", style: .default, handler: {action in guard let vc = self.window?.rootViewController as? UINavigationController else {return} if let settingsVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: String(describing: NotificationSettingsViewController.self)) as? NotificationSettingsViewController { vc.pushViewController(settingsVc, animated: true) } })) alert.addAction(UIAlertAction(title: "סגור", style: .default, handler: nil)) guard let vc = self.window?.rootViewController as? UINavigationController else {return} vc.present(alert, animated: true, completion: nil) } private func handleNotificationIfNeeded(_ notification: UILocalNotification?) { handleEventAboutToStartNotificationIfNeeded(notification) handleEventFeedbackReminderNotificationIfNeeded(notification) handleConventionNotificationIfNeeded(notification) } private func handleConventionNotificationIfNeeded(_ notification: UILocalNotification?) { guard let userInfo = notification?.userInfo, let vc = self.window?.rootViewController as? UINavigationController, let feedbackVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: String(describing: ConventionFeedbackViewController.self)) as? ConventionFeedbackViewController else { return } if userInfo[NotificationsSchedualer.CONVENTION_FEEDBACK_INFO] as? Bool != nil { vc.pushViewController(feedbackVc, animated: true) } else if userInfo[NotificationsSchedualer.CONVENTION_FEEDBACK_LAST_CHANCE_INFO] as? Bool != nil { vc.pushViewController(feedbackVc, animated: true) } } private func handleEventAboutToStartNotificationIfNeeded(_ notification: UILocalNotification?) { guard let userInfo = notification?.userInfo, let eventId = userInfo[NotificationsSchedualer.EVENT_ABOUT_TO_START_INFO] as? String, let event = Convention.instance.events.getAll().filter({$0.id == eventId}).first, let vc = self.window?.rootViewController as? UINavigationController, let eventVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: String(describing: EventViewController.self)) as? EventViewController else { return } eventVc.event = event vc.pushViewController(eventVc, animated: true) } private func handleEventFeedbackReminderNotificationIfNeeded(_ notification: UILocalNotification?) { guard let userInfo = notification?.userInfo, let eventId = userInfo[NotificationsSchedualer.EVENT_FEEDBACK_REMINDER_INFO] as? String, let event = Convention.instance.events.getAll().filter({$0.id == eventId}).first, let vc = self.window?.rootViewController as? UINavigationController, let eventVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: String(describing: EventViewController.self)) as? EventViewController else { return } eventVc.event = event eventVc.feedbackViewOpen = true vc.pushViewController(eventVc, animated: true) } private func getAlertForNotification(_ notification: UILocalNotification) -> UIAlertController { // Using hardcoded alert title instead of the notification one, since iOS8 didn't have // notification title if isConventionFeedbackNotification(notification) { let alert = UIAlertController(title: "עזור לנו להשתפר", message: notification.alertBody, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "מלא פידבק לספטיבל", style: .default, handler: {action -> Void in self.handleNotificationIfNeeded(notification) })); alert.addAction(UIAlertAction(title: "בטל", style: .cancel, handler: nil)) return alert } else { let alert = UIAlertController(title: "אירוע עומד להתחיל", message: notification.alertBody, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "פתח אירוע", style: .default, handler: {action -> Void in self.handleNotificationIfNeeded(notification) })); alert.addAction(UIAlertAction(title: "בטל", style: .cancel, handler: nil)) return alert } } private func isConventionFeedbackNotification(_ notification: UILocalNotification) -> Bool { return notification.userInfo?[NotificationsSchedualer.CONVENTION_FEEDBACK_INFO] as? Bool == true } private func categoryIdToName(_ category: String) -> String { if category == NotificationSettings.Category.test.toString() { return "בדיקות" } if category == NotificationSettings.Category.events.toString() { return "אירועים" } return "התראה" } }
apache-2.0
7f93cdc85de476ad88ddd84f35be40b4
46.691275
215
0.662961
5.483025
false
false
false
false
chanhx/iGithub
iGithub/Views/SegmentHeaderView.swift
2
5478
// // SegmentHeaderView.swift // iGithub // // Created by Chan Hocheung on 8/14/16. // Copyright © 2016 Hocheung. All rights reserved. // import UIKit enum TrendingType { case repositories case users } protocol SegmentHeaderViewDelegate: class { func headerView(_ view: SegmentHeaderView, didSelectSegmentTitle: TrendingType) } class SegmentHeaderView: UIView { weak var delegate: SegmentHeaderViewDelegate? var title: TrendingType = .repositories { didSet { reposButton.isSelected = title == .repositories usersButton.isSelected = title == .users delegate?.headerView(self, didSelectSegmentTitle: title) } } let titleLabel = TTTAttributedLabel(frame: CGRect.zero) let reposButton = SegmentButton(type: .custom) let usersButton = SegmentButton(type: .custom) override init(frame: CGRect) { super.init(frame: frame) clipsToBounds = false backgroundColor = UIColor(netHex: 0xFAFAFA) configureSubviews() layout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureSubviews() { titleLabel.font = UIFont.systemFont(ofSize: 14) titleLabel.layer.isOpaque = true titleLabel.backgroundColor = backgroundColor titleLabel.linkAttributes = [NSAttributedString.Key.foregroundColor: UIColor(netHex: 0x4078C0)] reposButton.setTitle("Repositories", for: UIControl.State()) reposButton.addTarget(self, action: #selector(SegmentHeaderView.buttonTouched(_:)), for: .touchUpInside) usersButton.setTitle("Users", for: UIControl.State()) usersButton.addTarget(self, action: #selector(SegmentHeaderView.buttonTouched(_:)), for: .touchUpInside) } func layout() { let separator = UIView() separator.backgroundColor = UIColor(netHex: 0xDDDDDD) let hStackView = UIStackView(arrangedSubviews: [reposButton, separator, usersButton]) hStackView.axis = .horizontal hStackView.alignment = .fill hStackView.distribution = .fill addSubviews([titleLabel, hStackView]) let margins = layoutMarginsGuide NSLayoutConstraint.activate([ separator.widthAnchor.constraint(equalToConstant: 1), reposButton.widthAnchor.constraint(equalTo: usersButton.widthAnchor), titleLabel.topAnchor.constraint(equalTo: margins.topAnchor, constant: 8), titleLabel.bottomAnchor.constraint(equalTo: hStackView.topAnchor, constant: -12), titleLabel.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 8), titleLabel.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -8), hStackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 1), hStackView.leadingAnchor.constraint(equalTo: leadingAnchor), hStackView.trailingAnchor.constraint(equalTo: trailingAnchor), hStackView.heightAnchor.constraint(equalToConstant: 43) ]) } @objc func buttonTouched(_ button: UIButton) { if button.isSelected {return} title = reposButton.isSelected ? .users : .repositories } class SegmentButton: UIButton { fileprivate let topBorder = UIView() fileprivate let bottomBorder = UIView() override var isSelected: Bool { didSet { topBorder.isHidden = !isSelected bottomBorder.isHidden = isSelected } } override init(frame: CGRect) { super.init(frame: frame) adjustsImageWhenHighlighted = false titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.medium) setTitleColor(UIColor(netHex: 0x4078C0), for: UIControl.State()) setTitleColor(UIColor(netHex: 0x444444), for: .selected) setBackgroundImage(UIImage.imageWithColor(UIColor.white), for: .selected) setBackgroundImage(UIImage.imageWithColor(UIColor(netHex: 0xFAFAFA)), for: UIControl.State()) addBorders() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addBorders() { topBorder.isHidden = true topBorder.backgroundColor = UIColor(netHex: 0xD26911) bottomBorder.backgroundColor = UIColor(netHex: 0xDDDDDD) self.addSubviews([topBorder, bottomBorder]) NSLayoutConstraint.activate([ topBorder.topAnchor.constraint(equalTo: topAnchor), topBorder.leadingAnchor.constraint(equalTo: leadingAnchor), topBorder.trailingAnchor.constraint(equalTo: trailingAnchor), topBorder.heightAnchor.constraint(equalToConstant: 2), bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor), bottomBorder.leadingAnchor.constraint(equalTo: leadingAnchor), bottomBorder.trailingAnchor.constraint(equalTo: trailingAnchor), bottomBorder.heightAnchor.constraint(equalToConstant: 1) ]) } } }
gpl-3.0
b7f4d6cb66cbbd03c661ea2a3cd4c854
36.772414
112
0.635019
5.487976
false
false
false
false
khizkhiz/swift
test/1_stdlib/ImplicitlyUnwrappedOptional.swift
2
1625
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test var x : Int! = .none if x != nil { print("x is non-empty!") } else { print("an empty optional is logically false") } // CHECK: an empty optional is logically false x = .some(0) if x != nil { print("a non-empty optional is logically true") } else { print("x is empty!") } // CHECK: a non-empty optional is logically true class C {} var c : C! = C() if c === nil { print("x is nil!") } else { print("a non-empty class optional should not equal nil") } // CHECK: a non-empty class optional should not equal nil c = nil if c === nil { print("an empty class optional should equal nil") } else { print("x is not nil!") } // CHECK: an empty class optional should equal nil import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif import Swift var ImplicitlyUnwrappedOptionalTests = TestSuite("ImplicitlyUnwrappedOptional") ImplicitlyUnwrappedOptionalTests.test("flatMap") { // FIXME(19798684): can't call map or flatMap on ImplicitlyUnwrappedOptional // let half: Int32 -> Int16! = // { if $0 % 2 == 0 { return Int16($0 / 2) } else { return .none } } // expectOptionalEqual(2 as Int16, half(4)) // expectEmpty(half(3)) // expectEmpty((.none as Int!).flatMap(half)) // expectOptionalEqual(2 as Int16, (4 as Int!).flatMap(half)) // expectEmpty((3 as Int!).flatMap(half)) } runAllTests()
apache-2.0
f4f11cb505c158503b518357cba01dbd
22.897059
79
0.686154
3.651685
false
true
false
false
AlbertMontserrat/AMGLanguageManager
AMGLanguageManager/Classes/AMGLanguageManager.swift
1
2627
// // AMGLanguageManager.swift // Albert Montserrat // // Created by Albert Montserrat on 08/03/17. // Copyright © 2017 Albert Montserrat. All rights reserved. // import Foundation public class AMGLanguageManager { public static let shared = AMGLanguageManager() public var languages = [String]() public func initialize(withLanguages languages: [String]) { self.languages = languages } public func setLanguage(name:String) { if !self.languages.contains(name) { return } UserDefaults.standard.set(name, forKey: "AMGSelectedLanguage") UserDefaults.standard.synchronize() } public func getLanguage() -> String? { let savedLanguage = UserDefaults.standard.string(forKey: "AMGSelectedLanguage") if let language = savedLanguage { if !self.languages.contains(language) { UserDefaults.standard.set(nil, forKey: "AMGSelectedLanguage") UserDefaults.standard.synchronize() return self.getLanguage() } return language } else { guard self.languages.count != 0 else { return nil } let preferredLanguages = Locale.preferredLanguages for preferredLanguage in preferredLanguages { if self.languages.contains(preferredLanguage) { self.setLanguage(name: preferredLanguage) return self.getLanguage() } } self.setLanguage(name: self.languages[0]) return self.getLanguage() } } public func localizedBundle() -> Bundle? { let bundlePath = Bundle.main.path(forResource: self.getLanguage(), ofType: "lproj") guard let path = bundlePath else { return nil } let bundle = Bundle(path: path) return bundle } public func localizedString(key:String) -> String { guard let bundle = localizedBundle() else { return key } return bundle.localizedString(forKey: key, value: "", table: "Localizable") } public func localizedPath(forResource name: String?, ofType ext: String?) -> String? { guard let bundle = localizedBundle() else { return nil } return bundle.path(forResource: name, ofType: ext) } } public extension String { public func amgLocalized() -> String { return AMGLanguageManager.shared.localizedString(key: self) } }
mit
38288568b214c426969f95dcdfe54f06
29.183908
91
0.586443
5.138943
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Common/Extensions/Decimal+Helpers.swift
1
1806
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit extension Decimal { init(_ string: String) { if let _ = Decimal(string: string) { self.init(string: string)! return } self.init(string: "0")! } var string: String { return String(describing: self) } var double: Double { return NSDecimalNumber(decimal:self).doubleValue } var float: Float { return NSDecimalNumber(decimal:self).floatValue } var int64: Int64 { return NSDecimalNumber(decimal:self).int64Value } var int: Int { return NSDecimalNumber(decimal:self).intValue } func abbrevation() -> String { let numFormatter = NumberFormatter() typealias Abbrevation = (threshold: Decimal, divisor: Decimal, suffix: String) let abbreviations:[Abbrevation] = [(0, 1, ""), (1000.0, 1000.0, "K"), (100_000.0, 1_000_000.0, "M"), (100_000_000.0, 1_000_000_000.0, "B")] // you can add more ! let abbreviation: Abbrevation = { var prevAbbreviation = abbreviations[0] for tmpAbbreviation in abbreviations { if self < tmpAbbreviation.threshold { break } prevAbbreviation = tmpAbbreviation } return prevAbbreviation } () let value = self / abbreviation.divisor numFormatter.positiveSuffix = abbreviation.suffix numFormatter.negativeSuffix = abbreviation.suffix numFormatter.allowsFloats = true numFormatter.minimumIntegerDigits = 1 numFormatter.minimumFractionDigits = 0 numFormatter.maximumFractionDigits = 1 return numFormatter.string(for: value) ?? self.string } }
gpl-3.0
ee988ec74b0a6112dfa5fd1c1a03431e
24.785714
82
0.61108
4.616368
false
false
false
false
iOSDevLog/InkChat
InkChat/Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationBallClipRotateMultiple.swift
1
3270
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallClipRotateMultiple: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 0.7 // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let bigCircleSize: CGFloat = size.width let smallCircleSize: CGFloat = size.width / 2 let longDuration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let circleLayer1 = makeCircleLayerOf(shape: .ringTwoHalfHorizontal, duration: longDuration, timingFunction: timingFunction, layerSize: layer.frame.size, size: bigCircleSize, color: color, reverse: false) let circleLayer2 = makeCircleLayerOf(shape: .ringTwoHalfVertical, duration: longDuration, timingFunction: timingFunction, layerSize: layer.frame.size, size: smallCircleSize, color: color, reverse: true) layer.addSublayer(circleLayer1) layer.addSublayer(circleLayer2) } } // MARK: - Setup private extension ActivityIndicatorAnimationBallClipRotateMultiple { func makeAnimation(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, reverse: Bool) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = [timingFunction, timingFunction] if !reverse { rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi] } else { rotateAnimation.values = [0, -CGFloat.pi, -2 * CGFloat.pi] } rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } // swiftlint:disable:next function_parameter_count func makeCircleLayerOf(shape: ActivityIndicatorShape, duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layerSize: CGSize, size: CGFloat, color: UIColor, reverse: Bool) -> CALayer { let circleLayer = shape.makeLayer(size: CGSize(width: size, height: size), color: color) let frame = CGRect(x: (layerSize.width - size) / 2, y: (layerSize.height - size) / 2, width: size, height: size) let animation = makeAnimation(duration: duration, timingFunction: timingFunction, reverse: reverse) circleLayer.frame = frame circleLayer.add(animation, forKey: "animation") return circleLayer } }
apache-2.0
d526cbb326c1261015e5904c97bfa23c
35.333333
117
0.688379
5.07764
false
false
false
false