repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kevin-zqw/play-swift
refs/heads/master
swift-lang/07. Closures.playground/section-1.swift
apache-2.0
1
// ------------------------------------------------------------------------------------------------ // Things to know: // // * Closures are blocks of code. // // * The can be passed as parameters to functions much like Function Types. In fact, functions // are a special case of closures. // // * Closures of all types (including nested functions) employ a method of capturing the surrounding // context in which is is defined, allowing it to access constants and variables from that // context. // ------------------------------------------------------------------------------------------------ // Closures can use constant, variable, inout, variadics, tuples for their parameters. They can // return any value, including Tuples. They cannot, however, have default parameters. // // The basic syntax is: // // { (parameters) -> return_type in // ... statements ... // } // // Here's an example of a simple String comparison closure that might be used for sorting Strings: // // { (s1: String, s2: String) -> Bool in // return s1 < s2 // } // // Here's an example using Swift's 'sort' member function. It's important to note that this // function receives a single closure. // // These can be a little tricky to read if you're not used to them. To understand the syntax, pay // special attention to the curly braces that encapsulate the closure and the parenthesis just // outside of those curly braces: let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] var reversed = names.sort({ (s1: String, s2: String) -> Bool in return s1 > s2 }) reversed = names.sort({ (s1: String, s2: String) -> Bool in return s1 > s2 }) /* Closure expression syntax { (parameters) -> return type in statements } */ reversed = names.sort({(s1: String, s2: String) -> Bool in return s1 > s2 }) reversed = names.sort({ s1, s2 in s1 > s2 }) // ------------------------------------------------------------------------------------------------ // Inferring Type from Context // // Like functions, closures have a type. // // If the type is known (as is always the case when passing a closure as a parameter to a function) // then the return type of the closure can be inferred, allowing us to simplify the syntax of our // call to sort. // // The following call is identical to the one above with the exception that "-> Bool" was removed: reversed = names.sort({ (s1: String, s2: String) in return s1 > s2 }) // Just as the return type can be inferred, so can the parameter types. This allows us to simplify // the syntax a bit further by removing the type annotations from the closure's parameters. // // The following call is identical to the one above with the exception that the parameter type // annotations (": String") have been removed: reversed = names.sort({ (s1, s2) in return s1 > s2 }) // Since all types can be inferred and we're not using any type annotation on the parameters, // we can simplify a bit further by removing the paranthesis around the parameters. We'll also put // it all on a single line, since it's a bit more clear now: reversed = names.sort({ s1, s2 in return s1 > s2 }) // If the closuere has only a single expression, then the return statement is also inferred. When // this is the case, the closure returns the value of the single expression: reversed = names.sort({ s1, s2 in s1 > s2 }) // We're not done simplifying yet. It turns out we can get rid of the parameters as well. If we // remove the parameters, we can still access them because Swift provides shorthand names to // parameters passed to inline closures. To access the first parameter, use $0. The second // parameter would be $1 and so on. // // Here's what that would might like (this will not compile - yet): // // reversed = names.sort({ s1, s2 in $0 > $1 }) // // This won't compile because you're not allowed to use shorthand names if you specify the // parameter list. Therefore, we need to remove those in order to get it to compile. This makes // for a very short inline closure: reversed = names.sort({ $0 > $1 }) // Interestingly enough, the operator < for String types is defined as: // // (String, String) -> Bool // // Notice how this is the same as the closure's type for the sort() routine? Wouldn't it be // nice if we could just pass in this operator? It turns out that for inline closures, Swift allows // exactly this. // // Here's what that looks like: reversed = names.sort(>) var mapped = names.map { str in str.characters.count } // If you want to just sort a mutable copy of an array (in place) you can use the sort() method var mutableCopyOfNames = names mutableCopyOfNames.sort(>) mutableCopyOfNames // ------------------------------------------------------------------------------------------------ // Trailing Closures // // Trailing Closures refer to closures that are the last parameter to a function. This special-case // syntax allows a few other syntactic simplifications. In essence, you can move trailing closures // just outside of the parameter list. Swift's sort() member function uses a trailing closure for // just this reason. // // Let's go back to our original call to sort with a fully-formed closure and move the closure // outside of the parameter list. This resembles a function definition, but it's a function call. reversed = names.sort { (s1: String, s2: String) -> Bool in return s1 > s2 } // Note that the opening brace for the closure must be on the same line as the function call's // ending paranthesis. This is the same functinon call with the starting brace for the closure // moved to the next line. This will not compile: // // reversed = sort(names) // { // (s1: String, s2: String) -> Bool in // return s1 > s2 // } // Let's jump back to our simplified closure ({$0 > $1}) and apply the trailing closure principle: reversed = names.sort {$0 > $1} // Another simplification: if a function receives just one closure as the only parameter, you can // remove the () from the function call. First, we'll need a function that receives just one // parameter, a closure: func returnValue(f: () -> Int) -> Int { // Simply return the value that the closure 'f' returns return f() } // Now let's call the function with the parenthesis removed and a trailing closure: returnValue {return 6} // And if we apply the simplification described earlier that implies the return statement for // single-expresssion closures, it simplifies to this oddly-looking line of code: returnValue {6} // ------------------------------------------------------------------------------------------------ // Capturing Values // // The idea of capturing is to allow a closure to access the variables and constants in their // surrounding context. // // For example, a nested function can access contstans and variables from the function in which // it is defined. If this nested function is returned, each time it is called, it will work within // that "captured" context. // // Here's an example that should help clear this up: func makeIncrementor(forIncrement amount: Int) -> () -> Int { var runningTotal = 0 // runningTotal and amount are 'captured' for the nested function incrementor() func incrementor() -> Int { runningTotal += amount return runningTotal } // We return the nested function, which has captured it's environment return incrementor } // Let's get a copy of the incrementor: var incrementBy10 = makeIncrementor(forIncrement: 10) // Whenever we call this function, it will return a value incremented by 10: incrementBy10() // returns 10 incrementBy10() // returns 20 // We can get another copy of incrementor that works on increments of 3. var incrementBy3 = makeIncrementor(forIncrement: 3) incrementBy3() // returns 3 incrementBy3() // returns 6 // 'incrementBy10' and 'incrementBy3' each has its own captured context, so they work independently // of each other. incrementBy10() // returns 30 // Closures are reference types, which allows us to assign them to a variable. When this happens, // the captured context comes along for the ride. var copyIncrementBy10 = incrementBy10 copyIncrementBy10() // returns 40 // If we request a new incremntor that increments by 10, it will have a separate and unique captured // context: var anotherIncrementBy10 = makeIncrementor(forIncrement: 10) anotherIncrementBy10() // returns 10 // Our first incrementor is still using its own context: incrementBy10() // returns 50 // Nonescaping Closures // Use @noescape to mark your closure will not escape from function func myAdder(@noescape adder: (a: Int, b: Int) -> Int) -> Int { return adder(a: 1, b: 2) } // Autoclosures func serveCustomer(@autoclosure customerProvider: () -> String) { print("Now serving \(customerProvider())!") } // Now you use pass a statement to this function var tempArray = ["1", "kevin", "hello"] serveCustomer(tempArray.removeLast()) // @autoclosure attribute implies the @noescape attribute,if you want to escape, use: // @autoclosure(escaping)
39d58c1c4442cf6e2663cecefbd1ee32
35.554656
100
0.680253
false
false
false
false
m-alani/contests
refs/heads/master
hackerrank/ClimbingTheLeaderboard.swift
mit
1
// // ClimbingTheLeaderboard.swift // // Practice solution - Marwan Alani - 2021 // // Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/climbing-the-leaderboard/ // Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code // func climbingLeaderboard(ranked: [Int], player: [Int]) -> [Int] { var output = [Int]() var rankings = removeDuplicates(from: ranked) for score in player { while ((rankings.last ?? 0) <= score && !rankings.isEmpty) { _ = rankings.popLast() } output.append((rankings.isEmpty) ? 1 : rankings.count + 1) } return output } func removeDuplicates(from arr: [Int]) -> [Int] { var uniques = [Int]() for score in arr { if score != uniques.last { uniques.append(score) } } return uniques }
85131e837ba3bd1a64b6652f11d36b85
27.030303
120
0.611892
false
false
false
false
ThumbWorks/i-meditated
refs/heads/master
Carthage/Checkouts/RxSwift/RxTests/Recorded.swift
mit
4
// // Recorded.swift // Rx // // Created by Krunoslav Zaher on 2/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift import Swift /** Record of a value including the virtual time it was produced on. */ public struct Recorded<Element> : CustomDebugStringConvertible { /** Gets the virtual time the value was produced on. */ public let time: TestTime /** Gets the recorded value. */ public let value: Element public init(time: TestTime, event: Element) { self.time = time self.value = event } } extension Recorded { /** A textual representation of `self`, suitable for debugging. */ public var debugDescription: String { return "\(value) @ \(time)" } } public func == <T: Equatable>(lhs: Recorded<T>, rhs: Recorded<T>) -> Bool { return lhs.time == rhs.time && lhs.value == rhs.value } public func == <T: Equatable>(lhs: Recorded<Event<T>>, rhs: Recorded<Event<T>>) -> Bool { return lhs.time == rhs.time && lhs.value == rhs.value }
f5e81c5cc9a502c956d832e98bec21ae
20.8
89
0.629936
false
false
false
false
Melon-IT/base-model-swift
refs/heads/master
MelonBaseModel/MelonBaseModel/MPropertyListData.swift
mit
1
// // MBFBaseDataParser.swift // MelonBaseModel // // Created by Tomasz Popis on 10/06/16. // Copyright © 2016 Melon. All rights reserved. // import Foundation /* public protocol MBFDataParserProtocol { var parserDataListener: MBFParserDataListener? {set get} var resource: Any? {set get} func load() func save() func clear() func delete() func parse(completionHandler: ((Bool) -> Void)?) } public protocol MBFParserDataListener { func dataDidParse(success: Bool, type: UInt?) } */ public class MPropertyList<Type> { public var resourcesName: String? fileprivate var resources: Type? public init() {} public init(resources: String) { self.resourcesName = resources } fileprivate func readResourcesFromBundle() { if let path = Bundle.main.path(forResource: resourcesName, ofType: "plist"), let content = try? Data(contentsOf: URL(fileURLWithPath: path)) { self.resources = (try? PropertyListSerialization.propertyList(from: content, options: [], format: nil)) as? Type } } fileprivate func cleanResources() { self.resources = nil } } public class MBundleDictionaryPropertyList<Type>: MPropertyList<Dictionary<String,Type>> { public func read() { self.readResourcesFromBundle(); } public func clean() { super.cleanResources() } public var numberOfItems: Int { var result = 0; if let counter = self.resources?.count { result = counter } return result } public subscript(key: String) -> Type? { return self.resources?[key] } } public class MBundleArrayPropertyList<Type>: MPropertyList<Array<Type>> { public func read() { self.readResourcesFromBundle(); } public func clean() { super.cleanResources() } public var numberOfItems: Int { var result = 0; if let counter = self.resources?.count { result = counter } return result } public subscript(index: Int) -> Type? { var result: Type? if let counter = self.resources?.count, index >= 0 && index < counter { result = self.resources?[index] } return result } } /* open class MBFBaseDataParser { public init() { } open func loadData() { } open func saveData() { } open func parseData(data: AnyObject?) { } open func loadFromDefaults(key: String) -> AnyObject? { let defaults = UserDefaults.standard return defaults.object(forKey: key) as AnyObject? } open func saveToDefaults(key: String, object: AnyObject?) { let defaults = UserDefaults.standard defaults.set(object, forKey: key) defaults.synchronize() } open func uniqueUserKey(userId: String, separator: String, suffix: String) -> String { return "\(userId)\(separator)\(suffix)" } } */
cda29c1efe1073838fe1b1ae04a7545b
17.929487
91
0.624788
false
false
false
false
joshua7v/ResearchOL-iOS
refs/heads/master
ResearchOL/Class/Me/Controller/ROLEditController.swift
mit
1
// // ROLEditController.swift // ResearchOL // // Created by Joshua on 15/5/16. // Copyright (c) 2015年 SigmaStudio. All rights reserved. // import UIKit protocol ROLEditControllerDelegate: NSObjectProtocol { func editControllerSaveButtonDidClicked(editController: ROLEditController, item: ROLEditItem, value: String) } class ROLEditController: SESettingViewController { var delegate: ROLEditControllerDelegate? var checkboxes: NSMutableArray = NSMutableArray() var isSingleChoice = true var textField = UITextField() var indexPath = NSIndexPath() var item: ROLEditItem = ROLEditItem() { didSet { self.title = item.title if item.type == 2 { var group = self.addGroup() var i = SESettingTextFieldItem(placeholder: self.item.title) self.textField = i.textField group.items = [i] group.header = "请输入" } else if item.type == 1 { var group = self.addGroup() var items: NSMutableArray = NSMutableArray() for i in 0 ..< item.choices.count { // var cell = SESettingArrowItem(title: item.choices[i]) var cell = SESettingCheckboxItem(title: item.choices[i], checkState: false) cell.checkbox.addTarget(self, action: "handleCheckboxTapped:", forControlEvents: UIControlEvents.TouchDown) cell.checkbox.userInteractionEnabled = false self.checkboxes.addObject(cell.checkbox) items.addObject(cell) } group.items = items as [AnyObject] group.header = "请选择" } } } @objc private func handleCheckboxTapped(sender: M13Checkbox) { if self.isSingleChoice == false { if sender.checkState.value == M13CheckboxStateChecked.value { sender.checkState = M13CheckboxStateUnchecked } else { sender.checkState = M13CheckboxStateChecked } return } if sender.checkState.value == M13CheckboxStateChecked.value { } else { for i:M13Checkbox in self.checkboxes.copy() as! [M13Checkbox] { if i == sender { i.checkState = M13CheckboxStateChecked } else { i.checkState = M13CheckboxStateUnchecked } } } } override func viewDidLoad() { super.viewDidLoad() self.title = "编辑信息" self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBtnDidClicked") self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: UIBarButtonItemStyle.Plain, target: self, action: "saveBtnDidClicked") } @objc private func saveBtnDidClicked() { println(item.title) var value = "" if item.type == 1 { if self.isSingleChoice { for i in enumerate(self.checkboxes.copy() as! [M13Checkbox]) { if i.element.checkState.value == M13CheckboxStateChecked.value { value = self.item.choices[i.index] } } } else { for i in enumerate(self.checkboxes.copy() as! [M13Checkbox]) { if i.element.checkState.value == M13CheckboxStateChecked.value { value = value.stringByAppendingString("\(self.item.choices[i.index]), ") } } var newValue: NSString = value value = newValue.substringToIndex(newValue.length - 2) } } else if item.type == 2 { value = self.textField.text } ROLUserInfoManager.sharedManager.saveAttributeForCurrentUser(item.title, value: value, success: { (finished) -> Void in println("attribute set success") self.dismissViewControllerAnimated(true, completion: { () -> Void in }) }) { (error) -> Void in println("error \(error)") if error.code == 127 { SEProgressHUDTool.showError("请输入正确的手机号", toView: self.navigationController?.view) } } // change text in superview if (self.delegate?.respondsToSelector("editControllerSaveButtonDidClicked:") != nil) { self.delegate?.editControllerSaveButtonDidClicked(self, item: self.item, value: value) } } @objc private func cancelBtnDidClicked() { self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ROLEditController: UITabBarDelegate { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) var checkbox = self.checkboxes[indexPath.row] as! M13Checkbox self.handleCheckboxTapped(checkbox) } }
24c81ebc76414b03ac9dcd7f15b7a2d0
37.106383
157
0.579564
false
false
false
false
hilen/TSWeChat
refs/heads/master
TSWeChat/Helpers/NSDictionary+Extension.swift
mit
1
// // NSDictionary+Extension.swift // TSWeChat // // Created by Hilen on 11/23/15. // Copyright © 2015 Hilen. All rights reserved. // import Foundation public extension Dictionary { /// Merges the dictionary with dictionaries passed. The latter dictionaries will override /// values of the keys that are already set /// /// :param dictionaries A comma seperated list of dictionaries mutating func merge<K, V>(_ dictionaries: Dictionary<K, V>...) { for dict in dictionaries { for (key, value) in dict { self.updateValue(value as! Value, forKey: key as! Key) } } } func combine(_ targetDictionary: Dictionary<String, AnyObject>, resultDictionary: Dictionary<String, AnyObject>) -> Dictionary<String, AnyObject> { var temp = resultDictionary for (key, value) in targetDictionary { temp[key] = value } return temp } } public func + <K, V>(left: Dictionary<K, V>, right: Dictionary<K, V>) -> Dictionary<K, V> { var map = Dictionary<K, V>() for (k, v) in left { map[k] = v } for (k, v) in right { map[k] = v } return map }
0adac8cdaa1eb025c9438f6601bc85c6
25.755556
151
0.597176
false
false
false
false
jovito-royeca/Cineko
refs/heads/master
Cineko/StartViewController.swift
apache-2.0
1
// // LoginViewController.swift // Cineko // // Created by Jovit Royeca on 04/04/2016. // Copyright © 2016 Jovito Royeca. All rights reserved. // import UIKit import JJJUtils import MBProgressHUD import MMDrawerController class StartViewController: UIViewController { // MARK: Actions @IBAction func loginAction(sender: UIButton) { do { if let requestToken = try TMDBManager.sharedInstance.getAvailableRequestToken() { let urlString = "\(TMDBConstants.AuthenticateURL)/\(requestToken)" performSegueWithIdentifier("presentLoginFromStart", sender: urlString) } else { let completion = { (error: NSError?) in if let error = error { performUIUpdatesOnMain { MBProgressHUD.hideHUDForView(self.view, animated: true) JJJUtil.alertWithTitle("Error", andMessage:"\(error.userInfo[NSLocalizedDescriptionKey]!)") } } else { do { if let requestToken = try TMDBManager.sharedInstance.getAvailableRequestToken() { performUIUpdatesOnMain { let urlString = "\(TMDBConstants.AuthenticateURL)/\(requestToken)" MBProgressHUD.hideHUDForView(self.view, animated: true) self.performSegueWithIdentifier("presentLoginFromStart", sender: urlString) } } } catch {} } } MBProgressHUD.showHUDAddedTo(view, animated: true) try TMDBManager.sharedInstance.authenticationTokenNew(completion) } } catch {} } @IBAction func skipLoginAction(sender: UIButton) { performSegueWithIdentifier("presentDrawerFromStart", sender: sender) } // MARK: Overrides override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "presentLoginFromStart" { if let vc = segue.destinationViewController as? LoginViewController { vc.authenticationURLString = sender as? String vc.delegate = self } } else if segue.identifier == "presentDrawerFromStart" { // no op } } } // MARK: LoginViewControllerDelegate extension StartViewController : LoginViewControllerDelegate { func loginSuccess(viewController: UIViewController) { if TMDBManager.sharedInstance.hasSessionID() { if let controller = self.storyboard!.instantiateViewControllerWithIdentifier("DrawerController") as? MMDrawerController { viewController.presentViewController(controller, animated: true, completion: nil) } } else { viewController.dismissViewControllerAnimated(true, completion: nil) } } }
48cb4391a3c0a2b4408fa8e5672e5f67
38.135802
133
0.564669
false
false
false
false
mcudich/TemplateKit
refs/heads/master
Examples/Twitter/Source/App.swift
mit
1
// // App.swift // TwitterClientExample // // Created by Matias Cudich on 10/27/16. // Copyright © 2016 Matias Cudich. All rights reserved. // import Foundation import TemplateKit import CSSLayout struct AppState: State { var tweets = [Tweet]() } func ==(lhs: AppState, rhs: AppState) -> Bool { return lhs.tweets == rhs.tweets } class App: Component<AppState, DefaultProperties, UIView> { override func didBuild() { TwitterClient.shared.fetchSearchResultsWithQuery(query: "donald trump") { tweets in self.updateState { state in state.tweets = tweets } } } override func render() -> Template { var properties = DefaultProperties() properties.core.layout = self.properties.core.layout var tree: Element! if state.tweets.count > 0 { tree = box(properties, [ renderTweets() ]) } else { properties.core.layout.alignItems = CSSAlignCenter properties.core.layout.justifyContent = CSSJustifyCenter tree = box(properties, [ activityIndicator(ActivityIndicatorProperties(["activityIndicatorViewStyle": UIActivityIndicatorViewStyle.gray])) ]) } return Template(tree) } @objc func handleEndReached() { guard let maxId = state.tweets.last?.id else { return } TwitterClient.shared.fetchSearchResultsWithQuery(query: "donald trump", maxId: maxId) { tweets in self.updateState { state in state.tweets.append(contentsOf: tweets.dropFirst()) } } } private func renderTweets() -> Element { var properties = TableProperties() properties.core.layout.flex = 1 properties.tableViewDataSource = self properties.items = [TableSection(items: state.tweets, hashValue: 0)] properties.onEndReached = #selector(App.handleEndReached) properties.onEndReachedThreshold = 700 return table(properties) } } extension App: TableViewDataSource { func tableView(_ tableView: TableView, elementAtIndexPath indexPath: IndexPath) -> Element { var properties = TweetProperties() properties.tweet = state.tweets[indexPath.row] properties.core.layout.width = self.properties.core.layout.width return component(TweetItem.self, properties) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return state.tweets.count } }
eac16b392d0815e73c333bbd621b9770
26.694118
121
0.697111
false
false
false
false
rbailoni/SOSHospital
refs/heads/master
SOSHospital/SOSHospital/Hospital.swift
mit
1
// // Hospital.swift // SOSHospital // // Created by William kwong huang on 27/10/15. // Copyright © 2015 Quaddro. All rights reserved. // import UIKit import MapKit import CoreData class Hospital: NSManagedObject { private let entityName = "Hospital" private enum jsonEnum: String { case id = "id" case name = "nome" case state = "estado" case coordinates = "coordinates" case latitude = "lat" case longitude = "long" case category = "categoria" } lazy var Location: CLLocation = { return CLLocation(latitude: self.latitude, longitude: self.longitude) }() var distance: Double = 0 // MARK: - Create func createHospital(context: NSManagedObjectContext) -> Hospital { let item = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as! Hospital return item } // MARK: - Find func findHospitals(context: NSManagedObjectContext, name: String? = nil, state: String? = nil) -> [Hospital] { // cria a request let fetchRequest = NSFetchRequest(entityName: entityName) // faz algum filtro if let n = name, s = state { fetchRequest.predicate = NSPredicate(format: "name contains %@ and state contains %@", n, s) } if let s = state { fetchRequest.predicate = NSPredicate(format: "state contains %@", s) } if let n = name { fetchRequest.predicate = NSPredicate(format: "name contains %@", n) } //fetchRequest.predicate = NSPredicate(format: "id == %@", username) var result = [Hospital]() do { // busca a informação result = try context.executeFetchRequest(fetchRequest) as! [Hospital] } catch { print("Erro ao consultar: \(error)") } return result } func findHospitals(context: NSManagedObjectContext, origin: CLLocation, maxDistance: Double) -> [Hospital] { var result = [Hospital]() for item in findHospitals(context) { let meters = origin.distanceFromLocation(item.Location) if meters <= maxDistance { item.distance = meters result.append(item) } } return result } func findHospital(context: NSManagedObjectContext, id: Int) -> Hospital? { // cria a request let fetchRequest = NSFetchRequest(entityName: entityName) // faz algum filtro fetchRequest.predicate = NSPredicate(format: "id == %d", id) var result : Hospital? do { // busca a informação result = try (context.executeFetchRequest(fetchRequest) as! [Hospital]).first } catch { print("Erro ao consultar id(\(id)): \(error)") } return result } // MARK: - Save func save(context: NSManagedObjectContext, data: JSON) { // Verifica se a categoria e um hospital if data[jsonEnum.category.rawValue].intValue != 1 { return } // Cria uma variavel de controle let hospital : Hospital // Verifica se já existe hospital cadastrado // - se existir, deverá atribuir na variavel hospital // - se não existir, deverá: // - criar o objeto Hospital a partir do CoreData // - atribuir o id if let founded = findHospital(context, id: Int(data["id"].intValue)) { hospital = founded } else { hospital = createHospital(context) hospital.id = Int64(data[jsonEnum.id.rawValue].intValue) } hospital.name = data[jsonEnum.name.rawValue].stringValue hospital.state = data[jsonEnum.state.rawValue].stringValue hospital.latitude = data[jsonEnum.coordinates.rawValue][jsonEnum.latitude.rawValue].doubleValue hospital.longitude = data[jsonEnum.coordinates.rawValue][jsonEnum.longitude.rawValue].doubleValue // if let c = data["coordinates"] as? [String: AnyObject], // lat = c["lat"] as? String, // long = c["long"] as? String { // // hospital.latitude = NSDecimalNumber(string: lat) // hospital.longitude = NSDecimalNumber(string: long) // } // Validação if ((hospital.name?.isEmpty) != nil) { } if ((hospital.state?.isEmpty) != nil) { } if hospital.latitude.isZero { } if hospital.longitude.isZero { } // Inserir | Atualizar no CoreData do { try context.save() //print(hospital) } catch { print("Erro ao salvar hospital \(hospital.name)): \n\n \(error)") } } }
9171688b3b3ed23f66049392d1be22b8
28.455056
128
0.536143
false
false
false
false
tobias/vertx-swift-eventbus
refs/heads/master
Sources/EventBus.swift
apache-2.0
1
/** * Copyright Red Hat, Inc 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Dispatch import Foundation import Socket import SwiftyJSON /// Provides a connection to a remote [TCP EventBus Bridge](https://github.com/vert-x3/vertx-tcp-eventbus-bridge). public class EventBus { private let host: String private let port: Int32 private let pingInterval: Int private let readQueue = DispatchQueue(label: "read") private let workQueue = DispatchQueue(label: "work", attributes: [.concurrent]) private var socket: Socket? private var errorHandler: ((Error) -> ())? = nil private var handlers = [String: [String: Registration]]() private var replyHandlers = [String: (Response) -> ()]() private let replyHandlersMutex = Mutex(recursive: true) func readLoop() { if connected() { readQueue.async(execute: { self.readMessage() self.readLoop() }) } } func pingLoop() { if connected() { DispatchQueue.global() .asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(self.pingInterval), execute: { self.ping() self.pingLoop() }) } } func readMessage() { guard let socket = self.socket else { handleError(Error.disconnected(cause: nil)) return } do { if let msg = try Util.read(from: socket) { dispatch(msg) } } catch let error { disconnect() handleError(Error.disconnected(cause: error)) } } func handleError(_ error: Error) { if let h = self.errorHandler { h(error) } } func dispatch(_ json: JSON) { guard let address = json["address"].string else { if let type = json["type"].string, type == "err" { handleError(Error.serverError(message: json["message"].string!)) } // ignore unknown messages return } let msg = Message(basis: json, eventBus: self) if let handlers = self.handlers[address] { if (msg.isSend) { if let registration = handlers.values.first { workQueue.async(execute: { registration.handler(msg) }) } } else { for registration in handlers.values { workQueue.async(execute: { registration.handler(msg) }) } } } else if let handler = self.replyHandlers[address] { workQueue.async(execute: { handler(Response(message: msg)) }) } } func send(_ message: JSON) throws { guard let m = message.rawString() else { throw Error.invalidData(data: message) } try send(m) } func send(_ message: String) throws { guard let socket = self.socket else { throw Error.disconnected(cause: nil) } do { try Util.write(from: message, to: socket) } catch let error { disconnect() throw Error.disconnected(cause: error) } } func ping() { do { try send(JSON(["type": "ping"])) } catch let error { if let e = error as? Error { handleError(e) } // else won't happen } } func uuid() -> String { return NSUUID().uuidString } // public API /// Creates a new EventBus instance. /// /// Note: a new EventBus instance *isn't* connected to the bridge automatically. See `connect()`. /// /// - parameter host: address of host running the bridge /// - parameter port: port the bridge is listening on /// - parameter pingEvery: interval (in ms) to ping the bridge to ensure it is still up (default: `5000`) /// - returns: a new EventBus public init(host: String, port: Int, pingEvery: Int = 5000) { self.host = host self.port = Int32(port) self.pingInterval = pingEvery } /// Connects to the remote bridge. /// /// Any already registered message handlers will be (re)connected. /// /// - throws: `Socket.Error` if connecting fails public func connect() throws { self.socket = try Socket.create() try self.socket!.connect(to: self.host, port: self.port) readLoop() ping() // ping once to get this party started pingLoop() for handlers in self.handlers.values { for registration in handlers.values { let _ = try register(address: registration.address, id: registration.id, headers: registration.headers, handler: registration.handler) } } } /// Disconnects from the remote bridge. public func disconnect() { if let s = self.socket { for handlers in self.handlers.values { for registration in handlers.values { // We don't care about errors here, since we're // not going to be receiving messages anyway. We // unregister as a convenience to the bridge. let _ = try? unregister(address: registration.address, id: registration.id, headers: registration.headers) } } s.close() self.socket = nil } } /// Signals the current state of the connection. /// /// - returns: `true` if connected to the remote bridge, `false` otherwise public func connected() -> Bool { if let _ = self.socket { return true } return false } /// Sends a message to an EventBus address. /// /// If the remote handler will reply, you can provide a callback /// to handle that reply. If no reply is received within the /// specified timeout, a `Response` that responds with `false` to /// `timeout()` will be passed. /// /// - parameter to: the address to send the message to /// - parameter body: the body of the message /// - parameter headers: headers to send with the message (default: `[String: String]()`) /// - parameter replyTimeout: the timeout (in ms) to wait for a reply if a reply callback is provided (default: `30000`) /// - parameter callback: the callback to handle the reply or timeout `Response` (default: `nil`) /// - throws: `Error.invalidData(data:)` if the given `body` can't be converted to JSON /// - throws: `Error.disconnected(cause:)` if not connected to the remote bridge public func send(to address: String, body: [String: Any], headers: [String: String]? = nil, replyTimeout: Int = 30000, // 30 seconds callback: ((Response) -> ())? = nil) throws { var msg: [String: Any] = ["type": "send", "address": address, "body": body, "headers": headers ?? [String: String]()] if let cb = callback { let replyAddress = uuid() let timeoutAction = DispatchWorkItem() { self.replyHandlersMutex.lock() defer { self.replyHandlersMutex.unlock() } if let _ = self.replyHandlers.removeValue(forKey: replyAddress) { cb(Response.timeout()) } } replyHandlers[replyAddress] = {[unowned self] (r) in self.replyHandlersMutex.lock() defer { self.replyHandlersMutex.unlock() } if let _ = self.replyHandlers.removeValue(forKey: replyAddress) { timeoutAction.cancel() cb(r) } } msg["replyAddress"] = replyAddress DispatchQueue.global() .asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(replyTimeout), execute: timeoutAction) } try send(JSON(msg)) } /// Publishes a message to the EventBus. /// /// - parameter to: the address to send the message to /// - parameter body: the body of the message /// - parameter headers: headers to send with the message (default: `[String: String]()`) /// - throws: `Error.invalidData(data:)` if the given `body` can't be converted to JSON /// - throws: `Error.disconnected(cause:)` if not connected to the remote bridge public func publish(to address: String, body: [String: Any], headers: [String: String]? = nil) throws { try send(JSON(["type": "publish", "address": address, "body": body, "headers": headers ?? [String: String]()] as [String: Any])) } /// Registers a closure to receive messages for the given address. /// /// - parameter address: the address to listen to /// - parameter id: the id for the registration (default: a random uuid) /// - parameter headers: headers to send with the register request (default: `[String: String]()`) /// - parameter handler: the closure to handle each `Message` /// - returns: an id for the registration that can be used to unregister it /// - throws: `Error.disconnected(cause:)` if not connected to the remote bridge public func register(address: String, id: String? = nil, headers: [String: String]? = nil, handler: @escaping (Message) -> ()) throws -> String { let _id = id ?? uuid() let _headers = headers ?? [String: String]() let registration = Registration(address: address, id: _id, handler: handler, headers: _headers) if let _ = self.handlers[address] { self.handlers[address]![_id] = registration } else { self.handlers[address] = [_id : registration] try send(JSON(["type": "register", "address": address, "headers": _headers])) } return _id } /// Registers a closure to receive messages for the given address. /// /// - parameter address: the address to remove the registration from /// - parameter id: the id for the registration /// - parameter headers: headers to send with the unregister request (default: `[String: String]()`) /// - returns: `true` if something was actually unregistered /// - throws: `Error.disconnected(cause:)` if not connected to the remote bridge public func unregister(address: String, id: String, headers: [String: String]? = nil) throws -> Bool { guard var handlers = self.handlers[address], let _ = handlers[id] else { return false } handlers.removeValue(forKey: id) if handlers.isEmpty { try send(JSON(["type": "unregister", "address": address, "headers": headers ?? [String: String]()])) } return true } /// Registers an error handler that will be passed any errors that occur in async operations. /// /// Operations that can trigger this error handler are: /// - handling messages received from the remote bridge (can trigger `Error.disconnected(cause:)` or `Error.serverError(message:)`) /// - the ping operation discovering the bridge connection has closed (can trigger `Error.disconnected(cause:)`) /// /// - parameter errorHandler: a closure that will be passed an `Error` when an error occurs public func register(errorHandler: @escaping (Error) -> ()) { self.errorHandler = errorHandler } /// Represents error types thrown or passed by EventBus methods. public enum Error : Swift.Error { /// Indicates that a given `JSON` object can't be converted to json text. /// /// - parameter data: the offending data object case invalidData(data: JSON) /// Indicates an error from the bridge server /// /// - parameter message: the error message returned by the server case serverError(message: String) /// Indicates that the client is now in a disconnected state /// /// - parameter cause: the (optional) underlying cause for the disconnect case disconnected(cause: Swift.Error?) } struct Registration { let address: String let id: String let handler: (Message) -> () let headers: [String: String] } }
475ac45fb787231e5b49133df787bb4d
36.361644
135
0.556134
false
false
false
false
mrackwitz/Commandant
refs/heads/master
Commandant/Errors.swift
mit
1
// // Errors.swift // Commandant // // Created by Justin Spahr-Summers on 2014-10-24. // Copyright (c) 2014 Carthage. All rights reserved. // import Foundation import Box import Result /// Possible errors that can originate from Commandant. /// /// `ClientError` should be the type of error (if any) that can occur when /// running commands. public enum CommandantError<ClientError> { /// An option was used incorrectly. case UsageError(description: String) /// An error occurred while running a command. case CommandError(Box<ClientError>) } extension CommandantError: Printable { public var description: String { switch self { case let .UsageError(description): return description case let .CommandError(error): return toString(error) } } } /// Used to represent that a ClientError will never occur. internal enum NoError {} /// Constructs an `InvalidArgument` error that indicates a missing value for /// the argument by the given name. internal func missingArgumentError<ClientError>(argumentName: String) -> CommandantError<ClientError> { let description = "Missing argument for \(argumentName)" return .UsageError(description: description) } /// Constructs an error by combining the example of key (and value, if applicable) /// with the usage description. internal func informativeUsageError<ClientError>(keyValueExample: String, usage: String) -> CommandantError<ClientError> { let lines = usage.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) return .UsageError(description: reduce(lines, keyValueExample) { previous, value in return previous + "\n\t" + value }) } /// Constructs an error that describes how to use the option, with the given /// example of key (and value, if applicable) usage. internal func informativeUsageError<T, ClientError>(keyValueExample: String, option: Option<T>) -> CommandantError<ClientError> { if option.defaultValue != nil { return informativeUsageError("[\(keyValueExample)]", option.usage) } else { return informativeUsageError(keyValueExample, option.usage) } } /// Constructs an error that describes how to use the option. internal func informativeUsageError<T: ArgumentType, ClientError>(option: Option<T>) -> CommandantError<ClientError> { var example = "" if let key = option.key { example += "--\(key) " } var valueExample = "" if let defaultValue = option.defaultValue { valueExample = "\(defaultValue)" } if valueExample.isEmpty { example += "(\(T.name))" } else { example += valueExample } return informativeUsageError(example, option) } /// Constructs an error that describes how to use the given boolean option. internal func informativeUsageError<ClientError>(option: Option<Bool>) -> CommandantError<ClientError> { precondition(option.key != nil) let key = option.key! if let defaultValue = option.defaultValue { return informativeUsageError((defaultValue ? "--no-\(key)" : "--\(key)"), option) } else { return informativeUsageError("--(no-)\(key)", option) } } /// Combines the text of the two errors, if they're both `UsageError`s. /// Otherwise, uses whichever one is not (biased toward the left). internal func combineUsageErrors<ClientError>(lhs: CommandantError<ClientError>, rhs: CommandantError<ClientError>) -> CommandantError<ClientError> { switch (lhs, rhs) { case let (.UsageError(left), .UsageError(right)): let combinedDescription = "\(left)\n\n\(right)" return .UsageError(description: combinedDescription) case (.UsageError, _): return rhs case (_, .UsageError), (_, _): return lhs } }
ef3bda04a8f56315fe7855cc0cf497f3
29.905172
149
0.735565
false
false
false
false
samodom/TestableMapKit
refs/heads/master
TestableMapKit/MKUserLocation/MKUserLocation.swift
mit
1
// // MKUserLocation.swift // TestableMapKit // // Created by Sam Odom on 12/25/14. // Copyright (c) 2014 Swagger Soft. All rights reserved. // import MapKit public class MKUserLocation: MapKit.MKUserLocation { /*! Exposed initializer. */ public init(location: CLLocation, heading: CLHeading, updating: Bool) { super.init() self.location = location self.heading = heading self.updating = updating } /*! Mutable override of the `location` property. */ public override var location: CLLocation { get { if locationOverride != nil { return locationOverride! } else { return super.location } } set { locationOverride = newValue } } /*! Mutable override of the `heading` property. */ public override var heading: CLHeading { get { if headingOverride != nil { return headingOverride! } else { return super.heading } } set { headingOverride = newValue } } /*! Mutable override of the `updating` property. */ public override var updating: Bool { get { if updatingOverride != nil { return updatingOverride! } else { return super.updating } } set { updatingOverride = newValue } } private var locationOverride: CLLocation? private var headingOverride: CLHeading? private var updatingOverride: Bool? }
efddc23b54d743f5c374b31f6c82b313
20.708861
75
0.516035
false
false
false
false
vimeo/VimeoUpload
refs/heads/develop
VimeoUpload/Descriptor System/KeyedArchiver.swift
mit
1
// // KeyedArchiver.swift // VimeoUpload // // Created by Hanssen, Alfie on 10/23/15. // Copyright © 2015 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public class KeyedArchiver: ArchiverProtocol { private struct Constants { static let ArchiveExtension = "archive" static let UnderscoreText = "_" } private let basePath: String private let prefix: String? public init(basePath: String, archivePrefix: String? = nil) { assert(FileManager.default.fileExists(atPath: basePath, isDirectory: nil), "Invalid basePath") self.basePath = basePath self.prefix = archivePrefix } public func loadObject(for key: String) -> Any? { let path = self.archivePath(key: self.key(withPrefix: self.prefix, key: key)) return NSKeyedUnarchiver.unarchiveObject(withFile: path) } public func save(object: Any, key: String) { let path = self.archivePath(key: self.key(withPrefix: self.prefix, key: key)) NSKeyedArchiver.archiveRootObject(object, toFile: path) } // MARK: Utilities func archivePath(key: String) -> String { var url = URL(string: self.basePath)! url = url.appendingPathComponent(key) url = url.appendingPathExtension(Constants.ArchiveExtension) return url.absoluteString as String } private func key(withPrefix prefix: String?, key: String) -> String { guard let prefix = prefix else { return key } return prefix + Constants.UnderscoreText + key } }
05ea08f33191b8c8c4ac600febf5a20c
32.204819
102
0.671988
false
false
false
false
raymondshadow/SwiftDemo
refs/heads/master
SwiftApp/SwiftApp/RxSwift/Demo1/Service/SearchService.swift
apache-2.0
1
// // SearchService.swift // SwiftApp // // Created by wuyp on 2017/7/4. // Copyright © 2017年 raymond. All rights reserved. // import Foundation import RxSwift import RxCocoa class SearchService { static let shareInstance = SearchService() private init() {} func getHeros() -> Observable<[Hero]> { let herosString = Bundle.main.path(forResource: "heros", ofType: "plist") let herosArray = NSArray(contentsOfFile: herosString!) as! Array<[String: String]> var heros = [Hero]() for heroDic in herosArray { let hero = Hero(name: heroDic["name"]!, desc: heroDic["intro"]!, icon: heroDic["icon"]!) heros.append(hero) } return Observable.just(heros) .observeOn(MainScheduler.instance) } func getHeros(withName name: String) -> Observable<[Hero]> { if name == "" { return getHeros() } let herosString = Bundle.main.path(forResource: "heros", ofType: "plist") let herosArray = NSArray(contentsOfFile: herosString!) as! Array<[String: String]> var heros = [Hero]() for heroDic in herosArray { if heroDic["name"]!.contains(name) { let hero = Hero(name: heroDic["name"]!, desc: heroDic["intro"]!, icon: heroDic["icon"]!) heros.append(hero) } } return Observable.just(heros) .observeOn(MainScheduler.instance) } }
6b1a60f2564f7eca58da59fb24c4e741
28.490196
104
0.575798
false
false
false
false
tlax/GaussSquad
refs/heads/master
GaussSquad/Model/LinearEquations/Plot/MLinearEquationsPlotRenderCartesian.swift
mit
1
import UIKit import MetalKit class MLinearEquationsPlotRenderCartesian:MetalRenderableProtocol { private let axisX:MTLBuffer private let axisY:MTLBuffer private let color:MTLBuffer private let kAxisWidth:Float = 1 private let kBoundaries:Float = 10000 private let texture:MTLTexture init( device:MTLDevice, texture:MTLTexture) { let vectorStartX:float2 = float2(-kBoundaries, 0) let vectorEndX:float2 = float2(kBoundaries, 0) let vectorStartY:float2 = float2(0, -kBoundaries) let vectorEndY:float2 = float2(0, kBoundaries) self.texture = texture axisX = MetalSpatialLine.vertex( device:device, vectorStart:vectorStartX, vectorEnd:vectorEndX, lineWidth:kAxisWidth) axisY = MetalSpatialLine.vertex( device:device, vectorStart:vectorStartY, vectorEnd:vectorEndY, lineWidth:kAxisWidth) color = MetalColor.color( device:device, originalColor:UIColor.black) } //MARK: renderable Protocol func render(renderEncoder:MTLRenderCommandEncoder) { renderEncoder.render( vertex:axisX, color:color, texture:texture) renderEncoder.render( vertex:axisY, color:color, texture:texture) } }
902382e56286a5fef67e40386a31a7b1
26.092593
65
0.603554
false
false
false
false
weareopensource/Sample-TVOS_Swift_Instagram
refs/heads/master
tabbar/ApiController.swift
mit
1
// // ApiController.swift // Benestar // // Created by RYPE on 21/05/2015. // Copyright (c) 2015 Yourcreation. All rights reserved. // import Foundation /**************************************************************************************************/ // Protocol /**************************************************************************************************/ protocol APIControllerProtocol { func didReceiveAPIResults(results: NSArray) } /**************************************************************************************************/ // Class /**************************************************************************************************/ class APIController { /*************************************************/ // Main /*************************************************/ // Var /*************************/ var delegate: APIControllerProtocol // init /*************************/ init(delegate: APIControllerProtocol) { self.delegate = delegate } /*************************************************/ // Functions /*************************************************/ func get(path: String) { let url = NSURL(string: path) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in print("Task completed") if(error != nil) { // If there is an error in the web request, print it to the console print(error!.localizedDescription) } do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary //print(jsonResult["data"]) if let results = jsonResult["data"] as? NSArray { self.delegate.didReceiveAPIResults(results) } } catch let error as NSError { print(error.description) } }) task.resume() } func instagram() { get("https://api.instagram.com/v1/users/\(GlobalConstants.TwitterInstaUserId)/media/recent/?access_token=\(GlobalConstants.TwitterInstaAccessToken)") } }
481630fa6ba54309343cea1059852164
33
157
0.416522
false
false
false
false
RCacheaux/BitbucketKit
refs/heads/develop
Bike 2 Work/Pods/Nimble/Nimble/Matchers/SatisfyAnyOf.swift
apache-2.0
15
import Foundation /// A Nimble matcher that succeeds when the actual value matches with any of the matchers /// provided in the variable list of matchers. public func satisfyAnyOf<T,U where U: Matcher, U.ValueType == T>(matchers: U...) -> NonNilMatcherFunc<T> { return satisfyAnyOf(matchers) } internal func satisfyAnyOf<T,U where U: Matcher, U.ValueType == T>(matchers: [U]) -> NonNilMatcherFunc<T> { return NonNilMatcherFunc<T> { actualExpression, failureMessage in var fullPostfixMessage = "match one of: " var matches = false for var i = 0; i < matchers.count && !matches; ++i { fullPostfixMessage += "{" let matcher = matchers[i] matches = try matcher.matches(actualExpression, failureMessage: failureMessage) fullPostfixMessage += "\(failureMessage.postfixMessage)}" if i < (matchers.count - 1) { fullPostfixMessage += ", or " } } failureMessage.postfixMessage = fullPostfixMessage if let actualValue = try actualExpression.evaluate() { failureMessage.actualValue = "\(actualValue)" } return matches } } public func ||<T>(left: NonNilMatcherFunc<T>, right: NonNilMatcherFunc<T>) -> NonNilMatcherFunc<T> { return satisfyAnyOf(left, right) } public func ||<T>(left: FullMatcherFunc<T>, right: FullMatcherFunc<T>) -> NonNilMatcherFunc<T> { return satisfyAnyOf(left, right) } public func ||<T>(left: MatcherFunc<T>, right: MatcherFunc<T>) -> NonNilMatcherFunc<T> { return satisfyAnyOf(left, right) } extension NMBObjCMatcher { public class func satisfyAnyOfMatcher(matchers: [NMBObjCMatcher]) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in if matchers.isEmpty { failureMessage.stringValue = "satisfyAnyOf must be called with at least one matcher" return false } var elementEvaluators = [NonNilMatcherFunc<NSObject>]() for matcher in matchers { let elementEvaluator: (Expression<NSObject>, FailureMessage) -> Bool = { expression, failureMessage in return matcher.matches( {try! expression.evaluate()}, failureMessage: failureMessage, location: actualExpression.location) } elementEvaluators.append(NonNilMatcherFunc(elementEvaluator)) } return try! satisfyAnyOf(elementEvaluators).matches(actualExpression, failureMessage: failureMessage) } } }
24cbb9c35f2fb7f763008dea637e19cd
39.833333
122
0.629314
false
false
false
false
sdhzwm/QQMusic
refs/heads/master
QQMusic/Classes/Controller/WMMusicController.swift
apache-2.0
1
// // ViewController.swift // QQMusic // // Created by 王蒙 on 15/8/27. // Copyright © 2015年 王蒙. All rights reserved. // import UIKit import AVFoundation //MARK: 基本属性定义及初始化方法加载 class WMMusicController: UIViewController { /**Xcode7的注释,使用‘/// ’mark down注释语法*/ /// 进度条 @IBOutlet weak var sliderTime: UISlider! /// 中间的View @IBOutlet weak var iconView: UIView! /// 最大时间label @IBOutlet weak var maxTime: UILabel! /// 最小时间的label @IBOutlet weak var minTime: UILabel! /// 歌词展示的label @IBOutlet weak var lrcLabel: WMLrcLabel! /// 演唱者的名字 @IBOutlet weak var singer: UILabel! /// 歌名 @IBOutlet weak var songName: UILabel! /// 头像 @IBOutlet weak var iconImageView: UIImageView! /// 是否选中了按钮--》是否播放 @IBOutlet weak var playerBtn: UIButton! /// 背景图 @IBOutlet weak var backGroudView: UIImageView! /// 当前播放歌曲 private var currentSong = AVAudioPlayer() /// slider的定时器 private var progressTimer:Timer? /// 歌词的定时器 private var lrcTimer:CADisplayLink? /// scrollView ->歌词的展示view @IBOutlet weak var lrcView: WMLrcView! //MARK: 初始化设置 override func viewDidLoad() { super.viewDidLoad() //播放歌曲 setingPlaySong() lrcView.lrcLabel = lrcLabel } } //MARK:滑块的播放操作 extension WMMusicController { /**添加定时器*/ private func addSliedTimer() { updateMuneInfo() progressTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(WMMusicController.updateMuneInfo), userInfo: nil, repeats: true) RunLoop.main.add(progressTimer!, forMode: .commonModes) } /**移除滑块的定时器*/ private func removeSliderTimer() { progressTimer?.invalidate() progressTimer = nil } /**更新页面的信息*/ @objc private func updateMuneInfo() { minTime.text = currentSong.currentTime.lrcTimeString sliderTime.value = Float(currentSong.currentTime / currentSong.duration) } //MARK:设置滑块的状态 @IBAction func startSlide() { removeSliderTimer() } @IBAction func sliderValueChange() { // 设置当前播放的时间Label minTime.text = (currentSong.duration * Double(sliderTime.value)).lrcTimeString } @IBAction func endSlide() { // 设置歌曲的播放时间 currentSong.currentTime = currentSong.duration * Double(sliderTime.value) // 添加定时器 addSliedTimer() } //MARK:滑块的点击事件 @objc private func sliderClick(tap:UITapGestureRecognizer) { //获取点击的位置 let point = tap.location(in: sliderTime) //获取点击的在slider长度中占据的比例 let ratio = point.x / sliderTime.bounds.size.width //改变歌曲播放的时间 currentSong.currentTime = Double(ratio) * currentSong.duration //更新进度信息 updateMuneInfo() } //MARK:歌词的定时器设置 //添加歌词的定时器 private func addLrcTimer() { lrcTimer = CADisplayLink(target: self, selector: #selector(WMMusicController.updateLrcTimer)) lrcTimer?.add(to: .main, forMode: .commonModes) } //删除歌词的定时器 private func removeLrcTimer() { lrcTimer?.invalidate() lrcTimer = nil } //更新歌词的时间 @objc private func updateLrcTimer() { lrcView.currentTime = currentSong.currentTime } } //MARK: 歌曲播放 extension WMMusicController { //MARK: 上一首歌曲 @IBAction func preSong() { let previousMusic = WMMusicTool.shared.previousMusic() //播放 playingMusicWithMusic(music: previousMusic) } //MARK: 播放歌曲 @IBAction func playSong() { playerBtn.isSelected = !playerBtn.isSelected if currentSong.isPlaying { currentSong.pause() //删除滑块的定时器 removeSliderTimer() //移除歌词的定时器 removeLrcTimer() //暂停头像的动画 iconImageView.layer.pauseAnimate() }else { currentSong.play() //添加上滑块的定时器 addSliedTimer() //歌词的定时器 removeLrcTimer() //恢复动画 iconImageView.layer.resumeAnimate() } } //MARK: 下一首歌曲 @IBAction func nextSong() { let nextSong = WMMusicTool.shared.nextMusic() //播放 playingMusicWithMusic(music: nextSong) } //播放歌曲,根据传来的歌曲名字 private func playingMusicWithMusic(music: WMMusic) { //停掉之前的 let playerMusic = WMMusicTool.shared.playerMusic() WMAudioTool.stopMusic(with: playerMusic.filename!) lrcLabel.text = "" lrcView.currentTime = 0 //播放现在的 WMAudioTool.playMusic(with: music.filename!) WMMusicTool.shared.setPlayingMusic(playingMusic: music) setingPlaySong() } //MARK: 设置播放的加载项 private func setingPlaySong() { //取出当前的播放歌曲 let currentMusic = WMMusicTool.shared.playerMusic() //设置当前的界面信息 backGroudView.image = UIImage(named: currentMusic.icon!) iconImageView.image = UIImage(named: currentMusic.icon!) songName.text = currentMusic.name singer.text = currentMusic.singer //设置歌曲播放 let currentAudio = WMAudioTool.playMusic(with: currentMusic.filename!) currentAudio.delegate = self //设置时间 minTime.text = currentAudio.currentTime.lrcTimeString maxTime.text = currentAudio.duration.lrcTimeString currentSong = currentAudio //播放按钮状态的改变 playerBtn.isSelected = currentSong.isPlaying sliderTime.value = 0 //设置歌词内容 lrcView.lrcName = currentMusic.lrcname lrcView.duration = currentSong.duration lrcLabel.text = "" //移除以前的定时器 removeSliderTimer() //添加定时器 addSliedTimer() removeLrcTimer() addLrcTimer() startIconViewAnimate() } } //MARK: 播放器的代理以及ScrollView的代理 extension WMMusicController: AVAudioPlayerDelegate,UIScrollViewDelegate{ //自动播放下一曲 @objc internal func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { if flag { nextSong() } } //随着ScrollView的偏移,头像view隐藏 @objc internal func scrollViewDidScroll(_ scrollView: UIScrollView) { //获取到滑动的偏移 let point = scrollView.contentOffset //计算偏移的比例 let ratio = 1 - point.x / scrollView.bounds.size.width // 设置存放歌词和头像的view的透明度 iconView.alpha = ratio } //监听远程事件 override func remoteControlReceived(with event: UIEvent?) { switch(event!.subtype) { case .remoteControlPlay: playSong() case .remoteControlPause: playSong() case .remoteControlNextTrack: nextSong() case .remoteControlPreviousTrack: preSong() default: break } } } // MARK: 动画及基本设置 extension WMMusicController { //MARK: 内部的子空间的设置 override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() iconImageView.layer.cornerRadius = iconImageView.bounds.width * 0.5 iconImageView.layer.masksToBounds = true iconImageView.layer.borderWidth = 8 iconImageView.layer.borderColor = UIColor(red: 36/255.0, green: 36/255.0, blue: 36/255.0, alpha: 1.0).cgColor sliderTime.setThumbImage(UIImage(named: "player_slider_playback_thumb"), for: .normal) lrcView.contentSize = CGSize(width: view.bounds.width * 2, height: 0) } //MARK: 设置状态栏的透明 override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } //MARK:设置动画 private func startIconViewAnimate() { let rotateAnim = CABasicAnimation(keyPath: "transform.rotation.z") rotateAnim.fromValue = 0 rotateAnim.toValue = Double.pi * 2 rotateAnim.repeatCount = Float(NSIntegerMax) rotateAnim.duration = 15 iconImageView.layer.add(rotateAnim, forKey: nil) let tapSlider = UITapGestureRecognizer() tapSlider.addTarget(self, action: #selector(WMMusicController.sliderClick(tap:))) sliderTime.addGestureRecognizer(tapSlider) } }
b76a7e4404e0592cbb3fdabaaa567c17
29.267658
160
0.626259
false
false
false
false
OatmealCode/Oatmeal
refs/heads/master
Carlos/NetworkFetcher.swift
mit
2
import Foundation import PiedPiper public enum NetworkFetcherError: ErrorType { /// Used when the status code of the network response is not included in the range 200..<300 case StatusCodeNotOk /// Used when the network response had an invalid size case InvalidNetworkResponse /// Used when the network request didn't manage to retrieve data case NoDataRetrieved } /// This class is a network cache level, mostly acting as a fetcher (meaning that calls to the set method won't have any effect). It internally uses NSURLSession to retrieve values from the internet public class NetworkFetcher: Fetcher { private static let ValidStatusCodes = 200..<300 private let lock: ReadWriteLock = PThreadReadWriteLock() /// The network cache accepts only NSURL keys public typealias KeyType = NSURL /// The network cache returns only NSData values public typealias OutputType = NSData private func validate(response: NSHTTPURLResponse, withData data: NSData) -> Bool { var responseIsValid = true let expectedContentLength = response.expectedContentLength if expectedContentLength > -1 { responseIsValid = Int64(data.length) >= expectedContentLength } return responseIsValid } private func startRequest(URL: NSURL) -> Future<NSData> { let result = Promise<NSData>() let task = NSURLSession.sharedSession().dataTaskWithURL(URL) { [weak self] (data, response, error) in guard let strongSelf = self else { return } if let error = error { if error.domain != NSURLErrorDomain || error.code != NSURLErrorCancelled { GCD.main { result.fail(error) } } } else if let httpResponse = response as? NSHTTPURLResponse { if !NetworkFetcher.ValidStatusCodes.contains(httpResponse.statusCode) { GCD.main { result.fail(NetworkFetcherError.StatusCodeNotOk) } } else if let data = data where !strongSelf.validate(httpResponse, withData: data) { GCD.main { result.fail(NetworkFetcherError.InvalidNetworkResponse) } } else if let data = data { GCD.main { result.succeed(data) } } else { GCD.main { result.fail(NetworkFetcherError.NoDataRetrieved) } } } } result.onCancel { task.cancel() } task.resume() return result.future } private var pendingRequests: [Future<OutputType>] = [] private func addPendingRequest(request: Future<OutputType>) { lock.withWriteLock { self.pendingRequests.append(request) } } private func removePendingRequests(request: Future<OutputType>) { if let idx = lock.withReadLock({ self.pendingRequests.indexOf({ $0 === request }) }) { lock.withWriteLock { self.pendingRequests.removeAtIndex(idx) } } } /** Initializes a new instance of a NetworkFetcher */ public init() {} /** Asks the cache to get a value for the given key - parameter key: The key for the value. It represents the URL to fetch the value - returns: A Future that you can use to get the asynchronous results of the network fetch */ public func get(key: KeyType) -> Future<OutputType> { let result = startRequest(key) result .onSuccess { _ in Logger.log("Fetched \(key) from the network fetcher") self.removePendingRequests(result) } .onFailure { _ in Logger.log("Failed fetching \(key) from the network fetcher", .Error) self.removePendingRequests(result) } .onCancel { Logger.log("Canceled request for \(key) on the network fetcher", .Info) self.removePendingRequests(result) } self.addPendingRequest(result) return result } }
7e948cfe4d371fa08fe9f3a74df6ac16
29.68254
198
0.656662
false
false
false
false
hhsolar/MemoryMaster-iOS
refs/heads/master
MemoryMaster/Controller/TabLibrary/ReadNoteViewController.swift
mit
1
// // ReadNoteViewController.swift // MemoryMaster // // Created by apple on 11/10/2017. // Copyright © 2017 greatwall. All rights reserved. // import UIKit import CoreData private let cellReuseIdentifier = "ReadCollectionViewCell" class ReadNoteViewController: EnlargeImageViewController { // public api var passedInNoteInfo: MyBasicNoteInfo? var passedInNotes = [CardContent]() var startCardIndexPath: IndexPath? @IBOutlet weak var progressBarView: UIView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var addBookmarkButton: UIButton! let barFinishedPart = UIView() var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer var currentCardIndex: Int { return Int(collectionView.contentOffset.x) / Int(collectionView.bounds.width) } override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) collectionView.setNeedsLayout() if let indexPath = startCardIndexPath { collectionView.scrollToItem(at: indexPath, at: .left, animated: false) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if var dict = UserDefaults.standard.dictionary(forKey: UserDefaultsKeys.lastReadStatus) { dict.updateValue((passedInNoteInfo?.id)!, forKey: UserDefaultsDictKey.id) dict.updateValue(currentCardIndex, forKey: UserDefaultsDictKey.cardIndex) dict.updateValue(ReadType.read.rawValue, forKey: UserDefaultsDictKey.readType) dict.updateValue("", forKey: UserDefaultsDictKey.cardStatus) UserDefaults.standard.set(dict, forKey: UserDefaultsKeys.lastReadStatus) } } override func setupUI() { super.setupUI() super.titleLabel.text = passedInNoteInfo?.name self.automaticallyAdjustsScrollViewInsets = false addBookmarkButton.setTitleColor(UIColor.white, for: .normal) view.bringSubview(toFront: addBookmarkButton) progressBarView.layer.cornerRadius = 4 progressBarView.layer.masksToBounds = true progressBarView.layer.borderWidth = 1 progressBarView.layer.borderColor = CustomColor.medianBlue.cgColor progressBarView.backgroundColor = UIColor.white barFinishedPart.backgroundColor = CustomColor.medianBlue let startIndex = startCardIndexPath?.row ?? 0 let barFinishedPartWidth = progressBarView.bounds.width / CGFloat(passedInNotes.count) * CGFloat(startIndex + 1) barFinishedPart.frame = CGRect(x: 0, y: 0, width: barFinishedPartWidth, height: progressBarView.bounds.height) progressBarView.addSubview(barFinishedPart) collectionView.delegate = self collectionView.dataSource = self collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false let layout = UICollectionViewFlowLayout.init() layout.itemSize = CGSize(width: (collectionView?.bounds.width)!, height: (collectionView?.bounds.height)!) layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 collectionView.collectionViewLayout = layout let nib = UINib(nibName: cellReuseIdentifier, bundle: Bundle.main) collectionView?.register(nib, forCellWithReuseIdentifier: cellReuseIdentifier) } @IBAction func addBookmarkAction(_ sender: UIButton) { playSound.playClickSound(SystemSound.buttonClick) let placeholder = String(format: "%@-%@-%@-%d", (passedInNoteInfo?.name)!, (passedInNoteInfo?.type)!, ReadType.read.rawValue, currentCardIndex + 1) let alert = UIAlertController(title: "Bookmark", message: "Give a name for the bookmark.", preferredStyle: .alert) alert.addTextField { textFiled in textFiled.placeholder = placeholder } let ok = UIAlertAction(title: "OK", style: .default, handler: { [weak self] action in self?.playSound.playClickSound(SystemSound.buttonClick) var text = placeholder if alert.textFields![0].text! != "" { text = alert.textFields![0].text! } let isNameUsed = try? BookMark.find(matching: text, in: (self?.container?.viewContext)!) if isNameUsed! { self?.showAlert(title: "Error!", message: "Name already used, please give another name.") } else { let bookmark = MyBookmark(name: text, id: (self?.passedInNoteInfo?.id)!, time: Date(), readType: ReadType.read.rawValue, readPage: (self?.currentCardIndex)!, readPageStatus: nil) self?.container?.performBackgroundTask({ (context) in BookMark.findOrCreate(matching: bookmark, in: context) DispatchQueue.main.async { self?.showSavedPrompt() } }) } }) let cancel = UIAlertAction(title: "cancel", style: .cancel, handler: nil) alert.addAction(ok) alert.addAction(cancel) self.present(alert, animated: true, completion: nil) } // MARK: draw prograss bar private func updatePrograssLing(readingIndex: CGFloat) { let width = progressBarView.bounds.width * (readingIndex + 1) / CGFloat(passedInNotes.count) UIView.animate(withDuration: 0.3, delay: 0.02, options: [], animations: { self.barFinishedPart.frame.size.width = width }, completion: nil) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { updatePrograssLing(readingIndex: CGFloat(currentCardIndex)) } } extension ReadNoteViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return passedInNotes.count } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let newCell = cell as! ReadCollectionViewCell newCell.updateUI(noteType: (passedInNoteInfo?.type)!, title: passedInNotes[indexPath.row].title, body: passedInNotes[indexPath.row].body, index: indexPath.row) newCell.delegate = self } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) } }
36ec63790a6a5f3cc7484ddb5fb3f2b1
43.402597
194
0.676806
false
false
false
false
alecchyi/SwiftDemos
refs/heads/master
SwiftDemos/MapsViewController.swift
mit
1
// // MapsViewController.swift // SwiftDemos // // Created by dst-macpro1 on 15/10/22. // Copyright (c) 2015年 ibm. All rights reserved. // import UIKit import MapKit class MapsViewController: UIViewController { @IBOutlet weak var picImageView: UIImageView! @IBOutlet weak var moveBtn: UIButton! @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let center:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 40.029915, longitude: 116.347082) let span = MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2) let region = MKCoordinateRegion(center: center, span: span) // self.mapView.setRegion(region, animated: true) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.fetchLocationCities() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func clickMoveBtnEvent(sender: AnyObject) { UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: {() -> Void in var btnFrame = self.moveBtn.frame var frame = self.view.bounds var imgFrame = self.picImageView.frame if imgFrame.origin.x + imgFrame.size.width < frame.size.width { imgFrame.origin.x = frame.size.width - imgFrame.size.width }else { imgFrame.origin.x = btnFrame.origin.x + btnFrame.size.width + 5 } self.picImageView.frame = imgFrame }, completion: {[weak self](let b) -> Void in if let weakSelf = self { weakSelf.moveToEnd() } }) } func moveToEnd() { UIView.animateKeyframesWithDuration(2.0, delay: 0.0, options: UIViewKeyframeAnimationOptions.CalculationModeCubic, animations: {() -> Void in UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1.0/2.0, animations: {() -> Void in var frame = self.picImageView.frame frame.origin.y = self.view.frame.size.height self.picImageView.frame = frame }) UIView.addKeyframeWithRelativeStartTime(1.0/2.0, relativeDuration: 1.0/2.0, animations: {() -> Void in var frame = self.picImageView.frame var btnFrame = self.moveBtn.center self.picImageView.center = CGPointMake(btnFrame.x + frame.size.width, btnFrame.y) }) }, completion: nil) } func fetchLocationCities() { var res = NSBundle.mainBundle().pathForResource("locations", ofType: "plist") if let resources = res { if let citiesData = NSMutableArray(contentsOfFile: resources) { if (citiesData.count > 0) { for c in citiesData { if let city = c as? Dictionary<String,AnyObject> { self.addAnchorPoint(city) } } } } } } func addAnchorPoint(city:Dictionary<String, AnyObject>) { var pointAnnotation = MKPointAnnotation() let point = city["coordinate"] as! Dictionary<String, AnyObject> if let lat = point["lat"] as? Double, lng = point["lng"] as? Double { pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: lat , longitude: lng ) } pointAnnotation.title = city["location"] as! String pointAnnotation.subtitle = "" self.mapView.addAnnotation(pointAnnotation) } } extension MapsViewController:MKMapViewDelegate { }
e1534b2b8b20f59e6ae8e1f79da43211
34.035088
149
0.588883
false
false
false
false
cseduardorangel/Cantina
refs/heads/master
Cantina/Class/ViewController/LoginViewController.swift
mit
1
// // LoginViewController.swift // Cantina // // Created by Eduardo Rangel on 10/25/15. // Copyright © 2015 Concrete Solutions. All rights reserved. // import UIKit import Google class LoginViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate { ////////////////////////////////////////////////////////////////////// // MARK: IBOutlet @IBOutlet weak var indicatorView: UIActivityIndicatorView! ////////////////////////////////////////////////////////////////////// // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.setupGoogleSignIn() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } ////////////////////////////////////////////////////////////////////// // MARK: - Instance Methods func setupGoogleSignIn() { GIDSignIn.sharedInstance().delegate = self GIDSignIn.sharedInstance().uiDelegate = self GIDSignIn.sharedInstance().signInSilently() } ////////////////////////////////////////////////////////////////////// // MARK: - IBAction @IBAction func login(sender: AnyObject) { self.indicatorView.startAnimating() GIDSignIn.sharedInstance().signIn() } ////////////////////////////////////////////////////////////////////// // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } ////////////////////////////////////////////////////////////////////// // MARK: - GIDSignInDelegate func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) { if (error == nil) { CredentialsService.logInUser(user, completion: { (success, error) -> Void in self.indicatorView.stopAnimating() if(success){ self.performSegueWithIdentifier("SegueToPurchases", sender: self) }else { let alertController = UIAlertController.init(title: ":(", message: error as String, preferredStyle: .Alert) let okBtn = UIAlertAction.init(title: "Ok", style: .Cancel, handler: nil) alertController.addAction(okBtn) self.presentViewController(alertController, animated: true, completion: nil) } }) } } func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!, withError error: NSError!) { print(">>>>>>>>>> signIn:didDisconnectWithUser:withError") // NSNotificationCenter.defaultCenter().postNotificationName("ToggleAuthUINotification", object: nil, userInfo: ["statusText": "Usuário disconectado."]) } }
d2059842a02fae65dadecc968c37614d
28.606061
159
0.506143
false
false
false
false
Cezar2005/SuperChat
refs/heads/master
SuperChat/MyChatViewController.swift
lgpl-3.0
1
import UIKit import Alamofire import SwiftWebSocket import SwiftyJSON import RealmSwift //The ViewController of available chat rooms. class MyChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { /* ViewController properties. 'currUser' - it's a dictionary for a current session. 'availableUserRooms' - it's a dictionary for the list of available user room for a current user. 'selectedRoom' - it's an implementation of chat room object in the list that was selected by the user. 'tavleView' - it's an UI TableView. It contains the list of chat rooms. */ var currUser:[String: String] = [:] var availableUserRooms: [ChatRoomsService.Room] = [] var selectedRoom = ChatRoomsService.Room() @IBOutlet weak var tableView: UITableView! //The function gets information about current user and then gets information about available chat rooms for him. override func viewDidLoad() { super.viewDidLoad() InfoUserService().infoAboutUser( {(result1: [String: String]) -> Void in self.currUser = result1 ChatRoomsService().availableRooms( {(result2: [ChatRoomsService.Room]) -> Void in self.availableUserRooms = result2 self.tableView.reloadData() }) }) } //The function sends the entity of selected chat room from the list into the segue between screens. override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "MyChatToRoom" { let roomVC = segue.destinationViewController as! RoomViewController roomVC.currentRoom = self.selectedRoom } } //This is a line treatment of choice in tavleView. func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if !self.availableUserRooms.isEmpty { self.selectedRoom = self.availableUserRooms[indexPath.row] self.performSegueWithIdentifier("MyChatToRoom", sender: self) } } //The function returns a number of rows in tableView that will be displayed on the screen. func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if !self.availableUserRooms.isEmpty { return self.availableUserRooms.count } else { return 0 } } //The function returns the cell of tableView. The cells contain the login of the users. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestSwiftCell") if !self.availableUserRooms.isEmpty { for user in self.availableUserRooms[indexPath.row].users { if String(user.id) != self.currUser["id"] { cell.textLabel!.text = user.login break } else { cell.textLabel!.text = "error" } } } return cell } }
f7bb7218f2182ab42c00fb51e52c5e8e
38.469136
125
0.651126
false
false
false
false
tecgirl/firefox-ios
refs/heads/master
Client/Frontend/Browser/TemporaryDocument.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Deferred import Shared private let temporaryDocumentOperationQueue = OperationQueue() class TemporaryDocument: NSObject { fileprivate let request: URLRequest fileprivate let filename: String fileprivate var session: URLSession? fileprivate var downloadTask: URLSessionDownloadTask? fileprivate var localFileURL: URL? fileprivate var pendingResult: Deferred<URL>? init(preflightResponse: URLResponse, request: URLRequest) { self.request = request self.filename = preflightResponse.suggestedFilename ?? "unknown" super.init() self.session = URLSession(configuration: .default, delegate: self, delegateQueue: temporaryDocumentOperationQueue) } deinit { // Delete the temp file. if let url = localFileURL { try? FileManager.default.removeItem(at: url) } } func getURL() -> Deferred<URL> { if let url = localFileURL { let result = Deferred<URL>() result.fill(url) return result } if let result = pendingResult { return result } let result = Deferred<URL>() pendingResult = result downloadTask = session?.downloadTask(with: request) downloadTask?.resume() UIApplication.shared.isNetworkActivityIndicatorVisible = true return result } } extension TemporaryDocument: URLSessionTaskDelegate, URLSessionDownloadDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { ensureMainThread { UIApplication.shared.isNetworkActivityIndicatorVisible = false } // If we encounter an error downloading the temp file, just return with the // original remote URL so it can still be shared as a web URL. if error != nil, let remoteURL = request.url { pendingResult?.fill(remoteURL) pendingResult = nil } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("TempDocs") let url = tempDirectory.appendingPathComponent(filename) try? FileManager.default.createDirectory(at: tempDirectory, withIntermediateDirectories: true, attributes: nil) try? FileManager.default.removeItem(at: url) do { try FileManager.default.moveItem(at: location, to: url) localFileURL = url pendingResult?.fill(url) pendingResult = nil } catch let error { // If we encounter an error downloading the temp file, just return with the // original remote URL so it can still be shared as a web URL. if let remoteURL = request.url { pendingResult?.fill(remoteURL) pendingResult = nil } } } }
6238fab1e9a3b73cd7c47bc09fc63301
32.905263
122
0.65787
false
false
false
false
edx/edx-app-ios
refs/heads/master
Test/VideoTranscriptTests.swift
apache-2.0
2
// // VideoTranscriptTests.swift // edX // // Created by Danial Zahid on 1/11/17. // Updated by Salman on 05/03/2018. // Copyright © 2017 edX. All rights reserved. // import XCTest @testable import edX class VideoTranscriptTests: XCTestCase { func testTranscriptLoaded() { let environment = TestRouterEnvironment() let transcriptView = VideoTranscript(environment: environment) XCTAssertEqual(transcriptView.transcriptTableView.numberOfRows(inSection: 0), 0) XCTAssertTrue(transcriptView.transcriptTableView.isHidden) let transcriptParser = TranscriptParser() transcriptParser.parse(transcript: TranscriptDataFactory.validTranscriptString) { (success, error) in if success { transcriptView.updateTranscript(transcript: transcriptParser.transcripts) } } XCTAssertEqual(transcriptView.transcriptTableView.numberOfRows(inSection: 0), 11) XCTAssertFalse(transcriptView.transcriptTableView.isHidden) } func testTranscriptSeek() { let environment = TestRouterEnvironment() let transcriptView = VideoTranscript(environment: environment) let transcriptParser = TranscriptParser() transcriptParser.parse(transcript: TranscriptDataFactory.validTranscriptString) { (success, error) in if success { transcriptView.updateTranscript(transcript: transcriptParser.transcripts) } } transcriptView.highlightSubtitle(for: 4.83) XCTAssertEqual(transcriptView.highlightedIndex, 1) transcriptView.highlightSubtitle(for: 10.0) XCTAssertEqual(transcriptView.highlightedIndex, 2) transcriptView.highlightSubtitle(for: 12.93) XCTAssertEqual(transcriptView.highlightedIndex, 3) } }
ce14040db7d8906cafb4d088c9b22fd4
34.226415
109
0.693091
false
true
false
false
1457792186/JWSwift
refs/heads/develop
NBUStatProject/Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift
apache-2.0
4
// // BubbleChartRenderer.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class BubbleChartRenderer: BarLineScatterCandleBubbleRenderer { @objc open weak var dataProvider: BubbleChartDataProvider? @objc public init(dataProvider: BubbleChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } open override func drawData(context: CGContext) { guard let dataProvider = dataProvider, let bubbleData = dataProvider.bubbleData else { return } for set in bubbleData.dataSets as! [IBubbleChartDataSet] { if set.isVisible { drawDataSet(context: context, dataSet: set) } } } fileprivate func getShapeSize( entrySize: CGFloat, maxSize: CGFloat, reference: CGFloat, normalizeSize: Bool) -> CGFloat { let factor: CGFloat = normalizeSize ? ((maxSize == 0.0) ? 1.0 : sqrt(entrySize / maxSize)) : entrySize let shapeSize: CGFloat = reference * factor return shapeSize } fileprivate var _pointBuffer = CGPoint() fileprivate var _sizeBuffer = [CGPoint](repeating: CGPoint(), count: 2) @objc open func drawDataSet(context: CGContext, dataSet: IBubbleChartDataSet) { guard let dataProvider = dataProvider, let viewPortHandler = self.viewPortHandler, let animator = animator else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) let valueToPixelMatrix = trans.valueToPixelMatrix _sizeBuffer[0].x = 0.0 _sizeBuffer[0].y = 0.0 _sizeBuffer[1].x = 1.0 _sizeBuffer[1].y = 0.0 trans.pointValuesToPixel(&_sizeBuffer) context.saveGState() let normalizeSize = dataSet.isNormalizeSizeEnabled // calcualte the full width of 1 step on the x-axis let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x) let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop) let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth) for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1) { guard let entry = dataSet.entryForIndex(j) as? BubbleChartDataEntry else { continue } _pointBuffer.x = CGFloat(entry.x) _pointBuffer.y = CGFloat(entry.y * phaseY) _pointBuffer = _pointBuffer.applying(valueToPixelMatrix) let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize, normalizeSize: normalizeSize) let shapeHalf = shapeSize / 2.0 if !viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf) || !viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf) { continue } if !viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf) { continue } if !viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf) { break } let color = dataSet.color(atIndex: Int(entry.x)) let rect = CGRect( x: _pointBuffer.x - shapeHalf, y: _pointBuffer.y - shapeHalf, width: shapeSize, height: shapeSize ) context.setFillColor(color.cgColor) context.fillEllipse(in: rect) } context.restoreGState() } open override func drawValues(context: CGContext) { guard let dataProvider = dataProvider, let viewPortHandler = self.viewPortHandler, let bubbleData = dataProvider.bubbleData, let animator = animator else { return } // if values are drawn if isDrawingValuesAllowed(dataProvider: dataProvider) { guard let dataSets = bubbleData.dataSets as? [IBubbleChartDataSet] else { return } let phaseX = max(0.0, min(1.0, animator.phaseX)) let phaseY = animator.phaseY var pt = CGPoint() for i in 0..<dataSets.count { let dataSet = dataSets[i] if !shouldDrawValues(forDataSet: dataSet) { continue } let alpha = phaseX == 1 ? phaseY : phaseX guard let formatter = dataSet.valueFormatter else { continue } _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let iconsOffset = dataSet.iconsOffset for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1) { guard let e = dataSet.entryForIndex(j) as? BubbleChartDataEntry else { break } let valueTextColor = dataSet.valueTextColorAt(j).withAlphaComponent(CGFloat(alpha)) pt.x = CGFloat(e.x) pt.y = CGFloat(e.y * phaseY) pt = pt.applying(valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } if ((!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))) { continue } let text = formatter.stringForValue( Double(e.size), entry: e, dataSetIndex: i, viewPortHandler: viewPortHandler) // Larger font for larger bubbles? let valueFont = dataSet.valueFont let lineHeight = valueFont.lineHeight if dataSet.isDrawValuesEnabled { ChartUtils.drawText( context: context, text: text, point: CGPoint( x: pt.x, y: pt.y - (0.5 * lineHeight)), align: .center, attributes: [NSAttributedStringKey.font: valueFont, NSAttributedStringKey.foregroundColor: valueTextColor]) } if let icon = e.icon, dataSet.isDrawIconsEnabled { ChartUtils.drawImage(context: context, image: icon, x: pt.x + iconsOffset.x, y: pt.y + iconsOffset.y, size: icon.size) } } } } } open override func drawExtras(context: CGContext) { } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let dataProvider = dataProvider, let viewPortHandler = self.viewPortHandler, let bubbleData = dataProvider.bubbleData, let animator = animator else { return } context.saveGState() let phaseY = animator.phaseY for high in indices { guard let dataSet = bubbleData.getDataSetByIndex(high.dataSetIndex) as? IBubbleChartDataSet, dataSet.isHighlightEnabled else { continue } guard let entry = dataSet.entryForXValue(high.x, closestToY: high.y) as? BubbleChartDataEntry else { continue } if !isInBoundsX(entry: entry, dataSet: dataSet) { continue } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) _sizeBuffer[0].x = 0.0 _sizeBuffer[0].y = 0.0 _sizeBuffer[1].x = 1.0 _sizeBuffer[1].y = 0.0 trans.pointValuesToPixel(&_sizeBuffer) let normalizeSize = dataSet.isNormalizeSizeEnabled // calcualte the full width of 1 step on the x-axis let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x) let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop) let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth) _pointBuffer.x = CGFloat(entry.x) _pointBuffer.y = CGFloat(entry.y * phaseY) trans.pointValueToPixel(&_pointBuffer) let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize, normalizeSize: normalizeSize) let shapeHalf = shapeSize / 2.0 if !viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf) || !viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf) { continue } if !viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf) { continue } if !viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf) { break } let originalColor = dataSet.color(atIndex: Int(entry.x)) var h: CGFloat = 0.0 var s: CGFloat = 0.0 var b: CGFloat = 0.0 var a: CGFloat = 0.0 originalColor.getHue(&h, saturation: &s, brightness: &b, alpha: &a) let color = NSUIColor(hue: h, saturation: s, brightness: b * 0.5, alpha: a) let rect = CGRect( x: _pointBuffer.x - shapeHalf, y: _pointBuffer.y - shapeHalf, width: shapeSize, height: shapeSize) context.setLineWidth(dataSet.highlightCircleWidth) context.setStrokeColor(color.cgColor) context.strokeEllipse(in: rect) high.setDraw(x: _pointBuffer.x, y: _pointBuffer.y) } context.restoreGState() } }
29d39f3aaac881721d2c7164c16f59d5
34.776074
145
0.511961
false
false
false
false
vector-im/vector-ios
refs/heads/master
Riot/Managers/Call/CallPresenter.swift
apache-2.0
1
// // Copyright 2020 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation // swiftlint:disable file_length #if canImport(JitsiMeetSDK) import JitsiMeetSDK import CallKit #endif /// The number of milliseconds in one second. private let MSEC_PER_SEC: TimeInterval = 1000 @objcMembers /// Service to manage call screens and call bar UI management. class CallPresenter: NSObject { private enum Constants { static let pipAnimationDuration: TimeInterval = 0.25 static let groupCallInviteLifetime: TimeInterval = 30 } /// Utilized sessions private var sessions: [MXSession] = [] /// Call view controllers map. Keys are callIds. private var callVCs: [String: CallViewController] = [:] /// Call background tasks map. Keys are callIds. private var callBackgroundTasks: [String: MXBackgroundTask] = [:] /// Actively presented direct call view controller. private weak var presentedCallVC: UIViewController? { didSet { updateOnHoldCall() } } private weak var pipCallVC: UIViewController? /// UI operation queue for various UI operations private var uiOperationQueue: OperationQueue = .main /// Flag to indicate whether the presenter is active. private var isStarted: Bool = false #if canImport(JitsiMeetSDK) private var widgetEventsListener: Any? /// Jitsi calls map. Keys are CallKit call UUIDs, values are corresponding widgets. private var jitsiCalls: [UUID: Widget] = [:] /// The current Jitsi view controller being displayed or not. private(set) var jitsiVC: JitsiViewController? { didSet { updateOnHoldCall() } } #endif private var isCallKitEnabled: Bool { MXCallKitAdapter.callKitAvailable() && MXKAppSettings.standard()?.isCallKitEnabled == true } private var activeCallVC: UIViewController? { return callVCs.values.filter { (callVC) -> Bool in guard let call = callVC.mxCall else { return false } return !call.isOnHold }.first ?? jitsiVC } private var onHoldCallVCs: [CallViewController] { return callVCs.values.filter { (callVC) -> Bool in guard let call = callVC.mxCall else { return false } return call.isOnHold } } private var numberOfPausedCalls: UInt { return UInt(callVCs.values.filter { (callVC) -> Bool in guard let call = callVC.mxCall else { return false } return call.isOnHold }.count) } // MARK: - Public /// Maximum number of concurrent calls allowed. let maximumNumberOfConcurrentCalls: UInt = 2 /// Delegate object weak var delegate: CallPresenterDelegate? func addMatrixSession(_ session: MXSession) { sessions.append(session) } func removeMatrixSession(_ session: MXSession) { if let index = sessions.firstIndex(of: session) { sessions.remove(at: index) } } /// Start the service func start() { MXLog.debug("[CallPresenter] start") addCallObservers() } /// Stop the service func stop() { MXLog.debug("[CallPresenter] stop") removeCallObservers() } // MARK - Group Calls /// Open the Jitsi view controller from a widget. /// - Parameter widget: the jitsi widget func displayJitsiCall(withWidget widget: Widget) { MXLog.debug("[CallPresenter] displayJitsiCall: for widget: \(widget.widgetId)") #if canImport(JitsiMeetSDK) let createJitsiBlock = { [weak self] in guard let self = self else { return } self.jitsiVC = JitsiViewController() self.jitsiVC?.openWidget(widget, withVideo: true, success: { [weak self] in guard let self = self else { return } if let jitsiVC = self.jitsiVC { jitsiVC.delegate = self self.presentCallVC(jitsiVC) self.startJitsiCall(withWidget: widget) } }, failure: { [weak self] (error) in guard let self = self else { return } self.jitsiVC = nil AppDelegate.theDelegate().showAlert(withTitle: nil, message: VectorL10n.callJitsiError) }) } if let jitsiVC = jitsiVC { if jitsiVC.widget.widgetId == widget.widgetId { self.presentCallVC(jitsiVC) } else { // end previous Jitsi call first endActiveJitsiCall() createJitsiBlock() } } else { createJitsiBlock() } #else AppDelegate.theDelegate().showAlert(withTitle: nil, message: VectorL10n.notSupportedYet) #endif } private func startJitsiCall(withWidget widget: Widget) { MXLog.debug("[CallPresenter] startJitsiCall") if let uuid = self.jitsiCalls.first(where: { $0.value.widgetId == widget.widgetId })?.key { // this Jitsi call is already managed by this class, no need to report the call again MXLog.debug("[CallPresenter] startJitsiCall: already managed with id: \(uuid.uuidString)") return } guard let roomId = widget.roomId else { MXLog.debug("[CallPresenter] startJitsiCall: no roomId on widget") return } guard let session = sessions.first else { MXLog.debug("[CallPresenter] startJitsiCall: no active session") return } guard let room = session.room(withRoomId: roomId) else { MXLog.debug("[CallPresenter] startJitsiCall: unknown room: \(roomId)") return } let newUUID = UUID() let handle = CXHandle(type: .generic, value: roomId) let startCallAction = CXStartCallAction(call: newUUID, handle: handle) let transaction = CXTransaction(action: startCallAction) MXLog.debug("[CallPresenter] startJitsiCall: new call with id: \(newUUID.uuidString)") JMCallKitProxy.request(transaction) { (error) in MXLog.debug("[CallPresenter] startJitsiCall: JMCallKitProxy returned \(String(describing: error))") if error == nil { JMCallKitProxy.reportCallUpdate(with: newUUID, handle: roomId, displayName: room.summary.displayname, hasVideo: true) JMCallKitProxy.reportOutgoingCall(with: newUUID, connectedAt: nil) self.jitsiCalls[newUUID] = widget } } } func endActiveJitsiCall() { MXLog.debug("[CallPresenter] endActiveJitsiCall") guard let jitsiVC = jitsiVC else { // there is no active Jitsi call MXLog.debug("[CallPresenter] endActiveJitsiCall: no active Jitsi call") return } if pipCallVC == jitsiVC { // this call currently in the PiP mode, // first present it by exiting PiP mode and then dismiss it exitPipCallVC(jitsiVC) } dismissCallVC(jitsiVC) jitsiVC.hangup() self.jitsiVC = nil guard let widget = jitsiVC.widget else { MXLog.debug("[CallPresenter] endActiveJitsiCall: no Jitsi widget for the active call") return } guard let uuid = self.jitsiCalls.first(where: { $0.value.widgetId == widget.widgetId })?.key else { // this Jitsi call is not managed by this class MXLog.debug("[CallPresenter] endActiveJitsiCall: Not managed Jitsi call: \(widget.widgetId)") return } let endCallAction = CXEndCallAction(call: uuid) let transaction = CXTransaction(action: endCallAction) MXLog.debug("[CallPresenter] endActiveJitsiCall: ended call with id: \(uuid.uuidString)") JMCallKitProxy.request(transaction) { (error) in MXLog.debug("[CallPresenter] endActiveJitsiCall: JMCallKitProxy returned \(String(describing: error))") if error == nil { self.jitsiCalls.removeValue(forKey: uuid) } } } func processWidgetEvent(_ event: MXEvent, inSession session: MXSession) { MXLog.debug("[CallPresenter] processWidgetEvent") guard let widget = Widget(widgetEvent: event, inMatrixSession: session) else { MXLog.debug("[CallPresenter] processWidgetEvent: widget couldn't be created") return } guard JMCallKitProxy.isProviderConfigured() else { // CallKit proxy is not configured, no benefit in parsing the event MXLog.debug("[CallPresenter] processWidgetEvent: JMCallKitProxy not configured") hangupUnhandledCallIfNeeded(widget) return } if widget.isActive { if let uuid = self.jitsiCalls.first(where: { $0.value.widgetId == widget.widgetId })?.key { // this Jitsi call is already managed by this class, no need to report the call again MXLog.debug("[CallPresenter] processWidgetEvent: Jitsi call already managed with id: \(uuid.uuidString)") return } guard widget.type == kWidgetTypeJitsiV1 || widget.type == kWidgetTypeJitsiV2 else { // not a Jitsi widget, ignore MXLog.debug("[CallPresenter] processWidgetEvent: not a Jitsi widget") return } if let jitsiVC = jitsiVC, jitsiVC.widget.widgetId == widget.widgetId { // this is already the Jitsi call we have atm MXLog.debug("[CallPresenter] processWidgetEvent: ongoing Jitsi call") return } if TimeInterval(event.age)/MSEC_PER_SEC > Constants.groupCallInviteLifetime { // too late to process the event MXLog.debug("[CallPresenter] processWidgetEvent: expired call invite") return } // an active Jitsi widget let newUUID = UUID() // assume this Jitsi call will survive self.jitsiCalls[newUUID] = widget if event.sender == session.myUserId { // outgoing call MXLog.debug("[CallPresenter] processWidgetEvent: Report outgoing call with id: \(newUUID.uuidString)") JMCallKitProxy.reportOutgoingCall(with: newUUID, connectedAt: nil) } else { // incoming call guard RiotSettings.shared.enableRingingForGroupCalls else { // do not ring for Jitsi calls return } let user = session.user(withUserId: event.sender) let displayName = NSString.localizedUserNotificationString(forKey: "GROUP_CALL_FROM_USER", arguments: [user?.displayname as Any]) MXLog.debug("[CallPresenter] processWidgetEvent: Report new incoming call with id: \(newUUID.uuidString)") JMCallKitProxy.reportNewIncomingCall(UUID: newUUID, handle: widget.roomId, displayName: displayName, hasVideo: true) { (error) in MXLog.debug("[CallPresenter] processWidgetEvent: JMCallKitProxy returned \(String(describing: error))") if error != nil { self.jitsiCalls.removeValue(forKey: newUUID) } } } } else { guard let uuid = self.jitsiCalls.first(where: { $0.value.widgetId == widget.widgetId })?.key else { // this Jitsi call is not managed by this class MXLog.debug("[CallPresenter] processWidgetEvent: not managed Jitsi call: \(widget.widgetId)") hangupUnhandledCallIfNeeded(widget) return } MXLog.debug("[CallPresenter] processWidgetEvent: ended call with id: \(uuid.uuidString)") JMCallKitProxy.reportCall(with: uuid, endedAt: nil, reason: .remoteEnded) self.jitsiCalls.removeValue(forKey: uuid) } } // MARK: - Private private func updateOnHoldCall() { guard let presentedCallVC = presentedCallVC as? CallViewController else { return } if onHoldCallVCs.isEmpty { // no on hold calls, clear the call presentedCallVC.mxCallOnHold = nil } else { for callVC in onHoldCallVCs where callVC != presentedCallVC { // do not set the same call (can happen in case of two on hold calls) presentedCallVC.mxCallOnHold = callVC.mxCall break } } } private func shouldHandleCall(_ call: MXCall) -> Bool { return callVCs.count < maximumNumberOfConcurrentCalls } private func callHolded(withCallId callId: String) { updateOnHoldCall() } private func endCall(withCallId callId: String) { guard let callVC = callVCs[callId] else { return } let completion = { [weak self] in guard let self = self else { return } self.updateOnHoldCall() self.callVCs.removeValue(forKey: callId) callVC.destroy() self.callBackgroundTasks[callId]?.stop() self.callBackgroundTasks.removeValue(forKey: callId) // if still have some calls and there is no present operation in the queue if let oldCallVC = self.callVCs.values.first, self.presentedCallVC == nil, !self.uiOperationQueue.containsPresentCallVCOperation, !self.uiOperationQueue.containsEnterPiPOperation, let oldCall = oldCallVC.mxCall, oldCall.state != .ended { // present the call screen after dismissing this one self.presentCallVC(oldCallVC) } } if pipCallVC == callVC { // this call currently in the PiP mode, // first present it by exiting PiP mode and then dismiss it exitPipCallVC(callVC) { self.dismissCallVC(callVC, completion: completion) } return } if callVC.isDisplayingAlert { completion() } else { dismissCallVC(callVC, completion: completion) } } private func logCallVC(_ callVC: UIViewController, log: String) { if let callVC = callVC as? CallViewController { MXLog.debug("[CallPresenter] \(log): Matrix call: \(String(describing: callVC.mxCall?.callId))") } else if let callVC = callVC as? JitsiViewController { MXLog.debug("[CallPresenter] \(log): Jitsi call: \(callVC.widget.widgetId)") } } // MARK: - Observers private func addCallObservers() { guard !isStarted else { return } NotificationCenter.default.addObserver(self, selector: #selector(newCall(_:)), name: NSNotification.Name(rawValue: kMXCallManagerNewCall), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(callStateChanged(_:)), name: NSNotification.Name(rawValue: kMXCallStateDidChange), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(callTileTapped(_:)), name: .RoomCallTileTapped, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(groupCallTileTapped(_:)), name: .RoomGroupCallTileTapped, object: nil) isStarted = true #if canImport(JitsiMeetSDK) JMCallKitProxy.addListener(self) guard let session = sessions.first else { return } widgetEventsListener = session.listenToEvents([ MXEventType(identifier: kWidgetMatrixEventTypeString), MXEventType(identifier: kWidgetModularEventTypeString) ]) { (event, direction, _) in if direction == .backwards { // ignore backwards events return } self.processWidgetEvent(event, inSession: session) } #endif } private func removeCallObservers() { guard isStarted else { return } NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kMXCallManagerNewCall), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kMXCallStateDidChange), object: nil) NotificationCenter.default.removeObserver(self, name: .RoomCallTileTapped, object: nil) NotificationCenter.default.removeObserver(self, name: .RoomGroupCallTileTapped, object: nil) isStarted = false #if canImport(JitsiMeetSDK) JMCallKitProxy.removeListener(self) guard let session = sessions.first else { return } if let widgetEventsListener = widgetEventsListener { session.removeListener(widgetEventsListener) } widgetEventsListener = nil #endif } @objc private func newCall(_ notification: Notification) { guard let call = notification.object as? MXCall else { return } if !shouldHandleCall(call) { return } guard let newCallVC = CallViewController(call) else { return } newCallVC.playRingtone = !isCallKitEnabled newCallVC.delegate = self if !call.isIncoming { // put other native calls on hold callVCs.values.forEach({ $0.mxCall.hold(true) }) // terminate Jitsi calls endActiveJitsiCall() } callVCs[call.callId] = newCallVC if UIApplication.shared.applicationState == .background && call.isIncoming { // Create backgound task. // Without CallKit this will allow us to play vibro until the call was ended // With CallKit we'll inform the system when the call is ended to let the system terminate our app to save resources let handler = MXSDKOptions.sharedInstance().backgroundModeHandler let callBackgroundTask = handler.startBackgroundTask(withName: "[CallPresenter] addMatrixCallObserver", expirationHandler: nil) callBackgroundTasks[call.callId] = callBackgroundTask } if call.isIncoming && isCallKitEnabled { return } else { presentCallVC(newCallVC) } } @objc private func callStateChanged(_ notification: Notification) { guard let call = notification.object as? MXCall else { return } switch call.state { case .createAnswer: MXLog.debug("[CallPresenter] callStateChanged: call created answer: \(call.callId)") if call.isIncoming, isCallKitEnabled, let callVC = callVCs[call.callId] { presentCallVC(callVC) } case .connected: MXLog.debug("[CallPresenter] callStateChanged: call connected: \(call.callId)") case .onHold: MXLog.debug("[CallPresenter] callStateChanged: call holded: \(call.callId)") callHolded(withCallId: call.callId) case .remotelyOnHold: MXLog.debug("[CallPresenter] callStateChanged: call remotely holded: \(call.callId)") callHolded(withCallId: call.callId) case .ended: MXLog.debug("[CallPresenter] callStateChanged: call ended: \(call.callId)") endCall(withCallId: call.callId) default: break } } @objc private func callTileTapped(_ notification: Notification) { MXLog.debug("[CallPresenter] callTileTapped") guard let bubbleData = notification.object as? RoomBubbleCellData else { return } guard let randomEvent = bubbleData.allLinkedEvents().randomElement() else { return } guard let callEventContent = MXCallEventContent(fromJSON: randomEvent.content) else { return } MXLog.debug("[CallPresenter] callTileTapped: for call: \(callEventContent.callId)") guard let session = sessions.first else { return } guard let call = session.callManager.call(withCallId: callEventContent.callId) else { return } if call.state == .ended { return } guard let callVC = callVCs[call.callId] else { return } if callVC == pipCallVC { exitPipCallVC(callVC) } else { presentCallVC(callVC) } } @objc private func groupCallTileTapped(_ notification: Notification) { MXLog.debug("[CallPresenter] groupCallTileTapped") guard let bubbleData = notification.object as? RoomBubbleCellData else { return } guard let randomEvent = bubbleData.allLinkedEvents().randomElement() else { return } guard randomEvent.eventType == .custom, (randomEvent.type == kWidgetMatrixEventTypeString || randomEvent.type == kWidgetModularEventTypeString) else { return } guard let session = sessions.first else { return } guard let widget = Widget(widgetEvent: randomEvent, inMatrixSession: session) else { return } MXLog.debug("[CallPresenter] groupCallTileTapped: for call: \(widget.widgetId)") guard let jitsiVC = jitsiVC, jitsiVC.widget.widgetId == widget.widgetId else { return } if jitsiVC == pipCallVC { exitPipCallVC(jitsiVC) } else { presentCallVC(jitsiVC) } } // MARK: - Call Screens private func presentCallVC(_ callVC: UIViewController, completion: (() -> Void)? = nil) { logCallVC(callVC, log: "presentCallVC") // do not use PiP transitions here, as we really want to present the screen callVC.transitioningDelegate = nil if let presentedCallVC = presentedCallVC { dismissCallVC(presentedCallVC) } let operation = CallVCPresentOperation(presenter: self, callVC: callVC) { [weak self] in self?.presentedCallVC = callVC if callVC == self?.pipCallVC { self?.pipCallVC = nil } completion?() } uiOperationQueue.addOperation(operation) } private func dismissCallVC(_ callVC: UIViewController, completion: (() -> Void)? = nil) { logCallVC(callVC, log: "dismissCallVC") // do not use PiP transitions here, as we really want to dismiss the screen callVC.transitioningDelegate = nil let operation = CallVCDismissOperation(presenter: self, callVC: callVC) { [weak self] in if callVC == self?.presentedCallVC { self?.presentedCallVC = nil } completion?() } uiOperationQueue.addOperation(operation) } private func enterPipCallVC(_ callVC: UIViewController, completion: (() -> Void)? = nil) { logCallVC(callVC, log: "enterPipCallVC") // assign self as transitioning delegate callVC.transitioningDelegate = self let operation = CallVCEnterPipOperation(presenter: self, callVC: callVC) { [weak self] in self?.pipCallVC = callVC if callVC == self?.presentedCallVC { self?.presentedCallVC = nil } completion?() } uiOperationQueue.addOperation(operation) } private func exitPipCallVC(_ callVC: UIViewController, completion: (() -> Void)? = nil) { logCallVC(callVC, log: "exitPipCallVC") // assign self as transitioning delegate callVC.transitioningDelegate = self let operation = CallVCExitPipOperation(presenter: self, callVC: callVC) { [weak self] in if callVC == self?.pipCallVC { self?.pipCallVC = nil } self?.presentedCallVC = callVC completion?() } uiOperationQueue.addOperation(operation) } /// Hangs up current Jitsi call, if it is inactive and associated with given widget. /// Should be used for calls that are not handled through JMCallKitProxy, /// as these should be removed regardless. private func hangupUnhandledCallIfNeeded(_ widget: Widget) { guard !widget.isActive, widget.widgetId == jitsiVC?.widget.widgetId else { return } MXLog.debug("[CallPresenter] hangupUnhandledCallIfNeeded: ending call with Widget id: %@", widget.widgetId) endActiveJitsiCall() } } // MARK: - MXKCallViewControllerDelegate extension CallPresenter: MXKCallViewControllerDelegate { func dismiss(_ callViewController: MXKCallViewController!, completion: (() -> Void)!) { guard let callVC = callViewController as? CallViewController else { // this call screen is not handled by this service completion?() return } if callVC.mxCall == nil || callVC.mxCall.state == .ended { // wait for the call state changes, will be handled there return } else { // go to pip mode here enterPipCallVC(callVC, completion: completion) } } func callViewControllerDidTap(onHoldCall callViewController: MXKCallViewController!) { guard let callOnHold = callViewController.mxCallOnHold else { return } guard let onHoldCallVC = callVCs[callOnHold.callId] else { return } if callOnHold.state == .onHold { // call is on hold locally, switch calls callViewController.mxCall.hold(true) callOnHold.hold(false) } // switch screens presentCallVC(onHoldCallVC) } } // MARK: - UIViewControllerTransitioningDelegate extension CallPresenter: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return PiPAnimator(animationDuration: Constants.pipAnimationDuration, animationType: .exit, pipViewDelegate: nil) } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return PiPAnimator(animationDuration: Constants.pipAnimationDuration, animationType: .enter, pipViewDelegate: self) } } // MARK: - PiPViewDelegate extension CallPresenter: PiPViewDelegate { func pipViewDidTap(_ view: PiPView) { guard let pipCallVC = pipCallVC else { return } exitPipCallVC(pipCallVC) } } // MARK: - OperationQueue Extension extension OperationQueue { var containsPresentCallVCOperation: Bool { return containsOperation(ofType: CallVCPresentOperation.self) } var containsEnterPiPOperation: Bool { return containsOperation(ofType: CallVCEnterPipOperation.self) } private func containsOperation(ofType type: Operation.Type) -> Bool { return operations.contains { (operation) -> Bool in return operation.isKind(of: type.self) } } } #if canImport(JitsiMeetSDK) // MARK: - JMCallKitListener extension CallPresenter: JMCallKitListener { func providerDidReset() { } func performAnswerCall(UUID: UUID) { guard let widget = jitsiCalls[UUID] else { return } displayJitsiCall(withWidget: widget) } func performEndCall(UUID: UUID) { guard let widget = jitsiCalls[UUID] else { return } if let jitsiVC = jitsiVC, jitsiVC.widget.widgetId == widget.widgetId { // hangup an active call dismissCallVC(jitsiVC) endActiveJitsiCall() } else { // decline incoming call JitsiService.shared.declineWidget(withId: widget.widgetId) } } func performSetMutedCall(UUID: UUID, isMuted: Bool) { guard let widget = jitsiCalls[UUID] else { return } if let jitsiVC = jitsiVC, jitsiVC.widget.widgetId == widget.widgetId { // mute the active Jitsi call jitsiVC.setAudioMuted(isMuted) } } func performStartCall(UUID: UUID, isVideo: Bool) { } func providerDidActivateAudioSession(session: AVAudioSession) { } func providerDidDeactivateAudioSession(session: AVAudioSession) { } func providerTimedOutPerformingAction(action: CXAction) { } } // MARK: - JitsiViewControllerDelegate extension CallPresenter: JitsiViewControllerDelegate { func jitsiViewController(_ jitsiViewController: JitsiViewController!, dismissViewJitsiController completion: (() -> Void)!) { if jitsiViewController == jitsiVC { endActiveJitsiCall() } } func jitsiViewController(_ jitsiViewController: JitsiViewController!, goBackToApp completion: (() -> Void)!) { if jitsiViewController == jitsiVC { enterPipCallVC(jitsiViewController, completion: completion) } } } #endif
defd1efbebae9f4a37ba9941bfbd7947
35.052922
170
0.566758
false
false
false
false
BrianSemiglia/Cycle.swift
refs/heads/master
Sources/Core/Cycle.swift
mit
1
// // Cycle.swift // Cycle // // Created by Brian Semiglia on 1/2/17. // Copyright © 2017 Brian Semiglia. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxSwift open class CycledApplicationDelegate<T: IORouter>: UIResponder, UIApplicationDelegate { private var cycle: Cycle<T> public var window: UIWindow? public override init() { fatalError("CycledApplicationDelegate must be instantiated with a router.") } public init(router: T) { cycle = Cycle(router: router) super.init() } public func application( _ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil ) -> Bool { window = UIWindow(frame: UIScreen.main.bounds, root: cycle.root) window?.makeKeyAndVisible() return cycle.delegate.application!( application, willFinishLaunchingWithOptions: launchOptions ) } override open func forwardingTarget(for input: Selector!) -> Any? { return cycle.delegate } override open func responds(to input: Selector!) -> Bool { return cycle.delegate.responds(to: input) } } extension UIWindow { convenience init(frame: CGRect, root: UIViewController) { self.init(frame: frame) rootViewController = root } } #elseif os(watchOS) import WatchKit import RxSwift open class CycledApplicationDelegate<T: IORouter>: NSObject, WKExtensionDelegate { private var cycle: Cycle<T> public override init() { fatalError("CycledApplicationDelegate must be instantiated with a router.") } public init(router: T) { cycle = Cycle(router: router) super.init() } override open func forwardingTarget(for input: Selector!) -> Any? { return cycle.delegate } override open func responds(to input: Selector!) -> Bool { return cycle.delegate.responds(to: input) } } #elseif os(macOS) import AppKit import RxSwift open class CycledApplicationDelegate<T: IORouter>: NSObject, NSApplicationDelegate { private var cycle: Cycle<T> public var main: NSWindowController? // <-- change to (NSWindow, NSViewController) combo to avoid internal storyboard use below public override init() { fatalError("CycledApplicationDelegate must be instantiated with a router.") } public init(router: T) { cycle = Cycle(router: router) super.init() } public func applicationWillFinishLaunching(_ notification: Notification) { main = NSStoryboard( name: "Main", bundle: nil ) .instantiateController( withIdentifier: "MainWindow" ) as? NSWindowController main?.window?.contentViewController = cycle.root main?.window?.makeKeyAndOrderFront(nil) } override open func forwardingTarget(for input: Selector!) -> Any? { return cycle.delegate } override open func responds(to input: Selector!) -> Bool { if input == #selector(applicationWillFinishLaunching(_:)) { applicationWillFinishLaunching( Notification( name: Notification.Name( rawValue: "" ) ) ) } return cycle.delegate.responds( to: input ) } } #endif public final class Cycle<E: IORouter> { private var output: Observable<E.Frame>? private var inputProxy: ReplaySubject<E.Frame>? private let cleanup = DisposeBag() private let drivers: E.Drivers fileprivate let delegate: AppDelegate fileprivate let root: AppView public required init(router: E) { inputProxy = ReplaySubject.create( bufferSize: 1 ) drivers = router.driversFrom(seed: E.seed) root = drivers.screen.root delegate = drivers.application output = router.effectsOfEventsCapturedAfterRendering( incoming: inputProxy!, to: drivers ) // `.startWith` is redundant, but necessary to kickoff cycle // Possibly removed if `output` was BehaviorSubject? // Not sure how to `merge` observables to single BehaviorSubject though. output? .startWith(E.seed) .subscribe(self.inputProxy!.on) .disposed(by: cleanup) } } public protocol IORouter { /* Defines schema and initial values of application model. */ associatedtype Frame static var seed: Frame { get } /* Defines drivers that handle effects, produce events. Requires two default drivers: 1. let application: UIApplicationDelegateProviding - can serve as UIApplicationDelegate 2. let screen: ScreenDrivable - can provide a root UIViewController A default UIApplicationDelegateProviding driver, RxUIApplicationDelegate, is included with Cycle. */ associatedtype Drivers: MainDelegateProviding, ScreenDrivable /* Instantiates drivers with initial model. Necessary to for drivers that require initial values. */ func driversFrom(seed: Frame) -> Drivers /* Returns a stream of Models created by rendering the incoming stream of effects to Drivers and then capturing and transforming Driver events into the Model type. */ func effectsOfEventsCapturedAfterRendering( incoming: Observable<Frame>, to drivers: Drivers ) -> Observable<Frame> } public protocol ScreenDrivable { associatedtype Driver: RootViewProviding var screen: Driver { get } } public protocol RootViewProviding { #if os(macOS) var root: NSViewController { get } #elseif os(iOS) || os(tvOS) var root: UIViewController { get } #elseif os(watchOS) var root: WKInterfaceController { get } #endif } public protocol MainDelegateProviding { #if os(macOS) associatedtype Delegate: NSApplicationDelegate #elseif os(iOS) || os(tvOS) associatedtype Delegate: UIApplicationDelegate #elseif os(watchOS) associatedtype Delegate: WKExtensionDelegate #endif var application: Delegate { get } } #if os(macOS) typealias AppDelegate = NSApplicationDelegate #elseif os(iOS) || os(tvOS) typealias AppDelegate = UIApplicationDelegate #elseif os(watchOS) typealias AppDelegate = WKExtensionDelegate #endif #if os(macOS) typealias AppView = NSViewController #elseif os(iOS) || os(tvOS) typealias AppView = UIViewController #elseif os(watchOS) typealias AppView = WKInterfaceController #endif
6984cd3815072e9bc3ef63c47433a26c
24.90795
163
0.710433
false
false
false
false
abellono/IssueReporter
refs/heads/master
IssueReporter/Core/ViewController/ReporterViewController.swift
mit
1
// // ReporterViewController.swift // IssueReporter // // Created by Hakon Hanesand on 10/6/16. // Copyright © 2017 abello. All rights reserved. // // import Foundation import UIKit import CoreGraphics internal class ReporterViewController: UIViewController { private static let kABETextFieldInset = 14 private static let kABEdescriptionTextViewCornerRadius: CGFloat = 4 private static let kABEdescriptionTextViewBorderWidth: CGFloat = 0.5 private static let kABETableName = "IssueReporter-Localizable" @IBOutlet private var descriptionTextView: UITextView! @IBOutlet private var titleTextField: UITextField! @IBOutlet private var placeHolderLabel: UILabel! private var imageCollectionViewController: ImageCollectionViewController! var issueManager: IssueManager! { didSet { issueManager.delegate = self } } class func instance(withIssueManager manager: IssueManager) -> ReporterViewController { let storyboard = UIStoryboard(name: String(describing: self), bundle: Bundle.bundleForLibrary()) let reporterViewController = storyboard.instantiateInitialViewController() as! ReporterViewController reporterViewController.issueManager = manager return reporterViewController } override func viewDidLoad() { super.viewDidLoad() configureTextView() setupLocalization() navigationController?.navigationBar.barTintColor = UIColor.blueNavigationBarColor() navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white] // navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white] } private func configureTextView() { let spacerView = UIView(frame: CGRect(x: 0, y: 0, width: ReporterViewController.kABETextFieldInset, height: ReporterViewController.kABETextFieldInset)) titleTextField.leftViewMode = .always titleTextField.leftView = spacerView descriptionTextView.layer.borderColor = UIColor.greyBorderColor().cgColor descriptionTextView.layer.cornerRadius = ReporterViewController.kABEdescriptionTextViewCornerRadius descriptionTextView.layer.borderWidth = ReporterViewController.kABEdescriptionTextViewBorderWidth let textFieldInset = CGFloat(ReporterViewController.kABETextFieldInset) descriptionTextView.textContainerInset = UIEdgeInsets(top: textFieldInset, left: textFieldInset, bottom: 0, right: textFieldInset) descriptionTextView.delegate = self } private func setupLocalization() { titleTextField.placeholder = NSLocalizedString(titleTextField.placeholder!, tableName: ReporterViewController.kABETableName, bundle: Bundle.bundleForLibrary(), comment: "title of issue") placeHolderLabel.text = NSLocalizedString(placeHolderLabel.text!, tableName: ReporterViewController.kABETableName, bundle: Bundle.bundleForLibrary(), comment: "placeholder for description") title = NSLocalizedString(navigationItem.title!, tableName: ReporterViewController.kABETableName, bundle: Bundle.bundleForLibrary(), comment: "title") } @IBAction func cancelIssueReporting(_ sender: AnyObject) { dismissIssueReporter(success: false) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier, identifier == "embed_segue" { imageCollectionViewController = segue.destination as? ImageCollectionViewController imageCollectionViewController.issueManager = issueManager } } @objc func saveIssue() { if let name = UserDefaults.standard.string(forKey: "tester_name") { return saveIssueInternal(name: name) } if (Reporter.shouldPresentNameAlert()) { return presentNameAlertBeforeSave() } else { saveIssueInternal(name: "No Name") } } private func saveIssueInternal(name: String) { UserDefaults.standard.set(name, forKey: "tester_name") issueManager.issue.title = titleTextField.text ?? "" issueManager.issue.issueDescription = descriptionTextView.text issueManager.saveIssue(completion: { [weak self] in guard let strongSelf = self else { return } DispatchQueue.main.async { strongSelf.dismissIssueReporter(success: true) } }) } func dismissIssueReporter(success: Bool) { view.endEditing(false) Reporter.dismissReporterView(with: success) } // Name Dialoge func presentNameAlertBeforeSave() { let alert = UIAlertController(title: "What is your first name?", message: "So we can shoot you a message to further investigate, if need be.", preferredStyle: .alert) alert.addTextField(configurationHandler: nil) alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { [weak self] _ in guard let name = alert.textFields?.first?.text else { return } self?.saveIssueInternal(name: name) })) present(alert, animated: true) } } extension ReporterViewController: IssueManagerDelegate { static let spinner = UIActivityIndicatorView(style: .white) internal func issueManagerUploadingStateDidChange(issueManager: IssueManager) { imageCollectionViewController?.collectionView?.reloadData() if issueManager.isUploading == ReporterViewController.spinner.isAnimating { return } if issueManager.isUploading { let spinner = UIActivityIndicatorView(style: .white) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: spinner) navigationItem.rightBarButtonItem?.isEnabled = false ReporterViewController.spinner.startAnimating() } else { ReporterViewController.spinner.stopAnimating() navigationItem.rightBarButtonItem = UIBarButtonItem.saveButton(self, action: #selector(ReporterViewController.saveIssue)) navigationItem.rightBarButtonItem?.isEnabled = true } } internal func issueManager(_ issueManager: IssueManager, didFailToUploadImage image: Image, error: IssueReporterError) { if issueManager.images.index(of: image) != nil { let alert = UIAlertController(error: error) present(alert, animated: true) } } internal func issueManager(_ issueManager: IssueManager, didFailToUploadFile file: File, error: IssueReporterError) { let alert = UIAlertController(error: error) present(alert, animated: true) } internal func issueManager(_ issueManager: IssueManager, didFailToUploadIssueWithError error: IssueReporterError) { let alert = UIAlertController(error: error) alert.addAction(UIAlertAction(title: "Retry", style: .default) { [weak self] _ in guard let strongSelf = self else { return } strongSelf.saveIssue() }) present(alert, animated: true) } } extension ReporterViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { let length = textView.text?.count ?? 0 let shouldHide = length > 0 placeHolderLabel.isHidden = shouldHide } }
35be8e7d58a51dac9f31f3abbbf0c6b4
37.21028
159
0.645469
false
false
false
false
KrishMunot/swift
refs/heads/master
test/SILGen/import_as_member.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen -I %S/../IDE/Inputs/custom-modules %s 2>&1 | FileCheck --check-prefix=SIL %s // REQUIRES: objc_interop import ImportAsMember.A import ImportAsMember.Proto import ImportAsMember.Class public func returnGlobalVar() -> Double { return Struct1.globalVar } // SIL-LABEL: sil {{.*}}returnGlobalVar{{.*}} () -> Double { // SIL: %0 = global_addr @IAMStruct1GlobalVar : $*Double // SIL: %2 = load %0 : $*Double // SIL: return %2 : $Double // SIL-NEXT: } // SIL-LABEL: sil {{.*}}useProto{{.*}} (@owned IAMProto) -> () { // TODO: Add in body checks public func useProto(p: IAMProto) { p.mutateSomeState() let v = p.someValue p.someValue = v+1 } // SIL-LABEL: sil {{.*}}anchor{{.*}} () -> () { func anchor() {} // SIL-LABEL: sil {{.*}}useClass{{.*}} // SIL: bb0([[D:%[0-9]+]] : $Double, [[OPTS:%[0-9]+]] : $SomeClass.Options): public func useClass(d: Double, opts: SomeClass.Options) { // SIL: [[CTOR:%[0-9]+]] = function_ref @MakeIAMSomeClass : $@convention(c) (Double) -> @autoreleased SomeClass // SIL: [[OBJ:%[0-9]+]] = apply [[CTOR]]([[D]]) let o = SomeClass(value: d) // SIL: [[APPLY_FN:%[0-9]+]] = function_ref @IAMSomeClassApplyOptions : $@convention(c) (SomeClass, SomeClass.Options) -> () // SIL: apply [[APPLY_FN]]([[OBJ]], [[OPTS]]) o.applyOptions(opts) } extension SomeClass { // SIL-LABEL: sil hidden @_TFE16import_as_memberCSo9SomeClasscfT6doubleSd_S0_ // SIL: bb0([[DOUBLE:%[0-9]+]] : $Double // SIL-NOT: value_metatype // SIL: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass // SIL: apply [[FNREF]]([[DOUBLE]]) convenience init(double: Double) { self.init(value: double) } }
e115f6c019437172e0f2aaab6951ee12
33.854167
126
0.620442
false
false
false
false
goyuanfang/SXSwiftWeibo
refs/heads/master
103 - swiftWeibo/103 - swiftWeibo/Classes/UI/OAuth/OAuthViewController.swift
mit
1
// // OAuthViewController.swift // 02-TDD // // Created by apple on 15/2/28. // Copyright (c) 2015年 heima. All rights reserved. // import UIKit import SwiftJ2M // 定义全局常量 let WB_Login_Successed_Notification = "WB_Login_Successed_Notification" class OAuthViewController: UIViewController { let WB_API_URL_String = "https://api.weibo.com" let WB_Redirect_URL_String = "http://www.baidu.com" let WB_Client_ID = "258115387" let WB_Client_Secret = "e6bc5950db8f4a041f09bd6ebeca8ec9" let WB_Grant_Type = "authorization_code" @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() loadAuthPage() } /// 加载授权页面 func loadAuthPage() { let urlString = "https://api.weibo.com/oauth2/authorize?client_id=258115387&redirect_uri=http://www.baidu.com" let url = NSURL(string: urlString) webView.loadRequest(NSURLRequest(URL: url!)) } } extension OAuthViewController: UIWebViewDelegate { func webViewDidStartLoad(webView: UIWebView) { println(__FUNCTION__) } func webViewDidFinishLoad(webView: UIWebView) { println(__FUNCTION__) } func webView(webView: UIWebView, didFailLoadWithError error: NSError) { println(__FUNCTION__) } /// 页面重定向 func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { println(request.URL) let result = continueWithCode(request.URL!) if let code = result.code { println("可以换 accesstoke \(code)") let params = ["client_id": WB_Client_ID, "client_secret": WB_Client_Secret, "grant_type":WB_Grant_Type, "redirect_uri": WB_Redirect_URL_String, "code": code] let net = NetworkManager.sharedManager net.requestJSON(.POST, "https://api.weibo.com/oauth2/access_token", params) { (result, error) -> () in println(result) let token = AccessToken(dict: result as! NSDictionary) token.saveAccessToken() // 切换UI - 通知 NSNotificationCenter.defaultCenter().postNotificationName(WB_Login_Successed_Notification, object: nil) } } if !result.load { println(request.URL) if result.reloadPage{ SVProgressHUD.showInfoWithStatus("真的要取消么", maskType: SVProgressHUDMaskType.Black) loadAuthPage() } } return result.load } /// 根据 URL 判断是否继续加载页面 /// 返回:是否加载,如果有 code,同时返回 code,否则返回 nil func continueWithCode(url: NSURL) -> (load: Bool, code: String?, reloadPage: Bool) { // 1. 将url转换成字符串 let urlString = url.absoluteString! // 2. 如果不是微博的 api 地址,都不加载 if !urlString.hasPrefix(WB_API_URL_String) { // 3. 如果是回调地址,需要判断 code if urlString.hasPrefix(WB_Redirect_URL_String) { if let query = url.query { let codestr: NSString = "code=" if query.hasPrefix(codestr as String) { var q = query as NSString! return (false, q.substringFromIndex(codestr.length),false) }else { return (false, nil, true) } } } return (false, nil,false) } return (true, nil,false) } }
4de1f3f095f35c81b7eb55eb170ccecd
29.491935
137
0.544829
false
false
false
false
seem-sky/ios-charts
refs/heads/master
Charts/Classes/Charts/ChartViewBase.swift
apache-2.0
1
// // ChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // // Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880 import Foundation import UIKit; @objc public protocol ChartViewDelegate { /// Called when a value has been selected inside the chart. /// :entry: The selected Entry. /// :dataSetIndex: The index in the datasets array of the data object the Entrys DataSet is in. optional func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight); // Called when nothing has been selected or an "un-select" has been made. optional func chartValueNothingSelected(chartView: ChartViewBase); } public class ChartViewBase: UIView, ChartAnimatorDelegate { // MARK: - Properties /// custom formatter that is used instead of the auto-formatter if set internal var _valueFormatter = NSNumberFormatter() /// the default value formatter internal var _defaultValueFormatter = NSNumberFormatter() /// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied internal var _data: ChartData! /// font object used for drawing the description text in the bottom right corner of the chart public var descriptionFont: UIFont? = UIFont(name: "HelveticaNeue", size: 9.0) internal var _descriptionTextColor: UIColor! = UIColor.blackColor() /// font object for drawing the information text when there are no values in the chart internal var _infoFont: UIFont! = UIFont(name: "HelveticaNeue", size: 12.0) internal var _infoTextColor: UIColor! = UIColor(red: 247.0/255.0, green: 189.0/255.0, blue: 51.0/255.0, alpha: 1.0) // orange /// description text that appears in the bottom right corner of the chart public var descriptionText = "Description" /// flag that indicates if the chart has been fed with data yet internal var _dataNotSet = true /// if true, units are drawn next to the values in the chart internal var _drawUnitInChart = false /// the number of x-values the chart displays internal var _deltaX = CGFloat(1.0) internal var _chartXMin = Float(0.0) internal var _chartXMax = Float(0.0) /// if true, value highlightning is enabled public var highlightEnabled = true /// the legend object containing all data associated with the legend internal var _legend: ChartLegend!; /// delegate to receive chart events public weak var delegate: ChartViewDelegate? /// text that is displayed when the chart is empty public var noDataText = "No chart data available." /// text that is displayed when the chart is empty that describes why the chart is empty public var noDataTextDescription: String? internal var _legendRenderer: ChartLegendRenderer! /// object responsible for rendering the data public var renderer: ChartDataRendererBase? /// object that manages the bounds and drawing constraints of the chart internal var _viewPortHandler: ChartViewPortHandler! /// object responsible for animations internal var _animator: ChartAnimator! /// flag that indicates if offsets calculation has already been done or not private var _offsetsCalculated = false /// array of Highlight objects that reference the highlighted slices in the chart internal var _indicesToHightlight = [ChartHighlight]() /// if set to true, the marker is drawn when a value is clicked public var drawMarkers = true /// the view that represents the marker public var marker: ChartMarker? private var _interceptTouchEvents = false // MARK: - Initializers public override init(frame: CGRect) { super.init(frame: frame); initialize(); } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); initialize(); } internal func initialize() { _animator = ChartAnimator(); _animator.delegate = self; _viewPortHandler = ChartViewPortHandler(); _viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height); _legend = ChartLegend(); _legendRenderer = ChartLegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend); _defaultValueFormatter.maximumFractionDigits = 1; _defaultValueFormatter.minimumFractionDigits = 1; _defaultValueFormatter.usesGroupingSeparator = true; _valueFormatter = _defaultValueFormatter.copy() as! NSNumberFormatter; } // MARK: - ChartViewBase /// The data for the chart public var data: ChartData? { get { return _data; } set { if (newValue == nil || newValue?.yValCount == 0) { println("Charts: data argument is nil on setData()"); return; } _dataNotSet = false; _offsetsCalculated = false; _data = newValue; // calculate how many digits are needed calculateFormatter(min: _data.getYMin(), max: _data.getYMax()); notifyDataSetChanged(); } } /// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()). public func clear() { _data = nil; _dataNotSet = true; setNeedsDisplay(); } /// Removes all DataSets (and thereby Entries) from the chart. Does not remove the x-values. Also refreshes the chart by calling setNeedsDisplay(). public func clearValues() { if (_data !== nil) { _data.clearValues(); } setNeedsDisplay(); } /// Returns true if the chart is empty (meaning it's data object is either null or contains no entries). public func isEmpty() -> Bool { if (_data == nil) { return true; } else { if (_data.yValCount <= 0) { return true; } else { return false; } } } /// Lets the chart know its underlying data has changed and should perform all necessary recalculations. public func notifyDataSetChanged() { fatalError("notifyDataSetChanged() cannot be called on ChartViewBase"); } /// calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position internal func calculateOffsets() { fatalError("calculateOffsets() cannot be called on ChartViewBase"); } /// calcualtes the y-min and y-max value and the y-delta and x-delta value internal func calcMinMax() { fatalError("calcMinMax() cannot be called on ChartViewBase"); } /// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter internal func calculateFormatter(#min: Float, max: Float) { // check if a custom formatter is set or not var reference = Float(0.0); if (_data == nil || _data.xValCount < 2) { var absMin = fabs(min); var absMax = fabs(max); reference = absMin > absMax ? absMin : absMax; } else { reference = fabs(max - min); } var digits = ChartUtils.decimals(reference); _defaultValueFormatter.maximumFractionDigits = digits; _defaultValueFormatter.minimumFractionDigits = digits; } public override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext(); let frame = self.bounds; if (_dataNotSet || _data === nil || _data.yValCount == 0) { // check if there is data CGContextSaveGState(context); // if no data, inform the user ChartUtils.drawText(context: context, text: noDataText, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0), align: .Center, attributes: [NSFontAttributeName: _infoFont, NSForegroundColorAttributeName: _infoTextColor]); if (noDataTextDescription?.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) > 0) { var textOffset = -_infoFont.lineHeight / 2.0; ChartUtils.drawText(context: context, text: noDataTextDescription!, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0 + textOffset), align: .Center, attributes: [NSFontAttributeName: _infoFont, NSForegroundColorAttributeName: _infoTextColor]); } return; } if (!_offsetsCalculated) { calculateOffsets(); _offsetsCalculated = true; } } /// draws the description text in the bottom right corner of the chart internal func drawDescription(#context: CGContext) { if (descriptionText.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) == 0) { return; } let frame = self.bounds; var attrs = [NSObject: AnyObject](); var font = descriptionFont; if (font == nil) { font = UIFont.systemFontOfSize(UIFont.systemFontSize()); } attrs[NSFontAttributeName] = font; attrs[NSForegroundColorAttributeName] = UIColor.blackColor(); ChartUtils.drawText(context: context, text: descriptionText, point: CGPoint(x: frame.width - _viewPortHandler.offsetRight - 10.0, y: frame.height - _viewPortHandler.offsetBottom - 10.0 - font!.lineHeight), align: .Right, attributes: attrs); } /// disables intercept touchevents public func disableScroll() { _interceptTouchEvents = true; } /// enables intercept touchevents public func enableScroll() { _interceptTouchEvents = false; } // MARK: - Highlighting /// Returns the array of currently highlighted values. This might be null or empty if nothing is highlighted. public var highlighted: [ChartHighlight] { return _indicesToHightlight; } /// Returns true if there are values to highlight, /// false if there are no values to highlight. /// Checks if the highlight array is null, has a length of zero or if the first object is null. public func valuesToHighlight() -> Bool { return _indicesToHightlight.count > 0; } /// Highlights the values at the given indices in the given DataSets. Provide /// null or an empty array to undo all highlighting. /// This should be used to programmatically highlight values. /// This DOES NOT generate a callback to the delegate. public func highlightValues(highs: [ChartHighlight]?) { // set the indices to highlight _indicesToHightlight = highs ?? [ChartHighlight](); // redraw the chart setNeedsDisplay(); } /// Highlights the value at the given x-index in the given DataSet. /// Provide -1 as the x-index to undo all highlighting. public func highlightValue(#xIndex: Int, dataSetIndex: Int, callDelegate: Bool) { if (xIndex < 0 || dataSetIndex < 0 || xIndex >= _data.xValCount || dataSetIndex >= _data.dataSetCount) { highlightValue(highlight: nil, callDelegate: callDelegate); } else { highlightValue(highlight: ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex), callDelegate: callDelegate); } } /// Highlights the value selected by touch gesture. public func highlightValue(#highlight: ChartHighlight?, callDelegate: Bool) { if (highlight == nil) { _indicesToHightlight.removeAll(keepCapacity: false); } else { // set the indices to highlight _indicesToHightlight = [highlight!]; } // redraw the chart setNeedsDisplay(); if (callDelegate && delegate != nil) { if (highlight == nil) { delegate!.chartValueNothingSelected!(self); } else { var e = _data.getEntryForHighlight(highlight!); // notify the listener delegate!.chartValueSelected!(self, entry: e, dataSetIndex: highlight!.dataSetIndex, highlight: highlight!); } } } // MARK: - Markers /// draws all MarkerViews on the highlighted positions internal func drawMarkers(#context: CGContext) { // if there is no marker view or drawing marker is disabled if (marker === nil || !drawMarkers || !valuesToHighlight()) { return; } for (var i = 0, count = _indicesToHightlight.count; i < count; i++) { let highlight = _indicesToHightlight[i]; let xIndex = highlight.xIndex; let dataSetIndex = highlight.dataSetIndex; if (xIndex <= Int(_deltaX) && xIndex <= Int(_deltaX * _animator.phaseX)) { let e = _data.getEntryForHighlight(highlight); var pos = getMarkerPosition(entry: e, dataSetIndex: dataSetIndex); // check bounds if (!_viewPortHandler.isInBounds(x: pos.x, y: pos.y)) { continue; } // callbacks to update the content marker!.refreshContent(entry: e, dataSetIndex: dataSetIndex); let markerSize = marker!.size; if (pos.y - markerSize.height <= 0.0) { let y = markerSize.height - pos.y; marker!.draw(context: context, point: CGPoint(x: pos.x, y: pos.y + y)); } else { marker!.draw(context: context, point: pos); } } } } /// Returns the actual position in pixels of the MarkerView for the given Entry in the given DataSet. public func getMarkerPosition(#entry: ChartDataEntry, dataSetIndex: Int) -> CGPoint { fatalError("getMarkerPosition() cannot be called on ChartViewBase"); } // MARK: - Animation /// Returns the animator responsible for animating chart values. public var animator: ChartAnimator! { return _animator; } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: yAxisDuration duration for animating the y axis /// :param: easingX an easing function for the animation on the x axis /// :param: easingY an easing function for the animation on the y axis public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY); } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: yAxisDuration duration for animating the y axis /// :param: easingOptionX the easing function for the animation on the x axis /// :param: easingOptionY the easing function for the animation on the y axis public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY); } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: yAxisDuration duration for animating the y axis /// :param: easing an easing function for the animation public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing); } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: yAxisDuration duration for animating the y axis /// :param: easingOption the easing function for the animation public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption); } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: yAxisDuration duration for animating the y axis public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration); } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: easing an easing function for the animation public func animate(#xAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, easing: easing); } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: easingOption the easing function for the animation public func animate(#xAxisDuration: NSTimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption); } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis public func animate(#xAxisDuration: NSTimeInterval) { _animator.animate(xAxisDuration: xAxisDuration); } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: yAxisDuration duration for animating the y axis /// :param: easing an easing function for the animation public func animate(#yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(yAxisDuration: yAxisDuration, easing: easing); } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: yAxisDuration duration for animating the y axis /// :param: easingOption the easing function for the animation public func animate(#yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption) { _animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption); } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: yAxisDuration duration for animating the y axis public func animate(#yAxisDuration: NSTimeInterval) { _animator.animate(yAxisDuration: yAxisDuration); } // MARK: - Accessors /// returns the total value (sum) of all y-values across all DataSets public var yValueSum: Float { return _data.yValueSum; } /// returns the current y-max value across all DataSets public var chartYMax: Float { return _data.yMax; } /// returns the current y-min value across all DataSets public var chartYMin: Float { return _data.yMin; } public var chartXMax: Float { return _chartXMax; } public var chartXMin: Float { return _chartXMin; } /// returns the average value of all values the chart holds public func getAverage() -> Float { return yValueSum / Float(_data.yValCount); } /// returns the average value for a specific DataSet (with a specific label) in the chart public func getAverage(#dataSetLabel: String) -> Float { var ds = _data.getDataSetByLabel(dataSetLabel, ignorecase: true); if (ds == nil) { return 0.0; } return ds!.yValueSum / Float(ds!.entryCount); } /// returns the total number of values the chart holds (across all DataSets) public var getValueCount: Int { return _data.yValCount; } /// Returns the center of the chart taking offsets under consideration. (returns the center of the content rectangle) public var centerOffsets: CGPoint { return _viewPortHandler.contentCenter; } /// Returns the Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend. public var legend: ChartLegend { return _legend; } /// Returns the renderer object responsible for rendering / drawing the Legend. public var legendRenderer: ChartLegendRenderer! { return _legendRenderer; } /// Returns the rectangle that defines the borders of the chart-value surface (into which the actual values are drawn). public var contentRect: CGRect { return _viewPortHandler.contentRect; } /// Sets the formatter to be used for drawing the values inside the chart. /// If no formatter is set, the chart will automatically determine a reasonable /// formatting (concerning decimals) for all the values that are drawn inside /// the chart. Set this to nil to re-enable auto formatting. public var valueFormatter: NSNumberFormatter! { get { return _valueFormatter; } set { if (newValue === nil) { _valueFormatter = _defaultValueFormatter.copy() as! NSNumberFormatter; } else { _valueFormatter = newValue; } } } /// returns the x-value at the given index public func getXValue(index: Int) -> String! { if (_data == nil || _data.xValCount <= index) { return nil; } else { return _data.xVals[index]; } } /// Get all Entry objects at the given index across all DataSets. public func getEntriesAtIndex(xIndex: Int) -> [ChartDataEntry] { var vals = [ChartDataEntry](); for (var i = 0, count = _data.dataSetCount; i < count; i++) { var set = _data.getDataSetByIndex(i); var e = set!.entryForXIndex(xIndex); if (e !== nil) { vals.append(e); } } return vals; } /// returns the percentage the given value has of the total y-value sum public func percentOfTotal(val: Float) -> Float { return val / _data.yValueSum * 100.0; } /// Returns the ViewPortHandler of the chart that is responsible for the /// content area of the chart and its offsets and dimensions. public var viewPortHandler: ChartViewPortHandler! { return _viewPortHandler; } /// Returns the bitmap that represents the chart. public func getChartImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, UIScreen.mainScreen().scale); layer.renderInContext(UIGraphicsGetCurrentContext()); var image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } public enum ImageFormat { case JPEG; case PNG; } /// Saves the current chart state with the given name to the given path on /// the sdcard leaving the path empty "" will put the saved file directly on /// the SD card chart is saved as a PNG image, example: /// saveToPath("myfilename", "foldername1/foldername2"); /// /// :filePath: path to the image to save /// :format: the format to save /// :compressionQuality: compression quality for lossless formats (JPEG) /// /// :returns: true if the image was saved successfully public func saveToPath(path: String, format: ImageFormat, compressionQuality: Float) -> Bool { var image = getChartImage(); var imageData: NSData!; switch (format) { case .PNG: imageData = UIImagePNGRepresentation(image); break; case .JPEG: imageData = UIImageJPEGRepresentation(image, CGFloat(compressionQuality)); break; } return imageData.writeToFile(path, atomically: true); } /// Saves the current state of the chart to the camera roll public func saveToCameraRoll() { UIImageWriteToSavedPhotosAlbum(getChartImage(), nil, nil, nil); } internal typealias VoidClosureType = () -> () internal var _sizeChangeEventActions = [VoidClosureType]() public override var bounds: CGRect { get { return super.bounds; } set { super.bounds = newValue; if (_viewPortHandler !== nil) { _viewPortHandler.setChartDimens(width: newValue.size.width, height: newValue.size.height); // Finish any pending viewport changes while (!_sizeChangeEventActions.isEmpty) { _sizeChangeEventActions.removeAtIndex(0)(); } } notifyDataSetChanged(); } } public func clearPendingViewPortChanges() { _sizeChangeEventActions.removeAll(keepCapacity: false); } /// if true, value highlightning is enabled public var isHighlightEnabled: Bool { return highlightEnabled; } // MARK: - ChartAnimatorDelegate public func chartAnimatorUpdated(chartAnimator: ChartAnimator) { setNeedsDisplay(); } public func chartAnimatorStopped(chartAnimator: ChartAnimator) { } // MARK: - Touches public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { if (!_interceptTouchEvents) { super.touchesBegan(touches, withEvent: event); } } public override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { if (!_interceptTouchEvents) { super.touchesMoved(touches, withEvent: event); } } public override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { if (!_interceptTouchEvents) { super.touchesEnded(touches, withEvent: event); } } public override func touchesCancelled(touches: Set<NSObject>, withEvent event: UIEvent) { if (!_interceptTouchEvents) { super.touchesCancelled(touches, withEvent: event); } } }
b67d78e18d5e21aa209f82b8c5eeb797
34.461631
268
0.624197
false
false
false
false
Goro-Otsubo/GPaperTrans
refs/heads/master
GPaperTrans/GCollectionView Base/GCollectionView.swift
mit
1
// // GCollectionView.swift // GPaperTrans // // Created by 大坪五郎 on 2015/02/03. // Copyright (c) 2015年 demodev. All rights reserved. // import UIKit //subclass of UICollectionView //which has "guard"to prevent from unexpected contentOffset change class GCollectionView: UICollectionView{ var offsetAccept:Bool var oldOffset:CGPoint = CGPointZero override var contentOffset:CGPoint{ willSet{ oldOffset = contentOffset } didSet{ if !self.offsetAccept{ super.contentOffset = oldOffset } } } required override init(frame:CGRect,collectionViewLayout:UICollectionViewLayout){ offsetAccept = true super.init(frame:frame, collectionViewLayout:collectionViewLayout) self.backgroundColor = UIColor.clearColor() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // func setContentOffset(contentOffset: CGPoint) { // // if self.offsetAccept{ // super.contentOffset = contentOffset // } // } override func finishInteractiveTransition() { self.offsetAccept = false super.finishInteractiveTransition() // self.offsetAccept = true //will be restored in viewController finish block } }
6e0057a53fa1e53a11fa7a322f4d6a42
23.690909
85
0.647275
false
false
false
false
FindGF/_BiliBili
refs/heads/master
WTBilibili/Other-其他/Login-登陆/Controller/WTLoginViewController.swift
apache-2.0
1
// // WTLoginViewController.swift // WTBilibili // // Created by 无头骑士 GJ on 16/5/30. // Copyright © 2016年 无头骑士 GJ. All rights reserved. // 登陆控制器 import UIKit class WTLoginViewController: UIViewController { // MARK: - 拖线的属性 @IBOutlet weak var loginHeaderImageV: UIImageView! /// 手机或邮箱 @IBOutlet weak var phoneTextF: UITextField! /// 密码 @IBOutlet weak var passwordTextF: UITextField! /// 注册按钮 @IBOutlet weak var registerBtn: UIButton! /// 登陆按钮 @IBOutlet weak var loginBtn: UIButton! // MARK: - 懒加载 /// 手机或邮箱左侧的View lazy var phoneLeftView: UIImageView = { let phoneLeftView = UIImageView() phoneLeftView.image = UIImage(named: "ictab_me") phoneLeftView.frame = CGRect(x: 0, y: 0, width: 50, height: 45) phoneLeftView.contentMode = .Center return phoneLeftView }() /// 密码左侧的View lazy var passwordLeftView: UIImageView = { let passwordLeftView = UIImageView() passwordLeftView.image = UIImage(named: "pws_icon") passwordLeftView.frame = CGRect(x: 0, y: 0, width: 50, height: 45) passwordLeftView.contentMode = .Center return passwordLeftView }() // MARK: - 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 设置UI setupUI() } } // MARK: - 自定义函数 extension WTLoginViewController { // MARK: 设置UI private func setupUI() { // 0、设置导航栏 setupNav() // 1、手机或邮箱 setupCommonTextField(phoneTextF, leftView: phoneLeftView) // 2、密码 setupCommonTextField(passwordTextF, leftView: passwordLeftView) // 3、注册按钮 self.registerBtn.layer.cornerRadius = 3 self.registerBtn.layer.borderColor = WTColor(r: 231, g: 231, b: 231).CGColor self.registerBtn.layer.borderWidth = 1 // 4、登陆按钮 self.loginBtn.layer.cornerRadius = 3 } // MARK: 设置导航栏 private func setupNav() { title = "登录" // 关闭按钮 navigationItem.leftBarButtonItem = UIBarButtonItem.createCloseItem(self, action: #selector(closeBtnClick)) // 忘记密码 let forgetPasswordBtn = UIButton(type: .Custom) forgetPasswordBtn.titleLabel?.font = UIFont.setQIHeiFontWithSize(14) forgetPasswordBtn.setTitle("忘记密码", forState: .Normal) forgetPasswordBtn.addTarget(self, action: #selector(forgetPasswordBtnClick), forControlEvents: .TouchUpInside) forgetPasswordBtn.sizeToFit() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: forgetPasswordBtn) } // MARK: 设置textField公共属性 private func setupCommonTextField(textField: UITextField, leftView: UIImageView) { textField.tintColor = WTMainColor textField.leftView = leftView textField.leftViewMode = .Always } } // MARK: - 事件 extension WTLoginViewController { // MARK: 关闭按钮 func closeBtnClick() { dismissViewControllerAnimated(true, completion: nil) } // MARK: 忘记密码 func forgetPasswordBtnClick() { } // MARK: 注册按钮 @IBAction func registerBtnClick() { } // MARK: 登陆按钮 @IBAction func loginBtnClick() { } } // MARK: - UITextFieldDelegate extension WTLoginViewController: UITextFieldDelegate { func textFieldDidBeginEditing(textField: UITextField) { if textField.tag == 1 { self.phoneLeftView.image = UIImage(named: "ictab_me_selected") } else if textField.tag == 2 { self.loginHeaderImageV.image = UIImage(named: "login_header_cover_eyes") self.passwordLeftView.image = UIImage(named: "pws_icon_hover") } } func textFieldDidEndEditing(textField: UITextField) { if textField.tag == 1 { self.phoneLeftView.image = UIImage(named: "ictab_me") } else if textField.tag == 2 { self.loginHeaderImageV.image = UIImage(named: "login_header") self.passwordLeftView.image = UIImage(named: "pws_icon") } } }
19e9330e5776ae5a8d1f13a3299b2adb
25.175
118
0.614136
false
false
false
false
smashingpks/iOS-SDK
refs/heads/master
Templates/swift/HeroIcon/HeroIcon/Estimote/BeaconID.swift
mit
1
// // BeaconID.swift // HeroIcon // struct BeaconID: Equatable, CustomStringConvertible, Hashable { let proximityUUID: NSUUID let major: CLBeaconMajorValue let minor: CLBeaconMinorValue init(proximityUUID: NSUUID, major: CLBeaconMajorValue, minor: CLBeaconMinorValue) { self.proximityUUID = proximityUUID self.major = major self.minor = minor } init(UUIDString: String, major: CLBeaconMajorValue, minor: CLBeaconMinorValue) { self.init(proximityUUID: NSUUID(UUIDString: UUIDString)!, major: major, minor: minor) } var asString: String { get { return "\(proximityUUID.UUIDString):\(major):\(minor)" } } var asBeaconRegion: CLBeaconRegion { get { return CLBeaconRegion( proximityUUID: self.proximityUUID, major: self.major, minor: self.minor, identifier: self.asString) } } var description: String { get { return self.asString } } var hashValue: Int { get { return self.asString.hashValue } } } func ==(lhs: BeaconID, rhs: BeaconID) -> Bool { return lhs.proximityUUID == rhs.proximityUUID && lhs.major == rhs.major && lhs.minor == rhs.minor } extension CLBeacon { var beaconID: BeaconID { get { return BeaconID( proximityUUID: proximityUUID, major: major.unsignedShortValue, minor: minor.unsignedShortValue) } } }
791242858406b214424f07984fb58ccf
24.385965
93
0.637871
false
false
false
false
realm/SwiftLint
refs/heads/main
Source/SwiftLintFramework/Rules/Style/CommaRule.swift
mit
1
import Foundation import SourceKittenFramework import SwiftSyntax struct CommaRule: CorrectableRule, ConfigurationProviderRule, SourceKitFreeRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "comma", name: "Comma Spacing", description: "There should be no space before and one after any comma.", kind: .style, nonTriggeringExamples: [ Example("func abc(a: String, b: String) { }"), Example("abc(a: \"string\", b: \"string\""), Example("enum a { case a, b, c }"), Example("func abc(\n a: String, // comment\n bcd: String // comment\n) {\n}\n"), Example("func abc(\n a: String,\n bcd: String\n) {\n}\n"), Example("#imageLiteral(resourceName: \"foo,bar,baz\")"), Example(""" kvcStringBuffer.advanced(by: rootKVCLength) .storeBytes(of: 0x2E /* '.' */, as: CChar.self) """), Example(""" public indirect enum ExpectationMessage { /// appends after an existing message ("<expectation> (use beNil() to match nils)") case appends(ExpectationMessage, /* Appended Message */ String) } """, excludeFromDocumentation: true) ], triggeringExamples: [ Example("func abc(a: String↓ ,b: String) { }"), Example("func abc(a: String↓ ,b: String↓ ,c: String↓ ,d: String) { }"), Example("abc(a: \"string\"↓,b: \"string\""), Example("enum a { case a↓ ,b }"), Example("let result = plus(\n first: 3↓ , // #683\n second: 4\n)\n"), Example(""" Foo( parameter: a.b.c, tag: a.d, value: a.identifier.flatMap { Int64($0) }↓ , reason: Self.abcd() ) """), Example(""" return Foo(bar: .baz, title: fuzz, message: My.Custom.message↓ , another: parameter, doIt: true, alignment: .center) """) ], corrections: [ Example("func abc(a: String↓,b: String) {}\n"): Example("func abc(a: String, b: String) {}\n"), Example("abc(a: \"string\"↓,b: \"string\"\n"): Example("abc(a: \"string\", b: \"string\"\n"), Example("abc(a: \"string\"↓ , b: \"string\"\n"): Example("abc(a: \"string\", b: \"string\"\n"), Example("enum a { case a↓ ,b }\n"): Example("enum a { case a, b }\n"), Example("let a = [1↓,1]\nlet b = 1\nf(1, b)\n"): Example("let a = [1, 1]\nlet b = 1\nf(1, b)\n"), Example("let a = [1↓,1↓,1↓,1]\n"): Example("let a = [1, 1, 1, 1]\n"), Example(""" Foo( parameter: a.b.c, tag: a.d, value: a.identifier.flatMap { Int64($0) }↓ , reason: Self.abcd() ) """): Example(""" Foo( parameter: a.b.c, tag: a.d, value: a.identifier.flatMap { Int64($0) }, reason: Self.abcd() ) """), Example(""" return Foo(bar: .baz, title: fuzz, message: My.Custom.message↓ , another: parameter, doIt: true, alignment: .center) """): Example(""" return Foo(bar: .baz, title: fuzz, message: My.Custom.message, another: parameter, doIt: true, alignment: .center) """) ] ) func validate(file: SwiftLintFile) -> [StyleViolation] { return violationRanges(in: file).map { StyleViolation(ruleDescription: Self.description, severity: configuration.severity, location: Location(file: file, byteOffset: $0.0.location)) } } private func violationRanges(in file: SwiftLintFile) -> [(ByteRange, shouldAddSpace: Bool)] { let syntaxTree = file.syntaxTree return syntaxTree .windowsOfThreeTokens() .compactMap { previous, current, next -> (ByteRange, shouldAddSpace: Bool)? in if current.tokenKind != .comma { return nil } else if !previous.trailingTrivia.isEmpty && !previous.trailingTrivia.containsBlockComments() { let start = ByteCount(previous.endPositionBeforeTrailingTrivia) let end = ByteCount(current.endPosition) let nextIsNewline = next.leadingTrivia.containsNewlines() return (ByteRange(location: start, length: end - start), shouldAddSpace: !nextIsNewline) } else if !current.trailingTrivia.starts(with: [.spaces(1)]), !next.leadingTrivia.containsNewlines() { return (ByteRange(location: ByteCount(current.position), length: 1), shouldAddSpace: true) } else { return nil } } } func correct(file: SwiftLintFile) -> [Correction] { let initialNSRanges = Dictionary( uniqueKeysWithValues: violationRanges(in: file) .compactMap { byteRange, shouldAddSpace in file.stringView .byteRangeToNSRange(byteRange) .flatMap { ($0, shouldAddSpace) } } ) let violatingRanges = file.ruleEnabled(violatingRanges: Array(initialNSRanges.keys), for: self) guard violatingRanges.isNotEmpty else { return [] } let description = Self.description var corrections = [Correction]() var contents = file.contents for range in violatingRanges.sorted(by: { $0.location > $1.location }) { let contentsNSString = contents.bridge() let shouldAddSpace = initialNSRanges[range] ?? true contents = contentsNSString.replacingCharacters(in: range, with: ",\(shouldAddSpace ? " " : "")") let location = Location(file: file, characterOffset: range.location) corrections.append(Correction(ruleDescription: description, location: location)) } file.write(contents) return corrections } } private extension Trivia { func containsBlockComments() -> Bool { contains { piece in if case .blockComment = piece { return true } else { return false } } } }
edbb67b1dff5e9f54940b59688fb59f7
41.810127
118
0.509905
false
false
false
false
bitboylabs/selluv-ios
refs/heads/master
selluv-ios/selluv-ios/Classes/Controller/UI/Product/SLVProductPhotoViewer.swift
mit
1
// // SLVProductPhotoViewer.swift // selluv-ios // // Created by 조백근 on 2017. 2. 9.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // /* 판매 사진편집 */ import Foundation import UIKit class SLVProductPhotoViewer: SLVBaseStatusHiddenController { @IBOutlet weak var backButton: UIButton! @IBOutlet weak var horizontalView: PagedHorizontalView! @IBOutlet weak var productButton: UIButton! var photos: [String]? var items: [SLVDetailProduct]? var type: ProductPhotoType = .none var viewerBlock: ((_ path: IndexPath, _ image: UIImage?,_ type: ProductPhotoType,_ item: SLVDetailProduct?) -> ())? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabController.animationTabBarHidden(true) tabController.hideFab() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = true self.setupCollectionLayout() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setupCollectionLayout() { // horizontalView.addObserver(self, forKeyPath: "currentIndex", options: NSKeyValueObservingOptions(rawValue: 0), context: nil) self.horizontalView.collectionView.register(UINib(nibName: "SLVProductPhotoViewerCell", bundle: nil), forCellWithReuseIdentifier: "SLVProductPhotoViewerCell") self.horizontalView.collectionView.dataSource = self } deinit { // horizontalView.removeObserver(self, forKeyPath: "currentIndex") } func setupData(type: ProductPhotoType, photos: [String], items: [SLVDetailProduct] ) { self.type = type self.items = items self.photos = photos } func moveIndex(index: Int) { self.horizontalView.moveToPage(index, animated: false) } func setupViewer(block: @escaping ((_ path: IndexPath, _ image: UIImage? ,_ type: ProductPhotoType,_ item: SLVDetailProduct?) -> ()) ) { self.viewerBlock = block } func move(path: IndexPath, item: SLVDetailProduct?) { if self.viewerBlock != nil { let cell = self.horizontalView.collectionView.cellForItem(at: path) as? SLVProductPhotoViewerCell let image = cell?.photo.image self.viewerBlock!(path, image, type, item) } } func imageDomain() -> String { var domain = dnProduct switch self.type { case .style : domain = dnStyle break case .damage : domain = dnDamage break case .accessory : domain = dnAccessory break default: break } return domain } //MARK: Event func dismiss() { self.dismiss(animated: true) { } } @IBAction func touchBack(_ sender: Any) { self.dismiss() } @IBAction func touchProductDetail(_ sender: Any) { let index = horizontalView.currentIndex var item: SLVDetailProduct? if self.items != nil && self.items!.count >= index + 1 { item = self.items![index] } self.dismiss(animated: true) { let path = IndexPath(row: index, section: 0) self.move(path: path, item: item) } } } extension SLVProductPhotoViewer : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.photos?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SLVProductPhotoViewerCell", for: indexPath) as! SLVProductPhotoViewerCell if let list = self.photos { let name = list[indexPath.row] if name != "" { let urlString = self.imageDomain() let from = URL(string: "\(urlString)\(name)") let dnModel = SLVDnImageModel.shared dnModel.setupImageView(view: cell.photo!, from: from!) } } return cell } }
3bd7f4e2352078e77734101de36551ab
30
166
0.617901
false
false
false
false
slepcat/mint
refs/heads/release
MINT/MintIOs.swift
gpl-3.0
1
// // MintIOs.swift // mint // // Created by NemuNeko on 2015/10/11. // Copyright © 2015年 Taizo A. All rights reserved. // import Foundation /* class Display: Primitive { let port : Mint3DPort init(port: Mint3DPort) { self.port = port } override func apply(var args: [SExpr]) -> SExpr { var acc: [Double] = [] var acc_normal: [Double] = [] var acc_color: [Float] = [] var portid = 0 if args.count > 0 { if let p = args.removeAtIndex(0) as? MInt { portid = p.value } } for arg in args { let polys = delayed_list_of_values(arg) for poly in polys { if let p = poly as? MPolygon { let vertices = p.value.vertices if vertices.count == 3 { for vertex in vertices { acc += [vertex.pos.x, vertex.pos.y, vertex.pos.z] acc_normal += [vertex.normal.x, vertex.normal.y, vertex.normal.z] acc_color += vertex.color } } else if vertices.count > 3 { // if polygon is not triangle, split it to triangle polygons //if polygon.checkIfConvex() { let triangles = p.value.triangulationConvex() for tri in triangles { for vertex in tri.vertices { acc += [vertex.pos.x, vertex.pos.y, vertex.pos.z] acc_normal += [vertex.normal.x, vertex.normal.y, vertex.normal.z] acc_color += vertex.color } } //} else { //} } } else { print("display take only polygons", terminator: "\n") return MNull() } } } port.write(IOMesh(mesh: acc, normal: acc_normal, color: acc_color), port: portid) return MNull() } override var category : String { get {return "3D Primitives"} } override func params_str() -> [String] { return ["portid", "poly."] } private func delayed_list_of_values(_opds :SExpr) -> [SExpr] { if let atom = _opds as? Atom { return [atom] } else { return tail_delayed_list_of_values(_opds, acc: []) } } private func tail_delayed_list_of_values(_opds :SExpr, var acc: [SExpr]) -> [SExpr] { if let pair = _opds as? Pair { acc.append(pair.car) return tail_delayed_list_of_values(pair.cdr, acc: acc) } else { return acc } } } */
3c3af48aa980ed4741ccc2890baf3ad8
28.771429
97
0.41248
false
false
false
false
joaoSakai/torpedo-saude
refs/heads/master
GrupoFlecha/GrupoFlecha/ConfigViewController.swift
gpl-2.0
1
// // ConfigViewController.swift // GrupoFlecha // // Created by Davi Rodrigues on 05/03/16. // Copyright © 2016 Davi Rodrigues. All rights reserved. // import UIKit class ConfigViewController: UIViewController, UITextFieldDelegate, UIGestureRecognizerDelegate { let defaults = NSUserDefaults.standardUserDefaults() @IBOutlet weak var ageTextField: UITextField! @IBOutlet weak var gestanteLabel: UILabel! @IBOutlet weak var gestanteSwitch: UISwitch! @IBOutlet weak var greenView: UIView! //var keyboard: CGSize = CGSize(width: 0, height: 0) @IBOutlet var tapGestureRecognizer: UITapGestureRecognizer! override func viewDidLoad() { super.viewDidLoad() greenView.layer.cornerRadius = 50 } ///Popula informações do usuário na tela override func viewWillAppear(animated: Bool) { if(UserInfo.userAge >= 0) { self.ageTextField.text = String(UserInfo.userAge) } self.gestanteSwitch.on = UserInfo.gestante } override func viewWillDisappear(animated: Bool) { //Faz a persistencia de dados do usuário em NSUserDefaults ao deixar a tela UserInfo.gestante = self.gestanteSwitch.on self.defaults.setBool(self.gestanteSwitch.on, forKey: "gestante") if(self.ageTextField.text != "") { UserInfo.userAge = Int(self.ageTextField.text!)! self.defaults.setInteger(Int(self.ageTextField.text!)!, forKey: "age") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Keyboard /* func textFieldShouldReturn(textField: UITextField) -> Bool { self.ageTextField.resignFirstResponder() return true } func registerForKeyboardNotifications() { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "keyboardWillBeShown:", name: UIKeyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil) } // Called when the UIKeyboardDidShowNotification is sent. func keyboardWillBeShown(sender: NSNotification) { let info: NSDictionary = sender.userInfo! let value: NSValue = info.valueForKey(UIKeyboardFrameBeginUserInfoKey) as! NSValue let keyboardSize: CGSize = value.CGRectValue().size self.keyboard = keyboardSize if(ageTextField.isFirstResponder()) { self.view.center.y -= keyboardSize.height } } */ //Recolhe teclado ao fim da edição do campo de texto @IBAction func tapGestureRecognizerHandler(sender: AnyObject) { self.ageTextField.resignFirstResponder() } }
060c617248fd67b42925836d0db3cd8a
29.35
96
0.6514
false
false
false
false
duliodenis/cs193p-Spring-2016
refs/heads/master
democode/Cassini-L8/Cassini/CassiniViewController.swift
mit
1
// // CassiniViewController.swift // Cassini // // Created by CS193p Instructor. // Copyright © 2016 Stanford University. All rights reserved. // import UIKit class CassiniViewController: UIViewController, UISplitViewControllerDelegate { // this is just our normal "put constants in a struct" thing // but we call it Storyboard, because all the constants in it // are strings in our Storyboard private struct Storyboard { static let ShowImageSegue = "Show Image" } // prepare for segue is called // even if we invoke the segue from code using performSegue (see below) override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == Storyboard.ShowImageSegue { if let ivc = segue.destinationViewController.contentViewController as? ImageViewController { let imageName = (sender as? UIButton)?.currentTitle ivc.imageURL = DemoURL.NASAImageNamed(imageName) ivc.title = imageName } } } // we changed the buttons to this target/action method // so that we could either // a) just set our imageURL in the detail if we're in a split view, or // b) cause the segue to happen from code with performSegue // to make the latter work, we had to create a segue in our storyboard // that was ctrl-dragged from the view controller icon (orange one at the top) @IBAction func showImage(sender: UIButton) { if let ivc = splitViewController?.viewControllers.last?.contentViewController as? ImageViewController { let imageName = sender.currentTitle ivc.imageURL = DemoURL.NASAImageNamed(imageName) ivc.title = imageName } else { performSegueWithIdentifier(Storyboard.ShowImageSegue, sender: sender) } } // if we are in a split view, we set ourselves as its delegate // this is so we can prevent an empty detail from collapsing on top of our master // see split view delegate method below override func viewDidLoad() { super.viewDidLoad() splitViewController?.delegate = self } // this method lets the split view's delegate // collapse the detail on top of the master when it's the detail's time to appear // this method returns whether we (the delegate) handled doing this // we don't want an empty detail to collapse on top of our master // so if the detail is an empty ImageViewController, we return true // (which tells the split view controller that we handled the collapse) // of course, we didn't actually handle it, we did nothing // but that's exactly what we want (i.e. no collapse if the detail ivc is empty) func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool { if primaryViewController.contentViewController == self { if let ivc = secondaryViewController.contentViewController as? ImageViewController where ivc.imageURL == nil { return true } } return false } } // a little helper extension // which either returns the view controller you send it to // or, if you send it to a UINavigationController, // it returns its visibleViewController // (if any, otherwise the UINavigationController itself) extension UIViewController { var contentViewController: UIViewController { if let navcon = self as? UINavigationController { return navcon.visibleViewController ?? self } else { return self } } }
eb52e44fe4a1edbce2cf4f9b7501efc4
39
222
0.688032
false
false
false
false
seongkyu-sim/BaseVCKit
refs/heads/master
BaseVCKit/Classes/extensions/UITableViewExtensions.swift
mit
1
// // UITableViewExtensions.swift // BaseVCKit // // Created by frank on 2015. 11. 10.. // Copyright © 2016년 colavo. All rights reserved. // import UIKit public extension UITableView { func isLastRow(at indexPath: IndexPath) -> Bool { let lastSectionIndex:Int = self.numberOfSections-1 let lastRowIndex:Int = self.numberOfRows(inSection: lastSectionIndex)-1 return (indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex) } func isSelectedCell(at indexPath: IndexPath) -> Bool { guard let selectedRows = self.indexPathsForSelectedRows else { return false } return selectedRows.contains(indexPath) } }
4a2660508d11f8594577f24130006212
26
87
0.678063
false
false
false
false
mikewxk/DYLiveDemo_swift
refs/heads/master
DYLiveDemo/DYLiveDemo/Classes/Main/View/PageTitleView.swift
unlicense
1
// // PageTitleView.swift // DYLiveDemo // // Created by xiaokui wu on 12/16/16. // Copyright © 2016 wxk. All rights reserved. // import UIKit //MARK: - 协议 protocol PageTitleViewDelegate : class {// : class 表明代理只能被类遵守 func pageTitleView(titleView : PageTitleView ,selectedIndex index: Int) } //MARK: - 常量 private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) // 元组定义rgb颜色 private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) // 元组定义rgb颜色 private let kScrollLineHeight: CGFloat = 2 class PageTitleView: UIView { //MARK: - 属性 private var titles: [String] private var currentIndex = 0 weak var delegate : PageTitleViewDelegate?// 代理指明weak //MARK: - 懒加载 private lazy var titleLabels: [UILabel] = [UILabel]() private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.scrollsToTop = false scrollView.pagingEnabled = false scrollView.bounces = false return scrollView }() private lazy var scrollLine: UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orangeColor() return scrollLine }() //MARK: - 自定义构造函数 init(frame: CGRect, titles: [String]) { self.titles = titles super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView{ private func setupUI(){ // 滚动视图 addSubview(scrollView) scrollView.frame = bounds // 标题label setupTitleLabels() // 底线 setupBottomAndScrollLine() } private func setupTitleLabels() { let labelW: CGFloat = frame.width / CGFloat(titles.count) let labelH: CGFloat = frame.height - kScrollLineHeight let labelY: CGFloat = 0 for (index, title) in titles.enumerate(){ let label = UILabel() label.text = title label.tag = index label.font = UIFont.systemFontOfSize(16.0) label.textColor = UIColor.darkGrayColor() label.textAlignment = .Center //frame let labelX: CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) // 添加到scrollView中,让label能随着scrollView滚动 scrollView.addSubview(label) // 添加到titleLabels数组里 titleLabels.append(label) // 给label添加手势 label.userInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelTap(_:))) label.addGestureRecognizer(tapGes) } } private func setupBottomAndScrollLine(){ // 底部分隔线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGrayColor() let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: (frame.height - lineH), width: frame.width, height: lineH) addSubview(bottomLine) // 拿到第一个label guard let firstLabel = titleLabels.first else{return} firstLabel.textColor = UIColor.orangeColor() // scrollLine滚动指示线 scrollView.addSubview(scrollLine) // 参照第一个label,设置frame scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineHeight, width: firstLabel.frame.size.width, height: kScrollLineHeight) } } //MARK: - 内部事件回调 extension PageTitleView{ @objc private func titleLabelTap(tapGes: UITapGestureRecognizer) { // 当前选中的label guard let currentLabel = tapGes.view as? UILabel else{return} // 上一个label let previousLabel = titleLabels[currentIndex] // 改变颜色 previousLabel.textColor = UIColor.darkGrayColor() currentLabel.textColor = UIColor.orangeColor() // 最新选中label的tag值,就是索引值 currentIndex = currentLabel.tag // 移动滚动条 UIView.animateWithDuration(0.15) { self.scrollLine.frame.origin.x = currentLabel.frame.origin.x } // 通知代理 delegate?.pageTitleView(self, selectedIndex: currentIndex) } } //MARK: - 外部方法 extension PageTitleView{ func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 记录最新选中的索引 currentIndex = targetIndex let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 滑块滑动 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 颜色渐变 // 变化范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) // 选中颜色变为普通颜色 sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) // 普通颜色变为选中颜色 targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) } }
8ab2e268199121fd1b39de170d7a5804
24.371681
174
0.603767
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Kickstarter-iOS/Features/ProjectPage/Views/ProjectPageNavigationBarView.swift
apache-2.0
1
import KsApi import Library import PassKit import Prelude import UIKit protocol ProjectPageNavigationBarViewDelegate: AnyObject { func configureSharing(with context: ShareContext) func configureWatchProject(with context: WatchProjectValue) func viewDidLoad() } private enum Layout { enum Button { static let height: CGFloat = 15 } } final class ProjectPageNavigationBarView: UIView { // MARK: - Properties private let shareViewModel: ShareViewModelType = ShareViewModel() private let watchProjectViewModel: WatchProjectViewModelType = WatchProjectViewModel() private lazy var navigationShareButton: UIButton = { UIButton(type: .custom) }() private lazy var navigationCloseButton: UIButton = { let buttonView = UIButton(type: .custom) |> UIButton.lens.title(for: .normal) .~ nil |> UIButton.lens.image(for: .normal) .~ image(named: "icon--cross") |> UIButton.lens.tintColor .~ .ksr_support_700 |> UIButton.lens.accessibilityLabel %~ { _ in Strings.accessibility_projects_buttons_close() } |> UIButton.lens.accessibilityHint %~ { _ in Strings.Closes_project() } return buttonView }() private lazy var navigationSaveButton: UIButton = { UIButton(type: .custom) }() private lazy var rootStackView: UIStackView = { UIStackView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() private lazy var spacer: UIView = { UIView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() weak var delegate: ProjectPageViewControllerDelegate? // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) self.configureSubviews() self.setupConstraints() self.setupNotifications() self.bindViewModel() } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Styles override func bindStyles() { super.bindStyles() _ = self |> \.backgroundColor .~ .ksr_white _ = self.rootStackView |> \.isLayoutMarginsRelativeArrangement .~ true |> \.insetsLayoutMarginsFromSafeArea .~ true |> \.spacing .~ Styles.grid(0) _ = self.navigationShareButton |> shareButtonStyle |> UIButton.lens.accessibilityLabel %~ { _ in Strings.dashboard_accessibility_label_share_project() } _ = self.navigationSaveButton |> saveButtonStyle |> UIButton.lens.accessibilityLabel %~ { _ in Strings.Toggle_saving_this_project() } } // MARK: - View Model override func bindViewModel() { super.bindViewModel() self.bindSharingViewModel() self.bindWatchViewModel() } private func bindSharingViewModel() { self.shareViewModel.outputs.showShareSheet .observeForControllerAction() .observeValues { [weak self] controller, _ in self?.delegate?.showShareSheet(controller, sourceView: self?.navigationShareButton) } } private func bindWatchViewModel() { self.navigationSaveButton.rac.accessibilityValue = self.watchProjectViewModel.outputs .saveButtonAccessibilityValue self.navigationSaveButton.rac.selected = self.watchProjectViewModel.outputs.saveButtonSelected self.watchProjectViewModel.outputs.generateImpactFeedback .observeForUI() .observeValues { generateImpactFeedback() } self.watchProjectViewModel.outputs.generateNotificationSuccessFeedback .observeForUI() .observeValues { generateNotificationSuccessFeedback() } self.watchProjectViewModel.outputs.generateSelectionFeedback .observeForUI() .observeValues { generateSelectionFeedback() } self.watchProjectViewModel.outputs.showProjectSavedAlert .observeForControllerAction() .observeValues { [weak self] in self?.delegate?.displayProjectStarredPrompt() } self.watchProjectViewModel.outputs.goToLoginTout .observeForControllerAction() .observeValues { [weak self] in self?.delegate?.goToLogin() } self.watchProjectViewModel.outputs.postNotificationWithProject .observeForUI() .observeValues { project in NotificationCenter.default.post( name: Notification.Name.ksr_projectSaved, object: nil, userInfo: ["project": project] ) } } // MARK: Helpers private func setupConstraints() { _ = (self.rootStackView, self) |> ksr_addSubviewToParent() |> ksr_constrainViewToEdgesInParent() _ = ( [ self.navigationCloseButton, self.spacer, self.navigationShareButton, self.navigationSaveButton ], self.rootStackView ) |> ksr_addArrangedSubviewsToStackView() NSLayoutConstraint .activate([ self.navigationShareButton.widthAnchor .constraint(equalTo: self.navigationShareButton.heightAnchor), self.navigationSaveButton.widthAnchor .constraint(equalTo: self.navigationSaveButton.heightAnchor), self.navigationCloseButton.widthAnchor .constraint(equalTo: self.navigationCloseButton.heightAnchor) ]) } private func setupNotifications() { NotificationCenter.default .addObserver( self, selector: #selector(ProjectPageNavigationBarView.userSessionStarted), name: .ksr_sessionStarted, object: nil ) NotificationCenter.default .addObserver( self, selector: #selector(ProjectPageNavigationBarView.userSessionEnded), name: .ksr_sessionEnded, object: nil ) } private func configureSubviews() { self.addTargetAction( buttonItem: self.navigationCloseButton, targetAction: #selector(ProjectPageNavigationBarView.closeButtonTapped), event: .touchUpInside ) self.addTargetAction( buttonItem: self.navigationShareButton, targetAction: #selector(ProjectPageNavigationBarView.shareButtonTapped), event: .touchUpInside ) self.addTargetAction( buttonItem: self.navigationSaveButton, targetAction: #selector(ProjectPageNavigationBarView.saveButtonTapped(_:)), event: .touchUpInside ) self.addTargetAction( buttonItem: self.navigationSaveButton, targetAction: #selector(ProjectPageNavigationBarView.saveButtonPressed), event: .touchDown ) } private func addTargetAction( buttonItem: UIButton, targetAction: Selector, event: UIControl.Event ) { buttonItem.addTarget( self, action: targetAction, for: event ) } // MARK: Selectors @objc private func shareButtonTapped() { self.shareViewModel.inputs.shareButtonTapped() } @objc private func userSessionStarted() { self.watchProjectViewModel.inputs.userSessionStarted() } @objc private func userSessionEnded() { self.watchProjectViewModel.inputs.userSessionEnded() } @objc private func closeButtonTapped() { self.delegate?.dismissPage(animated: true, completion: nil) } @objc private func saveButtonTapped(_ button: UIButton) { self.watchProjectViewModel.inputs.saveButtonTapped(selected: button.isSelected) } @objc private func saveButtonPressed() { self.watchProjectViewModel.inputs.saveButtonTouched() } } extension ProjectPageNavigationBarView: ProjectPageNavigationBarViewDelegate { func viewDidLoad() { self.watchProjectViewModel.inputs.viewDidLoad() } func configureSharing(with context: ShareContext) { self.shareViewModel.inputs.configureWith(shareContext: context, shareContextView: nil) } func configureWatchProject(with context: WatchProjectValue) { self.watchProjectViewModel.inputs .configure(with: context) } }
3a7e6efa5c5e98dd5f23313d9f7b0317
27.88764
107
0.706859
false
false
false
false
SwiftStudies/OysterKit
refs/heads/master
Tests/OysterKitTests/HomegenousASTTests.swift
bsd-2-clause
1
// // HomegenousASTTests.swift // PerformanceTests // // Created by Nigel Hughes on 30/01/2018. // import XCTest import OysterKit // // XML Parser // enum XMLGenerated : Int, TokenType { typealias T = XMLGenerated // Cache for compiled regular expressions private static var regularExpressionCache = [String : NSRegularExpression]() /// Returns a pre-compiled pattern from the cache, or if not in the cache builds /// the pattern, caches and returns the regular expression /// /// - Parameter pattern: The pattern the should be built /// - Returns: A compiled version of the pattern /// private static func regularExpression(_ pattern:String)->NSRegularExpression{ if let cached = regularExpressionCache[pattern] { return cached } do { let new = try NSRegularExpression(pattern: pattern, options: []) regularExpressionCache[pattern] = new return new } catch { fatalError("Failed to compile pattern /\(pattern)/\n\(error)") } } /// The tokens defined by the grammar case `ws`, `identifier`, `singleQuote`, `doubleQuote`, `value`, `attribute`, `attributes`, `data`, `openTag`, `closeTag`, `inlineTag`, `nestingTag`, `tag`, `contents`, `xml` /// The rule for the token var rule : Rule { switch self { /// ws case .ws: return -[ CharacterSet.whitespacesAndNewlines.require(.one) ].sequence /// identifier case .identifier: return [ [ CharacterSet.letters.require(.one), [ CharacterSet.letters.require(.one), [ "-".require(.one), CharacterSet.letters.require(.one)].sequence ].choice ].sequence ].sequence.parse(as: self) /// singleQuote case .singleQuote: return [ "\'".require(.one) ].sequence.parse(as: self) /// doubleQuote case .doubleQuote: return [ "\\\"".require(.one) ].sequence.parse(as: self) /// value case .value: return [ [ [ -T.singleQuote.rule.require(.one), !T.singleQuote.rule.require(.zeroOrMore), -T.singleQuote.rule.require(.one)].sequence , [ -T.doubleQuote.rule.require(.one), !T.doubleQuote.rule.require(.zeroOrMore), -T.doubleQuote.rule.require(.one)].sequence ].choice ].sequence.parse(as: self) /// attribute case .attribute: return [ [ T.ws.rule.require(.oneOrMore), T.identifier.rule.require(.one), [ T.ws.rule.require(.zeroOrMore), -"=".require(.one), T.ws.rule.require(.zeroOrMore), T.value.rule.require(.one)].sequence ].sequence ].sequence.parse(as: self) /// attributes case .attributes: return [ T.attribute.rule.require(.oneOrMore) ].sequence.parse(as: self) /// data case .data: return [ !"<".require(.oneOrMore) ].sequence.parse(as: self) /// openTag case .openTag: return [ [ T.ws.rule.require(.zeroOrMore), -"<".require(.one), T.identifier.rule.require(.one), [ T.attributes.rule.require(.one), T.ws.rule.require(.zeroOrMore)].choice , -">".require(.one)].sequence ].sequence.parse(as: self) /// closeTag case .closeTag: return -[ [ T.ws.rule.require(.zeroOrMore), -"</".require(.one), T.identifier.rule.require(.one), T.ws.rule.require(.zeroOrMore), -">".require(.one)].sequence ].sequence /// inlineTag case .inlineTag: return [ [ T.ws.rule.require(.zeroOrMore), -"<".require(.one), T.identifier.rule.require(.one), [ T.attribute.rule.require(.oneOrMore), T.ws.rule.require(.zeroOrMore)].choice , -"/>".require(.one)].sequence ].sequence.parse(as: self) /// nestingTag case .nestingTag: return [ [ ~T.openTag.rule.require(.one), T.contents.rule.require(.one), T.closeTag.rule.require(.one)].sequence ].sequence.parse(as: self) /// tag case .tag: return [ [ ~T.nestingTag.rule.require(.one), ~T.inlineTag.rule.require(.one)].choice ].sequence.parse(as: self) /// contents case .contents: return [ [ T.data.rule.require(.one), T.tag.rule.require(.one)].choice ].sequence.parse(as: self) /// xml case .xml: return [ T.tag.rule.require(.one) ].sequence.parse(as: self) } } /// Create a language that can be used for parsing etc public static var grammar: [Rule] { return [T.xml.rule] } } class HomegenousASTTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testCache() { let astConstructor = AbstractSyntaxTreeConstructor() astConstructor.initializeCache(depth: 3, breadth: 3) } }
a8d1597e8cfded9959272928e43afdb7
30.285714
177
0.438213
false
false
false
false
JGiola/swift
refs/heads/main
test/IRGen/prespecialized-metadata/enum-fileprivate-inmodule-1argument-1distinct_use.swift
apache-2.0
14
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5Value[[UNIQUE_ID_1:[0-9A-Z_]+]]OySiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5Value[[UNIQUE_ID_1]]OySiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 513, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.*}}$s4main5Value[[UNIQUE_ID_1]]OMn{{.*}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] fileprivate enum Value<First> { case first(First) } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}}, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main5Value[[UNIQUE_ID_1]]OySiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) // CHECK-SAME: ) // CHECK: } func doit() { consume( Value.first(13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]OMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, // CHECK-SAME: i8* [[ERASED_TYPE]], // CHECK-SAME: i8* undef, // CHECK-SAME: i8* undef, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main5Value[[UNIQUE_ID_1]]OMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
775f2866d7184a9ffbc1f1a1968992db
37.915493
157
0.592472
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Plans/PlanComparisonViewController.swift
gpl-2.0
2
import UIKit import Gridicons import WordPressShared class PlanComparisonViewController: PagedViewController { let initialPlan: Plan let plans: [Plan] let features: [PlanFeature] // Keep a more specific reference to the view controllers rather than force // downcast viewControllers. fileprivate let detailViewControllers: [PlanDetailViewController] lazy fileprivate var cancelXButton: UIBarButtonItem = { let button = UIBarButtonItem(image: .gridicon(.cross), style: .plain, target: self, action: #selector(PlanComparisonViewController.closeTapped)) button.accessibilityLabel = NSLocalizedString("Close", comment: "Dismiss the current view") return button }() init(plans: [Plan], initialPlan: Plan, features: [PlanFeature]) { self.initialPlan = initialPlan self.plans = plans self.features = features let controllers: [PlanDetailViewController] = plans.map({ plan in let controller = PlanDetailViewController.controllerWithPlan(plan, features: features) return controller }) self.detailViewControllers = controllers let initialIndex = plans.firstIndex { plan in return plan == initialPlan } super.init(viewControllers: controllers, initialIndex: initialIndex!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func closeTapped() { dismiss(animated: true) } override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = cancelXButton } }
58196941c44aed1e7a9fb1c1dafe939d
30.339623
152
0.686334
false
false
false
false
eugeneego/utilities-ios
refs/heads/master
Sources/UI/NetworkImageView.swift
mit
1
// // GradientView // Legacy // // Copyright (c) 2016 Eugene Egorov. // License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE // #if canImport(UIKit) && !os(watchOS) import UIKit open class NetworkImageView: UIImageView { open var imageLoader: ImageLoader? open var resizeMode: ResizeMode = .fill open var placeholder: UIImage? open var imageUrl: URL? { didSet { if oldValue != imageUrl { update() } } } override open func layoutSubviews() { super.layoutSubviews() if task == nil && image == nil { update() } } private var task: Task<Void, Never>? private func update() { task?.cancel() task = nil image = placeholder guard bounds.width > 0.1 && bounds.height > 0.1 else { return } guard let imageLoader = imageLoader, let imageUrl = imageUrl else { return } task = Task { let result = await imageLoader.load(url: imageUrl, size: frame.size, mode: resizeMode) task = nil guard let image = result.value?.1 else { return } addFadeTransition() self.image = image } } } #endif
f085cb88a43c93c0b1b0a6a56ba945f1
21.321429
98
0.5664
false
false
false
false
evermeer/EVWordPressAPI
refs/heads/master
EVWordPressAPI/EVWordPressAPI_Stats.swift
bsd-3-clause
1
// // EVWordPressAPI_Stats.swift // EVWordPressAPI // // Created by Edwin Vermeer on 11/24/15. // Copyright © 2015 evict. All rights reserved. // import Alamofire import AlamofireOauth2 import AlamofireJsonToObjects import EVReflection public extension EVWordPressAPI { // MARK: - Stats /** Get a site's stats (authentication is required) See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Stats object :return: No return value */ public func stats(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Stats?) -> Void) { genericOauthCall(.Stats(pdict(parameters)), completionHandler: completionHandler) } /** View a site's summarized views, visitors, likes and comments (authentication is required) See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/summary/ :param: parameters an array of statsSummaryParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the StatsSummary object :return: No return value */ public func statsSummary(_ parameters:[statsSummaryParameters]? = nil, completionHandler: @escaping (StatsSummary?) -> Void) { genericOauthCall(.StatsSummary(pdict(parameters)), completionHandler: completionHandler) } /** View a site's top posts and pages by views (authentication is required) See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/top-posts/ :param: parameters an array of statsSummaryParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the StatsTopTasks object :return: No return value */ public func statsTopPosts(_ parameters:[statsSummaryParameters]? = nil, completionHandler: @escaping (StatsTopTasks?) -> Void) { genericOauthCall(.StatsTopTasks(pdict(parameters)), completionHandler: completionHandler) } /** View the details of a single video (authentication is required) See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/video/%24post_id/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the StatsVideo object :return: No return value */ public func statsVideo(_ parameters:[basicContextParameters]? = nil, videoId: String, completionHandler: @escaping (StatsVideo?) -> Void) { genericOauthCall(.StatsVideo(pdict(parameters), videoId), completionHandler: completionHandler) } /** View a site's referrers (authentication is required) See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/referrers/ :param: parameters an array of statsReferrersParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the StatsReferrer object :return: No return value */ public func statsReferrers(_ parameters:[statsReferrersParameters]? = nil, completionHandler: @escaping (StatsReferrer?) -> Void) { genericOauthCall(.StatsReferrers(pdict(parameters)), completionHandler: completionHandler) } /** View a site's outbound clicks (authentication is required) See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/clicks/ :param: parameters an array of statsReferrersParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the StatsClicks object :return: No return value */ public func statsClicks(_ parameters:[statsReferrersParameters]? = nil, completionHandler: @escaping (StatsClicks?) -> Void) { genericOauthCall(.StatsClicks(pdict(parameters)), completionHandler: completionHandler) } /** View a site's views by tags and categories (authentication is required) See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/tags/ :param: parameters an array of statsTagsParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the StatsTags object :return: No return value */ public func statsTags(_ parameters:[statsTagsParameters]? = nil, completionHandler: @escaping (StatsTags?) -> Void) { genericOauthCall(.StatsTags(pdict(parameters)), completionHandler: completionHandler) } /** View a site's top authors (authentication is required) See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/top-authors/ :param: parameters an array of statsReferrersParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the StatsAuthors object :return: No return value */ public func statsAuthors(_ parameters:[statsReferrersParameters]? = nil, completionHandler: @escaping (StatsAuthors?) -> Void) { genericOauthCall(.StatsAuthors(pdict(parameters)), completionHandler: completionHandler) } /** View a site's top comment authors and most-commented posts (authentication is required) See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/comments/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the StatsComments object :return: No return value */ public func statsComments(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (StatsComments?) -> Void) { genericOauthCall(.StatsComments(pdict(parameters)), completionHandler: completionHandler) } /** View a site's video plays (authentication is required) See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/video-plays/ :param: parameters an array of statsReferrersParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the StatsVideoPlays object :return: No return value */ public func statsVideoPlays(_ parameters:[statsReferrersParameters]? = nil, completionHandler: @escaping (StatsVideoPlays?) -> Void) { genericOauthCall(.StatsVideoPlays(pdict(parameters)), completionHandler: completionHandler) } public func statsPost(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (StatsPost?) -> Void) { genericOauthCall(.StatsPost(pdict(parameters)), completionHandler: completionHandler) } }
4d19a898c9fa0372c7fbbbbbea3f84c1
47.208054
143
0.728943
false
false
false
false
Ivacker/swift
refs/heads/master
test/Interpreter/SDK/Reflection_KVO.swift
apache-2.0
9
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // rdar://problem/19060227 import Foundation class ObservedValue: NSObject { dynamic var amount = 0 } class ValueObserver: NSObject { private var observeContext = 0 let observedValue: ObservedValue init(value: ObservedValue) { observedValue = value super.init() observedValue.addObserver(self, forKeyPath: "amount", options: .New, context: &observeContext) } deinit { observedValue.removeObserver(self, forKeyPath: "amount") } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if context == &observeContext { if let change_ = change { if let amount = change_[NSKeyValueChangeNewKey as String] as? Int { print("Observed value updated to \(amount)") } } } } } let value = ObservedValue() value.amount = 42 let observer = ValueObserver(value: value) // CHECK: updated to 43 value.amount++ // CHECK: amount: 43 dump(value)
c0c2652ed32514ab7536b057c1622af9
22.361702
154
0.704007
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Contacts List/AAContactsListContentController.swift
agpl-3.0
2
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation public class AAContactsListContentController: AAContentTableController { public var delegate: AAContactsListContentControllerDelegate? public var isSearchAutoHide: Bool = true public var contactRows: AABindedRows<AAContactCell>! public var searchEnabled: Bool = true public init() { super.init(style: .Plain) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func tableDidLoad() { if searchEnabled { search(AAContactCell.self) { (s) -> () in s.searchList = Actor.buildContactsDisplayList() s.isSearchAutoHide = self.isSearchAutoHide s.selectAction = { (contact) -> () in if let d = self.delegate { d.contactDidTap(self, contact: contact) } } } } section { (s) -> () in s.autoSeparatorsInset = 80 if let d = self.delegate { d.willAddContacts(self, section: s) } self.contactRows = s.binded { (r: AABindedRows<AAContactCell>) -> () in r.displayList = Actor.buildContactsDisplayList() r.selectAction = { (contact) -> Bool in if let d = self.delegate { return d.contactDidTap(self, contact: contact) } return true } r.didBind = { (cell, contact) -> () in if let d = self.delegate { return d.contactDidBind(self, contact: contact, cell: cell) } } } if let d = self.delegate { d.didAddContacts(self, section: s) } } placeholder.setImage( UIImage.bundled("contacts_list_placeholder"), title: AALocalized("Placeholder_Contacts_Title"), subtitle: AALocalized("Placeholder_Contacts_Message").replace("{appname}", dest: ActorSDK.sharedActor().appName), actionTitle: AALocalized("Placeholder_Contacts_Action"), subtitle2: AALocalized("Placeholder_Contacts_Message2"), actionTarget: self, actionSelector: Selector("showSmsInvitation"), action2title: nil, action2Selector: nil) } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) binder.bind(Actor.getAppState().isContactsEmpty, closure: { (value: Any?) -> () in if let empty = value as? JavaLangBoolean { if Bool(empty.booleanValue()) == true { self.showPlaceholder() } else { self.hidePlaceholder() } } }) } }
478359db69f92a26208a524920a2f001
32.712766
125
0.505051
false
false
false
false
hryk224/IPhotoBrowser
refs/heads/master
IPhotoBrowserExample/IPhotoBrowserExample/Sources/View/Controller/Table/ImageUrlViewController.swift
mit
1
// // ColorViewController.swift // IPhotoBrowserExample // // Created by hryk224 on 2017/02/15. // Copyright © 2017年 hryk224. All rights reserved. // import UIKit import IPhotoBrowser final class ImageUrlViewController: UITableViewController { static func makeFromStoryboard() -> ImageUrlViewController { let storyboard = UIStoryboard(name: "ImageUrlViewController", bundle: nil) return storyboard.instantiateInitialViewController() as! ImageUrlViewController } fileprivate var imageUrls: Assets.ImageURL { return Assets.ImageURL.share } fileprivate var indexPathForSelectedRow: IndexPath? override func viewDidLoad() { super.viewDidLoad() tableView.register(WebImageTableViewCell.nib, forCellReuseIdentifier: WebImageTableViewCell.identifier) tableView.separatorInset = .zero title = MainViewController.Row.imageUrl.title } } // MARK: - UICollectionViewDelegate, UICollectionViewDataSource extension ImageUrlViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return imageUrls.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: WebImageTableViewCell.identifier, for: indexPath) as! WebImageTableViewCell cell.configure(imageUrl: imageUrls.objects[indexPath.row]) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let photoBrowser = IPhotoBrowser(imageUrls: imageUrls.objects, start: indexPath.item) photoBrowser.delegate = self DispatchQueue.main.async { self.present(photoBrowser, animated: true, completion: nil) } indexPathForSelectedRow = indexPath tableView.deselectRow(at: indexPath, animated: false) } } // MARK: - IPhotoBrowserAnimatedTransitionProtocol extension ImageUrlViewController: IPhotoBrowserAnimatedTransitionProtocol { var iPhotoBrowserSelectedImageViewCopy: UIImageView? { guard let indexPath = indexPathForSelectedRow, let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell else { return nil } let sourceImageView = UIImageView(image: cell.webImageView.image) sourceImageView.contentMode = cell.webImageView.contentMode sourceImageView.clipsToBounds = true sourceImageView.frame = cell.contentView.convert(cell.webImageView.frame, to: navigationController?.view) sourceImageView.layer.cornerRadius = cell.webImageView.layer.cornerRadius return sourceImageView } var iPhotoBrowserDestinationImageViewSize: CGSize? { guard let indexPath = indexPathForSelectedRow else { return nil } let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell return cell?.webImageView.frame.size } var iPhotoBrowserDestinationImageViewCenter: CGPoint? { guard let indexPath = indexPathForSelectedRow, let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell else { return nil } return cell.contentView.convert(cell.webImageView.center, to: navigationController?.view) } func iPhotoBrowserTransitionWillBegin() { guard let indexPath = indexPathForSelectedRow else { return } let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell cell?.webImageView.isHidden = true } func iPhotoBrowserTransitionDidEnded() { guard let indexPath = indexPathForSelectedRow else { return } let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell cell?.webImageView.isHidden = false } } // MARK: - IPhotoBrowserDelegate extension ImageUrlViewController: IPhotoBrowserDelegate { func iPhotoBrowser(_ iPhotoBrowser: IPhotoBrowser, didChange index: Int) { let indexPath = IndexPath(item: index, section: 0) tableView.selectRow(at: indexPath, animated: false, scrollPosition: .top) indexPathForSelectedRow = indexPath } func iPhotoBrowserDidDismissing(_ iPhotoBrowser: IPhotoBrowser) { guard let indexPath = indexPathForSelectedRow else { return } let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell cell?.webImageView.isHidden = true } func iPhotoBrowserDidCanceledDismiss(_ iPhotoBrowser: IPhotoBrowser) { guard let indexPath = indexPathForSelectedRow else { return } let cell = tableView.cellForRow(at: indexPath) as? WebImageTableViewCell cell?.webImageView.isHidden = false } }
d3dbbfc2086476e0759745dfdb78c872
41.707965
140
0.716743
false
false
false
false
Pluto-tv/RxSwift
refs/heads/master
RxCocoa/OSX/NSControl+Rx.swift
mit
1
// // NSControl+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 5/31/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import Cocoa #if !RX_NO_MODULE import RxSwift #endif var rx_value_key: UInt8 = 0 var rx_control_events_key: UInt8 = 0 extension NSControl { /** Reactive wrapper for control event. */ public var rx_controlEvents: ControlEvent<Void> { MainScheduler.ensureExecutingOnScheduler() let source = rx_lazyInstanceObservable(&rx_control_events_key) { () -> Observable<Void> in AnonymousObservable { [weak self] observer in MainScheduler.ensureExecutingOnScheduler() guard let control = self else { observer.on(.Completed) return NopDisposable.instance } let observer = ControlTarget(control: control) { control in observer.on(.Next()) } return observer }.takeUntil(self.rx_deallocated) } return ControlEvent(source: source) } /** Helper to make sure that `Observable` returned from `createCachedObservable` is only created once. This is important because on OSX there is only one `target` and `action` properties on `NSControl`. */ func rx_lazyInstanceObservable<T: AnyObject>(key: UnsafePointer<Void>, createCachedObservable: () -> T) -> T { if let value = objc_getAssociatedObject(self, key) { return value as! T } let observable = createCachedObservable() objc_setAssociatedObject(self, key, observable, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return observable } func rx_value<T>(getter getter: () -> T, setter: T -> Void) -> ControlProperty<T> { MainScheduler.ensureExecutingOnScheduler() let source = rx_lazyInstanceObservable(&rx_value_key) { () -> Observable<T> in return AnonymousObservable { [weak self] observer in guard let control = self else { observer.on(.Completed) return NopDisposable.instance } observer.on(.Next(getter())) let observer = ControlTarget(control: control) { control in observer.on(.Next(getter())) } return observer }.takeUntil(self.rx_deallocated) } return ControlProperty(source: source, observer: AnyObserver { event in switch event { case .Next(let value): setter(value) case .Error(let error): bindingErrorToInterface(error) case .Completed: break } }) } }
b111d7fd63ca088dce098b637c0c514e
29.347368
114
0.57356
false
false
false
false
googlecodelabs/automl-vision-edge-in-mlkit
refs/heads/master
ios/mlkit-automl/MLVisionExample/ViewController.swift
apache-2.0
1
// // Copyright 2019 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit class ViewController: UIViewController, UINavigationControllerDelegate { /// An image picker for accessing the photo library or camera. private var imagePicker = UIImagePickerController() /// Image counter. private var currentImage = 0 /// AutoML image classifier wrapper. private lazy var classifier = ImageClassifer() // MARK: - IBOutlets @IBOutlet fileprivate weak var imageView: UIImageView! @IBOutlet fileprivate weak var photoCameraButton: UIBarButtonItem! @IBOutlet fileprivate weak var videoCameraButton: UIBarButtonItem! @IBOutlet fileprivate weak var resultsLabelView: UILabel! // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self imagePicker.sourceType = .photoLibrary let isCameraAvailable = UIImagePickerController.isCameraDeviceAvailable(.front) || UIImagePickerController.isCameraDeviceAvailable(.rear) if isCameraAvailable { // `CameraViewController` uses `AVCaptureDevice.DiscoverySession` which is only supported for // iOS 10 or newer. if #available(iOS 10.0, *) { videoCameraButton.isEnabled = true } } else { photoCameraButton.isEnabled = false } // Set up image view and classify the first image in the bundle. imageView.image = UIImage(named: Constant.images[currentImage]) classifyImage() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.navigationBar.isHidden = false } // MARK: - IBActions @IBAction func openPhotoLibrary(_ sender: Any) { imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true) } @IBAction func openCamera(_ sender: Any) { guard UIImagePickerController.isCameraDeviceAvailable(.front) || UIImagePickerController.isCameraDeviceAvailable(.rear) else { return } imagePicker.sourceType = .camera present(imagePicker, animated: true) } @IBAction func changeImage(_ sender: Any) { nextImageAndClassify() } // MARK: - Private /// Clears the results text view and removes any frames that are visible. private func clearResults() { resultsLabelView.text = "" imageView.image = nil } /// Update the results text view with classification result. private func showResult(_ resultText: String) { self.resultsLabelView.text = resultText } /// Change to the next image available in app's bundle, and run image classification. private func nextImageAndClassify() { clearResults() currentImage = (currentImage + 1) % Constant.images.count imageView.image = UIImage(named: Constant.images[currentImage]) classifyImage() } /// Run image classification on the image currently display in imageView. private func classifyImage() { guard let image = imageView.image else { print("Error: Attempted to run classification on a nil object") showResult("Error: invalid image") return } classifier.classifyImage(image) { resultText, error in // Handle classification error guard error == nil else { self.showResult(error!.localizedDescription) return } // We don't expect resultText and error to be both nil, so this is just a safeguard. guard resultText != nil else { self.showResult("Error: Unknown error occured") return } self.showResult(resultText!) } } } // MARK: - UIImagePickerControllerDelegate extension ViewController: UIImagePickerControllerDelegate { public func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] ) { if let pickedImage = info[.originalImage] as? UIImage { clearResults() imageView.image = pickedImage classifyImage() } dismiss(animated: true) } } // MARK: - Constants private enum Constant { static let images = ["sunflower_1627193_640.jpg", "sunflower_3292932_640.jpg", "dandelion_4110356_640.jpg", "dandelion_2817950_640.jpg", "rose_1463562_640.jpg", "rose_3063284_640.jpg"] }
21bc1bf981ceabdfdb771929269dfbe9
28.270588
99
0.705587
false
false
false
false
elkanaoptimove/OptimoveSDK
refs/heads/master
OptimoveSDK/Tenant Config/FirebaseKeys/FirebaseProjectKeys.swift
mit
1
// // FirebaseProjectKeys.swift // WeAreOptimove // // Created by Elkana Orbach on 10/05/2018. // Copyright © 2018 Optimove. All rights reserved. // import Foundation class FirebaseProjectKeys:FirebaseKeys { var appid:String required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let appIds = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .appIds ) let ios = try appIds.nestedContainer(keyedBy: CK.self, forKey: .ios) let key = Bundle.main.bundleIdentifier! appid = try ios.decode(String.self, forKey: CK(stringValue:key)!) try super.init(from: decoder) } }
02e142338aaf3e6a74a2a1927efc9311
28.208333
91
0.68331
false
false
false
false
takayoshiotake/SevenSegmentSampler_swift
refs/heads/master
SevenSegmentViewSampler/ViewController.swift
mit
1
// // ViewController.swift // SevenSegmentViewSampler // // Created by Takayoshi Otake on 2015/11/08. // Copyright © 2015 Takayoshi Otake. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var stackView: UIStackView! let valueMap: [Int: Int16] = [ 0:0x3f, 1:0x06, 2:0x5b, 3:0x4f, 4:0x66, 5:0x6d, 6:0x7d, 7:0x07, 8:0x7f, 9:0x6f, ] var value: Int = 0 { didSet { if let temp_view = stackView.subviews[0] as? BBSevenSegmentView { temp_view.pinBits = valueMap[(value / 100) % 10]! } if let temp_view = stackView.subviews[1] as? BBSevenSegmentView { temp_view.pinBits = valueMap[(value / 10) % 10]! | 0x80 } if let temp_view = stackView.subviews[2] as? BBSevenSegmentView { temp_view.pinBits = valueMap[(value / 1) % 10]! } } } var timer: NSTimer? deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewDidLoad() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidBecomeActive:", name: UIApplicationDidBecomeActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillResignActive:", name: UIApplicationWillResignActiveNotification, object: nil) } func applicationDidBecomeActive(notification: NSNotification) { start() } func applicationWillResignActive(notification: NSNotification) { stop() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) start() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) stop() } private func start() { if let timer = timer { if timer.valid { return } } timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "timerDidTick:", userInfo: nil, repeats: true) } private func stop() { if let timer = timer { timer.invalidate() } timer = nil } func timerDidTick(timer: NSTimer) { dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in if let selfVC = self { if (selfVC.value < 1000) { selfVC.value += 1 } else { selfVC.value = 0 } } } } }
87e0e6a2677bee78cc43fcfec51e5d41
25.881188
166
0.554328
false
false
false
false
lucasmpaim/GuizionCardView
refs/heads/master
guizion-card-view/Classes/MaskLabel.swift
mit
1
// // MaskLabel.swift // guizion-card-view // // Created by Lucas Paim on 13/11/2017. // import Foundation import UIKit class MaskLabel: UILabel { var textMask: String = "#### #### #### ####" fileprivate var applyingMask = false override var text: String? { didSet { if !applyingMask { applyMask(text) } } } fileprivate func applyMask(_ _value: String?) { //Remove spaces applyingMask = true guard let value = _value?.replacingOccurrences(of: " ", with: "") else { return } var maskedValue = "" var currentTextIndex = 0 textMask.forEach { if currentTextIndex < value.count { if $0 == "#" { maskedValue += value[currentTextIndex] currentTextIndex += 1 } else { maskedValue += "\($0)" } } } text = maskedValue applyingMask = false } }
744e488b60ed7a7402a449bd525afb73
20.115385
89
0.456284
false
false
false
false
AnthonyMDev/AmazonS3RequestManager
refs/heads/develop
Carthage/Checkouts/Nimble/Sources/Nimble/Utils/Async.swift
apache-2.0
67
import CoreFoundation import Dispatch import Foundation #if !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) import CDispatch #endif private let timeoutLeeway = DispatchTimeInterval.milliseconds(1) private let pollLeeway = DispatchTimeInterval.milliseconds(1) /// Stores debugging information about callers internal struct WaitingInfo: CustomStringConvertible { let name: String let file: FileString let lineNumber: UInt var description: String { return "\(name) at \(file):\(lineNumber)" } } internal protocol WaitLock { func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt) func releaseWaitingLock() func isWaitingLocked() -> Bool } internal class AssertionWaitLock: WaitLock { private var currentWaiter: WaitingInfo? init() { } func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt) { let info = WaitingInfo(name: fnName, file: file, lineNumber: line) #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let isMainThread = Thread.isMainThread #else let isMainThread = _CFIsMainThread() #endif nimblePrecondition( isMainThread, "InvalidNimbleAPIUsage", "\(fnName) can only run on the main thread." ) nimblePrecondition( currentWaiter == nil, "InvalidNimbleAPIUsage", "Nested async expectations are not allowed to avoid creating flaky tests.\n\n" + "The call to\n\t\(info)\n" + "triggered this exception because\n\t\(currentWaiter!)\n" + "is currently managing the main run loop." ) currentWaiter = info } func isWaitingLocked() -> Bool { return currentWaiter != nil } func releaseWaitingLock() { currentWaiter = nil } } internal enum AwaitResult<T> { /// Incomplete indicates None (aka - this value hasn't been fulfilled yet) case incomplete /// TimedOut indicates the result reached its defined timeout limit before returning case timedOut /// BlockedRunLoop indicates the main runloop is too busy processing other blocks to trigger /// the timeout code. /// /// This may also mean the async code waiting upon may have never actually ran within the /// required time because other timers & sources are running on the main run loop. case blockedRunLoop /// The async block successfully executed and returned a given result case completed(T) /// When a Swift Error is thrown case errorThrown(Error) /// When an Objective-C Exception is raised case raisedException(NSException) func isIncomplete() -> Bool { switch self { case .incomplete: return true default: return false } } func isCompleted() -> Bool { switch self { case .completed: return true default: return false } } } /// Holds the resulting value from an asynchronous expectation. /// This class is thread-safe at receiving an "response" to this promise. internal class AwaitPromise<T> { private(set) internal var asyncResult: AwaitResult<T> = .incomplete private var signal: DispatchSemaphore init() { signal = DispatchSemaphore(value: 1) } deinit { signal.signal() } /// Resolves the promise with the given result if it has not been resolved. Repeated calls to /// this method will resolve in a no-op. /// /// @returns a Bool that indicates if the async result was accepted or rejected because another /// value was received first. func resolveResult(_ result: AwaitResult<T>) -> Bool { if signal.wait(timeout: .now()) == .success { self.asyncResult = result return true } else { return false } } } internal struct AwaitTrigger { let timeoutSource: DispatchSourceTimer let actionSource: DispatchSourceTimer? let start: () throws -> Void } /// Factory for building fully configured AwaitPromises and waiting for their results. /// /// This factory stores all the state for an async expectation so that Await doesn't /// doesn't have to manage it. internal class AwaitPromiseBuilder<T> { let awaiter: Awaiter let waitLock: WaitLock let trigger: AwaitTrigger let promise: AwaitPromise<T> internal init( awaiter: Awaiter, waitLock: WaitLock, promise: AwaitPromise<T>, trigger: AwaitTrigger) { self.awaiter = awaiter self.waitLock = waitLock self.promise = promise self.trigger = trigger } func timeout(_ timeoutInterval: TimeInterval, forcefullyAbortTimeout: TimeInterval) -> Self { // = Discussion = // // There's a lot of technical decisions here that is useful to elaborate on. This is // definitely more lower-level than the previous NSRunLoop based implementation. // // // Why Dispatch Source? // // // We're using a dispatch source to have better control of the run loop behavior. // A timer source gives us deferred-timing control without having to rely as much on // a run loop's traditional dispatching machinery (eg - NSTimers, DefaultRunLoopMode, etc.) // which is ripe for getting corrupted by application code. // // And unlike dispatch_async(), we can control how likely our code gets prioritized to // executed (see leeway parameter) + DISPATCH_TIMER_STRICT. // // This timer is assumed to run on the HIGH priority queue to ensure it maintains the // highest priority over normal application / test code when possible. // // // Run Loop Management // // In order to properly interrupt the waiting behavior performed by this factory class, // this timer stops the main run loop to tell the waiter code that the result should be // checked. // // In addition, stopping the run loop is used to halt code executed on the main run loop. #if swift(>=4.0) trigger.timeoutSource.schedule( deadline: DispatchTime.now() + timeoutInterval, repeating: .never, leeway: timeoutLeeway ) #else trigger.timeoutSource.scheduleOneshot( deadline: DispatchTime.now() + timeoutInterval, leeway: timeoutLeeway ) #endif trigger.timeoutSource.setEventHandler { guard self.promise.asyncResult.isIncomplete() else { return } let timedOutSem = DispatchSemaphore(value: 0) let semTimedOutOrBlocked = DispatchSemaphore(value: 0) semTimedOutOrBlocked.signal() let runLoop = CFRunLoopGetMain() #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let runLoopMode = CFRunLoopMode.defaultMode.rawValue #else let runLoopMode = kCFRunLoopDefaultMode #endif CFRunLoopPerformBlock(runLoop, runLoopMode) { if semTimedOutOrBlocked.wait(timeout: .now()) == .success { timedOutSem.signal() semTimedOutOrBlocked.signal() if self.promise.resolveResult(.timedOut) { CFRunLoopStop(CFRunLoopGetMain()) } } } // potentially interrupt blocking code on run loop to let timeout code run CFRunLoopStop(runLoop) let now = DispatchTime.now() + forcefullyAbortTimeout let didNotTimeOut = timedOutSem.wait(timeout: now) != .success let timeoutWasNotTriggered = semTimedOutOrBlocked.wait(timeout: .now()) == .success if didNotTimeOut && timeoutWasNotTriggered { if self.promise.resolveResult(.blockedRunLoop) { CFRunLoopStop(CFRunLoopGetMain()) } } } return self } /// Blocks for an asynchronous result. /// /// @discussion /// This function must be executed on the main thread and cannot be nested. This is because /// this function (and it's related methods) coordinate through the main run loop. Tampering /// with the run loop can cause undesirable behavior. /// /// This method will return an AwaitResult in the following cases: /// /// - The main run loop is blocked by other operations and the async expectation cannot be /// be stopped. /// - The async expectation timed out /// - The async expectation succeeded /// - The async expectation raised an unexpected exception (objc) /// - The async expectation raised an unexpected error (swift) /// /// The returned AwaitResult will NEVER be .incomplete. func wait(_ fnName: String = #function, file: FileString = #file, line: UInt = #line) -> AwaitResult<T> { waitLock.acquireWaitingLock( fnName, file: file, line: line) let capture = NMBExceptionCapture(handler: ({ exception in _ = self.promise.resolveResult(.raisedException(exception)) }), finally: ({ self.waitLock.releaseWaitingLock() })) capture.tryBlock { do { try self.trigger.start() } catch let error { _ = self.promise.resolveResult(.errorThrown(error)) } self.trigger.timeoutSource.resume() while self.promise.asyncResult.isIncomplete() { // Stopping the run loop does not work unless we run only 1 mode _ = RunLoop.current.run(mode: .defaultRunLoopMode, before: .distantFuture) } self.trigger.timeoutSource.cancel() if let asyncSource = self.trigger.actionSource { asyncSource.cancel() } } return promise.asyncResult } } internal class Awaiter { let waitLock: WaitLock let timeoutQueue: DispatchQueue let asyncQueue: DispatchQueue internal init( waitLock: WaitLock, asyncQueue: DispatchQueue, timeoutQueue: DispatchQueue) { self.waitLock = waitLock self.asyncQueue = asyncQueue self.timeoutQueue = timeoutQueue } private func createTimerSource(_ queue: DispatchQueue) -> DispatchSourceTimer { return DispatchSource.makeTimerSource(flags: .strict, queue: queue) } func performBlock<T>( file: FileString, line: UInt, _ closure: @escaping (@escaping (T) -> Void) throws -> Void ) -> AwaitPromiseBuilder<T> { let promise = AwaitPromise<T>() let timeoutSource = createTimerSource(timeoutQueue) var completionCount = 0 let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: nil) { try closure { completionCount += 1 if completionCount < 2 { if promise.resolveResult(.completed($0)) { CFRunLoopStop(CFRunLoopGetMain()) } } else { fail("waitUntil(..) expects its completion closure to be only called once", file: file, line: line) } } } return AwaitPromiseBuilder( awaiter: self, waitLock: waitLock, promise: promise, trigger: trigger) } func poll<T>(_ pollInterval: TimeInterval, closure: @escaping () throws -> T?) -> AwaitPromiseBuilder<T> { let promise = AwaitPromise<T>() let timeoutSource = createTimerSource(timeoutQueue) let asyncSource = createTimerSource(asyncQueue) let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: asyncSource) { let interval = DispatchTimeInterval.nanoseconds(Int(pollInterval * TimeInterval(NSEC_PER_SEC))) #if swift(>=4.0) asyncSource.schedule(deadline: .now(), repeating: interval, leeway: pollLeeway) #else asyncSource.scheduleRepeating(deadline: .now(), interval: interval, leeway: pollLeeway) #endif asyncSource.setEventHandler { do { if let result = try closure() { if promise.resolveResult(.completed(result)) { CFRunLoopStop(CFRunLoopGetCurrent()) } } } catch let error { if promise.resolveResult(.errorThrown(error)) { CFRunLoopStop(CFRunLoopGetCurrent()) } } } asyncSource.resume() } return AwaitPromiseBuilder( awaiter: self, waitLock: waitLock, promise: promise, trigger: trigger) } } internal func pollBlock( pollInterval: TimeInterval, timeoutInterval: TimeInterval, file: FileString, line: UInt, fnName: String = #function, expression: @escaping () throws -> Bool) -> AwaitResult<Bool> { let awaiter = NimbleEnvironment.activeInstance.awaiter let result = awaiter.poll(pollInterval) { () throws -> Bool? in if try expression() { return true } return nil }.timeout(timeoutInterval, forcefullyAbortTimeout: timeoutInterval / 2.0).wait(fnName, file: file, line: line) return result }
233d3b9961312d705aaf9f1b49c333a8
35.591512
118
0.60116
false
false
false
false
CaiMiao/CGSSGuide
refs/heads/master
DereGuide/Settings/Controller/DownloadImageViewController.swift
mit
1
// // DownloadImageViewController.swift // DereGuide // // Created by zzk on 2017/2/2. // Copyright © 2017年 zzk. All rights reserved. // import UIKit import SDWebImage typealias DownloadImageCell = WipeTableViewCell class DownloadImageViewController: BaseTableViewController { var dataTypes = [NSLocalizedString("全选", comment: ""), NSLocalizedString("卡片大图", comment: ""), NSLocalizedString("卡片图", comment: ""), NSLocalizedString("卡片头像", comment: ""), NSLocalizedString("签名图", comment: ""), NSLocalizedString("角色头像", comment: ""), NSLocalizedString("歌曲封面", comment: ""), NSLocalizedString("活动封面", comment: ""), NSLocalizedString("卡池封面", comment: "")] private struct ResourceURLs { var inCache = [URL]() var needToDownload = [URL]() var count: Int { return inCache.count + needToDownload.count } mutating func removeAll() { inCache.removeAll() needToDownload.removeAll() } } private var spreadURLs = ResourceURLs() { didSet { setupCellAtIndex(1) } } private var cardImageURLs = ResourceURLs() { didSet { setupCellAtIndex(2) } } private var cardIconURLs = ResourceURLs() { didSet { setupCellAtIndex(3) } } private var cardSignURLs = ResourceURLs() { didSet { setupCellAtIndex(4) } } private var charIconURLs = ResourceURLs() { didSet { setupCellAtIndex(5) } } private var jacketURLs = ResourceURLs() { didSet { setupCellAtIndex(6) } } private var eventURLs = ResourceURLs() { didSet { setupCellAtIndex(7) } } private var gachaURLs = ResourceURLs() { didSet { setupCellAtIndex(8) } } private func getURLsBy(index: Int) -> ResourceURLs { switch index { case 1: return spreadURLs case 2: return cardImageURLs case 3: return cardIconURLs case 4: return cardSignURLs case 5: return charIconURLs case 6: return jacketURLs case 7: return eventURLs case 8: return gachaURLs default: return ResourceURLs() } } func setupCellAtIndex(_ index: Int) { DispatchQueue.main.async { let cell = self.tableView.cellForRow(at: IndexPath.init(row: index, section: 0)) as? DownloadImageCell let urls = self.getURLsBy(index: index) cell?.rightLabel?.text = "\(urls.inCache.count)/\(urls.count)" } } override func viewDidLoad() { super.viewDidLoad() tableView.allowsMultipleSelection = true tableView.setEditing(true, animated: true) tableView.tableFooterView = UIView.init(frame: CGRect.zero) tableView.register(DownloadImageCell.self, forCellReuseIdentifier: "CacheCell") self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: #imageLiteral(resourceName: "703-download"), style: .plain, target: self, action: #selector(cacheData)) calculate() // Do any additional setup after loading the view. } func calculate() { DispatchQueue.global(qos: .userInitiated).async { self.removeAllURLs() let cards = CGSSDAO.shared.cardDict.allValues as! [CGSSCard] let chars = CGSSDAO.shared.charDict.allValues as! [CGSSChar] // 所有卡片大图和头像图 for card in cards { // 卡片大图 if card.hasSpread! { if let url = URL.init(string: card.spreadImageRef!) { SDWebImageManager.shared().cachedImageExists(for: url, completion: { (isInCache) in if isInCache { self.spreadURLs.inCache.append(url) } else { self.spreadURLs.needToDownload.append(url) } }) } } // 卡头像图 let url = URL.images.appendingPathComponent("/icon_card/\(card.id!).png") SDWebImageManager.shared().cachedImageExists(for: url, completion: { (isInCache) in if isInCache { self.cardIconURLs.inCache.append(url) } else { self.cardIconURLs.needToDownload.append(url) } }) // 卡签名图 if let url = card.signImageURL { SDWebImageManager.shared().cachedImageExists(for: url, completion: { (isInCache) in if isInCache { self.cardSignURLs.inCache.append(url) } else { self.cardSignURLs.needToDownload.append(url) } }) } // 卡片图 if let url = URL.init(string: card.cardImageRef) { SDWebImageManager.shared().cachedImageExists(for: url, completion: { (isInCache) in if isInCache { self.cardImageURLs.inCache.append(url) } else { self.cardImageURLs.needToDownload.append(url) } }) } } for char in chars { // 角色头像图 let url = URL.images.appendingPathComponent("/icon_char/\(char.charaId!).png") SDWebImageManager.shared().cachedImageExists(for: url, completion: { (isInCache) in if isInCache { self.charIconURLs.inCache.append(url) } else { self.charIconURLs.needToDownload.append(url) } }) } // 所有歌曲封面图 CGSSGameResource.shared.master.getLives(callback: { (lives) in for live in lives { let url = live.jacketURL SDWebImageManager.shared().cachedImageExists(for: url, completion: { (isInCache) in if isInCache { self.jacketURLs.inCache.append(url) } else { self.jacketURLs.needToDownload.append(url) } }) } }) CGSSGameResource.shared.master.getEvents(callback: { (events) in for event in events { if let url = event.detailBannerURL { SDWebImageManager.shared().cachedImageExists(for: url, completion: { (isInCache) in if isInCache { self.eventURLs.inCache.append(url) } else { self.eventURLs.needToDownload.append(url) } }) } } }) CGSSGameResource.shared.master.getValidGacha(callback: { (pools) in for gachaPool in pools { if let url = gachaPool.detailBannerURL, ![30001, 30006].contains(gachaPool.id) { // 温泉旅行和初始卡池的图片目前缺失, 故不加入待下载列表 SDWebImageManager.shared().cachedImageExists(for: url, completion: { (isInCache) in if isInCache { self.gachaURLs.inCache.append(url) } else { self.gachaURLs.needToDownload.append(url) } }) } } }) } } func removeAllURLs() { cardIconURLs.removeAll() spreadURLs.removeAll() cardImageURLs.removeAll() cardSignURLs.removeAll() charIconURLs.removeAll() eventURLs.removeAll() jacketURLs.removeAll() gachaURLs.removeAll() } @objc private func cacheData() { if CGSSUpdater.default.isWorking { return } var urls = [URL]() if let indexPaths = tableView.indexPathsForSelectedRows { for indexPath in indexPaths { urls.append(contentsOf: getURLsBy(index: indexPath.row).needToDownload) } } CGSSUpdatingHUDManager.shared.show() CGSSUpdatingHUDManager.shared.cancelAction = { [weak self] in SDWebImagePrefetcher.shared().cancelPrefetching() CGSSUpdater.default.isUpdating = false self?.calculate() } CGSSUpdatingHUDManager.shared.setup(current: 0, total: urls.count, animated: true, cancelable: true) CGSSUpdater.default.updateImages(urls: urls, progress: { (a, b) in DispatchQueue.main.async { CGSSUpdatingHUDManager.shared.setup(current: a, total: b, animated: true, cancelable: true) } }) { [weak self] (a, b) in DispatchQueue.main.async { let alert = UIAlertController(title: NSLocalizedString("缓存图片完成", comment: "设置页面"), message: "\(NSLocalizedString("成功", comment: "设置页面")) \(a), \(NSLocalizedString("失败", comment: "设置页面")) \(b - a)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("确定", comment: "设置页面"), style: .default, handler: nil)) UIViewController.root?.present(alert, animated: true, completion: nil) CGSSUpdatingHUDManager.shared.hide(animated: false) self?.calculate() } } } override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return dataTypes.count } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.init(rawValue: UITableViewCellEditingStyle.delete.rawValue | UITableViewCellEditingStyle.insert.rawValue)! } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CacheCell", for: indexPath) as! DownloadImageCell if indexPath.row == 0 { cell.rightLabel?.text = "" } else { setupCellAtIndex(indexPath.row) } cell.leftLabel?.text = dataTypes[indexPath.row] // Configure the cell... return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 0 { for i in 1..<dataTypes.count { tableView.selectRow(at: IndexPath.init(row: i, section: 0), animated: false, scrollPosition: .none) } } } override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if indexPath.row == 0 { for i in 1..<dataTypes.count { tableView.deselectRow(at: IndexPath.init(row: i, section: 0), animated: false) } } else { tableView.deselectRow(at: IndexPath.init(row: 0, section: 0), animated: false) } } }
6fd074f253d8d7f57fe1dd5e5e67f2c4
35.431953
237
0.515592
false
false
false
false
piscoTech/GymTracker
refs/heads/master
Gym Tracker iOS/CurrentWorkoutVC.swift
mit
1
// // CurrentWorkoutViewController.swift // Gym Tracker // // Created by Marco Boschi on 08/04/2017. // Copyright © 2017 Marco Boschi. All rights reserved. // import UIKit import MBLibrary import GymTrackerCore class CurrentWorkoutViewController: UIViewController { @IBOutlet private var cancelBtn: UIBarButtonItem! @IBOutlet private var endNowBtn: UIBarButtonItem! @IBOutlet private weak var manageFromWatchLbl: UILabel! @IBOutlet private weak var noWorkoutLabel: UIView! @IBOutlet private weak var workoutInfo: UIStackView! @IBOutlet private weak var workoutTitleLbl: UILabel! @IBOutlet private weak var bpmLbl: UILabel! @IBOutlet private weak var timerLbl: UILabel! @IBOutlet private weak var currentExerciseInfo: UIStackView! @IBOutlet private weak var exerciseNameLbl: UILabel! @IBOutlet private weak var currentSetInfoLbl: UILabel! @IBOutlet private weak var otherSetsLbl: UILabel! @IBOutlet private weak var setDoneBtn: UIButton! @IBOutlet private weak var restInfo: UIStackView! @IBOutlet private weak var restTimerLbl: UILabel! @IBOutlet private weak var restDoneBtn: UIButton! @IBOutlet private weak var workoutDoneInfo: UIStackView! @IBOutlet private weak var workoutDoneLbl: UILabel! @IBOutlet private weak var workoutDoneBtn: UIButton! @IBOutlet private weak var nextUpInfo: UIView! @IBOutlet private weak var nextUpLbl: UILabel! @IBOutlet private weak var tipView: UIView! private var workoutController: ExecuteWorkoutController? { return appDelegate.workoutController } override func viewDidLoad() { super.viewDidLoad() appDelegate.currentWorkout = self for b in [setDoneBtn, restDoneBtn] { b?.clipsToBounds = true b?.layer.cornerRadius = 5 } for l in [bpmLbl, timerLbl, restTimerLbl] { l?.font = l?.font?.makeMonospacedDigit() } // This method is always called during app launch by the app delegate and as soon as the view is loaded it also updates it as appropriate if #available(iOS 13, *) {} else { self.navigationController?.navigationBar.barStyle = .black self.view.backgroundColor = .black } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setWorkoutTitle(_ text: String) { workoutTitleLbl.text = text } func askForChoices(_ choices: [GTChoice]) { DispatchQueue.main.async { self.performSegue(withIdentifier: "askChoices", sender: choices) } } func setBPM(_ text: String) { bpmLbl.text = text } private var timerDate: Date! private var timerUpdater: Timer? { didSet { DispatchQueue.main.async { oldValue?.invalidate() } } } func startTimer(at date: Date) { timerDate = date let update = { self.timerLbl.text = Date().timeIntervalSince(self.timerDate).rawDuration() } DispatchQueue.main.async { self.timerUpdater = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in update() } RunLoop.main.add(self.timerUpdater!, forMode: .common) } update() } func stopTimer() { timerUpdater?.invalidate() timerUpdater = nil } private var currentExerciseInfoSpacing: CGFloat? func setCurrentExerciseViewHidden(_ hidden: Bool) { if hidden { currentExerciseInfoSpacing = currentExerciseInfo.isHidden ? currentExerciseInfoSpacing : currentExerciseInfo.spacing currentExerciseInfo.spacing = 0 } else { currentExerciseInfo.spacing = currentExerciseInfoSpacing ?? 0 } currentExerciseInfo.isHidden = hidden } func setExerciseName(_ name: String) { exerciseNameLbl.text = name } func setCurrentSetViewHidden(_ hidden: Bool) { currentSetInfoLbl.isHidden = hidden } func setCurrentSetText(_ text: NSAttributedString) { if #available(iOS 13, *) { // In iOS 12 and before there's a bug where the appearance color overrides the color of the attributed string } else { currentSetInfoLbl.textColor = UIColor(named: "Text Color") } currentSetInfoLbl.attributedText = text } func setOtherSetsViewHidden(_ hidden: Bool) { otherSetsLbl.isHidden = hidden } func setOtherSetsText(_ text: NSAttributedString) { if #available(iOS 13, *) { // In iOS 12 and before there's a bug where the appearance color overrides the color of the attributed string } else { otherSetsLbl.textColor = UIColor(named: "Text Color") } otherSetsLbl.attributedText = text } func setSetDoneButtonHidden(_ hidden: Bool) { setDoneBtn.isHidden = hidden } private var restTimerDate: Date! private var restTimerUpdater: Timer? { didSet { DispatchQueue.main.async { oldValue?.invalidate() } } } func startRestTimer(to date: Date) { restTimerDate = date let update = { let time = max(self.restTimerDate.timeIntervalSince(Date()), 0) self.restTimerLbl.text = time.rawDuration(hidingHours: true) if time == 0 { self.stopRestTimer() } } DispatchQueue.main.async { self.restTimerUpdater = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in update() } RunLoop.main.add(self.restTimerUpdater!, forMode: .common) } update() } func stopRestTimer() { restTimerUpdater?.invalidate() restTimerUpdater = nil } private var restInfoSpacing: CGFloat? func setRestViewHidden(_ hidden: Bool) { if hidden { restInfoSpacing = restInfo.isHidden ? restInfoSpacing : restInfo.spacing restInfo.spacing = 0 } else { restInfo.spacing = restInfoSpacing ?? 0 } restInfo.isHidden = hidden } func setRestEndButtonHidden(_ hidden: Bool) { restDoneBtn.isHidden = hidden } private var workoutDoneInfoSpacing: CGFloat? func setWorkoutDoneViewHidden(_ hidden: Bool) { if hidden { workoutDoneInfoSpacing = workoutDoneInfo.isHidden ? workoutDoneInfoSpacing : workoutDoneInfo.spacing workoutDoneInfo.spacing = 0 } else { workoutDoneInfo.spacing = workoutDoneInfoSpacing ?? 0 } workoutDoneInfo.isHidden = hidden } func setWorkoutDoneText(_ text: String) { workoutDoneLbl.text = text } func setWorkoutDoneButtonEnabled(_ enabled: Bool) { workoutDoneBtn.isEnabled = enabled } func disableGlobalActions() { DispatchQueue.main.async { self.cancelBtn.isEnabled = false self.endNowBtn.isEnabled = false } } func setNextUpTextHidden(_ hidden: Bool) { nextUpInfo.isHidden = hidden } func setNextUpText(_ text: NSAttributedString) { if #available(iOS 13, *) { // In iOS 12 and before there's a bug where the appearance color overrides the color of the attributed string } else { nextUpLbl.textColor = UIColor(named: "Text Color") } nextUpLbl.attributedText = text } var skipAskUpdate = false func askUpdateSecondaryInfo(with data: UpdateSecondaryInfoData) { if !skipAskUpdate { self.performSegue(withIdentifier: "updateWeight", sender: data) } skipAskUpdate = false } @IBAction func endRest() { workoutController?.endRest() } @IBAction func endSet() { workoutController?.endSet() } @IBAction func endWorkout() { let alert = UIAlertController(title: GTLocalizedString("WORKOUT_END", comment: "End"), message: GTLocalizedString("WORKOUT_END_TXT", comment: "End?"), preferredStyle: .alert) alert.addAction(UIAlertAction(title: GTLocalizedString("YES", comment: "Yes"), style: .default) { _ in self.workoutController?.endWorkout() }) alert.addAction(UIAlertAction(title: GTLocalizedString("NO", comment: "No"), style: .cancel, handler: nil)) self.present(alert, animated: true) } @IBAction func cancelWorkout() { let alert = UIAlertController(title: GTLocalizedString("WORKOUT_CANCEL", comment: "Cancel"), message: GTLocalizedString("WORKOUT_CANCEL_TXT", comment: "Cancel??"), preferredStyle: .alert) alert.addAction(UIAlertAction(title: GTLocalizedString("YES", comment: "Yes"), style: .destructive) { _ in self.workoutController?.cancelWorkout() }) alert.addAction(UIAlertAction(title: GTLocalizedString("NO", comment: "No"), style: .cancel, handler: nil)) self.present(alert, animated: true) } func workoutHasStarted() { skipAskUpdate = false let isWatch = workoutController?.isMirroring ?? false cancelBtn.isEnabled = true endNowBtn.isEnabled = true navigationItem.leftBarButtonItem = isWatch ? nil : cancelBtn navigationItem.rightBarButtonItem = isWatch ? nil : endNowBtn manageFromWatchLbl.isHidden = !isWatch tipView.isHidden = isWatch noWorkoutLabel.isHidden = true workoutInfo.isHidden = false } @IBAction func workoutDoneButton() { appDelegate.exitWorkoutTracking() } func exitWorkoutTracking() { navigationItem.leftBarButtonItem = nil navigationItem.rightBarButtonItem = nil noWorkoutLabel.isHidden = false workoutInfo.isHidden = true appDelegate.refreshData() } func exitWorkoutTrackingIfAppropriate() { if workoutController?.isCompleted ?? false { appDelegate.exitWorkoutTracking() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let segueID = segue.identifier else { return } let dest = segue.destination PopoverController.preparePresentation(for: dest) dest.popoverPresentationController?.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0) dest.popoverPresentationController?.sourceView = self.view dest.popoverPresentationController?.canOverlapSourceViewRect = true switch segueID { case "updateWeight": guard let updateSec = dest as? UpdateSecondaryInfoViewController, let data = sender as? UpdateSecondaryInfoData else { break } updateSec.secondaryInfoData = data updateSec.popoverPresentationController?.backgroundColor = updateSec.backgroundColor case "askChoices": guard let ask = (dest as? UINavigationController)?.viewControllers.first as? AskChoiceTableViewController, let choices = sender as? [GTChoice] else { break } ask.choices = choices ask.n = 0 default: break } } }
cd2e9611da5704ef2d9416c3cae3e739
26.075676
189
0.72759
false
false
false
false
ainopara/Stage1st-Reader
refs/heads/master
Stage1st/Manager/SentryBreadcrumbsLogger.swift
bsd-3-clause
1
// // SentryBreadcrumbsLogger.swift // Stage1st // // Created by Zheng Li on 2020/2/9. // Copyright © 2020 Renaissance. All rights reserved. // import CocoaLumberjack import Sentry private extension DDLoggerName { static let sentryBreadcrumbs = DDLoggerName("com.ainopara.sentryBreadcrumbsLogger") } class SentryBreadcrumbsLogger: DDAbstractLogger { @objc public static let shared = SentryBreadcrumbsLogger() override var loggerName: DDLoggerName { return .sentryBreadcrumbs } override func log(message logMessage: DDLogMessage) { let message: String? if let formatter = value(forKey: "_logFormatter") as? DDLogFormatter { message = formatter.format(message: logMessage) } else { message = logMessage.message } guard let finalMessage = message else { // Log Formatter decided to drop this message. return } let level: SentryLevel = { switch logMessage.level { case .debug: return .debug case .info: return .info case .warning: return .warning case .error: return .error default: return .debug } }() let rawCategory = (logMessage.tag as? S1LoggerTag)?.category.description ?? "default" let category: String = "log / \(rawCategory)" let breadcrumb = Breadcrumb(level: level, category: category) breadcrumb.message = finalMessage breadcrumb.timestamp = logMessage.timestamp breadcrumb.level = level SentrySDK.addBreadcrumb(crumb: breadcrumb) } }
124a89e2158565c96088e5e9dd346ea4
28.303571
93
0.636807
false
false
false
false
ZeeQL/ZeeQL3
refs/heads/develop
Tests/ZeeQLTests/AdaptorActiveRecordTestCase.swift
apache-2.0
1
// // AdaptorActiveRecordTestCase.swift // ZeeQL3 // // Created by Helge Hess on 18/05/17. // Copyright © 2017 ZeeZide GmbH. All rights reserved. // import Foundation import XCTest @testable import ZeeQL class AdapterActiveRecordTests: XCTestCase { // Is there a better way to share test cases? var adaptor : Adaptor! { XCTAssertNotNil(nil, "override in subclass") return nil } let verbose = true let model = ActiveRecordContactsDBModel.model func testSnapshotting() throws { let db = Database(adaptor: adaptor) let entity : Entity! = model[entity: "Person"] XCTAssert(entity != nil, "did not find person entity ...") guard entity != nil else { return } // tests continue to run let ds = ActiveDataSource<ActiveRecord>(database: db, entity: entity) let dagobert = try ds.findBy(matchingAll: [ "firstname": "Dagobert" ]) XCTAssert(dagobert != nil) XCTAssertFalse(dagobert!.isNew, "fetched object marked as new!") XCTAssertNotNil(dagobert!.snapshot, "missing snapshot") XCTAssertFalse(dagobert!.hasChanges, "marked as having changes") } func testSimpleChange() throws { let db = Database(adaptor: adaptor) let entity : Entity! = model[entity: "Person"] XCTAssert(entity != nil, "did not find person entity ...") guard entity != nil else { return } // tests continue to run let ds = ActiveDataSource<ActiveRecordContactsDBModel.Person>(database: db) let dagobert = try ds.findBy(matchingAll: [ "firstname": "Dagobert" ]) XCTAssert(dagobert != nil) XCTAssertFalse(dagobert!.isNew, "fetched object marked as new!") XCTAssertNotNil(dagobert!.snapshot, "missing snapshot") XCTAssertFalse(dagobert!.hasChanges, "marked as having changes") dagobert!["firstname"] = "Bobby" XCTAssertTrue(dagobert!.hasChanges, "marked as not having changes") let changes = dagobert!.changesFromSnapshot(dagobert!.snapshot!) XCTAssertEqual(changes.count, 1) XCTAssert(changes["firstname"] != nil) XCTAssert((changes["firstname"] as EquatableType).isEqual(to: "Bobby")) } func testInsertAndDelete() throws { let db = Database(adaptor: adaptor) let ds = db.datasource(ActiveRecordContactsDBModel.Person.self) // clear try adaptor.performSQL("DELETE FROM person WHERE firstname = 'Ronald'") // create object let person = ds.createObject() // this attaches to the DB/entity person["firstname"] = "Ronald" person["lastname"] = "McDonald" XCTAssertTrue(person.isNew, "new object not marked as new!") if verbose {print("before save: \(person)") } do { try person.save() } catch { XCTFail("save failed: \(error)") } if verbose { print("after save: \(person)") } XCTAssertFalse(person.isNew, "object still marked as new after save!") XCTAssertNotNil(person.snapshot, "missing snapshot after save") XCTAssertFalse(person.hasChanges, "marked as having changes after save") // TODO: check for primary key ... XCTAssertNotNil(person["id"], "got no primary key!") // refetch object let refetch = try ds.findBy(matchingAll: [ "firstname": "Ronald" ]) XCTAssert(refetch != nil, "did not find new Ronald") if verbose { print("Ronald: \(refetch as Optional)") } guard refetch != nil else { return } // keep tests running XCTAssertFalse(refetch!.isNew, "fetched object marked as new!") XCTAssertNotNil(refetch!.snapshot, "missing snapshot") XCTAssertFalse(refetch!.hasChanges, "marked as having changes") XCTAssert(refetch?["firstname"] != nil) XCTAssert(refetch?["lastname"] != nil) XCTAssert((refetch!["firstname"] as EquatableType).isEqual(to: "Ronald")) XCTAssert((refetch!["lastname"] as EquatableType).isEqual(to: "McDonald")) // delete object do { // try person.delete() // only works when the pkey is assigned .. try refetch?.delete() } catch { XCTFail("delete failed: \(error)") } } static var sharedTests = [ ( "testSnapshotting", testSnapshotting ), ( "testSimpleChange", testSimpleChange ), ( "testInsertAndDelete", testInsertAndDelete ), ] }
47639eba05395fe7a7f4cb7268751245
32.734375
79
0.657249
false
true
false
false
ShezHsky/Countdown
refs/heads/master
CountdownTouchTests/Test Cases/EventDetailViewControllerShould.swift
mit
1
// // EventDetailViewControllerShould.swift // Countdown // // Created by Thomas Sherwood on 27/01/2017. // Copyright © 2017 ShezHsky. All rights reserved. // @testable import CountdownTouch import XCTest class CapturingPresentationBinder: PresentationBinder { // MARK: PresentationBinder private var scenes = [Any]() func bind<Scene>(_ scene: Scene) { scenes.append(scene) } // MARK: Convenience Functions func boundScene<T>(ofType type: T.Type = T.self) -> T? { return scenes.flatMap({ $0 as? T }).first } } class EventDetailViewControllerShould: XCTestCase { // MARK: Properties var detailViewController: EventDetailViewController! var scene: EventDetailScene! // MARK: Overrides override func setUp() { super.setUp() detailViewController = UIStoryboard.main.instantiateViewController(EventDetailViewController.self) _ = detailViewController.view let binder = CapturingPresentationBinder() detailViewController.presentationBinder = binder detailViewController.viewWillAppear(true) scene = binder.boundScene() } // MARK: Tests func testShowThePlaceholderByDefault() { XCTAssertFalse(detailViewController.placeholderView.isHidden) } func testHideThePlaceholderWhenToldTo() { detailViewController.placeholderView.isHidden = false scene.hidePlaceholder() XCTAssertTrue(detailViewController.placeholderView.isHidden) } func testShowThePlaceholderWhenToldTo() { detailViewController.placeholderView.isHidden = true scene.showPlaceholder() XCTAssertFalse(detailViewController.placeholderView.isHidden) } }
d4a3366777ee3bc32a83c52d2710d0a2
24.130435
106
0.704152
false
true
false
false
slimane-swift/Hanger
refs/heads/master
Sources/Request.swift
mit
1
// // Request.swift // Hanger // // Created by Yuki Takei on 5/2/16. // // let CRLF = "\r\n" extension Request { public mutating func serialize() throws -> Data { var requestData = "\(method) \(path ?? "/") HTTP/\(version.major).\(version.minor)\(CRLF)" if headers["Host"].first == nil { var host = uri.host! let port = uri.port ?? 80 if port != 80 { host+=":\(port)" } headers["Host"] = Header(host) } if headers["Accept"].first == nil { headers["Accept"] = Header("*/*") } if headers["User-Agent"].first == nil { headers["User-Agent"] = Header("Hanger HTTP Client") } requestData += headers.filter({ _, v in v.first != nil }).map({ k, v in "\(k): \(v)" }).joined(separator: CRLF) let data = try body.becomeBuffer() requestData += CRLF + CRLF if !data.isEmpty { return requestData.data + data } return requestData.data } }
3445e1bc13226f5059536489fe84fb58
24.568182
119
0.464
false
false
false
false
wwu-pi/md2-framework
refs/heads/master
de.wwu.md2.framework/res/resources/ios/lib/controller/validator/MD2IsNumberValidator.swift
apache-2.0
1
// // MD2IsNumberValidator.swift // md2-ios-library // // Created by Christoph Rieger on 05.08.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // /** Validator to check for a numeric value. */ class MD2IsNumberValidator: MD2Validator { /// Unique identification string. let identifier: MD2String /// Custom message to display. var message: (() -> MD2String)? /// Default message to display. var defaultMessage: MD2String { get { return MD2String("This value must be a valid number!") } } /** Default initializer. :param: identifier The unique validator identifier. :param: message Closure of the custom method to display. */ init(identifier: MD2String, message: (() -> MD2String)?) { self.identifier = identifier self.message = message } /** Validate a value. :param: value The value to check. :return: Validation result */ func isValid(value: MD2Type) -> Bool { if value is MD2NumericType { return true } // Try to parse if MD2Float(MD2String(value.toString())).toString() == value.toString() || MD2Integer(MD2String(value.toString())).toString() == value.toString() { return true } return false } /** Return the message to display on wrong validation. Use custom method if set or else use default message. */ func getMessage() -> MD2String { if let _ = message { return message!() } else { return defaultMessage } } }
25b203998385cae7b7bfea825c5e7e3a
23.43662
87
0.5594
false
false
false
false
ifeherva/HSTracker
refs/heads/master
HSTracker/Importers/Handlers/Hearthstonetopdecks.swift
mit
1
// // Hearthstonetopdecks.swift // HSTracker // // Created by Istvan Fehervari on 29/08/16. // Copyright © 2016 Istvan Fehervari. All rights reserved. // import Foundation import Kanna import RegexUtil struct HearthstoneTopDecks: HttpImporter { var siteName: String { return "Hearthstonetopdecks" } var handleUrl: RegexPattern { return "hearthstonetopdecks\\.com\\/decks" } var preferHttps: Bool { return true } func loadDeck(doc: HTMLDocument, url: String) -> (Deck, [Card])? { guard let nameNode = doc.at_xpath("//h1[contains(@class, 'entry-title')]"), let deckName = nameNode.text else { logger.error("Deck name not found") return nil } logger.verbose("Got deck name \(deckName)") let xpath = "//div[contains(@class, 'deck-import-code')]/input[@type='text']" guard let deckStringNode = doc.at_xpath(xpath), let deckString = deckStringNode["value"]?.trim(), let (playerClass, cardList) = DeckSerializer.deserializeDeckString(deckString: deckString) else { logger.error("Card list not found") return nil } let deck = Deck() deck.name = deckName deck.playerClass = playerClass return (deck, cardList) } }
0cb72ee72b03ae3c5c922165fcaf95ac
26.632653
109
0.604136
false
false
false
false
psoamusic/PourOver
refs/heads/master
PourOver/POUserDocumentsTableViewController.swift
gpl-3.0
1
// // PieceTableViewController.swift // PourOver // // Created by labuser on 11/5/14. // Copyright (c) 2014 labuser. All rights reserved. // import UIKit class POUserDocumentsTableViewController: POPieceTableViewController { //=================================================================================== //MARK: Private Properties //=================================================================================== override var reminderTextViewText: String { get { return "No user documents present\n\nCopy your files into iTunes > \(UIDevice.currentDevice().name) > Apps > PourOver > File Sharing\n\n Supported file types: .pd, .aif, .wav, .txt" } } //=================================================================================== //MARK: Refresh //=================================================================================== override func refreshPieces() { cellDictionaries.removeAll(keepCapacity: false) if let availablePatches = POPdFileLoader.sharedPdFileLoader.availablePatchesInDocuments() { cellDictionaries = availablePatches } //add spacer cells to the top and bottom for correct scrolling behavior cellDictionaries.insert(Dictionary(), atIndex: 0) cellDictionaries.append(Dictionary()) checkForNoDocuments() } }
5b263029856af69753410d975a06ae54
36.236842
193
0.49894
false
false
false
false
digoreis/swift-proposal-analyzer
refs/heads/master
swift-proposal-analyzer.playground/Pages/SE-0155.xcplaygroundpage/Contents.swift
mit
1
/*: # Normalize Enum Case Representation * Proposal: [SE-0155][] * Authors: [Daniel Duan][], [Joe Groff][] * Review Manager: [John McCall][] * Status: **Active review (March 31...April 10, 2017)** * Previous Revision: [1][Revision 1] ## Introduction In Swift 3, associated values of an enum case are represented by a tuple. This implementation causes inconsistencies in case declaration, construction and pattern matching in several places. Enums, therefore, can be made more "regular" when we replace tuple as the representation of associated case values. This proposal aims to define the effect of doing so on various parts of the language. Swift-evolution thread: [Normalize Enum Case Representation (rev. 2)][] ## Motivation When user declares a case for an enum, a function which constructs the corresponding case value is declared. We'll refer to such functions as _case constructors_ in this proposal. ```swift enum Expr { // this case declares the case constructor `Expr.elet(_:_:)` indirect case elet(locals: [(String, Expr)], body: Expr) } // f's signature is f(_: _), type is ([(String, Expr)], Expr) -> Expr let f = Expr.elet // `f` is just a function f([], someExpr) // construct a `Expr.elet` ``` There are many surprising aspects of enum constructors, however: 1. After [SE-0111][], Swift function's fully qualified name consists of its base name and all of its argument labels. User can use the full name of the function at use site. In the example above, `locals` and `body` are currently not part of the case constructors name, therefore the expected syntax is invalid. ```swift func f(x: Int, y: Int) {} f(x: y:)(0, 0) // Okay, this is equivalent to f(x: 0, y: 0) Expr.elet(locals: body:)([], someExpr) // this doesn't work in Swift 3 ``` 2. Case constructors cannot include a default value for each parameter. This is yet another feature available to functions. As previous mentioned, these are symptoms of associated values being a tuple instead of having its own distinct semantics. This problem manifests more in Swift 3's pattern matching: 1. A pattern with a single value would match and result in a tuple: ```swift // this works for reasons most user probably don't expect! if case .elet(let wat) = anExpr { eval(wat.body) } ``` 2. Labels in patterns are not enforced: ```swift // note: there's no label in the first sub-pattern if case .elet(let p, let body: q) = anExpr { // code } ``` These extra rules makes pattern matching difficult to teach and to expand to other types. ## Proposed Solution We'll add first class syntax (which largely resemble the syntax in Swift 3) for declaring associated values with labels. Tuple will no longer be used to represent the aggregate of associated values for an enum case. This means pattern matching for enum cases needs its own syntax as well (as opposed to piggybacking on tuple patterns, which remains in the language for tuples.). ## Detailed Design ### Compound Names For Enum Constructors Associated values' labels should be part of the enum case's constructor name. When constructing an enum value with the case name, label names must either be supplied in the argument list it self, or as part of the full name. ```swift Expr.elet(locals: [], body: anExpr) // Okay, the Swift 3 way. Expr.elet(locals: body:)([], anExpr) // Okay, equivalent to the previous line. Expr.elet(locals: body:)(locals: 0, body: 0) // This would be an error, however. ``` Note that since the labels aren't part of a tuple, they no longer participate in type checking, behaving consistently with functions. ```swift let f = Expr.elet // f has type ([(String, Expr)], Expr) -> Expr f([], anExpr) // Okay! f(locals: [], body: anExpr) // Won't compile. ``` Enum cases should have distinct *full* names. Therefore, shared base name will be allowed: ```swift enum SyntaxTree { case type(variables: [TypeVariable]) case type(instantiated: [Type]) } ``` Using only the base name in pattern matching for the previous example would be ambiguous and result in an compile error. In this case, the full name must be supplied to disambiguate. ```swift case .type // error: ambiguous case .type(variables: let variables) // Okay ``` ### Default Parameter Values For Enum Constructors From a user's point view, declaring an enum case should remain the same as Swift 3 except now it's possible to add `= expression` after the type of an associated value to convey a default value for that field. ```swift enum Animation { case fadeIn(duration: TimeInterval = 0.3) // Okay! } let anim = Animation.fadeIn() // Great! ``` Updated syntax: ```ebnf union-style-enum-case = enum-case-name [enum-case-associated-value-clause]; enum-case-associated-value-clause = "(" ")" | "(" enum-case-associated-value-list ")"; enum-case-associated-value-list = enum-associated-value-element | enum-associated-value-element "," enum-case-associated-value-list; enum-case-associated-value-element = element-name type-annotation [enum-case-element-default-value-clause] | type [enum-case-element-default-value-clause]; element-name = identifier; enum-case-element-default-value-clause = "=" expression; ``` ### Alternative Payload-less Case Declaration In Swift 3, the following syntax is valid: ```swift enum Tree { case leaf() // the type of this constructor is confusing! } ``` `Tree.leaf` has a very unexpected type to most Swift users: `(()) -> Tree` We propose this syntax become illegal. User must explicitly declare associated value of type `Void` if needed: ```swift enum Tree { case leaf(Void) } ``` ### Pattern Consistency *(The following enum will be used throughout code snippets in this section).* ```swift indirect enum Expr { case variable(name: String) case lambda(parameters: [String], body: Expr) } ``` Compared to patterns in Swift 3, matching against enum cases will follow stricter rules. This is a consequence of no longer relying on tuple patterns. When an associated value has a label, the sub-pattern must include the label exactly as declared. There are two variants that should look familiar to Swift 3 users. Variant 1 allows user to bind the associated value to arbitrary name in the pattern by requiring the label: ```swift case .variable(name: let x) // okay case .variable(x: let x) // compile error; there's no label `x` case .lambda(parameters: let params, body: let body) // Okay case .lambda(params: let params, body: let body) // error: 1st label mismatches ``` User may choose not to use binding names that differ from labels. In this variant, the corresponding value will bind to the label, resulting in this shorter form: ```swift case .variable(let name) // okay, because the name is the same as the label case .lambda(let parameters, let body) // this is okay too, same reason. case .variable(let x) // compiler error. label must appear one way or another. case .lambda(let params, let body) // compiler error, same reason as above. ``` Only one of these variants may appear in a single pattern. Swift compiler will raise a compile error for mixed usage. ```swift case .lambda(parameters: let params, let body) // error, can not mix the two. ``` Some patterns will no longer match enum cases. For example, all associated values can bind as a tuple in Swift 3, this will no longer work after this proposal: ```swift // deprecated: matching all associated values as a tuple if case let .lambda(f) = anLambdaExpr { evaluateLambda(parameters: f.parameters, body: f.body) } ``` ## Source compatibility Despite a few additions, case declaration remain mostly source-compatible with Swift 3, with the exception of the change detailed in "Alternative Payload-less Case Declaration". Syntax for case constructor at use site remain source-compatible. A large portion of pattern matching syntax for enum cases with associated values remain unchanged. But patterns for matching all values as a tuple, patterns that elide the label and binds to names that differ from the labels, patterns that include labels for some sub-patterns but the rest of them are deprecated by this proposal. Therefore this is a source breaking change. ## Effect on ABI stability and resilience After this proposal, enum cases may have compound names. This means the standard library will expose different symbols for enum constructors. The name mangling rules should also change accordingly. ## Alternative Considered Between case declaration and pattern matching, there exist many reasonable combinations of improvement. On one hand, we can optimize for consistency, simplicity and teachability by bringing in as much similarity between enum and other part of the language as possible. Many decisions in the first revision were made in favor if doing so. Through the feedbacks from swift-evolution, we found that some of the changes impedes the ergonomics of these features too much . In this section, we describe some of the alternatives that were raised and rejected in hope to strike a balance between the two end of the goals. We discussed allowing user to declare a *parameter name* ("internal names") for each associated value. Such names may be used in various rules in pattern matching. Some feedback suggested they maybe used as property names when we make enum case subtypes of the enum and resembles a struct. This feature is not included in this proposal because parameter names are not very useful *today*. Using them in patterns actually don't improve consistency as users don't use them outside normal function definitions at all. If enum case gains a function body in a future proposal, it'd be better to define the semantics of parameter names then, as opposed to locking it down now. To maintain ergonomics/source compatibility, we could allow user to choose arbitrary bindings for each associated value. The problem is it makes the pattern deviate a lot from declaration and makes it hard for beginners to understand. This also decrease readability for seasoned users. Along the same line, a pattern that gets dropped is binding all associated values as a labeled tuple, which tuple pattern allowed in Swift 3. As T.J. Usiyan [pointed out][TJs comment], implementation of the equality protocol would be simplified due to tuple's conformance to `Equatable`. This feature may still be introduced with alternative syntax (perhaps related to splats) later without source-breakage. And the need to implement `Equatable` may also disappear with auto-deriving for `Equatable` conformance. The previous revision of this proposal mandated that the labeled form of sub-pattern (`case .elet(locals: let x, body: let y)`) be the only acceptable pattern. Turns out the community considers this to be too verbose in some cases. A drafted version of this proposal considered allowing "overloaded" declaration of enum cases (same full-name, but with associated values with different types). We ultimately decided that this feature is out of the scope of this proposal. [SE-0155]: 0155-normalize-enum-case-representation.md [SE-0111]: 0111-remove-arg-label-type-significance.md [Daniel Duan]: https://github.com/dduan [Joe Groff]: https://github.com/jckarter [John McCall]: https://github.com/rjmccall [TJs comment]: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170116/030614.html [Revision 1]: https://github.com/apple/swift-evolution/blob/43ca098355762014f53e1b54e02d2f6a01253385/proposals/0155-normalize-enum-case-representation.md [Normalize Enum Case Representation (rev. 2)]: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170306/033626.html ---------- [Previous](@previous) | [Next](@next) */
de1f667d283e02f9ec2d37bf153773f0
37.223642
153
0.740973
false
false
false
false
Aishwarya-Ramakrishnan/sparkios
refs/heads/master
Source/Phone/Call/CallInfoSequence.swift
mit
1
// Copyright 2016 Cisco Systems Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation class CallInfoSequence { enum OverwriteResult { // the value passed in is newer than the current CallInfo case `true` // the value passed in is older than or equal to the current CallInfo case `false` // there are inconsistencies between the two versions - they both contain overlapping unique values case deSync } enum CompareResult { case greaterThan case lessThan case equal case deSync } // calculate "only in a's" list and "only in b's" list static func populateSets(_ a: Sequence, _ b: Sequence) -> ([UInt64], [UInt64]) { var aOnly = [UInt64]() var bOnly = [UInt64]() var aArray = a.getEntries() var bArray = b.getEntries() var atEndOfA = false var atEndOfB = false var indexOfA = 0 var indexOfB = 0 while (indexOfA < aArray.count && indexOfB < bArray.count) { var aVal = aArray[indexOfA] var bVal = bArray[indexOfB] indexOfA += 1 indexOfB += 1 while (aVal != bVal && !atEndOfA && !atEndOfB) { while (aVal > bVal) { if !a.inRange(bVal) { bOnly.append(bVal) } if indexOfB < bArray.count { bVal = bArray[indexOfB] indexOfB += 1 } else { atEndOfB = true break } } while (bVal > aVal) { if !b.inRange(aVal) { aOnly.append(aVal) } if indexOfA < aArray.count { aVal = aArray[indexOfA] indexOfA += 1 } else { atEndOfA = true break } } } if (atEndOfA && !atEndOfB) { if (!a.inRange(bVal)) { bOnly.append(bVal) } } if ( !atEndOfA && atEndOfB) { if (!b.inRange(aVal)) { aOnly.append(aVal) } } } while (indexOfA < aArray.count) { let aVal = aArray[indexOfA] indexOfA += 1 if (!b.inRange(aVal)) { aOnly.append(aVal) } } while (indexOfB < bArray.count) { let bVal = bArray[indexOfB] indexOfB += 1 if (!a.inRange(bVal)) { bOnly.append(bVal) } } return (aOnly, bOnly) } static func compare(_ a: Sequence, _ b: Sequence) -> CompareResult { var aOnly = [UInt64]() var bOnly = [UInt64]() // if all of a's values are less than b's, b is newer if a.getCompareLastValue() < b.getCompareFirstValue() { return CompareResult.lessThan } // if all of a's values are greater than b's, a is newer if a.getCompareFirstValue() > b.getCompareLastValue() { return CompareResult.greaterThan } // calculate "only in a's" list and "only in b's" list (aOnly, bOnly) = populateSets(a, b) if aOnly.isEmpty && bOnly.isEmpty { // both sets are completely empty, use range to figure out order if a.getRangeEnd() > b.getRangeEnd() { return CompareResult.greaterThan } else if a.getRangeEnd() < b.getRangeEnd() { return CompareResult.lessThan } else if a.getRangeStart() < b.getRangeStart() { return CompareResult.greaterThan } else if a.getRangeStart() > b.getRangeStart() { return CompareResult.lessThan } else { return CompareResult.equal } } // If b has nothing unique and a does, then a is newer if !aOnly.isEmpty && bOnly.isEmpty { return CompareResult.greaterThan } // if I have nothing unique but b does, then b is newer if !bOnly.isEmpty && aOnly.isEmpty { return CompareResult.lessThan } // both have unique entries... // if a unique value in one list is within the min and max value in the others list then we are desync'd for i in aOnly { if i > b.getCompareFirstValue() && i < b.getCompareLastValue() { return CompareResult.deSync } } for i in bOnly { if i > a.getCompareFirstValue() && i < a.getCompareLastValue() { return CompareResult.deSync } } // aOnly and bOnly are 2 non-overlapping sets. compare first item in both if aOnly[0] > bOnly[0] { return CompareResult.greaterThan } else { return CompareResult.lessThan } } static func overwrite(oldValue: Sequence, newValue: Sequence) -> OverwriteResult { // special case the empty sequence. If you are currently empty then say update no matter what if oldValue.isEmpty() || newValue.isEmpty() { return OverwriteResult.true } else { let compareResult = compare(oldValue, newValue) switch (compareResult) { case CompareResult.greaterThan: return OverwriteResult.false case CompareResult.lessThan: return OverwriteResult.true case CompareResult.equal: return OverwriteResult.false case CompareResult.deSync: return OverwriteResult.deSync } } } }
2f7b685d4187daac64f5c7e275df398d
34.147059
112
0.524686
false
false
false
false
AbidHussainCom/HackingWithSwift
refs/heads/master
project13/Project13/ViewController.swift
unlicense
20
// // ViewController.swift // Project13 // // Created by Hudzilla on 22/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var intensity: UISlider! var currentImage: UIImage! var context: CIContext! var currentFilter: CIFilter! override func viewDidLoad() { super.viewDidLoad() // Yet Another Core Image Filters Program title = "YACIFP" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "importPicture") context = CIContext(options: nil) currentFilter = CIFilter(name: "CISepiaTone") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func importPicture() { let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self presentViewController(picker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject: AnyObject]) { var newImage: UIImage if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage { newImage = possibleImage } else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { newImage = possibleImage } else { return } dismissViewControllerAnimated(true, completion: nil) currentImage = newImage let beginImage = CIImage(image: currentImage) currentFilter.setValue(beginImage, forKey: kCIInputImageKey) applyProcessing() } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func applyProcessing() { let inputKeys = currentFilter.inputKeys() as! [NSString] if contains(inputKeys, kCIInputIntensityKey) { currentFilter.setValue(intensity.value, forKey: kCIInputIntensityKey) } if contains(inputKeys, kCIInputRadiusKey) { currentFilter.setValue(intensity.value * 200, forKey: kCIInputRadiusKey) } if contains(inputKeys, kCIInputScaleKey) { currentFilter.setValue(intensity.value * 10, forKey: kCIInputScaleKey) } if contains(inputKeys, kCIInputCenterKey) { currentFilter.setValue(CIVector(x: currentImage.size.width / 2, y: currentImage.size.height / 2), forKey: kCIInputCenterKey) } let cgimg = context.createCGImage(currentFilter.outputImage, fromRect: currentFilter.outputImage.extent()) let processedImage = UIImage(CGImage: cgimg) imageView.image = processedImage } @IBAction func intensityChanged(sender: AnyObject) { applyProcessing() } @IBAction func changeFilter(sender: AnyObject) { let ac = UIAlertController(title: "Choose filter", message: nil, preferredStyle: .ActionSheet) ac.addAction(UIAlertAction(title: "CIBumpDistortion", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CIGaussianBlur", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CIPixellate", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CISepiaTone", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CITwirlDistortion", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CIUnsharpMask", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CIVignette", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(ac, animated: true, completion: nil) } @IBAction func save(sender: AnyObject) { UIImageWriteToSavedPhotosAlbum(imageView.image, self, "image:didFinishSavingWithError:contextInfo:", nil) } func setFilter(action: UIAlertAction!) { currentFilter = CIFilter(name: action.title) let beginImage = CIImage(image: currentImage) currentFilter.setValue(beginImage, forKey: kCIInputImageKey) applyProcessing() } func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) { if error == nil { let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } else { let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } } }
6f521797998c45342211d4d2cd5fbdc1
37.211382
172
0.765957
false
false
false
false
wilfreddekok/Antidote
refs/heads/master
Antidote/OCTSubmanagerObjectsExtension.swift
mpl-2.0
1
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import Foundation extension OCTSubmanagerObjects { func friends(predicate predicate: NSPredicate? = nil) -> Results<OCTFriend> { let rlmResults = objectsForType(.Friend, predicate: predicate) return Results(results: rlmResults) } func friendRequests(predicate predicate: NSPredicate? = nil) -> Results<OCTFriendRequest> { let rlmResults = objectsForType(.FriendRequest, predicate: predicate) return Results(results: rlmResults) } func chats(predicate predicate: NSPredicate? = nil) -> Results<OCTChat> { let rlmResults = objectsForType(.Chat, predicate: predicate) return Results(results: rlmResults) } func calls(predicate predicate: NSPredicate? = nil) -> Results<OCTCall> { let rlmResults = objectsForType(.Call, predicate: predicate) return Results(results: rlmResults) } func messages(predicate predicate: NSPredicate? = nil) -> Results<OCTMessageAbstract> { let rlmResults = objectsForType(.MessageAbstract, predicate: predicate) return Results(results: rlmResults) } func getProfileSettings() -> ProfileSettings { guard let data = self.genericSettingsData else { return ProfileSettings() } let unarchiver = NSKeyedUnarchiver(forReadingWithData: data) let settings = ProfileSettings(coder: unarchiver) unarchiver.finishDecoding() return settings } func saveProfileSettings(settings: ProfileSettings) { let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWithMutableData: data) settings.encodeWithCoder(archiver) archiver.finishEncoding() self.genericSettingsData = data.copy() as! NSData } }
f131252cd082a29622ef3b5070e534c2
35.388889
95
0.691603
false
false
false
false
ByteriX/BxInputController
refs/heads/master
BxInputController/Sources/Common/View/Selector/BxInputSelectorRowBinder.swift
mit
1
/** * @file BxInputSelectorRowBinder.swift * @namespace BxInputController * * @details Binder for a selector row * @date 06.03.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit #warning("change BxInputBaseFieldRowBinder to BxInputBaseRowBinder") /// Binder for a selector row open class BxInputSelectorRowBinder<Row: BxInputSelectorRow, Cell: BxInputSelectorCell>: BxInputBaseFieldRowBinder<Row, Cell> { /// call when user selected this cell override open func didSelected() { super.didSelected() row.isOpened = !row.isOpened refreshOpened(animated: true) if row.isOpened { //owner?.beginUpdates() init crash owner?.addRows(row.children, after: row) if let owner = owner, owner.settings.isAutodissmissSelector { owner.dissmissAllRows(exclude: row) } //owner?.endUpdates() if row.children.count > 1 { owner?.scrollRow(row, at: .top, animated: true) } else if let firstItem = row.children.first { owner?.selectRow(firstItem, at: .middle, animated: true) } else { owner?.scrollRow(row, at: .middle, animated: true) } owner?.activeRow = row } else { owner?.deleteRows(row.children) } } /// update cell from model data override open func update() { super.update() // cell?.arrowImage.image = BxInputUtils.getImage(resourceId: "bx_arrow_to_bottom") // refreshOpened(animated: false) } /// event of change isEnabled override open func didSetEnabled(_ value: Bool) { super.didSetEnabled(value) guard let cell = cell else { return } // UI part if needChangeDisabledCell { if let changeViewEnableHandler = owner?.settings.changeViewEnableHandler { changeViewEnableHandler(cell.arrowImage, isEnabled) } else { cell.arrowImage.alpha = value ? 1 : alphaForDisabledView } } else { cell.arrowImage.isHidden = !value } } /// visual updating of state from opened/closed open func refreshOpened(animated: Bool) { if animated { UIView.beginAnimations(nil, context: nil) } if row.isOpened { cell?.arrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) } else { cell?.arrowImage.transform = CGAffineTransform.identity } checkValue() if animated { UIView.commitAnimations() } } /// visual updating of value && separator that depends on type of the row open func checkValue() { // all string changing of value if let row = row as? BxInputString{ cell?.valueTextField.text = row.stringValue } else { cell?.valueTextField.text = "" } } /// If selector is closed just will open public func toOpen() { if row.isOpened == false { didSelected() } } /// If selector is opened just will close public func toClose() { if row.isOpened == true { didSelected() } } }
c8f57b422b7233bf390c0f1bc4c7dd08
28.710744
125
0.574965
false
false
false
false
marcusellison/Yelply
refs/heads/master
Yelp/Filters.swift
mit
1
// // Filters.swift // Yelp // // Created by Marcus J. Ellison on 5/16/15. // Copyright (c) 2015 Marcus J. Ellison. All rights reserved. // import UIKit class Category: NSObject { let title = "Category" let categories = { return [ ["name" : "African", "code": "african"], ["name" : "Brazilian", "code": "brazilian"], ["name" : "Burgers", "code": "burgers"], ["name" : "American, New", "code": "newamerican"] ] } } class Sort: NSObject { let title = "Sort" let categories = ["match", "distance", "rating"] } class Radius: NSObject { let title = "Radius" var radius = 0 } class Deals: NSObject { let title = "Deals" var on = false }
6172c7958eb2f3f5f971ef23579664b2
18.1
62
0.527487
false
false
false
false
IngmarStein/swift
refs/heads/master
test/SILGen/closure_script_global_escape.swift
apache-2.0
7
// RUN: %target-swift-frontend -module-name foo -emit-silgen %s | %FileCheck %s // RUN: %target-swift-frontend -module-name foo -emit-sil -verify %s // CHECK-LABEL: sil @main // CHECK: [[GLOBAL:%.*]] = global_addr @_Tv3foo4flagSb // CHECK: [[MARK:%.*]] = mark_uninitialized [var] [[GLOBAL]] var flag: Bool // expected-note* {{defined here}} // CHECK: mark_function_escape [[MARK]] func useFlag() { // expected-error{{'flag' used by function definition before being initialized}} _ = flag } // CHECK: [[CLOSURE:%.*]] = function_ref @_TF3fooU_FT_T_ // CHECK: mark_function_escape [[MARK]] // CHECK: thin_to_thick_function [[CLOSURE]] _ = { _ = flag } // expected-error{{'flag' captured by a closure before being initialized}} // CHECK: mark_function_escape [[MARK]] // CHECK: [[CLOSURE:%.*]] = function_ref @_TF3fooU0_FT_T_ // CHECK: apply [[CLOSURE]] _ = { _ = flag }() // expected-error{{'flag' captured by a closure before being initialized}} flag = true // CHECK: mark_function_escape [[MARK]] func useFlag2() { _ = flag } // CHECK: [[CLOSURE:%.*]] = function_ref @_TF3fooU1_FT_T_ // CHECK: mark_function_escape [[MARK]] // CHECK: thin_to_thick_function [[CLOSURE]] _ = { _ = flag } // CHECK: mark_function_escape [[MARK]] // CHECK: [[CLOSURE:%.*]] = function_ref @_TF3fooU2_FT_T_ // CHECK: apply [[CLOSURE]] _ = { _ = flag }()
324aace6f3462ba325998f00d504f15b
32.575
97
0.632911
false
false
false
false
brettg/Signal-iOS
refs/heads/master
Signal/src/ViewControllers/InviteFlow.swift
gpl-3.0
2
// Created by Michael Kirk on 11/18/16. // Copyright © 2016 Open Whisper Systems. All rights reserved. import Foundation import Social import ContactsUI import MessageUI @objc(OWSInviteFlow) class InviteFlow: NSObject, MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate, ContactsPickerDelegate { enum Channel { case message, mail, twitter } let TAG = "[ShareActions]" let installUrl = "https://signal.org/install/" let homepageUrl = "https://whispersystems.org" let actionSheetController: UIAlertController let presentingViewController: UIViewController let contactsManager: OWSContactsManager var channel: Channel? required init(presentingViewController: UIViewController, contactsManager: OWSContactsManager) { self.presentingViewController = presentingViewController self.contactsManager = contactsManager actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) super.init() actionSheetController.addAction(dismissAction()) if #available(iOS 9.0, *) { if let messageAction = messageAction() { actionSheetController.addAction(messageAction) } if let mailAction = mailAction() { actionSheetController.addAction(mailAction) } } if let tweetAction = tweetAction() { actionSheetController.addAction(tweetAction) } } // MARK: Twitter func canTweet() -> Bool { return SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter) } func tweetAction() -> UIAlertAction? { guard canTweet() else { Logger.info("\(TAG) Twitter not supported.") return nil } guard let twitterViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter) else { Logger.error("\(TAG) unable to build twitter controller.") return nil } let tweetString = NSLocalizedString("SETTINGS_INVITE_TWITTER_TEXT", comment:"content of tweet when inviting via twitter") twitterViewController.setInitialText(tweetString) let tweetUrl = URL(string: installUrl) twitterViewController.add(tweetUrl) twitterViewController.add(#imageLiteral(resourceName: "twitter_sharing_image")) let tweetTitle = NSLocalizedString("SHARE_ACTION_TWEET", comment:"action sheet item") return UIAlertAction(title: tweetTitle, style: .default) { action in Logger.debug("\(self.TAG) Chose tweet") self.presentingViewController.present(twitterViewController, animated: true, completion: nil) } } func dismissAction() -> UIAlertAction { return UIAlertAction(title: NSLocalizedString("DISMISS_BUTTON_TEXT", comment:""), style: .cancel) } // MARK: ContactsPickerDelegate @available(iOS 9.0, *) func contactsPicker(_: ContactsPicker, didSelectMultipleContacts contacts: [Contact]) { Logger.debug("\(TAG) didSelectContacts:\(contacts)") guard let inviteChannel = channel else { Logger.error("\(TAG) unexpected nil channel after returning from contact picker.") return } switch inviteChannel { case .message: let phoneNumbers: [String] = contacts.map { $0.userTextPhoneNumbers.first }.filter { $0 != nil }.map { $0! } sendSMSTo(phoneNumbers: phoneNumbers) case .mail: let recipients: [String] = contacts.map { $0.emails.first }.filter { $0 != nil }.map { $0! } sendMailTo(emails: recipients) default: Logger.error("\(TAG) unexpected channel after returning from contact picker: \(inviteChannel)") } } @available(iOS 9.0, *) func contactsPicker(_: ContactsPicker, shouldSelectContact contact: Contact) -> Bool { guard let inviteChannel = channel else { Logger.error("\(TAG) unexpected nil channel in contact picker.") return true } switch inviteChannel { case .message: return contact.userTextPhoneNumbers.count > 0 case .mail: return contact.emails.count > 0 default: Logger.error("\(TAG) unexpected channel after returning from contact picker: \(inviteChannel)") } return true } // MARK: SMS @available(iOS 9.0, *) func messageAction() -> UIAlertAction? { guard MFMessageComposeViewController.canSendText() else { Logger.info("\(TAG) Device cannot send text") return nil } let messageTitle = NSLocalizedString("SHARE_ACTION_MESSAGE", comment: "action sheet item to open native messages app") return UIAlertAction(title: messageTitle, style: .default) { action in Logger.debug("\(self.TAG) Chose message.") self.channel = .message let picker = ContactsPicker(delegate: self, multiSelection: true, subtitleCellType: .phoneNumber) let navigationController = UINavigationController(rootViewController: picker) self.presentingViewController.present(navigationController, animated: true) } } func sendSMSTo(phoneNumbers: [String]) { self.presentingViewController.dismiss(animated: true) { if #available(iOS 10.0, *) { // iOS10 message compose view doesn't respect some system appearence attributes. // Specifically, the title is white, but the navbar is gray. // So, we have to set system appearence before init'ing the message compose view controller in order // to make its colors legible. // Then we have to be sure to set it back in the ComposeViewControllerDelegate callback. UIUtil.applyDefaultSystemAppearence() } let messageComposeViewController = MFMessageComposeViewController() messageComposeViewController.messageComposeDelegate = self messageComposeViewController.recipients = phoneNumbers let inviteText = NSLocalizedString("SMS_INVITE_BODY", comment:"body sent to contacts when inviting to Install Signal") messageComposeViewController.body = inviteText.appending(" \(self.installUrl)") self.presentingViewController.navigationController?.present(messageComposeViewController, animated:true) } } // MARK: MessageComposeViewControllerDelegate func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { // Revert system styling applied to make messaging app legible on iOS10. UIUtil.applySignalAppearence() self.presentingViewController.dismiss(animated: true, completion: nil) switch result { case .failed: let warning = UIAlertController(title: nil, message: NSLocalizedString("SEND_INVITE_FAILURE", comment:"Alert body after invite failed"), preferredStyle: .alert) warning.addAction(UIAlertAction(title: NSLocalizedString("DISMISS_BUTTON_TEXT", comment:""), style: .default, handler: nil)) self.presentingViewController.present(warning, animated: true, completion: nil) case .sent: Logger.debug("\(self.TAG) user successfully invited their friends via SMS.") case .cancelled: Logger.debug("\(self.TAG) user cancelled message invite") } } // MARK: Mail @available(iOS 9.0, *) func mailAction() -> UIAlertAction? { guard MFMailComposeViewController.canSendMail() else { Logger.info("\(TAG) Device cannot send mail") return nil } let mailActionTitle = NSLocalizedString("SHARE_ACTION_MAIL", comment: "action sheet item to open native mail app") return UIAlertAction(title: mailActionTitle, style: .default) { action in Logger.debug("\(self.TAG) Chose mail.") self.channel = .mail let picker = ContactsPicker(delegate: self, multiSelection: true, subtitleCellType: .email) let navigationController = UINavigationController(rootViewController: picker) self.presentingViewController.present(navigationController, animated: true) } } @available(iOS 9.0, *) func sendMailTo(emails recipientEmails: [String]) { let mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self mailComposeViewController.setBccRecipients(recipientEmails) let subject = NSLocalizedString("EMAIL_INVITE_SUBJECT", comment:"subject of email sent to contacts when inviting to install Signal") let bodyFormat = NSLocalizedString("EMAIL_INVITE_BODY", comment:"body of email sent to contacts when inviting to install Signal. Embeds {{link to install Signal}} and {{link to WhisperSystems home page}}") let body = String.init(format: bodyFormat, installUrl, homepageUrl) mailComposeViewController.setSubject(subject) mailComposeViewController.setMessageBody(body, isHTML: false) self.presentingViewController.dismiss(animated: true) { self.presentingViewController.navigationController?.present(mailComposeViewController, animated:true) { UIUtil.applySignalAppearence(); } } } // MARK: MailComposeViewControllerDelegate func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { self.presentingViewController.dismiss(animated: true, completion: nil) switch result { case .failed: let warning = UIAlertController(title: nil, message: NSLocalizedString("SEND_INVITE_FAILURE", comment:"Alert body after invite failed"), preferredStyle: .alert) warning.addAction(UIAlertAction(title: NSLocalizedString("DISMISS_BUTTON_TEXT", comment:""), style: .default, handler: nil)) self.presentingViewController.present(warning, animated: true, completion: nil) case .sent: Logger.debug("\(self.TAG) user successfully invited their friends via mail.") case .saved: Logger.debug("\(self.TAG) user saved mail invite.") case .cancelled: Logger.debug("\(self.TAG) user cancelled mail invite.") } } }
d6db729fac4b909a76142e847032b5c3
42.307377
213
0.669632
false
false
false
false
rain2540/RGNetwork
refs/heads/master
RGNetwork/RGNetwork/RGDataRequest.swift
mpl-2.0
1
// // RGDataRequest.swift // RGNetwork // // Created by Rain on 2020/3/6. // Copyright © 2020 Smartech. All rights reserved. // import Foundation import Alamofire class RGDataRequest { public var tag: Int = 0 public private(set) var config: RGDataRequestConfig // MARK: - Lifecycle /// create network request /// - Parameters: /// - urlString: string of URL path /// - method: HTTP method /// - parameters: request parameters /// - encoding: parameter encoding /// - headers: HTTP headers /// - timeoutInterval: 超时时长 init( urlString: String, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, timeoutInterval: TimeInterval = 30.0, isShowLog: Bool = true ) { self.config = RGDataRequestConfig( urlString: urlString, method: method, parameters: parameters, encoding: encoding, headers: headers, timeoutInterval: timeoutInterval, isShowLog: isShowLog ) } } // MARK: - Public extension RGDataRequest { /// 执行请求 /// - Parameters: /// - queue: 执行请求的队列 /// - showIndicator: 是否显示 Indicator /// - responseType: 返回数据格式类型 /// - success: 请求成功的 Task /// - failure: 请求失败的 Task public func task( queue: DispatchQueue = DispatchQueue.global(), showIndicator: Bool = false, responseType: ResponseType = .json, success: @escaping SuccessTask, failure: @escaping FailureTask ) { RGNetwork.request( config: config, queue: queue, showIndicator: showIndicator, responseType: responseType, success: success, failure: failure ) } }
7189660b4c305f5a91d257b01d77dd7c
22.925
58
0.575235
false
true
false
false
luizlopezm/ios-Luis-Trucking
refs/heads/master
Pods/Charts/Charts/Classes/Data/Implementations/Standard/PieChartDataSet.swift
mit
1
// // PieChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 24/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics public class PieChartDataSet: ChartDataSet, IPieChartDataSet { private func initialize() { self.valueTextColor = NSUIColor.whiteColor() self.valueFont = NSUIFont.systemFontOfSize(17.0) } public required init() { super.init() initialize() } public override init(yVals: [ChartDataEntry]?, label: String?) { super.init(yVals: yVals, label: label) initialize() } // MARK: - Styling functions and accessors private var _sliceSpace = CGFloat(0.0) /// the space in pixels between the pie-slices /// **default**: 0 /// **maximum**: 20 public var sliceSpace: CGFloat { get { return _sliceSpace } set { var space = newValue if (space > 20.0) { space = 20.0 } if (space < 0.0) { space = 0.0 } _sliceSpace = space } } /// indicates the selection distance of a pie slice public var selectionShift = CGFloat(18.0) // MARK: - NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! PieChartDataSet copy._sliceSpace = _sliceSpace copy.selectionShift = selectionShift return copy } }
3557721acf035d5ed8285fa4cf454153
21.294872
66
0.558688
false
false
false
false
grimbolt/BaseSwiftProject
refs/heads/master
BaseSwiftProject/Sources/Types/ConnectionManager.swift
mit
1
// // ConnectionManager.swift // BaseSwiftProject // // Created by Grimbolt on 07.01.2017. // // import Foundation import Alamofire import AlamofireObjectMapper import ObjectMapper public class ConnectionManager { enum PareseError: Error { case invalid } static let lock = NSLock() static var _sessionManager: SessionManager? public static var sessionManager: SessionManager { get { if let sessionManager = ConnectionManager._sessionManager { return sessionManager; } else { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 20 configuration.timeoutIntervalForResource = 20 configuration.urlCache = nil ConnectionManager._sessionManager = SessionManager(configuration: configuration) return ConnectionManager._sessionManager! } } set { ConnectionManager._sessionManager = newValue } } public static func request<T: BaseMappable> ( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, preloaderType: PreloaderType = .small, withSaveContext: Bool = true, beforeMapping: ((DefaultDataResponse) -> Void)? = nil, completionHandler: ((DataResponse<T>) -> Void)? = nil ) { let request = sessionManager.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers) let uuid = UUID().uuidString showPreloader(uuid, type: preloaderType) request .response { response in beforeMapping?(response) } .responseObject { (response: DataResponse<T>) in commonResponse(preloader: uuid, preloaderType: preloaderType, response: response, completionHandler: completionHandler, withSaveContext: withSaveContext) } .validate { request, response, data in return validate(request: request, response: response, data: data) } } public static func requestArray<T: BaseMappable> ( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, preloaderType: PreloaderType = .small, withSaveContext: Bool = true, beforeMapping: ((DefaultDataResponse) -> Void)? = nil, completionHandler: ((DataResponse<[T]>) -> Void)? = nil ) { let request = sessionManager.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers) let uuid = UUID().uuidString showPreloader(uuid, type: preloaderType) request .response { response in beforeMapping?(response) } .responseArray { (response: DataResponse<[T]>) in commonResponse(preloader: uuid, preloaderType: preloaderType, response: response, completionHandler: completionHandler, withSaveContext: withSaveContext) } .validate { request, response, data in return validate(request: request, response: response, data: data) } } public static func simpleRequestWithHttpBody<T: BaseMappable> ( url:URL, httpBody:Data?, method: HTTPMethod = .get, headers: HTTPHeaders? = nil, preloaderType: PreloaderType = .small, withSaveContext: Bool = true, beforeMapping: ((DefaultDataResponse) -> Void)? = nil, completionHandler: @escaping (DataResponse<[T]>) -> Void ) { var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15) urlRequest.httpBody = httpBody urlRequest.httpMethod = method.rawValue if let _ = headers { for header in headers! { urlRequest.setValue(header.value, forHTTPHeaderField: header.key) } } urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") let request = sessionManager.request(urlRequest) let uuid = UUID().uuidString showPreloader(uuid, type: preloaderType) request .response { response in beforeMapping?(response) } .responseArray { (response: DataResponse<[T]>) in commonResponse(preloader: uuid, preloaderType: preloaderType, response: response, completionHandler: completionHandler, withSaveContext: withSaveContext) } .validate { (requst, response, data) -> Request.ValidationResult in return validate(request: requst, response: response, data: data) } } public static func simpleRequestWithHttpBody<T: BaseMappable> ( url:URL, httpBody:Data?, method: HTTPMethod = .get, headers: HTTPHeaders? = nil, preloaderType: PreloaderType = .small, withSaveContext: Bool = true, beforeMapping: ((DefaultDataResponse) -> Void)? = nil, completionHandler: @escaping (DataResponse<T>) -> Void ) { var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15) urlRequest.httpBody = httpBody urlRequest.httpMethod = method.rawValue if let _ = headers { for header in headers! { urlRequest.setValue(header.value, forHTTPHeaderField: header.key) } } urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") let request = sessionManager.request(urlRequest) let uuid = UUID().uuidString showPreloader(uuid, type: preloaderType) request .response { response in beforeMapping?(response) } .responseObject { (response: DataResponse<T>) in commonResponse(preloader: uuid, preloaderType: preloaderType, response: response, completionHandler: completionHandler, withSaveContext: withSaveContext) } .validate { (requst, response, data) -> Request.ValidationResult in return validate(request: requst, response: response, data: data) } } public static func cancelAllTasks(whiteList: [String] = []) { sessionManager.session.getTasksWithCompletionHandler { (sessionDataTask, sessionUploadTask, sessionDownloadTask) in func forEach(_ task: URLSessionTask) { if let url = task.currentRequest?.url?.absoluteString { var onWhiteList = false; whiteList.forEach({ if url.hasPrefix($0) { onWhiteList = true } }) if !onWhiteList { task.cancel() } } else { task.cancel() } } sessionDataTask.forEach({ forEach($0) }) sessionUploadTask.forEach({ forEach($0) }) sessionDownloadTask.forEach({ forEach($0) }) } } private static func commonResponse<T>( preloader uuid: String, preloaderType: PreloaderType, response: DataResponse<T>, completionHandler: ((DataResponse<T>) -> Void)?, withSaveContext: Bool ) { hidePreloader(uuid, type: preloaderType) switch response.result { case .failure(let error): print("error \(error)") if (error as NSError).code == NSURLErrorCancelled { // nothing } else { completionHandler?(response) } break default: completionHandler?(response) } if withSaveContext { switch response.result { case .success: DatabaseHelper.sharedInstance.saveContext() case .failure: break } } } private static func validate(request: URLRequest?, response: HTTPURLResponse, data: Data?) -> DataRequest.ValidationResult { if let data = data, response.statusCode >= 200, response.statusCode < 300 { do { try JSONSerialization.jsonObject(with: data, options: []) return DataRequest.ValidationResult.success } catch { } } return DataRequest.ValidationResult.failure(PareseError.invalid) } }
34a2e80ded0bc6b5d071dcbf62759752
35.86
169
0.580901
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/News/Widgets/Countdown/View/ConventionCountdownTableViewDataSource.swift
mit
1
import Combine import ComponentBase import UIKit public class ConventionCountdownTableViewDataSource< ViewModel: ConventionCountdownViewModel >: NSObject, TableViewMediator { private let viewModel: ViewModel private var subscriptions = Set<AnyCancellable>() init(viewModel: ViewModel) { self.viewModel = viewModel super.init() viewModel .publisher(for: \.showCountdown) .sink { [weak self] (_) in if let self = self { self.delegate?.dataSourceContentsDidChange(self) } } .store(in: &subscriptions) } public var delegate: TableViewMediatorDelegate? public func registerReusableViews(into tableView: UITableView) { tableView.registerConventionBrandedHeader() tableView.register(NewsConventionCountdownTableViewCell.self) } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { viewModel.showCountdown ? 1 : 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(NewsConventionCountdownTableViewCell.self) viewModel .publisher(for: \.countdownDescription) .map({ $0 ?? "" }) .sink { [weak cell] (countdownDescription) in cell?.setTimeUntilConvention(countdownDescription) } .store(in: &subscriptions) return cell } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueConventionBrandedHeader() headerView.textLabel?.text = .daysUntilConvention return headerView } }
ab45482a333ab2efade5c804f1db72c8
31.206897
107
0.631156
false
false
false
false
Appstax/appstax-ios
refs/heads/master
Appstax/AppstaxTests/RealtimeTests.swift
mit
1
import Foundation import XCTest @testable import Appstax @objc class RealtimeTests: XCTestCase { private var realtimeService: AXRealtimeService! private var appKeyHeader: String? private var websocketUrl: NSURL? private var serverReceived: [[String:AnyObject]] = [] private var sessionRequestShouldFail = false private var websocketRequestShouldFail = false override func setUp() { super.setUp() OHHTTPStubs.setEnabled(true) OHHTTPStubs.removeAllStubs() Appstax.setAppKey("testappkey", baseUrl:"http://localhost:3000/"); Appstax.setLogLevel("debug"); realtimeService = Appstax.defaultContext.realtimeService appKeyHeader = nil websocketUrl = nil serverReceived = [] sessionRequestShouldFail = false websocketRequestShouldFail = false AXStubs.method("POST", urlPath: "/messaging/realtime/sessions") { request in self.appKeyHeader = request.allHTTPHeaderFields?["x-appstax-appkey"] if self.sessionRequestShouldFail { return OHHTTPStubsResponse(JSONObject: ["":""], statusCode: 422, headers: [:]) } else { return OHHTTPStubsResponse(JSONObject: ["realtimeSessionId":"testrsession"], statusCode: 200, headers: [:]) } } realtimeService.webSocketFactory = { self.websocketUrl = $0 let webSocket = MockWebSocket(self.realtimeService, fail: self.websocketRequestShouldFail) { self.serverReceived.append($0) } return webSocket } } override func tearDown() { super.tearDown() OHHTTPStubs.setEnabled(false) } func serverSend(dict: [String:AnyObject]) { realtimeService.webSocketDidReceiveMessage(dict) } func testShouldGetRealtimeSessionAndConnectToWebsocket() { let async = expectationWithDescription("async") let channel = AXChannel("public/chat") channel.on("open") { _ in async.fulfill() } waitForExpectationsWithTimeout(3) { error in AXAssertEqual(self.appKeyHeader, "testappkey") AXAssertNotNil(self.websocketUrl) AXAssertEqual(self.websocketUrl?.absoluteString, "ws://localhost:3000/messaging/realtime?rsession=testrsession") } } func testShouldReconnectIfDisconnected() { let async = expectationWithDescription("async") let channel = AXChannel("public/chat") var channelOpen = 0 channel.on("open") { _ in channelOpen += 1 } delay(2) { self.realtimeService.webSocketDidDisconnect(nil) delay(2) { channel.send("Message!") delay(2, async.fulfill) } } waitForExpectationsWithTimeout(10) { error in AXAssertEqual(channelOpen, 2) AXAssertEqual(self.serverReceived.count, 2) AXAssertEqual(self.serverReceived[0]["command"], "subscribe") AXAssertEqual(self.serverReceived[1]["command"], "publish") AXAssertEqual(self.serverReceived[1]["message"], "Message!") } } func testShouldSendSubscribeCommandToServerAndOpenEventToClient() { let async = expectationWithDescription("async") let channel = AXChannel("public/chat") var channelOpen = false channel.on("open") { _ in channelOpen = true } delay(1, async.fulfill) waitForExpectationsWithTimeout(3) { error in XCTAssertTrue(channelOpen) AXAssertEqual(self.serverReceived.count, 1) AXAssertEqual(self.serverReceived[0]["command"], "subscribe") AXAssertEqual(self.serverReceived[0]["channel"], "public/chat") } } func testShouldGetErrorEventWhenSessionRequestFails() { sessionRequestShouldFail = true let async = expectationWithDescription("async") let channel = AXChannel("public/chat") var channelOpen = false var channelError = false channel.on("open") { _ in channelOpen = true } channel.on("error") { _ in channelError = true } delay(1, async.fulfill) waitForExpectationsWithTimeout(3) { error in XCTAssertFalse(channelOpen) XCTAssertTrue(channelError) } } func testShouldGetErrorEventWhenWebSocketRequestFails() { websocketRequestShouldFail = true let async = expectationWithDescription("async") let channel = AXChannel("public/chat") var channelOpen = false var channelError = false channel.on("open") { _ in channelOpen = true } channel.on("error") { _ in channelError = true } delay(1, async.fulfill) waitForExpectationsWithTimeout(3) { error in XCTAssertFalse(channelOpen) XCTAssertTrue(channelError) } } func testShouldSendMessagesWithIdToServer() { let async = expectationWithDescription("async") let channel = AXChannel("public/chat") channel.send("This is my first message!") channel.send("This is my second message!") delay(1, async.fulfill) waitForExpectationsWithTimeout(3) { error in AXAssertEqual(self.serverReceived.count, 3) AXAssertEqual(self.serverReceived[1]["command"], "publish") AXAssertEqual(self.serverReceived[1]["channel"], "public/chat") AXAssertEqual(self.serverReceived[1]["message"], "This is my first message!") AXAssertEqual(self.serverReceived[2]["command"], "publish") AXAssertEqual(self.serverReceived[2]["channel"], "public/chat") AXAssertEqual(self.serverReceived[2]["message"], "This is my second message!") AXAssertNotNil(self.serverReceived[0]["id"]) AXAssertNotNil(self.serverReceived[1]["id"]) AXAssertNotNil(self.serverReceived[2]["id"]) let id1 = self.serverReceived[0]["id"] as! NSString let id2 = self.serverReceived[1]["id"] as! String XCTAssertFalse(id1.isEqualToString(id2)) } } func testShouldMapServerEventsToChannels() { let async = expectationWithDescription("async") let chat = AXChannel("public/chat") var chatReceived: [AXChannelEvent] = [] chat.on("message") { chatReceived.append($0) } chat.on("error") { chatReceived.append($0) } let stocks = AXChannel("public/stocks") var stocksReceived: [AXChannelEvent] = [] stocks.on("message") { stocksReceived.append($0) } stocks.on("error") { stocksReceived.append($0) } delay(0.2) { self.serverSend(["channel":"public/chat", "event":"message", "message":"Hello World!"]) self.serverSend(["channel":"public/chat", "event":"error", "error":"Bad dog!"]) self.serverSend(["channel":"public/stocks", "event":"message", "message":["AAPL": 127.61]]) self.serverSend(["channel":"public/stocks", "event":"error", "error":"Bad stock!"]) delay(0.1, async.fulfill) } waitForExpectationsWithTimeout(3) { error in AXAssertEqual(chatReceived.count, 2) AXAssertEqual(stocksReceived.count, 2) AXAssertEqual(chatReceived[0].channel, "public/chat") AXAssertEqual(chatReceived[0].message, "Hello World!") AXAssertNil(chatReceived[0].error) AXAssertEqual(chatReceived[1].channel, "public/chat") AXAssertEqual(chatReceived[1].error, "Bad dog!") AXAssertNil(chatReceived[1].message) AXAssertEqual(stocksReceived[0].channel, "public/stocks") AXAssertEqual(stocksReceived[0].message?["AAPL"], 127.61) AXAssertNil(stocksReceived[0].error) AXAssertEqual(stocksReceived[1].channel, "public/stocks") AXAssertEqual(stocksReceived[1].error, "Bad stock!") AXAssertNil(stocksReceived[1].message) } } func testShouldMapServerEventsToWildcardChannels() { let async = expectationWithDescription("async") let a1 = AXChannel("public/a/1") let a2 = AXChannel("public/a/2") let aw = AXChannel("public/a/*") let b1 = AXChannel("public/b/1") let b2 = AXChannel("public/b/2") let bw = AXChannel("public/b/*") var received: [String:[AXChannelEvent]] = ["a1":[],"a2":[],"aw":[],"b1":[],"b2":[],"bw":[]] a1.on("message") { received["a1"]?.append($0) } a2.on("message") { received["a2"]?.append($0) } aw.on("message") { received["aw"]?.append($0) } b1.on("message") { received["b1"]?.append($0) } b2.on("message") { received["b2"]?.append($0) } bw.on("message") { received["bw"]?.append($0) } delay(0.2) { self.serverSend(["channel":"public/a/1", "event":"message", "message":"A1"]) self.serverSend(["channel":"public/a/2", "event":"message", "message":"A2"]) self.serverSend(["channel":"public/b/1", "event":"message", "message":"B1"]) self.serverSend(["channel":"public/b/2", "event":"message", "message":"B2"]) delay(0.1, async.fulfill) } waitForExpectationsWithTimeout(3) { error in AXAssertEqual(received["a1"]?.count, 1) AXAssertEqual(received["a2"]?.count, 1) AXAssertEqual(received["aw"]?.count, 2) AXAssertEqual(received["b1"]?.count, 1) AXAssertEqual(received["b2"]?.count, 1) AXAssertEqual(received["bw"]?.count, 2) } } func testShouldMapServerEventsToWildcardEventHandlers() { let async = expectationWithDescription("async") let a1 = AXChannel("public/a/1") let a2 = AXChannel("public/a/2") let aw = AXChannel("public/a/*") let b1 = AXChannel("public/b/1") let b2 = AXChannel("public/b/2") let bw = AXChannel("public/b/*") var received: [String:[AXChannelEvent]] = ["a1":[],"a2":[],"aw":[],"b1":[],"b2":[],"bw":[]] a1.on("*") { received["a1"]?.append($0) } a2.on("*") { received["a2"]?.append($0) } aw.on("*") { received["aw"]?.append($0) } b1.on("*") { received["b1"]?.append($0) } b2.on("*") { received["b2"]?.append($0) } bw.on("*") { received["bw"]?.append($0) } delay(1.0) { self.serverSend(["channel":"public/a/1", "event":"message", "message":"A1"]) self.serverSend(["channel":"public/a/2", "event":"message", "message":"A2"]) self.serverSend(["channel":"public/b/1", "event":"message", "message":"B1"]) self.serverSend(["channel":"public/b/2", "event":"message", "message":"B2"]) delay(0.1, async.fulfill) } waitForExpectationsWithTimeout(3) { error in AXAssertEqual(received["a1"]?[0].type, "status") AXAssertEqual(received["a2"]?[0].type, "status") AXAssertEqual(received["aw"]?[0].type, "status") AXAssertEqual(received["b1"]?[0].type, "status") AXAssertEqual(received["b2"]?[0].type, "status") AXAssertEqual(received["bw"]?[0].type, "status") AXAssertEqual(received["a1"]?[1].type, "open") AXAssertEqual(received["a2"]?[1].type, "open") AXAssertEqual(received["aw"]?[1].type, "open") AXAssertEqual(received["b1"]?[1].type, "open") AXAssertEqual(received["b2"]?[1].type, "open") AXAssertEqual(received["bw"]?[1].type, "open") AXAssertEqual(received["a1"]?[2].type, "message") AXAssertEqual(received["a2"]?[2].type, "message") AXAssertEqual(received["aw"]?[2].type, "message") AXAssertEqual(received["b1"]?[2].type, "message") AXAssertEqual(received["b2"]?[2].type, "message") AXAssertEqual(received["bw"]?[2].type, "message") AXAssertEqual(received["a1"]?[2].channel, "public/a/1") AXAssertEqual(received["a2"]?[2].channel, "public/a/2") AXAssertEqual(received["aw"]?[2].channel, "public/a/1") AXAssertEqual(received["aw"]?[3].channel, "public/a/2") AXAssertEqual(received["b1"]?[2].channel, "public/b/1") AXAssertEqual(received["b2"]?[2].channel, "public/b/2") AXAssertEqual(received["bw"]?[2].channel, "public/b/1") AXAssertEqual(received["bw"]?[3].channel, "public/b/2") } } func testShouldSubscribeToAPrivateChannel() { let async = expectationWithDescription("async") let _ = AXChannel("private/mychannel") delay(1, async.fulfill) waitForExpectationsWithTimeout(3) { error in AXAssertEqual(self.serverReceived.count, 1) AXAssertEqual(self.serverReceived[0]["command"], "subscribe") AXAssertEqual(self.serverReceived[0]["channel"], "private/mychannel") } } func testShouldGrantPermissionsOnPrivateChannels() { let async = expectationWithDescription("async") let channel = AXChannel("private/mychannel") channel.grant("buddy", permissions:["read"]) channel.grant("friend", permissions:["read", "write"]) channel.revoke("buddy", permissions:["read", "write"]) channel.revoke("friend", permissions:["write"]) delay(1, async.fulfill) waitForExpectationsWithTimeout(8) { error in AXAssertEqual(self.serverReceived.count, 8) AXAssertEqual(self.serverReceived[0]["command"], "subscribe") AXAssertEqual(self.serverReceived[0]["channel"], "private/mychannel") AXAssertEqual(self.serverReceived[1]["command"], "channel.create") AXAssertEqual(self.serverReceived[1]["channel"], "private/mychannel") AXAssertEqual(self.serverReceived[2]["channel"], "private/mychannel") AXAssertEqual(self.serverReceived[2]["command"], "grant.read") AXAssertEqual((self.serverReceived[2]["data"] as! [String])[0], "buddy") AXAssertEqual(self.serverReceived[3]["channel"], "private/mychannel") AXAssertEqual(self.serverReceived[3]["command"], "grant.read") AXAssertEqual((self.serverReceived[3]["data"] as! [String])[0], "friend") AXAssertEqual(self.serverReceived[4]["channel"], "private/mychannel") AXAssertEqual(self.serverReceived[4]["command"], "grant.write") AXAssertEqual((self.serverReceived[4]["data"] as! [String])[0], "friend") AXAssertEqual(self.serverReceived[5]["channel"], "private/mychannel") AXAssertEqual(self.serverReceived[5]["command"], "revoke.read") AXAssertEqual((self.serverReceived[5]["data"] as! [String])[0], "buddy") AXAssertEqual(self.serverReceived[6]["channel"], "private/mychannel") AXAssertEqual(self.serverReceived[6]["command"], "revoke.write") AXAssertEqual((self.serverReceived[6]["data"] as! [String])[0], "buddy") AXAssertEqual(self.serverReceived[7]["channel"], "private/mychannel") AXAssertEqual(self.serverReceived[7]["command"], "revoke.write") AXAssertEqual((self.serverReceived[7]["data"] as! [String])[0], "friend") } } func testShouldSubscribeToObjectChannel() { let async = expectationWithDescription("async") let _ = AXChannel("objects/mycollection") delay(1, async.fulfill) waitForExpectationsWithTimeout(8) { error in AXAssertEqual(self.serverReceived.count, 1) AXAssertEqual(self.serverReceived[0]["channel"], "objects/mycollection") AXAssertEqual(self.serverReceived[0]["command"], "subscribe") } } func testShouldSubscribeToObjectChannelWithFilter() { let async = expectationWithDescription("async") let _ = AXChannel("objects/mycollection", filter: "text like Hello%") delay(1, async.fulfill) waitForExpectationsWithTimeout(8) { error in AXAssertEqual(self.serverReceived.count, 1) AXAssertEqual(self.serverReceived[0]["channel"], "objects/mycollection") AXAssertEqual(self.serverReceived[0]["command"], "subscribe") AXAssertEqual(self.serverReceived[0]["filter"], "text like Hello%") } } func testShouldConvertReceivedDataToAppstaxObjects() { let async = expectationWithDescription("async") let channel = AXChannel("objects/mycollection3") var receivedObjects: [AXObject?] = [] channel.on("object.created") { receivedObjects.append($0.object) } channel.on("object.updated") { receivedObjects.append($0.object) } channel.on("object.deleted") { receivedObjects.append($0.object) } delay(1) { self.serverSend([ "channel": "objects/mycollection3", "event": "object.created", "data": ["sysObjectId":"id1", "prop1":"value1"] ]) self.serverSend([ "channel": "objects/mycollection3", "event": "object.updated", "data": ["sysObjectId":"id2", "prop2":"value2"] ]) self.serverSend([ "channel": "objects/mycollection3", "event": "object.deleted", "data": ["sysObjectId":"id3", "prop3":"value3"] ]) delay(0.1, async.fulfill) } waitForExpectationsWithTimeout(8) { error in AXAssertEqual(receivedObjects.count, 3) AXAssertEqual(receivedObjects[0]?.objectID, "id1") AXAssertEqual(receivedObjects[0]?.collectionName, "mycollection3") AXAssertEqual(receivedObjects[0]?.string("prop1"), "value1") AXAssertEqual(receivedObjects[1]?.objectID, "id2") AXAssertEqual(receivedObjects[1]?.collectionName, "mycollection3") AXAssertEqual(receivedObjects[1]?.string("prop2"), "value2") AXAssertEqual(receivedObjects[2]?.objectID, "id3") AXAssertEqual(receivedObjects[2]?.collectionName, "mycollection3") AXAssertEqual(receivedObjects[2]?.string("prop3"), "value3") } } func testShouldTriggerStatusEventsThrougoutConnectionLifecycle() { let async = expectationWithDescription("async") var statusChanges: [[String:AnyObject]] = [] realtimeService.on("status") { event in let status = self.realtimeService.status statusChanges.append(["eventType": event.type, "status": status.rawValue]) } AXAssertEqual(realtimeService.status.rawValue, AXRealtimeServiceStatus.Disconnected.rawValue) let channel = AXChannel("public/foo") channel.send("foo") delay(1) { AXAssertEqual(statusChanges.count, 2) self.realtimeService.webSocketDidDisconnect(nil) delay(3) { AXAssertEqual(statusChanges.count, 4) async.fulfill() } } waitForExpectationsWithTimeout(10) { error in AXAssertEqual(statusChanges[0]["status"], AXRealtimeServiceStatus.Connecting.rawValue) AXAssertEqual(statusChanges[1]["status"], AXRealtimeServiceStatus.Connected.rawValue) AXAssertEqual(statusChanges[2]["status"], AXRealtimeServiceStatus.Connecting.rawValue) AXAssertEqual(statusChanges[3]["status"], AXRealtimeServiceStatus.Connected.rawValue) } } } private class MockWebSocket: AXWebSocketAdapter { private var realtimeService: AXRealtimeService! private var received: ([String:AnyObject])->() init(_ realtimeService: AXRealtimeService, fail: Bool, received: ([String:AnyObject])->()) { self.realtimeService = realtimeService self.received = received delay(0.5) { if fail { self.realtimeService.webSocketDidDisconnect(NSError(domain: "webSocketDidDisconnect", code: 0, userInfo: nil)) } else { self.realtimeService.webSocketDidConnect() } } } func send(message:AnyObject) { if let packet = message as? [String:AnyObject] { received(packet) } } }
809c6ddb7f073ed0f023035efe45a89d
41.659229
126
0.588797
false
false
false
false
eljeff/AudioKit
refs/heads/v5-main
Sources/AudioKit/Operations/OperationEffect.swift
mit
1
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation import CAudioKit let floatRange = -Float.greatestFiniteMagnitude ... Float.greatestFiniteMagnitude /// Operation-based effect public class OperationEffect: Node, AudioUnitContainer, Tappable, Toggleable { /// Internal audio unit type public typealias AudioUnitType = InternalAU /// Four letter unique description "cstm" public static let ComponentDescription = AudioComponentDescription(effect: "cstm") // MARK: - Properties /// Internal audio unit public private(set) var internalAU: AudioUnitType? /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU?.isStarted ?? false } // MARK: - Parameters /// Specification for Parameter 1 public static let parameter1Def = OperationGenerator.makeParam(1) /// Specification for Parameter 2 public static let parameter2Def = OperationGenerator.makeParam(2) /// Specification for Parameter 3 public static let parameter3Def = OperationGenerator.makeParam(3) /// Specification for Parameter 4 public static let parameter4Def = OperationGenerator.makeParam(4) /// Specification for Parameter 5 public static let parameter5Def = OperationGenerator.makeParam(5) /// Specification for Parameter 6 public static let parameter6Def = OperationGenerator.makeParam(6) /// Specification for Parameter 7 public static let parameter7Def = OperationGenerator.makeParam(7) /// Specification for Parameter 8 public static let parameter8Def = OperationGenerator.makeParam(8) /// Specification for Parameter 9 public static let parameter9Def = OperationGenerator.makeParam(9) /// Specification for Parameter 10 public static let parameter10Def = OperationGenerator.makeParam(10) /// Specification for Parameter 11 public static let parameter11Def = OperationGenerator.makeParam(11) /// Specification for Parameter 12 public static let parameter12Def = OperationGenerator.makeParam(12) /// Specification for Parameter 13 public static let parameter13Def = OperationGenerator.makeParam(13) /// Specification for Parameter 14 public static let parameter14Def = OperationGenerator.makeParam(14) /// Operation parameter 1 @Parameter public var parameter1: AUValue /// Operation parameter 2 @Parameter public var parameter2: AUValue /// Operation parameter 3 @Parameter public var parameter3: AUValue /// Operation parameter 4 @Parameter public var parameter4: AUValue /// Operation parameter 5 @Parameter public var parameter5: AUValue /// Operation parameter 6 @Parameter public var parameter6: AUValue /// Operation parameter 7 @Parameter public var parameter7: AUValue /// Operation parameter 8 @Parameter public var parameter8: AUValue /// Operation parameter 9 @Parameter public var parameter9: AUValue /// Operation parameter 10 @Parameter public var parameter10: AUValue /// Operation parameter 11 @Parameter public var parameter11: AUValue /// Operation parameter 12 @Parameter public var parameter12: AUValue /// Operation parameter 13 @Parameter public var parameter13: AUValue /// Operation parameter 14 @Parameter public var parameter14: AUValue // MARK: - Audio Unit /// Internal Audio Unit for Operation Effect public class InternalAU: AudioUnitBase { /// Get an array of the parameter definitions /// - Returns: Array of parameter definitions public override func getParameterDefs() -> [NodeParameterDef] { [OperationEffect.parameter1Def, OperationEffect.parameter2Def, OperationEffect.parameter3Def, OperationEffect.parameter4Def, OperationEffect.parameter5Def, OperationEffect.parameter6Def, OperationEffect.parameter7Def, OperationEffect.parameter8Def, OperationEffect.parameter9Def, OperationEffect.parameter10Def, OperationEffect.parameter11Def, OperationEffect.parameter12Def, OperationEffect.parameter13Def, OperationEffect.parameter14Def] } /// Create the DSP Refence for this node /// - Returns: DSP Reference public override func createDSP() -> DSPRef { akCreateDSP("OperationEffectDSP") } /// Set sporth string /// - Parameter sporth: Sporth string public func setSporth(_ sporth: String) { sporth.withCString { str -> Void in akOperationEffectSetSporth(dsp, str, Int32(sporth.utf8CString.count)) } } } // MARK: - Initializers /// Initialize the generator for stereo (2 channels) /// /// - Parameters: /// - input: Node to use for processing /// - channelCount: Only 2 channels are supported, but need to differentiate the initializer /// - operations: Array of operations [left, right] /// public convenience init(_ input: Node, channelCount: Int, operations: (StereoOperation, [Operation]) -> [Operation]) { let computedParameters = operations(StereoOperation.input, Operation.parameters) let left = computedParameters[0] if channelCount == 2 { let right = computedParameters[1] self.init(input, sporth: "\(right.sporth) \(left.sporth)") } else { self.init(input, sporth: "\(left.sporth)") } } /// Initialize the generator for stereo (2 channels) /// /// - Parameters: /// - input: Node to use for processing /// - operation: Operation to generate, can be mono or stereo /// public convenience init(_ input: Node, operation: (StereoOperation, [Operation]) -> ComputedParameter) { let computedParameter = operation(StereoOperation.input, Operation.parameters) if type(of: computedParameter) == Operation.self { if let monoOperation = computedParameter as? Operation { self.init(input, sporth: monoOperation.sporth + " dup ") return } } else { if let stereoOperation = computedParameter as? StereoOperation { self.init(input, sporth: stereoOperation.sporth + " swap ") return } } Log("Initialization failed.") self.init(input, sporth: "") } /// Initializw with a stereo operation /// - Parameters: /// - input: Node to use for processing /// - operation: Stereo operation /// public convenience init(_ input: Node, operation: (StereoOperation) -> ComputedParameter) { self.init(input, operation: { node, _ in operation(node) }) } /// Initialize the effect with an input and a valid Sporth string /// /// - Parameters: /// - input: Node to use for processing /// - sporth: String of valid Sporth code /// public init(_ input: Node, sporth: String) { super.init(avAudioNode: AVAudioNode()) instantiateAudioUnit { avAudioUnit in self.avAudioUnit = avAudioUnit self.avAudioNode = avAudioUnit self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType self.internalAU?.setSporth(sporth) } connections.append(input) } }
c47618ca4acb06591cf45c5c494ab398
36.539216
100
0.658005
false
false
false
false
asbhat/stanford-ios9-apps
refs/heads/master
Calculator/Calculator/ViewController.swift
apache-2.0
1
// // ViewController.swift // Calculator // // Created by Aditya Bhat on 5/2/2016. // Copyright © 2016 Aditya Bhat. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit class ViewController: UIViewController { // implicitly (automatically) unwraps display @IBOutlet fileprivate weak var display: UILabel! @IBOutlet fileprivate weak var history: UILabel! fileprivate let displayFormatter = NumberFormatter() fileprivate var userIsInTheMiddleOfTyping = false @IBAction fileprivate func touchDigit(_ sender: UIButton) { let digit = sender.currentTitle! if userIsInTheMiddleOfTyping { let textCurrentlyInDisplay = display.text! if digit != "." || textCurrentlyInDisplay.range(of: ".") == nil { display.text = textCurrentlyInDisplay + digit } } else { display.text = (digit == "." ? "0." : digit) } userIsInTheMiddleOfTyping = true } // computed propery fileprivate var displayValue: Double? { get { return Double(display.text!) } set { displayFormatter.maximumFractionDigits = (newValue ?? 0).truncatingRemainder(dividingBy: 1) == 0 ? 0 : 6 display.text = displayFormatter.string(from: newValue as NSNumber? ?? 0) } } // initializing CalculatorBrain with the default initializer (takes no arguments) fileprivate var brain = CalculatorBrain() @IBAction fileprivate func performOperation(_ sender: UIButton) { if userIsInTheMiddleOfTyping { brain.enter(operand: displayValue!) userIsInTheMiddleOfTyping = false } if let mathematicalSymbol = sender.currentTitle { brain.performOperation(symbol: mathematicalSymbol) } displayValue = brain.result history.text = brain.description + (brain.isPartialResult ? "..." : "=") } @IBAction fileprivate func allClear() { displayValue = 0 history.text = " " userIsInTheMiddleOfTyping = false brain.allClear() } @IBAction func backspace() { if userIsInTheMiddleOfTyping { if display.text!.characters.count > 1 { display.text!.remove(at: display.text!.characters.index(before: display.text!.endIndex)) } else { displayValue = 0 userIsInTheMiddleOfTyping = false } } } }
76aa2cdfd4a2253eb617c9f99bfd3ae6
33.066667
116
0.630137
false
false
false
false
piscoTech/MBLibrary
refs/heads/master
Shared/HealthKit.swift
mit
1
// // HealthKit.swift // MBLibrary // // Created by Marco Boschi on 05/03/2017. // Copyright © 2017 Marco Boschi. All rights reserved. // import Foundation import MBLibrary import HealthKit extension HKWorkoutActivityType { public var name: String { let wType: Int switch self { case .americanFootball: wType = 1 case .archery: wType = 2 case .australianFootball: wType = 3 case .badminton: wType = 4 case .baseball: wType = 5 case .basketball: wType = 6 case .bowling: wType = 7 case .boxing: wType = 8 case .climbing: wType = 9 case .cricket: wType = 10 case .crossTraining: wType = 11 case .curling: wType = 12 case .cycling: wType = 13 case .dance: wType = 14 case .danceInspiredTraining: wType = 15 case .elliptical: wType = 16 case .equestrianSports: wType = 17 case .fencing: wType = 18 case .fishing: wType = 19 case .functionalStrengthTraining: wType = 20 case .golf: wType = 21 case .gymnastics: wType = 22 case .handball: wType = 23 case .hiking: wType = 24 case .hockey: wType = 25 case .hunting: wType = 26 case .lacrosse: wType = 27 case .martialArts: wType = 28 case .mindAndBody: wType = 29 case .mixedMetabolicCardioTraining: wType = 30 case .paddleSports: wType = 31 case .play: wType = 32 case .preparationAndRecovery: wType = 33 case .racquetball: wType = 34 case .rowing: wType = 35 case .rugby: wType = 36 case .running: wType = 37 case .sailing: wType = 38 case .skatingSports: wType = 39 case .snowSports: wType = 40 case .soccer: wType = 41 case .softball: wType = 42 case .squash: wType = 43 case .stairClimbing: wType = 44 case .surfingSports: wType = 45 case .swimming: wType = 46 case .tableTennis: wType = 47 case .tennis: wType = 48 case .trackAndField: wType = 49 case .traditionalStrengthTraining: wType = 50 case .volleyball: wType = 51 case .walking: wType = 52 case .waterFitness: wType = 53 case .waterPolo: wType = 54 case .waterSports: wType = 55 case .wrestling: wType = 56 case .yoga: wType = 57 case .barre: wType = 58 case .coreTraining: wType = 59 case .crossCountrySkiing: wType = 60 case .downhillSkiing: wType = 61 case .flexibility: wType = 62 case .highIntensityIntervalTraining: wType = 63 case .jumpRope: wType = 64 case .kickboxing: wType = 65 case .pilates: wType = 66 case .snowboarding: wType = 67 case .stairs: wType = 68 case .stepTraining: wType = 69 case .wheelchairWalkPace: wType = 70 case .wheelchairRunPace: wType = 71 case .taiChi: wType = 72 case .mixedCardio: wType = 73 case .handCycling: wType = 74 case .discSports: wType = 75 case .fitnessGaming: wType = 76 case .cardioDance: wType = 77 case .socialDance: wType = 78 case .pickleball: wType = 79 case .cooldown: wType = 80 case .other: fallthrough @unknown default: wType = 0 } return MBLocalizedString("WORKOUT_NAME_\(wType)", comment: "Workout") } }
e30ddff9346d9d7bd7015fc37ac3fe25
16.069149
71
0.631973
false
false
false
false
skylib/SnapImagePicker
refs/heads/master
SnapImagePicker_Snapshot_Tests/SnapImagePickerAlbumTest.swift
bsd-3-clause
1
@testable import SnapImagePicker import SnapFBSnapshotBase class SnapImagePickerAlbumTest: SnapFBSnapshotBase { override func setUp() { super.setUp() let bundle = NSBundle(identifier: "com.snapsale.SnapImagePicker") let storyboard = UIStoryboard(name: "SnapImagePicker", bundle: bundle) if let viewController = storyboard.instantiateViewControllerWithIdentifier("Image Picker View Controller") as? SnapImagePickerViewController { sutBackingViewController = viewController sut = viewController.view setup(viewController) recordMode = super.recordAll || true } } override func tearDown() { super.tearDown() } } extension SnapImagePickerAlbumTest { private func setup(vc: SnapImagePickerViewController) { if let image = UIImage(named: "dress.jpg", inBundle: NSBundle(forClass: SnapImagePickerAlbumTest.self), compatibleWithTraitCollection: nil) { vc.eventHandler = self let mainImage = SnapImagePickerImage(image: image, localIdentifier: "localIdentifier", createdDate: NSDate()) vc.display(SnapImagePickerViewModel(albumTitle: "Title", mainImage: mainImage, selectedIndex: 0, isLoading: false)) } } } extension SnapImagePickerAlbumTest: SnapImagePickerEventHandlerProtocol { func viewWillAppearWithCellSize(cellSize: CGFloat) { } func albumImageClicked(index: Int) -> Bool { return false } func albumTitleClicked(destinationViewController: UIViewController) { } func selectButtonPressed(image: UIImage, withImageOptions: ImageOptions) { } func numberOfSectionsForNumberOfColumns(columns: Int) -> Int { return 40 } func numberOfItemsInSection(section: Int, withColumns: Int) -> Int { return withColumns } func presentCell(cell: ImageCell, atIndex: Int) -> ImageCell { cell.imageView?.image = UIImage(named: "dress.jpg", inBundle: NSBundle(forClass: SnapImagePickerAlbumTest.self), compatibleWithTraitCollection: nil) if atIndex == 0 { cell.backgroundColor = SnapImagePicker.Theme.color cell.spacing = 2 } return cell } func scrolledToCells(cells: Range<Int>, increasing: Bool, fromOldRange: Range<Int>?) { } }
4b5d0fd87ff02754c3404b37b10ad563
35.784615
156
0.676151
false
true
false
false
hstdt/GodEye
refs/heads/master
Carthage/Checkouts/Log4G/Log4G/Classes/Log4G.swift
mit
1
// // Log4G.swift // Pods // // Created by zixun on 17/1/10. // // import Foundation //-------------------------------------------------------------------------- // MARK: - Log4gDelegate //-------------------------------------------------------------------------- public protocol Log4GDelegate: NSObjectProtocol { func log4gDidRecord(with model:LogModel) } //-------------------------------------------------------------------------- // MARK: - WeakLog4gDelegate // DESCRIPTION: Weak wrap of delegate //-------------------------------------------------------------------------- class WeakLog4GDelegate: NSObject { weak var delegate : Log4GDelegate? init (delegate: Log4GDelegate) { super.init() self.delegate = delegate } } //-------------------------------------------------------------------------- // MARK: - Log4G // DESCRIPTION: Simple, lightweight logging framework written in Swift // 4G means for GodEye, it was development for GodEye at the beginning of the time //-------------------------------------------------------------------------- open class Log4G: NSObject { //-------------------------------------------------------------------------- // MARK: OPEN FUNCTION //-------------------------------------------------------------------------- /// record a log type message /// /// - Parameters: /// - message: log message /// - file: file which call the api /// - line: line number at file which call the api /// - function: function name which call the api open class func log(_ message: Any = "", file: String = #file, line: Int = #line, function: String = #function) { self.shared.record(type: .log, thread: Thread.current, message: "\(message)", file: file, line: line, function: function) } /// record a warning type message /// /// - Parameters: /// - message: warning message /// - file: file which call the api /// - line: line number at file which call the api /// - function: function name which call the api open class func warning(_ message: Any = "", file: String = #file, line: Int = #line, function: String = #function) { self.shared.record(type: .warning, thread: Thread.current, message: "\(message)", file: file, line: line, function: function) } /// record an error type message /// /// - Parameters: /// - message: error message /// - file: file which call the api /// - line: line number at file which call the api /// - function: function name which call the api open class func error(_ message: Any = "", file: String = #file, line: Int = #line, function: String = #function) { self.shared.record(type: .error, thread: Thread.current, message: "\(message)", file: file, line: line, function: function) } //-------------------------------------------------------------------------- // MARK: PRIVATE FUNCTION //-------------------------------------------------------------------------- /// record message base function /// /// - Parameters: /// - type: log type /// - thread: thread which log the messsage /// - message: log message /// - file: file which call the api /// - line: line number at file which call the api /// - function: function name which call the api private func record(type:Log4gType, thread:Thread, message: String, file: String, line: Int, function: String) { self.queue.async { let model = LogModel(type: type, thread: thread, message: message, file: self.name(of: file), line: line, function: function) print(message) for delegate in self.delegates { delegate.delegate?.log4gDidRecord(with: model) } } } /// get the name of file in filepath /// /// - Parameter file: path of file /// - Returns: filename private func name(of file:String) -> String { return URL(fileURLWithPath: file).lastPathComponent } //MARK: - Private Variable /// singleton for Log4g fileprivate static let shared = Log4G() /// log queue private let queue = DispatchQueue(label: "Log4g") /// weak delegates fileprivate var delegates = [WeakLog4GDelegate]() } //-------------------------------------------------------------------------- // MARK: - Log4gDelegate Fucntion Extension //-------------------------------------------------------------------------- extension Log4G { open class var delegateCount: Int { get { return self.shared.delegates.count } } open class func add(delegate:Log4GDelegate) { let log4g = self.shared // delete null week delegate log4g.delegates = log4g.delegates.filter { return $0.delegate != nil } // judge if contains the delegate from parameter let contains = log4g.delegates.contains { return $0.delegate?.hash == delegate.hash } // if not contains, append it with weak wrapped if contains == false { let week = WeakLog4GDelegate(delegate: delegate) self.shared.delegates.append(week) } } open class func remove(delegate:Log4GDelegate) { let log4g = self.shared log4g.delegates = log4g.delegates.filter { // filter null weak delegate return $0.delegate != nil }.filter { // filter the delegate from parameter return $0.delegate?.hash != delegate.hash } } }
0849573dbdb48a465aaff9e273d0e679
32.766497
95
0.428593
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
refs/heads/master
nRF Toolbox/Profiles/UART/NewCommand/UARTNewCommandViewController.swift
bsd-3-clause
1
/* * Copyright (c) 2020, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import UIKit protocol UARTNewCommandDelegate: AnyObject { func createdNewCommand(_ viewController: UARTNewCommandViewController, command: UARTCommandModel, index: Int) } class UARTNewCommandViewController: UIViewController { @IBOutlet private var createButton: NordicButton! @IBOutlet private var deleteButton: NordicButton! @IBOutlet private var collectionView: UICollectionView! @IBOutlet private var valueTextField: UITextField! @IBOutlet private var typeSegmentControl: UISegmentedControl! @IBOutlet private var textView: AutoReszableTextView! @IBOutlet private var eolLabel: UILabel! @IBOutlet private var eolSegment: UISegmentedControl! weak var delegate: UARTNewCommandDelegate? private var command: UARTCommandModel? private var index: Int init(command: UARTCommandModel?, index: Int) { self.command = command self.index = index super.init(nibName: "UARTNewCommandViewController", bundle: .main) } required init?(coder: NSCoder) { SystemLog(category: .app, type: .fault).fault("required init?(coder: NSCoder) is not implemented for UARTNewCommandViewController") } override func viewDidLoad() { super.viewDidLoad() if #available(iOS 13.0, *) { view.backgroundColor = .systemBackground } setupTextField() setupTextView() createButton.style = .mainAction navigationItem.title = "Create new command" collectionView.register(type: ImageCollectionViewCell.self) command.map { self.setupUI(with: $0) } if #available(iOS 13, *) { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(dismsiss)) } else { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Close", style: .done, target: self, action: #selector(dismsiss)) } } @IBAction func typeChanged(_ sender: UISegmentedControl) { // textField.isHidden, textView.isHidden, eolLabel.isHidden, eolSegment.isHidden let hiddenOptions: (Bool, Bool, Bool, Bool) if sender.selectedSegmentIndex == 0 { hiddenOptions = (true, false, false, false ) } else { hiddenOptions = (false, true, true, true ) } valueTextField.isHidden = hiddenOptions.0 textView.isHidden = hiddenOptions.1 eolLabel.isHidden = hiddenOptions.2 eolSegment.isHidden = hiddenOptions.3 createButton.isEnabled = readyForCreate() textView.resignFirstResponder() valueTextField.resignFirstResponder() } @IBAction func textChanged(_ sender: Any) { createButton.isEnabled = readyForCreate() } @IBAction func createCommand() { let command: UARTCommandModel let selectedItem = (collectionView.indexPathsForSelectedItems?.first?.item)! let image = CommandImage.allCases[selectedItem] if typeSegmentControl.selectedSegmentIndex == 0 { let slices = textView.text.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) let text = slices.joined(separator: eolSymbol()) command = TextCommand(text: text, image: image, eol: self.eolSymbol()) } else { command = DataCommand(data: Data(valueTextField.text!.hexa), image: image) } delegate?.createdNewCommand(self, command: command, index: index) } @IBAction func deleteBtnPressed() { delegate?.createdNewCommand(self, command: EmptyModel(), index: index) } } extension UARTNewCommandViewController { private func setupUI(with command: UARTCommandModel) { let typeIndex: Int let title: String switch command { case let tCommand as TextCommand: typeIndex = 0 title = tCommand.title textView.text = title updateEOLSegment(eol: tCommand.eol) case is DataCommand: typeIndex = 1 title = command.data.hexEncodedString().uppercased() valueTextField.text = title default: return } typeSegmentControl.selectedSegmentIndex = typeIndex typeChanged(typeSegmentControl) CommandImage.allCases.enumerated() .first(where: { $0.element.name == command.image.name }) .map { self.collectionView.selectItem(at: IndexPath(item: $0.offset, section: 0), animated: false, scrollPosition: .top) } deleteButton.isHidden = false deleteButton.style = .destructive createButton.setTitle("Save", for: .normal) } private func updateButtonState() { createButton.isEnabled = !(valueTextField.text?.isEmpty ?? true) && collectionView.indexPathsForSelectedItems?.first != nil } private func setupTextView() { let accessoryToolbar = UIToolbar() accessoryToolbar.autoresizingMask = .flexibleHeight let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: textView, action: #selector(resignFirstResponder)) accessoryToolbar.items = [doneBtn] textView.inputAccessoryView = accessoryToolbar textView.didChangeText = { [weak self] _ in self?.createButton.isEnabled = self?.readyForCreate() == true } } private func updateEOLSegment(eol: String) { let symbols = ["\n", "\r", "\n\r"] eolSegment.selectedSegmentIndex = symbols.enumerated().first(where: { eol == $0.element })?.offset ?? 0 } private func setupTextField() { let accessoryToolbar = UIToolbar() accessoryToolbar.autoresizingMask = .flexibleHeight let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: valueTextField, action: #selector(resignFirstResponder)) accessoryToolbar.items = [doneBtn] let hexLabel = UILabel() hexLabel.text = " 0x" hexLabel.font = valueTextField.font hexLabel.textColor = UIColor.Text.secondarySystemText hexLabel.textAlignment = .center valueTextField.leftView = hexLabel valueTextField.leftViewMode = .always valueTextField.inputAccessoryView = accessoryToolbar } private func readyForCreate() -> Bool { let selectedItem = collectionView.indexPathsForSelectedItems?.first != nil let dataIsReady = typeSegmentControl.selectedSegmentIndex == 0 ? !textView.text.isEmpty : valueTextField.text?.isEmpty == false return selectedItem && dataIsReady } private func eolSymbol() -> String { switch eolSegment.selectedSegmentIndex { case 0: return "\n" case 1: return "\r" case 2: return "\n\r" default: return "" } } } extension UARTNewCommandViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { createButton.isEnabled = readyForCreate() valueTextField.resignFirstResponder() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let side = collectionView.frame.size.width / 3 - 6 return CGSize(width: side, height: side) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 8 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { 8 } } extension UARTNewCommandViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { CommandImage.allCases.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let img = CommandImage.allCases[indexPath.item] let cell = collectionView.dequeueCell(ofType: ImageCollectionViewCell.self, for: indexPath) cell.imageView.image = img.image?.withRenderingMode(.alwaysTemplate) return cell } } extension UARTNewCommandViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return CharacterSet(charactersIn: "0123456789abcdefABCDEF").isSuperset(of: CharacterSet(charactersIn: string)) } }
fb5290255713fc64d70a68d0b1e9fcee
38.805243
175
0.68169
false
false
false
false
CodaFi/swift
refs/heads/main
test/IRGen/Inputs/metadata2.swift
apache-2.0
29
import resilient_struct struct Item { var d: ResilientInt? = nil } struct InternalContainer { fileprivate enum SomeEnumType { case none case single(Item) init(item: [Item]) { if item.count >= 1 { self = .single(item.first!) } else { self = .none } } } private var type: SomeEnumType init(item: [Item]) { self.type = SomeEnumType(item: item) } } struct InternalContainer2 { fileprivate enum SomeEnumType { case none case single(Item) init(item: [Item]) { if item.count >= 1 { self = .single(item.first!) } else { self = .none } } } private var type: (SomeEnumType, SomeEnumType) init(item: [Item]) { self.type = SomeEnumType(item: item) } } enum InternalSingletonEnum { fileprivate enum SomeEnumType { case none case single(Item) init(item: [Item]) { if item.count >= 1 { self = .single(item.first!) } else { self = .none } } } case first(SomeEnumType) init() { return .first(.none) } } enum InternalSingletonEnum2 { fileprivate enum SomeEnumType { case none case single(Item) init(item: [Item]) { if item.count >= 1 { self = .single(item.first!) } else { self = .none } } } case first(SomeEnumType, SomeEnumType) init() { return .first(.none, .none) } }
c16a62441c30384570e6e8b8c9d9551e
17.404494
50
0.490842
false
false
false
false
psoamusic/PourOver
refs/heads/master
PourOver/POCoreMotionGenerator.swift
gpl-3.0
1
// // POCoreMotionGenerator.swift // LibraryLoader // // Created by kevin on 6/15/15. // Copyright (c) 2015 labuser. All rights reserved. // import Foundation import UIKit import CoreMotion //constants for controller names: //note: case-insensitive compared for lookup let kPitchController = "CMMotionManager.deviceMotion.attitude.pitch" let kRollController = "CMMotionManager.deviceMotion.attitude.roll" let kYawController = "CMMotionManager.deviceMotion.attitude.yaw" let kGravityXController = "CMMotionManager.deviceMotion.gravity.x" let kGravityYController = "CMMotionManager.deviceMotion.gravity.y" let kGravityZController = "CMMotionManager.deviceMotion.gravity.z" let kUserAccelerationXController = "CMMotionManager.deviceMotion.userAcceleration.x" let kUserAccelerationYController = "CMMotionManager.deviceMotion.userAcceleration.y" let kUserAccelerationZController = "CMMotionManager.deviceMotion.userAcceleration.z" let kRotationRateXController = "CMMotionManager.deviceMotion.rotationRate.x" let kRotationRateYController = "CMMotionManager.deviceMotion.rotationRate.y" let kRotationRateZController = "CMMotionManager.deviceMotion.rotationRate.z" class POCoreMotionGenerator: POControllerUpdating { //=================================================================================== //MARK: Properties //=================================================================================== //framework objects should be lazy loaded, not instantiated during init() lazy final var motionManager = CMMotionManager() //=================================================================================== //MARK: Initialization //=================================================================================== deinit { endUpdating() } //=================================================================================== //MARK: POControllerUpdating //=================================================================================== static var controllers: [String : POController] = [ kPitchController : POController(name: kPitchController, min: -M_PI_2, max: M_PI_2), kRollController : POController(name: kRollController, min: -M_PI, max: M_PI), kYawController : POController(name: kYawController, min: -M_PI, max: M_PI), kGravityXController : POController(name: kGravityXController, min: -M_PI, max: M_PI), kGravityYController : POController(name: kGravityYController, min: -M_PI, max: M_PI), kGravityZController : POController(name: kGravityZController, min: -M_PI, max: M_PI), kUserAccelerationXController : POController(name: kUserAccelerationXController, min: -M_PI, max: M_PI), kUserAccelerationYController : POController(name: kUserAccelerationYController, min: -M_PI, max: M_PI), kUserAccelerationZController : POController(name: kUserAccelerationZController, min: -M_PI, max: M_PI), kRotationRateXController : POController(name: kRotationRateXController, min: -M_PI, max: M_PI), kRotationRateYController : POController(name: kRotationRateYController, min: -M_PI, max: M_PI), kRotationRateZController : POController(name: kRotationRateZController, min: -M_PI, max: M_PI), ] static var requiresTimer: Bool = true func update() { if let deviceMotion = motionManager.deviceMotion { updateValue(deviceMotion.attitude.pitch, forControllerNamed: kPitchController) updateValue(deviceMotion.attitude.roll, forControllerNamed: kRollController) updateValue(deviceMotion.attitude.yaw, forControllerNamed: kYawController) updateValue(deviceMotion.gravity.x, forControllerNamed: kGravityXController) updateValue(deviceMotion.gravity.y, forControllerNamed: kGravityYController) updateValue(deviceMotion.gravity.z, forControllerNamed: kGravityZController) updateValue(deviceMotion.userAcceleration.x, forControllerNamed: kUserAccelerationXController) updateValue(deviceMotion.userAcceleration.y, forControllerNamed: kUserAccelerationYController) updateValue(deviceMotion.userAcceleration.z, forControllerNamed: kUserAccelerationZController) updateValue(deviceMotion.rotationRate.x, forControllerNamed: kRotationRateXController) updateValue(deviceMotion.rotationRate.y, forControllerNamed: kRotationRateYController) updateValue(deviceMotion.rotationRate.z, forControllerNamed: kRotationRateZController) } } func beginUpdating() { if motionManager.gyroAvailable { motionManager.startDeviceMotionUpdates() } } func endUpdating() { motionManager.stopDeviceMotionUpdates() } }
6b3158096a158bd6cec4660221edf3ca
49.645833
111
0.657548
false
false
false
false
TG908/iOS
refs/heads/master
TUM Campus App/TumOnlineLoginRequestManager.swift
gpl-3.0
1
// // TumOnlineLoginRequestManager.swift // TUM Campus App // // Created by Mathias Quintero on 12/5/15. // Copyright © 2015 LS1 TUM. All rights reserved. // import Sweeft import Alamofire import SWXMLHash class TumOnlineLoginRequestManager { init(delegate:AccessTokenReceiver?) { self.delegate = delegate } var token = "" let defaults = UserDefaults.standard var delegate: AccessTokenReceiver? var lrzID : String? func newId(_ newId: String) { lrzID = newId } func getLoginURL() -> String { let version = (Bundle.main.infoDictionary?["CFBundleVersion"] as? String) ?? "1" let base = TUMOnlineWebServices.BaseUrl.rawValue + TUMOnlineWebServices.TokenRequest.rawValue if let id = lrzID { return base + "?pUsername=" + id + "&pTokenName=TumCampusApp-" + version } return "" } func getConfirmationURL() -> String { return TUMOnlineWebServices.BaseUrl.rawValue + TUMOnlineWebServices.TokenConfirmation.rawValue + "?" + TUMOnlineWebServices.TokenParameter.rawValue + "=" + token } func fetch() { let url = getLoginURL() print(url) Alamofire.request(url).responseString() { (response) in if let data = response.result.value { let tokenData = SWXMLHash.parse(data) if let token = tokenData["token"].element?.text { self.token = token } } } } func confirmToken() { let url = getConfirmationURL() print(url) Alamofire.request(url).responseString() { (response) in if let data = response.result.value { let tokenData = SWXMLHash.parse(data) print(tokenData) if let confirmed = tokenData["confirmed"].element?.text { if confirmed == "true" { self.delegate?.receiveToken(self.token) } else { self.delegate?.tokenNotConfirmed() } } else { self.delegate?.tokenNotConfirmed() } } else { self.delegate?.tokenNotConfirmed() } } } func loginSuccesful(_ user: User) { PersistentUser.value = .some(lrzID: (user.lrzID).?, token: user.token) User.shared = user } func logOut() { PersistentUser.reset() User.shared = nil } }
e2a2b2144a433e64e2a8775341d33597
27.7
169
0.546264
false
false
false
false
Mazy-ma/DemoBySwift
refs/heads/master
ComplexLoadingAnimation/ComplexLoadingAnimation/ViewController.swift
apache-2.0
1
// // ViewController.swift // ComplexLoadingAnimation // // Created by Mazy on 2017/6/30. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class ViewController: UIViewController { var holderView = HolderView(frame: CGRect.zero) override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) addHolderView() } func addHolderView() { let boxSize: CGFloat = 100 holderView.frame = CGRect(x: view.bounds.width/2 - boxSize/2, y: view.bounds.height/2-boxSize/2, width: boxSize, height: boxSize) holderView.parentFrame = view.frame holderView.delegate = self holderView.addOval() view.addSubview(holderView) } func addButton() { let button = UIButton(type: .custom) button.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height) button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) } func buttonPressed() { view.backgroundColor = Colors.white _ = view.subviews.map{ $0.removeFromSuperview()} holderView = HolderView(frame: CGRect.zero) addHolderView() } } extension ViewController: HolderViewDelegate { func animationLabel() { // 1 holderView.removeFromSuperview() view.backgroundColor = Colors.blue // 2 let label: UILabel = UILabel(frame: view.frame) label.textColor = Colors.white label.font = UIFont(name: "HelveticaNeue-Thin", size: 170) label.textAlignment = .center label.text = "S" label.transform = label.transform.scaledBy(x: 0.25, y: 0.25) view.addSubview(label) // 3 UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.1, options: .curveEaseInOut, animations: { label.transform = label.transform.scaledBy(x: 4.0, y: 4.0) }) { (_) in self.addButton() } } }
19133d127cb18172f4a939d3b083c0bd
28.219178
151
0.614158
false
false
false
false
iosliutingxin/DYVeideoVideo
refs/heads/master
DYZB/DYZB/Classes/Home/Controller/HomeViewController.swift
mit
1
// // HomeViewController.swift // DYZB // // Created by 北京时代华擎 on 17/4/30. // Copyright © 2017年 iOS _Liu. All rights reserved. // import UIKit private let titleViewH:CGFloat=40 class HomeViewController: UIViewController { public var currentIndex : Int = 0{ didSet{ setCurrentIndex(index: currentIndex) } } //懒加载属性 fileprivate lazy var pageTitleView:PageTitleView = {[weak self] in let titleFrame=CGRect(x: 0, y: stateBarH+NavigationBar, width:screenW, height: titleViewH) let titles=["推荐","游戏","娱乐","趣玩"] let titleView=PageTitleView(frame: titleFrame, titles: titles) titleView.delegate=self return titleView }() //内容部分 fileprivate lazy var pageContentView : PageContentView = {[weak self]in //1、确定frame let contentH = screenH - stateBarH - NavigationBar - titleViewH - tabBarH let contentFrame = CGRect(x: 0, y: stateBarH + NavigationBar + titleViewH, width: screenW, height: contentH) //2、确定所有子控制器 var childVc = [UIViewController]() //(1--推荐控制器 childVc.append(RecommeViewController()) //(2--游戏控制器 childVc.append(gameController()) //3、游戏界面 childVc.append(AmuseController()) for _ in 0..<1{ let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVc.append(vc) } let contentView = PageContentView(frame: contentFrame, chilVcs: childVc, parentViewController: self) contentView.ContentCurrentPage = {[weak self] (index)in guard let strongSelf = self else { return } strongSelf.currentIndex = index } return contentView }() //系统回调函数 override func viewDidLoad() { super.viewDidLoad() setUpUI() } } //设置UI界面 extension HomeViewController{ fileprivate func setUpUI(){ //不需要调整UIscrollView的内边距 automaticallyAdjustsScrollViewInsets=false //1、设置导航栏 setUpNavigationBar() //2、添加titlview view.addSubview(pageTitleView) //3、添加contentView view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.purple } fileprivate func setUpNavigationBar(){ let btn=UIButton() btn.setImage(UIImage (named: "homeLogoIcon"), for:UIControlState() ) btn.sizeToFit() navigationItem.leftBarButtonItem=UIBarButtonItem(customView: btn) let size=CGSize(width: 40, height: 40) let historyItem=UIBarButtonItem(imageName: "btn_close_danmu", highImage: "btn_close_danmu", size: size) let searchItem=UIBarButtonItem(imageName: "home_newSeacrhcon", highImage: "home_newSaoicon", size: size) let qrcodeItem=UIBarButtonItem(imageName: "home_newSaoicon", highImage: "home_newSeacrhcon", size: size) navigationItem.rightBarButtonItems=[historyItem,searchItem,qrcodeItem] } } extension HomeViewController{ func setCurrentIndex(index : Int) { pageTitleView.setCurrentId(index) } } //pageTitleDelegate extension HomeViewController : pageTitleDelegate { func pageTitleView(_ titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(index) } }
c0bbbb3fd340c1b2aac97bee187cf192
24.811594
156
0.629141
false
false
false
false
qiscus/qiscus-sdk-ios
refs/heads/master
Qiscus/Qiscus/Library/QReachability.swift
mit
1
// // QReachability.swift // QiscusSDK // // Created by Ahmad Athaullah on 10/24/16. // Copyright © 2016 Ahmad Athaullah. All rights reserved. // import UIKit /* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CA AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Reachability.swift version 2.2beta2 import SystemConfiguration import Foundation public enum QReachabilityError: Error { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue } public let QReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification") func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) { guard let info = info else { return } let reachability = Unmanaged<QReachability>.fromOpaque(info).takeUnretainedValue() DispatchQueue.main.async { reachability.reachabilityChanged() } } public class QReachability { public typealias NetworkReachable = (QReachability) -> () public typealias NetworkUnreachable = (QReachability) -> () public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN public var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? public var reachableOnWWAN: Bool public var currentReachabilityString: String { return "\(currentReachabilityStatus)" } public var currentReachabilityStatus: NetworkStatus { guard isReachable else { return .notReachable } if isReachableViaWiFi { return .reachableViaWiFi } if isRunningOnDevice { return .reachableViaWWAN } return .notReachable } fileprivate var previousFlags: SCNetworkReachabilityFlags? fileprivate var isRunningOnDevice: Bool = { #if (arch(i386) || arch(x86_64)) && os(iOS) return false #else return true #endif }() fileprivate var notifierRunning = false fileprivate var reachabilityRef: SCNetworkReachability? fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability") required public init(reachabilityRef: SCNetworkReachability) { reachableOnWWAN = true self.reachabilityRef = reachabilityRef } public convenience init?(hostname: String) { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } self.init(reachabilityRef: ref) } public convenience init?() { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) guard let ref: SCNetworkReachability = withUnsafePointer(to: &zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return nil } self.init(reachabilityRef: ref) } deinit { stopNotifier() reachabilityRef = nil whenReachable = nil whenUnreachable = nil } } public extension QReachability { // MARK: - *** Notifier methods *** func startNotifier() throws { guard let reachabilityRef = reachabilityRef, !notifierRunning else { return } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<QReachability>.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw QReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw QReachabilityError.UnableToSetDispatchQueue } // Perform an intial check reachabilitySerialQueue.async { self.reachabilityChanged() } notifierRunning = true } func stopNotifier() { defer { notifierRunning = false } guard let reachabilityRef = reachabilityRef else { return } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** var isReachable: Bool { guard isReachableFlagSet else { return false } if isConnectionRequiredAndTransientFlagSet { return false } if isRunningOnDevice { if isOnWWANFlagSet && !reachableOnWWAN { // We don't want to connect when on 3G. return false } } return true } var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet } var isReachableViaWiFi: Bool { // Check we're reachable guard isReachableFlagSet else { return false } // If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi guard isRunningOnDevice else { return true } // Check we're NOT on WWAN return !isOnWWANFlagSet } var description: String { let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X" let R = isReachableFlagSet ? "R" : "-" let c = isConnectionRequiredFlagSet ? "c" : "-" let t = isTransientConnectionFlagSet ? "t" : "-" let i = isInterventionRequiredFlagSet ? "i" : "-" let C = isConnectionOnTrafficFlagSet ? "C" : "-" let D = isConnectionOnDemandFlagSet ? "D" : "-" let l = isLocalAddressFlagSet ? "l" : "-" let d = isDirectFlagSet ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } fileprivate extension QReachability { func reachabilityChanged() { let flags = reachabilityFlags guard previousFlags != flags else { return } let block = isReachable ? whenReachable : whenUnreachable block?(self) NotificationCenter.default.post(name: QReachabilityChangedNotification, object:self) previousFlags = flags } var isOnWWANFlagSet: Bool { #if os(iOS) return reachabilityFlags.contains(.isWWAN) #else return false #endif } var isReachableFlagSet: Bool { return reachabilityFlags.contains(.reachable) } var isConnectionRequiredFlagSet: Bool { return reachabilityFlags.contains(.connectionRequired) } var isInterventionRequiredFlagSet: Bool { return reachabilityFlags.contains(.interventionRequired) } var isConnectionOnTrafficFlagSet: Bool { return reachabilityFlags.contains(.connectionOnTraffic) } var isConnectionOnDemandFlagSet: Bool { return reachabilityFlags.contains(.connectionOnDemand) } var isConnectionOnTrafficOrDemandFlagSet: Bool { return !reachabilityFlags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } var isTransientConnectionFlagSet: Bool { return reachabilityFlags.contains(.transientConnection) } var isLocalAddressFlagSet: Bool { return reachabilityFlags.contains(.isLocalAddress) } var isDirectFlagSet: Bool { return reachabilityFlags.contains(.isDirect) } var isConnectionRequiredAndTransientFlagSet: Bool { return reachabilityFlags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection] } var reachabilityFlags: SCNetworkReachabilityFlags { guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() } var flags = SCNetworkReachabilityFlags() let gotFlags = withUnsafeMutablePointer(to: &flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return flags } else { return SCNetworkReachabilityFlags() } } }
790fc7c07a46e1f5508877676434f1f7
31.853896
137
0.657081
false
false
false
false
breadwallet/breadwallet-ios
refs/heads/master
breadwalletIntentHandler/IntentHandler.swift
mit
1
// // IntentHandler.swift // breadwalletIntentHandler // // Created by stringcode on 11/02/2021. // Copyright © 2021 Breadwinner AG. All rights reserved. // // See the LICENSE file at the project root for license information. // import Intents class IntentHandler: INExtension { private let service: WidgetService override init() { service = DefaultWidgetService(widgetDataShareService: nil, imageStoreService: nil) super.init() } override func handler(for intent: INIntent) -> Any { return self } } // MARK: - AssetIntentHandling extension IntentHandler: AssetIntentHandling { func provideChartUpColorOptionsCollection(for intent: AssetIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartUpColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartUpColor(for intent: AssetIntent) -> ColorOption? { return service.defaultChartUpOptions() } func provideChartDownColorOptionsCollection(for intent: AssetIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartDownColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartDownColor(for intent: AssetIntent) -> ColorOption? { return service.defaultChartDownOptions() } func provideBackgroundColorOptionsCollection(for intent: AssetIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchBackgroundColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionCurrency, items: options.filter { $0.isCurrencyColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultBackgroundColor(for intent: AssetIntent) -> ColorOption? { return service.defaultBackgroundColor() } func provideTextColorOptionsCollection(for intent: AssetIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchTextColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultTextColor(for intent: AssetIntent) -> ColorOption? { return service.defaultTextColor() } func provideAssetOptionsCollection(for intent: AssetIntent, with completion: @escaping (INObjectCollection<AssetOption>?, Error?) -> Void) { service.fetchAssetOptions { result in switch result { case let .success(options): completion(INObjectCollection(items: options), nil) case let .failure(error): print("Failed to load asset options", error) completion(INObjectCollection(items: []), error) } } } func defaultAsset(for intent: AssetIntent) -> AssetOption? { return service.defaultAssetOptions().first } } // MARK: - AssetListIntentHandling extension IntentHandler: AssetListIntentHandling { func provideAssetsOptionsCollection(for intent: AssetListIntent, with completion: @escaping (INObjectCollection<AssetOption>?, Error?) -> Void) { service.fetchAssetOptions { result in switch result { case let .success(options): completion(INObjectCollection(items: options), nil) case let .failure(error): print("Failed to load asset options", error) completion(INObjectCollection(items: []), error) } } } func defaultAssets(for intent: AssetListIntent) -> [AssetOption]? { return service.defaultAssetOptions() } func provideChartUpColorOptionsCollection(for intent: AssetListIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartUpColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartUpColor(for intent: AssetListIntent) -> ColorOption? { return service.defaultChartUpOptions() } func provideChartDownColorOptionsCollection(for intent: AssetListIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartDownColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartDownColor(for intent: AssetListIntent) -> ColorOption? { return service.defaultChartDownOptions() } func provideBackgroundColorOptionsCollection(for intent: AssetListIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchBackgroundColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionCurrency, items: options.filter { $0.isCurrencyColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultBackgroundColor(for intent: AssetListIntent) -> ColorOption? { return service.defaultBackgroundColor() } func provideTextColorOptionsCollection(for intent: AssetListIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchTextColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultTextColor(for intent: AssetListIntent) -> ColorOption? { return service.defaultTextColor() } } // MARK: - PortfolioIntentHandling extension IntentHandler: PortfolioIntentHandling { func provideAssetsOptionsCollection(for intent: PortfolioIntent, with completion: @escaping (INObjectCollection<AssetOption>?, Error?) -> Void) { service.fetchAssetOptions { result in switch result { case let .success(options): completion(INObjectCollection(items: options), nil) case let .failure(error): print("Failed to load asset options", error) completion(INObjectCollection(items: []), error) } } } func defaultAssets(for intent: PortfolioIntent) -> [AssetOption]? { return service.defaultAssetOptions() } func provideChartUpColorOptionsCollection(for intent: PortfolioIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartUpColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartUpColor(for intent: PortfolioIntent) -> ColorOption? { return service.defaultChartUpOptions() } func provideChartDownColorOptionsCollection(for intent: PortfolioIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartDownColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartDownColor(for intent: PortfolioIntent) -> ColorOption? { return service.defaultChartDownOptions() } func provideBackgroundColorOptionsCollection(for intent: PortfolioIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchBackgroundColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionCurrency, items: options.filter { $0.isCurrencyColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultBackgroundColor(for intent: PortfolioIntent) -> ColorOption? { return service.defaultBackgroundColor() } func provideTextColorOptionsCollection(for intent: PortfolioIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchTextColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultTextColor(for intent: PortfolioIntent) -> ColorOption? { return service.defaultTextColor() } }
37e1387dfcfd6f38ea760a2ab28113bb
44.617788
158
0.548611
false
false
false
false
asynchrony/Re-Lax
refs/heads/master
ReLax/ReLax/CoreStructuredImage.swift
mit
1
import UIKit enum CoreStructuredImage { case flattened(imageName: String) case layer(imageName: String, imageSize: CGSize) case layeredImage(imageName: String, imageSize: CGSize) private var pixelFormat: String { switch self { case .flattened(_): return "GEPJ" case .layer(_, _): return "BGRA" case .layeredImage(_, _): return "ATAD" } } private var colorSpaceID: Int { switch self { case .flattened(_), .layeredImage(_, _): return 15 case .layer(_, _): return 1 } } // Type of Rendition private var layout: Int { switch self { case .flattened(_), .layer(_, _): return 10 case .layeredImage(_, _): return 0x03EA } } private var imageSize: CGSize { switch self { case .flattened(_): return .zero case .layer(_, let size): return size case .layeredImage(_, let size): return size } } private var imageName: String { switch self { case .flattened(let name): return name case .layer(let name, _): return name case .layeredImage(let name, _): return name } } func data(structuredInfoDataLength: Int, payloadDataLength: Int) -> Data { let infoListLength = int32Data(structuredInfoDataLength) let bitmapInfoData = bitmapInfo(payloadLength: payloadDataLength) return concatData([renditionHeader(), metaData(), infoListLength, bitmapInfoData]) } private func renditionHeader() -> Data { let ctsi = "ISTC".data(using: .ascii)! let version = int32Data(1) let renditionFlags = int32Data(0) // unused let width = int32Data(Int(imageSize.width)) let height = int32Data(Int(imageSize.height)) let scale = int32Data(100) // 100 = 1x, 200 = 2x let pixelFormat = self.pixelFormat.data(using: .ascii)! let colorSpaceIDData = int32Data(self.colorSpaceID) return concatData([ctsi, version, renditionFlags, width, height, scale, pixelFormat, colorSpaceIDData]) } private func metaData() -> Data { let modifiedDate = int32Data(0) let layout = int32Data(self.layout) let nameData = self.imageName.padded(count: 128) return concatData([modifiedDate, layout, nameData]) } private func bitmapInfo(payloadLength: Int) -> Data { let bitmapCount = int32Data(1) let reserved = int32Data(0) let payloadSize = int32Data(payloadLength) return concatData([bitmapCount, reserved, payloadSize]) } }
61d65d5e4ac26de109e1e3dc2424e142
29.681319
111
0.577006
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Storage/SQL/BrowserDB.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared private let log = Logger.syncLogger public typealias Args = [Any?] open class BrowserDB { fileprivate let db: SwiftData public let databasePath: String // SQLITE_MAX_VARIABLE_NUMBER = 999 by default. This controls how many ?s can // appear in a query string. public static let MaxVariableNumber = 999 public init(filename: String, schema: Schema, files: FileAccessor) { log.debug("Initializing BrowserDB: \(filename).") self.databasePath = URL(fileURLWithPath: (try! files.getAndEnsureDirectory())).appendingPathComponent(filename).path self.db = SwiftData(filename: self.databasePath, schema: schema, files: files) } // Returns the SQLite version for debug purposes. public func sqliteVersion() -> Deferred<Maybe<String>> { return withConnection { connection -> String in let result = connection.executeQueryUnsafe( "SELECT sqlite_version()", factory: { row -> String in return row[0] as? String ?? "" }, withArgs: nil) return result.asArray().first ?? "" } } // Returns the SQLite compile_options for debug purposes. public func sqliteCompileOptions() -> Deferred<Maybe<[String]>> { return withConnection { connection -> [String] in let result = connection.executeQueryUnsafe( "PRAGMA compile_options", factory: { row -> String in return row[0] as? String ?? "" }, withArgs: nil) return result.asArray().filter({ !$0.isEmpty }) } } // Returns the SQLite secure_delete setting for debug purposes. public func sqliteSecureDelete() -> Deferred<Maybe<Int>> { return withConnection { connection -> Int in let result = connection.executeQueryUnsafe( "PRAGMA secure_delete", factory: { row -> Int in return row[0] as? Int ?? 0 }, withArgs: nil) return result.asArray().first ?? 0 } } // For testing purposes or other cases where we want to ensure that this `BrowserDB` // instance has been initialized (schema is created/updated). public func touch() -> Success { return withConnection { connection -> Void in guard connection as? ConcreteSQLiteDBConnection != nil else { throw DatabaseError(description: "Could not establish a database connection") } } } /* * Opening a WAL-using database with a hot journal cannot complete in read-only mode. * The supported mechanism for a read-only query against a WAL-using SQLite database is to use PRAGMA query_only, * but this isn't all that useful for us, because we have a mixed read/write workload. */ @discardableResult func withConnection<T>(flags: SwiftData.Flags = .readWriteCreate, _ callback: @escaping (_ connection: SQLiteDBConnection) throws -> T) -> Deferred<Maybe<T>> { return db.withConnection(flags, callback) } func transaction<T>(_ callback: @escaping (_ connection: SQLiteDBConnection) throws -> T) -> Deferred<Maybe<T>> { return db.transaction(callback) } @discardableResult func vacuum() -> Success { log.debug("Vacuuming a BrowserDB.") return withConnection({ connection -> Void in try connection.vacuum() }) } @discardableResult func checkpoint() -> Success { log.debug("Checkpointing a BrowserDB.") return transaction { connection in connection.checkpoint() } } public class func varlist(_ count: Int) -> String { return "(" + Array(repeating: "?", count: count).joined(separator: ", ") + ")" } enum InsertOperation: String { case Insert = "INSERT" case Replace = "REPLACE" case InsertOrIgnore = "INSERT OR IGNORE" case InsertOrReplace = "INSERT OR REPLACE" case InsertOrRollback = "INSERT OR ROLLBACK" case InsertOrAbort = "INSERT OR ABORT" case InsertOrFail = "INSERT OR FAIL" } /** * Insert multiple sets of values into the given table. * * Assumptions: * 1. The table exists and contains the provided columns. * 2. Every item in `values` is the same length. * 3. That length is the same as the length of `columns`. * 4. Every value in each element of `values` is non-nil. * * If there are too many items to insert, multiple individual queries will run * in sequence. * * A failure anywhere in the sequence will cause immediate return of failure, but * will not roll back — use a transaction if you need one. */ func bulkInsert(_ table: String, op: InsertOperation, columns: [String], values: [Args]) -> Success { // Note that there's a limit to how many ?s can be in a single query! // So here we execute 999 / (columns * rows) insertions per query. // Note that we can't use variables for the column names, so those don't affect the count. if values.isEmpty { log.debug("No values to insert.") return succeed() } let variablesPerRow = columns.count // Sanity check. assert(values[0].count == variablesPerRow) let cols = columns.joined(separator: ", ") let queryStart = "\(op.rawValue) INTO \(table) (\(cols)) VALUES " let varString = BrowserDB.varlist(variablesPerRow) let insertChunk: ([Args]) -> Success = { vals -> Success in let valuesString = Array(repeating: varString, count: vals.count).joined(separator: ", ") let args: Args = vals.flatMap { $0 } return self.run(queryStart + valuesString, withArgs: args) } let rowCount = values.count if (variablesPerRow * rowCount) < BrowserDB.MaxVariableNumber { return insertChunk(values) } log.debug("Splitting bulk insert across multiple runs. I hope you started a transaction!") let rowsPerInsert = (999 / variablesPerRow) let chunks = chunk(values, by: rowsPerInsert) log.debug("Inserting in \(chunks.count) chunks.") // There's no real reason why we can't pass the ArraySlice here, except that I don't // want to keep fighting Swift. return walk(chunks, f: { insertChunk(Array($0)) }) } func write(_ sql: String, withArgs args: Args? = nil) -> Deferred<Maybe<Int>> { return withConnection { connection -> Int in try connection.executeChange(sql, withArgs: args) let modified = connection.numberOfRowsModified log.debug("Modified rows: \(modified).") return modified } } public func forceClose() { db.forceClose() } public func reopenIfClosed() { db.reopenIfClosed() } public func run(_ sql: String, withArgs args: Args? = nil) -> Success { return run([(sql, args)]) } func run(_ commands: [String]) -> Success { return run(commands.map { (sql: $0, args: nil) }) } /** * Runs an array of SQL commands. Note: These will all run in order in a transaction and will block * the caller's thread until they've finished. If any of them fail the operation will abort (no more * commands will be run) and the transaction will roll back, returning a DatabaseError. */ func run(_ commands: [(sql: String, args: Args?)]) -> Success { if commands.isEmpty { return succeed() } return transaction { connection -> Void in for (sql, args) in commands { try connection.executeChange(sql, withArgs: args) } } } public func runQuery<T>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T) -> Deferred<Maybe<Cursor<T>>> { return withConnection { connection -> Cursor<T> in connection.executeQuery(sql, factory: factory, withArgs: args) } } public func runQueryConcurrently<T>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T) -> Deferred<Maybe<Cursor<T>>> { return withConnection(flags: .readOnly) { connection -> Cursor<T> in connection.executeQuery(sql, factory: factory, withArgs: args) } } func runQueryUnsafe<T, U>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T, block: @escaping (Cursor<T>) throws -> U) -> Deferred<Maybe<U>> { return withConnection { connection -> U in let cursor = connection.executeQueryUnsafe(sql, factory: factory, withArgs: args) defer { cursor.close() } return try block(cursor) } } func queryReturnsResults(_ sql: String, args: Args? = nil) -> Deferred<Maybe<Bool>> { return runQuery(sql, args: args, factory: { _ in true }) >>== { deferMaybe($0[0] ?? false) } } func queryReturnsNoResults(_ sql: String, args: Args? = nil) -> Deferred<Maybe<Bool>> { return runQuery(sql, args: nil, factory: { _ in false }) >>== { deferMaybe($0[0] ?? true) } } }
d69d26025e92fe26e6b09d9fd01a9733
37.342742
182
0.609317
false
false
false
false
pmtao/SwiftUtilityFramework
refs/heads/master
SwiftUtilityFramework/Foundation/Text/TextReader.swift
mit
1
// // TextReader.swift // SwiftUtilityFramework // // Created by Meler Paine on 2019/1/18. // Copyright © 2019 SinkingSoul. All rights reserved. // import Foundation import Speech public class TextReader { weak var synthesizerDelegate: AVSpeechSynthesizerDelegate? public var syntesizer = AVSpeechSynthesizer() public init(synthesizerDelegate: AVSpeechSynthesizerDelegate) { self.synthesizerDelegate = synthesizerDelegate syntesizer.delegate = synthesizerDelegate } public func readText(_ text: String) { let textLanguage = TextTagger.decideTextLanguage(text) let isEnglishWord = TextTagger.englishWordDetect(text) let voices = AVSpeechSynthesisVoice.speechVoices() let utterance = AVSpeechUtterance(string: text) var zh_voices:[AVSpeechSynthesisVoice] = [] var enGB_voices:[AVSpeechSynthesisVoice] = [] for voice in voices { if voice.language == "en-GB" && voice.name.hasPrefix("Daniel") { enGB_voices.append(voice) } if voice.language.hasPrefix("zh") { zh_voices.append(voice) } } var speechVoice = AVSpeechSynthesisVoice() if isEnglishWord { speechVoice = enGB_voices[0] } if textLanguage.hasPrefix("zh") { speechVoice = zh_voices[0] } utterance.voice = speechVoice utterance.rate = 0.5; syntesizer.speak(utterance) } }
92b7427e5c11ffc81b6587ae731112bf
27.851852
76
0.615533
false
false
false
false
drinkapoint/DrinkPoint-iOS
refs/heads/master
DrinkPoint/DrinkPoint/Games/Plink/PlinkDefined.swift
mit
1
// // PlinkDefined.swift // DrinkPoint // // Created by Paul Kirk Adams on 6/25/16. // Copyright © 2016 Paul Kirk Adams. All rights reserved. // import Foundation import CoreGraphics let DefinedScreenWidth: CGFloat = 1536 let DefinedScreenHeight: CGFloat = 2048 enum GameSceneChildName: String { case FingerName = "Finger" case GlassAName = "GlassA" case GlassBName = "GlassB" case GlassCName = "GlassC" case ScoreName = "Score" case HealthName = "Health" case GameOverLayerName = "GameOver" } enum GameSceneActionKey: String { case WalkAction = "walk" case GrowAudioAction = "grow_audio" case GrowAction = "grow" case ScaleAction = "scale" } enum GameSceneEffectAudioName: String { case GlassBulletAudioName = "GlassBullet.wav" case GlassHitAudioName = "GlassHit.wav" case FingerBulletAudioName = "FingerBullet.wav" case FingerHitAudioName = "FingerHit.wav" } enum GameSceneZposition: CGFloat { case BackgroundZposition = 0 case FingerZposition = 10 case GlassAZposition = 20 case GlassBZposition = 30 case GlassCZposition = 40 }
9f9fd6794d60df58510ae3381ce9910e
26.888889
58
0.637959
false
false
false
false
steelwheels/KiwiComponents
refs/heads/master
UnitTest/OSX/ConsoleWindow/AppDelegate.swift
lgpl-2.1
1
/** * @file AppDelegate.swift * @brief Define Appdelegate class * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import KiwiComponents import Canary import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { private var mMainWindow: NSWindowController? = nil func applicationWillFinishLaunching(_ notification: Notification) { let app = KMApplication.shared /* Open console window to get console */ app.openConsoleWindow() /* Open main window */ let console = app.console mMainWindow = KMLoadWindow(ambFile: "main_window", console: console) if let mwindow = mMainWindow { mwindow.showWindow(nil) } } func applicationDidFinishLaunching(_ aNotification: Notification) { /* Open console window to get console */ //KMApplication.shared.openConsoleWindow() } func applicationWillTerminate(_ aNotification: Notification) { } }
a8de3a460ca45c8400e851c6e2b12122
20.761905
70
0.7407
false
false
false
false
allbto/Swiftility
refs/heads/master
Swiftility/Sources/Core/GCD.swift
mit
2
// // GCD.swift // Swiftility // // Created by Allan Barbato on 10/23/15. // Copyright © 2015 Allan Barbato. All rights reserved. // import Foundation public typealias DispatchClosure = () -> Void // TODO: Tests // MARK: - Async /// Convenience call to dispatch_async public func async(queue: DispatchQueue = .global(qos: .background), execute closure: @escaping DispatchClosure) { queue.async(execute: closure) } /// Convenience call to async(queue: .main) public func async_main(_ closure: @escaping DispatchClosure) { async(queue: .main, execute: closure) } // MARK: - After / Delay /// Convenience call to dispatch_after (time is in seconds) public func after(_ delay: TimeInterval, queue: DispatchQueue = .main, execute closure: @escaping DispatchClosure) { queue.asyncAfter( deadline: .now() + delay, execute: closure ) } /// Same as after public func delay(_ delay: TimeInterval, queue: DispatchQueue = .main, execute closure: @escaping DispatchClosure) { after(delay, queue: queue, execute: closure) } // MARK: - Once fileprivate extension DispatchQueue { static var _onceTracker = [String]() } /** Executes a block of code, associated with a unique token, only once. The code is thread safe and will only execute the code once even in the presence of multithreaded calls. - parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID - parameter execute: Closure to execute once */ public func once(token: String, execute closure: DispatchClosure) { objc_sync_enter(DispatchQueue.self); defer { objc_sync_exit(DispatchQueue.self) } if DispatchQueue._onceTracker.contains(token) { return } DispatchQueue._onceTracker.append(token) closure() } // MARK: - Debounce /** Debounce will fire method when delay passed, but if there was request before that, then it invalidates the previous method and uses only the last - parameter delay: delay before each debounce - parameter queue: =.main; Queue to fire to - parameter action: closure called when debouncing - returns: closure to call to fire the debouncing */ public func debounce<T>(_ delay: TimeInterval, queue: DispatchQueue = .main, action: @escaping (T) -> Void) -> (T) -> Void { var lastCall: Int = 0 return { t in // Increase call counter and invalidate the call if it is not the last one lastCall += 1 let currentCall = lastCall queue.asyncAfter( deadline: .now() + delay, execute: { if lastCall == currentCall { action(t) } } ) } }
de040082fcb8610192494d6b5e66d9c3
25.411765
146
0.667038
false
false
false
false
blokadaorg/blokada
refs/heads/main
Distrib/KeychainSwiftDistrib.swift
mit
3
// // Keychain helper for iOS/Swift. // // https://github.com/evgenyneu/keychain-swift // // This file was automatically generated by combining multiple Swift source files. // // ---------------------------- // // KeychainSwift.swift // // ---------------------------- import Security import Foundation /** A collection of helper functions for saving text and data in the keychain. */ open class KeychainSwift { var lastQueryParameters: [String: Any]? // Used by the unit tests /// Contains result code from the last operation. Value is noErr (0) for a successful result. open var lastResultCode: OSStatus = noErr var keyPrefix = "" // Can be useful in test. /** Specify an access group that will be used to access keychain items. Access groups can be used to share keychain items between applications. When access group value is nil all application access groups are being accessed. Access group name is used by all functions: set, get, delete and clear. */ open var accessGroup: String? /** Specifies whether the items can be synchronized with other devices through iCloud. Setting this property to true will add the item to other devices with the `set` method and obtain synchronizable items with the `get` command. Deleting synchronizable items will remove them from all devices. In order for keychain synchronization to work the user must enable "Keychain" in iCloud settings. Does not work on macOS. */ open var synchronizable: Bool = false private let lock = NSLock() /// Instantiate a KeychainSwift object public init() { } /** - parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain. */ public init(keyPrefix: String) { self.keyPrefix = keyPrefix } /** Stores the text value in the keychain item under the given key. - parameter key: Key under which the text value is stored in the keychain. - parameter value: Text string to be written to the keychain. - parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user. - returns: True if the text was successfully written to the keychain. */ @discardableResult open func set(_ value: String, forKey key: String, withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool { if let value = value.data(using: String.Encoding.utf8) { return set(value, forKey: key, withAccess: access) } return false } /** Stores the data in the keychain item under the given key. - parameter key: Key under which the data is stored in the keychain. - parameter value: Data to be written to the keychain. - parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user. - returns: True if the text was successfully written to the keychain. */ @discardableResult open func set(_ value: Data, forKey key: String, withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool { // The lock prevents the code to be run simultaneously // from multiple threads which may result in crashing lock.lock() defer { lock.unlock() } deleteNoLock(key) // Delete any existing key before saving it let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value let prefixedKey = keyWithPrefix(key) var query: [String : Any] = [ KeychainSwiftConstants.klass : kSecClassGenericPassword, KeychainSwiftConstants.attrAccount : prefixedKey, KeychainSwiftConstants.valueData : value, KeychainSwiftConstants.accessible : accessible ] query = addAccessGroupWhenPresent(query) query = addSynchronizableIfRequired(query, addingItems: true) lastQueryParameters = query lastResultCode = SecItemAdd(query as CFDictionary, nil) return lastResultCode == noErr } /** Stores the boolean value in the keychain item under the given key. - parameter key: Key under which the value is stored in the keychain. - parameter value: Boolean to be written to the keychain. - parameter withAccess: Value that indicates when your app needs access to the value in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user. - returns: True if the value was successfully written to the keychain. */ @discardableResult open func set(_ value: Bool, forKey key: String, withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool { let bytes: [UInt8] = value ? [1] : [0] let data = Data(bytes) return set(data, forKey: key, withAccess: access) } /** Retrieves the text value from the keychain that corresponds to the given key. - parameter key: The key that is used to read the keychain item. - returns: The text value from the keychain. Returns nil if unable to read the item. */ open func get(_ key: String) -> String? { if let data = getData(key) { if let currentString = String(data: data, encoding: .utf8) { return currentString } lastResultCode = -67853 // errSecInvalidEncoding } return nil } /** Retrieves the data from the keychain that corresponds to the given key. - parameter key: The key that is used to read the keychain item. - parameter asReference: If true, returns the data as reference (needed for things like NEVPNProtocol). - returns: The text value from the keychain. Returns nil if unable to read the item. */ open func getData(_ key: String, asReference: Bool = false) -> Data? { // The lock prevents the code to be run simultaneously // from multiple threads which may result in crashing lock.lock() defer { lock.unlock() } let prefixedKey = keyWithPrefix(key) var query: [String: Any] = [ KeychainSwiftConstants.klass : kSecClassGenericPassword, KeychainSwiftConstants.attrAccount : prefixedKey, KeychainSwiftConstants.matchLimit : kSecMatchLimitOne ] if asReference { query[KeychainSwiftConstants.returnReference] = kCFBooleanTrue } else { query[KeychainSwiftConstants.returnData] = kCFBooleanTrue } query = addAccessGroupWhenPresent(query) query = addSynchronizableIfRequired(query, addingItems: false) lastQueryParameters = query var result: AnyObject? lastResultCode = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } if lastResultCode == noErr { return result as? Data } return nil } /** Retrieves the boolean value from the keychain that corresponds to the given key. - parameter key: The key that is used to read the keychain item. - returns: The boolean value from the keychain. Returns nil if unable to read the item. */ open func getBool(_ key: String) -> Bool? { guard let data = getData(key) else { return nil } guard let firstBit = data.first else { return nil } return firstBit == 1 } /** Deletes the single keychain item specified by the key. - parameter key: The key that is used to delete the keychain item. - returns: True if the item was successfully deleted. */ @discardableResult open func delete(_ key: String) -> Bool { // The lock prevents the code to be run simultaneously // from multiple threads which may result in crashing lock.lock() defer { lock.unlock() } return deleteNoLock(key) } /** Return all keys from keychain - returns: An string array with all keys from the keychain. */ public var allKeys: [String] { var query: [String: Any] = [ KeychainSwiftConstants.klass : kSecClassGenericPassword, KeychainSwiftConstants.returnData : true, KeychainSwiftConstants.returnAttributes: true, KeychainSwiftConstants.returnReference: true, KeychainSwiftConstants.matchLimit: KeychainSwiftConstants.secMatchLimitAll ] query = addAccessGroupWhenPresent(query) query = addSynchronizableIfRequired(query, addingItems: false) var result: AnyObject? let lastResultCode = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } if lastResultCode == noErr { return (result as? [[String: Any]])?.compactMap { $0[KeychainSwiftConstants.attrAccount] as? String } ?? [] } return [] } /** Same as `delete` but is only accessed internally, since it is not thread safe. - parameter key: The key that is used to delete the keychain item. - returns: True if the item was successfully deleted. */ @discardableResult func deleteNoLock(_ key: String) -> Bool { let prefixedKey = keyWithPrefix(key) var query: [String: Any] = [ KeychainSwiftConstants.klass : kSecClassGenericPassword, KeychainSwiftConstants.attrAccount : prefixedKey ] query = addAccessGroupWhenPresent(query) query = addSynchronizableIfRequired(query, addingItems: false) lastQueryParameters = query lastResultCode = SecItemDelete(query as CFDictionary) return lastResultCode == noErr } /** Deletes all Keychain items used by the app. Note that this method deletes all items regardless of the prefix settings used for initializing the class. - returns: True if the keychain items were successfully deleted. */ @discardableResult open func clear() -> Bool { // The lock prevents the code to be run simultaneously // from multiple threads which may result in crashing lock.lock() defer { lock.unlock() } var query: [String: Any] = [ kSecClass as String : kSecClassGenericPassword ] query = addAccessGroupWhenPresent(query) query = addSynchronizableIfRequired(query, addingItems: false) lastQueryParameters = query lastResultCode = SecItemDelete(query as CFDictionary) return lastResultCode == noErr } /// Returns the key with currently set prefix. func keyWithPrefix(_ key: String) -> String { return "\(keyPrefix)\(key)" } func addAccessGroupWhenPresent(_ items: [String: Any]) -> [String: Any] { guard let accessGroup = accessGroup else { return items } var result: [String: Any] = items result[KeychainSwiftConstants.accessGroup] = accessGroup return result } /** Adds kSecAttrSynchronizable: kSecAttrSynchronizableAny` item to the dictionary when the `synchronizable` property is true. - parameter items: The dictionary where the kSecAttrSynchronizable items will be added when requested. - parameter addingItems: Use `true` when the dictionary will be used with `SecItemAdd` method (adding a keychain item). For getting and deleting items, use `false`. - returns: the dictionary with kSecAttrSynchronizable item added if it was requested. Otherwise, it returns the original dictionary. */ func addSynchronizableIfRequired(_ items: [String: Any], addingItems: Bool) -> [String: Any] { if !synchronizable { return items } var result: [String: Any] = items result[KeychainSwiftConstants.attrSynchronizable] = addingItems == true ? true : kSecAttrSynchronizableAny return result } } // ---------------------------- // // TegKeychainConstants.swift // // ---------------------------- import Foundation import Security /// Constants used by the library public struct KeychainSwiftConstants { /// Specifies a Keychain access group. Used for sharing Keychain items between apps. public static var accessGroup: String { return toString(kSecAttrAccessGroup) } /** A value that indicates when your app needs access to the data in a keychain item. The default value is AccessibleWhenUnlocked. For a list of possible values, see KeychainSwiftAccessOptions. */ public static var accessible: String { return toString(kSecAttrAccessible) } /// Used for specifying a String key when setting/getting a Keychain value. public static var attrAccount: String { return toString(kSecAttrAccount) } /// Used for specifying synchronization of keychain items between devices. public static var attrSynchronizable: String { return toString(kSecAttrSynchronizable) } /// An item class key used to construct a Keychain search dictionary. public static var klass: String { return toString(kSecClass) } /// Specifies the number of values returned from the keychain. The library only supports single values. public static var matchLimit: String { return toString(kSecMatchLimit) } /// A return data type used to get the data from the Keychain. public static var returnData: String { return toString(kSecReturnData) } /// Used for specifying a value when setting a Keychain value. public static var valueData: String { return toString(kSecValueData) } /// Used for returning a reference to the data from the keychain public static var returnReference: String { return toString(kSecReturnPersistentRef) } /// A key whose value is a Boolean indicating whether or not to return item attributes public static var returnAttributes : String { return toString(kSecReturnAttributes) } /// A value that corresponds to matching an unlimited number of items public static var secMatchLimitAll : String { return toString(kSecMatchLimitAll) } static func toString(_ value: CFString) -> String { return value as String } } // ---------------------------- // // KeychainSwiftAccessOptions.swift // // ---------------------------- import Security /** These options are used to determine when a keychain item should be readable. The default value is AccessibleWhenUnlocked. */ public enum KeychainSwiftAccessOptions { /** The data in the keychain item can be accessed only while the device is unlocked by the user. This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups. This is the default value for keychain items added without explicitly setting an accessibility constant. */ case accessibleWhenUnlocked /** The data in the keychain item can be accessed only while the device is unlocked by the user. This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present. */ case accessibleWhenUnlockedThisDeviceOnly /** The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user. After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups. */ case accessibleAfterFirstUnlock /** The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user. After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present. */ case accessibleAfterFirstUnlockThisDeviceOnly /** The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device. This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted. */ case accessibleWhenPasscodeSetThisDeviceOnly static var defaultOption: KeychainSwiftAccessOptions { return .accessibleWhenUnlocked } var value: String { switch self { case .accessibleWhenUnlocked: return toString(kSecAttrAccessibleWhenUnlocked) case .accessibleWhenUnlockedThisDeviceOnly: return toString(kSecAttrAccessibleWhenUnlockedThisDeviceOnly) case .accessibleAfterFirstUnlock: return toString(kSecAttrAccessibleAfterFirstUnlock) case .accessibleAfterFirstUnlockThisDeviceOnly: return toString(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) case .accessibleWhenPasscodeSetThisDeviceOnly: return toString(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly) } } func toString(_ value: CFString) -> String { return KeychainSwiftConstants.toString(value) } }
e4023f06dd3595656fb9ecd1dd5fd10b
33.433071
377
0.713526
false
false
false
false
raptorxcz/Rubicon
refs/heads/main
Generator/Generator/TearDownInteractor.swift
mit
1
// // TearDownInteractor.swift // Generator // // Created by Kryštof Matěj on 19.05.2022. // Copyright © 2022 Kryštof Matěj. All rights reserved. // import SwiftSyntax import SwiftSyntaxBuilder import SwiftSyntaxParser public final class TearDownInteractor { private let nilableVariablesParser: NilableVariablesParser public init(nilableVariablesParser: NilableVariablesParser) { self.nilableVariablesParser = nilableVariablesParser } public func execute(text: String, spacing: Int) throws -> String { let file = try SyntaxParser.parse(source: text) let classRewriter = ClassRewriter( nilableVariablesParser: nilableVariablesParser, spacing: spacing ) return classRewriter.visit(file.root).description } } private class ClassRewriter: SyntaxRewriter { private let nilableVariablesParser: NilableVariablesParser private let spacing: Int init(nilableVariablesParser: NilableVariablesParser, spacing: Int) { self.nilableVariablesParser = nilableVariablesParser self.spacing = spacing } override func visit(_ node: ClassDeclSyntax) -> DeclSyntax { guard isRelevantClass(node: node) else { return super.visit(node) } var node = node if let index = firstIndex(node: node, methodName: "tearDown") { let newMembers = node.members.members.removing(childAt: index) node.members = node.members.withMembers(newMembers) } let nilableVariables = nilableVariablesParser.parse(from: node) let tearDownMethod = makeTearDownMethod(variables: nilableVariables) if let index = firstIndex(node: node, methodName: "setUp") { let newMembers = node.members.members.inserting(tearDownMethod, at: index + 1) node.members = node.members.withMembers(newMembers) } else if let index = firstIndex(node: node, methodName: "setUpWithError") { let newMembers = node.members.members.inserting(tearDownMethod, at: index + 1) node.members = node.members.withMembers(newMembers) } else { node.members = node.members.addMember(tearDownMethod) } return super.visit(node) } private func isRelevantClass(node: ClassDeclSyntax) -> Bool { guard node.identifier.text.hasSuffix("Tests") else { return false } guard firstIndex(node: node, methodName: "tearDownWithError") == nil else { return false } return true } private func makeTearDownMethod(variables: [String]) -> MemberDeclListItemSyntax { var modifiers = SyntaxFactory.makeModifierList([ SyntaxFactory.makeDeclModifier(name: .identifier("override"), detailLeftParen: nil, detail: nil, detailRightParen: nil), ]) modifiers.trailingTrivia = .spaces(1) let leftBrace = SyntaxFactory.makeLeftBraceToken(leadingTrivia: .spaces(1)) let rightBrace = SyntaxFactory.makeRightBraceToken(leadingTrivia: Trivia(pieces: [.newlines(1), .spaces(spacing)])) let input = SyntaxFactory.makeParameterClause( leftParen: .leftParen, parameterList: SyntaxFactory.makeFunctionParameterList([]), rightParen: .rightParen ) let signature = SyntaxFactory.makeFunctionSignature(input: input, asyncOrReasyncKeyword: nil, throwsOrRethrowsKeyword: nil, output: nil) var function = SyntaxFactory.makeFunctionDecl( attributes: nil, modifiers: modifiers, funcKeyword: .func, identifier: .identifier("tearDown"), genericParameterClause: nil, signature: signature, genericWhereClause: nil, body: SyntaxFactory.makeCodeBlock( leftBrace: leftBrace, statements: SyntaxFactory.makeCodeBlockItemList([makeSuperRow()] + variables.map(makeRow)), rightBrace: rightBrace ) ) function.leadingTrivia = Trivia(pieces: [.newlines(2), .spaces(spacing)]) return SyntaxFactory.makeMemberDeclListItem( decl: DeclSyntax(function), semicolon: nil ) } private func makeSuperRow() -> CodeBlockItemSyntax { var superExpression = SyntaxFactory.makeSuperRefExpr(superKeyword: .super) superExpression.trailingTrivia = nil var memberExpression = SyntaxFactory.makeMemberAccessExpr(base: ExprSyntax(superExpression), dot: .period, name: .identifier("tearDown"), declNameArguments: nil) memberExpression.leadingTrivia = Trivia(pieces: [.newlines(1), .spaces(2 * spacing)]) let syntax = SyntaxFactory.makeFunctionCallExpr( calledExpression: ExprSyntax(memberExpression), leftParen: .leftParen, argumentList: SyntaxFactory.makeTupleExprElementList([]), rightParen: .rightParen, trailingClosure: nil, additionalTrailingClosures: nil ) return SyntaxFactory.makeCodeBlockItem( item: Syntax(syntax), semicolon: nil, errorTokens: nil ) } private func makeRow(variable: String) -> CodeBlockItemSyntax { let variableSyntax = SyntaxFactory.makeIdentifierExpr(identifier: SyntaxFactory.makeIdentifier(variable, leadingTrivia: Trivia(pieces: [.newlines(1), .spaces(2 * spacing)])), declNameArguments: nil) var assignmentSyntax = SyntaxFactory.makeAssignmentExpr(assignToken: .equal) assignmentSyntax.trailingTrivia = .spaces(1) var nilSyntax = SyntaxFactory.makeNilLiteralExpr(nilKeyword: .nil) nilSyntax.trailingTrivia = nil let syntax = SyntaxFactory.makeSequenceExpr( elements: SyntaxFactory.makeExprList([ ExprSyntax(variableSyntax), ExprSyntax(assignmentSyntax), ExprSyntax(nilSyntax), ]) ) return SyntaxFactory.makeCodeBlockItem( item: Syntax(syntax), semicolon: nil, errorTokens: nil ) } private func firstIndex(node: ClassDeclSyntax, methodName: String) -> Int? { if let (index, _) = node.members.members.enumerated().first(where: { isMethod($1, name: methodName) }) { return index } else { return nil } } private func isMethod(_ member: MemberDeclListItemSyntax, name: String) -> Bool { guard let function = member.decl.as(FunctionDeclSyntax.self) else { return false } if function.modifiers?.contains(where: { $0.name.text == "static" }) == true { return false } return function.identifier.text == name } }
db67f6dff5314340877de0b6e9e4f636
38.55814
206
0.65241
false
false
false
false