repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Isuru-Nanayakkara/IJProgressView
IJProgressView/IJProgressView/WithNavBarViewController.swift
1
1638
// // WithNavBarViewController.swift // IJProgressView // // Created by Isuru Nanayakkara on 7/24/19. // Copyright © 2019 Appex. All rights reserved. // import UIKit class WithNavBarViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() IJProgressView.shared.showProgressView() setCloseTimer() } @objc func close() { IJProgressView.shared.hideProgressView() } func setCloseTimer() { _ = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(close), userInfo: nil, repeats: false) } @IBOutlet weak var redSlider: UISlider! @IBOutlet weak var greenSlider: UISlider! @IBOutlet weak var blueSlider: UISlider! @IBOutlet weak var alphaSlider: UISlider! @IBAction func showButtonTapped(_ sender: UIButton) { IJProgressView.shared.backgroundColor = UIColor.init(red: CGFloat(redSlider.value/255.0), green: CGFloat(greenSlider.value/255.0), blue: CGFloat(blueSlider.value/255.0), alpha: CGFloat(alphaSlider!.value)) IJProgressView.shared.showProgressView() setCloseTimer() } @IBAction func leftButtonTapped(_ sender: UIBarButtonItem) { print(#function) let size = IJProgressView.shared.size IJProgressView.shared.size = CGSize(width: size.width - 5, height: size.height - 5) } @IBAction func rightButtonTapped(_ sender: UIBarButtonItem) { print(#function) let size = IJProgressView.shared.size IJProgressView.shared.size = CGSize(width: size.width + 5, height: size.height + 5) } }
mit
4ccbbd478d0b7e887fe7dec250a90f2f
33.104167
213
0.675015
4.319261
false
false
false
false
irshadqureshi/IQCacheResources
IQCacheResources/Classes/DiscardableData.swift
1
953
// // DiscardableData.swift // Pods // // Created by Irshad on 15/07/17. // // import Foundation open class DiscardableData: NSObject, NSDiscardableContent { private(set) public var data : Data? var accessedCounter : UInt = 0 public init(data:Data) { self.data = data } public func beginContentAccess() -> Bool { if data == nil { return false } accessedCounter += 1 return true } public func endContentAccess() { if accessedCounter > 0 { accessedCounter -= 1 } } public func discardContentIfPossible() { if accessedCounter == 0 { data = nil } } public func isContentDiscarded() -> Bool { return data == nil ? true : false } }
mit
9d5737fae3796c285db4555a1470e905
15.431034
60
0.467996
5.015789
false
false
false
false
nathawes/swift
test/SILGen/function_type_conversion.swift
9
4012
// RUN: %target-swift-frontend -emit-silgen -disable-availability-checking -module-name main -enable-subst-sil-function-types-for-function-values %s | %FileCheck %s func generic<T, U>(_ f: @escaping (T) -> U) -> (T) -> U { return f } // CHECK-LABEL: sil {{.*}}4main{{.*}}11sameGeneric func sameGeneric<X, Y, Z>(_: X, _: Y, _ f: @escaping (Z) -> Z) -> (Z) -> Z { // CHECK: bb0({{.*}}, [[F:%[0-9]+]] : @guaranteed $@callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1 for <Z, Z> // Similarly generic types should be directly substitutable // CHECK: [[GENERIC:%.*]] = function_ref @{{.*}}4main{{.*}}7generic // CHECK: [[RET:%.*]] = apply [[GENERIC]]<Z, Z>([[F]]) // CHECK: return [[RET]] return generic(f) } // CHECK-LABEL: sil {{.*}}4main{{.*}}16concreteIndirect func concreteIndirect(_ f: @escaping (Any) -> Any) -> (Any) -> Any { // CHECK: bb0([[F:%[0-9]+]] : @guaranteed $@callee_guaranteed (@in_guaranteed Any) -> @out Any) // Any is passed indirectly, but is a concrete type, so we need to convert // to the generic abstraction level // CHECK: [[F2:%.*]] = copy_value [[F]] // CHECK: [[GENERIC_F:%.*]] = convert_function [[F2]] : {{.*}} to $@callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1 for <Any, Any> // CHECK: [[GENERIC:%.*]] = function_ref @{{.*}}4main{{.*}}7generic // CHECK: [[GENERIC_RET:%.*]] = apply [[GENERIC]]<Any, Any>([[GENERIC_F]]) // CHECK: [[RET:%.*]] = convert_function [[GENERIC_RET]] : {{.*}} // CHECK: return [[RET]] return generic(f) } // CHECK-LABEL: sil {{.*}}4main{{.*}}14concreteDirect func concreteDirect(_ f: @escaping (Int) -> String) -> (Int) -> String { // CHECK: bb0([[F:%[0-9]+]] : @guaranteed $@callee_guaranteed (Int) -> @owned String): // Int and String are passed and returned directly, so we need both // thunking and conversion to the substituted form // CHECK: [[F2:%.*]] = copy_value [[F]] // CHECK: [[REABSTRACT_F:%.*]] = partial_apply {{.*}}([[F2]]) // CHECK: [[GENERIC_F:%.*]] = convert_function [[REABSTRACT_F]] : {{.*}} to $@callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1 for <Int, String> // CHECK: [[GENERIC:%.*]] = function_ref @{{.*}}4main{{.*}}7generic // CHECK: [[GENERIC_RET:%.*]] = apply [[GENERIC]]<Int, String>([[GENERIC_F]]) // CHECK: [[REABSTRACT_RET:%.*]] = convert_function [[GENERIC_RET]] : {{.*}} // CHECK: [[RET:%.*]] = partial_apply {{.*}}([[REABSTRACT_RET]]) // CHECK: return [[RET]] return generic(f) } func genericTakesFunction<T, U>( _ f: @escaping ((T) -> U) -> (T) -> U ) -> ((T) -> U) -> (T) -> U { return f } func sameGenericTakesFunction<T>( _ f: @escaping ((T) -> T) -> (T) -> T ) -> ((T) -> T) -> (T) -> T { return genericTakesFunction(f) } // CHECK-LABEL: sil {{.*}}4main29concreteIndirectTakesFunction func concreteIndirectTakesFunction( _ f: @escaping ((Any) -> Any) -> (Any) -> Any ) -> ((Any) -> Any) -> (Any) -> Any { // CHECK: bb0([[F:%[0-9]+]] : @guaranteed $@callee_guaranteed // Calling convention matches callee, but the representation of the argument // to `f` needs to change, so we still have to thunk // CHECK: [[F2:%.*]] = copy_value [[F]] // CHECK: [[REABSTRACT_F:%.*]] = partial_apply {{.*}}([[F2]]) // CHECK: [[GENERIC_F:%.*]] = convert_function [[REABSTRACT_F]] // CHECK: [[GENERIC:%.*]] = function_ref @{{.*}}4main{{.*}}20genericTakesFunction // CHECK: [[GENERIC_RET:%.*]] = apply [[GENERIC]]<Any, Any>([[GENERIC_F]]) // CHECK: [[REABSTRACT_RET:%.*]] = convert_function [[GENERIC_RET]] : {{.*}} // CHECK: [[RET:%.*]] = partial_apply {{.*}}([[REABSTRACT_RET]]) // CHECK: return [[RET]] return genericTakesFunction(f) } func concreteDirectTakesFunction( _ f: @escaping ((Int) -> String) -> (Int) -> String ) -> ((Int) -> String) -> (Int) -> String { // Int and String are passed and returned directly, so we need both // thunking and conversion to the substituted form return genericTakesFunction(f) }
apache-2.0
9a4a94096d4e36e965e43870d7203aff
48.382716
180
0.584
3.341688
false
false
false
false
OneBusAway/onebusaway-iphone
OneBusAway/ui/map/MapTypePickerController.swift
3
1689
// // MapTypePickerController.swift // OneBusAway // // Created by Aaron Brethorst on 9/15/18. // Copyright © 2018 OneBusAway. All rights reserved. // import UIKit import MapKit import OBAKit class MapTypePickerController: PickerViewController { private let application: OBAApplication public init(application: OBAApplication) { self.application = application super.init(nibName: nil, bundle: nil) let standardRow = OBATableRow(title: NSLocalizedString("map_controller.standard_map_type_title", comment: "Title for Standard Map toggle option.")) { [weak self] _ in self?.updateDefaults(to: .standard) } let hybridRow = OBATableRow(title: NSLocalizedString("map_controller.hybrid_map_type_title", comment: "Title for Hybrid Map toggle option.")) { [weak self] _ in self?.updateDefaults(to: .hybrid) } switch currentMapType { case .standard: standardRow.accessoryType = .checkmark default: hybridRow.accessoryType = .checkmark } self.sections = [OBATableSection(title: nil, rows: [standardRow, hybridRow])] } private var currentMapType: MKMapType { let rawMapType = UInt(bitPattern: application.userDefaults.integer(forKey: OBAMapSelectedTypeDefaultsKey)) return MKMapType(rawValue: rawMapType)! } private func updateDefaults(to value: MKMapType) { let rawValue = Int(bitPattern: value.rawValue) application.userDefaults.set(rawValue, forKey: OBAMapSelectedTypeDefaultsKey) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
4e4efb7040d6a2b5b96ef2459bea95e2
32.098039
174
0.686019
4.489362
false
false
false
false
reactive-swift/Future
Sources/Future/Future+Functional.swift
2
8527
//===--- Future+Functional.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import Foundation import Result import Boilerplate import ExecutionContext public extension Future { @discardableResult public func onComplete(_ callback: @escaping (Result<Value, AnyError>) -> Void) -> Self { return self.onCompleteInternal(callback: callback) } } public extension FutureProtocol { @discardableResult public func onSuccess(_ f: @escaping (Value) -> Void) -> Self { return self.onComplete { (result:Result<Value, AnyError>) in result.analysis(ifSuccess: { value in f(value) }, ifFailure: {_ in}) } } @discardableResult public func onFailure<E : Error>(_ f: @escaping (E) -> Void) -> Self{ return self.onComplete { (result:Result<Value, E>) in result.analysis(ifSuccess: {_ in}, ifFailure: {error in f(error) }) } } @discardableResult public func onFailure(_ f:@escaping (Error) -> Void) -> Self { return self.onComplete { (result:Result<Value, AnyError>) in result.analysis(ifSuccess: {_ in}, ifFailure: {error in f(error.error) }) } } } public extension FutureProtocol { public func map<B>(_ f:@escaping (Value) throws -> B) -> Future<B> { let future = MutableFuture<B>(context: self.context) self.onComplete { (result:Result<Value, AnyError>) in let result = result.flatMap { value -> Result<B, AnyError> in materializeAny { try f(value) } } try! future.complete(result: result) } return future } public func flatMap<B, F : FutureProtocol>(_ f:@escaping (Value) -> F) -> Future<B> where F.Value == B { let future = MutableFuture<B>(context: self.context) self.onComplete { (result:Result<Value, AnyError>) in result.analysis(ifSuccess: { value in let b = f(value) b.onComplete { (result:Result<B, AnyError>) in try! future.complete(result: result) } }, ifFailure: { error in try! future.fail(error: error) }) } return future } public func flatMap<B, E : Error>(_ f:@escaping (Value) -> Result<B, E>) -> Future<B> { let future = MutableFuture<B>(context: self.context) self.onComplete { (result:Result<Value, AnyError>) in result.analysis(ifSuccess: { value in let b = f(value) try! future.complete(result: b) }, ifFailure: { error in try! future.fail(error: error) }) } return future } public func flatMap<B>(_ f:@escaping (Value) -> B?) -> Future<B> { let future = MutableFuture<B>(context: self.context) self.onComplete { (result:Result<Value, AnyError>) in let result:Result<B, AnyError> = result.flatMap { value in guard let b = f(value) else { return Result(error: AnyError(FutureError.MappedNil)) } return Result(value: b) } try! future.complete(result: result) } return future } public func filter(_ f: @escaping (Value)->Bool) -> Future<Value> { let future = MutableFuture<Value>(context: self.context) self.onComplete { (result:Result<Value, AnyError>) in result.analysis(ifSuccess: { value in if f(value) { try! future.success(value: value) } else { try! future.fail(error: FutureError.FilteredOut) } }, ifFailure: { error in try! future.fail(error: error) }) } return future } public func filterNot(_ f:@escaping (Value)->Bool) -> Future<Value> { return self.filter { value in return !f(value) } } public func recover<E : Error>(_ f:@escaping (E) throws ->Value) -> Future<Value> { let future = MutableFuture<Value>(context: self.context) self.onComplete { (result:Result<Value, E>) in let result = result.flatMapError { error in return materializeAny { try f(error) } } //yes, we want to supress double completion here let _ = future.tryComplete(result: result) } // if first one didn't match this one will be called next future.completeWith(future: self) return future } public func recover(_ f:@escaping (Error) throws ->Value) -> Future<Value> { let future = MutableFuture<Value>(context: self.context) self.onComplete { (result:Result<Value, AnyError>) in let result = result.flatMapError { error in return materializeAny { try f(error.error) } } //yes, we want to supress double completion here let _ = future.tryComplete(result: result) } // if first one didn't match this one will be called next future.completeWith(future: self) return future } public func recoverWith<E : Error>(_ f:@escaping (E) -> Future<Value>) -> Future<Value> { let future = MutableFuture<Value>(context: self.context) self.onComplete { (result:Result<Value, AnyError>) in guard let mapped:Result<Value, E> = result.tryAsError() else { try! future.complete(result: result) return } mapped.analysis(ifSuccess: { _ -> Void in try! future.complete(result: result) }, ifFailure: { e in future.completeWith(future: f(e)) }) } return future } public func recoverWith(_ f:@escaping (Error) -> Future<Value>) -> Future<Value> { let future = MutableFuture<Value>(context: self.context) self.onComplete { (result:Result<Value, AnyError>) in guard let mapped:Result<Value, AnyError> = result.tryAsError() else { try! future.complete(result: result) return } mapped.analysis(ifSuccess: { _ -> Void in try! future.complete(result: result) }, ifFailure: { e in future.completeWith(future: f(e.error)) }) } return future } public func zip<B, F : FutureProtocol>(_ f:F) -> Future<(Value, B)> where F.Value == B { let future = MutableFuture<(Value, B)>(context: self.context) self.onComplete { (result:Result<Value, AnyError>) in let context = ExecutionContext.current result.analysis(ifSuccess: { first -> Void in f.onComplete { (result:Result<B, AnyError>) in context.execute { result.analysis(ifSuccess: { second in try! future.success(value: (first, second)) }, ifFailure: { e in try! future.fail(error: e.error) }) } } }, ifFailure: { e in try! future.fail(error: e.error) }) } return future } }
apache-2.0
c69367d30e54c8e9306142bc77e8b7a6
33.522267
108
0.52023
4.790449
false
false
false
false
alexanderedge/European-Sports
EurosportKit/Protocols/StringIdentifiable.swift
1
1023
// // StringIdentifierType.swift // EurosportPlayer // // Created by Alexander Edge on 28/05/2016. import Foundation import CoreData @objc public protocol StringIdentifiable { var identifier: String { get set } } extension Fetchable where Self: NSManagedObject, Self: StringIdentifiable, FetchableType == Self { public static func existingObject(_ identifier: String, inContext context: NSManagedObjectContext) throws -> FetchableType? { let predicate = NSPredicate(format: "identifier == %@", identifier) return try singleObject(in: context, predicate: predicate, sortedBy: nil, ascending: true) } public static func newOrExistingObject(_ identifier: String, inContext context: NSManagedObjectContext) throws -> FetchableType { if let existingObject = try existingObject(identifier, inContext: context) { return existingObject } let newObject = Self(context: context) newObject.identifier = identifier return newObject } }
mit
3b1461c055d9eea539a728032de34406
30.96875
133
0.715543
5.014706
false
false
false
false
cs4278-2015/tinderFood
tinderForFood/LoginViewController.swift
1
9882
// // LoginViewController.swift // tinderForFood // // Created by Edward Yun on 12/3/15. // Copyright © 2015 Edward Yun. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class LoginViewController: UIViewController { private var accessToken = "" let loginSegueIdentifier = "loginSegue" @IBOutlet weak var loginSegmentedControl: UISegmentedControl! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordLabel: UILabel! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var confirmLabel: UILabel! @IBOutlet weak var confirmTextField: UITextField! @IBOutlet weak var loginButton: UIButton! private var loginBool = true override func viewDidLoad() { super.viewDidLoad() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard") view.addGestureRecognizer(tap) } // MARK: Networking (Alamofire) func makeJsonCall(apiCall: String, params: [String: String], completionHandler: (Int, JSON, NSError?) -> ()) { Alamofire.request(.POST, "https://tinder-for-food.herokuapp.com/api/\(apiCall)", parameters: params, encoding: .JSON).responseJSON { response in guard response.result.error == nil else { // got an error in getting the data, need to handle it print("error calling POST on /api/\(apiCall)") print(response.result.error!) return } if let value: AnyObject = response.result.value { // handle the results as JSON, without a bunch of nested if loops let responseJson = JSON(value) completionHandler(response.response!.statusCode, responseJson, response.result.error) } } } func makeCall(apiCall: String, params: [String: String], completionHandler: (Int, NSError?) -> ()) { Alamofire.request(.POST, "https://tinder-for-food.herokuapp.com/api/\(apiCall)", parameters: params, encoding: .JSON).responseString { response in guard response.result.error == nil else { // got an error in getting the data, need to handle it print("error calling POST on /api/\(apiCall)") print(response.result.error!) return } if let value: Int = response.response!.statusCode { // handle the results as JSON, without a bunch of nested if loops completionHandler(value, response.result.error) } } } func checkUsername(username: String, completionHandler: (Int, NSError?) -> ()) { let parameters = ["username": username] makeCall("checkUsername", params: parameters) { responseCode, error in print(responseCode) print(error) completionHandler(responseCode, error) } } func checkEmail(email: String, completionHandler: (Int, NSError?) -> ()) { let parameters = ["email": email] makeCall("checkEmail", params: parameters) { responseCode, error in print(responseCode) print(error) completionHandler(responseCode, error) } } //MARK: Storyboard @IBAction func loginButtonClicked(sender: AnyObject) { if loginBool { login() } else { signup() } } func login() { let username = usernameTextField.text! let email = emailTextField.text! let password = passwordTextField.text! let parameters = ["username": username, "email": email, "password": password] makeJsonCall("login", params: parameters) { responseCode, responseJson, error in print(responseCode) self.accessToken = responseJson["access_token"].stringValue NSUserDefaults.standardUserDefaults().setObject(self.accessToken, forKey: "access_token") NSUserDefaults.standardUserDefaults().synchronize() print(self.accessToken) self.loggedInSuccessfully() } } func signup() { let email = emailTextField.text let username = usernameTextField.text let password = passwordTextField.text let confirm = confirmTextField.text if password != confirm { let alertController = UIAlertController(title: "Oops", message: "Make sure your passwords match!", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } else if password?.characters.count < 5 { let alertController = UIAlertController(title: "Oops", message: "Password must be at least 5 characters", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } else if username?.characters.count < 5 { let alertController = UIAlertController(title: "Oops", message: "Username must be at least 5 characters", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } else if email?.characters.count < 5 { let alertController = UIAlertController(title: "Oops", message: "Email must be at least 5 characters", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } else { checkUsername(username!) { responseCode, error in //TODO: Fix alerts when register fails if responseCode == 200 { self.checkEmail(email!) { responseCode, error in if responseCode == 200 { self.registerUser(username!, email: email!, password: password!) } else { print(error) let alertController = UIAlertController(title: "Oops", message: "Email has already been used. Try a new one.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } } else { print(error) let alertController = UIAlertController(title: "Oops", message: "Username is already taken. Try something different.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } } } func registerUser(username: String, email: String, password: String) { let parameters = ["username": username, "email": email, "password": password] print(parameters) makeJsonCall("register", params: parameters) { responseCode, responseJson, error in print(responseCode) self.accessToken = responseJson["access_token"].stringValue print("SETTING ACCESS_TOKEN") NSUserDefaults.standardUserDefaults().setObject(self.accessToken, forKey: "access_token") NSUserDefaults.standardUserDefaults().synchronize() print("ACCESS TOKEN IS \(NSUserDefaults.standardUserDefaults().objectForKey("access_token"))") print(self.accessToken) self.loggedInSuccessfully() } } func loggedInSuccessfully() { performSegueWithIdentifier(loginSegueIdentifier, sender: self) } @IBAction func segmentChanged(sender: AnyObject) { switch loginSegmentedControl.selectedSegmentIndex { case 0: loginSelected() case 1: signupSelected() default: break } } func loginSelected() { print("login") confirmLabel.hidden = true confirmTextField.hidden = true loginButton.setTitle("Login", forState: .Normal) loginBool = true } func signupSelected() { print("signup") confirmLabel.hidden = false confirmTextField.hidden = false loginButton.setTitle("Signup", forState: .Normal) loginBool = false } func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } }
mit
2f74378aae349ce5e95a6c450097e450
40.516807
154
0.600648
5.604651
false
false
false
false
andrea-prearo/swift-algorithm-data-structures-dojo
SwiftAlgorithmsAndDataStructuresDojo/BinarySearchTree/BinarySearchTree.swift
1
8196
// // BinarySearchTree.swift // SwiftAlgorithmsAndDataStructuresDojo // // Created by Andrea Prearo on 3/21/17. // Copyright © 2017 Andrea Prearo. All rights reserved. // import Foundation /* The `key` property of `BinarySearchTreeNode` will be used for ordering the nodes. This requires `key` to be of `Comparable` type so we can define an ordering for the nodes. */ public class BinarySearchTreeNode<K: Comparable, T: Comparable> { var key: K var value: T var left: BinarySearchTreeNode<K, T>? = nil var right: BinarySearchTreeNode<K, T>? = nil weak var parent: BinarySearchTreeNode<K, T>? = nil public init(key: K, value: T) { self.key = key self.value = value } } // MARK: - BinarySearchTreeNode + CustomStringConvertible extension BinarySearchTreeNode: CustomStringConvertible { public var description: String { return "[\(key), \(value)]" } } // MARK: - BinarySearchTreeNode + Equatable extension BinarySearchTreeNode: Equatable {} public func ==<K: Comparable, T: Comparable>(lhs: BinarySearchTreeNode<K, T>, rhs: BinarySearchTreeNode<K, T>) -> Bool { guard lhs.key == rhs.key, lhs.value == lhs.value else { return false } return true } // MARK: - BinarySearchTree: Lifecycle and Traversal /* `BinarySearchTree` requires the concept of order. This is the reason why the generic type `K` has to be `Comparable`. We need to be able to compare the data of each node to implement operations such as `insert`, `remove` and `search`. */ public class BinarySearchTree<K: Comparable, T: Comparable> { var root: BinarySearchTreeNode<K, T>? public var isEmpty: Bool { return root == nil } public init(root: BinarySearchTreeNode<K, T>?) { self.root = root } public convenience init() { self.init(root: nil) } public convenience init(array: [BinarySearchTreeNode<K, T>]) { self.init(root: nil) for node in array { insert(newNode: node) } } public convenience init(arrayLiteral elements: BinarySearchTreeNode<K, T>...) { self.init(root: nil) for element in elements { insert(newNode: element) } } public func traverseInOrder(_ node: BinarySearchTreeNode<K, T>?, visit: ((BinarySearchTreeNode<K, T>?) -> Void)? = nil) { guard let node = node else { return } traverseInOrder(node.left, visit: visit) visit?(node) traverseInOrder(node.right, visit: visit) } public func traverseLevelOrder(_ node: BinarySearchTreeNode<K, T>?, visit: ((BinarySearchTreeNode<K, T>?) -> Void)? = nil) { guard let node = node else { return } let queue = Queue<BinarySearchTreeNode<K, T>>() try? queue.push(node) while !queue.isEmpty { let node = queue.pop() visit?(node) if let leftNode = node?.left { try? queue.push(leftNode) } if let rightNode = node?.right { try? queue.push(rightNode) } } } public func traversePreOrder(_ node: BinarySearchTreeNode<K, T>?, visit: ((BinarySearchTreeNode<K, T>?) -> Void)? = nil) { guard let node = node else { return } visit?(node) traversePreOrder(node.left, visit: visit) traversePreOrder(node.right, visit: visit) } public func traversePostOrder(_ node: BinarySearchTreeNode<K, T>?, visit: ((BinarySearchTreeNode<K, T>?) -> Void)? = nil) { guard let node = node else { return } traversePostOrder(node.left, visit: visit) traversePostOrder(node.right, visit: visit) visit?(node) } public func traverseBreadthFirst(visit: ((BinarySearchTreeNode<K, T>?) -> Void)? = nil) { traverseLevelOrder(root, visit: visit) } public func traverseDepthFirst(visit: ((BinarySearchTreeNode<K, T>?) -> Void)? = nil) { traverseInOrder(root, visit: visit) } } // MARK: - BinarySearchTree: Order-based operations public extension BinarySearchTree { func search(_ node: BinarySearchTreeNode<K, T>?, key: K) -> BinarySearchTreeNode<K, T>? { guard let node = node else { return nil } if node.key == key { return node } if key <= node.key { return search(node.left, key: key) } else { return search(node.right, key: key) } } func minimum(_ node: BinarySearchTreeNode<K, T>? = nil) -> BinarySearchTreeNode<K, T>? { var target = (node == nil) ? root : node while target?.left != nil { target = target?.left } return target } func maximum(_ node: BinarySearchTreeNode<K, T>? = nil) -> BinarySearchTreeNode<K, T>? { var target = (node == nil) ? root : node while target?.right != nil { target = target?.right } return target } func insert(newNode: BinarySearchTreeNode<K, T>) { insert(key: newNode.key, value: newNode.value) } func insert(key: K, value: T) { var leaf: BinarySearchTreeNode<K, T>? = nil var node = root while node != nil { leaf = node if key <= node!.key { node = node!.left } else { node = node!.right } } let newNode = BinarySearchTreeNode(key: key, value: value) guard let target = leaf else { root = newNode return } newNode.parent = target if key <= target.key { target.left = newNode } else { target.right = newNode } } func remove(node: BinarySearchTreeNode<K, T>) { if node.left == nil { transplant(source: node, dest: node.right) return } else if node.right == nil { transplant(source: node, dest: node.left) return } guard let target = minimum(node.right) else { return } if target.parent != node { transplant(source: target, dest: target.right) } transplant(source: node, dest: target) target.left = node.left target.left?.parent = target } subscript(key: K) -> BinarySearchTreeNode<K, T>? { return search(root, key: key) } } // MARK: - Private Methods fileprivate extension BinarySearchTree { func dump() -> String { var nodeDumps: [String] = [] traverseInOrder(root) { node in let nodeDump: String = { guard let node = node else { return "-" } return node.description }() nodeDumps.append(nodeDump) } return nodeDumps.joined(separator: ", ") } func transplant(source: BinarySearchTreeNode<K, T>, dest: BinarySearchTreeNode<K, T>?) { if source.parent == nil { root = dest } else if source == source.parent?.left { source.parent?.left = dest } else { source.parent?.right = dest } dest?.parent = source.parent } } // MARK: - BinarySearchTree + CustomStringConvertible extension BinarySearchTree: CustomStringConvertible { public var description: String { return dump() } } // MARK: - BinarySearchTree to Array extension BinarySearchTree { var array: [BinarySearchTreeNode<K, T>] { var nodes: [BinarySearchTreeNode<K, T>] = [] traverseInOrder(root) { node in if let node = node { nodes.append(node) } } return nodes } } // MARK: - BinarySearchTree + Equatable extension BinarySearchTree: Equatable {} public func ==<K: Comparable, T: Comparable>(lhs: BinarySearchTree<K, T>, rhs: BinarySearchTree<K, T>) -> Bool { return lhs.array == rhs.array }
mit
94b6b6a8b6fe5d4131672450523058b5
28.584838
120
0.566809
4.463508
false
false
false
false
iOSTestApps/WordPress-iOS
WordPress/Classes/Utility/Migrations/20-21/AccountToAccount20to21.swift
11
3719
import UIKit import Foundation /** Note: This migration policy handles database migration from WPiOS 4.3 to 4.4 */ class AccountToAccount20to21: NSEntityMigrationPolicy { private let defaultDotcomUsernameKey = "defaultDotcomUsernameKey" private let defaultDotcomKey = "AccountDefaultDotcom" override func beginEntityMapping(mapping: NSEntityMapping, manager: NSMigrationManager, error: NSErrorPointer) -> Bool { // Note: // NSEntityMigrationPolicy instance might not be the same all over. Let's use NSUserDefaults if let unwrappedAccount = legacyDefaultWordPressAccount(manager.sourceContext) { let username = unwrappedAccount.valueForKey("username") as! String let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setValue(username, forKey: defaultDotcomUsernameKey) userDefaults.synchronize() DDLogSwift.logWarn(">> Migration process matched [\(username)] as the default WordPress.com account") } else { DDLogSwift.logError(">> Migration process couldn't locate a default WordPress.com account") } return true } override func endEntityMapping(mapping: NSEntityMapping, manager: NSMigrationManager, error: NSErrorPointer) -> Bool { // Load the default username let userDefaults = NSUserDefaults.standardUserDefaults() let defaultUsername = userDefaults.stringForKey(defaultDotcomUsernameKey) ?? String() // Find the Default Account let context = manager.destinationContext let request = NSFetchRequest(entityName: "Account") let predicate = NSPredicate(format: "username == %@ AND isWpcom == true", defaultUsername) request.predicate = predicate let accounts = context.executeFetchRequest(request, error: nil) as! [NSManagedObject]? if let defaultAccount = accounts?.first { setLegacyDefaultWordPressAccount(defaultAccount) DDLogSwift.logInfo(">> Migration process located default account with username [\(defaultUsername)\")") } else { DDLogSwift.logError(">> Migration process failed to locate default account)") } // Cleanup! userDefaults.removeObjectForKey(defaultDotcomUsernameKey) userDefaults.synchronize() return true } // MARK: - Private Helpers private func legacyDefaultWordPressAccount(context: NSManagedObjectContext) -> NSManagedObject? { let objectURL = NSUserDefaults.standardUserDefaults().URLForKey(defaultDotcomKey) if objectURL == nil { return nil } let objectID = context.persistentStoreCoordinator!.managedObjectIDForURIRepresentation(objectURL!) if objectID == nil { return nil } var error: NSError? var defaultAccount = context.existingObjectWithID(objectID!, error: &error) if let unwrappedError = error { DDLogSwift.logError("\(unwrappedError)") } return defaultAccount } private func setLegacyDefaultWordPressAccount(account: NSManagedObject) { // Just in case if account.objectID.temporaryID { account.managedObjectContext?.obtainPermanentIDsForObjects([account], error: nil) } let accountURL = account.objectID.URIRepresentation() let defaults = NSUserDefaults.standardUserDefaults() defaults.setURL(accountURL, forKey: defaultDotcomKey) defaults.synchronize() } }
gpl-2.0
46b58cd8b5ff89fe0d3986b17f365738
36.565657
124
0.658241
5.810938
false
false
false
false
overtake/TelegramSwift
packages/Translate/Sources/Translate/Translate.swift
1
15013
import SwiftSignalKit import NaturalLanguage import AppKit private extension String { func replacingOccurrences(with: String, of: String) -> String { return self.replacingOccurrences(of: of, with: with) } } private func escape(with link:String) -> String { var escaped = link escaped = escaped.replacingOccurrences(with: "%21", of: "!") escaped = escaped.replacingOccurrences(with: "%24", of: "$") escaped = escaped.replacingOccurrences(with: "%26", of: "&") escaped = escaped.replacingOccurrences(with: "%2B", of: "+") escaped = escaped.replacingOccurrences(with: "%2C", of: ",") escaped = escaped.replacingOccurrences(with: "%2F", of: "/") escaped = escaped.replacingOccurrences(with: "%3A", of: ":") escaped = escaped.replacingOccurrences(with: "%3B", of: ";") escaped = escaped.replacingOccurrences(with: "%3D", of: "=") escaped = escaped.replacingOccurrences(with: "%3F", of: "?") escaped = escaped.replacingOccurrences(with: "%40", of: "@") escaped = escaped.replacingOccurrences(with: "%20", of: " ") escaped = escaped.replacingOccurrences(with: "%09", of: "\t") escaped = escaped.replacingOccurrences(with: "%23", of: "#") escaped = escaped.replacingOccurrences(with: "%3C", of: "<") escaped = escaped.replacingOccurrences(with: "%3E", of: ">") escaped = escaped.replacingOccurrences(with: "%22", of: "\"") escaped = escaped.replacingOccurrences(with: "%0A", of: "\n") escaped = escaped.replacingOccurrences(with: "%2E", of: ".") escaped = escaped.replacingOccurrences(with: "%2C", of: ",") escaped = escaped.replacingOccurrences(with: "%7D", of: "}") escaped = escaped.replacingOccurrences(with: "%7B", of: "{") escaped = escaped.replacingOccurrences(with: "%5B", of: "[") escaped = escaped.replacingOccurrences(with: "%5D", of: "]") return escaped } public struct Translate { public enum Error { case generic } public struct Value { public let language: String public let code: [String] public let emoji: String? } public static func find(_ code: String) -> Value? { return self.codes.first(where: { return $0.code.contains(code) }) } public static var codes: [Value] { var values: [Value] = [] values.append(.init(language: "Afrikaans", code: ["af"], emoji: nil)) values.append(.init(language: "Albanian", code: ["sq"], emoji: nil)) values.append(.init(language: "Amharic", code: ["am"], emoji: nil)) values.append(.init(language: "Arabic", code: ["ar"], emoji: nil)) values.append(.init(language: "Armenian", code: ["hy"], emoji: nil)) values.append(.init(language: "Azerbaijani", code: ["az"], emoji: nil)) values.append(.init(language: "Basque", code: ["eu"], emoji: nil)) values.append(.init(language: "Belarusian", code: ["be"], emoji: nil)) values.append(.init(language: "Bengali", code: ["bn"], emoji: nil)) values.append(.init(language: "Bosnian", code: ["bs"], emoji: nil)) values.append(.init(language: "Bulgarian", code: ["bg"], emoji: nil)) values.append(.init(language: "Catalan", code: ["ca"], emoji: nil)) values.append(.init(language: "Cebuano", code: ["ceb"], emoji: nil)) values.append(.init(language: "Chinese (Simplified)", code: ["zh-CN", "zh"], emoji: nil)) values.append(.init(language: "Chinese (Traditional)", code: ["zh-TW"], emoji: nil)) values.append(.init(language: "Corsican", code: ["co"], emoji: nil)) values.append(.init(language: "Croatian", code: ["hr"], emoji: nil)) values.append(.init(language: "Czech", code: ["cs"], emoji: nil)) values.append(.init(language: "Danish", code: ["da"], emoji: nil)) values.append(.init(language: "Dutch", code: ["nl"], emoji: nil)) values.append(.init(language: "English", code: ["en"], emoji: nil)) values.append(.init(language: "Esperanto", code: ["eo"], emoji: nil)) values.append(.init(language: "Estonian", code: ["et"], emoji: nil)) values.append(.init(language: "Finnish", code: ["fi"], emoji: nil)) values.append(.init(language: "French", code: ["fr"], emoji: nil)) values.append(.init(language: "Frisian", code: ["fy"], emoji: nil)) values.append(.init(language: "Galician", code: ["gl"], emoji: nil)) values.append(.init(language: "Georgian", code: ["ka"], emoji: nil)) values.append(.init(language: "German", code: ["de"], emoji: nil)) values.append(.init(language: "Greek", code: ["el"], emoji: nil)) values.append(.init(language: "Gujarati", code: ["gu"], emoji: nil)) values.append(.init(language: "Haitian Creole", code: ["ht"], emoji: nil)) values.append(.init(language: "Hausa", code: ["ha"], emoji: nil)) values.append(.init(language: "Hawaiian", code: ["haw"], emoji: nil)) values.append(.init(language: "Hebrew", code: ["he", "iw"], emoji: nil)) values.append(.init(language: "Hindi", code: ["hi"], emoji: nil)) values.append(.init(language: "Hmong", code: ["hmn"], emoji: nil)) values.append(.init(language: "Hungarian", code: ["hu"], emoji: nil)) values.append(.init(language: "Icelandic", code: ["is"], emoji: nil)) values.append(.init(language: "Igbo", code: ["ig"], emoji: nil)) values.append(.init(language: "Indonesian", code: ["id"], emoji: nil)) values.append(.init(language: "Irish", code: ["ga"], emoji: nil)) values.append(.init(language: "Italian", code: ["it"], emoji: nil)) values.append(.init(language: "Japanese", code: ["ja"], emoji: nil)) values.append(.init(language: "Javanese", code: ["jv"], emoji: nil)) values.append(.init(language: "Kannada", code: ["kn"], emoji: nil)) values.append(.init(language: "Kazakh", code: ["kk"], emoji: nil)) values.append(.init(language: "Khmer", code: ["km"], emoji: nil)) values.append(.init(language: "Kinyarwanda", code: ["rw"], emoji: nil)) values.append(.init(language: "Korean", code: ["ko"], emoji: nil)) values.append(.init(language: "Kurdish", code: ["ku"], emoji: nil)) values.append(.init(language: "Kyrgyz", code: ["ky"], emoji: nil)) values.append(.init(language: "Lao", code: ["lo"], emoji: nil)) values.append(.init(language: "Latvian", code: ["lv"], emoji: nil)) values.append(.init(language: "Lithuanian", code: ["lt"], emoji: nil)) values.append(.init(language: "Luxembourgish", code: ["lb"], emoji: nil)) values.append(.init(language: "Macedonian", code: ["mk"], emoji: nil)) values.append(.init(language: "Malagasy", code: ["mg"], emoji: nil)) values.append(.init(language: "Malay", code: ["ms"], emoji: nil)) values.append(.init(language: "Malayalam", code: ["ml"], emoji: nil)) values.append(.init(language: "Maltese", code: ["mt"], emoji: nil)) values.append(.init(language: "Maori", code: ["mi"], emoji: nil)) values.append(.init(language: "Marathi", code: ["mr"], emoji: nil)) values.append(.init(language: "Mongolian", code: ["mn"], emoji: nil)) values.append(.init(language: "Myanmar (Burmese)", code: ["my"], emoji: nil)) values.append(.init(language: "Nepali", code: ["ne"], emoji: nil)) values.append(.init(language: "Norwegian", code: ["no"], emoji: nil)) values.append(.init(language: "Nyanja (Chichewa)", code: ["ny"], emoji: nil)) values.append(.init(language: "Odia (Oriya)", code: ["or"], emoji: nil)) values.append(.init(language: "Pashto", code: ["ps"], emoji: nil)) values.append(.init(language: "Persian", code: ["fa"], emoji: nil)) values.append(.init(language: "Polish", code: ["pl"], emoji: nil)) values.append(.init(language: "Portuguese (Portugal, Brazil)", code: ["pt"], emoji: nil)) values.append(.init(language: "Punjabi", code: ["pa"], emoji: nil)) values.append(.init(language: "Romanian", code: ["ro"], emoji: nil)) values.append(.init(language: "Russian", code: ["ru"], emoji: nil)) values.append(.init(language: "Samoan", code: ["sm"], emoji: nil)) values.append(.init(language: "Scots Gaelic", code: ["gd"], emoji: nil)) values.append(.init(language: "Serbian", code: ["sr"], emoji: nil)) values.append(.init(language: "Sesotho", code: ["st"], emoji: nil)) values.append(.init(language: "Shona", code: ["sn"], emoji: nil)) values.append(.init(language: "Sindhi", code: ["sd"], emoji: nil)) values.append(.init(language: "Sinhala (Sinhalese)", code: ["si"], emoji: nil)) values.append(.init(language: "Slovak", code: ["sk"], emoji: nil)) values.append(.init(language: "Slovenian", code: ["sl"], emoji: nil)) values.append(.init(language: "Somali", code: ["so"], emoji: nil)) values.append(.init(language: "Spanish", code: ["es"], emoji: nil)) values.append(.init(language: "Sundanese", code: ["su"], emoji: nil)) values.append(.init(language: "Swahili", code: ["sw"], emoji: nil)) values.append(.init(language: "Swedish", code: ["sv"], emoji: nil)) values.append(.init(language: "Tagalog (Filipino)", code: ["tl"], emoji: nil)) values.append(.init(language: "Tajik", code: ["tg"], emoji: nil)) values.append(.init(language: "Tamil", code: ["ta"], emoji: nil)) values.append(.init(language: "Tatar", code: ["tt"], emoji: nil)) values.append(.init(language: "Telugu", code: ["te"], emoji: nil)) values.append(.init(language: "Thai", code: ["th"], emoji: nil)) values.append(.init(language: "Turkish", code: ["tr"], emoji: nil)) values.append(.init(language: "Turkmen", code: ["tk"], emoji: nil)) values.append(.init(language: "Ukrainian", code: ["uk"], emoji: nil)) values.append(.init(language: "Urdu", code: ["ur"], emoji: nil)) values.append(.init(language: "Uyghur", code: ["ug"], emoji: nil)) values.append(.init(language: "Uzbek", code: ["uz"], emoji: nil)) values.append(.init(language: "Vietnamese", code: ["vi"], emoji: nil)) values.append(.init(language: "Welsh", code: ["cy"], emoji: nil)) values.append(.init(language: "Xhosa", code: ["xh"], emoji: nil)) values.append(.init(language: "Yiddish", code: ["yi"], emoji: nil)) values.append(.init(language: "Yoruba", code: ["yo"], emoji: nil)) values.append(.init(language: "Zulu", code: ["zu"], emoji: nil)) return values } public static var supportedTranslationLanguages = [ "en", "ar", "zh", "fr", "de", "it", "jp", "ko", "pt", "ru", "es" ] public static var languagesEmojies:[String:String] = [ "en":"🏴󠁧󠁢󠁥󠁮󠁧󠁿", "ar":"🇦🇷", "zh":"🇨🇳", "fr":"🇫🇷", "de":"🇩🇪", "it":"🇮🇹", "jp":"🇯🇵", "ko":"🇰🇷", "pt":"🇵🇹", "ru":"🇷🇺", "es":"🇪🇸" ] private static let userAgents: [String] = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36", // 13.5% "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36", // 6.6% "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0", // 6.4% "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0", // 6.2% "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36", // 5.2% "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36" // 4.8% ] @available(macOS 10.14, *) private static let languageRecognizer = NLLanguageRecognizer() public static func detectLanguage(for text: String) -> String? { let text = String(text.prefix(64)) if #available(macOS 10.14, *) { languageRecognizer.processString(text) let hypotheses = languageRecognizer.languageHypotheses(withMaximum: 3) languageRecognizer.reset() if let value = hypotheses.sorted(by: { $0.value > $1.value }).first?.key.rawValue { return value } } return nil } public static func translateText(text: String, from: String?, to: String) -> Signal<(detect: String?, result: String), Error> { return Signal { subscriber in var uri = "https://translate.goo"; uri += "gleapis.com/transl"; uri += "ate_a"; uri += "/singl"; uri += "e?client=gtx&sl=" + (from ?? "auto") + "&tl=" + to + "&dt=t" + "&ie=UTF-8&oe=UTF-8&otf=1&ssel=0&tsel=0&kc=7&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&q="; uri += text.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! var request = URLRequest(url: URL(string: uri)!) request.httpMethod = "GET" request.setValue(userAgents[Int.random(in: 0 ..< userAgents.count)], forHTTPHeaderField: "User-Agent") let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { data, response, error in if let _ = error { subscriber.putError(.generic) } else if let data = data { let json = try? JSONSerialization.jsonObject(with: data, options: []) as? NSArray if let json = json, json.count > 0 { let array = json[0] as? NSArray ?? NSArray() var result: String = "" for i in 0 ..< array.count { let blockText = array[i] as? NSArray if let blockText = blockText, blockText.count > 0 { let value = blockText[0] as? String if let value = value, value != "null" { result += value } } } subscriber.putNext((detect: json[2] as? String, result: result)) } else { subscriber.putError(.generic) } } }) task.resume() return ActionDisposable { task.cancel() } } } }
gpl-2.0
eef329e6a5bc6c40493d8e1ea21bcbf7
53.49635
187
0.566568
3.643729
false
false
false
false
ITzTravelInTime/TINU
TINU/FilesystemObserver.swift
1
2289
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Foundation public class FileSystemObserver { private var fileHandle: CInt? private var eventSource: DispatchSourceProtocol? private var observingStarted: Bool = false private let path: String private let handler: () -> Void public var isObserving: Bool{ return fileHandle != nil && eventSource != nil && observingStarted } deinit { stop() } public required init(path: String, changeHandler: @escaping ()->Void, startObservationNow: Bool = true) { assert(!path.isEmpty, "The filesystem object to observe must have a path!") self.path = path self.handler = changeHandler if startObservationNow{ start() } } public convenience init(url: URL, changeHandler: @escaping ()->Void, startObservationNow: Bool = true) { self.init(path: url.path, changeHandler: { changeHandler() }, startObservationNow: startObservationNow) } public func stop() { self.eventSource?.cancel() if fileHandle != nil{ close(fileHandle!) } self.eventSource = nil self.fileHandle = nil self.observingStarted = false } public func start() { if fileHandle != nil || eventSource != nil{ stop() } self.fileHandle = open(path, O_EVTONLY) self.eventSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: self.fileHandle!, eventMask: .all, queue: DispatchQueue.global(qos: .utility)) self.eventSource!.setEventHandler { self.handler() } self.eventSource!.resume() self.observingStarted = true } }
gpl-2.0
c6d9233e33b102b996d3ee02953e908f
26.578313
157
0.736129
3.98087
false
false
false
false
codercd/DPlayer
DPlayer/CollectionViewController.swift
1
9296
// // CollectionViewController.swift // DPlayer // // Created by LiChendi on 16/4/19. // Copyright © 2016年 LiChendi. All rights reserved. // import UIKit import Kingfisher private let reuseIdentifier = "Cell" class CollectionViewController: UICollectionViewController,UICollectionViewDelegateFlowLayout { // var list:Array<AnyObject> = [] // var homepageModel = BaseClass(json: nil) var homepageModel = HomepageModel() private let CarouselViewCellIdentifier = "CarouselViewCell" private let ClassificationCellIdentifier = "ClassificationCell" private let LiveDetailCellIdentifier = "LiveDetailCell" // private let CollectionHeaderViewIndentifer = "CollectionHeaderView" override func viewDidLoad() { super.viewDidLoad() self.collectionView?.backgroundColor = UIColor.lightGrayColor() self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) self.collectionView?.registerNib(UINib(nibName: "CarouselViewCell" ,bundle: NSBundle.mainBundle()), forCellWithReuseIdentifier: CarouselViewCellIdentifier) self.collectionView?.registerNib(UINib(nibName: "ClassificationCell" ,bundle: NSBundle.mainBundle()), forCellWithReuseIdentifier: ClassificationCellIdentifier) self.collectionView?.registerNib(UINib(nibName: "LiveDetailCell" ,bundle: NSBundle.mainBundle()), forCellWithReuseIdentifier: LiveDetailCellIdentifier) self.collectionView?.registerNib(UINib(nibName: "CollectionHeaderView" ,bundle: NSBundle.mainBundle()), forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: "header") NetworkManager().getHomepageJson { (model) in self.homepageModel = model self.collectionView?.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return self.homepageModel.lists.count } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items switch section { case 0: return 1 case 1: return 1 default: let dictionary = self.homepageModel.mapTable[section] let slug = dictionary["slug"].description for item in self.homepageModel.lists { if item.0 == slug { return (item.1.homepageItem?.count)! } } return 0 } } //cell override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { switch indexPath.section { case 0: let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CarouselViewCellIdentifier, forIndexPath: indexPath) return cell case 1: let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ClassificationCellIdentifier, forIndexPath: indexPath) return cell default: let cell:LiveDetailCell = collectionView.dequeueReusableCellWithReuseIdentifier(LiveDetailCellIdentifier, forIndexPath: indexPath) as! LiveDetailCell let category = self.homepageModel.homepageCategoryForSection(indexPath.section) let homepageItem = category!.homepageItem![indexPath.row] guard let imageURLStr = homepageItem.linkObject?.thumb else { return cell } let imageURL = NSURL(string: imageURLStr)! cell.iconView.kf_setImageWithURL(imageURL) // cell.iconView.image = UIImage( // cell.iconView.backgroundColor = UIColor.greenColor() return cell } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { switch indexPath.section { case 0: return CGSizeMake(self.collectionView!.bounds.size.width, 200) case 1: return CGSizeMake(self.collectionView!.bounds.size.width, 80) default: return CGSizeMake((self.collectionView!.bounds.size.width - 24) / 2, (self.collectionView!.bounds.size.width - 24) / 2 / 16 * 9) } } // Section边距 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { switch section { case 0: return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) case 1: return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0) default: return UIEdgeInsets(top: 0, left: 8, bottom: 10, right: 8) } } // Cell边距 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { if section == 0 { return 0 } return 8 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { if section == 0 { return 0 } return 8 } // header size func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { switch section { case 0: return CGSizeZero case 1: return CGSizeZero default: return CGSize(width: 200, height: 50) } } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { let header:CollectionHeaderView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "header", forIndexPath: indexPath) as! CollectionHeaderView header.backgroundColor = UIColor.whiteColor() let dictionary = self.homepageModel.mapTable[indexPath.section] let slug = dictionary["name"].description header.titileLabel.text = slug return header } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let category = self.homepageModel.homepageCategoryForSection(indexPath.section) let homepageItem = category!.homepageItem![indexPath.row] guard let roomID = homepageItem.linkObject?.uid else {return} print("roomID\(roomID)") NetworkManager().getHomeInfo(roomID) { (roomModel) in // print(roomModel.live?.ws?.flv?.liveList) guard let liveURL = roomModel.live?.ws?.flv?.liveURL else { return} let playViewController = DPlayerMoviePlayerViewController(url: NSURL(string: liveURL)!) print(liveURL) self.presentViewController(playViewController, animated: true, completion: nil) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ }
mit
f12b858c5eb5fa1dc149bbc30f20ae31
40.636771
214
0.686914
5.869153
false
false
false
false
ShengQiangLiu/arcgis-runtime-samples-ios
OfflineFeatureEditingSample/swift/OfflineFeatureEditing/FeatureTemplatePickerViewController.swift
4
5334
// Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm import Foundation import ArcGIS import UIKit class FeatureTemplatePickerInfo { var featureType:AGSFeatureType! var featureTemplate:AGSFeatureTemplate! var source:AGSGDBFeatureSourceInfo! var renderer:AGSRenderer! } protocol FeatureTemplatePickerDelegate:class { func featureTemplatePickerViewControllerWasDismissed(controller:FeatureTemplatePickerViewController) func featureTemplatePickerViewController(controller:FeatureTemplatePickerViewController, didSelectFeatureTemplate template:AGSFeatureTemplate, forLayer layer:AGSGDBFeatureSourceInfo) } class FeatureTemplatePickerViewController:UIViewController, UITableViewDataSource, UITableViewDelegate { var infos = [FeatureTemplatePickerInfo]() @IBOutlet weak var featureTemplateTableView: UITableView! weak var delegate:FeatureTemplatePickerDelegate? override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() } func addTemplatesForLayersInMap(mapView:AGSMapView) { for layer in mapView.mapLayers { if layer is AGSFeatureLayer { self.addTemplatesFromSource(layer as! AGSFeatureLayer, renderer: (layer as! AGSFeatureLayer).renderer) } else if layer is AGSFeatureTableLayer { self.addTemplatesFromSource(((layer as! AGSFeatureTableLayer).table as! AGSGDBFeatureTable), renderer: (layer as! AGSFeatureTableLayer).renderer) } } } func addTemplatesFromSource(source:AGSGDBFeatureSourceInfo, renderer:AGSRenderer) { if source.types != nil && source.types.count > 0 { //for each type for type in source.types as! [AGSFeatureType] { //for each temple in type for template in type.templates as! [AGSFeatureTemplate] { let info = FeatureTemplatePickerInfo() info.source = source info.renderer = renderer info.featureTemplate = template info.featureType = type //add to array self.infos.append(info) } } } //if layer contains only templates (no feature types) else if source.templates != nil { //for each template for template in source.templates as! [AGSFeatureTemplate] { let info = FeatureTemplatePickerInfo() info.source = source info.renderer = renderer info.featureTemplate = template info.featureType = nil //add to array self.infos.append(info) } } } @IBAction func dismiss() { //Notify the delegate that user tried to dismiss the view controller self.delegate?.featureTemplatePickerViewControllerWasDismissed(self) } //MARK: - table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.infos.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return nil } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //Get a cell let cellIdentifier = "TemplatePickerCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! UITableViewCell! if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier) } cell.selectionStyle = .Blue //Set its label, image, etc for the template let info = self.infos[indexPath.row] cell.textLabel?.font = UIFont.systemFontOfSize(12) cell.textLabel?.text = info.featureTemplate.name cell.imageView?.image = info.renderer.swatchForFeatureWithAttributes(info.featureTemplate.prototypeAttributes, geometryType: info.source.geometryType, size: CGSizeMake(20, 20)) return cell } //MARK: - table view delegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //Notify the delegate that the user picked a feature template let info = self.infos[indexPath.row] println("\(self), \(info.featureTemplate), \(info.source), \(self.delegate)") self.delegate?.featureTemplatePickerViewController(self , didSelectFeatureTemplate: info.featureTemplate, forLayer: info.source) //unselect the cell tableView.cellForRowAtIndexPath(indexPath)?.selected = false } }
apache-2.0
3c45e4332c769e51fdf6450f2d0fbc40
38.227941
186
0.65973
5.270751
false
false
false
false
emaloney/CleanroomBridging
Sources/CleanroomBridging/NotificationWatcher.swift
1
4316
// // NotificationWatcher.swift // Cleanroom Project // // Created by Evan Maloney on 3/15/15. // Copyright © 2015 Gilt Groupe. All rights reserved. // import Foundation open class NotificationWatcher { private let receivers: [NotificationReceiver] public convenience init(notificationName: String, object: Any? = nil, startWatching: Bool = true, callback: @escaping (Notification) -> Void) { self.init(notification: Notification.Name(notificationName), object: object, startWatching: startWatching, callback: callback) } public convenience init(notificationNames: [String], object: Any? = nil, startWatching: Bool = true, callback: @escaping (Notification) -> Void) { let notifications = notificationNames.map { Notification.Name($0) } self.init(notifications: notifications, object: object, startWatching: startWatching, callback: callback) } public init(notification: Notification.Name, object: Any? = nil, startWatching: Bool = true, callback: @escaping (Notification) -> Void) { self.receivers = [NotificationReceiver(notification: notification, object: object, startWatching: startWatching, callback: callback)] } public init(notifications: [Notification.Name], object: Any? = nil, startWatching: Bool = true, callback: @escaping (Notification) -> Void) { self.receivers = notifications.map { return NotificationReceiver(notification: $0, object: object, startWatching: startWatching, callback: callback) } } open func stopWatching() { receivers.forEach { $0.stopObserving() } } open func resumeWatching() { receivers.forEach { $0.startObserving() } } } open class NotificationObjectWatcher<T>: NotificationWatcher { public convenience init(notificationName: String, object: Any? = nil, startWatching: Bool = true, callback: @escaping (Notification, T) -> Void) { self.init(notification: Notification.Name(notificationName), object: object, startWatching: startWatching, callback: callback) } public convenience init(notificationNames: [String], object: Any? = nil, startWatching: Bool = true, callback: @escaping (Notification, T) -> Void) { let notifications = notificationNames.map { Notification.Name($0) } self.init(notifications: notifications, object: object, startWatching: startWatching, callback: callback) } public init(notification: Notification.Name, object: Any? = nil, startWatching: Bool = true, callback: @escaping (Notification, T) -> Void) { super.init(notification: notification, object: object, startWatching: startWatching, callback: { notif in if let typedObj = notif.object as? T { callback(notif, typedObj) } }) } public init(notifications: [Notification.Name], object: Any? = nil, startWatching: Bool = true, callback: @escaping (Notification, T) -> Void) { super.init(notifications: notifications, object: object, startWatching: startWatching, callback: { notif in if let typedObj = notif.object as? T { callback(notif, typedObj) } }) } } private class NotificationReceiver { let callback: (Notification) -> Void let notification: Notification.Name let object: Any? var isObserving = false init(notification: Notification.Name, object: Any? = nil, startWatching: Bool, callback: @escaping (Notification) -> Void) { self.notification = notification self.object = object self.callback = callback if startWatching { startObserving() } } deinit { stopObserving() } @objc func notificationReceived(_ notification: Notification) { callback(notification) } func startObserving() { if !isObserving { NotificationCenter.default.addObserver(self, selector: #selector(NotificationReceiver.notificationReceived(_:)), name: notification, object: object) isObserving = true } } func stopObserving() { if isObserving { isObserving = false NotificationCenter.default.removeObserver(self) } } }
mit
060845cc7e5fd89d29ef8141686b13e0
33.798387
160
0.661182
4.605123
false
false
false
false
syllabix/swipe-card-carousel
Source/Arrow.swift
1
1364
// // Arrow.swift // Icons // // Created by Tom Stoepker on 10/15/16. // Copyright © 2016 CrushOnly. All rights reserved. // import UIKit public class Arrow: IndicatorIcon { private var stem: CAShapeLayer? private var arrow: CAShapeLayer? private func drawArrow() { remove(layer: stem) remove(layer: arrow) let stemY = bounds.size.height / 2 let stemXStart = (direction == .Left) ? lineWidth : bounds.size.width - lineWidth let stemXEnd = (direction == .Left) ? bounds.size.width - lineWidth: lineWidth let stemStartPoint = CGPoint(x: stemXStart, y: stemY) let stemEndPoint = CGPoint(x: stemXEnd, y: stemY) stem = addLayer(start: stemStartPoint, end: stemEndPoint) let arrowStartY = bounds.size.height / 4 let arrowStartX = bounds.size.width / 2 let arrowStart = CGPoint(x: arrowStartX, y: arrowStartY) let arrowTipX = (direction == .Left) ? lineWidth : bounds.size.width - lineWidth let arrowEndY = (bounds.size.height / 2) + (bounds.size.height / 4) let arrowEndX = bounds.size.width / 2 let arrowPath = UIBezierPath() arrowPath.move(to: arrowStart) arrowPath.addLine(to: CGPoint(x: arrowTipX, y: stemY)) arrowPath.addLine(to: CGPoint(x: arrowEndX, y: arrowEndY)) arrow = addLayerWith(path: arrowPath) } override public func layoutSubviews() { super.layoutSubviews() drawArrow() } }
mit
ce43142e16ec1cb78e95bd47bd7e302b
26.816327
83
0.699193
3.276442
false
false
false
false
tscholze/nomster-ios
Nomster/SuggestionTableViewCell.swift
1
1603
// // SuggestionTableViewCell.swift // Nomster // // Created by Tobias Scholze on 01.03.15. // Copyright (c) 2015 Tobias Scholze. All rights reserved. // import UIKit class SuggestionTableViewCell: UITableViewCell { @IBOutlet var logoView: UIImageView! @IBOutlet var nameLabel: UILabel! @IBOutlet var dateLabel: UILabel! @IBOutlet var creatorLabel: UILabel! func useSuggestion(suggestion: Suggestion) { nameLabel.text = suggestion.name creatorLabel.text = "Suggested by \(suggestion.creator)" dateLabel.text = NSDateFormatter.localizedStringFromDate ( suggestion.date, dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.ShortStyle ) // Setup image view logoView.layer.cornerRadius = logoView.frame.width / 2 logoView.clipsToBounds = true logoView.layer.borderWidth = 1.0 logoView.layer.borderColor = NomsterColors.green().CGColor // Use image by url or by local path if (suggestion.image != "") { if (suggestion.image.rangeOfString("http://") != nil || suggestion.image.rangeOfString("https://") != nil) { logoView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: suggestion.image)!)!) } else { let path = NSBundle.mainBundle().pathForResource(suggestion.image, ofType: "png") logoView.image = UIImage(data: NSData(contentsOfFile: path!)!) } } } }
mit
055231ce73e1acd735aa08e17f72659e
36.302326
120
0.615721
5.040881
false
false
false
false
Averylamp/openwhisk-xcode
whiskbot-demo-app/WhiskBot/SpeechRecognizer.swift
2
4815
/* * Copyright 2015-2016 IBM Corporation * * 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. */ // // SpeechRecognizer.swift // WhiskBot // // Created by whisk on 1/18/17. // Copyright © 2017 Avery Lamp. All rights reserved. // import UIKit import Speech protocol appleSpeechFeedbackProtocall: class { func finalAppleRecognitionRecieved( phrase: String) func partialAppleRecognitionRecieved( phrase: String) func errorAppleRecieved(error: String) } class SpeechRecognizer: NSObject, SFSpeechRecognizerDelegate { let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US")) var recognitionRequest : SFSpeechAudioBufferRecognitionRequest? var recognitionTask : SFSpeechRecognitionTask? let audioEngine = AVAudioEngine() var delegate: appleSpeechFeedbackProtocall? var speechAuthorized = false var isRecording = false func setupSpeechRecognition(){ speechRecognizer?.delegate = self SFSpeechRecognizer.requestAuthorization { (authStatus) in OperationQueue.main.addOperation { switch authStatus{ case .authorized: print("Recording Authorized") self.speechAuthorized = true case .denied: print("Recording Denied") default: print("Something went wrong") } } } } func startRecording() { if isRecording{ isRecording = false self.audioEngine.stop() audioEngine.inputNode?.removeTap(onBus: 0) self.recognitionRequest = nil self.recognitionTask = nil print("Stopped Recording") return }else{ print("Started Recording") isRecording = true } if speechAuthorized == false{ setupSpeechRecognition() } if recognitionTask != nil { recognitionTask?.cancel() recognitionTask = nil } let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryRecord) try audioSession.setMode(AVAudioSessionModeMeasurement) try audioSession.setActive(true, with: .notifyOthersOnDeactivation) }catch { print("Error creating audio session") } recognitionRequest = SFSpeechAudioBufferRecognitionRequest() guard let input = audioEngine.inputNode else { fatalError("Audio Engine has no input") } guard let recognitionRequest = recognitionRequest else { fatalError("Unable to create SFSpeechAudioBuffer") } recognitionRequest.shouldReportPartialResults = true recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in if let result = result { for transcription in result.transcriptions { print(transcription.formattedString) } let partialText = result.bestTranscription.formattedString if result.isFinal == true { self.audioEngine.stop() input.removeTap(onBus: 0) self.recognitionRequest = nil self.recognitionTask = nil self.delegate?.finalAppleRecognitionRecieved(phrase: result.bestTranscription.formattedString) }else{ self.delegate?.partialAppleRecognitionRecieved(phrase: partialText) } } if error != nil { print("Error recieved - \(error)") self.delegate?.errorAppleRecieved(error: "\(error)") } }) let recordingFormat = input.outputFormat(forBus: 0) input.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, time) in self.recognitionRequest?.append(buffer) } audioEngine.prepare() do { try audioEngine.start() }catch{ print("Unable to start audio engine") } } }
apache-2.0
4d75ef1921e5c9650b5e889a0a240e38
33.884058
121
0.607603
5.730952
false
false
false
false
marcelganczak/swift-js-transpiler
test/weheartswift/dictionaries-2.swift
1
863
var code = [ "a" : "b", "b" : "c", "c" : "d", "d" : "e", "e" : "f", "f" : "g", "g" : "h", "h" : "i", "i" : "j", "j" : "k", "k" : "l", "l" : "m", "m" : "n", "n" : "o", "o" : "p", "p" : "q", "q" : "r", "r" : "s", "s" : "t", "t" : "u", "u" : "v", "v" : "w", "w" : "x", "x" : "y", "y" : "z", "z" : "a" ] var encodedMessage = "uijt nfttbhf jt ibse up sfbe" var decoder: [String:String] = [:] // reverse the code for (key, value) in code { decoder[value] = key } var decodedMessage = "" for char in encodedMessage.characters { var character = "\(char)" if let encodedChar = decoder[character] { // letter decodedMessage += encodedChar } else { // space decodedMessage += character } } print(decodedMessage)
mit
1f5b1421d0de8698fd7899c73aefebc6
15.301887
51
0.402086
2.545723
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Collections/CollectionLinkCell.swift
1
3637
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireDataModel import WireCommonComponents final class CollectionLinkCell: CollectionCell { private var articleView: ArticleView? = .none private var headerView = CollectionCellHeader() func createArticleView(with textMessageData: ZMTextMessageData) { let articleView = ArticleView(withImagePlaceholder: textMessageData.linkPreviewHasImage) articleView.isUserInteractionEnabled = false articleView.imageHeight = 0 articleView.messageLabel.numberOfLines = 1 articleView.authorLabel.numberOfLines = 1 articleView.configure(withTextMessageData: textMessageData, obfuscated: false) secureContentsView.addSubview(articleView) // Reconstraint the header headerView.removeFromSuperview() headerView.message = message! secureContentsView.addSubview(headerView) contentView.layoutMargins = UIEdgeInsets(top: 16, left: 4, bottom: 4, right: 4) [articleView, headerView].prepareForLayout() NSLayoutConstraint.activate([ headerView.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor), headerView.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor, constant: 12), headerView.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor, constant: -12), articleView.topAnchor.constraint(greaterThanOrEqualTo: headerView.bottomAnchor, constant: -4), articleView.leftAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leftAnchor), articleView.rightAnchor.constraint(equalTo: contentView.layoutMarginsGuide.rightAnchor), articleView.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor) ]) self.articleView = articleView } override var obfuscationIcon: StyleKitIcon { return .link } override func updateForMessage(changeInfo: MessageChangeInfo?) { super.updateForMessage(changeInfo: changeInfo) guard let message = message, let textMessageData = message.textMessageData, textMessageData.linkPreview != nil else { return } var shouldReload = false if changeInfo == nil { shouldReload = true } else { shouldReload = changeInfo!.imageChanged } if shouldReload { articleView?.removeFromSuperview() articleView = nil createArticleView(with: textMessageData) } } override func copyDisplayedContent(in pasteboard: UIPasteboard) { guard let link = message?.textMessageData?.linkPreview else { return } UIPasteboard.general.url = link.openableURL as URL? } public override func prepareForReuse() { super.prepareForReuse() message = .none } }
gpl-3.0
07176a8d3b4eb30815656540c75dfa9b
36.885417
125
0.706626
5.309489
false
false
false
false
sonsongithub/numsw
Sources/numsw/NDArray/NDArrayCompoundAssignment.swift
1
941
// MARK: - Scalar public func +=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: T) { lhs = lhs + rhs } public func -=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: T) { lhs = lhs - rhs } public func *=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: T) { lhs = lhs * rhs } public func /=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: T) { lhs = lhs / rhs } public func %=<T: Moduloable>(lhs: inout NDArray<T>, rhs: T) { lhs = lhs % rhs } // MARK: - NDArray public func +=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: NDArray<T>) { lhs = lhs + rhs } public func -=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: NDArray<T>) { lhs = lhs - rhs } public func *=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: NDArray<T>) { lhs = lhs * rhs } public func /=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: NDArray<T>) { lhs = lhs / rhs } public func %=<T: Moduloable>(lhs: inout NDArray<T>, rhs: NDArray<T>) { lhs = lhs % rhs }
mit
1d8aed69feaad3439bb8e6751ecba0d7
21.95122
71
0.590861
2.931464
false
false
false
false
LawrenceHan/Games
CapNap/CapNap/GameScene.swift
1
3666
// // GameScene.swift // CapNap // // Created by Hanguang on 4/24/16. // Copyright (c) 2016 Hanguang. All rights reserved. // import SpriteKit protocol CustomNodeEvents { func didMoveToScene() } protocol InteractiveNode { func interact() } struct PhysicsCategory { static let None: UInt32 = 0 static let Cat: UInt32 = 0b1 // 1 static let Block: UInt32 = 0b10 // 2 static let Bed: UInt32 = 0b100 // 4 static let Edge: UInt32 = 0b1000 // 8 static let Label: UInt32 = 0b10000 // 16 } class GameScene: SKScene, SKPhysicsContactDelegate { var bedNode: BedNode! var catNode: CatNode! var playable = true override func didMoveToView(view: SKView) { // Calculate playable margin let maxAspectRatio: CGFloat = 16.0/9.0 // iPhone 5 let maxAspectRatioHeight = size.width / maxAspectRatio let playableMargin: CGFloat = (size.height - maxAspectRatioHeight) / 2 let playableRect = CGRect(x: 0, y: playableMargin, width: size.width, height: size.height-playableMargin*2) physicsBody = SKPhysicsBody(edgeLoopFromRect: playableRect) physicsWorld.contactDelegate = self physicsBody!.categoryBitMask = PhysicsCategory.Edge bedNode = childNodeWithName("bed") as! BedNode catNode = childNodeWithName("//cat_body") as! CatNode enumerateChildNodesWithName("//*") { (node, _) in if let customNode = node as? CustomNodeEvents { customNode.didMoveToScene() } } SKTAudio.sharedInstance().playBackgroundMusic("backgroundMusic.mp3") } func inGameMessage(text: String) { let message = MessageNode(message: text) message.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)) addChild(message) } func newGame() { let scene = GameScene(fileNamed: "GameScene") scene!.scaleMode = scaleMode view!.presentScene(scene) } func lose() { // 1 SKTAudio.sharedInstance().pauseBackgroundMusic() runAction(SKAction.playSoundFileNamed("lose.mp3", waitForCompletion: false)) // 2 inGameMessage("Try again...") // 3 performSelector(#selector(newGame), withObject: nil, afterDelay: 5) playable = false catNode.wakeUp() } func win() { playable = false SKTAudio.sharedInstance().pauseBackgroundMusic() runAction(SKAction.playSoundFileNamed("win.mp3", waitForCompletion: false)) inGameMessage("Nice job!") performSelector(#selector(newGame), withObject: nil, afterDelay: 5) catNode.curlAt(bedNode.position) } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } // MARK: Contact test delegate func didBeginContact(contact: SKPhysicsContact) { if let labelNode = ((contact.bodyA.categoryBitMask == PhysicsCategory.Label) ? contact.bodyA.node : contact.bodyB.node) as? MessageNode { labelNode.didBounce() } if !playable { return } let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask if collision == PhysicsCategory.Cat | PhysicsCategory.Bed { print("SUCCESS") win() } else if collision == PhysicsCategory.Cat | PhysicsCategory.Edge { print("FAIL") lose() } } }
mit
351993610dedd8f9e273bf15c3750887
28.328
115
0.603382
4.792157
false
false
false
false
neerajDamle/OpenWeatherForecast
OpenWeatherForecast/OpenWeatherForecast/City.swift
1
14962
// // City.swift // OpenWeatherForecast // // Created by Neeraj Damle on 8/28/15. // Copyright (c) 2015 Neeraj Damle. All rights reserved. // import UIKit let WEATHER_INFO_BASE_URL_WITH_NAME = "http://api.openweathermap.org/data/2.5/forecast/daily?" let WEATHER_INFO_BASE_URL_WITH_ID = "http://api.openweathermap.org/data/2.5/forecast/daily?" // This enum contains all the possible states a city weather record can be in enum CityWeatherRecordState { case new, downloading, downloaded, failed; } class GeoCoordinates { var latitude = 0.0; var longitude = 0.0; } class City: NSObject { var name: String = ""; var id: Int = -1; var geoCoordinates = GeoCoordinates(); var country: String = ""; var noOfWeatherDays: Int = 14; var weatherForDays: [Weather] = []; var weatherInfoURL: String = ""; var state: CityWeatherRecordState = CityWeatherRecordState.new; override init() { } init(name: String) { self.name = name; weatherInfoURL = WEATHER_INFO_BASE_URL_WITH_NAME; //Add city name weatherInfoURL += "\(REQUEST_KEY_CITY_NAME)=" weatherInfoURL += name; //Add no of days weatherInfoURL += "&\(REQUEST_KEY_DAY_COUNT)="; weatherInfoURL += String(noOfWeatherDays); //Add App ID weatherInfoURL += "&\(REQUEST_KEY_APP_ID)="; weatherInfoURL += OPEN_WEATHER_MAP_APP_ID; } init(id: Int) { self.id = id; weatherInfoURL = WEATHER_INFO_BASE_URL_WITH_ID; //Add city id weatherInfoURL += "\(REQUEST_KEY_CITY_ID)=" weatherInfoURL += String(id); //Add no of days weatherInfoURL += "&\(REQUEST_KEY_DAY_COUNT)="; weatherInfoURL += String(noOfWeatherDays); //Add App ID weatherInfoURL += "&\(REQUEST_KEY_APP_ID)="; weatherInfoURL += OPEN_WEATHER_MAP_APP_ID; } } class PendingOperations { lazy var downloadsInProgressBasedOnName = Dictionary<String,Operation>(); lazy var downloadsInProgressBasedOnId = Dictionary<Int,Operation>(); lazy var downloadQueueBasedOnName: OperationQueue = { var queue = OperationQueue(); queue.name = "City name based weather info download queue"; return queue; }(); lazy var downloadQueueBasedOnId: OperationQueue = { var queue = OperationQueue(); queue.name = "City ID based weather info download queue"; return queue; }(); } class WeatherInfoDownloader : Operation { let city: City; init(city: City) { self.city = city; self.city.state = CityWeatherRecordState.downloading; } override func main() { if(self.isCancelled) { self.city.state = CityWeatherRecordState.failed; return; } var strWeatherURL = self.city.weatherInfoURL; strWeatherURL = strWeatherURL.addingPercentEscapes(using: String.Encoding.utf8)!; print("Weather URL: \(strWeatherURL)"); let weatherURL = URL(string: strWeatherURL); let weatherURLRequest = URLRequest(url: weatherURL!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 10); var response: AutoreleasingUnsafeMutablePointer<URLResponse?>?=nil; var err: NSError? = nil; NSURLConnection.sendAsynchronousRequest(weatherURLRequest, queue: OperationQueue.main) { (response, data, err) -> Void in // println("Weather web service response: \(response)"); do { var serializationError: NSError?; let jsonResult: [String:Any]! = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any]; print("JSON response: \(jsonResult)"); let requestCityName = self.city.name; var errorMessage: String = ""; if(jsonResult != nil) { var isError = false; repeat { if((jsonResult[RESPONSE_KEY_INTERNAL_CODE] as? String) == nil) { isError = true; break; } let internalCode = jsonResult[RESPONSE_KEY_INTERNAL_CODE] as! String; if(Int(internalCode) != 200) { isError = true; if((jsonResult[RESPONSE_KEY_MESSAGE] as? String) != nil) { errorMessage = jsonResult[RESPONSE_KEY_MESSAGE] as! String; print("Message: \(errorMessage)"); } break; } //Parse city info if((jsonResult[RESPONSE_KEY_CITY] as? NSDictionary) != nil) { let cityInfo = jsonResult[RESPONSE_KEY_CITY] as! NSDictionary; //Parse City ID if((cityInfo[RESPONSE_KEY_CITY_ID] as? Int) != nil) { let cityId = cityInfo[RESPONSE_KEY_CITY_ID] as! Int; self.city.id = cityId; } //Parse City Name if((cityInfo[RESPONSE_KEY_CITY_NAME] as? String) != nil) { let cityName = cityInfo[RESPONSE_KEY_CITY_NAME] as! String; self.city.name = cityName; } //Parse City Geo Coordinates if((cityInfo[RESPONSE_KEY_CITY_GEO_COORDINATES] as? NSDictionary) != nil) { let cityGeoCoords = cityInfo[RESPONSE_KEY_CITY_GEO_COORDINATES] as! NSDictionary; let latitude = cityGeoCoords[RESPONSE_KEY_LATITUDE] as! Double; let longitude = cityGeoCoords[RESPONSE_KEY_LONGITUDE] as! Double; self.city.geoCoordinates.latitude = latitude; self.city.geoCoordinates.longitude = longitude; } //Parse country name if((cityInfo[RESPONSE_KEY_COUNTRY] as? String) != nil) { let country = cityInfo[RESPONSE_KEY_COUNTRY] as! String; self.city.country = country; } } if((jsonResult[RESPONSE_KEY_COUNT] as? Int) == nil) { isError = true; break; } let dayCount = jsonResult[RESPONSE_KEY_COUNT] as! Int; if((jsonResult[RESPONSE_KEY_LIST] as? [[String:Any]]) == nil) { isError = true; break; } let weatherForDays = jsonResult[RESPONSE_KEY_LIST] as! [[String:Any]] for weatherInfo in weatherForDays { if((weatherInfo as? [String:Any]) == nil) { isError = true; break; } let weather = Weather(); if((weatherInfo[RESPONSE_KEY_TEMP] as? [String:Any]) == nil) { isError = true; break; } //Parse temperature information let tempInfo = weatherInfo[RESPONSE_KEY_TEMP] as! NSDictionary; let minDailyTemp = tempInfo[RESPONSE_KEY_MIN_DAILY_TEMP] as! Double; let maxDailyTemp = tempInfo[RESPONSE_KEY_MAX_DAILY_TEMP] as! Double; let morningTemp = tempInfo[RESPONSE_KEY_MORNING_TEMP] as! Double; let eveningTemp = tempInfo[RESPONSE_KEY_EVENING_TEMP] as! Double; let nightTemp = tempInfo[RESPONSE_KEY_NIGHT_TEMP] as! Double; let overAllTemp = tempInfo[RESPONSE_KEY_OVERALL_TEMP] as! Double; let dayTemperature = DayTemperature(); dayTemperature.minDailyTemp = minDailyTemp; dayTemperature.maxDailyTemp = maxDailyTemp; dayTemperature.morningTemp = morningTemp; dayTemperature.eveningTemp = eveningTemp; dayTemperature.nightTemp = nightTemp; dayTemperature.overAllTemp = overAllTemp; weather.temeperature = dayTemperature; //Parse weather information if((weatherInfo[RESPONSE_KEY_WEATHER] as? [[String:Any]]) == nil) { isError = true; break; } let weatherGroupInfoArray = weatherInfo[RESPONSE_KEY_WEATHER] as! [[String:Any]]; for weatherGroupInfo in weatherGroupInfoArray { let conditionID = weatherGroupInfo[RESPONSE_KEY_CONDITION_ID] as! Int; let iconID = weatherGroupInfo[RESPONSE_KEY_ICON_ID] as! String; let groupParameters = weatherGroupInfo[RESPONSE_KEY_GROUP_PARAMETERS] as! String; let conditionDescription = weatherGroupInfo[RESPONSE_KEY_CONDITION_DESCRIPTION] as! String; let weatherGroup = WeatherGroup(); weatherGroup.conditionID = conditionID; weatherGroup.iconID = iconID; weatherGroup.groupParameters = groupParameters; weatherGroup.conditionDescription = conditionDescription; weather.weatherGroups.append(weatherGroup); } let cloudiness = weatherInfo[RESPONSE_KEY_CLOUDINESS] as! Double; let windSpeed = weatherInfo[RESPONSE_KEY_WIND_SPEED] as! Double; let windDirectionInDegrees = weatherInfo[RESPONSE_KEY_WIND_DIRECTION_IN_DEGREES] as! Double; let humidity = weatherInfo[RESPONSE_KEY_HUMIDITY] as! Double; let pressure = weatherInfo[RESPONSE_KEY_PRESSURE] as! Double; let timeStamp = weatherInfo[RESPONSE_KEY_WEATHER_DATE] as! TimeInterval; let date = Date(timeIntervalSince1970: timeStamp); weather.cloudiness = cloudiness; weather.windSpeed = windSpeed; weather.windDirectionInDegrees = windDirectionInDegrees; weather.humidity = humidity; weather.pressure = pressure; weather.date = date; self.city.weatherForDays.append(weather); } if(isError) { self.city.state = CityWeatherRecordState.failed; NotificationCenter.default.post(name: Notification.Name(rawValue: NOTIFICATION_WEATHER_INFO_DOWNLOAD_FAILED), object: nil, userInfo: [REQUEST_KEY_CITY_NAME:requestCityName,CITY_INFO_KEY_CITY_NAME:self.city.name, RESPONSE_KEY_MESSAGE:errorMessage]); break; } //Update state self.city.state = CityWeatherRecordState.downloaded; NotificationCenter.default.post(name: Notification.Name(rawValue: NOTIFICATION_WEATHER_INFO_DOWNLOAD_COMPLETE), object: nil, userInfo: [REQUEST_KEY_CITY_NAME:requestCityName,CITY_INFO_KEY_CITY_NAME:self.city.name]); }while false if(isError) { self.city.state = CityWeatherRecordState.failed; NotificationCenter.default.post(name: Notification.Name(rawValue: NOTIFICATION_WEATHER_INFO_DOWNLOAD_FAILED), object: nil, userInfo: [REQUEST_KEY_CITY_NAME:requestCityName,CITY_INFO_KEY_CITY_NAME:self.city.name,RESPONSE_KEY_MESSAGE:errorMessage]); } } else { self.city.state = CityWeatherRecordState.failed; NotificationCenter.default.post(name: Notification.Name(rawValue: NOTIFICATION_WEATHER_INFO_DOWNLOAD_FAILED), object: nil, userInfo: [REQUEST_KEY_CITY_NAME:requestCityName,CITY_INFO_KEY_CITY_NAME:self.city.name,RESPONSE_KEY_MESSAGE:errorMessage]); } } catch { } } } }
mit
703c813c628b0fcb08c51c4337939f30
48.055738
280
0.457893
5.74357
false
false
false
false
BrandonMA/SwifterUI
SwifterUI/SwifterUI/UILibrary/Views/SFTextScrollSection.swift
1
1820
// // SFTextScrollSection // SwifterUI // // Created by brandon maldonado alonso on 10/02/18. // Copyright © 2018 Brandon Maldonado Alonso. All rights reserved. // import UIKit public final class SFTextScrollSection: SFSection { // MARK: - Instance Properties public final var textView: SFTextView! { return bottomView as? SFTextView } public override var useAlternativeColors: Bool { didSet { textView.useAlternativeColors = useAlternativeColors } } public override final var text: String? { get { guard let text = textView.text else { return nil } if text != "" { return text } else { return nil } } set { textView.text = newValue } } // MARK: - Initializer public init(automaticallyAdjustsColorStyle: Bool = true, useAlternativeColors: Bool = false, frame: CGRect = .zero) { let textView = SFTextView(automaticallyAdjustsColorStyle: automaticallyAdjustsColorStyle, useAlternativeColors: useAlternativeColors, frame: frame) textView.font = UIFont.systemFont textView.translatesAutoresizingMaskIntoConstraints = false textView.layer.cornerRadius = 10 textView.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) super.init(automaticallyAdjustsColorStyle: automaticallyAdjustsColorStyle, useAlternativeColors: useAlternativeColors, frame: frame, bottomView: textView) if automaticallyAdjustsColorStyle { updateColors() } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
20c74bbce3ba2a85ed375631718a8171
29.830508
162
0.627268
5.596923
false
false
false
false
fluttercommunity/plus_plugins
packages/connectivity_plus/connectivity_plus/macos/Classes/ConnectivityPlugin.swift
1
2697
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source is governed by a BSD-style license that can // be found in the LICENSE file. import Cocoa import FlutterMacOS public class ConnectivityPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { private let connectivityProvider: ConnectivityProvider private var eventSink: FlutterEventSink? init(connectivityProvider: ConnectivityProvider) { self.connectivityProvider = connectivityProvider super.init() self.connectivityProvider.connectivityUpdateHandler = connectivityUpdateHandler } public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel( name: "dev.fluttercommunity.plus/connectivity", binaryMessenger: registrar.messenger) let streamChannel = FlutterEventChannel( name: "dev.fluttercommunity.plus/connectivity_status", binaryMessenger: registrar.messenger) let connectivityProvider: ConnectivityProvider if #available(macOS 10.14, *) { connectivityProvider = PathMonitorConnectivityProvider() } else { connectivityProvider = ReachabilityConnectivityProvider() } let instance = ConnectivityPlugin(connectivityProvider: connectivityProvider) streamChannel.setStreamHandler(instance) registrar.addMethodCallDelegate(instance, channel: channel) } public func detachFromEngine(for registrar: FlutterPluginRegistrar) { eventSink = nil connectivityProvider.stop() } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "check": result(statusFrom(connectivityType: connectivityProvider.currentConnectivityType)) default: result(FlutterMethodNotImplemented) } } private func statusFrom(connectivityType: ConnectivityType) -> String { switch connectivityType { case .wifi: return "wifi" case .cellular: return "mobile" case .wiredEthernet: return "ethernet" case .none: return "none" } } public func onListen( withArguments _: Any?, eventSink events: @escaping FlutterEventSink ) -> FlutterError? { eventSink = events connectivityProvider.start() connectivityUpdateHandler(connectivityType: connectivityProvider.currentConnectivityType) return nil } private func connectivityUpdateHandler(connectivityType: ConnectivityType) { DispatchQueue.main.async { self.eventSink?(self.statusFrom(connectivityType: connectivityType)) } } public func onCancel(withArguments _: Any?) -> FlutterError? { connectivityProvider.stop() eventSink = nil return nil } }
bsd-3-clause
fffa29cc5f19c4fdd7f4cab56ec64199
29.647727
93
0.744531
4.976015
false
false
false
false
gunterhager/AnnotationClustering
AnnotationClustering/Code/AnnotationClusterView.swift
1
4707
// // AnnotationClusterView.swift // AnnotationClustering // // Created by Gunter Hager on 07.06.16. // Copyright © 2016 Gunter Hager. All rights reserved. // import UIKit import MapKit /// Annotation view that represents a cluster. If you reuse an instance of this view, be sure to call `reuseWithAnnotation()`. open class AnnotationClusterView : MKAnnotationView { /// Count of the annotations this cluster view represents. open var count = 0 { didSet { setNeedsLayout() } } fileprivate var fontSize: CGFloat = 12 fileprivate var imageName = "cluster_30" fileprivate var loadExternalImage = false fileprivate var countLabel: UILabel = UILabel() fileprivate var options: AnnotationClusterViewOptions? /** Creates a new cluster annotation view. - parameter annotation: Annotation that represents a cluster. - parameter reuseIdentifier: Identifier for reusing the annotation view. - parameter options: Options that customize the annotation view. - returns: Returns an initialised cluster annotation view. */ public init(annotation: AnnotationCluster?, reuseIdentifier: String?, options: AnnotationClusterViewOptions?) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) self.options = options guard let cluster = annotation else { return } updateViewFromCount(cluster.annotations.count) backgroundColor = UIColor.clear // Setup label self.countLabel.frame = bounds self.countLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.countLabel.textAlignment = .center self.countLabel.backgroundColor = UIColor.clear self.countLabel.textColor = UIColor.white self.countLabel.adjustsFontSizeToFitWidth = true self.countLabel.minimumScaleFactor = 0.8 self.countLabel.numberOfLines = 1 self.countLabel.font = UIFont.boldSystemFont(ofSize: fontSize) self.countLabel.baselineAdjustment = .alignCenters addSubview(self.countLabel) setNeedsLayout() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func layoutSubviews() { // Images are faster than using drawRect: let bundle: Bundle? = loadExternalImage ? nil : Bundle(for: AnnotationClusterView.self) let imageAsset = UIImage(named: imageName, in: bundle, compatibleWith: nil) countLabel.frame = self.bounds image = imageAsset centerOffset = CGPoint.zero guard let cluster = annotation as? AnnotationCluster else { return } updateViewFromCount(cluster.annotations.count) } /** Reuse the annotation view by providing a new annotation. Should be called after dequeing it from a map view. - parameter annotation: Annotation that represents a cluster. */ open func reuseWithAnnotation(_ annotation: AnnotationCluster) { self.annotation = annotation self.count = annotation.annotations.count } fileprivate func updateViewFromCount(_ count: Int) { countLabel.text = "\(count)" switch count { case 0...5: fontSize = 12 if let options = options { loadExternalImage = true; imageName = options.smallClusterImage } else { imageName = "cluster_30" } case 6...15: fontSize = 13 if let options = options { loadExternalImage = true; imageName = options.mediumClusterImage } else { imageName = "cluster_40" } default: fontSize = 14 if let options = options { loadExternalImage = true; imageName = options.largeClusterImage } else { imageName = "cluster_50" } } } } /** * Provides options for the annotation cluster view. */ public struct AnnotationClusterViewOptions { let smallClusterImage: String let mediumClusterImage: String let largeClusterImage: String public init(smallClusterImage: String, mediumClusterImage: String, largeClusterImage: String) { self.smallClusterImage = smallClusterImage self.mediumClusterImage = mediumClusterImage self.largeClusterImage = largeClusterImage } }
mit
e4cf1146d1bf86c182e17e1244acb409
30.583893
126
0.622822
5.510539
false
false
false
false
infobip/mobile-messaging-sdk-ios
Classes/Vendor/PSOperations/Operation.swift
1
12840
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the foundational subclass of NSOperation. */ import Foundation /** The subclass of `NSOperation` from which all other operations should be derived. This class adds both Conditions and Observers, which allow the operation to define extended readiness requirements, as well as notify many interested parties about interesting operation state changes */ open class Operation: Foundation.Operation { unowned(unsafe) open var underlyingQueue: DispatchQueue! /* The completionBlock property has unexpected behaviors such as executing twice and executing on unexpected threads. BlockObserver * executes in an expected manner. */ @available(*, deprecated, message: "use BlockObserver completions instead") override open var completionBlock: (() -> Void)? { set { fatalError("The completionBlock property on NSOperation has unexpected behavior and is not supported in PSOperations.Operation 😈") } get { return nil } } // use the KVO mechanism to indicate that changes to "state" affect other properties as well @objc class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> { return ["state" as NSObject] } @objc class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> { return ["state" as NSObject] } @objc class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> { return ["state" as NSObject] } @objc class func keyPathsForValuesAffectingIsCancelled() -> Set<NSObject> { return ["cancelledState" as NSObject] } private var instanceContext = 0 public override init() { super.init() self.addObserver(self, forKeyPath: "isReady", options: [], context: &instanceContext) } init(isUserInitiated: Bool) { super.init() self.userInitiated = isUserInitiated self.addObserver(self, forKeyPath: "isReady", options: [], context: &instanceContext) } deinit { self.removeObserver(self, forKeyPath: "isReady", context: &instanceContext) } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &instanceContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } stateAccess.lock() defer { stateAccess.unlock() } guard super.isReady && !isCancelled && state == .pending else { return } evaluateConditions() } /** Indicates that the Operation can now begin to evaluate readiness conditions, if appropriate. */ func didEnqueue() { stateAccess.lock() defer { stateAccess.unlock() } state = .pending } private let stateAccess = NSRecursiveLock() /// Private storage for the `state` property that will be KVO observed. private var _state = State.initialized private let stateQueue = DispatchQueue(label: "Operations.Operation.state") fileprivate var state: State { get { var currentState = State.initialized stateQueue.sync { currentState = _state } return currentState } set { // guard newValue != _state else { return } /* It's important to note that the KVO notifications are NOT called from inside the lock. If they were, the app would deadlock, because in the middle of calling the `didChangeValueForKey()` method, the observers try to access properties like "isReady" or "isFinished". Since those methods also acquire the lock, then we'd be stuck waiting on our own lock. It's the classic definition of deadlock. */ willChangeValue(forKey: "state") stateQueue.sync { guard _state != .finished else { return } assert(_state.canTransitionToState(newValue, operationIsCancelled: isCancelled), "Performing invalid state transition. from: \(_state) to: \(newValue)") _state = newValue } didChangeValue(forKey: "state") } } // Here is where we extend our definition of "readiness". override open var isReady: Bool { stateAccess.lock() defer { stateAccess.unlock() } guard super.isReady else { return false } guard !isCancelled else { return true } switch state { case .initialized, .evaluatingConditions, .pending: return false case .ready, .executing, .finishing, .finished: return true } } open var userInitiated: Bool { get { return qualityOfService == .userInitiated } set { stateAccess.lock() defer { stateAccess.unlock() } assert(state < .executing, "Cannot modify userInitiated after execution has begun.") qualityOfService = newValue ? .userInitiated : .default } } override open var isExecuting: Bool { return state == .executing } override open var isFinished: Bool { return state == .finished } private var __cancelled = false private let cancelledQueue = DispatchQueue(label: "Operations.Operation.cancelled") private var _cancelled: Bool { get { var currentState = false cancelledQueue.sync { currentState = __cancelled } return currentState } set { stateAccess.lock() defer { stateAccess.unlock() } guard _cancelled != newValue else { return } willChangeValue(forKey: "cancelledState") cancelledQueue.sync { __cancelled = newValue } if state == .initialized || state == .pending { state = .ready } didChangeValue(forKey: "cancelledState") if newValue { for observer in observers { observer.operationDidCancel(self) } } } } override open var isCancelled: Bool { return _cancelled } fileprivate func evaluateConditions() { stateAccess.lock() defer { stateAccess.unlock() } assert(state == .pending && !isCancelled, "evaluateConditions() was called out-of-order") guard conditions.count > 0 else { state = .ready return } state = .evaluatingConditions OperationConditionEvaluator.evaluate(conditions, operation: self) { failures in self.stateAccess.lock() defer { self.stateAccess.unlock() } if !failures.isEmpty { self.cancelWithErrors(failures) } self.state = .ready } } // MARK: Observers and Conditions fileprivate(set) var conditions: [OperationCondition] = [] open func addCondition(_ condition: OperationCondition) { assert(state < .evaluatingConditions, "Cannot modify conditions after execution has begun.") conditions.append(condition) } fileprivate(set) var observers: [OperationObserver] = [] open func addObserver(_ observer: OperationObserver) { assert(state < .executing, "Cannot modify observers after execution has begun.") observers.append(observer) } override open func addDependency(_ operation: Foundation.Operation) { assert(state <= .executing, "Dependencies cannot be modified after execution has begun.") super.addDependency(operation) } // MARK: Execution and Cancellation override final public func main() { stateAccess.lock() assert(state == .ready, "This operation must be performed on an operation queue.") if _internalErrors.isEmpty && !isCancelled { state = .executing stateAccess.unlock() for observer in observers { observer.operationDidStart(self) } execute() } else { finish() stateAccess.unlock() } } /** `execute()` is the entry point of execution for all `Operation` subclasses. If you subclass `Operation` and wish to customize its execution, you would do so by overriding the `execute()` method. At some point, your `Operation` subclass must call one of the "finish" methods defined below; this is how you indicate that your operation has finished its execution, and that operations dependent on yours can re-evaluate their readiness state. */ open func execute() { print("\(type(of: self)) must override `execute()`.") finish() } fileprivate var _internalErrors: [NSError] = [] open var errors : [NSError] { return _internalErrors } override open func cancel() { stateAccess.lock() defer { stateAccess.unlock() } guard !isFinished else { return } _cancelled = true if state > .ready { finish() } } open func cancelWithErrors(_ errors: [NSError]) { _internalErrors += errors cancel() } open func cancelWithError(_ error: NSError) { cancelWithErrors([error]) } public final func produceOperation(_ operation: Foundation.Operation) { for observer in observers { observer.operation(self, didProduceOperation: operation) } } // MARK: Finishing /** Most operations may finish with a single error, if they have one at all. This is a convenience method to simplify calling the actual `finish()` method. This is also useful if you wish to finish with an error provided by the system frameworks. As an example, see `DownloadEarthquakesOperation` for how an error from an `NSURLSession` is passed along via the `finishWithError()` method. */ public final func finishWithError(_ error: NSError?) { if let error = error { finish([error]) } else { finish() } } /** A private property to ensure we only notify the observers once that the operation has finished. */ fileprivate var hasFinishedAlready = false public final func finish(_ errors: [NSError] = []) { stateAccess.lock() defer { stateAccess.unlock() } guard !hasFinishedAlready else { return } hasFinishedAlready = true state = .finishing _internalErrors += errors let finishedBlock = { self.finished(self._internalErrors) } if userInitiated { DispatchQueue.main.async(execute: finishedBlock) } else { finishedBlock() } for observer in observers { observer.operationDidFinish(self, errors: _internalErrors) } state = .finished } /** Subclasses may override `finished(_:)` if they wish to react to the operation finishing with errors. For example, the `LoadModelOperation` implements this method to potentially inform the user about an error when trying to bring up the Core Data stack. */ open func finished(_ errors: [NSError]) { } // override open func waitUntilFinished() { // /* // Waiting on operations is almost NEVER the right thing to do. It is // usually superior to use proper locking constructs, such as `dispatch_semaphore_t` // or `dispatch_group_notify`, or even `NSLocking` objects. Many developers // use waiting when they should instead be chaining discrete operations // together using dependencies. // // To reinforce this idea, invoking `waitUntilFinished()` will crash your // app, as incentive for you to find a more appropriate way to express // the behavior you're wishing to create. // */ // fatalError("Waiting on operations is an anti-pattern.") // } }
apache-2.0
b36595bcdb1243bc3f8a3b3b168fb5e2
32.599476
168
0.594468
5.332364
false
false
false
false
mkaply/firefox-ios
Storage/ThirdParty/SwiftData.swift
9
64365
/* 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/. */ /* * This is a heavily modified version of SwiftData.swift by Ryan Fowler * This has been enhanced to support custom files, correct binding, versioning, * and a streaming results via Cursors. The API has also been changed to use NSError, Cursors, and * to force callers to request a connection before executing commands. Database creation helpers, savepoint * helpers, image support, and other features have been removed. */ // SwiftData.swift // // Copyright (c) 2014 Ryan Fowler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Shared import XCGLogger private let DatabaseBusyTimeout: Int32 = 3 * 1000 private let log = Logger.syncLogger public class DBOperationCancelled : MaybeErrorType { public var description: String { return "Database operation cancelled" } } class DeferredDBOperation<T>: CancellableDeferred<T> { fileprivate weak var connection: ConcreteSQLiteDBConnection? override func cancel() { objc_sync_enter(self) defer { objc_sync_exit(self) } if running { connection?.interrupt() } super.cancel() } } enum SQLiteDBConnectionCreatedResult { case success case failure case needsRecovery } // SQLite standard error codes when the DB file is locked, busy or the disk is // full. These error codes indicate that any issues with writing to the database // are temporary and we should not wipe out and re-create the database file when // we encounter them. enum SQLiteDBRecoverableError: Int { case Busy = 5 case Locked = 6 case ReadOnly = 8 case IOErr = 10 case Full = 13 } /** * Handle to a SQLite database. * Each instance holds a single connection that is shared across all queries. */ open class SwiftData { let filename: String let schema: Schema let files: FileAccessor static var EnableWAL = true static var EnableForeignKeys = true /// Used to keep track of the corrupted databases we've logged. static var corruptionLogsWritten = Set<String>() /// For thread-safe access to the primary shared connection. fileprivate let primaryConnectionQueue: DispatchQueue /// For thread-safe access to the secondary shared connection. fileprivate let secondaryConnectionQueue: DispatchQueue /// Primary shared connection to this database. fileprivate var primaryConnection: ConcreteSQLiteDBConnection? /// Secondary shared connection to this database. fileprivate var secondaryConnection: ConcreteSQLiteDBConnection? /// A simple state flag to track whether we should accept new connection requests. /// If a connection request is made while the database is closed, a /// FailedSQLiteDBConnection will be returned. fileprivate(set) var closed = false init(filename: String, schema: Schema, files: FileAccessor) { self.filename = filename self.schema = schema self.files = files self.primaryConnectionQueue = DispatchQueue(label: "SwiftData primary queue: \(filename)", attributes: []) self.secondaryConnectionQueue = DispatchQueue(label: "SwiftData secondary queue: \(filename)", attributes: []) // Ensure that SQLite/SQLCipher has been compiled with // `SQLITE_THREADSAFE=1` or `SQLITE_THREADSAFE=2`. // https://www.sqlite.org/compile.html#threadsafe // https://www.sqlite.org/threadsafe.html assert(sqlite3_threadsafe() > 0) } /** * The real meat of all the execute methods. This is used internally to open and * close a database connection and run a block of code inside it. */ func withConnection<T>(_ flags: SwiftData.Flags, synchronous: Bool = false, _ callback: @escaping (_ connection: SQLiteDBConnection) throws -> T) -> Deferred<Maybe<T>> { objc_sync_enter(self) defer { objc_sync_exit(self) } // We can only use the secondary queue if we already have a primary // connection and a read-only connection has been requested. This is // because if we do not yet have a primary connection, we need to ensure // we wait for any operations on the primary queue (such as schema prep). let queue: DispatchQueue let useSecondaryConnection: Bool if flags == .readOnly && primaryConnection != nil { queue = secondaryConnectionQueue useSecondaryConnection = true } else { queue = primaryConnectionQueue useSecondaryConnection = false } let deferred = DeferredDBOperation<Maybe<T>>() func doWork() { if deferred.cancelled { deferred.fill(Maybe(failure: DBOperationCancelled())) return } deferred.running = true defer { deferred.running = false deferred.connection = nil } if !self.closed { if useSecondaryConnection && self.secondaryConnection == nil { self.secondaryConnection = ConcreteSQLiteDBConnection(filename: self.filename, flags: SwiftData.Flags.readOnly, schema: self.schema, files: self.files) } else if self.primaryConnection == nil { self.primaryConnection = ConcreteSQLiteDBConnection(filename: self.filename, flags: SwiftData.Flags.readWriteCreate, schema: self.schema, files: self.files) } } guard let connection = useSecondaryConnection ? self.secondaryConnection : self.primaryConnection else { do { _ = try callback(FailedSQLiteDBConnection()) deferred.fill(Maybe(failure: NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not create a connection"]))) } catch let err as NSError { deferred.fill(Maybe(failure: DatabaseError(err: err))) } return } deferred.connection = connection if debugSimulateSlowDBOperations { sleep(2) } do { let result = try callback(connection) deferred.fill(Maybe(success: result)) } catch let err as NSError { deferred.fill(Maybe(failure: DatabaseError(err: err))) } } let work = DispatchWorkItem { doWork() } deferred.dispatchWorkItem = work if synchronous { queue.sync(execute: work) } else { queue.async(execute: work) } return deferred } /** * Helper for opening a connection, starting a transaction, and then running a block of code inside it. * The code block can return true if the transaction should be committed. False if we should roll back. */ func transaction<T>(synchronous: Bool = false, _ transactionClosure: @escaping (_ connection: SQLiteDBConnection) throws -> T) -> Deferred<Maybe<T>> { return withConnection(SwiftData.Flags.readWriteCreate, synchronous: synchronous) { connection in try connection.transaction(transactionClosure) } } /// Don't use this unless you know what you're doing. The deinitializer should be used to achieve refcounting semantics. /// The shutdown is *sync*, meaning the queue will complete the current db operations before closing. /// If an operation is queued with an open connection, it will execute before this runs. func forceClose() { primaryConnectionQueue.sync { guard !self.closed else { return } self.closed = true // Optimize the database if needed, but only on the read/write connection. self.primaryConnection?.optimize() self.primaryConnection = nil self.secondaryConnection = nil let baseFilename = URL(fileURLWithPath: self.filename).lastPathComponent NotificationCenter.default.post(name: .DatabaseWasClosed, object: baseFilename) } } /// Reopens a database that had previously been force-closed. /// Does nothing if this database is already open. func reopenIfClosed() { primaryConnectionQueue.sync { guard self.closed else { return } self.closed = false let baseFilename = URL(fileURLWithPath: self.filename).lastPathComponent NotificationCenter.default.post(name: .DatabaseWasReopened, object: baseFilename) } } public enum Flags { case readOnly case readWrite case readWriteCreate // We use `SQLITE_OPEN_NOMUTEX` here which effectively makes // `SQLITE_THREADSAFE=1` behave like `SQLITE_THREADSAFE=2`. // This is safe ONLY IF no two threads touch the same connection // at the same time. // https://www.sqlite.org/compile.html#threadsafe // https://www.sqlite.org/threadsafe.html fileprivate func toSQL() -> Int32 { switch self { case .readOnly: return SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READONLY case .readWrite: return SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE case .readWriteCreate: return SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE } } } } /** * Wrapper class for a SQLite statement. * This class helps manage the statement lifecycle. By holding a reference to the SQL connection, we ensure * the connection is never deinitialized while the statement is active. This class is responsible for * finalizing the SQL statement once it goes out of scope. */ private class SQLiteDBStatement { var pointer: OpaquePointer? fileprivate let connection: ConcreteSQLiteDBConnection init(connection: ConcreteSQLiteDBConnection, query: String, args: [Any?]?) throws { self.connection = connection let status = sqlite3_prepare_v2(connection.sqliteDB, query, -1, &pointer, nil) if status != SQLITE_OK { throw connection.createErr("During: SQL Prepare \(query)", status: Int(status)) } if let args = args, let bindError = bind(args) { throw bindError } } /// Binds arguments to the statement. fileprivate func bind(_ objects: [Any?]) -> NSError? { let count = Int(sqlite3_bind_parameter_count(pointer)) if count < objects.count { return connection.createErr("During: Bind", status: 202) } if count > objects.count { return connection.createErr("During: Bind", status: 201) } for (index, obj) in objects.enumerated() { var status: Int32 = SQLITE_OK // Doubles also pass obj as Int, so order is important here. if obj is Double { status = sqlite3_bind_double(pointer, Int32(index+1), obj as! Double) } else if obj is Int64 { status = sqlite3_bind_int64(pointer, Int32(index+1), Int64(obj as! Int64)) } else if obj is Int { status = sqlite3_bind_int(pointer, Int32(index+1), Int32(obj as! Int)) } else if obj is Bool { status = sqlite3_bind_int(pointer, Int32(index+1), (obj as! Bool) ? 1 : 0) } else if obj is String { typealias CFunction = @convention(c) (UnsafeMutableRawPointer?) -> Void let transient = unsafeBitCast(-1, to: CFunction.self) status = sqlite3_bind_text(pointer, Int32(index+1), (obj as! String).cString(using: .utf8)!, -1, transient) } else if obj is Data { status = sqlite3_bind_blob(pointer, Int32(index+1), ((obj as! Data) as NSData).bytes, -1, nil) } else if obj is Date { let timestamp = (obj as! Date).timeIntervalSince1970 status = sqlite3_bind_double(pointer, Int32(index+1), timestamp) } else if obj is UInt64 { status = sqlite3_bind_double(pointer, Int32(index+1), Double(obj as! UInt64)) } else if obj == nil { status = sqlite3_bind_null(pointer, Int32(index+1)) } if status != SQLITE_OK { return connection.createErr("During: Bind", status: Int(status)) } } return nil } func close() { if nil != self.pointer { sqlite3_finalize(self.pointer) self.pointer = nil } } deinit { if nil != self.pointer { sqlite3_finalize(self.pointer) } } } public protocol SQLiteDBConnection { var lastInsertedRowID: Int64 { get } var numberOfRowsModified: Int { get } var version: Int { get } func executeChange(_ sqlStr: String) throws -> Void func executeChange(_ sqlStr: String, withArgs args: Args?) throws -> Void func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> func transaction<T>(_ transactionClosure: @escaping (_ connection: SQLiteDBConnection) throws -> T) throws -> T func interrupt() func checkpoint() func checkpoint(_ mode: Int32) func optimize() func vacuum() throws -> Void func setVersion(_ version: Int) throws -> Void } // Represents a failure to open. class FailedSQLiteDBConnection: SQLiteDBConnection { var lastInsertedRowID: Int64 = 0 var numberOfRowsModified: Int = 0 var version: Int = 0 fileprivate func fail(_ str: String) -> NSError { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: str]) } func executeChange(_ sqlStr: String, withArgs args: Args?) throws -> Void { throw fail("Non-open connection; can't execute change.") } func executeChange(_ sqlStr: String) throws -> Void { throw fail("Non-open connection; can't execute change.") } func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> { return Cursor<T>(err: fail("Non-open connection; can't execute query.")) } func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { return Cursor<T>(err: fail("Non-open connection; can't execute query.")) } func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { return Cursor<T>(err: fail("Non-open connection; can't execute query.")) } func transaction<T>(_ transactionClosure: @escaping (_ connection: SQLiteDBConnection) throws -> T) throws -> T { throw fail("Non-open connection; can't start transaction.") } func interrupt() {} func checkpoint() {} func checkpoint(_ mode: Int32) {} func optimize() {} func vacuum() throws -> Void { throw fail("Non-open connection; can't vacuum.") } func setVersion(_ version: Int) throws -> Void { throw fail("Non-open connection; can't set user_version.") } } open class ConcreteSQLiteDBConnection: SQLiteDBConnection { open var lastInsertedRowID: Int64 { return Int64(sqlite3_last_insert_rowid(sqliteDB)) } open var numberOfRowsModified: Int { return Int(sqlite3_changes(sqliteDB)) } open var version: Int { return pragma("user_version", factory: IntFactory) ?? 0 } open var cipherVersion: String? { return pragma("cipher_version", factory: StringFactory) } fileprivate var sqliteDB: OpaquePointer? fileprivate let filename: String fileprivate let flags: SwiftData.Flags fileprivate let schema: Schema fileprivate let files: FileAccessor fileprivate let debug_enabled = false private var didAttemptToMoveToBackup = false init?(filename: String, flags: SwiftData.Flags, schema: Schema, files: FileAccessor) { log.debug("Opening connection to \(filename).") self.filename = filename self.flags = flags self.schema = schema self.files = files func doOpen() -> Bool { if let failure = openWithFlags(flags) { log.warning("Opening connection to \(filename) failed: \(failure).") return false } do { try self.prepareCleartext() } catch { return false } return true } // If we cannot even open the database file, return `nil` to force SwiftData // into using a `FailedSQLiteDBConnection` so we can retry opening again later. if !doOpen() { let extra = ["filename" : filename] Sentry.shared.sendWithStacktrace(message: "Cannot open a database connection.", tag: SentryTag.swiftData, severity: .error, extra: extra) return nil } // Now that we've successfully opened a connection to the database file, call // `prepareSchema()`. If it succeeds, our work here is done. If it returns // `.failure`, this means there was a temporary error preventing us from initing // the schema (e.g. SQLITE_BUSY, SQLITE_LOCK, SQLITE_FULL); so we return `nil` to // force SwiftData into using a `FailedSQLiteDBConnection` to retry preparing the // schema again later. However, if it returns `.needsRecovery`, this means there // was a permanent error preparing the schema and we need to move the current // database file to a backup location and start over with a brand new one. switch self.prepareSchema() { case .success: log.debug("Database successfully created or updated.") case .failure: Sentry.shared.sendWithStacktrace(message: "Failed to create or update the database schema.", tag: SentryTag.swiftData, severity: .error) return nil case .needsRecovery: Sentry.shared.sendWithStacktrace(message: "Database schema cannot be created or updated due to an unrecoverable error.", tag: SentryTag.swiftData, severity: .error) // We need to close this new connection before we can move the database file to // its backup location. If we cannot even close the connection, something has // gone really wrong. In that case, bail out and return `nil` to force SwiftData // into using a `FailedSQLiteDBConnection` so we can retry again later. if let error = self.closeCustomConnection(immediately: true) { Sentry.shared.sendWithStacktrace(message: "Cannot close the database connection to begin recovery.", tag: SentryTag.swiftData, severity: .error, description: error.localizedDescription) return nil } // Move the current database file to its backup location. self.moveDatabaseFileToBackupLocation() // If we cannot open the *new* database file (which shouldn't happen), return // `nil` to force SwiftData into using a `FailedSQLiteDBConnection` so we can // retry opening again later. if !doOpen() { log.error("Cannot re-open a database connection to the new database file to begin recovery.") Sentry.shared.sendWithStacktrace(message: "Cannot re-open a database connection to the new database file to begin recovery.", tag: SentryTag.swiftData, severity: .error) return nil } // Notify the world that we re-created the database schema. This allows us to // reset Sync and start over in the case of corruption. defer { let baseFilename = URL(fileURLWithPath: self.filename).lastPathComponent NotificationCenter.default.post(name: .DatabaseWasRecreated, object: baseFilename) } // Now that we've got a brand new database file, let's call `prepareSchema()` on // it to re-create the schema. Again, if this fails (it shouldn't), return `nil` // to force SwiftData into using a `FailedSQLiteDBConnection` so we can retry // again later. if self.prepareSchema() != .success { log.error("Cannot re-create the schema in the new database file to complete recovery.") Sentry.shared.sendWithStacktrace(message: "Cannot re-create the schema in the new database file to complete recovery.", tag: SentryTag.swiftData, severity: .error) return nil } } if debug_enabled { traceOn() } } deinit { log.debug("deinit: closing connection on thread \(Thread.current).") self.closeCustomConnection() } public func setVersion(_ version: Int) throws -> Void { try executeChange("PRAGMA user_version = \(version)") } public func interrupt() { log.debug("Interrupt") sqlite3_interrupt(sqliteDB) } fileprivate func pragma<T: Equatable>(_ pragma: String, expected: T?, factory: @escaping (SDRow) -> T, message: String) throws { let cursorResult = self.pragma(pragma, factory: factory) if cursorResult != expected { log.error("\(message): \(cursorResult.debugDescription), \(expected.debugDescription)") throw NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "PRAGMA didn't return expected output: \(message)."]) } } fileprivate func pragma<T>(_ pragma: String, factory: @escaping (SDRow) -> T) -> T? { let cursor = executeQueryUnsafe("PRAGMA \(pragma)", factory: factory, withArgs: [] as Args) defer { cursor.close() } return cursor[0] } fileprivate func prepareShared() { if SwiftData.EnableForeignKeys { let _ = pragma("foreign_keys=ON", factory: IntFactory) } // Retry queries before returning locked errors. sqlite3_busy_timeout(self.sqliteDB, DatabaseBusyTimeout) } fileprivate func prepareCleartext() throws { // If we just created the DB -- i.e., no tables have been created yet -- then // we can set the page size right now and save a vacuum. // // For where these values come from, see Bug 1213623. // // Note that sqlcipher uses cipher_page_size instead, but we don't set that // because it needs to be set from day one. let desiredPageSize = 32 * 1024 let _ = pragma("page_size=\(desiredPageSize)", factory: IntFactory) let currentPageSize = pragma("page_size", factory: IntFactory) // This has to be done without WAL, so we always hop into rollback/delete journal mode. if currentPageSize != desiredPageSize { try pragma("journal_mode=DELETE", expected: "delete", factory: StringFactory, message: "delete journal mode set") try pragma("page_size=\(desiredPageSize)", expected: nil, factory: IntFactory, message: "Page size set") log.info("Vacuuming to alter database page size from \(currentPageSize ?? 0) to \(desiredPageSize).") do { try vacuum() log.debug("Vacuuming succeeded.") } catch let err as NSError { log.error("Vacuuming failed: \(err.localizedDescription).") } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") let desiredPagesPerJournal = 16 let desiredCheckpointSize = desiredPagesPerJournal * desiredPageSize let desiredJournalSizeLimit = 3 * desiredCheckpointSize /* * With whole-module-optimization enabled in Xcode 7.2 and 7.2.1, the * compiler seems to eagerly discard these queries if they're simply * inlined, causing a crash in `pragma`. * * Hackily hold on to them. */ let journalModeQuery = "journal_mode=WAL" let autoCheckpointQuery = "wal_autocheckpoint=\(desiredPagesPerJournal)" let journalSizeQuery = "journal_size_limit=\(desiredJournalSizeLimit)" try withExtendedLifetime(journalModeQuery, { try pragma(journalModeQuery, expected: "wal", factory: StringFactory, message: "WAL journal mode set") }) try withExtendedLifetime(autoCheckpointQuery, { try pragma(autoCheckpointQuery, expected: desiredPagesPerJournal, factory: IntFactory, message: "WAL autocheckpoint set") }) try withExtendedLifetime(journalSizeQuery, { try pragma(journalSizeQuery, expected: desiredJournalSizeLimit, factory: IntFactory, message: "WAL journal size limit set") }) } self.prepareShared() } // Creates the database schema in a new database. fileprivate func createSchema() -> Bool { log.debug("Trying to create schema \(self.schema.name) at version \(self.schema.version)") if !schema.create(self) { // If schema couldn't be created, we'll bail without setting the `PRAGMA user_version`. log.debug("Creation failed.") return false } do { try setVersion(schema.version) } catch let error as NSError { log.error("Unable to set the schema version; \(error.localizedDescription)") } return true } // Updates the database schema in an existing database. fileprivate func updateSchema() -> Bool { log.debug("Trying to update schema \(self.schema.name) from version \(self.version) to \(self.schema.version)") if !schema.update(self, from: self.version) { // If schema couldn't be updated, we'll bail without setting the `PRAGMA user_version`. log.debug("Updating failed.") return false } do { try setVersion(schema.version) } catch let error as NSError { log.error("Unable to set the schema version; \(error.localizedDescription)") } return true } // Drops the database schema from an existing database. fileprivate func dropSchema() -> Bool { log.debug("Trying to drop schema \(self.schema.name)") if !self.schema.drop(self) { // If schema couldn't be dropped, we'll bail without setting the `PRAGMA user_version`. log.debug("Dropping failed.") return false } do { try setVersion(0) } catch let error as NSError { log.error("Unable to reset the schema version; \(error.localizedDescription)") } return true } // Checks if the database schema needs created or updated and acts accordingly. // Calls to this function will be serialized to prevent race conditions when // creating or updating the schema. fileprivate func prepareSchema() -> SQLiteDBConnectionCreatedResult { if self.flags == .readOnly { log.debug("Skipping schema (\(self.schema.name)) preparation for read-only connection.") return .success } Sentry.shared.addAttributes(["dbSchema.\(schema.name).version": schema.version]) // Get the current schema version for the database. let currentVersion = self.version // If the current schema version for the database matches the specified // `Schema` version, no further action is necessary and we can bail out. // NOTE: This assumes that we always use *ONE* `Schema` per database file // since SQLite can only track a single value in `PRAGMA user_version`. if currentVersion == schema.version { log.debug("Schema \(self.schema.name) already exists at version \(self.schema.version). Skipping additional schema preparation.") return .success } // Set an attribute for Sentry to include with any future error/crash // logs to indicate what schema version we're coming from and going to. Sentry.shared.addAttributes(["dbUpgrade.\(self.schema.name).from": currentVersion, "dbUpgrade.\(self.schema.name).to": self.schema.version]) // This should not ever happen since the schema version should always be // increasing whenever a structural change is made in an app update. guard currentVersion <= schema.version else { let errorString = "\(self.schema.name) cannot be downgraded from version \(currentVersion) to \(self.schema.version)." Sentry.shared.sendWithStacktrace(message: "Schema cannot be downgraded.", tag: SentryTag.swiftData, severity: .error, description: errorString) return .failure } log.debug("Schema \(self.schema.name) needs created or updated from version \(currentVersion) to \(self.schema.version).") var success = true do { success = try transaction { connection -> Bool in log.debug("Create or update \(self.schema.name) version \(self.schema.version) on \(Thread.current.description).") // If `PRAGMA user_version` is zero, check if we can safely create the // database schema from scratch. if connection.version == 0 { // Query for the existence of the `tableList` table to determine if we are // migrating from an older DB version. let sqliteMasterCursor = connection.executeQueryUnsafe("SELECT count(*) AS number FROM sqlite_master WHERE type = 'table' AND name = 'tableList'", factory: IntFactory, withArgs: [] as Args) let tableListTableExists = sqliteMasterCursor[0] == 1 sqliteMasterCursor.close() // If the `tableList` table doesn't exist, we can simply invoke // `createSchema()` to create a brand new DB from scratch. if !tableListTableExists { log.debug("Schema \(self.schema.name) doesn't exist. Creating.") success = self.createSchema() return success } } Sentry.shared.send(message: "Attempting to update schema", tag: SentryTag.swiftData, severity: .info, description: "\(currentVersion) to \(self.schema.version).") // If we can't create a brand new schema from scratch, we must // call `updateSchema()` to go through the update process. if self.updateSchema() { log.debug("Updated schema \(self.schema.name).") success = true return success } // If we failed to update the schema, we'll drop everything from the DB // and create everything again from scratch. Assuming our schema upgrade // code is correct, this *shouldn't* happen. If it does, log it to Sentry. Sentry.shared.sendWithStacktrace(message: "Update failed for schema. Dropping and re-creating.", tag: SentryTag.swiftData, severity: .error, description: "\(self.schema.name) from version \(currentVersion) to \(self.schema.version)") // If we can't even drop the schema here, something has gone really wrong, so // return `false` which should force us into recovery. if !self.dropSchema() { Sentry.shared.sendWithStacktrace(message: "Unable to drop schema.", tag: SentryTag.swiftData, severity: .error, description: "\(self.schema.name) from version \(currentVersion).") success = false return success } // Try to re-create the schema. If this fails, we are out of options and we'll // return `false` which should force us into recovery. success = self.createSchema() return success } } catch let error as NSError { // If we got an error trying to get a transaction, then we either bail out early and return // `.failure` if we think we can retry later or return `.needsRecovery` if the error is not // recoverable. Sentry.shared.sendWithStacktrace(message: "Unable to get a transaction", tag: SentryTag.swiftData, severity: .error, description: "\(error.localizedDescription)") // Check if the error we got is recoverable (e.g. SQLITE_BUSY, SQLITE_LOCK, SQLITE_FULL). // If so, just return `.failure` so we can retry preparing the schema again later. if let _ = SQLiteDBRecoverableError(rawValue: error.code) { return .failure } // Otherwise, this is a non-recoverable error and we return `.needsRecovery` so the database // file can be backed up and a new one will be created. return .needsRecovery } // If any of our operations inside the transaction failed, this also means we need to go through // the recovery process to re-create the database from scratch. if !success { return .needsRecovery } // No error means we're all good! \o/ return .success } fileprivate func moveDatabaseFileToBackupLocation() { didAttemptToMoveToBackup = true let baseFilename = URL(fileURLWithPath: filename).lastPathComponent // Attempt to make a backup as long as the database file still exists. if files.exists(baseFilename) { Sentry.shared.sendWithStacktrace(message: "Couldn't create or update schema. Attempted to move db to another location.", tag: SentryTag.swiftData, severity: .warning, description: "Attempting to move '\(baseFilename)' for schema '\(self.schema.name)'") // Note that a backup file might already exist! We append a counter to avoid this. var bakCounter = 0 var bak: String repeat { bakCounter += 1 bak = "\(baseFilename).bak.\(bakCounter)" } while files.exists(bak) do { try files.move(baseFilename, toRelativePath: bak) let shm = baseFilename + "-shm" let wal = baseFilename + "-wal" log.debug("Moving \(shm) and \(wal)…") if files.exists(shm) { log.debug("\(shm) exists.") try files.move(shm, toRelativePath: bak + "-shm") } if files.exists(wal) { log.debug("\(wal) exists.") try files.move(wal, toRelativePath: bak + "-wal") } log.debug("Finished moving database \(baseFilename) successfully.") } catch let error as NSError { Sentry.shared.sendWithStacktrace(message: "Unable to move db to another location", tag: SentryTag.swiftData, severity: .error, description: "DB file '\(baseFilename)'. \(error.localizedDescription)") } } else { // No backup was attempted since the database file did not exist. Sentry.shared.sendWithStacktrace(message: "The database file has been deleted while previously in use.", tag: SentryTag.swiftData, description: "DB file '\(baseFilename)'") } } public func checkpoint() { self.checkpoint(SQLITE_CHECKPOINT_FULL) } /** * Blindly attempts a WAL checkpoint on all attached databases. */ public func checkpoint(_ mode: Int32) { guard sqliteDB != nil else { log.warning("Trying to checkpoint a nil DB!") return } log.debug("Running WAL checkpoint on \(self.filename) on thread \(Thread.current).") sqlite3_wal_checkpoint_v2(sqliteDB, nil, mode, nil, nil) log.debug("WAL checkpoint done on \(self.filename).") } public func optimize() { _ = pragma("optimize", factory: StringFactory) } public func vacuum() throws -> Void { try executeChange("VACUUM") } // Developers can manually add a call to this to trace to console. func traceOn() { let uMask = UInt32( SQLITE_TRACE_STMT | SQLITE_TRACE_PROFILE | SQLITE_TRACE_ROW | SQLITE_TRACE_CLOSE ) // https://stackoverflow.com/questions/43593618/sqlite-trace-for-logging/43595437 sqlite3_trace_v2(sqliteDB, uMask, { (reason, context, p, x) -> Int32 in switch Int32(reason) { case SQLITE_TRACE_STMT: // The P argument is a pointer to the prepared statement. // The X argument is a pointer to a string which is the unexpanded SQL text guard let pStmt = OpaquePointer(p) /*, let cSql = x?.assumingMemoryBound(to: CChar.self) */ else { return 0 } // let sql = String(cString: cSql) // The unexpanded SQL text let expandedSql = String(cString: sqlite3_expanded_sql(pStmt)) // The expanded SQL text print("SQLITE_TRACE_STMT:", expandedSql) case SQLITE_TRACE_PROFILE: // The P argument is a pointer to the prepared statement and the X argument points // to a 64-bit integer which is the estimated of the number of nanosecond that the // prepared statement took to run. guard let pStmt = OpaquePointer(p), let duration = x?.load(as: UInt64.self) else { return 0 } let milliSeconds = Double(duration)/Double(NSEC_PER_MSEC) let sql = String(cString: sqlite3_sql(pStmt)) // The unexpanded SQL text print("SQLITE_TRACE_PROFILE:", milliSeconds, "ms for statement:", sql) case SQLITE_TRACE_ROW: // The P argument is a pointer to the prepared statement and the X argument is unused. guard let _ = OpaquePointer(p) else { return 0 } print("SQLITE_TRACE_ROW") case SQLITE_TRACE_CLOSE: // The P argument is a pointer to the database connection object and the X argument is unused. guard let _ = OpaquePointer(p) else { return 0 } print("SQLITE_TRACE_CLOSE") default: break } return 0 }, nil) } /// Creates an error from a sqlite status. Will print to the console if debug_enabled is set. /// Do not call this unless you're going to return this error. fileprivate func createErr(_ description: String, status: Int) -> NSError { var msg = SDError.errorMessageFromCode(status) if debug_enabled { log.debug("SwiftData Error -> \(description)") log.debug(" -> Code: \(status) - \(msg)") } if let errMsg = String(validatingUTF8: sqlite3_errmsg(sqliteDB)) { msg += " " + errMsg if debug_enabled { log.debug(" -> Details: \(errMsg)") } } return NSError(domain: "org.mozilla", code: status, userInfo: [NSLocalizedDescriptionKey: msg]) } /// Open the connection. This is called when the db is created. You should not call it yourself. fileprivate func openWithFlags(_ flags: SwiftData.Flags) -> NSError? { let status = sqlite3_open_v2(filename.cString(using: .utf8)!, &sqliteDB, flags.toSQL(), nil) if status != SQLITE_OK { return createErr("During: Opening Database with Flags", status: Int(status)) } guard let _ = self.cipherVersion else { // XXX: Temporarily remove this assertion until we find a way to // reuse the copy of sqlcipher that comes with the Rust components. // return createErr("Expected SQLCipher, got SQLite", status: Int(-1)) log.warning("Database \(self.filename) was not opened with SQLCipher") return nil } // Since we're using SQLCipher, ensure that `cipher_memory_security` is // turned off. Otherwise, there is a HUGE performance penalty. _ = pragma("cipher_memory_security=OFF", factory: StringFactory) return nil } /// Closes a connection. This is called via deinit. Do not call this yourself. @discardableResult fileprivate func closeCustomConnection(immediately: Bool = false) -> NSError? { log.debug("Closing custom connection for \(self.filename) on \(Thread.current).") // TODO: add a lock here? let db = self.sqliteDB self.sqliteDB = nil // Don't bother trying to call sqlite3_close multiple times. guard db != nil else { log.warning("Connection was nil.") return nil } var status = sqlite3_close(db) if status != SQLITE_OK { Sentry.shared.sendWithStacktrace(message: "Got error status while attempting to close.", tag: SentryTag.swiftData, severity: .error, description: "SQLite status: \(status)") if immediately { return createErr("During: closing database with flags", status: Int(status)) } // Note that if we use sqlite3_close_v2, this will still return SQLITE_OK even if // there are outstanding prepared statements status = sqlite3_close_v2(db) if status != SQLITE_OK { // Based on the above comment regarding sqlite3_close_v2, this shouldn't happen. Sentry.shared.sendWithStacktrace(message: "Got error status while attempting to close_v2.", tag: SentryTag.swiftData, severity: .error, description: "SQLite status: \(status)") return createErr("During: closing database with flags", status: Int(status)) } } log.debug("Closed \(self.filename).") return nil } open func executeChange(_ sqlStr: String) throws -> Void { try executeChange(sqlStr, withArgs: nil) } /// Executes a change on the database. open func executeChange(_ sqlStr: String, withArgs args: Args?) throws -> Void { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } // Close, not reset -- this isn't going to be reused. defer { statement?.close() } if debug_enabled { let timer = PerformanceTimer(thresholdSeconds: 0.01, label: "executeChange") defer { timer.stopAndPrint() } explain(query: sqlStr, withArgs: args) } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) Sentry.shared.sendWithStacktrace(message: "SQLITE_CORRUPT", tag: SentryTag.swiftData, severity: .error, description: "DB file '\(filename)'. \(error.localizedDescription)") } let message = "Error code: \(error.code), \(error) for SQL \(String(sqlStr.prefix(500)))." Sentry.shared.sendWithStacktrace(message: "SQL error", tag: SentryTag.swiftData, severity: .error, description: message) throw error } let status = sqlite3_step(statement!.pointer) if status != SQLITE_DONE && status != SQLITE_OK { throw createErr("During: SQL Step \(sqlStr)", status: Int(status)) } } public func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T)) -> Cursor<T> { return self.executeQuery(sqlStr, factory: factory, withArgs: nil) } func explain(query sqlStr: String, withArgs args: Args?) { do { let qp = try SQLiteDBStatement(connection: self, query: "EXPLAIN QUERY PLAN \(sqlStr)", args: args) let qpFactory: ((SDRow) -> String) = { row in return "id: \(row[0] as! Int), order: \(row[1] as! Int), from: \(row[2] as! Int), details: \(row[3] as! String)" } let qpCursor = FilledSQLiteCursor<String>(statement: qp, factory: qpFactory) print("⦿ EXPLAIN QUERY (Columns: id, order, from, details) ---------------- ") qpCursor.forEach { print("⦿ EXPLAIN: \($0 ?? "")") } } catch { print("Explain query plan failed!") } } /// Queries the database. /// Returns a cursor pre-filled with the complete result set. public func executeQuery<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } // Close, not reset -- this isn't going to be reused, and the FilledSQLiteCursor // consumes everything. defer { statement?.close() } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) Sentry.shared.sendWithStacktrace(message: "SQLITE_CORRUPT", tag: SentryTag.swiftData, severity: .error, description: "DB file '\(filename)'. \(error.localizedDescription)") } // Don't log errors caused by `sqlite3_interrupt()` to Sentry. if error.code != Int(SQLITE_INTERRUPT) { Sentry.shared.sendWithStacktrace(message: "SQL error", tag: SentryTag.swiftData, severity: .error, description: "Error code: \(error.code), \(error) for SQL \(String(sqlStr.prefix(500))).") } return Cursor<T>(err: error) } if debug_enabled { let timer = PerformanceTimer(thresholdSeconds: 0.01, label: "executeQuery") defer { timer.stopAndPrint() } explain(query: sqlStr, withArgs: args) } return FilledSQLiteCursor<T>(statement: statement!, factory: factory) } func writeCorruptionInfoForDBNamed(_ dbFilename: String, toLogger logger: XCGLogger) { DispatchQueue.global(qos: DispatchQoS.default.qosClass).sync { guard !SwiftData.corruptionLogsWritten.contains(dbFilename) else { return } logger.error("Corrupt DB detected! DB filename: \(dbFilename)") let dbFileSize = ("file://\(dbFilename)".asURL)?.allocatedFileSize() ?? 0 logger.error("DB file size: \(dbFileSize) bytes") logger.error("Integrity check:") let args: [Any?]? = nil let messages = self.executeQueryUnsafe("PRAGMA integrity_check", factory: StringFactory, withArgs: args) defer { messages.close() } if messages.status == CursorStatus.success { for message in messages { logger.error(message) } logger.error("----") } else { logger.error("Couldn't run integrity check: \(messages.statusMessage).") } // Write call stack. logger.error("Call stack: ") for message in Thread.callStackSymbols { logger.error(" >> \(message)") } logger.error("----") // Write open file handles. let openDescriptors = FSUtils.openFileDescriptors() logger.error("Open file descriptors: ") for (k, v) in openDescriptors { logger.error(" \(k): \(v)") } logger.error("----") SwiftData.corruptionLogsWritten.insert(dbFilename) } } /** * Queries the database. * Returns a live cursor that holds the query statement and database connection. * Instances of this class *must not* leak outside of the connection queue! */ public func executeQueryUnsafe<T>(_ sqlStr: String, factory: @escaping ((SDRow) -> T), withArgs args: Args?) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } if let error = error { return Cursor(err: error) } return LiveSQLiteCursor(statement: statement!, factory: factory) } public func transaction<T>(_ transactionClosure: @escaping (_ connection: SQLiteDBConnection) throws -> T) throws -> T { do { try executeChange("BEGIN EXCLUSIVE") } catch let err as NSError { Sentry.shared.sendWithStacktrace(message: "BEGIN EXCLUSIVE failed.", tag: SentryTag.swiftData, severity: .error, description: "\(err.code), \(err)") throw err } var result: T do { result = try transactionClosure(self) } catch let err as NSError { log.error("Op in transaction threw an error. Rolling back.") Sentry.shared.sendWithStacktrace(message: "Op in transaction threw an error. Rolling back.", tag: SentryTag.swiftData, severity: .error) do { try executeChange("ROLLBACK") } catch let err as NSError { Sentry.shared.sendWithStacktrace(message: "ROLLBACK after errored op in transaction failed", tag: SentryTag.swiftData, severity: .error, description: "\(err.code), \(err)") throw err } throw err } log.verbose("Op in transaction succeeded. Committing.") do { try executeChange("COMMIT") } catch let err as NSError { Sentry.shared.sendWithStacktrace(message: "COMMIT failed. Rolling back.", tag: SentryTag.swiftData, severity: .error, description: "\(err.code), \(err)") do { try executeChange("ROLLBACK") } catch let err as NSError { Sentry.shared.sendWithStacktrace(message: "ROLLBACK after failed COMMIT failed.", tag: SentryTag.swiftData, severity: .error, description: "\(err.code), \(err)") throw err } throw err } return result } } /// Helper for queries that return a single integer result. func IntFactory(_ row: SDRow) -> Int { return row[0] as! Int } /// Helper for queries that return a single String result. func StringFactory(_ row: SDRow) -> String { return row[0] as! String } /// Wrapper around a statement for getting data from a row. This provides accessors for subscript indexing /// and a generator for iterating over columns. open class SDRow: Sequence { // The sqlite statement this row came from. fileprivate let statement: SQLiteDBStatement // The columns of this database. The indices of these are assumed to match the indices // of the statement. fileprivate let columnNames: [String] fileprivate init(statement: SQLiteDBStatement, columns: [String]) { self.statement = statement self.columnNames = columns } // Return the value at this index in the row fileprivate func getValue(_ index: Int) -> Any? { let i = Int32(index) let type = sqlite3_column_type(statement.pointer, i) var ret: Any? = nil switch type { case SQLITE_NULL: return nil case SQLITE_INTEGER: //Everyone expects this to be an Int. On Ints larger than 2^31 this will lose information. ret = Int(truncatingIfNeeded: sqlite3_column_int64(statement.pointer, i)) case SQLITE_TEXT: if let text = sqlite3_column_text(statement.pointer, i) { return String(cString: text) } case SQLITE_BLOB: if let blob = sqlite3_column_blob(statement.pointer, i) { let size = sqlite3_column_bytes(statement.pointer, i) ret = Data(bytes: blob, count: Int(size)) } case SQLITE_FLOAT: ret = Double(sqlite3_column_double(statement.pointer, i)) default: log.warning("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil") } return ret } // Accessor getting column 'key' in the row public subscript(key: Int) -> Any? { return getValue(key) } // Accessor getting a named column in the row. This (currently) depends on // the columns array passed into this Row to find the correct index. public subscript(key: String) -> Any? { get { if let index = columnNames.firstIndex(of: key) { return getValue(index) } return nil } } // Allow iterating through the row. public func makeIterator() -> AnyIterator<Any> { let nextIndex = 0 return AnyIterator() { if nextIndex < self.columnNames.count { return self.getValue(nextIndex) } return nil } } } /// Helper for pretty printing SQL (and other custom) error codes. private struct SDError { fileprivate static func errorMessageFromCode(_ errorCode: Int) -> String { switch errorCode { case -1: return "No error" // SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html case 0: return "Successful result" case 1: return "SQL error or missing database" case 2: return "Internal logic error in SQLite" case 3: return "Access permission denied" case 4: return "Callback routine requested an abort" case 5: return "The database file is busy" case 6: return "A table in the database is locked" case 7: return "A malloc() failed" case 8: return "Attempt to write a readonly database" case 9: return "Operation terminated by sqlite3_interrupt()" case 10: return "Some kind of disk I/O error occurred" case 11: return "The database disk image is malformed" case 12: return "Unknown opcode in sqlite3_file_control()" case 13: return "Insertion failed because database is full" case 14: return "Unable to open the database file" case 15: return "Database lock protocol error" case 16: return "Database is empty" case 17: return "The database schema changed" case 18: return "String or BLOB exceeds size limit" case 19: return "Abort due to constraint violation" case 20: return "Data type mismatch" case 21: return "Library used incorrectly" case 22: return "Uses OS features not supported on host" case 23: return "Authorization denied" case 24: return "Auxiliary database format error" case 25: return "2nd parameter to sqlite3_bind out of range" case 26: return "File opened that is not a database file" case 27: return "Notifications from sqlite3_log()" case 28: return "Warnings from sqlite3_log()" case 100: return "sqlite3_step() has another row ready" case 101: return "sqlite3_step() has finished executing" // Custom SwiftData errors // Binding errors case 201: return "Not enough objects to bind provided" case 202: return "Too many objects to bind provided" // Custom connection errors case 301: return "A custom connection is already open" case 302: return "Cannot open a custom connection inside a transaction" case 303: return "Cannot open a custom connection inside a savepoint" case 304: return "A custom connection is not currently open" case 305: return "Cannot close a custom connection inside a transaction" case 306: return "Cannot close a custom connection inside a savepoint" // Index and table errors case 401: return "At least one column name must be provided" case 402: return "Error extracting index names from sqlite_master" case 403: return "Error extracting table names from sqlite_master" // Transaction and savepoint errors case 501: return "Cannot begin a transaction within a savepoint" case 502: return "Cannot begin a transaction within another transaction" // Unknown error default: return "Unknown error" } } } /// Provides access to the result set returned by a database query. /// The entire result set is cached, so this does not retain a reference /// to the statement or the database connection. private class FilledSQLiteCursor<T>: ArrayCursor<T> { fileprivate init(statement: SQLiteDBStatement, factory: (SDRow) -> T) { let (data, status, statusMessage) = FilledSQLiteCursor.getValues(statement, factory: factory) super.init(data: data, status: status, statusMessage: statusMessage) } /// Return an array with the set of results and release the statement. fileprivate class func getValues(_ statement: SQLiteDBStatement, factory: (SDRow) -> T) -> ([T], CursorStatus, String) { var rows = [T]() var status = CursorStatus.success var statusMessage = "Success" var count = 0 var columns = [String]() let columnCount = sqlite3_column_count(statement.pointer) for i in 0..<columnCount { let columnName = String(cString: sqlite3_column_name(statement.pointer, i)) columns.append(columnName) } while true { let sqlStatus = sqlite3_step(statement.pointer) if sqlStatus != SQLITE_ROW { if sqlStatus != SQLITE_DONE { // NOTE: By setting our status to failure here, we'll report our count as zero, // regardless of how far we've read at this point. status = CursorStatus.failure statusMessage = SDError.errorMessageFromCode(Int(sqlStatus)) } break } count += 1 let row = SDRow(statement: statement, columns: columns) let result = factory(row) rows.append(result) } return (rows, status, statusMessage) } } /// Wrapper around a statement to help with iterating through the results. private class LiveSQLiteCursor<T>: Cursor<T> { fileprivate var statement: SQLiteDBStatement! // Function for generating objects of type T from a row. fileprivate let factory: (SDRow) -> T // Status of the previous fetch request. fileprivate var sqlStatus: Int32 = 0 // Number of rows in the database // XXX - When Cursor becomes an interface, this should be a normal property, but right now // we can't override the Cursor getter for count with a stored property. fileprivate var _count: Int = 0 override var count: Int { get { if status != .success { return 0 } return _count } } fileprivate var position: Int = -1 { didSet { // If we're already there, shortcut out. if oldValue == position { return } var stepStart = oldValue // If we're currently somewhere in the list after this position // we'll have to jump back to the start. if position < oldValue { sqlite3_reset(self.statement.pointer) stepStart = -1 } // Now step up through the list to the requested position for _ in stepStart..<position { sqlStatus = sqlite3_step(self.statement.pointer) } } } init(statement: SQLiteDBStatement, factory: @escaping (SDRow) -> T) { self.factory = factory self.statement = statement // The only way I know to get a count. Walk through the entire statement to see how many rows there are. var count = 0 self.sqlStatus = sqlite3_step(statement.pointer) while self.sqlStatus != SQLITE_DONE { count += 1 self.sqlStatus = sqlite3_step(statement.pointer) } sqlite3_reset(statement.pointer) self._count = count super.init(status: .success, msg: "success") } // Helper for finding all the column names in this statement. fileprivate lazy var columns: [String] = { // This untangles all of the columns and values for this row when its created let columnCount = sqlite3_column_count(self.statement.pointer) var columns = [String]() for i: Int32 in 0 ..< columnCount { let columnName = String(cString: sqlite3_column_name(self.statement.pointer, i)) columns.append(columnName) } return columns }() override subscript(index: Int) -> T? { get { if status != .success { return nil } self.position = index if self.sqlStatus != SQLITE_ROW { return nil } let row = SDRow(statement: statement, columns: self.columns) return self.factory(row) } } override func close() { statement = nil super.close() } }
mpl-2.0
ec2909d96970da9d98c947c7faa27749
39.9669
264
0.607856
4.844851
false
false
false
false
furuya02/ARKitFurnitureArrangementSample
ARKitFurnitureArrangementSample/RecordingButton.swift
1
2441
// // RecordingButton.swift // ARKitMeasurementSample // // Created by SIN on 2017/09/01. // Copyright © 2017年 Classmethod.Inc. All rights reserved. // import UIKit import ReplayKit class RecordingButton : UIButton { var isRecording = false let height:CGFloat = 50.0 let width:CGFloat = 100.0 let viewController: UIViewController! required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(_ viewController: UIViewController) { self.viewController = viewController super.init(frame: CGRect(x:0, y:0, width:width, height:height)) // layer.position = CGPoint(x: viewController.view.frame.width/2, y:viewController.view.frame.height - height) layer.position = CGPoint(x: width/2, y:viewController.view.frame.height - height) layer.cornerRadius = 10 layer.borderWidth = 1 setTitleColor(UIColor.white, for: .normal) addTarget(self, action: #selector(tapped), for:.touchUpInside) setAppearance() viewController.view.addSubview(self) } @objc func tapped() { if !isRecording { isRecording = true RPScreenRecorder.shared().startRecording(handler: { (error) in print(error as Any) }) } else { isRecording = false RPScreenRecorder.shared().stopRecording(handler: { (previewViewController, error) in previewViewController?.previewControllerDelegate = self self.viewController.present(previewViewController!, animated: true, completion: nil) }) } setAppearance() } func setAppearance() { var alpha:CGFloat = 1.0 var title = "REC" if isRecording { title = "" alpha = 0 } setTitle(title, for: .normal) backgroundColor = UIColor(red: 0.7, green: 0, blue: 0, alpha: alpha) layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: alpha).cgColor } } extension RecordingButton: RPPreviewViewControllerDelegate { func previewControllerDidFinish(_ previewController: RPPreviewViewController) { DispatchQueue.main.async { [unowned previewController] in previewController.dismiss(animated: true, completion: nil) } } }
mit
82b8e87e684a6a95f92fc4797364c993
29.860759
125
0.614028
4.733981
false
false
false
false
humeng12/DouYuZB
DouYuZB/Pods/Alamofire/Source/Request.swift
1
22466
// // Request.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. public protocol RequestAdapter { /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. /// /// - parameter urlRequest: The URL request to adapt. /// /// - throws: An `Error` if the adaptation encounters an error. /// /// - returns: The adapted `URLRequest`. func adapt(_ urlRequest: URLRequest) throws -> URLRequest } // MARK: - /// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void /// A type that determines whether a request should be retried after being executed by the specified session manager /// and encountering an error. public protocol RequestRetrier { /// Determines whether the `Request` should be retried by calling the `completion` closure. /// /// This operation is fully asychronous. Any amount of time can be taken to determine whether the request needs /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly /// cleaned up after. /// /// - parameter manager: The session manager the request was executed on. /// - parameter request: The request that failed due to the encountered error. /// - parameter error: The error encountered when executing the request. /// - parameter completion: The completion closure to be executed when retry decision has been determined. @available(iOS 9.0, *) func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) } // MARK: - protocol TaskConvertible { func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask } /// A dictionary of headers to apply to a `URLRequest`. public typealias HTTPHeaders = [String: String] // MARK: - /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. open class Request { // MARK: Helper Types /// A closure executed when monitoring upload or download progress of a request. public typealias ProgressHandler = (Progress) -> Void enum RequestTask { case data(TaskConvertible?, URLSessionTask?) case download(TaskConvertible?, URLSessionTask?) case upload(TaskConvertible?, URLSessionTask?) case stream(TaskConvertible?, URLSessionTask?) } // MARK: Properties /// The delegate for the underlying task. open internal(set) var delegate: TaskDelegate { get { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } return taskDelegate } set { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } taskDelegate = newValue } } /// The underlying task. open var task: URLSessionTask? { return delegate.task } /// The session belonging to the underlying task. open let session: URLSession /// The request sent or to be sent to the server. open var request: URLRequest? { return task?.originalRequest } /// The response received from the server, if any. open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } let originalTask: TaskConvertible? var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? var validations: [() -> Void] = [] private var taskDelegate: TaskDelegate private var taskDelegateLock = NSLock() // MARK: Lifecycle init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { self.session = session switch requestTask { case .data(let originalTask, let task): taskDelegate = DataTaskDelegate(task: task) self.originalTask = originalTask case .download(let originalTask, let task): taskDelegate = DownloadTaskDelegate(task: task) self.originalTask = originalTask case .upload(let originalTask, let task): taskDelegate = UploadTaskDelegate(task: task) self.originalTask = originalTask case .stream(let originalTask, let task): taskDelegate = TaskDelegate(task: task) self.originalTask = originalTask } delegate.error = error delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } } // MARK: Authentication /// Associates an HTTP Basic credential with the request. /// /// - parameter user: The user. /// - parameter password: The password. /// - parameter persistence: The URL credential persistence. `.ForSession` by default. /// /// - returns: The request. @discardableResult open func authenticate( user: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { let credential = URLCredential(user: user, password: password, persistence: persistence) return authenticate(usingCredential: credential) } /// Associates a specified credential with the request. /// /// - parameter credential: The credential. /// /// - returns: The request. @discardableResult open func authenticate(usingCredential credential: URLCredential) -> Self { delegate.credential = credential return self } /// Returns a base64 encoded basic authentication credential as an authorization header tuple. /// /// - parameter user: The user. /// - parameter password: The password. /// /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } let credential = data.base64EncodedString(options: []) return (key: "Authorization", value: "Basic \(credential)") } // MARK: State /// Resumes the request. open func resume() { guard let task = task else { delegate.queue.isSuspended = false ; return } if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } task.resume() NotificationCenter.default.post( name: Notification.Name.Task.DidResume, object: self, userInfo: [Notification.Key.Task: task] ) } /// Suspends the request. open func suspend() { guard let task = task else { return } task.suspend() NotificationCenter.default.post( name: Notification.Name.Task.DidSuspend, object: self, userInfo: [Notification.Key.Task: task] ) } /// Cancels the request. open func cancel() { guard let task = task else { return } task.cancel() NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task] ) } } // MARK: - CustomStringConvertible extension Request: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as /// well as the response status code if a response has been received. open var description: String { var components: [String] = [] if let HTTPMethod = request?.httpMethod { components.append(HTTPMethod) } if let urlString = request?.url?.absoluteString { components.append(urlString) } if let response = response { components.append("(\(response.statusCode))") } return components.joined(separator: " ") } } // MARK: - CustomDebugStringConvertible extension Request: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, in the form of a cURL command. open var debugDescription: String { return cURLRepresentation() } func cURLRepresentation() -> String { var components = ["$ curl -i"] guard let request = self.request, let url = request.url, let host = url.host else { return "$ curl command could not be created" } if let httpMethod = request.httpMethod, httpMethod != "GET" { components.append("-X \(httpMethod)") } if let credentialStorage = self.session.configuration.urlCredentialStorage { let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { components.append("-u \(credential.user!):\(credential.password!)") } } else { if let credential = delegate.credential { components.append("-u \(credential.user!):\(credential.password!)") } } } if session.configuration.httpShouldSetCookies { if let cookieStorage = session.configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") } } var headers: [AnyHashable: Any] = [:] if let additionalHeaders = session.configuration.httpAdditionalHeaders { for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { headers[field] = value } } if let headerFields = request.allHTTPHeaderFields { for (field, value) in headerFields where field != "Cookie" { headers[field] = value } } for (field, value) in headers { components.append("-H \"\(field): \(value)\"") } if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(url.absoluteString)\"") return components.joined(separator: " \\\n\t") } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDataTask`. open class DataRequest: Request { // MARK: Helper Types struct Requestable: TaskConvertible { let urlRequest: URLRequest func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let urlRequest = try self.urlRequest.adapt(using: adapter) return queue.syncResult { session.dataTask(with: urlRequest) } } } // MARK: Properties /// The progress of fetching the response data from the server for the request. open var progress: Progress { return dataDelegate.progress } var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } // MARK: Stream /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. /// /// This closure returns the bytes most recently received from the server, not including data from previous calls. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is /// also important to note that the server data in any `Response` object will be `nil`. /// /// - parameter closure: The code to be executed periodically during the lifecycle of the request. /// /// - returns: The request. @discardableResult open func stream(closure: ((Data) -> Void)? = nil) -> Self { dataDelegate.dataStream = closure return self } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { dataDelegate.progressHandler = (closure, queue) return self } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. open class DownloadRequest: Request { // MARK: Helper Types /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the /// destination URL. public struct DownloadOptions: OptionSet { /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. public let rawValue: UInt /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. /// /// - parameter rawValue: The raw bitmask value for the option. /// /// - returns: A new log level instance. public init(rawValue: UInt) { self.rawValue = rawValue } } /// A closure executed once a download request has successfully completed in order to determine where to move the /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and /// the options defining how the file should be moved. public typealias DownloadFileDestination = ( _ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: DownloadOptions) enum Downloadable: TaskConvertible { case request(URLRequest) case resumeData(Data) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .request(urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.syncResult { session.downloadTask(with: urlRequest) } case let .resumeData(resumeData): task = queue.syncResult { session.downloadTask(withResumeData: resumeData) } } return task } } // MARK: Properties /// The resume data of the underlying download task if available after a failure. open var resumeData: Data? { return downloadDelegate.resumeData } /// The progress of downloading the response data from the server for the request. open var progress: Progress { return downloadDelegate.progress } var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } // MARK: State /// Cancels the request. open override func cancel() { downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task] ) } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { downloadDelegate.progressHandler = (closure, queue) return self } // MARK: Destination /// Creates a download file destination closure which uses the default file manager to move the temporary file to a /// file URL in the first available directory with the specified search path directory and search path domain mask. /// /// - parameter directory: The search path directory. `.DocumentDirectory` by default. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. /// /// - returns: A download file destination closure. open class func suggestedDownloadDestination( for directory: FileManager.SearchPathDirectory = .documentDirectory, in domain: FileManager.SearchPathDomainMask = .userDomainMask) -> DownloadFileDestination { return { temporaryURL, response in let directoryURLs = FileManager.default.urls(for: directory, in: domain) if !directoryURLs.isEmpty { return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) } return (temporaryURL, []) } } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. open class UploadRequest: DataRequest { // MARK: Helper Types enum Uploadable: TaskConvertible { case data(Data, URLRequest) case file(URL, URLRequest) case stream(InputStream, URLRequest) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .data(data, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.syncResult { session.uploadTask(with: urlRequest, from: data) } case let .file(url, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.syncResult { session.uploadTask(with: urlRequest, fromFile: url) } case let .stream(_, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.syncResult { session.uploadTask(withStreamedRequest: urlRequest) } } return task } } // MARK: Properties /// The progress of uploading the payload to the server for the upload request. open var uploadProgress: Progress { return uploadDelegate.uploadProgress } var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } // MARK: Upload Progress /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to /// the server. /// /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress /// of data being read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is sent to the server. /// /// - returns: The request. @discardableResult open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { uploadDelegate.uploadProgressHandler = (closure, queue) return self } } // MARK: - #if !os(watchOS) /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. open class StreamRequest: Request { @available(iOS 9.0, *) enum Streamable: TaskConvertible { case stream(hostName: String, port: Int) case netService(NetService) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .stream(hostName, port): task = queue.syncResult { session.streamTask(withHostName: hostName, port: port) } case let .netService(netService): task = queue.syncResult { session.streamTask(with: netService) } } return task } } } #endif
mit
813a7b3db38a9c153cb2a4daab022f81
36.318937
131
0.651518
5.119872
false
false
false
false
Paladinfeng/Weibo-Swift
Weibo/Weibo/Classes/View/Main/View/PFTabBar.swift
1
2182
// // PFTabBar.swift // Weibo // // Created by Paladinfeng on 15/12/5. // Copyright © 2015年 Paladinfeng. All rights reserved. // import UIKit class PFTabBar: UITabBar { var clickCompose: (()->())? override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { // 设置它为了解决导航栏push时变黑得BUG backgroundImage = UIImage(named: "tabbar_background") addSubview(composeBtn) } override func layoutSubviews() { super.layoutSubviews() composeBtn.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5) let itemW = frame.width / 5 var index = 0 for childView in subviews{ if childView.isKindOfClass(NSClassFromString("UITabBarButton")!){ childView.frame.size.width = itemW childView.frame.origin.x = CGFloat(index) * itemW index++ if index == 2 { index++ } } } } // MARK: - 懒加载控件 lazy var composeBtn: UIButton = { let btn = UIButton() btn.addTarget(self, action: "didClickCompose", forControlEvents: .TouchUpInside) //img btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal) btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted) //backgroundImg btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted) btn.sizeToFit() return btn }() @objc private func didClickCompose() { clickCompose?() } }
mit
578db39f12b937780b5f18847844675f
22.788889
107
0.519383
4.944573
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV2/Models/EnrichmentOptions.swift
1
6103
/** * (C) Copyright IBM Corp. 2022. * * 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 /** An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. */ public struct EnrichmentOptions: Codable, Equatable { /** An array of supported languages for this enrichment. When creating an enrichment, only specify a language that is used by the model or in the dictionary. Required when `type` is `dictionary`. Optional when `type` is `rule_based`. Not valid when creating any other type of enrichment. */ public var languages: [String]? /** The name of the entity type. This value is used as the field name in the index. Required when `type` is `dictionary` or `regular_expression`. Not valid when creating any other type of enrichment. */ public var entityType: String? /** The regular expression to apply for this enrichment. Required when `type` is `regular_expression`. Not valid when creating any other type of enrichment. */ public var regularExpression: String? /** The name of the result document field that this enrichment creates. Required when `type` is `rule_based` or `classifier`. Not valid when creating any other type of enrichment. */ public var resultField: String? /** A unique identifier of the document classifier. Required when `type` is `classifier`. Not valid when creating any other type of enrichment. */ public var classifierID: String? /** A unique identifier of the document classifier model. Required when `type` is `classifier`. Not valid when creating any other type of enrichment. */ public var modelID: String? /** Specifies a threshold. Only classes with evaluation confidence scores that are higher than the specified threshold are included in the output. Optional when `type` is `classifier`. Not valid when creating any other type of enrichment. */ public var confidenceThreshold: Double? /** Evaluates only the classes that fall in the top set of results when ranked by confidence. For example, if set to `5`, then the top five classes for each document are evaluated. If set to 0, the `confidence_threshold` is used to determine the predicted classes. Optional when `type` is `classifier`. Not valid when creating any other type of enrichment. */ public var topK: Int? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case languages = "languages" case entityType = "entity_type" case regularExpression = "regular_expression" case resultField = "result_field" case classifierID = "classifier_id" case modelID = "model_id" case confidenceThreshold = "confidence_threshold" case topK = "top_k" } /** Initialize a `EnrichmentOptions` with member variables. - parameter languages: An array of supported languages for this enrichment. When creating an enrichment, only specify a language that is used by the model or in the dictionary. Required when `type` is `dictionary`. Optional when `type` is `rule_based`. Not valid when creating any other type of enrichment. - parameter entityType: The name of the entity type. This value is used as the field name in the index. Required when `type` is `dictionary` or `regular_expression`. Not valid when creating any other type of enrichment. - parameter regularExpression: The regular expression to apply for this enrichment. Required when `type` is `regular_expression`. Not valid when creating any other type of enrichment. - parameter resultField: The name of the result document field that this enrichment creates. Required when `type` is `rule_based` or `classifier`. Not valid when creating any other type of enrichment. - parameter classifierID: A unique identifier of the document classifier. Required when `type` is `classifier`. Not valid when creating any other type of enrichment. - parameter confidenceThreshold: Specifies a threshold. Only classes with evaluation confidence scores that are higher than the specified threshold are included in the output. Optional when `type` is `classifier`. Not valid when creating any other type of enrichment. - parameter topK: Evaluates only the classes that fall in the top set of results when ranked by confidence. For example, if set to `5`, then the top five classes for each document are evaluated. If set to 0, the `confidence_threshold` is used to determine the predicted classes. Optional when `type` is `classifier`. Not valid when creating any other type of enrichment. - returns: An initialized `EnrichmentOptions`. */ public init( languages: [String]? = nil, entityType: String? = nil, regularExpression: String? = nil, resultField: String? = nil, classifierID: String? = nil, confidenceThreshold: Double? = nil, topK: Int? = nil ) { self.languages = languages self.entityType = entityType self.regularExpression = regularExpression self.resultField = resultField self.classifierID = classifierID self.confidenceThreshold = confidenceThreshold self.topK = topK } }
apache-2.0
6a830d450a2dbe840e6da4d0eadf163e
45.234848
121
0.702769
4.683807
false
false
false
false
CoderXiaoming/Ronaldo
SaleManager/SaleManager/Car/View/SAMShoppingCarListCell.swift
1
2351
// // SAMShoppingCarListCell.swift // SaleManager // // Created by apple on 16/12/14. // Copyright © 2016年 YZH. All rights reserved. // import UIKit class SAMShoppingCarListCell: UITableViewCell { ///接收的数据模型 var listModel: SAMShoppingCarListModel? { didSet{ ///设置选中指示器的照片 if listModel!.selected { selectedImageView.image = SAMShoppingCarCellIndicaterSelectedImage }else { selectedImageView.image = SAMShoppingCarCellIndicaterNormalImage } //设置产品图片 if listModel!.thumbUrl != "" { productImageView.sd_setImage(with: URL.init(string: listModel!.thumbUrl), placeholderImage: UIImage(named: "photo_loadding")) }else { productImageView.image = UIImage(named: "photo_loadding") } //设置产品名称 productName.text = listModel!.productIDName //设置米数,价格 var str: String? if (listModel?.countM != 0.0) && (listModel?.price != 0.0) { str = String(format: "%.1f/%.1f", listModel!.countM, listModel!.price) }else if (listModel?.countM == 0.0) && (listModel?.price == 0.0) { str = "---/---" }else if listModel?.countM == 0.0 { str = String(format: "---/%.1f", listModel!.price) }else { str = String(format: "%.1f/---", listModel!.countM) } mishuJiageLabel.text = str //设置匹数 pishuLabel.text = String(format: "%d", listModel!.countP) //设置备注 remarkLabel.text = listModel!.memoInfo } } //MARK: - awakeFromNib override func awakeFromNib() { super.awakeFromNib() selectedImageView.image = SAMShoppingCarCellIndicaterNormalImage } //MARK: - xib链接属性 @IBOutlet weak var selectedImageView: UIImageView! @IBOutlet weak var productImageView: UIImageView! @IBOutlet weak var productName: UILabel! @IBOutlet weak var pishuLabel: UILabel! @IBOutlet weak var mishuJiageLabel: UILabel! @IBOutlet weak var remarkLabel: UILabel! }
apache-2.0
57e72a83081b67f5e5a79b19de85ad14
32.117647
141
0.556838
4.381323
false
false
false
false
mapsme/omim
iphone/Maps/Core/Ads/RB/RBBanner.swift
6
3883
final class RBBanner: MTRGNativeAd, Banner { private enum Limits { static let minTimeOnScreen: TimeInterval = 3 static let minTimeSinceLastRequest: TimeInterval = 5 } fileprivate enum Settings { static let placementIDKey = "_SITEZONE" } fileprivate var success: Banner.Success! fileprivate var failure: Banner.Failure! fileprivate var click: Banner.Click! fileprivate var requestDate: Date? private var showDate: Date? private var remainingTime = Limits.minTimeOnScreen init!(bannerID: String) { super.init(slotId: UInt(MY_TARGET_RB_KEY)) delegate = self self.bannerID = bannerID let center = NotificationCenter.default center.addObserver(self, selector: #selector(enterForeground), name: UIApplication.willEnterForegroundNotification, object: nil) center.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func enterForeground() { if isBannerOnScreen { startCountTimeOnScreen() } } @objc private func enterBackground() { if isBannerOnScreen { stopCountTimeOnScreen() } } private func startCountTimeOnScreen() { if showDate == nil { showDate = Date() } if remainingTime > 0 { perform(#selector(setEnoughTimeOnScreen), with: nil, afterDelay: remainingTime) } } private func stopCountTimeOnScreen() { guard let date = showDate else { assert(false) return } let timePassed = Date().timeIntervalSince(date) if timePassed < Limits.minTimeOnScreen { remainingTime = Limits.minTimeOnScreen - timePassed NSObject.cancelPreviousPerformRequests(withTarget: self) } else { remainingTime = 0 } } @objc private func setEnoughTimeOnScreen() { isNeedToRetain = false } // MARK: - Banner func reload(success: @escaping Banner.Success, failure: @escaping Banner.Failure, click: @escaping Click) { self.success = success self.failure = failure self.click = click load() requestDate = Date() } func unregister() { unregisterView() } var isBannerOnScreen = false { didSet { if isBannerOnScreen { startCountTimeOnScreen() } else { stopCountTimeOnScreen() } } } private(set) var isNeedToRetain = false var isPossibleToReload: Bool { if let date = requestDate { return Date().timeIntervalSince(date) > Limits.minTimeSinceLastRequest } return true } var type: BannerType { return .rb(bannerID) } var mwmType: MWMBannerType { return type.mwmType } var bannerID: String! { get { return customParams.customParam(forKey: Settings.placementIDKey) } set { customParams.setCustomParam(newValue, forKey: Settings.placementIDKey) } } var statisticsDescription: [String: String] { return [kStatBanner: bannerID, kStatProvider: kStatRB] } } extension RBBanner: MTRGNativeAdDelegate { func onLoad(with _: MTRGNativePromoBanner!, nativeAd: MTRGNativeAd!) { guard nativeAd === self else { return } success(self) } func onNoAd(withReason reason: String!, nativeAd: MTRGNativeAd!) { guard nativeAd === self else { return } let params: [String: Any] = [ kStatBanner: bannerID ?? "", kStatProvider: kStatRB, kStatReason: reason ?? "", ] let event = kStatPlacePageBannerError let error = NSError(domain: kMapsmeErrorDomain, code: 1001, userInfo: params) failure(self.type, event, params, error) } func onAdClick(with nativeAd: MTRGNativeAd!) { guard nativeAd === self else { return } click(self) } }
apache-2.0
fd2feac1faea954778bdc3312dfc5cc8
24.886667
109
0.660572
4.723844
false
false
false
false
combes/audio-weather
AudioWeather/AudioWeather/UnitsModel.swift
1
893
// // UnitsModel.swift // AudioWeather // // Created by Christopher Combes on 6/25/17. // Copyright © 2017 Christopher Combes. All rights reserved. // import Foundation import SwiftyJSON class UnitsModel { static var distanceUnit = "ft" static var pressureUnit = "in" static var speedUnit = "mph" static var temperatureUnit = "F" init(json: JSON) { if let distance = json[UnitFields.distance.rawValue].string { UnitsModel.distanceUnit = distance } if let pressure = json[UnitFields.pressure.rawValue].string { UnitsModel.pressureUnit = pressure } if let speed = json[UnitFields.speed.rawValue].string { UnitsModel.speedUnit = speed } if let temperature = json[UnitFields.temperature.rawValue].string { UnitsModel.temperatureUnit = temperature } } }
mit
b830b528f71c50d1481bbf6144997e79
26.875
75
0.643498
4.227488
false
false
false
false
mattfenwick/TodoRx
TodoRx/TodoFlow/TodoFlowController.swift
1
2553
// // TodoFlowController.swift // TodoRx // // Created by Matt Fenwick on 7/19/17. // Copyright © 2017 mf. All rights reserved. // import UIKit import RxSwift class TodoFlowController { let viewController: UIViewController private let flowPresenter: TodoFlowPresenter private let todoListCoordinator: TodoListCoordinator private var createTodoCoordinator: CreateTodoCoordinator? private var editTodoCoordinator: EditTodoCoordinator? private let disposeBag = DisposeBag() init(interactor: TodoFlowInteractor) { flowPresenter = TodoFlowPresenter(interactor: interactor) todoListCoordinator = TodoListCoordinator(interactor: flowPresenter) viewController = todoListCoordinator.viewController flowPresenter.presentCreateItemView .drive(onNext: { [unowned self] in self.showCreateView() }) .disposed(by: disposeBag) flowPresenter.dismissCreateItemView .drive(onNext: { [unowned self] in self.hideCreateView() }) .disposed(by: disposeBag) flowPresenter.presentEditItemView .drive(onNext: { [unowned self] item in self.showEditView(item: item) }) .disposed(by: disposeBag) flowPresenter.dismissEditItemView .drive(onNext: { [unowned self] in self.hideEditView() }) .disposed(by: disposeBag) } // MARK: - actions private func showCreateView() { let coordinator = CreateTodoCoordinator(interactor: flowPresenter) let navController = UINavigationController(rootViewController: coordinator.viewController) viewController.present(navController, animated: true, completion: nil) self.createTodoCoordinator = coordinator } private func hideCreateView() { viewController.dismiss(animated: true, completion: nil) createTodoCoordinator = nil } private func showEditView(item: EditTodoIntent) { let coordinator = EditTodoCoordinator( item: item, interactor: flowPresenter) let navController = UINavigationController(rootViewController: coordinator.viewController) viewController.present(navController, animated: true, completion: nil) self.editTodoCoordinator = coordinator } private func hideEditView() { viewController.dismiss(animated: true, completion: nil) editTodoCoordinator = nil } }
mit
aeb1f02f1eb37bd92b3290725e95652d
29.746988
98
0.665752
5.186992
false
false
false
false
thierryH91200/Charts-log
Charts-log/Demos/LineDemoViewController.swift
1
10588
// // LineDemoViewController.swift // ChartsDemo-OSX // // 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 Cocoa import Charts open class LineDemoViewController: NSViewController { @IBOutlet var lineChartView: LineChartView! @IBOutlet weak var buttonAxeOX: NSButton! @IBOutlet weak var buttonAxeOY: NSButton! @IBOutlet weak var stickButtonOX: NSButton! @IBOutlet weak var stickButtonOY: NSButton! @IBOutlet weak var stickMajorButtonOX: NSButton! @IBOutlet weak var stickMajorButtonOY: NSButton! @IBOutlet weak var courbe1: NSButton! @IBOutlet weak var courbe2: NSButton! @IBOutlet weak var courbe3: NSButton! var logAxeOX = false var logAxeOY = false var stickOX = false var stickOY = false var stickMajorOX = true var stickMajorOY = true var selectCourbe = 0 override open func viewDidLoad() { super.viewDidLoad() courbe1.state = 1 stickButtonOX.isEnabled = logAxeOX stickButtonOY.isEnabled = logAxeOY stickMajorButtonOX.isEnabled = logAxeOX stickMajorButtonOY.isEnabled = logAxeOY drawGraph() } open func drawGraph() { lineChartView.gridBackgroundColor = NSUIColor.white lineChartView.chartDescription?.text = "Linechart Lin/log Demo" lineChartView.drawGridBackgroundEnabled = true lineChartView.drawBordersEnabled = true let xAxis = lineChartView.xAxis xAxis.drawAxisLineEnabled = true xAxis.labelPosition = .bottom xAxis.labelRotationAngle = CGFloat(-75) xAxis.labelFont = NSFont.systemFont( ofSize: 10.0) xAxis.drawGridLinesEnabled = true xAxis.valueFormatter = LogValueFormatter(appendix: "") // xAxis.spaceMin = 0.5 // xAxis.spaceMax = 0.5 lineChartView.leftAxis.valueFormatter = LogValueFormatter(appendix: "") lineChartView.leftAxis.labelFont = NSFont.systemFont( ofSize: 8.0) let marker = XYMarkerView( color: #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1), font: NSFont.systemFont(ofSize: 12.0), textColor: NSColor.blue, insets: NSEdgeInsetsMake(8.0, 8.0, 20.0, 8.0), xAxisValueFormatter: DoubleAxisValueFormatter(postFixe: "s"), yAxisValueFormatter: DoubleAxisValueFormatter(postFixe: ""), logXAxis : logAxeOX, logYAxis: logAxeOY) marker.minimumSize = CGSize( width: 80.0, height :40.0) lineChartView.marker = marker // Do any additional setup after loading the view. var ys1 = [Double]() var ys2 = [Double]() var ys3 = [Double]() var x1 = [Double]() switch selectCourbe { case 0: ys1 = Array(stride(from: 1, to: 1e9, by: 1e5)).map { x in return Double( x )} ys2 = Array(stride(from: 1e9, to: 1, by: -1e5)).map { x in return Double(x )} ys3 = Array(stride(from: 1.001, to: 1e9, by: 1e5)).map { x in return log10(Double(x))} x1 = Array(stride(from: 1, to: 1e9, by: 1e5)).map { x in return x} case 1: ys1 = Array(stride(from: 20, to: 20000, by: 100)).map { x in return Double(arc4random_uniform(UInt32(100))) + 50} ys2 = Array(stride(from: 20, to: 20000, by: 100)).map { x in return Double(arc4random_uniform(UInt32(100))) + 300} ys3 = Array(stride(from: 20, to: 20000, by: 100)).map { x in return Double(arc4random_uniform(UInt32(100))) + 700} x1 = Array(stride(from: 20, to: 20000, by: 100)).map { x in return x} case 2: ys1 = Array(stride(from: 0.0001, to: 10, by: 0.0005)).map { x in return Double( x )} ys2 = Array(stride(from: 0.0001, to: 10, by: 0.0005)).map { x in return Double(0.5 * x )} ys3 = Array(stride(from: 0.0001, to: 10, by: 0.0005)).map { x in return log10(Double(x))} x1 = Array(stride(from: 0.0001, to: 10, by: 0.0005)).map { x in return x} default: ys1 = Array(stride(from: 1, to: 1000, by: 1)).map { x in return Double( x )} ys2 = Array(stride(from: 1, to: 1000, by: 1)).map { x in return Double(2 * x )} ys3 = Array(stride(from: 1, to: 1000, by: 1)).map { x in return Double(3 * x + 20)} x1 = Array(stride(from: 1, to: 1e9, by: 10)).map { x in return x} break } let dataInput : [([Double], [Double])] = [(x1 , ys1),(x1 , ys2), (x1 , ys3)] lineChartView.xAxis.stickEnabled = stickOX lineChartView.leftAxis.stickEnabled = stickOY lineChartView.xAxis.stickMajorEnabled = stickMajorOX lineChartView.leftAxis.stickMajorEnabled = stickMajorOY lineChartView.xAxis.maskLabels = [true, true, false, true, false, true, false, true, false] lineChartView.xAxis.maskAxis = [1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 , 7.0 , 8.0 , 9.0] lineChartView.leftAxis.maskLabels = [true, false, false, false, false, false, false, false, false] lineChartView.leftAxis.maskAxis = [1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 , 7.0 , 8.0 , 9.0] lineChartView.leftAxis.logarithmicEnabled = logAxeOY lineChartView.xAxis.logarithmicEnabled = logAxeOX let dataSets = prepareDataToPlot(dataInput: dataInput, labels: ["y = x", "y = 2x + 10", "y = log(x)"], color: [NSUIColor.green, NSUIColor.red, NSUIColor.black] ) let data = LineChartData() for dataSet in dataSets { data.addDataSet(dataSet) } lineChartView.rightAxis.enabled = false lineChartView.data = data } /// function that prepates the data for plotting and setup labels, markers, colors, ... /// /// - Parameters: /// - dataInput: <#dataInput description#> /// - labels: <#labels description#> /// - marker: <#marker description#> /// - color: <#color description#> /// - Returns: <#return value description#> public func prepareDataToPlot(dataInput: [([Double], [Double])], labels: [String] = [], color: Array<Any> = [] )->([LineChartDataSet]) { print("start preparing data for plotting") var dataInput = dataInput // setup of markers, colors, ... and their default values if no input is given var labels = labels var color = color var colors = [NSUIColor.black, NSUIColor.blue, NSUIColor.red, NSUIColor.cyan, NSUIColor.green, NSUIColor.magenta, NSUIColor.orange, NSUIColor.magenta, NSUIColor.brown, NSUIColor.yellow] // (Marker) Color set-up if color.count != dataInput.count { color = [] if dataInput.count < colors.count { for i in 0..<dataInput.count { color.append(colors[i]) } } else { var counter = 0 for _ in 0..<dataInput.count { color.append(colors[counter]) if counter == colors.endIndex { counter = 0 } } } } // Description lable set-up if labels.count != dataInput.count { labels = [String](repeating: "-", count: dataInput.count) } // chart data set-up var dataEntries: [[ChartDataEntry]] = [] for i in 0..<dataInput.count { var dataEntriesSet: [ChartDataEntry] = [] for j in 0..<dataInput[i].0.count { let x = logAxeOX == true ? log10(dataInput[i].0[j]) : dataInput[i].0[j] let y = logAxeOY == true ? log10(dataInput[i].1[j]) : dataInput[i].1[j] dataEntriesSet.append(ChartDataEntry(x: x, y: y)) } dataEntries.append(dataEntriesSet) } // plot apperance set-up var lineChartDataSets = [LineChartDataSet]() for i in 0..<dataEntries.count { let lineChartDataSetI = LineChartDataSet(values: dataEntries[i], label: labels[i]) lineChartDataSetI.colors = [color[i] as! NSColor] lineChartDataSetI.drawCirclesEnabled = false lineChartDataSetI.lineWidth = 2.0 // lineChartDataSetI.mode = .stepped lineChartDataSets.append(lineChartDataSetI) } // return processed data to be plotted by plot function print("done preparing data for plotting") return lineChartDataSets } override open func viewWillAppear() { self.lineChartView.animate(xAxisDuration: 0.0, yAxisDuration: 1.0) } @IBAction func ActionAxeOX(_ sender: NSButton) { logAxeOX = !logAxeOX stickButtonOX.isEnabled = logAxeOX stickMajorButtonOX.isEnabled = logAxeOX drawGraph() } @IBAction func ActionAxeOY(_ sender: NSButton) { logAxeOY = !logAxeOY stickButtonOY.isEnabled = logAxeOY stickMajorButtonOY.isEnabled = logAxeOY drawGraph() } @IBAction func ActionStickAxeOX(_ sender: NSButton) { stickOX = !stickOX drawGraph() } @IBAction func ActionStickAxeOY(_ sender: NSButton) { stickOY = !stickOY drawGraph() } @IBAction func ActionStickMajorAxeOX(_ sender: NSButton) { stickMajorOX = !stickMajorOX drawGraph() } @IBAction func ActionStickMajorAxeOY(_ sender: NSButton) { stickMajorOY = !stickMajorOY drawGraph() } @IBAction func whichRadioButton1(_ sender: NSButton) { if courbe1.state == 1 { selectCourbe = 0 } if courbe2.state == 1 { selectCourbe = 1 } if courbe3.state == 1 { selectCourbe = 2 } drawGraph() } }
apache-2.0
135d03530f7c6cc08b49c040669d4bca
35.510345
193
0.56054
4.155416
false
false
false
false
naokits/my-programming-marathon
RxSwiftDemo/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/Calculator/CalculatorViewController.swift
9
3821
// // CalculatorViewController.swift // RxExample // // Created by Carlos García on 4/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class CalculatorViewController: ViewController { @IBOutlet weak var lastSignLabel: UILabel! @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var allClearButton: UIButton! @IBOutlet weak var changeSignButton: UIButton! @IBOutlet weak var percentButton: UIButton! @IBOutlet weak var divideButton: UIButton! @IBOutlet weak var multiplyButton: UIButton! @IBOutlet weak var minusButton: UIButton! @IBOutlet weak var plusButton: UIButton! @IBOutlet weak var equalButton: UIButton! @IBOutlet weak var dotButton: UIButton! @IBOutlet weak var zeroButton: UIButton! @IBOutlet weak var oneButton: UIButton! @IBOutlet weak var twoButton: UIButton! @IBOutlet weak var threeButton: UIButton! @IBOutlet weak var fourButton: UIButton! @IBOutlet weak var fiveButton: UIButton! @IBOutlet weak var sixButton: UIButton! @IBOutlet weak var sevenButton: UIButton! @IBOutlet weak var eightButton: UIButton! @IBOutlet weak var nineButton: UIButton! override func viewDidLoad() { let commands:[Observable<Action>] = [ allClearButton.rx_tap.map { _ in .Clear }, changeSignButton.rx_tap.map { _ in .ChangeSign }, percentButton.rx_tap.map { _ in .Percent }, divideButton.rx_tap.map { _ in .Operation(.Division) }, multiplyButton.rx_tap.map { _ in .Operation(.Multiplication) }, minusButton.rx_tap.map { _ in .Operation(.Subtraction) }, plusButton.rx_tap.map { _ in .Operation(.Addition) }, equalButton.rx_tap.map { _ in .Equal }, dotButton.rx_tap.map { _ in .AddDot }, zeroButton.rx_tap.map { _ in .AddNumber("0") }, oneButton.rx_tap.map { _ in .AddNumber("1") }, twoButton.rx_tap.map { _ in .AddNumber("2") }, threeButton.rx_tap.map { _ in .AddNumber("3") }, fourButton.rx_tap.map { _ in .AddNumber("4") }, fiveButton.rx_tap.map { _ in .AddNumber("5") }, sixButton.rx_tap.map { _ in .AddNumber("6") }, sevenButton.rx_tap.map { _ in .AddNumber("7") }, eightButton.rx_tap.map { _ in .AddNumber("8") }, nineButton.rx_tap.map { _ in .AddNumber("9") } ] commands .toObservable() .merge() .scan(CalculatorState.CLEAR_STATE) { a, x in return a.tranformState(x) } .debug("debugging") .subscribeNext { [weak self] calState in self?.resultLabel.text = self?.prettyFormat(calState.inScreen) switch calState.action { case .Operation(let operation): switch operation { case .Addition: self?.lastSignLabel.text = "+" case .Subtraction: self?.lastSignLabel.text = "-" case .Multiplication: self?.lastSignLabel.text = "x" case .Division: self?.lastSignLabel.text = "/" } default: self?.lastSignLabel.text = "" } } .addDisposableTo(disposeBag) } func prettyFormat(str: String) -> String { if str.hasSuffix(".0") { return str.substringToIndex(str.endIndex.predecessor().predecessor()) } return str } }
mit
8ed270f0117e3aa6dc4fd4ca842d17e9
33.098214
81
0.556167
4.409931
false
false
false
false
ronaldho/visionproject
EMIT/EMIT/ImageUtils.swift
1
4137
// // ImageUtils.swift // EMIT // // Created by Andrew on 13/12/15. // Copyright © 2015 Andrew. All rights reserved. // import UIKit class ImageUtils: NSObject { static func cropToSquare(originalImage: UIImage) -> UIImage { let originalWidth = originalImage.size.width let originalHeight = originalImage.size.height var x: CGFloat = 0.0 var y: CGFloat = 0.0 var edge: CGFloat = 0.0 if (originalWidth > originalHeight) { // landscape edge = originalHeight x = (originalWidth - originalHeight) / 2.0 y = 0.0 } else if (originalHeight > originalWidth) { // portrait edge = originalWidth x = 0.0 y = (originalHeight - originalWidth) / 2.0 } else { // square edge = originalWidth } let cropSquare = CGRectMake(x, y, edge, edge) let imageRef = CGImageCreateWithImageInRect(originalImage.CGImage, cropSquare); return UIImage(CGImage: imageRef!, scale: 0, orientation: originalImage.imageOrientation) } static func fixOrientation(originalImage: UIImage) -> UIImage { if originalImage.imageOrientation == UIImageOrientation.Up { return originalImage } var transform = CGAffineTransformIdentity switch originalImage.imageOrientation { case .Down, .DownMirrored: transform = CGAffineTransformTranslate(transform, originalImage.size.width, originalImage.size.height) transform = CGAffineTransformRotate(transform, CGFloat(M_PI)); case .Left, .LeftMirrored: transform = CGAffineTransformTranslate(transform, originalImage.size.width, 0); transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2)); case .Right, .RightMirrored: transform = CGAffineTransformTranslate(transform, 0, originalImage.size.height); transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2)); case .Up, .UpMirrored: break } switch originalImage.imageOrientation { case .UpMirrored, .DownMirrored: transform = CGAffineTransformTranslate(transform, originalImage.size.width, 0) transform = CGAffineTransformScale(transform, -1, 1) case .LeftMirrored, .RightMirrored: transform = CGAffineTransformTranslate(transform, originalImage.size.height, 0) transform = CGAffineTransformScale(transform, -1, 1); default: break; } // Now we draw the underlying CGImage into a new context, applying the transform // calculated above. let ctx = CGBitmapContextCreate( nil, Int(originalImage.size.width), Int(originalImage.size.height), CGImageGetBitsPerComponent(originalImage.CGImage), 0, CGImageGetColorSpace(originalImage.CGImage), UInt32(CGImageGetBitmapInfo(originalImage.CGImage).rawValue) ) CGContextConcatCTM(ctx, transform); switch originalImage.imageOrientation { case .Left, .LeftMirrored, .Right, .RightMirrored: // Grr... CGContextDrawImage(ctx, CGRectMake(0, 0, originalImage.size.height,originalImage.size.width), originalImage.CGImage); default: CGContextDrawImage(ctx, CGRectMake(0, 0, originalImage.size.width,originalImage.size.height), originalImage.CGImage); break; } // And now we just create a new UIImage from the drawing context let cgimg = CGBitmapContextCreateImage(ctx) let img = UIImage(CGImage: cgimg!) //CGContextRelease(ctx); //CGImageRelease(cgimg); return img; } }
mit
7d54fde143815b3a27d904790e8549da
31.825397
129
0.583656
5.55914
false
false
false
false
devpunk/velvet_room
Source/Model/Vita/MVitaLinkStrategyRequestVitaInfo.swift
1
1233
import Foundation import XmlHero final class MVitaLinkStrategyRequestVitaInfo:MVitaLinkStrategyRequestData { override func failed() { let message:String = String.localizedModel( key:"MVitaLinkStrategyRequestVitaInfo_messageFailed") model?.errorCloseConnection( message:message) } override func success() { let unwrappedData:Data = MVitaLink.unwrapDataWithSizeHeader( data:data) Xml.object(data:unwrappedData) { [weak self] (xml:[String:Any]?, error:XmlError?) in guard let xml:[String:Any] = xml, error == nil else { self?.failed() return } self?.vitaInfo(xml:xml) } } //MARK: private private func vitaInfo(xml:[String:Any]) { guard let vitaInfo:MVitaInfo = MVitaInfo.factoryInfo( xml:xml) else { failed() return } model?.sendLocalInfo(vitaInfo:vitaInfo) } }
mit
adcccc576c9a196537c0fbf27b397714
21.017857
73
0.480941
5.032653
false
false
false
false
johndpope/objc2swift
src/test/resources/declaration_sample.swift
1
1397
class Declaration { func declare() { var num1: Int var num2: Int = 7 var num3: Int var num4: Int var num5: Int = 1 var num6: Int var num7: Int var num8: UInt var num9: UInt var num10: UInt = 1 var num11: UInt = 8 var num12: Int var num13: UInt var num14: Int var num15: Int64 var num16: UInt64 var num17: UInt64 = 3 var num18: Int64 var num19: Int8 var num20: UInt8 var num21: Int8 var f1: Float = 123.45f var d1: Double = 123.45 var c1: char = 'A' var b1: Bool = true var b2: Bool = false var str1: NSString var str2: NSString = "hoge" var str3: NSString var str4: NSString = "fuga" var n1: Int var n2: Int = -2 var n3: UInt = 4 var n4: NSNumber var i1: AnyObject var i2: AnyObject var i3: AnyObject = null var i4: AnyObject = "foo" var o1: HogeClass var a: [AnyObject] static var num21: Int let kConstNum1: Int = 200 static let kConstNum2: Int = 200 static let kNumFloat: Float = 1.25f static let kSectionTitleFavorite: NSString = "お気に入り" static let kSectionTitleFavorite2: NSString = "お気に入り" } }
mit
cfcce0ca3a792660f59f61731dfc9c41
25.480769
61
0.519245
3.5953
false
false
false
false
appsandwich/ppt2rk
ppt2rk/RunkeeperActivitiesParser.swift
1
3233
// // RunkeeperActivitiesParser.swift // ppt2rk // // Created by Vinny Coyne on 17/05/2017. // Copyright © 2017 App Sandwich Limited. All rights reserved. // import Foundation class RunkeeperActivitiesParser { var data: Data? = nil init(_ data: Data) { self.data = data } public func parseWithHandler(_ handler: @escaping ([RunkeeperActivity]?) -> Void) { guard let data = self.data else { handler(nil) return } guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else { handler(nil) return } guard let dictionary = json as? Dictionary<String, Any> else { handler(nil) return } guard let activities = dictionary["activities"] as? Dictionary<String, Any> else { handler(nil) return } guard let year = activities.values.first as? Dictionary<String, Any> else { handler(nil) return } guard let month = year.values.first as? [Dictionary<String, Any>], month.count > 0 else { handler(nil) return } let runkeeperActivities: [RunkeeperActivity] = month.flatMap { (activity) -> RunkeeperActivity? in if let id = activity["activity_id"] as? Int, let distance = activity["distance"] as? String, let elapsedTime = activity["elapsedTime"] as? String, let dayOfMonth = activity["dayOfMonth"] as? String, let monthNum = activity["monthNum"] as? String, let year = activity["year"] as? String, let timestamp = RunkeeperActivitiesParser.dateFrom(dayOfMonth, monthNum: monthNum, year: year) { let timeComps = elapsedTime.components(separatedBy: ":") var durationInSeconds = 0.0 for (index, timeComp) in timeComps.enumerated() { guard let s = Double(timeComp) else { continue } let seconds = s * NSDecimalNumber(decimal: pow(60.0, timeComps.count - (index + 1))).doubleValue guard seconds > 0.0 else { continue } durationInSeconds += seconds } return RunkeeperActivity(id: id, timestamp: timestamp, distance: distance, duration: "\(durationInSeconds)", day: dayOfMonth + "/" + monthNum + "/" + year) } else { return nil } } handler(runkeeperActivities) } class func dateFrom(_ dayOfMonth: String, monthNum: String, year: String) -> Date? { let dateString = dayOfMonth + "/" + monthNum + "/" + year let df = DateFormatter() df.locale = Locale(identifier: "en_US_POSIX") df.timeZone = TimeZone(identifier: "UTC") df.dateFormat = "d/MM/yyyy" return df.date(from: dateString) } }
mit
7a39640050275e3e6786ab8576c66fc7
33.021053
395
0.51578
4.987654
false
false
false
false
tanuva/ampacheclient
AmpacheClient/AmpacheAPI.swift
1
5921
// // AmpacheAPI.swift // AmpacheClient // // Created by Marcel on 23.09.14. // Copyright (c) 2014 FileTrain. All rights reserved. // import Foundation import UIKit import CoreData protocol AmpacheAPIProtocol { func didReceiveResponse(results: NSDictionary) } class AuthParserDelegate: NSObject, NSXMLParserDelegate { var token: String? var buffer = NSMutableString() func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: NSDictionary!) { // println("sta elm: \(elementName)") buffer.setString("") } func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) { // println("end elm: \(elementName)") if(elementName == "auth") { token = (buffer.copy() as String) buffer.setString("") println("token: \(token)") } } func parser(parser: NSXMLParser!, foundCharacters string: String) { // println(" chars: \(string)") buffer.appendString(string) } func parseErrorOcurred(parser: NSXMLParser, error: NSError) { println("Error: \(error.localizedDescription)") } } class AmpacheAPI : NSObject, NSXMLParserDelegate { var delegate: AmpacheAPIProtocol? var hostname = "http://192.168.1.210/owncloud/index.php/apps/music/ampache" // var hostname = "http://192.168.0.14/owncloud/index.php/apps/music/ampache" var username = "admin" var passwordHash = "16c64e70aad7bd7c1bd1a1e10f5593890641d9a9467eeab31674087976de8cc3" // "f5r3cbqyzlbl" var token: String? var buffer = NSMutableString() var curDelegate: NSXMLParserDelegate? var context: NSManagedObjectContext override init() { let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate context = appDel.managedObjectContext! super.init() } func sha256(data : NSData) -> NSString { var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0) CC_SHA256(data.bytes, CC_LONG(data.length), &hash) let resstr = NSMutableString() for byte in hash { resstr.appendFormat("%02hhx", byte) } return resstr } func generatePassphrase(passwordHash: NSString, timestamp: Int) -> NSString { // Ampache passphrase: sha256(unixtime + sha256(password)) where '+' denotes concatenation // Concatenate timestamp and password hash var dataStr = "\(timestamp)\(passwordHash)" var data = dataStr.dataUsingEncoding(NSASCIIStringEncoding)! let passphrase = sha256(data) return passphrase } func requestDatabase() { var artists = requestArtists() var albums = requestAlbums() var songs = requestSongs(albums) var error = NSErrorPointer() // if(!context.save(error)) { // println(error.debugDescription) // } } func authenticate() { let timestamp = Int(NSDate().timeIntervalSince1970) let passphrase = generatePassphrase(passwordHash, timestamp: timestamp) var urlPath = "\(hostname)/server/xml.server.php?action=handshake&auth=\(passphrase)&timestamp=\(timestamp)&version=350001&user=\(username)" var url = NSURL(string: urlPath) println("Request: \(url)") // var request = NSURLRequest(URL: url) // var connection = NSURLConnection(request: request, delegate: self, startImmediately: false) // connection.start() var parser = NSXMLParser(contentsOfURL: url)! var curDelegate = AuthParserDelegate() parser.delegate = curDelegate var success = parser.parse() if(success) { token = curDelegate.token! } else { println("Couldn't get a login token.") } } func requestArtists() -> Array<Artist> { if let unwrapToken = token { var urlPath = "\(hostname)/server/xml.server.php?auth=\(unwrapToken)&action=artists" var url = NSURL(string: urlPath) println("Request: \(url)") var parser = NSXMLParser(contentsOfURL: url)! var curDelegate = ArtistParserDelegate() parser.delegate = curDelegate var success = parser.parse() var data = curDelegate.artists return data } else { authenticate() return requestArtists() } } func requestAlbums() -> Array<Album> { if let unwrapToken = token { var urlPath = "\(hostname)/server/xml.server.php?auth=\(unwrapToken)&action=albums" var url = NSURL(string: urlPath) println("Request: \(url)") var parser = NSXMLParser(contentsOfURL: url)! var curDelegate = AlbumParserDelegate() parser.delegate = curDelegate var success = parser.parse() var data = curDelegate.albums return data } else { authenticate() return requestAlbums() } } func requestSongs(albums: Array<Album>) -> Array<Song> { if let unwrapToken = token { var urlPath = "\(hostname)/server/xml.server.php?auth=\(unwrapToken)&action=album_songs&filter=" var result = Array<Song>() for album in albums { var url = NSURL(string: "\(urlPath)\(album.ampacheId)") println("Request: \(url)") var parser = NSXMLParser(contentsOfURL: url)! var curDelegate = SongParserDelegate() parser.delegate = curDelegate var success = parser.parse() for song in curDelegate.songs { result.append(song) } } return result } else { authenticate() return requestSongs(albums) } } // === NSURLConnection delegate method === /*func connection(connection: NSURLConnection!, didFailWithError error: NSError!) { println("Failed with error:\(error.localizedDescription)") } func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { //New request so we need to clear the data object self.data = NSMutableData() } func connection(connection: NSURLConnection!, didReceiveData data: NSData!) { //Append incoming data self.data.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection!) { //Finished receiving data and convert it to a JSON object println(data) // delegate?.didReceiveResponse(jsonResult) }*/ }
unlicense
4eefe764ad1916d71bedd30274225123
28.311881
168
0.711366
3.693699
false
false
false
false
gskbyte/jotajota
jotajota/Spike.swift
1
902
// // Spike.swift // jotajota // // Created by Jose Alcalá-Correa on 23/04/15. // Copyright (c) 2015 XING. All rights reserved. // import UIKit import SpriteKit class Spike: SKSpriteNode { init() { let radius : CGFloat = 20 let texture = SKTexture(imageNamed:"spike") super.init(texture: texture, color: .clear, size: CGSize(width: radius*2, height: radius*2)) self.physicsBody = SKPhysicsBody(circleOfRadius: radius) self.physicsBody?.isDynamic = false self.physicsBody?.friction = 0.0 self.physicsBody?.restitution = 0.4 self.physicsBody?.categoryBitMask = SpikeCategory self.physicsBody?.contactTestBitMask = CollidableCategory self.physicsBody?.collisionBitMask = CollidableCategory } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
8c30d32156051574a19feb5617f46a99
26.30303
100
0.669256
4.095455
false
false
false
false
gkaimakas/SwiftyForms
SwiftyForms/Classes/Forms/Form.swift
1
2262
// // Form.swift // Pods // // Created by Γιώργος Καϊμακάς on 14/06/16. // // import Foundation open class Form { open let name: String fileprivate var _sections: [Section] open var data: [String: Any]? { return self._sections .map() { $0.data } .filter() { $0 != nil } .map() { $0! } .reduce([String: Any]()) { return $0.0?.mergeWith($0.1) } } open var errors: [String] { var array:[String] = [] for section in _sections { array.append(contentsOf: section.errors) } return array } open var isSubmitted: Bool { return _submitted } open var isValid: Bool { return _valid } open var numberOfSections: Int { return _sections .filter() { $0.hidden == false } .count } open func toObject<T: FormDataSerializable>(_ type: T.Type) -> T? { return T(data: self.data) } fileprivate var _valid = false fileprivate var _submitted = false fileprivate var _valueEvents: [(Form, Section, Input) -> Void] = [] fileprivate var _validateEvents: [(Form) -> Void] = [] fileprivate var _submitEvents: [(Form) -> Void] = [] public init (name: String, sections: [Section] = []) { self.name = name self._sections = sections } @discardableResult open func addSection(_ section: Section) -> Self { _sections.append(section) return self } @discardableResult open func on(_ value: ((Form, Section, Input) -> Void)? = nil, validate: ((Form) -> Void)? = nil, submit: ((Form) -> Void)? = nil) -> Self { if let event = value { _valueEvents.append(event) } if let event = validate { _validateEvents.append(event) } if let event = submit { _submitEvents.append(event) } return self } open func sectionAtIndex(_ index: Int) -> Section { let sections = _sections .filter() { $0.hidden == false} return sections[index] } open func submit() { let _ = _sections .map() { $0.submit() } for event in _submitEvents { event(self) } } open func validate() -> Bool { _validate() for event in _validateEvents { event(self) } return _valid } fileprivate func _validate() { _valid = _sections .map() { $0.validate() } .reduce(true) { $0 && $1 } } }
mit
3277da738324f0895e86168b30005d49
17.268293
68
0.596351
3.036486
false
false
false
false
haawa799/Metal-Flaps
MetalTryOut-Objc/Nodes/Pipe/Pipe.swift
1
922
import UIKit @objc class Pipe: Node { init(baseEffect: BaseEffect) { let url = Bundle.main.url(forResource: "pipe", withExtension: "txt")! let content = try! String(contentsOf: url, encoding: .utf8) var array = content.components(separatedBy: "\n") array.removeLast() let verticesArray:Array<Vertex> = array.map { Vertex(text: $0) } super.init(name: "Pipe", baseEffect: baseEffect, vertices: verticesArray, vertexCount: verticesArray.count, textureName: "pip.png") self.ambientIntensity = 0.800000 self.diffuseIntensity = 0.700000 self.specularIntensity = 0.800000 self.shininess = 8.078431 self.setScale(scale: 0.5) } override func updateWithDelta(delta: CFTimeInterval) { super.updateWithDelta(delta: delta) // rotationZ += Float(M_PI/2) * Float(delta) } }
mit
6d5cdf3953fc91a3af8dc2073ced3992
26.117647
139
0.621475
3.90678
false
false
false
false
stephentyrone/swift
test/attr/attr_autoclosure.swift
3
11814
// RUN: %target-typecheck-verify-swift -swift-version 5 // Simple case. var fn : @autoclosure () -> Int = 4 // expected-error {{'@autoclosure' may only be used on parameters}} @autoclosure func func1() {} // expected-error {{attribute can only be applied to types, not declarations}} func func1a(_ v1 : @autoclosure Int) {} // expected-error {{@autoclosure attribute only applies to function types}} func func2(_ fp : @autoclosure () -> Int) { func2(4)} func func3(fp fpx : @autoclosure () -> Int) {func3(fp: 0)} func func4(fp : @autoclosure () -> Int) {func4(fp: 0)} func func6(_: @autoclosure () -> Int) {func6(0)} // autoclosure + inout doesn't make sense. func func8(_ x: inout @autoclosure () -> Bool) -> Bool { // expected-error {{'@autoclosure' may only be used on parameters}} } func func9(_ x: @autoclosure (Int) -> Bool) {} // expected-error {{argument type of @autoclosure parameter must be '()'}} func func10(_ x: @autoclosure (Int, String, Int) -> Void) {} // expected-error {{argument type of @autoclosure parameter must be '()'}} // <rdar://problem/19707366> QoI: @autoclosure declaration change fixit let migrate4 : (@autoclosure() -> ()) -> () struct SomeStruct { @autoclosure let property : () -> Int // expected-error {{attribute can only be applied to types, not declarations}} init() { } } class BaseClass { @autoclosure var property : () -> Int // expected-error {{attribute can only be applied to types, not declarations}} init() {} } class DerivedClass { var property : () -> Int { get {} set {} } } protocol P1 { associatedtype Element } protocol P2 : P1 { associatedtype Element } func overloadedEach<O: P1>(_ source: O, _ closure: @escaping () -> ()) { } func overloadedEach<P: P2>(_ source: P, _ closure: @escaping () -> ()) { } struct S : P2 { typealias Element = Int func each(_ closure: @autoclosure () -> ()) { // expected-note@-1{{parameter 'closure' is implicitly non-escaping}} overloadedEach(self, closure) // expected-error {{passing non-escaping parameter 'closure' to function expecting an @escaping closure}} } } struct AutoclosureEscapeTest { @autoclosure let delayed: () -> Int // expected-error {{attribute can only be applied to types, not declarations}} } // @autoclosure(escaping) is no longer a thing; just make sure we don't crash // expected-error @+1 {{attribute can only be applied to types, not declarations}} func func10(@autoclosure(escaping _: () -> ()) { } // expected-error{{expected parameter name followed by ':'}} func func11(_: @autoclosure(escaping) @noescape () -> ()) { } // expected-error{{cannot find type 'escaping' in scope}} // expected-error @-1 {{attribute can only be applied to types, not declarations}} // expected-error @-2 {{expected ',' separator}} // expected-error @-3 {{expected parameter name followed by ':'}} func func12_sink(_ x: @escaping () -> Int) { } func func12a(_ x: @autoclosure () -> Int) { // expected-note@-1{{parameter 'x' is implicitly non-escaping}} func12_sink(x) // expected-error {{passing non-escaping parameter 'x' to function expecting an @escaping closure}} } func func12c(_ x: @autoclosure @escaping () -> Int) { func12_sink(x) // ok } func func12d(_ x: @escaping @autoclosure () -> Int) { func12_sink(x) // ok } class TestFunc12 { var x: Int = 5 func foo() -> Int { return 0 } func test() { func12a(x + foo()) // okay func12c(x + foo()) // expected-error@-1{{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note@-1{{reference 'self.' explicitly}} {{13-13=self.}} // expected-error@-2{{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note@-2{{reference 'self.' explicitly}} {{17-17=self.}} } } enum AutoclosureFailableOf<T> { case Success(@autoclosure () -> T) case Failure } let _ : AutoclosureFailableOf<Int> = .Success(42) let _ : (@autoclosure () -> ()) -> () // escaping is the name of param type let _ : (@autoclosure(escaping) -> ()) -> () // expected-error {{cannot find type 'escaping' in scope}} // Migration // expected-error @+1 {{attribute can only be applied to types, not declarations}} func migrateAC(@autoclosure _: () -> ()) { } // expected-error @+1 {{attribute can only be applied to types, not declarations}} func migrateACE(@autoclosure(escaping) _: () -> ()) { } func takesAutoclosure(_ fn: @autoclosure () -> Int) {} func takesThrowingAutoclosure(_: @autoclosure () throws -> Int) {} func callAutoclosureWithNoEscape(_ fn: () -> Int) { takesAutoclosure(1+1) // ok } func callAutoclosureWithNoEscape_2(_ fn: () -> Int) { takesAutoclosure(fn()) // ok } func callAutoclosureWithNoEscape_3(_ fn: @autoclosure () -> Int) { takesAutoclosure(fn()) // ok } // expected-error @+1 {{'@autoclosure' must not be used on variadic parameters}} func variadicAutoclosure(_ fn: @autoclosure () -> ()...) { for _ in fn {} } // rdar://41219750 // These are all arguably invalid; the autoclosure should have to be called. // But as long as we allow them, we shouldn't crash. func passNonThrowingToNonThrowingAC(_ fn: @autoclosure () -> Int) { takesAutoclosure(fn) // expected-error {{add () to forward @autoclosure parameter}} {{22-22=()}} } func passNonThrowingToThrowingAC(_ fn: @autoclosure () -> Int) { takesThrowingAutoclosure(fn) // expected-error {{add () to forward @autoclosure parameter}} {{30-30=()}} } func passThrowingToThrowingAC(_ fn: @autoclosure () throws -> Int) { takesThrowingAutoclosure(fn) // expected-error {{add () to forward @autoclosure parameter}} {{30-30=()}} } func passAutoClosureToSubscriptAndMember(_ fn: @autoclosure () -> Int) { struct S { func bar(_: Int, _ fun: @autoclosure () -> Int) {} subscript(_ fn: @autoclosure () -> Int) -> Int { return fn() } static func foo(_ fn: @autoclosure () -> Int) {} } let s = S() let _ = s.bar(42, fn) // expected-error {{add () to forward @autoclosure parameter}} {{23-23=()}} let _ = s[fn] // expected-error {{add () to forward @autoclosure parameter}} {{15-15=()}} let _ = S.foo(fn) // expected-error {{add () to forward @autoclosure parameter}} {{19-19=()}} } func passAutoClosureToEnumCase(_ fn: @autoclosure () -> Int) { enum E { case baz(@autoclosure () -> Int) } let _: E = .baz(42) // Ok let _: E = .baz(fn) // expected-error {{add () to forward @autoclosure parameter}} {{21-21=()}} } // rdar://problem/20591571 - Various type inference problems with @autoclosure func rdar_20591571() { func foo(_ g: @autoclosure () -> Int) { typealias G = ()->Int let _ = unsafeBitCast(g, to: G.self) // expected-error {{converting non-escaping parameter 'g' to generic parameter 'T' may allow it to escape}} } func id<T>(_: T) -> T {} // expected-note {{eneric parameters are always considered '@escaping'}} func same<T>(_: T, _: T) {} // expected-note@-1 2 {{generic parameters are always considered '@escaping'}} func takesAnAutoclosure(_ fn: @autoclosure () -> Int, _ efn: @escaping @autoclosure () -> Int) { // These are OK -- they count as non-escaping uses var _ = fn let _ = fn var _ = efn let _ = efn _ = id(fn) // expected-error {{converting non-escaping parameter 'fn' to generic parameter 'T' may allow it to escape}} _ = same(fn, { 3 }) // expected-error {{converting non-escaping parameter 'fn' to generic parameter 'T' may allow it to escape}} _ = same({ 3 }, fn) // expected-error {{converting non-escaping parameter 'fn' to generic parameter 'T' may allow it to escape}} withoutActuallyEscaping(fn) { _ in } // Ok withoutActuallyEscaping(fn) { (_: () -> Int) in } // Ok } } // rdar://problem/30906031 - [SR-4188]: withoutActuallyEscaping doesn't accept an @autoclosure argument func rdar_30906031(in arr: [Int], fn: @autoclosure () -> Int) -> Bool { return withoutActuallyEscaping(fn) { escapableF in // Ok arr.lazy.filter { $0 >= escapableF() }.isEmpty } } // SR-2688 class Foo { typealias FooClosure = () -> String func fooFunction(closure: @autoclosure FooClosure) {} // ok } class Bar { typealias BarClosure = (String) -> String func barFunction(closure: @autoclosure BarClosure) {} // expected-error {{argument type of @autoclosure parameter must be '()'}} } func rdar_47586626() { struct S {} typealias F = () -> S func foo(_: @autoclosure S) {} // expected-error {{@autoclosure attribute only applies to function types}} func bar(_: @autoclosure F) {} // Ok let s = S() foo(s) // ok bar(s) // ok } protocol P_47586626 { typealias F = () -> Int typealias G<T> = () -> T func foo(_: @autoclosure F) func bar<T>(_: @autoclosure G<T>) } func overloaded_autoclj<T>(_: @autoclosure () -> T) {} func overloaded_autoclj(_: @autoclosure () -> Int) {} func autoclosure_param_returning_func_type() { func foo(_ fn: @autoclosure () -> (() -> Int)) {} func generic_foo<T>(_ fn: @autoclosure () -> T) {} // expected-note {{generic parameters are always considered '@escaping'}} func bar_1(_ fn: @autoclosure @escaping () -> Int) { foo(fn) } // Ok func bar_2(_ fn: @autoclosure () -> Int) { foo(fn) } // expected-note {{parameter 'fn' is implicitly non-escaping}} // expected-error@-1 {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} func baz_1(_ fn: @autoclosure @escaping () -> Int) { generic_foo(fn) } // Ok (T is inferred as () -> Int) func baz_2(_ fn: @autoclosure @escaping () -> Int) { generic_foo(fn()) } // Ok (T is inferred as Int) func baz_3(_ fn: @autoclosure () -> Int) { generic_foo(fn) } // Fails because fn is not marked as @escaping // expected-error@-1 {{converting non-escaping parameter 'fn' to generic parameter 'T' may allow it to escape}} // Let's make sure using `fn` as value works fine in presence of overloading func biz_1(_ fn: @autoclosure @escaping () -> Int) { overloaded_autoclj(fn) } // Ok func biz_2(_ fn: @autoclosure @escaping () -> Int) { overloaded_autoclj(fn()) } // Ok func biz_3(_ fn: @autoclosure () -> Int) { overloaded_autoclj(fn) } // Fails because fn is not marked as @escaping // expected-error@-1 {{add () to forward @autoclosure parameter}} {{67-67=()}} func fiz(_: @autoclosure () -> (() -> Int)) {} func biz_4(_ fn: @autoclosure @escaping () -> (() -> Int)) { fiz(fn) } // Can't forward in Swift >= 5 mode // expected-error@-1 {{add () to forward @autoclosure parameter}} {{70-70=()}} func biz_5(_ fn: @escaping () -> (() -> Int)) { fiz(fn) } // Can't forward in Swift >= 5 mode // expected-error@-1 {{add () to forward @autoclosure parameter}} {{57-57=()}} } func test_autoclosure_with_generic_argument_mismatch() { struct S<T> {} // expected-note {{arguments to generic parameter 'T' ('String' and 'Int') are expected to be equal}} func foo(_: @autoclosure () -> S<Int>) {} foo(S<String>()) // expected-error {{cannot convert value of type 'S<String>' to expected argument type 'S<Int>'}} } // SR-11934 func sr_11934(_ x: @autoclosure String...) {} // expected-error {{'@autoclosure' must not be used on variadic parameters}} // SR-11938 let sr_11938_1: Array<@autoclosure String> = [] // expected-error {{'@autoclosure' may only be used on parameters}} func sr_11938_2() -> @autoclosure String { "" } // expected-error {{'@autoclosure' may only be used on parameters}} func sr_11938_3(_ x: [@autoclosure String]) {} // expected-error {{'@autoclosure' may only be used on parameters}} protocol SR_11938_P {} struct SR_11938_S : @autoclosure SR_11938_P {} // expected-error {{'@autoclosure' may only be used on parameters}} // SR-9178 func bar<T>(_ x: @autoclosure T) {} // expected-error 1{{@autoclosure attribute only applies to function types}}
apache-2.0
5d5c2503be64eadfb371f8d6ff05cb7f
38.777778
196
0.647368
3.671224
false
false
false
false
dche/FlatUtil
Tests/FlatUtilTests/ResultTests.swift
1
2007
import XCTest @testable import FlatUtil class ResultTests: XCTestCase { enum TestError: Error { case a, b, c, d } func testValue() { let v: Result<Int> = .value(1) let e: Result<Int> = .error(TestError.a) XCTAssertNotNil(v.value) XCTAssertEqual(v.value!, 1) XCTAssertNil(e.value) } func testError() { let v: Result<Int> = .value(1) let e: Result<Int> = .error(TestError.a) XCTAssertNil(v.error) XCTAssertNil(e.value) XCTAssertNotNil(e.error) XCTAssertEqual(e.error! as! TestError, TestError.a) } func testFlatMap() { let v: Result<Int> = .value(1) let e: Result<Int> = .error(TestError.a) let op: (Int) -> Result<String> = { i in return .value("\(i)") } let strv: Result<String> = v.flatMap(op) XCTAssertNotNil(strv.value) XCTAssertEqual(strv.value!, "1") let ev: Result<String> = e.flatMap(op) XCTAssertNil(ev.value) XCTAssertEqual(ev.error! as! TestError, TestError.a) } func testMap() { let v: Result<Int> = .value(1) let e: Result<Int> = .error(TestError.b) let op: (Int) -> String = { i in return "\(i)" } let strv: Result<String> = v.map(op) XCTAssertNotNil(strv.value) XCTAssertEqual(strv.value!, "1") let ev: Result<String> = e.map(op) XCTAssertNil(ev.value) XCTAssertEqual(ev.error! as! TestError, TestError.b) } func testOrElse() { let v: Result<String> = .value("1") let e: Result<String> = .error(TestError.b) let op: () -> Result<String> = { return .value("\(2)") } let strv: Result<String> = v.orElse(op) XCTAssertNotNil(strv.value) XCTAssertEqual(strv.value!, "1") let ev: Result<String> = e.orElse(op) XCTAssertNotNil(ev.value) XCTAssertEqual(ev.value!, "2") } }
mit
2b8811e6495527f760b9408636a2cc27
28.086957
60
0.55157
3.603232
false
true
false
false
saagarjha/iina
iina/Regex.swift
1
1420
// // Regex.swift // iina // // Created by lhc on 12/1/2017. // Copyright © 2017 lhc. All rights reserved. // import Foundation class Regex { static let aspect = Regex("\\A\\d+(\\.\\d+)?:\\d+(\\.\\d+)?\\Z") static let httpFileName = Regex("attachment; filename=(.+?)\\Z") static let url = Regex("^(([^:\\/?#]+):)(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?") static let filePath = Regex("^(/[^/]+)+$") static let geometry = Regex("^((\\d+%?)?(x(\\d+%?))?)?((\\+|\\-)(\\d+%?)(\\+|\\-)(\\d+%?))?$") var regex: NSRegularExpression? init (_ pattern: String) { if let exp = try? NSRegularExpression(pattern: pattern, options: []) { self.regex = exp } else { fatalError("Cannot create regex \(pattern)") } } func matches(_ str: String) -> Bool { if let matches = regex?.numberOfMatches(in: str, options: [], range: NSMakeRange(0, str.count)) { return matches > 0 } else { return false } } func captures(in str: String) -> [String] { var result: [String] = [] if let match = regex?.firstMatch(in: str, options: [], range: NSMakeRange(0, str.count)) { for i in 0..<match.numberOfRanges { let range = match.range(at: i) if range.length > 0 { result.append((str as NSString).substring(with: match.range(at: i))) } else { result.append("") } } } return result } }
gpl-3.0
e8facebfb7fdefeb414eafd3764f64d8
26.823529
101
0.524313
3.460976
false
false
false
false
robbits/SceneKit-TEST
master/SceneKitTest/GlobeScene.swift
1
3819
// // GlobeScene.swift // SceneKitTest // // Created by Rob James on 6/6/14. // import SceneKit import QuartzCore class GlobeScene: SCNScene { var camera: SCNCamera var cameraNode: SCNNode var ambientLightNode: SCNNode var globeNode: SCNNode override init() { self.camera = SCNCamera() self.camera.zNear = 0.01 self.cameraNode = SCNNode() self.cameraNode.position = SCNVector3(x: 0.0, y: 0.0, z: 1.5) self.cameraNode.camera = self.camera self.camera.focalBlurRadius = 0; // CABasicAnimation *theFocusAnimation = [CABasicAnimation animationWithKeyPath:"focalBlurRadius"]; // theFocusAnimation.fromValue = @(100); // theFocusAnimation.toValue = @(0); // theFocusAnimation.duration = 2.0; // theFocusAnimation.removedOnCompletion = YES; // [self.camera addAnimation:theFocusAnimation forKey:@"focus"]; let theAmbientLight = SCNLight() theAmbientLight.type = SCNLightTypeAmbient theAmbientLight.color = UIColor(white: 0.5, alpha: 1.0) self.ambientLightNode = SCNNode() self.ambientLightNode.light = theAmbientLight self.globeNode = SCNNode() let theGlobeGeometry = SCNSphere(radius: 0.5) theGlobeGeometry.firstMaterial?.diffuse.contents = UIImage(named:"earth_diffuse.jpg") theGlobeGeometry.firstMaterial?.ambient.contents = UIImage(named:"earth_ambient2.jpeg") // theGlobeGeometry.firstMaterial?.ambient.contents = UIImage(named:"earth_ambient.jpg") theGlobeGeometry.firstMaterial?.specular.contents = UIImage(named:"earth_specular.jpg") theGlobeGeometry.firstMaterial?.emission.contents = nil theGlobeGeometry.firstMaterial?.transparent.contents = nil theGlobeGeometry.firstMaterial?.reflective.contents = nil theGlobeGeometry.firstMaterial?.multiply.contents = nil theGlobeGeometry.firstMaterial?.normal.contents = UIImage(named:"earth_normal.jpg") let theGlobeModelNode = SCNNode(geometry: theGlobeGeometry) self.globeNode.addChildNode(theGlobeModelNode) let theCloudGeometry = SCNSphere(radius:0.505) theCloudGeometry.firstMaterial?.diffuse.contents = nil theCloudGeometry.firstMaterial?.ambient.contents = nil theCloudGeometry.firstMaterial?.specular.contents = nil theCloudGeometry.firstMaterial?.emission.contents = nil theCloudGeometry.firstMaterial?.transparent.contents = UIImage(named:"earth_clouds.png") theCloudGeometry.firstMaterial?.reflective.contents = nil theCloudGeometry.firstMaterial?.multiply.contents = nil theCloudGeometry.firstMaterial?.normal.contents = nil let theCloudModelNode = SCNNode(geometry: theCloudGeometry) self.globeNode.addChildNode(theCloudModelNode) // animate the 3d object let animation: CABasicAnimation = CABasicAnimation(keyPath: "rotation") animation.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 1, z: 0, w: Float(M_PI)*2)) animation.duration = 500 animation.repeatCount = MAXFLOAT //repeat forever self.globeNode.addAnimation(animation, forKey: nil) // animate the 3d object let cloudAnimation: CABasicAnimation = CABasicAnimation(keyPath: "rotation") cloudAnimation.toValue = NSValue(SCNVector4: SCNVector4(x: -1, y: 2, z: 0, w: Float(M_PI)*2)) cloudAnimation.duration = 1050 cloudAnimation.repeatCount = .infinity //repeat forever theCloudModelNode.addAnimation(cloudAnimation, forKey: nil) super.init() self.rootNode.addChildNode(self.cameraNode) self.rootNode.addChildNode(self.ambientLightNode) self.rootNode.addChildNode(self.globeNode) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
unlicense
9842853a87cbd45956abc3bb62f3ee1d
39.2
106
0.715109
4.215232
false
false
false
false
iOS-Swift-Developers/Swift
基础语法/字符串常用方法/main.swift
1
2643
// // main.swift // 字符串常用方法 // // Created by 韩俊强 on 2017/6/1. // Copyright © 2017年 HaRi. All rights reserved. // import Foundation /* 计算字符串长度: C: char *stringValue = "abc李"; printf("%tu", strlen(stringValue)); 打印结果6 OC: NSString *stringValue = @"abc李"; NSLog(@"%tu", stringValue.length); 打印结果4, 以UTF16计算 */ var stringVlaue = "abc韩" print(stringVlaue.lengthOfBytes(using: String.Encoding.utf8)) // 打印结果:6, 和C语言一样计算字节数 /* 字符串拼接 C: char str1[] = "abc"; char *str2 = "bcd"; char *str = strcat(str1, str2); OC: NSMutableString *str1 = [NSMutableString stringWithString:@"abc"]; NSString *str2 = @"bcd"; [str1 appendString:str2]; NSLog(@"%@", str1); */ var str1 = "abc" var str2 = "hjq" var str = str1 + str2 print(str) /* 格式化字符串 C: 相当麻烦, 指针, 下标等方式 OC: NSInteger index = 1; NSString *str1 = [NSMutableString stringWithFormat:@"http://ios.520it.cn/pic/%tu.png", index]; NSLog(@"%@", str1); */ var index = 1 var str3 = "http://www.blog26.com/pic/\(index).png" print(str3) /* 字符串比较: OC: NSString *str1 = @"abc"; NSString *str2 = @"abc"; if ([str1 compare:str2] == NSOrderedSame) { NSLog(@"相等"); }else { NSLog(@"不相等"); } if ([str1 isEqualToString:str2]) { NSLog(@"相等"); }else { NSLog(@"不相等"); } Swift:(== / != / >= / <=), 和C语言的strcmp一样是逐个比较 */ var str4 = "abc" var str5 = "abc" if str4 == str5 { print("相等") }else { print("不相等") } var str6 = "abd" var str7 = "abc" if str6 >= str7 { print("大于等于") }else { print("不大于等于") } /* 判断前后缀 OC: NSString *str = @"http://www.blog26.com"; if ([str hasPrefix:@"http"]) { NSLog(@"是url"); } if ([str hasSuffix:@".com"]) { NSLog(@"是天朝顶级域名"); } */ var str8 = "http://www.blog26.com" if str8.hasPrefix("www") { print("是url") } if str8.hasSuffix(".com") { print("是顶级域名") } /* 大小写转换 OC: NSString *str = @"abc.txt"; NSLog(@"%@", [str uppercaseString]); NSLog(@"%@", [str lowercaseString]); */ var str9 = "abc.txt" print(str9.uppercased()) print(str9.lowercased()) /* 转换为基本数据类型 OC: NSString *str = @"250"; NSInteger number = [str integerValue]; NSLog(@"%tu", number); */ var str10 = "250" // 如果str不能转换为整数, 那么可选类型返回nil // str = "250sd", 不能转换所以可能为nil var numerber:Int? = Int(str10) if numerber != nil { print(numerber!) // 2.0可以自动拆包,3.0以后则不会 }
mit
f330a7bdfb7aba9af1e3ce9be103b527
13.468354
95
0.602362
2.594779
false
false
false
false
SPECURE/rmbt-ios-client
Sources/ControlServer.swift
1
32655
/***************************************************************************************************** * Copyright 2016 SPECURE GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************************************/ import Foundation import Alamofire import AlamofireObjectMapper import ObjectMapper // TODO !!!!! public func getHistoryFilter(success: @escaping (_ filter: HistoryFilterType) -> (), error failure: @escaping ErrorCallback) { ControlServer.sharedControlServer.getSettings(success: { return }, error: failure ) } // // public func getHistoryFilter()-> HistoryFilterType? { return ControlServer.sharedControlServer.historyFilter } // ONT public func getMeasurementServerInfo(success: @escaping (_ response: MeasurementServerInfoResponse) -> (), error failure: @escaping ErrorCallback) { ControlServer.sharedControlServer.getMeasurementServerDetails(success: { servers in success(servers) }, error: failure) } public func checkSurvey(success: @escaping (_ response: CheckSurveyResponse) -> (), error failure: @escaping ErrorCallback) { ControlServer.sharedControlServer.checkSurvey(success: success, error: failure) } /// data type alias for filters public typealias HistoryFilterType = [String: [String]] /// public typealias EmptyCallback = () -> () /// public typealias ErrorCallback = (_ error: Error) -> () /// public typealias IpResponseSuccessCallback = (_ ipResponse: IpResponse_Old) -> () /// let secureRequestPrefix = "https://" /// class ControlServer { /// static let sharedControlServer = ControlServer() /// private let alamofireManager: Alamofire.Session /// private let settings = RMBTSettings.sharedSettings /// private var uuidQueue = DispatchQueue(label: "com.specure.nettest.uuid_queue", attributes: []) /// var version: String? /// var uuid: String? /// var historyFilter: HistoryFilterType? var surveySettings: SettingsReponse_Old.Settings.SurveySettings? var advertisingSettings: AdvertisingResponse? /// var openTestBaseURL: String? /// private var uuidKey: String = "client_uuid" // TODO: unique for each control server? /// var baseUrl = "https://netcouch.specure.com/api/v1" /// private var defaultBaseUrl = "https://netcouch.specure.com/api/v1" /*"http://localhost:8080/api/v1"*/ //RMBT_CONTROL_SERVER_URL // TODO: HTTP/2, NGINX, IOS PROBLEM! http://stackoverflow.com/questions/36907767/nsurlerrordomain-code-1004-for-few-seconds-after-app-start-up // /// var mapServerBaseUrl: String? // let storeUUIDKey = "uuid_" /// private init() { alamofireManager = ServerHelper.configureAlamofireManager() } /// deinit { alamofireManager.session.invalidateAndCancel() } func clearStoredUUID() { UserDefaults.clearStoredUUID(uuidKey: uuidKey) self.uuid = nil } /// func updateWithCurrentSettings(success successCallback: @escaping EmptyCallback, error failure: @escaping ErrorCallback) { baseUrl = RMBTConfig.sharedInstance.RMBT_CONTROL_SERVER_URL if self.uuid == nil { uuid = UserDefaults.checkStoredUUID(uuidKey: uuidKey) } // Check for old NKOM if self.uuid == nil { let uuidKey = "uuid_nettest-p-web.nettfart.no" uuid = UserDefaults.checkStoredUUID(uuidKey: uuidKey) if let uuid = self.uuid { UserDefaults.storeNewUUID(uuidKey: self.uuidKey, uuid: uuid) } } // Check for old ONT if self.uuid == nil { let uuidKey = "uuid_nettest.org" uuid = UserDefaults.checkStoredUUID(uuidKey: uuidKey) if let uuid = self.uuid { UserDefaults.storeNewUUID(uuidKey: self.uuidKey, uuid: uuid) } } // get settings of control server getSettings(success: { // check for ip version force if self.settings.nerdModeForceIPv6 { self.baseUrl = RMBTConfig.sharedInstance.RMBT_CONTROL_SERVER_IPV6_URL } else if self.settings.nerdModeForceIPv4 { self.baseUrl = RMBTConfig.sharedInstance.RMBT_CONTROL_SERVER_IPV4_URL } // if self.settings.debugUnlocked { // check for custom control server if self.settings.debugControlServerCustomizationEnabled { let scheme = self.settings.debugControlServerUseSSL ? "https" : "http" var hostname = self.settings.debugControlServerHostname if self.settings.debugControlServerPort != 0 && self.settings.debugControlServerPort != 80 { hostname = "\(String(describing: hostname)):\(self.settings.debugControlServerPort)" } // if let url = NSURL(scheme: scheme, host: hostname, path: "/api/v1"/*RMBT_CONTROL_SERVER_PATH*/) as URL? { // self.baseUrl = url.absoluteString // ! // self.uuidKey = "\(self.storeUUIDKey)\(url.host!)" // } let theUrl = NSURLComponents() theUrl.host = hostname theUrl.scheme = scheme theUrl.path = "/api/v1"/*RMBT_CONTROL_SERVER_PATH*/ self.baseUrl = (theUrl.url?.absoluteString)! // ! } } Log.logger.info("Control Server base url = \(self.baseUrl)") // self.mapServerBaseUrl = RMBTConfig.sharedInstance.RMBT_MAP_SERVER_PATH_URL successCallback() }) { error in failure(error) } } // func getMeasurementServerDetails(success: @escaping (_ response: MeasurementServerInfoResponse) -> (), error failure: @escaping ErrorCallback) { let req = MeasurementServerInfoRequest() if let l = RMBTLocationTracker.sharedTracker.predefinedGeoLocation { req.geoLocation = l } else if let l = RMBTLocationTracker.sharedTracker.location { let geoLocation = GeoLocation(location: l) req.geoLocation = geoLocation } // let baseUrl = RMBTConfig.sharedInstance.RMBT_CONTROL_MEASUREMENT_SERVER_URL // self.request(baseUrl, .post, path: "/measurementServer", requestObject: req, success: success, error: failure) // self.request(baseUrl, .get, path: "/measurementServer", requestObject: req, success: success, error: failure) let success: (_ response: [MeasurementServerInfoResponse.Servers]) -> () = { response in let measurementResponse = MeasurementServerInfoResponse() measurementResponse.servers = response success(measurementResponse) } ServerHelper.requestCustomArray(self.alamofireManager, baseUrl: baseUrl, method: .get, path: "/measurementServer", requestObject: req, success: success, error: failure) } // MARK: Advertising func getAdvertising(success successCallback: @escaping EmptyCallback, error failure: @escaping ErrorCallback) { ensureClientUuid(success: { (uuid) in let advertisingRequest = AdvertisingRequest() advertisingRequest.uuid = uuid if RMBTConfig.sharedInstance.RMBT_VERSION_NEW { successCallback() } else { let successFunc: (_ response: AdvertisingResponse) -> () = { response in Log.logger.debug("advertising: \(String(describing: response.isShowAdvertising))") self.advertisingSettings = response successCallback() } self.request(.post, path: "/advertising", requestObject: advertisingRequest, success: successFunc, error: { error in Log.logger.debug("advertising error") failure(error) }) } }, error: failure) } // MARK: Settings /// func getSettings(success successCallback: @escaping EmptyCallback, error failure: @escaping ErrorCallback) { let settingsRequest = SettingsRequest() settingsRequest.client = ClientSettings() settingsRequest.client?.clientType = "MOBILE" settingsRequest.client?.termsAndConditionsAccepted = true settingsRequest.client?.uuid = uuid //// // NKOM solution let successFunc: (_ response: SettingsReponse) -> () = { response in Log.logger.debug("settings: \(String(describing: response.client))") // set uuid self.uuid = response.client?.uuid // save uuid if let u = self.uuid { UserDefaults.storeNewUUID(uuidKey: self.uuidKey, uuid: u) } // set control server version self.version = response.settings?.versions?.controlServerVersion // set qos test type desc response.qosMeasurementTypes?.forEach({ measurementType in if let type = measurementType.type { QosMeasurementType.localizedNameDict[type] = measurementType.name } }) if RMBTConfig.sharedInstance.settingsMode == .remotely { /// // No synchro = No filters // if let ipv4Server = response.settings?.controlServerIpv4Host { RMBTConfig.sharedInstance.configNewCS_IPv4(server: ipv4Server) } // if let ipv6Server = response.settings?.controlServerIpv6Host { RMBTConfig.sharedInstance.configNewCS_IPv6(server: ipv6Server) } // if let mapServer = response.settings?.mapServer?.host { RMBTConfig.sharedInstance.configNewMapServer(server: mapServer) } } self.mapServerBaseUrl = RMBTConfig.sharedInstance.RMBT_MAP_SERVER_PATH_URL successCallback() } //// // ONT and all other project solution let successFuncOld: (_ response: SettingsReponse_Old) -> () = { response in Log.logger.debug("settings: \(response)") if let set = response.settings?.first { // set uuid if let newUUID = set.uuid { self.uuid = newUUID } // save uuid if let u = self.uuid { UserDefaults.storeNewUUID(uuidKey: self.uuidKey, uuid: u) } self.surveySettings = set.surveySettings // set control server version self.version = set.versions?.controlServerVersion // set qos test type desc set.qosMeasurementTypes?.forEach({ measurementType in if let theType = measurementType.testType, let theDesc = measurementType.testDesc { if let type = QosMeasurementType(rawValue: theType.lowercased()) { QosMeasurementType.localizedNameDict.updateValue(theDesc, forKey:type) } } }) // get history filters self.historyFilter = set.history if RMBTConfig.sharedInstance.settingsMode == .remotely { // if let ipv4Server = set.urls?.ipv4IpOnly { RMBTConfig.sharedInstance.configNewCS_IPv4(server: ipv4Server) } // if let ipv6Server = set.urls?.ipv6IpOnly { RMBTConfig.sharedInstance.configNewCS_IPv6(server: ipv6Server) } // if let theOpenTestBase = set.urls?.opendataPrefix { self.openTestBaseURL = theOpenTestBase } // if let checkip4 = set.urls?.ipv4IpCheck { RMBTConfig.sharedInstance.RMBT_CHECK_IPV4_URL = checkip4 } // check for map server from settings if let mapServer = set.map_server { let host = mapServer.host ?? "" let scheme = mapServer.useTls ? "https" : "http" // var port = (mapServer.port as NSNumber?)?.stringValue ?? "" if (port == "80" || port == "443") { port = "" } else { port = ":\(port)" } self.mapServerBaseUrl = "\(scheme)://\(host)\(port)\(RMBT_MAP_SERVER_PATH)" Log.logger.debug("setting map server url to \(String(describing: self.mapServerBaseUrl)) from settings request") } } else { self.mapServerBaseUrl = RMBTConfig.sharedInstance.RMBT_MAP_SERVER_PATH_URL } } successCallback() } if RMBTConfig.sharedInstance.RMBT_VERSION_NEW { request(.post, path: "/mobile/settings", requestObject: settingsRequest, success: successFunc, error: { error in Log.logger.debug("settings error") failure(error) }) } else { let settingsRequest_Old = SettingsRequest_Old() settingsRequest_Old.termsAndConditionsAccepted = true settingsRequest_Old.termsAndConditionsAccepted_Version = 1 settingsRequest_Old.uuid = self.uuid request(.post, path: "/mobile/settings", requestObject: settingsRequest_Old, success: successFuncOld, error: { error in Log.logger.debug("settings error") failure(error) }) } } // MARK: IP /// func getIpv4( success successCallback: @escaping IpResponseSuccessCallback, error failure: @escaping ErrorCallback) { // This doesn't seem to work: // getIpVersion(baseUrl: RMBTConfig.sharedInstance.RMBT_CHECK_IPV4_URL, success: successCallback, error: failure) // So we use this instead: ServerHelper.request(alamofireManager, baseUrl: "https://api.ipify.org?format=json", method: .get, path: "", requestObject: nil, success: successCallback , error: failure) } /// no NAT // func getIpv6( success successCallback: @escaping IpResponseSuccessCallback, error failure: @escaping ErrorCallback) { // getIpVersion(baseUrl: RMBTConfig.sharedInstance.RMBT_CONTROL_SERVER_IPV6_URL, success: successCallback, error: failure) // } /// func getIpVersion(baseUrl:String, success successCallback: @escaping IpResponseSuccessCallback, error failure: @escaping ErrorCallback) { let infoParams = IPRequest_Old() infoParams.uuid = self.uuid infoParams.plattform = "iOS" ServerHelper.request(alamofireManager, baseUrl: baseUrl, method: .post, path: "", requestObject: infoParams, success: successCallback , error: failure) } // MARK: Speed measurement /// func requestSpeedMeasurement(_ speedMeasurementRequest: SpeedMeasurementRequest, success: @escaping (_ response: SpeedMeasurementResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in speedMeasurementRequest.uuid = uuid speedMeasurementRequest.anonymous = RMBTSettings.sharedSettings.anonymousModeEnabled Log.logger.debugExec { if speedMeasurementRequest.anonymous { Log.logger.debug("CLIENT IS ANONYMOUS!") } } self.request(.post, path: "/measurements/speed", requestObject: speedMeasurementRequest, success: success, error: failure) }, error: failure) } /// func requestSpeedMeasurement_Old(_ speedMeasurementRequest: SpeedMeasurementRequest_Old, success: @escaping (_ response: SpeedMeasurementResponse_Old) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in speedMeasurementRequest.uuid = uuid speedMeasurementRequest.ndt = false speedMeasurementRequest.time = RMBTTimestampWithNSDate(NSDate() as Date) as? UInt64 self.request(.post, path: "/mobile/testRequest", requestObject: speedMeasurementRequest, success: success, error: failure) }, error: failure) } /// func submitZeroMeasurementRequests(_ measurementRequests: [ZeroMeasurementRequest], success: @escaping (_ response: SpeedMeasurementSubmitResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in var passedMeasurementResults: [ZeroMeasurementRequest] = [] for measurement in measurementRequests { if let _ = measurement.uuid { measurement.clientUuid = uuid passedMeasurementResults.append(measurement) } } if passedMeasurementResults.count > 0 { self.request(.post, path: "/zeroMeasurement", requestObjects: passedMeasurementResults, key: "zero_measurement", success: success, error: failure) } else { failure(NSError(domain: "controlServer", code: 134534, userInfo: nil)) // give error if no uuid was provided by caller } }, error: failure) } /// func submitSpeedMeasurementResult(_ speedMeasurementResult: SpeedMeasurementResult, success: @escaping (_ response: SpeedMeasurementSubmitResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in if let measurementUuid = speedMeasurementResult.uuid { speedMeasurementResult.clientUuid = uuid RMBTConfig.sharedInstance.RMBT_VERSION_NEW ? self.request(.put, path: "/measurements/speed/\(measurementUuid)", requestObject: speedMeasurementResult, success: success, error: failure) : self.request(.post, path: "/mobile/result", requestObject: speedMeasurementResult, success: success, error: failure) } else { failure(NSError(domain: "controlServer", code: 134534, userInfo: nil)) // give error if no uuid was provided by caller } }, error: failure) } /// func submitSpeedMeasurementResult_Old(_ speedMeasurementResult: SpeedMeasurementResult, success: @escaping (_ response: SpeedMeasurementSubmitResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in if speedMeasurementResult.uuid != nil { speedMeasurementResult.clientUuid = uuid self.request(.post, path: "/mobile/result", requestObject: speedMeasurementResult, success: success, error: failure) } else { failure(NSError(domain: "controlServer", code: 134534, userInfo: nil)) // give error if no uuid was provided by caller } }, error: failure) } /// func getSpeedMeasurement(_ uuid: String, success: @escaping (_ response: SpeedMeasurementResultResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { _ in self.request(.get, path: "/mobile/measurements/speed/\(uuid)", requestObject: nil, success: success, error: failure) }, error: failure) } /// func getSpeedMeasurementDetails(_ uuid: String, success: @escaping (_ response: SpeedMeasurementDetailResultResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { _ in self.request(.get, path: "/mobile/measurements/speed/\(uuid)/details", requestObject: nil, success: success, error: failure) }, error: failure) } /// func disassociateMeasurement(_ measurementUuid: String, success: @escaping (_ response: SpeedMeasurementDisassociateResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { clientUuid in self.request(.delete, path: "/mobile/clients/\(clientUuid)/measurements/\(measurementUuid)", requestObject: nil, success: success, error: failure) }, error: failure) } // MARK: Qos measurements /// func requestQosMeasurement(_ measurementUuid: String?, success: @escaping (_ response: QosMeasurmentResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in let qosMeasurementRequest = QosMeasurementRequest() qosMeasurementRequest.clientUuid = uuid qosMeasurementRequest.uuid = uuid qosMeasurementRequest.measurementUuid = measurementUuid self.request(.post, path: RMBTConfig.sharedInstance.RMBT_VERSION_NEW ? "/mobile/measurements/qos" : "/mobile/qosTestRequest" , requestObject: qosMeasurementRequest, success: success, error: failure) }, error: failure) } /// func submitQosMeasurementResult(_ qosMeasurementResult: QosMeasurementResultRequest, success: @escaping (_ response: QosMeasurementSubmitResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in qosMeasurementResult.clientUuid = uuid self.request(.post, path: "/mobile/resultQoS", requestObject: qosMeasurementResult, success: success, error: failure) }, error: failure) } /// func submitQosMeasurementResult_Old(_ qosMeasurementResult: QosMeasurementResultRequest, success: @escaping (_ response: QosMeasurementSubmitResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in if let measurementUuid = qosMeasurementResult.measurementUuid { qosMeasurementResult.clientUuid = uuid self.request(.put, path: "/measurements/qos/\(measurementUuid)", requestObject: qosMeasurementResult, success: success, error: failure) } else { failure(NSError(domain: "controlServer", code: 134535, userInfo: nil)) // TODO: give error if no measurement uuid was provided by caller } }, error: failure) } /// func getQosMeasurement(_ uuid: String, success: @escaping (_ response: QosMeasurementResultResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { _ in self.request(.get, path: "/measurements/qos/\(uuid)", requestObject: nil, success: success, error: failure) }, error: failure) } /// OLD solution func getQOSHistoryResultWithUUID(testUuid: String, success: @escaping (_ response: QosMeasurementResultResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { _ in let r = HistoryWithQOSRequest() r.testUUID = testUuid self.request(.post, path: "/mobile/qosTestResult", requestObject: r, success: success, error: failure) }, error: failure) } // MARK: History /// func getMeasurementHistory(_ success: @escaping (_ response: [HistoryItem]) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in self.requestArray(.get, path: "/clients/\(uuid)/measurements", requestObject: nil, success: success, error: failure) }, error: failure) } /// func getMeasurementHistory(_ timestamp: UInt64, success: @escaping (_ response: [HistoryItem]) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in self.requestArray(.get, path: "/clients/\(uuid)/measurements?timestamp=\(timestamp)", requestObject: nil, success: success, error: failure) }, error: failure) } // OLD /// func getHistoryWithFilters(filters: HistoryFilterType?, size: UInt, page: UInt, success: @escaping (_ response: HistoryWithFiltersResponse) -> (), error errorCallback: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in let req = HistoryWithFiltersRequest() req.uuid = uuid if let theFilters = filters { for filter in theFilters { if filter.key == "devices" { req.devices = filter.value } if filter.key == "networks" { req.networks = filter.value } } } self.request(.post, path: "/mobile/history?page=\(page)&size=\(size)&sort=measurementDate,desc", requestObject: req, success: success, error: errorCallback) }, error: errorCallback) } // /// func getHistoryResultWithUUID(uuid: String, fullDetails: Bool, success: @escaping (_ response: HistoryItem) -> (), error errorCallback: @escaping ErrorCallback) { let key = fullDetails ? "/mobile/testresultdetail" : "/mobile/history/\(uuid)" ensureClientUuid(success: { theUuid in let r = HistoryWithQOSRequest() r.testUUID = uuid self.request(.get, path: key, requestObject: nil, success: success, error: errorCallback) }, error: { error in Log.logger.debug("\(error)") errorCallback(error) }) } /// func getBasicHistoryResult(with uuid: String, success: @escaping (_ response: HistoryItem) -> (), error errorCallback: @escaping ErrorCallback) { ensureClientUuid(success: { theUuid in let path = "/mobile/history/\(uuid)" self.request(.get, path: path, requestObject: nil, success: success, error: errorCallback) }, error: { error in Log.logger.debug("\(error)") errorCallback(error) }) } /// func getHistoryResultWithUUID_Full(uuid: String, success: @escaping (_ response: SpeedMeasurementDetailResultResponse) -> (), error errorCallback: @escaping ErrorCallback) { let key = "/mobile/testresultdetail" ensureClientUuid(success: { theUuid in let r = HistoryWithQOSRequest() r.testUUID = uuid self.request(.post, path: key, requestObject: r, success: success, error: errorCallback) }, error: { error in Log.logger.debug("\(error)") errorCallback(error) }) } /// func getHistoryResultGraphs(by uuid: String, success: @escaping (_ response: RMBTHistorySpeedGraph) -> (), error errorCallback: @escaping ErrorCallback) { let key = "/mobile/graphs/\(uuid)" ensureClientUuid(success: { theUuid in self.request(.get, path: key, requestObject: nil, success: success, error: errorCallback) }, error: { error in Log.logger.debug("\(error)") errorCallback(error) }) } // MARK: Synchro /// func syncWithCode(code:String, success: @escaping (_ response: SyncCodeResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in let req = SyncCodeRequest() req.code = code req.uuid = uuid self.request(.post, path: "/sync", requestObject: req, success: success, error: failure) }, error: failure) } /// func synchGetCode(success: @escaping (_ response: GetSyncCodeResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in let req = GetSyncCodeRequest() req.uuid = uuid self.request(.post, path: "/sync", requestObject: req, success: success, error: failure) }, error: failure) } // MARK: Survey Settings /// func checkSurvey(success: @escaping (_ response: CheckSurveyResponse) -> (), error failure: @escaping ErrorCallback) { ensureClientUuid(success: { uuid in let req = CheckSurveyRequest() req.clientUuid = uuid self.request(.post, path: "/checkSurvey", requestObject: req, success: success, error: failure) }, error: failure) } // MARK: Private /// private func ensureClientUuid(success successCallback: @escaping (_ uuid: String) -> (), error errorCallback: @escaping ErrorCallback) { uuidQueue.async { if let uuid = self.uuid { successCallback(uuid) } else { self.uuidQueue.suspend() self.getSettings(success: { self.uuidQueue.resume() if let uuid = self.uuid { successCallback(uuid) } else { errorCallback(NSError(domain: "strange error, should never happen, should have uuid by now", code: -1234345, userInfo: nil)) } }, error: { error in self.uuidQueue.resume() errorCallback(error) }) } } } /// private func requestArray<T: BasicResponse>(_ method: Alamofire.HTTPMethod, path: String, requestObject: BasicRequest?, success: @escaping (_ response: [T]) -> (), error failure: @escaping ErrorCallback) { ServerHelper.requestArray(alamofireManager, baseUrl: baseUrl, method: method, path: path, requestObject: requestObject, success: success, error: failure) } /// private func request<T: BasicResponse>(_ method: Alamofire.HTTPMethod, path: String, requestObject: BasicRequest?, success: @escaping (_ response: T) -> (), error failure: @escaping ErrorCallback) { ServerHelper.request(alamofireManager, baseUrl: baseUrl, method: method, path: path, requestObject: requestObject, success: success, error: failure) } /// private func request<T: BasicResponse>(_ baseUrl: String?, _ method: Alamofire.HTTPMethod, path: String, requestObject: BasicRequest?, success: @escaping (_ response: T) -> (), error failure: @escaping ErrorCallback) { ServerHelper.request(alamofireManager, baseUrl: baseUrl, method: method, path: path, requestObject: requestObject, success: success, error: failure) } /// private func request<T: BasicResponse>(_ method: Alamofire.HTTPMethod, path: String, requestObjects: [BasicRequest]?, key: String?, success: @escaping (_ response: T) -> (), error failure: @escaping ErrorCallback) { ServerHelper.request(alamofireManager, baseUrl: baseUrl, method: method, path: path, requestObjects: requestObjects, key: key, success: success, error: failure) } }
apache-2.0
f5e2832745f26f7832692a98c805d8c5
41.027027
223
0.586801
5.01151
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Scenes/Shared Scene Objects/Table View Cells/Settings Dual Label Subtitle Cell/SettingsDualLabelSubtitleCell.swift
1
4267
// // SettingsDualLabelSubtitleCell.swift // NearbyWeather // // Created by Erik Maximilian Martens on 11.03.22. // Copyright © 2022 Erik Maximilian Martens. All rights reserved. // import UIKit import RxSwift // MARK: - Definitions private extension SettingsDualLabelSubtitleCell { struct Definitions {} } // MARK: - Class Definition final class SettingsDualLabelSubtitleCell: UITableViewCell, BaseCell { typealias CellViewModel = SettingsDualLabelSubtitleCellViewModel private typealias CellContentInsets = Constants.Dimensions.Spacing.ContentInsets private typealias CellInterelementSpacing = Constants.Dimensions.Spacing.InterElementSpacing // MARK: - UIComponents private lazy var leadingImageView = Factory.ImageView.make(fromType: .cellPrefix) private lazy var contentLabel = Factory.Label.make(fromType: .body(textColor: Constants.Theme.Color.ViewElement.Label.titleDark)) private lazy var subtitleLabel = Factory.Label.make(fromType: .subtitle()) // MARK: - Assets private var disposeBag = DisposeBag() // MARK: - Properties var cellViewModel: CellViewModel? // MARK: - Initialization override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layoutUserInterface() setupAppearance() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { printDebugMessage( domain: String(describing: self), message: "was deinitialized", type: .info ) } // MARK: - Cell Life Cycle func configure(with cellViewModel: BaseCellViewModelProtocol?) { guard let cellViewModel = cellViewModel as? SettingsDualLabelSubtitleCellViewModel else { return } self.cellViewModel = cellViewModel cellViewModel.observeEvents() bindContentFromViewModel(cellViewModel) bindUserInputToViewModel(cellViewModel) } override func prepareForReuse() { super.prepareForReuse() disposeBag = DisposeBag() } } // MARK: - ViewModel Bindings extension SettingsDualLabelSubtitleCell { func bindContentFromViewModel(_ cellViewModel: CellViewModel) { cellViewModel.cellModelDriver .drive(onNext: { [setContent] in setContent($0) }) .disposed(by: disposeBag) } } // MARK: - Cell Composition private extension SettingsDualLabelSubtitleCell { func setContent(for cellModel: SettingsDualLabelSubtitleCellModel) { contentLabel.text = cellModel.contentLabelText subtitleLabel.text = cellModel.subtitleLabelText selectionStyle = (cellModel.isSelectable ?? false) ? .default : .none accessoryType = (cellModel.isDisclosable ?? false) ? .disclosureIndicator : .none } func layoutUserInterface() { contentView.addSubview(contentLabel, constraints: [ contentLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), contentLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: CellContentInsets.top(from: .medium)), contentLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CellContentInsets.leading(from: .large)), contentLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CellContentInsets.trailing(from: .large)) ]) contentView.addSubview(subtitleLabel, constraints: [ subtitleLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height*(3/4)), subtitleLabel.topAnchor.constraint(equalTo: contentLabel.bottomAnchor, constant: CellInterelementSpacing.yDistance(from: .medium)), subtitleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -CellContentInsets.bottom(from: .medium)), subtitleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CellContentInsets.leading(from: .large)), subtitleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CellContentInsets.trailing(from: .large)) ]) } func setupAppearance() { backgroundColor = Constants.Theme.Color.ViewElement.primaryBackground contentView.backgroundColor = .clear } }
mit
6f7b99ad0c191cf6781fafc61efdf0bc
33.682927
137
0.755743
5.158404
false
false
false
false
EddieCeausu/Projects
swift/projectEuler/projectEuler.swift
1
1307
import Darwin import Foundation print("This is Project Euler problems") func mult3and5() { print("Problem 1 Multiples of 3 and 5") var multi = [Int]() for i in 0...1000 { if i % 3 == 0 { multi.append(i) } else if i % 5 == 0 { multi.append(i) } } let x = multi.reduce(0, +) print("Sum of multiples of 3 and 5 between 0 and 1000: \(x)") }; mult3and5() // *************************************************************************** // sleep(2) // *************************************************************************** // var done = false while !done { func fib(_ n:Int) -> Int { if n <= 1 { return n } else { return(fib(n-1) + fib(n-2)) } } print("Fibonacci sequence of values under 4,000,000") var i = 0 var fibo = [Int]() while fib(i) < 4_000_000 { if fib(i) % 2 == 0 { fibo.append(fib(i)) print(fib(i)) } i += 1 } i = fibo.reduce(0, +) print("The sum of the Even numbers of the fibonacci sequence values under 4,000,000: \(i)") done = true } // *************************************************************************** // sleep(2) // *************************************************************************** //
gpl-3.0
66ca47e01e87322cf3e1d0d40df52dcf
25.14
95
0.382555
4.021538
false
false
false
false
teodorpatras/SrollViewPlay
ScrollViewPlay/ScrollViewPlay/DotView.swift
1
2787
// // DotView.swift // ScrollViewPlay // // Created by Teodor Patras on 05/07/15. // Copyright (c) 2015 Teodor Patras. All rights reserved. // import UIKit class DotView: UIView { var color = UIColor.whiteColor() var highlightColor = UIColor.blackColor() class func placeRandomViewsWithinSuperview(superview : UIView, numberOfViews : Int, target : UIGestureRecognizerDelegate?, selector: Selector?) { for i in 1...numberOfViews { let randomDim = CGFloat(max(10, arc4random() % 100)) let bounds = superview.bounds let randomYCenter = max (randomDim / 2 + 10, CGFloat(arc4random()) % (bounds.size.height - randomDim / 2)) let randomXCenter = max (randomDim / 2 + 10, CGFloat(arc4random()) % (bounds.size.width - randomDim / 2)) let view = DotView(frame: CGRectMake(0, 0, randomDim, randomDim)) view.center = CGPointMake(randomXCenter, randomYCenter) superview.addSubview(view) view.backgroundColor = randomColor() view.color = view.backgroundColor! view.highlightColor = view.darkerColor() view.layer.cornerRadius = randomDim / 2 if let t = target, let s = selector { let gesture = UILongPressGestureRecognizer(target: t, action: s) view.addGestureRecognizer(gesture) gesture.cancelsTouchesInView = false gesture.delegate = target } } } func darkerColor() -> UIColor{ var r:CGFloat = 0 var g:CGFloat = 0 var b:CGFloat = 0 var a:CGFloat = 0 color.getRed(&r, green: &g, blue: &b, alpha: &a) let darkeningFactor : CGFloat = 0.3 return UIColor(red: max (r - darkeningFactor, 0.0), green: max (0.0, g - darkeningFactor), blue: max(b - darkeningFactor, 0.0), alpha: a) } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { self.backgroundColor = self.highlightColor } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { self.backgroundColor = color } override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) { self.backgroundColor = color } override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { var touchBounds = self.bounds if CGRectGetWidth(touchBounds) < 44 { let expansion = 44 - CGRectGetWidth(touchBounds) touchBounds = CGRectInset(touchBounds, -expansion, -expansion) } return CGRectContainsPoint(touchBounds, point) } }
mit
1194cbb78e68d41d110b734c36d8b637
35.194805
147
0.601722
4.59901
false
false
false
false
sschiau/swift
test/SILGen/observers.swift
6
20123
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -parse-as-library -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck %s var zero: Int = 0 func use(_: Int) {} func takeInt(_ a : Int) {} public struct DidSetWillSetTests { // CHECK-LABEL: sil [ossa] @$s9observers010DidSetWillC5TestsV{{[_0-9a-zA-Z]*}}fC public init(x : Int) { // Accesses to didset/willset variables are direct in init methods and dtors. a = x a = x // CHECK: bb0(%0 : $Int, %1 : $@thin DidSetWillSetTests.Type): // CHECK: [[SELF:%.*]] = mark_uninitialized [rootself] // CHECK: [[PB_SELF:%.*]] = project_box [[SELF]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_SELF]] // CHECK: [[P1:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign %0 to [[P1]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_SELF]] // CHECK: [[P2:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign %0 to [[P2]] } public var a: Int { // CHECK-LABEL: sil private [ossa] @$s9observers010DidSetWillC5TestsV1a{{[_0-9a-zA-Z]*}}vw willSet(newA) { // CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: debug_value_addr %1 : $*DidSetWillSetTests takeInt(a) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %1 // CHECK-NEXT: [[FIELDPTR:%.*]] = struct_element_addr [[READ]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: [[A:%.*]] = load [trivial] [[FIELDPTR]] : $*Int // CHECK-NEXT: end_access [[READ]] // CHECK: [[TAKEINTFN:%.*]] = function_ref @$s9observers7takeInt{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: apply [[TAKEINTFN]]([[A]]) : $@convention(thin) (Int) -> () takeInt(newA) // CHECK-NEXT: // function_ref observers.takeInt(Swift.Int) -> () // CHECK-NEXT: [[TAKEINTFN:%.*]] = function_ref @$s9observers7takeInt{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: apply [[TAKEINTFN]](%0) : $@convention(thin) (Int) -> () a = zero // reassign, but don't infinite loop. // CHECK-NEXT: // function_ref observers.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s9observers4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %1 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign [[ZERO]] to [[AADDR]] } // CHECK-LABEL: sil private [ossa] @$s9observers010DidSetWillC5TestsV1a{{[_0-9a-zA-Z]*}}vW didSet { // CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests): // CHECK-NEXT: debug // CHECK-NEXT: debug_value_addr %1 : $*DidSetWillSetTests takeInt(a) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %1 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[READ]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: [[A:%.*]] = load [trivial] [[AADDR]] : $*Int // CHECK-NEXT: end_access [[READ]] // CHECK-NEXT: // function_ref observers.takeInt(Swift.Int) -> () // CHECK-NEXT: [[TAKEINTFN:%.*]] = function_ref @$s9observers7takeInt{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: apply [[TAKEINTFN]]([[A]]) : $@convention(thin) (Int) -> () (self).a = zero // reassign, but don't infinite loop. // CHECK-NEXT: // function_ref observers.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s9observers4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %1 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign [[ZERO]] to [[AADDR]] } // This is the synthesized getter and setter for the willset/didset variable. // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s9observers010DidSetWillC5TestsV1aSivg // CHECK: bb0(%0 : $DidSetWillSetTests): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: return %2 : $Int{{.*}} // id: %3 // CHECK-LABEL: sil [ossa] @$s9observers010DidSetWillC5TestsV1aSivs // CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: debug_value_addr %1 // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] %1 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[READ]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: [[OLDVAL:%.*]] = load [trivial] [[AADDR]] : $*Int // CHECK-NEXT: end_access [[READ]] // CHECK-NEXT: debug_value [[OLDVAL]] : $Int, let, name "tmp" // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %1 // CHECK-NEXT: // function_ref {{.*}}.DidSetWillSetTests.a.willset : Swift.Int // CHECK-NEXT: [[WILLSETFN:%.*]] = function_ref @$s9observers010DidSetWillC5TestsV1a{{[_0-9a-zA-Z]*}}vw // CHECK-NEXT: apply [[WILLSETFN]](%0, [[WRITE]]) : $@convention(method) (Int, @inout DidSetWillSetTests) -> () // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %1 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign %0 to [[AADDR]] : $*Int // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %1 // CHECK-NEXT: // function_ref {{.*}}.DidSetWillSetTests.a.didset : Swift.Int // CHECK-NEXT: [[DIDSETFN:%.*]] = function_ref @$s9observers010DidSetWillC5TestsV1a{{[_0-9a-zA-Z]*}}vW : $@convention(method) (Int, @inout DidSetWillSetTests) -> () // CHECK-NEXT: apply [[DIDSETFN]]([[OLDVAL]], [[WRITE]]) : $@convention(method) (Int, @inout DidSetWillSetTests) -> () } // CHECK-LABEL: sil hidden [ossa] @$s9observers010DidSetWillC5TestsV8testReadSiyF // CHECK: [[SELF:%.*]] = begin_access [read] [unknown] %0 : $*DidSetWillSetTests // CHECK-NEXT: [[PROP:%.*]] = struct_element_addr [[SELF]] : $*DidSetWillSetTests // CHECK-NEXT: [[LOAD:%.*]] = load [trivial] [[PROP]] : $*Int // CHECK-NEXT: end_access [[SELF]] : $*DidSetWillSetTests // CHECK-NEXT: return [[LOAD]] : $Int mutating func testRead() -> Int { return a } // CHECK-LABEL: sil hidden [ossa] @$s9observers010DidSetWillC5TestsV9testWrite5inputySi_tF // CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %1 : $*DidSetWillSetTests // CHECK-NEXT: // function_ref observers.DidSetWillSetTests.a.setter // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$s9observers010DidSetWillC5TestsV1aSivs // CHECK-NEXT: apply [[SETTER]](%0, [[SELF]]) // CHECK-NEXT: end_access [[SELF]] : $*DidSetWillSetTests // CHECK-NEXT: [[RET:%.*]] = tuple () // CHECK-NEXT: return [[RET]] : $() mutating func testWrite(input: Int) { a = input } // CHECK-LABEL: sil hidden [ossa] @$s9observers010DidSetWillC5TestsV13testReadWrite5inputySi_tF // CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %1 : $*DidSetWillSetTests // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Int // CHECK-NEXT: [[PROP:%.*]] = struct_element_addr [[SELF]] : $*DidSetWillSetTests // CHECK-NEXT: [[LOAD:%.*]] = load [trivial] [[PROP]] : $*Int // CHECK-NEXT: store [[LOAD]] to [trivial] [[TEMP]] : $*Int // (modification goes here) // CHECK: [[RELOAD:%.*]] = load [trivial] [[TEMP]] : $*Int // CHECK-NEXT: // function_ref observers.DidSetWillSetTests.a.setter // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$s9observers010DidSetWillC5TestsV1aSivs // CHECK-NEXT: apply [[SETTER]]([[RELOAD]], [[SELF]]) // CHECK-NEXT: end_access [[SELF]] : $*DidSetWillSetTests // CHECK-NEXT: dealloc_stack [[TEMP]] : $*Int // CHECK-NEXT: [[RET:%.*]] = tuple () // CHECK-NEXT: return [[RET]] : $() mutating func testReadWrite(input: Int) { a += input } } // Test global observing properties. var global_observing_property : Int = zero { // The variable is initialized with "zero". // CHECK-LABEL: sil private [ossa] @globalinit_{{.*}}_func1 : $@convention(c) () -> () { // CHECK: bb0: // CHECK-NEXT: alloc_global @$s9observers25global_observing_propertySiv // CHECK-NEXT: %1 = global_addr @$s9observers25global_observing_propertySivp : $*Int // CHECK: observers.zero.unsafeMutableAddressor // CHECK: return // global_observing_property's setter needs to call didSet. // CHECK-LABEL: sil private [ossa] @$s9observers25global_observing_property{{[_0-9a-zA-Z]*}}vW didSet { // The didSet implementation needs to call takeInt. takeInt(global_observing_property) // CHECK: function_ref observers.takeInt // CHECK-NEXT: function_ref @$s9observers7takeInt{{[_0-9a-zA-Z]*}}F // Setting the variable from within its own didSet doesn't recursively call didSet. global_observing_property = zero // CHECK: // function_ref observers.global_observing_property.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @$s9observers25global_observing_propertySivau : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ADDRESS:%.*]] = apply [[ADDRESSOR]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: // function_ref observers.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s9observers4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[POINTER]] : $*Int // CHECK-NEXT: assign [[ZERO]] to [[WRITE]] : $*Int // CHECK-NEXT: end_access [[WRITE]] : $*Int // CHECK-NOT: function_ref @$s9observers25global_observing_property{{[_0-9a-zA-Z]*}}vW // CHECK: end sil function } // CHECK-LABEL: sil hidden [ossa] @$s9observers25global_observing_property{{[_0-9a-zA-Z]*}}vs // CHECK: function_ref observers.global_observing_property.unsafeMutableAddressor // CHECK-NEXT: function_ref @$s9observers25global_observing_property{{[_0-9a-zA-Z]*}}vau // CHECK: function_ref observers.global_observing_property.didset // CHECK-NEXT: function_ref @$s9observers25global_observing_property{{[_0-9a-zA-Z]*}}vW } func force_global_observing_property_setter() { let x = global_observing_property global_observing_property = x } // Test local observing properties. // CHECK-LABEL: sil hidden [ossa] @$s9observers24local_observing_property{{[_0-9a-zA-Z]*}}SiF func local_observing_property(_ arg: Int) { var localproperty: Int = arg { didSet { takeInt(localproperty) localproperty = zero } } takeInt(localproperty) localproperty = arg // Alloc and initialize the property to the argument value. // CHECK: bb0([[ARG:%[0-9]+]] : $Int) // CHECK: [[BOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[BOX]] // CHECK: store [[ARG]] to [trivial] [[PB]] } // didSet of localproperty (above) // Ensure that setting the variable from within its own didSet doesn't recursively call didSet. // CHECK-LABEL: sil private [ossa] @$s9observers24local_observing_property{{[_0-9a-zA-Z]*}}SiF13localproperty{{[_0-9a-zA-Z]*}}SivW // CHECK: bb0(%0 : $Int, %1 : @guaranteed ${ var Int }) // CHECK: [[POINTER:%.*]] = project_box %1 : ${ var Int }, 0 // CHECK: // function_ref observers.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s9observers4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[POINTER]] : $*Int // CHECK-NEXT: assign [[ZERO]] to [[WRITE]] : $*Int // CHECK-NEXT: end_access [[WRITE]] : $*Int // CHECK-NOT: function_ref @$s9observers24local_observing_property{{[_0-9a-zA-Z]*}}SiF13localproperty{{[_0-9a-zA-Z]*}}SivW // CHECK: end sil function func local_generic_observing_property<T>(_ arg: Int, _: T) { var localproperty1: Int = arg { didSet { takeInt(localproperty1) } } takeInt(localproperty1) localproperty1 = arg var localproperty2: Int = arg { didSet { _ = T.self takeInt(localproperty2) } } takeInt(localproperty2) localproperty2 = arg } // <rdar://problem/16006333> observing properties don't work in @objc classes @objc class ObservingPropertyInObjCClass { var bounds: Int { willSet {} didSet {} } init(b: Int) { bounds = b } } // CHECK-LABEL: sil hidden [ossa] @$s9observers32propertyWithDidSetTakingOldValueyyF : $@convention(thin) () -> () { func propertyWithDidSetTakingOldValue() { var p : Int = zero { didSet(oldValue) { // access to oldValue use(oldValue) // and newValue. use(p) } } p = zero } // CHECK-LABEL: sil private [ossa] @$s9observers32propertyWithDidSetTakingOldValueyyF1pL_Sivs // CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : @guaranteed ${ var Int }): // CHECK-NEXT: debug_value [[ARG1]] : $Int, let, name "value", argno 1 // CHECK-NEXT: [[ARG2_PB:%.*]] = project_box [[ARG2]] // CHECK-NEXT: debug_value_addr [[ARG2_PB]] : $*Int, var, name "p", argno 2 // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[ARG2_PB]] // CHECK-NEXT: [[ARG2_PB_VAL:%.*]] = load [trivial] [[READ]] : $*Int // CHECK-NEXT: end_access [[READ]] // CHECK-NEXT: debug_value [[ARG2_PB_VAL]] : $Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG2_PB]] // CHECK-NEXT: assign [[ARG1]] to [[WRITE]] : $*Int // CHECK-NEXT: end_access [[WRITE]] // SEMANTIC ARC TODO: Another case where we need to put the mark_function_escape on a new projection after a copy. // CHECK-NEXT: mark_function_escape [[ARG2_PB]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FUNC:%.*]] = function_ref @$s9observers32propertyWithDidSetTakingOldValueyyF1pL_SivW : $@convention(thin) (Int, @guaranteed { var Int }) -> () // CHECK-NEXT: %{{.*}} = apply [[FUNC]]([[ARG2_PB_VAL]], [[ARG2]]) : $@convention(thin) (Int, @guaranteed { var Int }) -> () // CHECK-NEXT: %{{.*}} = tuple () // CHECK-NEXT: return %{{.*}} : $() // CHECK-NEXT:} // end sil function '$s9observers32propertyWithDidSetTakingOldValue{{[_0-9a-zA-Z]*}}' // <rdar://problem/16406886> Observing properties don't work with ownership types class Ref {} struct ObservingPropertiesWithOwnershipTypes { unowned var alwaysPresent : Ref { didSet { } } init(res: Ref) { alwaysPresent = res } } // CHECK-LABEL: sil private [ossa] @$s9observers37ObservingPropertiesWithOwnershipTypesV13alwaysPresentAA3RefCvW : $@convention(method) (@guaranteed Ref, @inout ObservingPropertiesWithOwnershipTypes) -> () { struct ObservingPropertiesWithOwnershipTypesInferred { unowned var alwaysPresent = Ref() { didSet { } } weak var maybePresent = nil as Ref? { willSet { } } } // CHECK-LABEL: sil private [ossa] @$s9observers45ObservingPropertiesWithOwnershipTypesInferredV13alwaysPresentAA3RefCvW : $@convention(method) (@guaranteed Ref, @inout ObservingPropertiesWithOwnershipTypesInferred) -> () { // CHECK-LABEL: sil private [ossa] @$s9observers45ObservingPropertiesWithOwnershipTypesInferredV12maybePresentAA3RefCSgvw : $@convention(method) (@guaranteed Optional<Ref>, @inout ObservingPropertiesWithOwnershipTypesInferred) -> () { //<rdar://problem/16620121> Initializing constructor tries to initialize computed property overridden with willSet/didSet class ObservedBase { var printInfo: Ref! } class ObservedDerived : ObservedBase { override init() {} override var printInfo: Ref! { didSet { } } } // CHECK-LABEL: sil private [ossa] @$s9observers15ObservedDerivedC9printInfoAA3RefCSgvW : $@convention(method) (@guaranteed Optional<Ref>, @guaranteed ObservedDerived) -> () { /// <rdar://problem/26408353> crash when overriding internal property with /// public property public class BaseClassWithInternalProperty { var x: () = () } public class DerivedClassWithPublicProperty : BaseClassWithInternalProperty { public override var x: () { didSet {} } } // CHECK-LABEL: sil hidden [transparent] [ossa] @$s9observers29BaseClassWithInternalPropertyC1xytvg // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s9observers30DerivedClassWithPublicPropertyC1xytvg // CHECK: bb0([[SELF:%.*]] : @guaranteed $DerivedClassWithPublicProperty): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $DerivedClassWithPublicProperty // CHECK-NEXT: [[SUPER:%.*]] = upcast [[SELF_COPY]] : $DerivedClassWithPublicProperty to $BaseClassWithInternalProperty // CHECK-NEXT: [[BORROWED_SUPER:%.*]] = begin_borrow [[SUPER]] // CHECK-NEXT: [[DOWNCAST_BORROWED_SUPER:%.*]] = unchecked_ref_cast [[BORROWED_SUPER]] : $BaseClassWithInternalProperty to $DerivedClassWithPublicProperty // CHECK-NEXT: [[METHOD:%.*]] = super_method [[DOWNCAST_BORROWED_SUPER]] : $DerivedClassWithPublicProperty, #BaseClassWithInternalProperty.x!getter.1 : (BaseClassWithInternalProperty) -> () -> (), $@convention(method) (@guaranteed BaseClassWithInternalProperty) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[BORROWED_SUPER]]) : $@convention(method) (@guaranteed BaseClassWithInternalProperty) -> () // CHECK-NEXT: end_borrow [[BORROWED_SUPER]] // CHECK-NEXT: destroy_value [[SUPER]] : $BaseClassWithInternalProperty // CHECK: } // end sil function '$s9observers30DerivedClassWithPublicPropertyC1xytvg' // Make sure we use the correct substitutions when referencing a property in a // generic base class public class GenericBase<T> { var storage: T? = nil } public class ConcreteDerived : GenericBase<Int> { override var storage: Int? { didSet {} } } // CHECK-LABEL: sil private [ossa] @$s9observers15ConcreteDerivedC7storageSiSgvW : $@convention(method) (Optional<Int>, @guaranteed ConcreteDerived) -> () { // Make sure we upcast properly when the overridden property is in an ancestor // of our superclass public class BaseObserved { var x: Int = 0 } public class MiddleObserved : BaseObserved {} public class DerivedObserved : MiddleObserved { override var x: Int { didSet {} } } // CHECK-LABEL: sil private [ossa] @$s9observers15DerivedObservedC1xSivW : $@convention(method) (Int, @guaranteed DerivedObserved) -> () {
apache-2.0
f9ae6711b1e0253930696b3ed886b91f
44.942922
270
0.637976
3.66339
false
true
false
false
WhisperSystems/Signal-iOS
Signal/src/ViewControllers/Photos/PhotoCapture.swift
1
30679
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit protocol PhotoCaptureDelegate: AnyObject { // MARK: Still Photo func photoCaptureDidStartPhotoCapture(_ photoCapture: PhotoCapture) func photoCapture(_ photoCapture: PhotoCapture, didFinishProcessingAttachment attachment: SignalAttachment) func photoCapture(_ photoCapture: PhotoCapture, processingDidError error: Error) // MARK: Video func photoCaptureDidBeginVideo(_ photoCapture: PhotoCapture) func photoCaptureDidCompleteVideo(_ photoCapture: PhotoCapture) func photoCaptureDidCancelVideo(_ photoCapture: PhotoCapture) // MARK: Utility func photoCaptureCanCaptureMoreItems(_ photoCapture: PhotoCapture) -> Bool func photoCaptureDidTryToCaptureTooMany(_ photoCapture: PhotoCapture) var zoomScaleReferenceHeight: CGFloat? { get } var captureOrientation: AVCaptureVideoOrientation { get } func beginCaptureButtonAnimation(_ duration: TimeInterval) func endCaptureButtonAnimation(_ duration: TimeInterval) } @objc class PhotoCapture: NSObject { weak var delegate: PhotoCaptureDelegate? var flashMode: AVCaptureDevice.FlashMode { return captureOutput.flashMode } let session: AVCaptureSession // There can only ever be one `CapturePreviewView` per AVCaptureSession lazy private(set) var previewView = CapturePreviewView(session: session) let sessionQueue = DispatchQueue(label: "PhotoCapture.sessionQueue") private var currentCaptureInput: AVCaptureDeviceInput? private let captureOutput: CaptureOutput var captureDevice: AVCaptureDevice? { return currentCaptureInput?.device } private(set) var desiredPosition: AVCaptureDevice.Position = .back let recordingAudioActivity = AudioActivity(audioDescription: "PhotoCapture", behavior: .playAndRecord) override init() { self.session = AVCaptureSession() self.captureOutput = CaptureOutput() } // MARK: - Dependencies var audioSession: OWSAudioSession { return Environment.shared.audioSession } // MARK: - var audioDeviceInput: AVCaptureDeviceInput? func startAudioCapture() throws { assertIsOnSessionQueue() guard audioSession.startAudioActivity(recordingAudioActivity) else { throw PhotoCaptureError.assertionError(description: "unable to capture audio activity") } self.session.beginConfiguration() defer { self.session.commitConfiguration() } let audioDevice = AVCaptureDevice.default(for: .audio) // verify works without audio permissions let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice!) if session.canAddInput(audioDeviceInput) { // self.session.addInputWithNoConnections(audioDeviceInput) session.addInput(audioDeviceInput) self.audioDeviceInput = audioDeviceInput } else { owsFailDebug("Could not add audio device input to the session") } } func stopAudioCapture() { assertIsOnSessionQueue() self.session.beginConfiguration() defer { self.session.commitConfiguration() } guard let audioDeviceInput = self.audioDeviceInput else { owsFailDebug("audioDevice was unexpectedly nil") return } session.removeInput(audioDeviceInput) self.audioDeviceInput = nil audioSession.endAudioActivity(recordingAudioActivity) } func startVideoCapture() -> Promise<Void> { // If the session is already running, no need to do anything. guard !self.session.isRunning else { return Promise.value(()) } return sessionQueue.async(.promise) { [weak self] in guard let self = self else { return } self.session.beginConfiguration() defer { self.session.commitConfiguration() } self.session.sessionPreset = .medium try self.updateCurrentInput(position: .back) guard let photoOutput = self.captureOutput.photoOutput else { throw PhotoCaptureError.initializationFailed } guard self.session.canAddOutput(photoOutput) else { throw PhotoCaptureError.initializationFailed } if let connection = photoOutput.connection(with: .video) { if connection.isVideoStabilizationSupported { connection.preferredVideoStabilizationMode = .auto } } self.session.addOutput(photoOutput) let movieOutput = self.captureOutput.movieOutput if self.session.canAddOutput(movieOutput) { self.session.addOutput(movieOutput) guard let connection = movieOutput.connection(with: .video) else { throw PhotoCaptureError.initializationFailed } if connection.isVideoStabilizationSupported { connection.preferredVideoStabilizationMode = .auto } if #available(iOS 11.0, *) { guard movieOutput.availableVideoCodecTypes.contains(.h264) else { throw PhotoCaptureError.initializationFailed } // Use the H.264 codec to encode the video rather than HEVC. // Before iOS11, HEVC wasn't supported and H.264 was the default. movieOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.h264], for: connection) } } }.done(on: sessionQueue) { self.session.startRunning() } } func stopCapture() -> Guarantee<Void> { return sessionQueue.async(.promise) { self.session.stopRunning() } } func assertIsOnSessionQueue() { assertOnQueue(sessionQueue) } func switchCamera() -> Promise<Void> { AssertIsOnMainThread() let newPosition: AVCaptureDevice.Position switch desiredPosition { case .front: newPosition = .back case .back: newPosition = .front case .unspecified: newPosition = .front @unknown default: owsFailDebug("Unexpected enum value.") newPosition = .front break } desiredPosition = newPosition return sessionQueue.async(.promise) { [weak self] in guard let self = self else { return } self.session.beginConfiguration() defer { self.session.commitConfiguration() } try self.updateCurrentInput(position: newPosition) } } // This method should be called on the serial queue, // and between calls to session.beginConfiguration/commitConfiguration func updateCurrentInput(position: AVCaptureDevice.Position) throws { assertIsOnSessionQueue() guard let device = captureOutput.videoDevice(position: position) else { throw PhotoCaptureError.assertionError(description: description) } let newInput = try AVCaptureDeviceInput(device: device) if let oldInput = self.currentCaptureInput { session.removeInput(oldInput) NotificationCenter.default.removeObserver(self, name: .AVCaptureDeviceSubjectAreaDidChange, object: oldInput.device) } session.addInput(newInput) NotificationCenter.default.addObserver(self, selector: #selector(subjectAreaDidChange), name: .AVCaptureDeviceSubjectAreaDidChange, object: newInput.device) currentCaptureInput = newInput resetFocusAndExposure() } func switchFlashMode() -> Guarantee<Void> { return sessionQueue.async(.promise) { switch self.captureOutput.flashMode { case .auto: Logger.debug("new flashMode: on") self.captureOutput.flashMode = .on case .on: Logger.debug("new flashMode: off") self.captureOutput.flashMode = .off case .off: Logger.debug("new flashMode: auto") self.captureOutput.flashMode = .auto @unknown default: owsFailDebug("unknown flashMode: \(self.captureOutput.flashMode)") self.captureOutput.flashMode = .auto } } } func focus(with focusMode: AVCaptureDevice.FocusMode, exposureMode: AVCaptureDevice.ExposureMode, at devicePoint: CGPoint, monitorSubjectAreaChange: Bool) { sessionQueue.async { Logger.debug("focusMode: \(focusMode), exposureMode: \(exposureMode), devicePoint: \(devicePoint), monitorSubjectAreaChange:\(monitorSubjectAreaChange)") guard let device = self.captureDevice else { owsFailDebug("device was unexpectedly nil") return } do { try device.lockForConfiguration() // Setting (focus/exposure)PointOfInterest alone does not initiate a (focus/exposure) operation. // Call set(Focus/Exposure)Mode() to apply the new point of interest. if device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode) { device.focusPointOfInterest = devicePoint device.focusMode = focusMode } if device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode) { device.exposurePointOfInterest = devicePoint device.exposureMode = exposureMode } device.isSubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange device.unlockForConfiguration() } catch { owsFailDebug("error: \(error)") } } } func resetFocusAndExposure() { let devicePoint = CGPoint(x: 0.5, y: 0.5) focus(with: .continuousAutoFocus, exposureMode: .continuousAutoExposure, at: devicePoint, monitorSubjectAreaChange: false) } @objc func subjectAreaDidChange(notification: NSNotification) { resetFocusAndExposure() } // MARK: - Zoom let minimumZoom: CGFloat = 1.0 let maximumZoom: CGFloat = 3.0 var previousZoomFactor: CGFloat = 1.0 func updateZoom(alpha: CGFloat) { assert(alpha >= 0 && alpha <= 1) sessionQueue.async { guard let captureDevice = self.captureDevice else { owsFailDebug("captureDevice was unexpectedly nil") return } // we might want this to be non-linear let scale = CGFloatLerp(self.minimumZoom, self.maximumZoom, alpha) let zoomFactor = self.clampZoom(scale, device: captureDevice) self.updateZoom(factor: zoomFactor) } } func updateZoom(scaleFromPreviousZoomFactor scale: CGFloat) { sessionQueue.async { guard let captureDevice = self.captureDevice else { owsFailDebug("captureDevice was unexpectedly nil") return } let zoomFactor = self.clampZoom(scale * self.previousZoomFactor, device: captureDevice) self.updateZoom(factor: zoomFactor) } } func completeZoom(scaleFromPreviousZoomFactor scale: CGFloat) { sessionQueue.async { guard let captureDevice = self.captureDevice else { owsFailDebug("captureDevice was unexpectedly nil") return } let zoomFactor = self.clampZoom(scale * self.previousZoomFactor, device: captureDevice) Logger.debug("ended with scaleFactor: \(zoomFactor)") self.previousZoomFactor = zoomFactor self.updateZoom(factor: zoomFactor) } } private func updateZoom(factor: CGFloat) { assertIsOnSessionQueue() guard let captureDevice = self.captureDevice else { owsFailDebug("captureDevice was unexpectedly nil") return } do { try captureDevice.lockForConfiguration() captureDevice.videoZoomFactor = factor captureDevice.unlockForConfiguration() } catch { owsFailDebug("error: \(error)") } } private func clampZoom(_ factor: CGFloat, device: AVCaptureDevice) -> CGFloat { return min(factor.clamp(minimumZoom, maximumZoom), device.activeFormat.videoMaxZoomFactor) } // MARK: - Photo private func handleTap() { Logger.verbose("") guard let delegate = delegate else { return } guard delegate.photoCaptureCanCaptureMoreItems(self) else { delegate.photoCaptureDidTryToCaptureTooMany(self) return } delegate.photoCaptureDidStartPhotoCapture(self) sessionQueue.async { self.captureOutput.takePhoto(delegate: self) } } // MARK: - Video private func handleLongPressBegin() { AssertIsOnMainThread() Logger.verbose("") guard let delegate = delegate else { return } guard delegate.photoCaptureCanCaptureMoreItems(self) else { delegate.photoCaptureDidTryToCaptureTooMany(self) return } sessionQueue.async(.promise) { try self.startAudioCapture() self.captureOutput.beginVideo(delegate: self) }.done { self.delegate?.photoCaptureDidBeginVideo(self) }.catch { error in self.delegate?.photoCapture(self, processingDidError: error) }.retainUntilComplete() } private func handleLongPressComplete() { Logger.verbose("") sessionQueue.async { self.captureOutput.completeVideo(delegate: self) self.stopAudioCapture() } AssertIsOnMainThread() // immediately inform UI that capture is stopping delegate?.photoCaptureDidCompleteVideo(self) } private func handleLongPressCancel() { Logger.verbose("") AssertIsOnMainThread() sessionQueue.async { self.stopAudioCapture() } delegate?.photoCaptureDidCancelVideo(self) } } extension PhotoCapture: VolumeButtonObserver { func didPressVolumeButton(with identifier: VolumeButtons.Identifier) { delegate?.beginCaptureButtonAnimation(0.5) } func didReleaseVolumeButton(with identifier: VolumeButtons.Identifier) { delegate?.endCaptureButtonAnimation(0.2) } func didTapVolumeButton(with identifier: VolumeButtons.Identifier) { handleTap() } func didBeginLongPressVolumeButton(with identifier: VolumeButtons.Identifier) { handleLongPressBegin() } func didCompleteLongPressVolumeButton(with identifier: VolumeButtons.Identifier) { handleLongPressComplete() } func didCancelLongPressVolumeButton(with identifier: VolumeButtons.Identifier) { handleLongPressCancel() } } extension PhotoCapture: CaptureButtonDelegate { func didTapCaptureButton(_ captureButton: CaptureButton) { handleTap() } func didBeginLongPressCaptureButton(_ captureButton: CaptureButton) { handleLongPressBegin() } func didCompleteLongPressCaptureButton(_ captureButton: CaptureButton) { handleLongPressComplete() } func didCancelLongPressCaptureButton(_ captureButton: CaptureButton) { handleLongPressCancel() } var zoomScaleReferenceHeight: CGFloat? { return delegate?.zoomScaleReferenceHeight } func longPressCaptureButton(_ captureButton: CaptureButton, didUpdateZoomAlpha zoomAlpha: CGFloat) { updateZoom(alpha: zoomAlpha) } } extension PhotoCapture: CaptureOutputDelegate { var captureOrientation: AVCaptureVideoOrientation { guard let delegate = delegate else { return .portrait } return delegate.captureOrientation } // MARK: - Photo func captureOutputDidFinishProcessing(photoData: Data?, error: Error?) { Logger.verbose("") AssertIsOnMainThread() if let error = error { delegate?.photoCapture(self, processingDidError: error) return } guard let photoData = photoData else { owsFailDebug("photoData was unexpectedly nil") delegate?.photoCapture(self, processingDidError: PhotoCaptureError.captureFailed) return } let dataSource = DataSourceValue.dataSource(with: photoData, utiType: kUTTypeJPEG as String) let attachment = SignalAttachment.attachment(dataSource: dataSource, dataUTI: kUTTypeJPEG as String, imageQuality: .medium) delegate?.photoCapture(self, didFinishProcessingAttachment: attachment) } // MARK: - Movie func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { Logger.verbose("") AssertIsOnMainThread() } func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { Logger.verbose("") AssertIsOnMainThread() if let error = error { guard didSucceedDespiteError(error) else { delegate?.photoCapture(self, processingDidError: error) return } Logger.info("Ignoring error, since capture succeeded.") } guard let dataSource = try? DataSourcePath.dataSource(with: outputFileURL, shouldDeleteOnDeallocation: true) else { delegate?.photoCapture(self, processingDidError: PhotoCaptureError.captureFailed) return } // AVCaptureMovieFileOutput records to .mov, but for compatibility we need to send mp4's. // Because we take care to record with h264 compression (not hevc), this conversion // doesn't require re-encoding the media streams and happens quickly. let (attachmentPromise, _) = SignalAttachment.compressVideoAsMp4(dataSource: dataSource, dataUTI: kUTTypeMPEG4 as String) attachmentPromise.map { [weak self] attachment in guard let self = self else { return } self.delegate?.photoCapture(self, didFinishProcessingAttachment: attachment) }.retainUntilComplete() } /// The AVCaptureFileOutput can return an error even though recording succeeds. /// I can't find useful documentation on this, but Apple's example AVCam app silently /// discards these errors, so we do the same. /// These spurious errors can be reproduced 1/3 of the time when making a series of short videos. private func didSucceedDespiteError(_ error: Error) -> Bool { let nsError = error as NSError guard let successfullyFinished = nsError.userInfo[AVErrorRecordingSuccessfullyFinishedKey] as? Bool else { return false } return successfullyFinished } } // MARK: - Capture Adapter protocol CaptureOutputDelegate: AVCaptureFileOutputRecordingDelegate { var session: AVCaptureSession { get } func assertIsOnSessionQueue() func captureOutputDidFinishProcessing(photoData: Data?, error: Error?) var captureOrientation: AVCaptureVideoOrientation { get } } protocol ImageCaptureOutput: AnyObject { var avOutput: AVCaptureOutput { get } var flashMode: AVCaptureDevice.FlashMode { get set } func videoDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice? func takePhoto(delegate: CaptureOutputDelegate) } class CaptureOutput { let imageOutput: ImageCaptureOutput let movieOutput: AVCaptureMovieFileOutput // MARK: - Init init() { if #available(iOS 10.0, *) { imageOutput = PhotoCaptureOutputAdaptee() } else { imageOutput = StillImageCaptureOutput() } movieOutput = AVCaptureMovieFileOutput() // disable movie fragment writing since it's not supported on mp4 // leaving it enabled causes all audio to be lost on videos longer // than the default length (10s). movieOutput.movieFragmentInterval = CMTime.invalid } var photoOutput: AVCaptureOutput? { return imageOutput.avOutput } var flashMode: AVCaptureDevice.FlashMode { get { return imageOutput.flashMode } set { imageOutput.flashMode = newValue } } func videoDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice? { return imageOutput.videoDevice(position: position) } func takePhoto(delegate: CaptureOutputDelegate) { delegate.assertIsOnSessionQueue() guard let photoOutput = photoOutput else { owsFailDebug("photoOutput was unexpectedly nil") return } guard let photoVideoConnection = photoOutput.connection(with: .video) else { owsFailDebug("photoVideoConnection was unexpectedly nil") return } let videoOrientation = delegate.captureOrientation photoVideoConnection.videoOrientation = videoOrientation Logger.verbose("videoOrientation: \(videoOrientation)") return imageOutput.takePhoto(delegate: delegate) } // MARK: - Movie Output func beginVideo(delegate: CaptureOutputDelegate) { delegate.assertIsOnSessionQueue() guard let videoConnection = movieOutput.connection(with: .video) else { owsFailDebug("movieOutputConnection was unexpectedly nil") return } let videoOrientation = delegate.captureOrientation videoConnection.videoOrientation = videoOrientation let outputFilePath = OWSFileSystem.temporaryFilePath(withFileExtension: "mp4") movieOutput.startRecording(to: URL(fileURLWithPath: outputFilePath), recordingDelegate: delegate) } func completeVideo(delegate: CaptureOutputDelegate) { delegate.assertIsOnSessionQueue() movieOutput.stopRecording() } func cancelVideo(delegate: CaptureOutputDelegate) { delegate.assertIsOnSessionQueue() // There's currently no user-visible way to cancel, if so, we may need to do some cleanup here. owsFailDebug("video was unexpectedly canceled.") } } @available(iOS 10.0, *) class PhotoCaptureOutputAdaptee: NSObject, ImageCaptureOutput { let photoOutput = AVCapturePhotoOutput() var avOutput: AVCaptureOutput { return photoOutput } var flashMode: AVCaptureDevice.FlashMode = .off override init() { photoOutput.isLivePhotoCaptureEnabled = false photoOutput.isHighResolutionCaptureEnabled = true } private var photoProcessors: [Int64: PhotoProcessor] = [:] func takePhoto(delegate: CaptureOutputDelegate) { delegate.assertIsOnSessionQueue() let settings = buildCaptureSettings() let photoProcessor = PhotoProcessor(delegate: delegate, completion: { [weak self] in self?.photoProcessors[settings.uniqueID] = nil }) photoProcessors[settings.uniqueID] = photoProcessor photoOutput.capturePhoto(with: settings, delegate: photoProcessor) } func videoDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice? { // use dual camera where available return AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: position) } // MARK: - private func buildCaptureSettings() -> AVCapturePhotoSettings { let photoSettings = AVCapturePhotoSettings() photoSettings.flashMode = flashMode photoSettings.isHighResolutionPhotoEnabled = true photoSettings.isAutoStillImageStabilizationEnabled = photoOutput.isStillImageStabilizationSupported return photoSettings } private class PhotoProcessor: NSObject, AVCapturePhotoCaptureDelegate { weak var delegate: CaptureOutputDelegate? let completion: () -> Void init(delegate: CaptureOutputDelegate, completion: @escaping () -> Void) { self.delegate = delegate self.completion = completion } @available(iOS 11.0, *) func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { let data = photo.fileDataRepresentation()! DispatchQueue.main.async { self.delegate?.captureOutputDidFinishProcessing(photoData: data, error: error) } completion() } // for legacy (iOS10) devices func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) { if #available(iOS 11, *) { owsFailDebug("unexpectedly calling legacy method.") } guard let photoSampleBuffer = photoSampleBuffer else { owsFailDebug("sampleBuffer was unexpectedly nil") return } let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(photoSampleBuffer) DispatchQueue.main.async { self.delegate?.captureOutputDidFinishProcessing(photoData: data, error: error) } completion() } } } class StillImageCaptureOutput: ImageCaptureOutput { var flashMode: AVCaptureDevice.FlashMode = .off let stillImageOutput = AVCaptureStillImageOutput() var avOutput: AVCaptureOutput { return stillImageOutput } init() { stillImageOutput.isHighResolutionStillImageOutputEnabled = true } // MARK: - func takePhoto(delegate: CaptureOutputDelegate) { guard let videoConnection = stillImageOutput.connection(with: .video) else { owsFailDebug("videoConnection was unexpectedly nil") return } stillImageOutput.captureStillImageAsynchronously(from: videoConnection) { [weak delegate] (sampleBuffer, error) in guard let sampleBuffer = sampleBuffer else { owsFailDebug("sampleBuffer was unexpectedly nil") return } let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) DispatchQueue.main.async { delegate?.captureOutputDidFinishProcessing(photoData: data, error: error) } } } func videoDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice? { let captureDevices = AVCaptureDevice.devices() guard let device = (captureDevices.first { $0.hasMediaType(.video) && $0.position == position }) else { Logger.debug("unable to find desired position: \(position)") return captureDevices.first } return device } } extension AVCaptureVideoOrientation { init?(deviceOrientation: UIDeviceOrientation) { switch deviceOrientation { case .portrait: self = .portrait case .portraitUpsideDown: self = .portraitUpsideDown case .landscapeLeft: self = .landscapeRight case .landscapeRight: self = .landscapeLeft default: return nil } } } extension AVCaptureDevice.FocusMode: CustomStringConvertible { public var description: String { switch self { case .locked: return "FocusMode.locked" case .autoFocus: return "FocusMode.autoFocus" case .continuousAutoFocus: return "FocusMode.continuousAutoFocus" @unknown default: return "FocusMode.unknown" } } } extension AVCaptureDevice.ExposureMode: CustomStringConvertible { public var description: String { switch self { case .locked: return "ExposureMode.locked" case .autoExpose: return "ExposureMode.autoExpose" case .continuousAutoExposure: return "ExposureMode.continuousAutoExposure" case .custom: return "ExposureMode.custom" @unknown default: return "ExposureMode.unknown" } } } extension AVCaptureVideoOrientation: CustomStringConvertible { public var description: String { switch self { case .portrait: return "AVCaptureVideoOrientation.portrait" case .portraitUpsideDown: return "AVCaptureVideoOrientation.portraitUpsideDown" case .landscapeRight: return "AVCaptureVideoOrientation.landscapeRight" case .landscapeLeft: return "AVCaptureVideoOrientation.landscapeLeft" @unknown default: return "AVCaptureVideoOrientation.unknown" } } } extension UIDeviceOrientation: CustomStringConvertible { public var description: String { switch self { case .unknown: return "UIDeviceOrientation.unknown" case .portrait: return "UIDeviceOrientation.portrait" case .portraitUpsideDown: return "UIDeviceOrientation.portraitUpsideDown" case .landscapeLeft: return "UIDeviceOrientation.landscapeLeft" case .landscapeRight: return "UIDeviceOrientation.landscapeRight" case .faceUp: return "UIDeviceOrientation.faceUp" case .faceDown: return "UIDeviceOrientation.faceDown" @unknown default: return "UIDeviceOrientation.unknown" } } } extension UIImage.Orientation: CustomStringConvertible { public var description: String { switch self { case .up: return "UIImageOrientation.up" case .down: return "UIImageOrientation.down" case .left: return "UIImageOrientation.left" case .right: return "UIImageOrientation.right" case .upMirrored: return "UIImageOrientation.upMirrored" case .downMirrored: return "UIImageOrientation.downMirrored" case .leftMirrored: return "UIImageOrientation.leftMirrored" case .rightMirrored: return "UIImageOrientation.rightMirrored" @unknown default: return "UIImageOrientation.unknown" } } }
gpl-3.0
139496d46242cc8587190dfdf1dd57cf
33.941913
296
0.655106
5.581044
false
false
false
false
practicalswift/swift
benchmark/single-source/DictionaryOfAnyHashableStrings.swift
5
2277
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils // This benchmark tests the performance of Dictionary<AnyHashable, Any> with // small ASCII String keys. Untyped NSDictionary values get imported as this // type, so it occurs relatively often in practice. public var DictionaryOfAnyHashableStrings = [ BenchmarkInfo( name: "DictionaryOfAnyHashableStrings_insert", runFunction: run_DictionaryOfAnyHashableStrings_insert, tags: [.abstraction, .runtime, .cpubench], setUpFunction: { keys = buildKeys(500) } ), BenchmarkInfo( name: "DictionaryOfAnyHashableStrings_lookup", runFunction: run_DictionaryOfAnyHashableStrings_lookup, tags: [.abstraction, .runtime, .cpubench], setUpFunction: { keys = buildKeys(500) workload = buildWorkload() } ), ] var keys: [String] = [] var workload: [AnyHashable: Any] = [:] func buildKeys(_ size: Int) -> [String] { var result: [String] = [] let keyPrefixes = ["font", "bgcolor", "fgcolor", "blink", "marquee"] for key in keyPrefixes { for i in 0 ..< size { result.append(key + "\(i)") } } return result } func buildWorkload() -> [AnyHashable: Any] { precondition(keys.count > 0) var result: [AnyHashable: Any] = [:] var i = 0 for key in keys { result[key] = i i += 1 } return result } @inline(never) public func run_DictionaryOfAnyHashableStrings_insert(_ n: Int) { precondition(keys.count > 0) for _ in 0 ... n { blackHole(buildWorkload()) } } @inline(never) public func run_DictionaryOfAnyHashableStrings_lookup(_ n: Int) { precondition(workload.count > 0) precondition(keys.count > 0) for _ in 0 ... n { for i in 0 ..< keys.count { let key = keys[i] CheckResults((workload[key] as! Int) == i) } } }
apache-2.0
8bcdce71bab487d0c95e0383ac5d59c9
26.433735
80
0.62231
4.037234
false
false
false
false
networkextension/SFSocket
SFSocket/scaner/Opt.swift
1
1767
import Foundation public struct Opt { public static var MAXNWTCPSocketReadDataSize = 15000 //fuck iOS9 limit allco memory use public static var MAXNWTCPSocketReadDataSize9 = 1024*8 // This is only used in finding the end of HTTP header (as of now). There is no limit on the length of http header, but Apache set it to 8KB public static var MAXNWTCPScanLength = 8912 public static var DNSFakeIPTTL = 300 public static var DNSPendingSessionLifeTime = 10 public static var UDPSocketActiveTimeout = 60//300 public static var UDPSocketActiveCheckInterval = 5 public static var MAXHTTPContentBlockLength = 10240 public static var RejectAdapterDefaultDelay = 300 // public static var MAXNWTCPSocketReadDataSize = 128 * 1024 // // // This is only used in finding the end of HTTP header (as of now). There is no limit on the length of http header, but Apache set it to 8KB // public static var MAXNWTCPScanLength = 8912 // // public static var DNSFakeIPTTL = 300 // // public static var DNSPendingSessionLifeTime = 10 // // public static var UDPSocketActiveTimeout = 300 // // public static var UDPSocketActiveCheckInterval = 60 // // public static var MAXHTTPContentBlockLength = 10240 // // public static var RejectAdapterDefaultDelay = 300 public static var ProxyActiveSocketLimit = -1 /// Setting this will resolve the requested domain before matching any rules. This allows us to make everything asynchronous. public static var resolveDNSInAdvance = true /// This will let all socket use the same dispatch queue. /// /// Must be used with `resolveDNSInAdvance` set. public static var shareDispatchQueue = true }
bsd-3-clause
0e662b370b5738db4c33e618e913fa59
35.061224
146
0.716469
4.27845
false
false
false
false
jpachecou/SwiftyHelpers
SwiftyHelpersTest/UIKit/UIView+UtilsTest.swift
1
1878
// // UIView+UtilsTest.swift // SwiftyHelpers // // Created by Jonathan Pacheco on 1/24/16. // Copyright © 2016 Grability. All rights reserved. // import XCTest @testable import SwiftyHelpers class UIView_UtilsTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { } func testRemoveAllSubviews() { let viewTest = UIView() let view = UIView() let view2 = UIView() view.addSubview(view2) view2.addSubview(UIView()) view.addSubview(UIView()) viewTest.addSubview(UIView()) viewTest.addSubview(UIView()) viewTest.addSubview(view) viewTest.removeAllSubViews() XCTAssertEqual(viewTest.subviews.count, 0, "viewTest cannot have subviews") XCTAssertEqual(view2.subviews.count, 0, "view2 cannot have subviews") XCTAssertEqual(view.subviews.count, 0, "view cannot have subviews") } func testFindViewForClass() { class FooView: UIView {} let view = UIView() let view2 = UIView() let view3 = UIView() let fooView = FooView() view.addSubview(UIView()) view.addSubview(view2) view2.addSubview(view3) view2.addSubview(fooView) view2.addSubview(UIView()) view3.addSubview(UIView()) let findView: FooView? = getSubviewIntoView(view) XCTAssertNotNil(findView, "fooView no found") } func testLoadCustomView() { guard let testView: TestView = loadCustomView() else { XCTAssert(false) return } XCTAssertTrue(testView.classForCoder is TestView.Type, "testView need TestView Type") XCTAssertNotNil(testView, "testView cannot be nil") } }
mit
5d653211de285b9126d3d9ad771cfcf3
25.43662
93
0.592968
4.611794
false
true
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/NSNumberFormatter+WMFExtras.swift
2
3410
import Foundation let thousandsFormatter = { () -> NumberFormatter in let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 1 formatter.roundingMode = .halfUp return formatter }() let threeSignificantDigitWholeNumberFormatterGlobal = { () -> NumberFormatter in let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 0 formatter.usesSignificantDigits = true formatter.maximumSignificantDigits = 3 formatter.roundingMode = .halfUp return formatter }() extension NumberFormatter { public class var threeSignificantDigitWholeNumberFormatter: NumberFormatter { get { return threeSignificantDigitWholeNumberFormatterGlobal } } public class func localizedThousandsStringFromNumber(_ number: NSNumber) -> String { let doubleValue = number.doubleValue let absDoubleValue = abs(doubleValue) var adjustedDoubleValue: Double = doubleValue var formatString: String = "%1$@" if absDoubleValue > 1000000000 { adjustedDoubleValue = doubleValue/1000000000.0 formatString = WMFLocalizedString("number-billions", value:"%1$@B", comment:"%1$@B - %1$@ is replaced with a number represented in billions. In English 'B' is commonly used after a number to indicate that number is in 'billions'. So the 'B' should be changed to a character or short string indicating billions. For example 5,100,000,000 would become 5.1B. If there is no simple translation for this in the target language, make the translation %1$@ with no other characters and the full number will be shown.") } else if absDoubleValue > 1000000 { adjustedDoubleValue = doubleValue/1000000.0 formatString = WMFLocalizedString("number-millions", value:"%1$@M", comment:"%1$@M - %1$@ is replaced with a number represented in millions. In English 'M' is commonly used after a number to indicate that number is in 'millions'. So the 'M' should be changed to a character or short string indicating millions. For example 500,000,000 would become 500M. If there is no simple translation for this in the target language, make the translation %1$@ with no other characters and the full number will be shown.") } else if absDoubleValue > 1000 { adjustedDoubleValue = doubleValue/1000.0 formatString = WMFLocalizedString("number-thousands", value:"%1$@K", comment:"%1$@K - %1$@ is replaced with a number represented in thousands. In English the letter 'K' is commonly used after a number to indicate that number is in 'thousands'. So the letter 'K' should be changed to a character or short string indicating thousands. For example 500,000 would become 500K. If there is no simple translation for this in the target language, make the translation %1$@ with no other characters and the full number will be shown.\n{{Identical|%1$@k}}") } if formatString == "%1$@" { //check for opt-out translations adjustedDoubleValue = doubleValue } if let numberString = thousandsFormatter.string(from: NSNumber(value:adjustedDoubleValue)) { return String.localizedStringWithFormat(formatString, numberString) } else { return "" } } }
mit
5a73875d89060259a7f87b4d0ab485e3
56.79661
559
0.70176
5.089552
false
false
false
false
sman591/pegg
Pegg/AddFriendViewController.swift
1
2800
// // AddFriendViewController.swift // Pegg // // Created by Stuart Olivera on 2/7/15. // Copyright (c) 2015 Henry Saniuk, Stuart Olivera, Brandon Hudson. All rights reserved. // import UIKit import SwiftyJSON class AddFriendViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var friends = [Friend]() var searchCount = 0 @IBAction func cancelButton(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBOutlet weak var searchInput: UISearchBar! override func viewDidLoad() { searchInput.delegate = self // searchInput.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchText.utf16Count == 0 { return } searchCount++ let currentSearch = searchCount PeggAPI.search(searchText, completion: { json in if (currentSearch != self.searchCount) { // prevents late return API calls from overriding a newer table return; } self.friends = [] for (friendIndex: String, friend: JSON) in json { self.friends.append(Friend( username: friend["username"].stringValue, first: friend["first"].stringValue, last: friend["last"].stringValue )) } self.tableView.reloadData() }, failure: { json in } ) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.friends.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UserTableViewCell let friend = self.friends[indexPath.row] cell.nameLabel?.text = friend.fullName() cell.descriptionLabel?.text = friend.username return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { PeggAPI.addFriend(friends[indexPath.row].username, completion: { json in self.dismissViewControllerAnimated(true, completion: nil) }, failure: { json in self.tableView.deselectRowAtIndexPath(indexPath, animated: true) } ) } }
mit
8fd2d09e81a7fa43cee4fa12b92c96af
32.333333
114
0.605
5.479452
false
false
false
false
karwa/swift-corelibs-foundation
TestFoundation/TestNSAffineTransform.swift
1
15587
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import PortableFoundation import SwiftXCTest #endif class TestNSAffineTransform : XCTestCase { private let accuracyThreshold = 0.001 static var allTests: [(String, (TestNSAffineTransform) -> () throws -> Void)] { return [ ("test_BasicConstruction", test_BasicConstruction), ("test_IdentityTransformation", test_IdentityTransformation), ("test_Scale", test_Scale), ("test_Scaling", test_Scaling), ("test_TranslationScaling", test_TranslationScaling), ("test_ScalingTranslation", test_ScalingTranslation), ("test_Rotation_Degrees", test_Rotation_Degrees), ("test_Rotation_Radians", test_Rotation_Radians), ("test_Inversion", test_Inversion), ("test_IdentityTransformation", test_IdentityTransformation), ("test_Translation", test_Translation), ("test_TranslationComposed", test_TranslationComposed), ("test_AppendTransform", test_AppendTransform), ("test_PrependTransform", test_PrependTransform), ("test_TransformComposition", test_TransformComposition), ] } func checkPointTransformation(_ transform: NSAffineTransform, point: NSPoint, expectedPoint: NSPoint, _ message: String = "", file: StaticString = #file, line: UInt = #line) { let newPoint = transform.transformPoint(point) XCTAssertEqualWithAccuracy(Double(newPoint.x), Double(expectedPoint.x), accuracy: accuracyThreshold, file: file, line: line, "x (expected: \(expectedPoint.x), was: \(newPoint.x)): \(message)") XCTAssertEqualWithAccuracy(Double(newPoint.y), Double(expectedPoint.y), accuracy: accuracyThreshold, file: file, line: line, "y (expected: \(expectedPoint.y), was: \(newPoint.y)): \(message)") } func checkSizeTransformation(_ transform: NSAffineTransform, size: NSSize, expectedSize: NSSize, _ message: String = "", file: StaticString = #file, line: UInt = #line) { let newSize = transform.transformSize(size) XCTAssertEqualWithAccuracy(Double(newSize.width), Double(expectedSize.width), accuracy: accuracyThreshold, file: file, line: line, "width (expected: \(expectedSize.width), was: \(newSize.width)): \(message)") XCTAssertEqualWithAccuracy(Double(newSize.height), Double(expectedSize.height), accuracy: accuracyThreshold, file: file, line: line, "height (expected: \(expectedSize.height), was: \(newSize.height)): \(message)") } func checkRectTransformation(_ transform: NSAffineTransform, rect: NSRect, expectedRect: NSRect, _ message: String = "", file: StaticString = #file, line: UInt = #line) { let newRect = transform.transformRect(rect) checkPointTransformation(transform, point: newRect.origin, expectedPoint: expectedRect.origin, file: file, line: line, "origin (expected: \(expectedRect.origin), was: \(newRect.origin)): \(message)") checkSizeTransformation(transform, size: newRect.size, expectedSize: expectedRect.size, file: file, line: line, "size (expected: \(expectedRect.size), was: \(newRect.size)): \(message)") } func test_BasicConstruction() { let identityTransform = NSAffineTransform() let transformStruct = identityTransform.transformStruct // The diagonal entries (1,1) and (2,2) of the identity matrix are ones. The other entries are zeros. // TODO: These should use DBL_MAX but it's not available as part of Glibc on Linux XCTAssertEqualWithAccuracy(Double(transformStruct.m11), Double(1), accuracy: accuracyThreshold) XCTAssertEqualWithAccuracy(Double(transformStruct.m22), Double(1), accuracy: accuracyThreshold) XCTAssertEqualWithAccuracy(Double(transformStruct.m12), Double(0), accuracy: accuracyThreshold) XCTAssertEqualWithAccuracy(Double(transformStruct.m21), Double(0), accuracy: accuracyThreshold) XCTAssertEqualWithAccuracy(Double(transformStruct.tX), Double(0), accuracy: accuracyThreshold) XCTAssertEqualWithAccuracy(Double(transformStruct.tY), Double(0), accuracy: accuracyThreshold) } func test_IdentityTransformation() { let identityTransform = NSAffineTransform() func checkIdentityPointTransformation(_ point: NSPoint) { checkPointTransformation(identityTransform, point: point, expectedPoint: point) } checkIdentityPointTransformation(NSPoint()) checkIdentityPointTransformation(NSMakePoint(CGFloat(24.5), CGFloat(10.0))) checkIdentityPointTransformation(NSMakePoint(CGFloat(-7.5), CGFloat(2.0))) func checkIdentitySizeTransformation(_ size: NSSize) { checkSizeTransformation(identityTransform, size: size, expectedSize: size) } checkIdentitySizeTransformation(NSSize()) checkIdentitySizeTransformation(NSMakeSize(CGFloat(13.0), CGFloat(12.5))) checkIdentitySizeTransformation(NSMakeSize(CGFloat(100.0), CGFloat(-100.0))) } func test_Translation() { let point = NSPoint(x: CGFloat(0.0), y: CGFloat(0.0)) let noop = NSAffineTransform() noop.translateXBy(CGFloat(), yBy: CGFloat()) checkPointTransformation(noop, point: point, expectedPoint: point) let translateH = NSAffineTransform() translateH.translateXBy(CGFloat(10.0), yBy: CGFloat()) checkPointTransformation(translateH, point: point, expectedPoint: NSPoint(x: CGFloat(10.0), y: CGFloat())) let translateV = NSAffineTransform() translateV.translateXBy(CGFloat(), yBy: CGFloat(20.0)) checkPointTransformation(translateV, point: point, expectedPoint: NSPoint(x: CGFloat(), y: CGFloat(20.0))) let translate = NSAffineTransform() translate.translateXBy(CGFloat(-30.0), yBy: CGFloat(40.0)) checkPointTransformation(translate, point: point, expectedPoint: NSPoint(x: CGFloat(-30.0), y: CGFloat(40.0))) } func test_Scale() { let size = NSSize(width: CGFloat(10.0), height: CGFloat(10.0)) let noop = NSAffineTransform() noop.scaleBy(CGFloat(1.0)) checkSizeTransformation(noop, size: size, expectedSize: size) let shrink = NSAffineTransform() shrink.scaleBy(CGFloat(0.5)) checkSizeTransformation(shrink, size: size, expectedSize: NSSize(width: CGFloat(5.0), height: CGFloat(5.0))) let grow = NSAffineTransform() grow.scaleBy(CGFloat(3.0)) checkSizeTransformation(grow, size: size, expectedSize: NSSize(width: CGFloat(30.0), height: CGFloat(30.0))) let stretch = NSAffineTransform() stretch.scaleXBy(CGFloat(2.0), yBy: CGFloat(0.5)) checkSizeTransformation(stretch, size: size, expectedSize: NSSize(width: CGFloat(20.0), height: CGFloat(5.0))) } func test_Rotation_Degrees() { let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) let noop = NSAffineTransform() noop.rotateByDegrees(CGFloat()) checkPointTransformation(noop, point: point, expectedPoint: point) let tenEighty = NSAffineTransform() tenEighty.rotateByDegrees(CGFloat(1080.0)) checkPointTransformation(tenEighty, point: point, expectedPoint: point) let rotateCounterClockwise = NSAffineTransform() rotateCounterClockwise.rotateByDegrees(CGFloat(90.0)) checkPointTransformation(rotateCounterClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(10.0))) let rotateClockwise = NSAffineTransform() rotateClockwise.rotateByDegrees(CGFloat(-90.0)) checkPointTransformation(rotateClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(10.0), y: CGFloat(-10.0))) let reflectAboutOrigin = NSAffineTransform() reflectAboutOrigin.rotateByDegrees(CGFloat(180.0)) checkPointTransformation(reflectAboutOrigin, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(-10.0))) } func test_Rotation_Radians() { let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) let noop = NSAffineTransform() noop.rotateByRadians(CGFloat()) checkPointTransformation(noop, point: point, expectedPoint: point) let tenEighty = NSAffineTransform() tenEighty.rotateByRadians(CGFloat(6 * M_PI)) checkPointTransformation(tenEighty, point: point, expectedPoint: point) let rotateCounterClockwise = NSAffineTransform() rotateCounterClockwise.rotateByRadians(CGFloat(M_PI_2)) checkPointTransformation(rotateCounterClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(10.0))) let rotateClockwise = NSAffineTransform() rotateClockwise.rotateByRadians(CGFloat(-M_PI_2)) checkPointTransformation(rotateClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(10.0), y: CGFloat(-10.0))) let reflectAboutOrigin = NSAffineTransform() reflectAboutOrigin.rotateByRadians(CGFloat(M_PI)) checkPointTransformation(reflectAboutOrigin, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(-10.0))) } func test_Inversion() { let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) let translate = NSAffineTransform() translate.translateXBy(CGFloat(-30.0), yBy: CGFloat(40.0)) let rotate = NSAffineTransform() translate.rotateByDegrees(CGFloat(30.0)) let scale = NSAffineTransform() scale.scaleBy(CGFloat(2.0)) let identityTransform = NSAffineTransform() // append transformations identityTransform.appendTransform(translate) identityTransform.appendTransform(rotate) identityTransform.appendTransform(scale) // invert transformations scale.invert() rotate.invert() translate.invert() // append inverse transformations in reverse order identityTransform.appendTransform(scale) identityTransform.appendTransform(rotate) identityTransform.appendTransform(translate) checkPointTransformation(identityTransform, point: point, expectedPoint: point) } func test_TranslationComposed() { let xyPlus5 = NSAffineTransform() xyPlus5.translateXBy(CGFloat(2.0), yBy: CGFloat(3.0)) xyPlus5.translateXBy(CGFloat(3.0), yBy: CGFloat(2.0)) checkPointTransformation(xyPlus5, point: NSMakePoint(CGFloat(-2.0), CGFloat(-3.0)), expectedPoint: NSMakePoint(CGFloat(3.0), CGFloat(2.0))) } func test_Scaling() { let xyTimes5 = NSAffineTransform() xyTimes5.scaleBy(CGFloat(5.0)) checkPointTransformation(xyTimes5, point: NSMakePoint(CGFloat(-2.0), CGFloat(3.0)), expectedPoint: NSMakePoint(CGFloat(-10.0), CGFloat(15.0))) let xTimes2YTimes3 = NSAffineTransform() xTimes2YTimes3.scaleXBy(CGFloat(2.0), yBy: CGFloat(-3.0)) checkPointTransformation(xTimes2YTimes3, point: NSMakePoint(CGFloat(-1.0), CGFloat(3.5)), expectedPoint: NSMakePoint(CGFloat(-2.0), CGFloat(-10.5))) } func test_TranslationScaling() { let xPlus2XYTimes5 = NSAffineTransform() xPlus2XYTimes5.translateXBy(CGFloat(2.0), yBy: CGFloat()) xPlus2XYTimes5.scaleXBy(CGFloat(5.0), yBy: CGFloat(-5.0)) checkPointTransformation(xPlus2XYTimes5, point: NSMakePoint(CGFloat(1.0), CGFloat(2.0)), expectedPoint: NSMakePoint(CGFloat(7.0), CGFloat(-10.0))) } func test_ScalingTranslation() { let xyTimes5XPlus3 = NSAffineTransform() xyTimes5XPlus3.scaleBy(CGFloat(5.0)) xyTimes5XPlus3.translateXBy(CGFloat(3.0), yBy: CGFloat()) checkPointTransformation(xyTimes5XPlus3, point: NSMakePoint(CGFloat(1.0), CGFloat(2.0)), expectedPoint: NSMakePoint(CGFloat(20.0), CGFloat(10.0))) } func test_AppendTransform() { let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) let identityTransform = NSAffineTransform() identityTransform.appendTransform(identityTransform) checkPointTransformation(identityTransform, point: point, expectedPoint: point) let translate = NSAffineTransform() translate.translateXBy(CGFloat(10.0), yBy: CGFloat()) let scale = NSAffineTransform() scale.scaleBy(CGFloat(2.0)) let translateThenScale = NSAffineTransform(transform: translate) translateThenScale.appendTransform(scale) checkPointTransformation(translateThenScale, point: point, expectedPoint: NSPoint(x: CGFloat(40.0), y: CGFloat(20.0))) } func test_PrependTransform() { let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) let identityTransform = NSAffineTransform() identityTransform.prependTransform(identityTransform) checkPointTransformation(identityTransform, point: point, expectedPoint: point) let translate = NSAffineTransform() translate.translateXBy(CGFloat(10.0), yBy: CGFloat()) let scale = NSAffineTransform() scale.scaleBy(CGFloat(2.0)) let scaleThenTranslate = NSAffineTransform(transform: translate) scaleThenTranslate.prependTransform(scale) checkPointTransformation(scaleThenTranslate, point: point, expectedPoint: NSPoint(x: CGFloat(30.0), y: CGFloat(20.0))) } func test_TransformComposition() { let origin = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) let size = NSSize(width: CGFloat(40.0), height: CGFloat(20.0)) let rect = NSRect(origin: origin, size: size) let center = NSPoint(x: NSMidX(rect), y: NSMidY(rect)) let rotate = NSAffineTransform() rotate.rotateByDegrees(CGFloat(90.0)) let moveOrigin = NSAffineTransform() moveOrigin.translateXBy(-center.x, yBy: -center.y) let moveBack = NSAffineTransform(transform: moveOrigin) moveBack.invert() let rotateAboutCenter = NSAffineTransform(transform: rotate) rotateAboutCenter.prependTransform(moveOrigin) rotateAboutCenter.appendTransform(moveBack) // center of rect shouldn't move as its the rotation anchor checkPointTransformation(rotateAboutCenter, point: center, expectedPoint: center) } } extension NSAffineTransform { func transformRect(_ aRect: NSRect) -> NSRect { return NSRect(origin: transformPoint(aRect.origin), size: transformSize(aRect.size)) } }
apache-2.0
f8719c1444641b7d5fcdce5b3ea83e9a
46.233333
179
0.659331
4.785692
false
true
false
false
alaphao/gitstatus
GitStatus/GitStatus/RequestAuthorization.swift
1
904
// // RequestAuthorization.swift // TesteGitStatus // // Created by Gustavo Tiago on 29/04/15. // Copyright (c) 2015 Gustavo Tiago. All rights reserved. // import Foundation class RequestAuthorization{ func getRequest(url: String, username: String, pw: String) -> NSMutableURLRequest{ let username = username as String let password = pw as String let loginString = NSString(format: "%@:%@", username, password) let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)! let base64LoginString = loginData.base64EncodedStringWithOptions(nil) // create the request let url = NSURL(string: url) let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "GET" request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization") return request } }
mit
7eb4ca84a82f8145a0b3c346e0d966a8
31.321429
91
0.672566
4.783069
false
false
false
false
Yalantis/Segmentio
Segmentio/Source/Cells/SegmentioCellWithImageBeforeLabel.swift
1
2123
// // SegmentioCellWithImageBeforeLabel.swift // Segmentio // // Created by Dmitriy Demchenko // Copyright © 2016 Yalantis Mobile. All rights reserved. // import UIKit class SegmentioCellWithImageBeforeLabel: SegmentioCell { override func setupConstraintsForSubviews() { super.setupConstraintsForSubviews() guard let imageContainerView = imageContainerView else { return } guard let containerView = containerView else { return } let metrics = ["labelHeight": SegmentioCell.segmentTitleLabelHeight] let views = [ "imageContainerView": imageContainerView, "containerView": containerView ] // main constraints let segmentImageViewVerticalConstraint = NSLayoutConstraint.constraints( withVisualFormat: "V:[imageContainerView(labelHeight)]", options: [.alignAllCenterY], metrics: metrics, views: views) NSLayoutConstraint.activate(segmentImageViewVerticalConstraint) let contentViewHorizontalConstraints = NSLayoutConstraint.constraints( withVisualFormat: "|-[imageContainerView(labelHeight)]-[containerView]-|", options: [.alignAllCenterY], metrics: metrics, views: views) NSLayoutConstraint.activate(contentViewHorizontalConstraints) // custom constraints topConstraint = NSLayoutConstraint( item: containerView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: padding ) topConstraint?.isActive = true bottomConstraint = NSLayoutConstraint( item: contentView, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1, constant: padding ) bottomConstraint?.isActive = true } }
mit
f08fe6b12731d23226ce03665d2e4ac7
29.753623
86
0.598492
6.353293
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/chance_btc_wallet/viewcontrollers/public/FontsExtension.swift
1
2927
// // FontsExtension.swift // chance_btc_wallet // // Created by Chance on 2017/2/25. // Copyright © 2017年 chance. All rights reserved. // import UIKit /* extension UIFont { @objc class func myPreferredFont(forTextStyle style: String) -> UIFont { let defaultFont = myPreferredFont(forTextStyle: style) // don´t know but it works... let newDescriptor = defaultFont.fontDescriptor.withFamily(defaultFontFamily) return UIFont(descriptor: newDescriptor, size: defaultFont.pointSize) } @objc fileprivate class func mySystemFont(ofSize fontSize: CGFloat) -> UIFont { return myDefaultFont(ofSize: fontSize) } @objc fileprivate class func myBoldSystemFont(ofSize fontSize: CGFloat) -> UIFont { return myDefaultFont(ofSize: fontSize, withTraits: .traitBold) } @objc fileprivate class func myItalicSystemFont(ofSize fontSize: CGFloat) -> UIFont { return myDefaultFont(ofSize: fontSize, withTraits: .traitItalic) } fileprivate class func myDefaultFont(ofSize fontSize: CGFloat, withTraits traits: UIFontDescriptorSymbolicTraits = []) -> UIFont { let descriptor = UIFontDescriptor(name: defaultFontFamily, size: fontSize).withSymbolicTraits(traits) return UIFont(descriptor: descriptor!, size: fontSize) } } extension UIFont { class var defaultFontFamily: String { return "Menlo" } override open class func initialize() { if self == UIFont.self { _ = { swizzleSystemFont() }() } } private class func swizzleSystemFont() { let systemPreferredFontMethod = class_getClassMethod(self, #selector(UIFont.preferredFont(forTextStyle:))) let mySystemPreferredFontMethod = class_getClassMethod(self, #selector(UIFont.myPreferredFont(forTextStyle:))) method_exchangeImplementations(systemPreferredFontMethod, mySystemPreferredFontMethod) let systemFontMethod = class_getClassMethod(self, #selector(UIFont.systemFont(ofSize:))) let mySystemFontMethod = class_getClassMethod(self, #selector(UIFont.mySystemFont(ofSize:))) method_exchangeImplementations(systemFontMethod, mySystemFontMethod) let boldSystemFontMethod = class_getClassMethod(self, #selector(UIFont.boldSystemFont(ofSize:))) let myBoldSystemFontMethod = class_getClassMethod(self, #selector(UIFont.myBoldSystemFont(ofSize:))) method_exchangeImplementations(boldSystemFontMethod, myBoldSystemFontMethod) let italicSystemFontMethod = class_getClassMethod(self, #selector(UIFont.italicSystemFont(ofSize:))) let myItalicSystemFontMethod = class_getClassMethod(self, #selector(UIFont.myItalicSystemFont(ofSize:))) method_exchangeImplementations(italicSystemFontMethod, myItalicSystemFontMethod) } } */
mit
168de284068649145432897bdd84a7ff
39.041096
134
0.703045
5.048359
false
false
false
false
LiulietLee/Pick-Color
Pick Color/CoreDataModel.swift
1
1269
// // CoreDataModel.swift // Pick Color // // Created by Liuliet.Lee on 27/8/2016. // Copyright © 2016 Liuliet.Lee. All rights reserved. // import UIKit import CoreData class CoreDataModel { fileprivate var context = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext fileprivate func saveContext() { do { try context.save() } catch { print("save failed") } } func fetchColors() -> [Colors] { var colorItems = [Colors]() let fetchRequest = NSFetchRequest<Colors>(entityName: "Colors") do { try colorItems = context.fetch(fetchRequest) } catch { print("fetch failed") } return colorItems } func saveNewColor(_ newColor: UIColor, title: String) -> Colors { let entity = NSEntityDescription.entity(forEntityName: "Colors", in: context)! let newItem = Colors(entity: entity, insertInto: context) newItem.title = title newItem.uiColor = newColor saveContext() return newItem } func saveEditedColor() { saveContext() } func deleteColor(_ color: Colors) { context.delete(color) saveContext() } }
mit
c1f1669d2d3a02c4c555a647811926a8
24.877551
98
0.592271
4.766917
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/LeftTopWidth.Individual.swift
1
1260
// // LeftTopWidth.Individual.swift // NotAutoLayout // // Created by 史 翔新 on 2017/06/15. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct LeftTopWidth { let left: LayoutElement.Horizontal let top: LayoutElement.Vertical let width: LayoutElement.Length } } // MARK: - Make Frame extension IndividualProperty.LeftTopWidth { private func makeFrame(left: Float, top: Float, width: Float, height: Float) -> Rect { let x = left let y = top let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Length - // MARK: Height extension IndividualProperty.LeftTopWidth: LayoutPropertyCanStoreHeightToEvaluateFrameType { public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let left = self.left.evaluated(from: parameters) let top = self.top.evaluated(from: parameters) let width = self.width.evaluated(from: parameters, withTheOtherAxis: .height(0)) let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width)) return self.makeFrame(left: left, top: top, width: width, height: height) } }
apache-2.0
ab5bcd0d6b074ad17cea7595cebe6405
21.196429
116
0.715205
3.710448
false
false
false
false
malcommac/SwiftRichString
Sources/SwiftRichString/Style/Style.swift
1
26133
// // SwiftRichString // Elegant Strings & Attributed Strings Toolkit for Swift // // Created by Daniele Margutti. // Copyright © 2018 Daniele Margutti. All rights reserved. // // Web: http://www.danielemargutti.com // Email: [email protected] // Twitter: @danielemargutti // // // 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 #if os(OSX) import AppKit #else import UIKit #endif /// Style class encapsulate all the information about the attributes you can apply to a text. public class Style: StyleProtocol { //MARK: - INTERNAL PROPERTIES /// Handler to initialize a new style. public typealias StyleInitHandler = ((Style) -> (Void)) /// Contains font description and size along with all other additional /// attributes to render the text. You should not need to modify this object; /// configurable attributes are exposed at `Style` level. public var fontData: FontData? = FontData() /// Attributes defined by the style. This is the dictionary modified when you /// set a style attributed. private var innerAttributes: [NSAttributedString.Key : Any] = [:] /// This is a cache array used to avoid the evaluation of font description and other /// sensitive data. Cache is invalidated automatically when needed. private var cachedAttributes: [NSAttributedString.Key : Any]? = nil //MARK: - PROPERTIES /// Apply any transform to the text. public var textTransforms: [TextTransform]? /// Alter the size of the currently set font to the specified value (expressed in point) /// **Note**: in order to be used you must also set the `.font` attribute of the style. public var size: CGFloat? { set { self.fontData?.size = newValue self.invalidateCache() } get { return self.fontData?.size } } /// Set the font of the style. /// You can pass any `FontConvertible` conform object, it will be transformed to a valid `UIFont`/`NSFont`` /// and used by the style itself. Both `String`, `SystemFonts` and `UIFont`/`NSFont` are conform to this protocol yet /// so you are able to pass a valid font as a string, from predefined list or directly as an instance. public var font: FontConvertible? { set { self.fontData?.font = newValue if let f = newValue as? Font { self.fontData?.size = f.pointSize } self.invalidateCache() } get { return self.fontData?.font } } #if os(tvOS) || os(watchOS) || os(iOS) /// Set the dynamic text attributes to adapt the font/text to the current Dynamic Type settings. /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. @available(iOS 11.0, tvOS 11.0, iOSApplicationExtension 11.0, watchOS 4, *) public var dynamicText: DynamicText? { set { self.fontData?.dynamicText = newValue } get { return self.fontData?.dynamicText } } #endif /// Set the text color of the style. /// You can pass any `ColorConvertible` conform object, it will be transformed to a valid `UIColor`/`NSColor` /// automatically. Both `UIColor`/`NSColor` and `String` are conform to this protocol. public var color: ColorConvertible? { set { self.set(attribute: newValue?.color, forKey: .foregroundColor) } get { return self.get(attributeForKey: .foregroundColor) } } /// Set the background color of the style. /// You can pass any `ColorConvertible` conform object, it will be transformed to a valid `UIColor`/`NSColor` /// automatically. Both `UIColor`/`NSColor` and `String` are conform to this protocol. public var backColor: ColorConvertible? { set { self.set(attribute: newValue?.color, forKey: .backgroundColor) } get { return self.get(attributeForKey: .backgroundColor) } } /// This value indicates whether the text is underlined. /// Value must be a tuple which define the style of the line (as `NSUnderlineStyle`) /// and the optional color of the line (if `nil`, foreground color is used instead). public var underline: (style: NSUnderlineStyle?, color: ColorConvertible?)? { set { self.set(attribute: NSNumber.from(underlineStyle: newValue?.style), forKey: .underlineStyle) self.set(attribute: newValue?.color?.color, forKey: .underlineColor) } get { let style: NSNumber? = self.get(attributeForKey: .underlineStyle) let color: Color? = self.get(attributeForKey: .underlineColor) return (style?.toUnderlineStyle(),color) } } /// Define stroke attributes /// Value must be a tuple which defines the color of the line and the width. /// /// If `color` it is not defined it is assumed to be the same as the value of color; /// otherwise, it describes the outline color. /// /// The `width` value represents the amount to change the stroke width and is specified as a percentage /// of the font point size. Specify 0 (the default) for no additional changes. /// Specify positive values to change the stroke width alone. /// Specify negative values to stroke and fill the text. For example, a typical value for /// outlined text would be -3.0. public var stroke: (color: ColorConvertible?, width: Float?)? { set { self.set(attribute: newValue?.color?.color, forKey: .strokeColor) self.set(attribute: NSNumber.from(float: newValue?.width), forKey: .strokeWidth) } get { let color: Color? = self.get(attributeForKey: .strokeColor) let width: NSNumber? = self.get(attributeForKey: .strokeWidth) return (color,width?.floatValue) } } /// This value indicates whether the text has a line through it. /// Value must be a tuple which define the style of the line (as `NSUnderlineStyle`) /// and the optional color of the line (if `nil`, foreground color is used instead). public var strikethrough: (style: NSUnderlineStyle?, color: ColorConvertible?)? { set { self.set(attribute: NSNumber.from(underlineStyle: newValue?.style), forKey: .strikethroughStyle) self.set(attribute: newValue?.color?.color, forKey: .strikethroughColor) } get { let style: NSNumber? = self.get(attributeForKey: .strikethroughStyle) let color: Color? = self.get(attributeForKey: .strikethroughColor) return (style?.toUnderlineStyle(),color) } } /// Floating point value indicating the character’s offset from the baseline, in points. /// Default value when not set is 0. public var baselineOffset: Float? { set { self.set(attribute: NSNumber.from(float: newValue), forKey: .baselineOffset) } get { let value: NSNumber? = self.get(attributeForKey: .baselineOffset) return value?.floatValue } } /// Allows to set a default paragraph style to the content. /// A new `NSMutableParagraphStyle` instance is created automatically when you set any paragraph /// related property if an instance is not set yet. public var paragraph: NSMutableParagraphStyle { set { self.invalidateCache() self.set(attribute: newValue, forKey: .paragraphStyle) } get { if let paragraph: NSMutableParagraphStyle = self.get(attributeForKey: .paragraphStyle) { return paragraph } let paragraph = NSMutableParagraphStyle() self.set(attribute: paragraph, forKey: .paragraphStyle) return paragraph } } /// The distance in points between the bottom of one line fragment and the top of the next. /// This value is always nonnegative. /// This value is included in the line fragment heights in the layout manager. /// The default value is 0. public var lineSpacing: CGFloat { set { self.paragraph.lineSpacing = newValue } get { return self.paragraph.lineSpacing } } /// The distance between the paragraph’s top and the beginning of its text content. /// This property contains the space (measured in points) between the paragraph’s top /// and the beginning of its text content. /// /// The default value of this property is 0. public var paragraphSpacingBefore: CGFloat { set { self.paragraph.paragraphSpacingBefore = newValue } get { return self.paragraph.paragraphSpacingBefore } } /// This property contains the space (measured in points) added at the end of the paragraph /// to separate it from the following paragraph. /// /// This value must be nonnegative. /// The space between paragraphs is determined by adding the previous paragraph’s `paragraphSpacing` /// and the current paragraph’s `paragraphSpacingBefore`. /// /// Default value is 0. public var paragraphSpacingAfter: CGFloat { set { self.paragraph.paragraphSpacing = newValue } get { return self.paragraph.paragraphSpacing } } /// The text alignment of the receiver. /// By default value is `natural`, depending by system's locale. /// Natural text alignment is realized as left or right alignment depending on the line sweep /// direction of the first script contained in the paragraph. /// /// Default value is `natural`. public var alignment: NSTextAlignment { set { self.paragraph.alignment = newValue } get { return self.paragraph.alignment } } /// The distance (in points) from the leading margin of a text container to /// the beginning of the paragraph’s first line. /// This value is always nonnegative. /// /// Default value is 0. public var firstLineHeadIndent: CGFloat { set { self.paragraph.firstLineHeadIndent = newValue } get { return self.paragraph.firstLineHeadIndent } } /// The distance (in points) from the leading margin of a text container to the beginning /// of lines other than the first. /// This value is always nonnegative. /// /// Default value is 0. public var headIndent: CGFloat { set { self.paragraph.headIndent = newValue } get { return self.paragraph.headIndent } } /// If positive, this value is the distance from the leading margin /// (for example, the left margin in left-to-right text). /// If 0 or negative, it’s the distance from the trailing margin. /// /// Default value is `0.0`. public var tailIndent: CGFloat { set { self.paragraph.tailIndent = newValue } get { return self.paragraph.tailIndent } } /// The mode that should be used to break lines. /// /// Default value is `byTruncatingTail`. public var lineBreakMode: LineBreak { set { self.paragraph.lineBreakMode = newValue } get { return self.paragraph.lineBreakMode } } /// The minimum height in points that any line in the receiver will occupy, /// regardless of the font size or size of any attached graphic. /// This value must be nonnegative. /// /// The default value is 0. public var minimumLineHeight: CGFloat { set { self.paragraph.minimumLineHeight = newValue } get { return self.paragraph.minimumLineHeight } } /// The maximum height in points that any line in the receiver will occupy, /// regardless of the font size or size of any attached graphic. /// This value is always nonnegative. /// /// Glyphs and graphics exceeding this height will overlap neighboring lines; /// however, a maximum height of 0 implies no line height limit. /// Although this limit applies to the line itself, line spacing adds extra space between adjacent lines. /// /// The default value is 0. public var maximumLineHeight: CGFloat { set { self.paragraph.maximumLineHeight = newValue } get { return self.paragraph.maximumLineHeight } } /// The initial writing direction used to determine the actual writing direction for text. /// The default value of this property is `natural`. /// /// The Text system uses this value as a hint for calculating the actual direction for displaying Unicode characters. /// If you know the base writing direction of the text you are rendering, you can set the value of this property /// to the correct direction to help the text system. public var baseWritingDirection: NSWritingDirection { set { self.paragraph.baseWritingDirection = newValue } get { return self.paragraph.baseWritingDirection } } /// The natural line height of the receiver is multiplied by this factor (if positive) /// before being constrained by minimum and maximum line height. /// /// The default value of this property is 0. public var lineHeightMultiple: CGFloat { set { self.paragraph.lineHeightMultiple = newValue } get { return self.paragraph.lineHeightMultiple } } /// The threshold controlling when hyphenation is attempted. public var hyphenationFactor: Float { set { self.paragraph.hyphenationFactor = newValue } get { return self.paragraph.hyphenationFactor } } /// Ligatures cause specific character combinations to be rendered using a single custom glyph that corresponds /// to those characters. /// /// The default value for this attribute is `defaults`. (Value `all` is unsupported on iOS.) public var ligatures: Ligatures? { set { self.set(attribute: NSNumber.from(int: newValue?.rawValue), forKey: .ligature) } get { guard let value: NSNumber = self.get(attributeForKey: .ligature) else { return nil } return Ligatures(rawValue: value.intValue) } } #if os(iOS) || os(tvOS) || os(macOS) /// The value of this attribute is an `NSShadow` object. The default value of this property is nil. public var shadow: NSShadow? { set { self.set(attribute: newValue, forKey: .shadow) } get { return self.get(attributeForKey: .shadow) } } #endif #if os(iOS) || os(tvOS) || os(watchOS) /// Enable spoken of all punctuation in the text. public var speaksPunctuation: Bool? { set { self.set(attribute: newValue, forKey: NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilitySpeechPunctuation))) } get { return self.get(attributeForKey: NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilitySpeechPunctuation))) } } /// The language to use when speaking a string (value is a BCP 47 language code string). public var speakingLanguage: String? { set { self.set(attribute: newValue, forKey: NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilitySpeechLanguage))) } get { return self.get(attributeForKey: NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilitySpeechLanguage))) } } /// Pitch to apply to spoken content. Value must be in range range 0.0 to 2.0. /// The value indicates whether the text should be specified spoken with a higher or lower pitch /// than is used for the default. /// Values between 0.0 and 1.0 result in a lower pitch and values between 1.0 and 2.0 result in a higher pitch. /// /// The default value for this attribute is 1.0, which indicates a normal pitch. public var speakingPitch: Double? { set { self.set(attribute: newValue, forKey: NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilitySpeechPitch))) } get { return self.get(attributeForKey: NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilitySpeechPitch))) } } /// No overview available. /// Note: available only from iOS 11, tvOS 11 and watchOS 4. @available(iOS 11.0, tvOS 11.0, iOSApplicationExtension 11.0, watchOS 4, *) public var speakingPronunciation: String? { set { self.set(attribute: newValue, forKey: NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilitySpeechIPANotation))) } get { return self.get(attributeForKey: NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilitySpeechIPANotation))) } } /// Spoken text is queued behind, or interrupts, existing spoken content. /// When the value is true, this announcement is queued behind existing speech. /// When the value is false, the announcement interrupts the existing speech. /// /// The default behavior is to interrupt existing speech. @available(iOS 11.0, tvOS 11.0, iOSApplicationExtension 11.0, watchOS 4, *) public var shouldQueueSpeechAnnouncement: Bool? { set { let key = NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilitySpeechQueueAnnouncement)) guard let v = newValue else { self.innerAttributes.removeValue(forKey: key) return } self.set(attribute: NSNumber.init(value: v), forKey: key) } get { let key = NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilitySpeechQueueAnnouncement)) if let n: NSNumber = self.get(attributeForKey: key) { return n.boolValue } else { return false } } } /// Specify the heading level of the text. /// Value is a number in the range 0 to 6. /// Use 0 to indicate the absence of a specific heading level and use other numbers to indicate the heading level. @available(iOS 11.0, tvOS 11.0, iOSApplicationExtension 11.0, watchOS 4, *) public var headingLevel: HeadingLevel? { set { let key = NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilityTextHeadingLevel)) guard let v = newValue else { self.innerAttributes.removeValue(forKey: key) return } self.set(attribute: v.rawValue, forKey: key) } get { let key = NSAttributedString.Key(convertFromNSAttributedStringKey(NSAttributedString.Key.accessibilityTextHeadingLevel)) if let n: Int = self.get(attributeForKey: key) { return HeadingLevel(rawValue: n) } else { return nil } } } #endif /// The value of this attribute is an NSURL object (preferred) or an NSString object. /// The default value of this property is nil, indicating no link. public var linkURL: URLRepresentable? { set { self.set(attribute: newValue, forKey: .link) } get { return self.get(attributeForKey: .link) } } #if os(OSX) || os(iOS) || os(tvOS) /// Configuration for the number case, also known as "figure style". /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var numberCase: NumberCase? { set { self.fontData?.numberCase = newValue } get { return self.fontData?.numberCase } } /// Configuration for number spacing, also known as "figure spacing". /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var numberSpacing: NumberSpacing? { set { self.fontData?.numberSpacing = newValue } get { return self.fontData?.numberSpacing } } /// Configuration for displyaing a fraction. /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var fractions: Fractions? { set { self.fontData?.fractions = newValue } get { return self.fontData?.fractions } } /// Superscript (superior) glpyh variants are used, as in footnotes¹. /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var superscript: Bool? { set { self.fontData?.superscript = newValue } get { return self.fontData?.superscript } } /// Subscript (inferior) glyph variants are used: vₑ. /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var `subscript`: Bool? { set { self.fontData?.subscript = newValue } get { return self.fontData?.subscript } } /// Ordinal glyph variants are used, as in the common typesetting of 4th. /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var ordinals: Bool? { set { self.fontData?.ordinals = newValue } get { return self.fontData?.ordinals } } /// Scientific inferior glyph variants are used: H₂O /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var scientificInferiors: Bool? { set { self.fontData?.scientificInferiors = newValue } get { return self.fontData?.scientificInferiors } } /// Configure small caps behavior. /// `fromUppercase` and `fromLowercase` can be combined: they are not mutually exclusive. /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var smallCaps: Set<SmallCaps> { set { self.fontData?.smallCaps = newValue } get { return self.fontData?.smallCaps ?? Set() } } /// Different stylistic alternates available for customizing a font. /// /// Typically, a font will support a small subset of these alternates, and /// what they mean in a particular font is up to the font's creator. /// /// For example, in Apple's San Francisco font, turn on alternate set "six" to /// enable high-legibility alternates for ambiguous characters like: 0lI164. /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var stylisticAlternates: StylisticAlternates { set { self.fontData?.stylisticAlternates = newValue } get { return self.fontData?.stylisticAlternates ?? StylisticAlternates() } } /// Different contextual alternates available for customizing a font. /// Note: Not all fonts support all (or any) of these options. /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var contextualAlternates: ContextualAlternates { set { self.fontData?.contextualAlternates = newValue } get { return self.fontData?.contextualAlternates ?? ContextualAlternates() } } /// Tracking to apply. /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var kerning: Kerning? { set { self.fontData?.kerning = newValue } get { return self.fontData?.kerning } } /// Describe trait variants to apply to the font. /// **Note**: in order to be used you must also set the `.font`/`.size` attribute of the style. public var traitVariants: TraitVariant? { set { self.fontData?.traitVariants = newValue } get { return self.fontData?.traitVariants } } #endif //MARK: - INIT /// Initialize a new style with optional configuration handler callback. /// /// - Parameter handler: configuration handler callback. public init(_ handler: StyleInitHandler? = nil) { self.fontData?.style = self /*#if os(tvOS) self.set(attribute: Font.systemFont(ofSize: TVOS_SYSTEMFONT_SIZE), forKey: .font) #elseif os(watchOS) self.set(attribute: Font.systemFont(ofSize: WATCHOS_SYSTEMFONT_SIZE), forKey: .font) #else self.set(attribute: Font.systemFont(ofSize: Font.systemFontSize), forKey: .font) #endif*/ handler?(self) } /// Initialize a new style from a predefined set of attributes. /// Font related attributes are not set automatically but are encapsulasted to the font object itself. /// /// - Parameter dictionary: dictionary to set /// - Parameters: /// - dictionary: dictionary to set. /// - textTransforms: tranforms to apply. public init(dictionary: [NSAttributedString.Key: Any]?, textTransforms: [TextTransform]? = nil) { self.fontData?.style = self if let font = dictionary?[.font] as? Font { self.fontData?.font = font self.fontData?.size = font.pointSize } self.innerAttributes = (dictionary ?? [:]) self.textTransforms = textTransforms } /// Initialize a new Style by cloning an existing style. /// /// - Parameter style: style to clone public init(style: Style) { self.fontData?.style = self self.innerAttributes = style.innerAttributes self.fontData = style.fontData } //MARK: - INTERNAL METHODS /// Invalidate cache internal func invalidateCache() { self.cachedAttributes = nil } //MARK: - PUBLIC METHODS /// Set a raw `NSAttributedStringKey`'s attribute value. /// /// - Parameters: /// - value: valid value to set, `nil` to remove exiting value for given key. /// - key: key to set public func set<T>(attribute value: T?, forKey key: NSAttributedString.Key) { guard let value = value else { self.innerAttributes.removeValue(forKey: key) return } self.innerAttributes[key] = value self.invalidateCache() } /// Get the raw value for given `NSAttributedStringKey` key. /// /// - Parameter key: key to read. /// - Returns: value or `nil` if value is not set. public func get<T>(attributeForKey key: NSAttributedString.Key) -> T? { return (self.innerAttributes[key] as? T) } /// Return attributes defined by the style. /// Not all attributes are returned, fonts attributes may be omitted. /// Refer to `attributes` to get the complete list. public var attributes: [NSAttributedString.Key : Any] { if let cachedAttributes = self.cachedAttributes { return cachedAttributes } // generate font from `fontInfo` attributes collection, then merge it with the inner attributes of the // string to generate a single attributes dictionary for `NSAttributedString`. let fontAttributes = self.fontData?.attributes ?? [:] self.cachedAttributes = self.innerAttributes.merging(fontAttributes) { (_, new) in return new } // if let font = self.fontData?.font { // self.cachedAttributes?[.font] = font // } return self.cachedAttributes! } /// Create a new style copy of `self` with the opportunity to configure it via configuration callback. /// /// - Parameter handler: configuration handler. /// - Returns: configured style. public func byAdding(_ handler: StyleInitHandler) -> Style { let styleCopy = Style(style: self) handler(styleCopy) return styleCopy } }
mit
befaf843482d95d40d2b1244affccd04
39.73791
160
0.724237
3.924996
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Seller/views/SLVUserFollowingProductsView.swift
1
4098
// // SLVUserFollowingProductsView.swift // selluv-ios // // Created by 조백근 on 2017. 2. 13.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import UIKit import TagListView class SLVUserFollowingProductsView: UICollectionViewCell { @IBOutlet weak var photosView: UICollectionView! //"SLVPhotoSelectionCell" var type: ProductPhotoType = .sellerItem var items: [FollowerProductSimpleInfo]? var photos: [[String]] = [] var viewerBlock: ((_ path: IndexPath, _ photo: UIImage, _ productId: String) -> ())? override public func awakeFromNib() { super.awakeFromNib() self.setupCollectionView() } func setupData(type: ProductPhotoType, items: [FollowerProductSimpleInfo] ) { self.type = type self.items = items for (_, v) in (self.items?.enumerated())! { let item = v as FollowerProductSimpleInfo if let photos = item.photos { if photos.count > 0 { let photo = photos.first! as String let productId = (item.id ?? "").copy() let value = [photo , productId] self.photos.append(value as! [String]) } } } // log.debug("[PhotoCell] type : \(self.type) --> \(self.photos!)") self.photosView.reloadData() } func setupCollectionView() { self.photosView.register(UINib(nibName: "SLVProductPhoteHorizontalCell", bundle: nil), forCellWithReuseIdentifier: "SLVProductPhoteHorizontalCell") self.photosView.delegate = self self.photosView.dataSource = self } func setupViewer(block: @escaping ((_ path: IndexPath, _ photo: UIImage, _ productId: String) -> ()) ) { self.viewerBlock = block } func move(path: IndexPath, image: UIImage, productId: String) { if self.viewerBlock != nil { self.viewerBlock!(path, image, productId) } } 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 } } extension SLVUserFollowingProductsView: UICollectionViewDataSource, UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let index = indexPath.row let cell = collectionView.cellForItem(at: indexPath) as? SLVProductPhoteHorizontalCell if let cell = cell { let image = cell.thumnail.image let info = self.photos[index] let productId = info.last self.move(path: indexPath, image: image!, productId: productId! ) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // log.debug("PhotoType : \(self.type) - count : \( self.photos!.count)") return self.photos.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SLVProductPhoteHorizontalCell", for: indexPath) as! SLVProductPhoteHorizontalCell cell.isViewer = true if self.photos.count >= indexPath.row + 1 { let info = self.photos[indexPath.row] as! [String] let name = info.first! if name != "" { let domain = self.imageDomain() let from = URL(string: "\(domain)\(name)") let dnModel = SLVDnImageModel.shared DispatchQueue.global(qos: .default).async { dnModel.setupImageView(view: (cell.thumnail)!, from: from!) } } } return cell } }
mit
af6b6b621ff9aeea30f40d1a92bb8dac
33.652542
157
0.589631
4.879475
false
false
false
false
Vostro162/VaporTelegram
Sources/App/main.swift
1
5748
import Vapor import Foundation import HTTP let drop = Droplet() do { let button = KeyboardButton(text: "geilomat", requestContact: false) let keyboard = ReplyKeyboardMarkup(keyboardButtons: [[button]]) /*let button = InlineKeyboardButton(text: "test", url: URL(string: "https://google.de")!) let keyboard = InlineKeyboardMarkup(inlineKeyboardButtons: [[button]])*/ let telegramService = TelegramService(drop: drop) let message = try? telegramService.sendMessage( chatId: -214763808, text: "telegram is cool", disableWebPagePreview: true, disableNotification: true, replyToMessageId: 221, replyMarkup: keyboard ) //let message = try telegramService.forwardMessage(chatId: -214763808, fromChatId: -214763808, messageId: 238) /*let message = try telegramService.sendLocation(chatId: -214763808, latitude: 50.2351011, longitude: 11.3293869, replyMarkup: keyboard)*/ /*let message = try telegramService.sendVenue(chatId: -214763808 , latitude: 50.2351011, longitude: 11.3293869, title: "Marius Party", address: "Josef Ritz Weg 23", replyMarkup: keyboard)*/ /*let message = try telegramService.sendContact(chatId: -214763808, phoneNumber: "+4637388", firstName: "M", lastName: "H")*/ /*let message = try telegramService.sendChatAction(chatId: -214763808, action: .typing) dump(message)*/ /*let me = try telegramService.getMe() dump(me)*/ /*let photos = try telegramService.getUserProfilePhotos(userId: 25908543, offset: 1, limit: 2) dump(photos)*/ /*let chat = try telegramService.getChat(chatId: 25908543) dump(chat)*/ /*let members = try telegramService.getChatAdministrators(chatId: -214763808) dump(members)*/ /*let count = try telegramService.getChatMembersCount(chatId: -214763808) dump(count)*/ /*let member = try telegramService.getChatMember(chatId: -214763808, userId: 25908543) dump(member)*/ /*let message = try telegramService.editMessageText(chatId: -214763808 , messageId: 238, text: "#editMessageText") dump(message)*/ /*let message = try telegramService.editMessageCaption(chatId: -214763808, messageId: 283, caption: "caption") dump(message)*/ if let bundle = Bundle.publicResources, let filePath = bundle.path(forResource: "vapor-logo", ofType: "png", inDirectory: "images") { /*let fileURL = URL(fileURLWithPath: filePath) let fileData = try Data(contentsOf: fileURL) let fileName = fileURL.lastPathComponent */ /*let photoURL = URL(string: "http://www.airpower.at/news03/0909_ciaf/IMG_9848.jpg")! let message = try telegramService.sendPhoto(chatId: -214763808, photo: photoURL, replyMarkup: keyboard) dump(message)*/ /*let file = try telegramService.getFile(fileId: "AgADBAAD1Hw3G6MZZAfZp5r58HCvZfFimxkABHs_-DpgHTryDUIEAAEC") dump(file)*/ //dump(try telegramService.url(filePath: "photos/532578844263546068.jpg")) } if let bundle = Bundle.publicResources, let filePath = bundle.path(forResource: "test", ofType: "mp3", inDirectory: "audio") { /*let fileURL = URL(fileURLWithPath: filePath) let fileData = try Data(contentsOf: fileURL) let fileName = fileURL.lastPathComponent*/ /* let fileURL = URL(string: "http://imegumii.space/music/English/Monstercat/Obsidia%20-%20To%20The%20Limit.mp3")! let message = try telegramService.sendAudio(chatId: -214763808, audio: fileURL, replyMarkup: keyboard) dump(message)*/ /*let file = try telegramService.getFile(fileId: "CQADBAADeQADh0PwUIGGLRU-YfRCAg") dump(file)*/ } if let bundle = Bundle.publicResources, let filePath = bundle.path(forResource: "test", ofType: "txt", inDirectory: "documents") { /*let fileURL = URL(fileURLWithPath: filePath) let fileData = try Data(contentsOf: fileURL) let fileName = fileURL.lastPathComponent*/ /*let fileURL = URL(string: "http://floatingworldweb.com/MUSIC/CLASSICAL/@byCOMPOSER/SCHUBERT/SCHUBERT%20LIEDER/SCHUBERT-DIE%20WINTERREISE/Schubert%20-Winterreise%20-%20Hotter%20-%20Moore/scans/scans.PDF")! let message = try telegramService.sendDocument(chatId: -214763808, document: fileURL, replyMarkup: keyboard) dump(message)*/ } if let bundle = Bundle.publicResources, let filePath = bundle.path(forResource: "test", ofType: "webp", inDirectory: "images") { let fileURL = URL(fileURLWithPath: filePath) let fileData = try Data(contentsOf: fileURL) let fileName = fileURL.lastPathComponent //let photoURL = URL(string: "http://www.airpower.at/news03/0909_ciaf/IMG_9848.jpg")! /*let message = try telegramService.sendSticker(chatId: -214763808, sticker: fileData, fileName: fileName, replyMarkup: keyboard) dump(message)*/ /*let file = try telegramService.getFile(fileId: "AgADBAAD1Hw3G6MZZAfZp5r58HCvZfFimxkABHs_-DpgHTryDUIEAAEC") dump(file)*/ //dump(try telegramService.url(filePath: "photos/532578844263546068.jpg")) } } catch TelegramServiceError.server(let code, let description) { print(description) } catch { print("error") } //print(test.elementsInArraysToNode()) /*drop.get { req in return try drop.view.make("welcome", [ "message": drop.localization[req.lang, "welcome", "title"] ]) } drop.resource("posts", PostController()) drop.run()*/
mit
ebc14fe956ec66e27ac9f612a2a47999
37.577181
215
0.660578
3.912866
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/RealmSwift/RealmSwift/RealmConfiguration.swift
28
12601
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private extension Realm { /** A `Configuration` instance describes the different options used to create an instance of a Realm. `Configuration` instances are just plain Swift structs. Unlike `Realm`s and `Object`s, they can be freely shared between threads as long as you do not mutate them. Creating configuration values for class subsets (by setting the `objectClasses` property) can be expensive. Because of this, you will normally want to cache and reuse a single configuration value for each distinct configuration rather than creating a new value each time you open a Realm. */ public struct Configuration { // MARK: Default Configuration /** The default `Configuration` used to create Realms when no configuration is explicitly specified (i.e. `Realm()`) */ public static var defaultConfiguration: Configuration { get { return fromRLMRealmConfiguration(RLMRealmConfiguration.default()) } set { RLMRealmConfiguration.setDefault(newValue.rlmConfiguration) } } // MARK: Initialization /** Creates a `Configuration` which can be used to create new `Realm` instances. - note: The `fileURL`, `inMemoryIdentifier`, and `syncConfiguration` parameters are mutually exclusive. Only set one of them, or none if you wish to use the default file URL. - parameter fileURL: The local URL to the Realm file. - parameter inMemoryIdentifier: A string used to identify a particular in-memory Realm. - parameter syncConfiguration: For Realms intended to sync with the Realm Object Server, a sync configuration. - parameter encryptionKey: An optional 64-byte key to use to encrypt the data. - parameter readOnly: Whether the Realm is read-only (must be true for read-only files). - parameter schemaVersion: The current schema version. - parameter migrationBlock: The block which migrates the Realm to the current version. - parameter deleteRealmIfMigrationNeeded: If `true`, recreate the Realm file with the provided schema if a migration is required. - parameter shouldCompactOnLaunch: A block called when opening a Realm for the first time during the life of a process to determine if it should be compacted before being returned to the user. It is passed the total file size (data + free space) and the total bytes used by data in the file. Return `true ` to indicate that an attempt to compact the file should be made. The compaction will be skipped if another process is accessing it. - parameter objectTypes: The subset of `Object` subclasses persisted in the Realm. */ public init(fileURL: URL? = URL(fileURLWithPath: RLMRealmPathForFile("default.realm"), isDirectory: false), inMemoryIdentifier: String? = nil, syncConfiguration: SyncConfiguration? = nil, encryptionKey: Data? = nil, readOnly: Bool = false, schemaVersion: UInt64 = 0, migrationBlock: MigrationBlock? = nil, deleteRealmIfMigrationNeeded: Bool = false, shouldCompactOnLaunch: ((Int, Int) -> Bool)? = nil, objectTypes: [Object.Type]? = nil) { self.fileURL = fileURL if let inMemoryIdentifier = inMemoryIdentifier { self.inMemoryIdentifier = inMemoryIdentifier } if let syncConfiguration = syncConfiguration { self.syncConfiguration = syncConfiguration } self.encryptionKey = encryptionKey self.readOnly = readOnly self.schemaVersion = schemaVersion self.migrationBlock = migrationBlock self.deleteRealmIfMigrationNeeded = deleteRealmIfMigrationNeeded self.shouldCompactOnLaunch = shouldCompactOnLaunch self.objectTypes = objectTypes } // MARK: Configuration Properties /** A configuration value used to configure a Realm for synchronization with the Realm Object Server. Mutually exclusive with `inMemoryIdentifier` and `fileURL`. */ public var syncConfiguration: SyncConfiguration? { set { _path = nil _inMemoryIdentifier = nil _syncConfiguration = newValue } get { return _syncConfiguration } } private var _syncConfiguration: SyncConfiguration? /// The local URL of the Realm file. Mutually exclusive with `inMemoryIdentifier` and `syncConfiguration`. public var fileURL: URL? { set { _inMemoryIdentifier = nil _syncConfiguration = nil _path = newValue?.path } get { return _path.map { URL(fileURLWithPath: $0) } } } private var _path: String? /// A string used to identify a particular in-memory Realm. Mutually exclusive with `fileURL` and /// `syncConfiguration`. public var inMemoryIdentifier: String? { set { _path = nil _syncConfiguration = nil _inMemoryIdentifier = newValue } get { return _inMemoryIdentifier } } private var _inMemoryIdentifier: String? /// A 64-byte key to use to encrypt the data, or `nil` if encryption is not enabled. public var encryptionKey: Data? /** Whether to open the Realm in read-only mode. This is required to be able to open Realm files which are not writeable or are in a directory which is not writeable. This should only be used on files which will not be modified by anyone while they are open, and not just to get a read-only view of a file which may be written to by another thread or process. Opening in read-only mode requires disabling Realm's reader/writer coordination, so committing a write transaction from another process will result in crashes. */ public var readOnly: Bool = false /// The current schema version. public var schemaVersion: UInt64 = 0 /// The block which migrates the Realm to the current version. public var migrationBlock: MigrationBlock? /** Whether to recreate the Realm file with the provided schema if a migration is required. This is the case when the stored schema differs from the provided schema or the stored schema version differs from the version on this configuration. Setting this property to `true` deletes the file if a migration would otherwise be required or executed. - note: Setting this property to `true` doesn't disable file format migrations. */ public var deleteRealmIfMigrationNeeded: Bool = false /** A block called when opening a Realm for the first time during the life of a process to determine if it should be compacted before being returned to the user. It is passed the total file size (data + free space) and the total bytes used by data in the file. Return `true ` to indicate that an attempt to compact the file should be made. The compaction will be skipped if another process is accessing it. */ public var shouldCompactOnLaunch: ((Int, Int) -> Bool)? /// The classes managed by the Realm. public var objectTypes: [Object.Type]? { set { self.customSchema = newValue.map { RLMSchema(objectClasses: $0) } } get { return self.customSchema.map { $0.objectSchema.map { $0.objectClass as! Object.Type } } } } /// A custom schema to use for the Realm. private var customSchema: RLMSchema? /// If `true`, disables automatic format upgrades when accessing the Realm. internal var disableFormatUpgrade: Bool = false // MARK: Private Methods internal var rlmConfiguration: RLMRealmConfiguration { let configuration = RLMRealmConfiguration() if let fileURL = fileURL { configuration.fileURL = fileURL } else if let inMemoryIdentifier = inMemoryIdentifier { configuration.inMemoryIdentifier = inMemoryIdentifier } else if let syncConfiguration = syncConfiguration { configuration.syncConfiguration = syncConfiguration.asConfig() } else { fatalError("A Realm Configuration must specify a path or an in-memory identifier.") } configuration.encryptionKey = self.encryptionKey configuration.readOnly = self.readOnly configuration.schemaVersion = self.schemaVersion configuration.migrationBlock = self.migrationBlock.map { accessorMigrationBlock($0) } configuration.deleteRealmIfMigrationNeeded = self.deleteRealmIfMigrationNeeded configuration.shouldCompactOnLaunch = self.shouldCompactOnLaunch.map(ObjectiveCSupport.convert) configuration.customSchema = self.customSchema configuration.disableFormatUpgrade = self.disableFormatUpgrade return configuration } internal static func fromRLMRealmConfiguration(_ rlmConfiguration: RLMRealmConfiguration) -> Configuration { var configuration = Configuration() configuration._path = rlmConfiguration.fileURL?.path configuration._inMemoryIdentifier = rlmConfiguration.inMemoryIdentifier if let objcSyncConfig = rlmConfiguration.syncConfiguration { configuration._syncConfiguration = SyncConfiguration(config: objcSyncConfig) } else { configuration._syncConfiguration = nil } configuration.encryptionKey = rlmConfiguration.encryptionKey configuration.readOnly = rlmConfiguration.readOnly configuration.schemaVersion = rlmConfiguration.schemaVersion configuration.migrationBlock = rlmConfiguration.migrationBlock.map { rlmMigration in return { migration, schemaVersion in rlmMigration(migration.rlmMigration, schemaVersion) } } configuration.deleteRealmIfMigrationNeeded = rlmConfiguration.deleteRealmIfMigrationNeeded configuration.shouldCompactOnLaunch = rlmConfiguration.shouldCompactOnLaunch.map(ObjectiveCSupport.convert) configuration.customSchema = rlmConfiguration.customSchema configuration.disableFormatUpgrade = rlmConfiguration.disableFormatUpgrade return configuration } } } // MARK: CustomStringConvertible extension Realm.Configuration: CustomStringConvertible { /// A human-readable description of the configuration value. public var description: String { return gsub(pattern: "\\ARLMRealmConfiguration", template: "Realm.Configuration", string: rlmConfiguration.description) ?? "" } }
mit
6242744274c7540766e5bdbadf9b03b9
46.194757
122
0.623522
5.839203
false
true
false
false
ello/ello-ios
Sources/Controllers/ArtistInvites/Cells/ArtistInviteGuideCell.swift
1
2317
//// /// ArtistInviteGuideCell.swift // import SnapKit class ArtistInviteGuideCell: CollectionViewCell { static let reuseIdentifier = "ArtistInviteGuideCell" struct Size { static let otherHeights: CGFloat = 56 static let margins = UIEdgeInsets(sides: 15) static let guideSpacing: CGFloat = 20 } typealias Config = ArtistInvite.Guide var config: Config? { didSet { updateConfig() } } private let titleLabel = StyledLabel(style: .artistInviteGuide) private let guideWebView = ElloWebView() override func bindActions() { guideWebView.delegate = self } override func arrange() { contentView.addSubview(titleLabel) contentView.addSubview(guideWebView) titleLabel.snp.makeConstraints { make in make.top.leading.trailing.equalTo(contentView).inset(Size.margins) } guideWebView.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(Size.guideSpacing) make.leading.trailing.equalTo(titleLabel) make.bottom.equalTo(contentView) } } override func prepareForReuse() { super.prepareForReuse() config = nil } func updateConfig() { titleLabel.text = config?.title let htmlString: String if let html = config?.html { htmlString = StreamTextCellHTML.artistInviteGuideHTML(html) } else { htmlString = "" } guideWebView.loadHTMLString(htmlString, baseURL: URL(string: "/")) } } extension StyledLabel.Style { static let artistInviteGuide = StyledLabel.Style( textColor: .greyA, fontFamily: .artistInviteTitle ) } extension ArtistInviteGuideCell: UIWebViewDelegate { func webView( _ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType ) -> Bool { if let scheme = request.url?.scheme, scheme == "default" { let responder: StreamCellResponder? = findResponder() responder?.streamCellTapped(cell: self) return false } else { return ElloWebViewHelper.handle(request: request, origin: self) } } }
mit
0d728ba7f4a110218fb5346d6acb9c72
25.329545
78
0.62883
4.908898
false
true
false
false
imex94/KCLTech-iOS-2015
Hackalendar/Hackalendar/Hackalendar/HCHackathonTableViewCell.swift
1
2063
// // HTLHackathonTableViewCell.swift // HackTheList // // Created by Alex Telek on 03/11/2015. // Copyright © 2015 Alex Telek. All rights reserved. // import UIKit import MapKit protocol HCHackathonTableViewDelegate { func performSegueOnMapClick(index: Int) } class HCHackathonTableViewCell: UITableViewCell { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var hackathonName: UILabel! @IBOutlet weak var hackathonDate: UILabel! @IBOutlet weak var HackathonPlace: UILabel! @IBOutlet var labelsView: UIView! var delegate: HCHackathonTableViewDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code mapView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("performTransition:"))) // Creating a blur effect with dark style let blurEffect = UIBlurEffect(style: .Dark) // Creating a view for the blur effect with the same size of labels view let blurView = UIVisualEffectView(frame: labelsView.frame) // Add effect for the blur view blurView.effect = blurEffect // Insert the blur layer below our existing labels self.contentView.insertSubview(blurView, belowSubview: labelsView) } func performTransition(gesture: UITapGestureRecognizer) { delegate?.performSegueOnMapClick(tag) } /** Modified the function signature to take a latitude and a longitude, instead of a CLLocationCoordinate2D object, because our HackathonItem has those two attributes. They can be also nil, if that's the case we won't animate the map to that location. */ func addLocation(latitude: Double?, longitude: Double?) { if let l1 = latitude, l2 = longitude { let region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: l1, longitude: l2), 5000, 5000) mapView.setRegion(region, animated: true) } } }
mit
69db7d965f137f153b516c0f7525e6ac
32.258065
124
0.676528
4.980676
false
false
false
false
scotlandyard/expocity
expocity/View/Chat/Input/VChatInput.swift
1
7172
import UIKit class VChatInput:UIView, UITextViewDelegate { weak var controller:CChat! weak var menu:VChatInputMenu! weak var field:UITextView! weak var layoutHeight:NSLayoutConstraint! weak var layoutBaseRight:NSLayoutConstraint! let kMinHeight:CGFloat = 40 private let kFieldMarginVr:CGFloat = 4 private let kBorderHeight:CGFloat = 1 private let kMaxHeight:CGFloat = 75 private let kCornerRadius:CGFloat = 4 private let kAnimationDuration:TimeInterval = 0.3 private let kHypoteticalMaxHeight:CGFloat = 10000 private let kEmpty:String = "" convenience init(controller:CChat) { self.init() clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor.collectionBackground() self.controller = controller let menu:VChatInputMenu = VChatInputMenu(controller:controller) self.menu = menu let borderTop:UIView = UIView() borderTop.isUserInteractionEnabled = false borderTop.translatesAutoresizingMaskIntoConstraints = false borderTop.backgroundColor = UIColor.bubbleMine() let fieldBase:UIView = UIView() fieldBase.clipsToBounds = true fieldBase.backgroundColor = UIColor.white fieldBase.translatesAutoresizingMaskIntoConstraints = false fieldBase.layer.borderWidth = 1 fieldBase.layer.borderColor = UIColor.bubbleMine().cgColor fieldBase.layer.cornerRadius = kCornerRadius let field:UITextView = UITextView() field.translatesAutoresizingMaskIntoConstraints = false field.clipsToBounds = true field.backgroundColor = UIColor.clear field.font = UIFont.medium(size:15) field.textColor = UIColor.black field.tintColor = UIColor.black field.returnKeyType = UIReturnKeyType.default field.keyboardAppearance = UIKeyboardAppearance.light field.autocorrectionType = UITextAutocorrectionType.no field.spellCheckingType = UITextSpellCheckingType.no field.autocapitalizationType = UITextAutocapitalizationType.sentences field.textContainerInset = UIEdgeInsetsMake(6, 0, 0, 0) field.delegate = self self.field = field fieldBase.addSubview(field) addSubview(borderTop) addSubview(menu) addSubview(fieldBase) let views:[String:UIView] = [ "field":field, "fieldBase":fieldBase, "borderTop":borderTop, "menu":menu] let metrics:[String:CGFloat] = [ "fieldMarginVr":kFieldMarginVr, "borderHeight":kBorderHeight, "minHeight":kMinHeight] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-10-[fieldBase]", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[borderTop(borderHeight)]-(fieldMarginVr)-[fieldBase]-(fieldMarginVr)-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-6-[field]-3-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[borderTop]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[menu]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[field]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[menu(minHeight)]", options:[], metrics:metrics, views:views)) let rightMargin:CGFloat = -menu.rightMargin() layoutBaseRight = NSLayoutConstraint( item:fieldBase, attribute:NSLayoutAttribute.right, relatedBy:NSLayoutRelation.equal, toItem:self, attribute:NSLayoutAttribute.right, multiplier:1, constant:rightMargin) addConstraint(layoutBaseRight) } //MARK: private private func sendMessage() { let text:String = field.text if !text.isEmpty { var textValidating:String = text.replacingOccurrences(of:" ", with:"") textValidating = textValidating.replacingOccurrences(of:"\n", with:"") if !textValidating.isEmpty { controller.addTextMine(text:text) } DispatchQueue.main.async { [weak self] in self?.field.text = self?.kEmpty self?.heightForText() } } } private func heightForText() { let newHeight:CGFloat let height:CGFloat = field.contentSize.height + kFieldMarginVr + kBorderHeight if height > kMaxHeight { newHeight = kMaxHeight } else if height < kMinHeight { newHeight = kMinHeight } else { newHeight = height } layoutHeight.constant = newHeight } private func updateRightMargin() { let rightMargin:CGFloat = -menu.rightMargin() layoutBaseRight.constant = rightMargin UIView.animate(withDuration: kAnimationDuration) { [weak self] in self?.layoutIfNeeded() } } private func updateTypingMenu() { if field.text.isEmpty { menu.modeTypeReady() } else { menu.modeTyping() } updateRightMargin() } //MARK: public func actionSend() { UIApplication.shared.keyWindow!.endEditing(true) DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.sendMessage() } } func updateStandbyMenu() { if controller.viewChat.display.imageView.image == nil { menu.modeStandby() } else { menu.modeStandbyImage() } updateRightMargin() } //MARK: textview del func textViewDidBeginEditing(_ textView:UITextView) { heightForText() updateTypingMenu() } func textViewDidEndEditing(_ textView:UITextView) { heightForText() updateStandbyMenu() } func textViewDidChange(_ textView:UITextView) { heightForText() updateTypingMenu() } }
mit
e91f326c0a83a264767869073ee8c450
28.514403
109
0.580452
5.616288
false
false
false
false
moonknightskye/Luna
Luna/ViewController+ SalesforceServiceCoreDelegate.swift
1
2674
// // ViewController+UNUserNotificationCenterDelegate.swift // Luna // // Created by Mart Civil on 2017/06/09. // Copyright © 2017年 salesforce.com. All rights reserved. // import UIKit import ServiceCore import ServiceSOS extension ViewController: SOSDelegate { /** * Tells the delegate that an SOS session is stopping. * * This event is invoked when the session is entering its cleanup phase. * * @param sos `SOSSessionManager` instance that invoked the delegate method. * @param reason `SOSStopReason` enum for why the session ended. * @param error `NSError` instance returned if the session ended as the result of an error. * Compare the error code to `SOSErrorCode` for details about the error. * Error is `nil` if the session ended cleanly. * @see `SOSSessionManager` * @see `SOSStopReason` * @see `SOSErrorCode` */ func sos(_ sos: SOSSessionManager!, didStopWith reason: SOSStopReason, error: Error!) { var code = 0 var label = "" if (error != nil) { code = (error as NSError).code label = error.localizedDescription } else { code = reason.rawValue label = SFServiceSOS.instance.getErrorLabel(reason: reason) } let value = NSMutableDictionary() value.setValue( code, forKey: "code") value.setValue( label, forKey: "label") CommandProcessor.processSFServiceSOSdidStop( value: value ) } /** * Calls the delegate when the SOS session has connected. The session is now fully active. * * @param sos `SOSSessionManager` instance that invoked the delegate method. * @see `SOSSessionManager` */ func sosDidConnect(_ sos: SOSSessionManager!) { CommandProcessor.processSFServiceSOSdidConnect() } /** * Tells the delegate that the SOS state changed. * * @param sos `SOSSessionManager` instance that executed the delegate. * @param current The new `SOSSessionState` that has been set on the `SOSSessionManager` instance. * @param previous The previous `SOSSessionState`. * @see `SOSSessionManager` * @see `SOSSessionState` */ func sos(_ sos: SOSSessionManager!, stateDidChange current: SOSSessionState, previous: SOSSessionState) { let value = NSMutableDictionary() value.setValue( current.rawValue, forKey: "code") value.setValue( SFServiceSOS.instance.getState(state: current), forKey: "label") CommandProcessor.processSFServiceSOSstateChange(value: value) } }
gpl-3.0
0ba09cfda7afb55937a7d428c0ec70b6
36.097222
109
0.647697
4.18652
false
false
false
false
debugsquad/nubecero
nubecero/Controller/Photos/CPhotosAlbumPhotoSettings.swift
1
3233
import UIKit class CPhotosAlbumPhotoSettings:CController, CPhotosAlbumSelectionDelegate { let model:MPhotosAlbumPhotoSettings weak var photo:MPhotosItemPhoto? weak var photoController:CPhotosAlbumPhoto! private weak var viewSettings:VPhotosAlbumPhotoSettings! init( photoController:CPhotosAlbumPhoto, photo:MPhotosItemPhoto) { model = MPhotosAlbumPhotoSettings() super.init() self.photoController = photoController self.photo = photo } required init?(coder:NSCoder) { fatalError() } override func loadView() { let viewSettings:VPhotosAlbumPhotoSettings = VPhotosAlbumPhotoSettings( controller:self) self.viewSettings = viewSettings view = viewSettings } //MARK: private private func confirmedDelete() { guard let photo:MPhotosItemPhoto = photo else { back() return } parentController.pop { [weak photoController] in photoController?.deletePhoto(photo:photo) } } //MARK: public func back() { parentController.pop(completion:nil) } func deletePhoto() { let alert:UIAlertController = UIAlertController( title: NSLocalizedString("CPhotosAlbumPhotoSettings_deleteTitle", comment:""), message: NSLocalizedString("CPhotosAlbumPhotoSettings_deleteMessage", comment:""), preferredStyle:UIAlertControllerStyle.actionSheet) let actionCancel:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbumPhotoSettings_deleteCancel", comment:""), style: UIAlertActionStyle.cancel) let actionDelete:UIAlertAction = UIAlertAction( title: NSLocalizedString("CPhotosAlbumPhotoSettings_deleteDo", comment:""), style: UIAlertActionStyle.destructive) { [weak self] (action:UIAlertAction) in self?.confirmedDelete() } alert.addAction(actionDelete) alert.addAction(actionCancel) present(alert, animated:true, completion:nil) } func changeAlbum() { let album:MPhotosItem? = photoController.albumController.model let albumSelection:CPhotosAlbumSelection = CPhotosAlbumSelection( currentAlbum:album, delegate:self) parentController.over( controller:albumSelection, pop:false, animate:true) } //MARK: albumSelection delegate func albumSelected(album:MPhotosItem) { guard let photo:MPhotosItemPhoto = photo else { back() return } parentController.pop { [weak photoController] in photoController?.moveToAlbum( photo:photo, album:album) } } }
mit
71bf6a9b86deefb21d2992781bb7dfa9
24.062016
85
0.564491
5.804309
false
false
false
false
mihaicris/learn
20140901 BlurrySideBar/BlurrySidebar/SideBarTableViewController.swift
1
1630
// // SideBarTableViewController.swift // BlurrySidebar // // Created by mihai.cristescu on 26/05/2017. // Copyright © 2017 Mihai Cristescu. All rights reserved. // import UIKit @objc protocol SideBarTableViewControllerDelegate { func sideBar(_ sideBar: UITableViewController, didSelectRowAt indexPath: IndexPath) } class SideBarTableViewController: UITableViewController { weak var delegate: SideBarTableViewControllerDelegate? var tableData: [String] = [] // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.backgroundColor = .clear cell.textLabel?.textColor = UIColor.white cell.textLabel?.font = UIFont(name: "Avenir-Black", size: 16) let selectedView = UIView(frame: CGRect(x: 2, y: 2, width: cell.frame.size.width - 2, height: cell.frame.size.height - 2)) selectedView.backgroundColor = UIColor.black.withAlphaComponent(0.1) cell.backgroundView = selectedView cell.textLabel?.text = tableData[indexPath.row] return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 45 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.sideBar(self, didSelectRowAt: indexPath) } }
mit
1aba7c593ae0fc434a4a0e0edb4b59d9
29.166667
130
0.707182
4.777126
false
false
false
false
lukesutton/uut
Sources/Properties-Text.swift
1
2812
extension PropertyNames { public static let hangingPunctuation = "hanging-punctuation" public static let letterSpacing = "letter-spacing" public static let lineHeight = "line-height" public static let textAlign = "text-align" public static let textIndent = "text-indent" public static let textTransform = "text-transform" public static let whiteSpace = "white-space" public static let wordBreak = "word-break" public static let wordSpacing = "word-spacing" public static let wordWrap = "word-wrap" public static let textDecoration = "text-decoration" public static let textShadown = "text-shadow" } public func hangingPunctuation(value: PropertyValues.HangingPunctuation) -> Property { return Property(PropertyNames.hangingPunctuation, value) } public func letterSpacing(value: PropertyValues.LetterSpacing) -> Property { return Property(PropertyNames.letterSpacing, value) } public func letterSpacing(value: Measurement) -> Property { return Property(PropertyNames.letterSpacing, PropertyValues.LetterSpacing.Value(value)) } public func lineHeight(value: PropertyValues.LineHeight) -> Property { return Property(PropertyNames.lineHeight, value) } public func lineHeight(value: Measurement) -> Property { return Property(PropertyNames.lineHeight, PropertyValues.LineHeight.Value(value)) } public func lineHeight(value: Double) -> Property { return Property(PropertyNames.lineHeight, PropertyValues.LineHeight.Number(value)) } public func textAlign(value: PropertyValues.TextAlign) -> Property { return Property(PropertyNames.textAlign, value) } public func textIndent(value: PropertyValues.Number) -> Property { return Property(PropertyNames.textAlign, value) } public func textIndent(value: Int) -> Property { return Property(PropertyNames.textAlign, PropertyValues.Number.Value(value)) } public func textTransform(value: PropertyValues.TextTransform) -> Property { return Property(PropertyNames.textTransform, value) } public func whiteSpace(value: PropertyValues.WhiteSpace) -> Property { return Property(PropertyNames.whiteSpace, value) } public func wordSpacing(value: PropertyValues.MeasurementWithNormal) -> Property { return Property(PropertyNames.wordSpacing, value) } public func wordSpacing(value: Measurement) -> Property { return Property(PropertyNames.wordSpacing, PropertyValues.MeasurementWithNormal.Value(value)) } public func wordWrap(value: PropertyValues.WordWrap) -> Property { return Property(PropertyNames.wordWrap, value) } public func textDecoration(value: PropertyValues.TextDecoration) -> Property { return Property(PropertyNames.textDecoration, value) } public func textShadown(values: PropertyValues.Shadow...) -> Property { return Property(PropertyNames.textShadown, PropertyValues.ShadowCollection(values)) }
mit
1bcce740e5b682e8ac21a165288dd4a3
35.051282
95
0.791252
4.339506
false
false
false
false
mukeshthawani/Swift-Algo-DS
Binary Search/BinarySearch.playground/Contents.swift
1
707
//: Playground - noun: a place where people can play import Cocoa public func binarySearch(start: Int, end: Int, list: Array<Int>, elementToSearch: Int) -> Int { if end >= start { let midIndex = (start + end)/2 if list[midIndex] == elementToSearch { return midIndex } else if list[midIndex] > elementToSearch { return binarySearch(start: start, end: midIndex - 1, list: list, elementToSearch: elementToSearch) } else { return binarySearch(start: midIndex + 1, end: end, list: list, elementToSearch: elementToSearch) } } else { return -1 } } let list = [1,2,3,4,5,6,7,8,9] print(binarySearch(start: 0, end: list.count - 1, list: list, elementToSearch: 9))
mit
19f7904b9cca12e841cb9e0434862b1a
32.666667
104
0.663366
3.5
false
false
false
false
migueloruiz/la-gas-app-swift
lasgasmx/GasStationModel.swift
1
2646
// // GasStationModel.swift // lasgasmx // // Created by Desarrollo on 4/19/17. // Copyright © 2017 migueloruiz. All rights reserved. // import Foundation import CoreLocation struct GasStation { let name : String let address : String let location: CLLocationCoordinate2D let prices: [GasPrice] var route: GasStationRouteData? = nil init(json: [String: Any]) { guard let name = json["name"] as? String, let address = json["address"] as? String, let location = json["location"] as? [String: String], let pricesArray = json["prices"] as? [String: String] else { self.name = "" self.address = "" self.location = CLLocationCoordinate2D() self.prices = [] return } self.name = name self.address = address self.location = CLLocationCoordinate2D(latitude: CLLocationDegrees(location["lat"]!)!, longitude: CLLocationDegrees(location["long"]!)!) self.prices = GasPrice.buildArray(from: pricesArray) } static func getArray(json: [String: Any]) -> [GasStation]{ guard let stations = json["stations"] as? [[String:Any]] else { return [] as [GasStation] } return stations.map{GasStation(json: $0)} } mutating func set(route newRoute: GasStationRouteData?) { self.route = newRoute } func pricesAreValid() -> Bool { let sum = prices.reduce(0, { (result, item) in return item.price + result }) return sum > 1 } func getPriceOf(type: FuelType) -> GasPrice? { let filter = prices.filter({ item in return item.type == type }) guard let price = filter.first else { return nil } guard price.price > 0 else { return nil } return price } } struct GasStationRouteData { let time: String let distance: String let address: String init?(json: [String: Any]) { guard let routes = json["routes"] as? [[String: Any]] else { return nil } guard let data = routes.first?["legs"] as? [[String: Any]] else { return nil } guard let distanceData = data.first?["distance"] as? [String: Any], let durationData = data.first?["duration"] as? [String: Any], let address = data.first?["end_address"] as? String else { return nil } guard let d = distanceData["text"] as? String, let t = durationData["text"] as? String else { return nil } self.time = t self.distance = d self.address = address } }
mit
9e3184548d4d343da657b678b7ef493b
31.256098
144
0.581096
4.158805
false
false
false
false
littleHH/WarePush
WarePush/Charts-master/Source/ChartsRealm/Data/RealmCandleDataSet.swift
2
6927
// // RealmCandleDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if NEEDS_CHARTS import Charts #endif import Realm import RealmSwift import Realm.Dynamic open class RealmCandleDataSet: RealmLineScatterCandleRadarDataSet, ICandleChartDataSet { open override func initialize() { } public required init() { super.init() } public init(results: RLMResults<RLMObject>?, xValueField: String, highField: String, lowField: String, openField: String, closeField: String, label: String?) { _highField = highField _lowField = lowField _openField = openField _closeField = closeField super.init(results: results, xValueField: xValueField, yValueField: "", label: label) } public convenience init(results: Results<Object>?, xValueField: String, highField: String, lowField: String, openField: String, closeField: String, label: String?) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) } self.init(results: converted, xValueField: xValueField, highField: highField, lowField: lowField, openField: openField, closeField: closeField, label: label) } public convenience init(results: RLMResults<RLMObject>?, xValueField: String, highField: String, lowField: String, openField: String, closeField: String) { self.init(results: results, xValueField: xValueField, highField: highField, lowField: lowField, openField: openField, closeField: closeField, label: "DataSet") } public convenience init(results: Results<Object>?, xValueField: String, highField: String, lowField: String, openField: String, closeField: String) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) } self.init(results: converted, xValueField: xValueField, highField: highField, lowField: lowField, openField: openField, closeField: closeField) } public init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String, highField: String, lowField: String, openField: String, closeField: String, label: String?) { _highField = highField _lowField = lowField _openField = openField _closeField = closeField super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: "", label: label) } public convenience init(realm: Realm?, modelName: String, resultsWhere: String, xValueField: String, highField: String, lowField: String, openField: String, closeField: String, label: String?) { var converted: RLMRealm? if realm != nil { converted = ObjectiveCSupport.convert(object: realm!) } self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, highField: highField, lowField: lowField, openField: openField, closeField: closeField, label: label) } // MARK: - Data functions and accessors internal var _highField: String? internal var _lowField: String? internal var _openField: String? internal var _closeField: String? internal override func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry { let entry = CandleChartDataEntry( x: _xValueField == nil ? x : object[_xValueField!] as! Double, shadowH: object[_highField!] as! Double, shadowL: object[_lowField!] as! Double, open: object[_openField!] as! Double, close: object[_closeField!] as! Double) return entry } open override func calcMinMax() { if _cache.count == 0 { return } _yMax = -Double.greatestFiniteMagnitude _yMin = Double.greatestFiniteMagnitude _xMax = -Double.greatestFiniteMagnitude _xMin = Double.greatestFiniteMagnitude for e in _cache as! [CandleChartDataEntry] { if e.low < _yMin { _yMin = e.low } if e.high > _yMax { _yMax = e.high } if e.x < _xMin { _xMin = e.x } if e.x > _xMax { _xMax = e.x } } } // MARK: - Styling functions and accessors /// the space between the candle entries /// /// **default**: 0.1 (10%) fileprivate var _barSpace = CGFloat(0.1) /// the space that is left out on the left and right side of each candle, /// **default**: 0.1 (10%), max 0.45, min 0.0 open var barSpace: CGFloat { set { if newValue < 0.0 { _barSpace = 0.0 } else if newValue > 0.45 { _barSpace = 0.45 } else { _barSpace = newValue } } get { return _barSpace } } /// should the candle bars show? /// when false, only "ticks" will show /// /// **default**: true open var showCandleBar: Bool = true /// the width of the candle-shadow-line in pixels. /// /// **default**: 3.0 open var shadowWidth = CGFloat(1.5) /// the color of the shadow line open var shadowColor: NSUIColor? /// use candle color for the shadow open var shadowColorSameAsCandle = false /// Is the shadow color same as the candle color? open var isShadowColorSameAsCandle: Bool { return shadowColorSameAsCandle } /// color for open == close open var neutralColor: NSUIColor? /// color for open > close open var increasingColor: NSUIColor? /// color for open < close open var decreasingColor: NSUIColor? /// Are increasing values drawn as filled? /// increasing candlesticks are traditionally hollow open var increasingFilled = false /// Are increasing values drawn as filled? open var isIncreasingFilled: Bool { return increasingFilled } /// Are decreasing values drawn as filled? /// descreasing candlesticks are traditionally filled open var decreasingFilled = true /// Are decreasing values drawn as filled? open var isDecreasingFilled: Bool { return decreasingFilled } }
apache-2.0
88cd347361b32e216eb628717cb5f2e8
30.202703
213
0.60127
4.705842
false
false
false
false
khizkhiz/swift
stdlib/public/core/ImplicitlyUnwrappedOptional.swift
1
4064
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// An optional type that allows implicit member access. public enum ImplicitlyUnwrappedOptional<Wrapped> : NilLiteralConvertible { // The compiler has special knowledge of the existence of // `ImplicitlyUnwrappedOptional<Wrapped>`, but always interacts with it using // the library intrinsics below. case none case some(Wrapped) /// Construct a non-`nil` instance that stores `some`. public init(_ some: Wrapped) { self = .some(some) } /// Create an instance initialized with `nil`. @_transparent public init(nilLiteral: ()) { self = .none } } extension ImplicitlyUnwrappedOptional : CustomStringConvertible { /// A textual representation of `self`. public var description: String { switch self { case .some(let value): return String(value) case .none: return "nil" } } } /// Directly conform to CustomDebugStringConvertible to support /// optional printing. Implementation of that feature relies on /// _isOptional thus cannot distinguish ImplicitlyUnwrappedOptional /// from Optional. When conditional conformance is available, this /// outright conformance can be removed. extension ImplicitlyUnwrappedOptional : CustomDebugStringConvertible { public var debugDescription: String { return description } } @_transparent @warn_unused_result public // COMPILER_INTRINSIC func _stdlib_ImplicitlyUnwrappedOptional_isSome<Wrapped> (`self`: Wrapped!) -> Bool { return `self` != nil } @_transparent @warn_unused_result public // COMPILER_INTRINSIC func _stdlib_ImplicitlyUnwrappedOptional_unwrapped<Wrapped> (`self`: Wrapped!) -> Wrapped { switch `self` { case .some(let wrapped): return wrapped case .none: _preconditionFailure( "unexpectedly found nil while unwrapping an Optional value") } } #if _runtime(_ObjC) extension ImplicitlyUnwrappedOptional : _ObjectiveCBridgeable { public static func _getObjectiveCType() -> Any.Type { return Swift._getBridgedObjectiveCType(Wrapped.self)! } public func _bridgeToObjectiveC() -> AnyObject { switch self { case .none: _preconditionFailure("attempt to bridge an implicitly unwrapped optional containing nil") case .some(let x): return Swift._bridgeToObjectiveC(x)! } } public static func _forceBridgeFromObjectiveC( x: AnyObject, result: inout Wrapped!? ) { result = Swift._forceBridgeFromObjectiveC(x, Wrapped.self) } public static func _conditionallyBridgeFromObjectiveC( x: AnyObject, result: inout Wrapped!? ) -> Bool { let bridged: Wrapped? = Swift._conditionallyBridgeFromObjectiveC(x, Wrapped.self) if let value = bridged { result = value } return false } public static func _isBridgedToObjectiveC() -> Bool { return Swift._isBridgedToObjectiveC(Wrapped.self) } } #endif extension ImplicitlyUnwrappedOptional { @available(*, unavailable, message="Please use nil literal instead.") public init() { fatalError("unavailable function can't be called") } @available(*, unavailable, message="Has been removed in Swift 3.") public func map<U>( @noescape f: (Wrapped) throws -> U ) rethrows -> ImplicitlyUnwrappedOptional<U> { fatalError("unavailable function can't be called") } @available(*, unavailable, message="Has been removed in Swift 3.") public func flatMap<U>( @noescape f: (Wrapped) throws -> ImplicitlyUnwrappedOptional<U> ) rethrows -> ImplicitlyUnwrappedOptional<U> { fatalError("unavailable function can't be called") } }
apache-2.0
6887edea7ba80e4d436ab4d9cad175f3
28.028571
95
0.686762
4.872902
false
false
false
false
obrichak/discounts
discounts/Classes/BarCodeGenerator/RSCodeGenerator.swift
1
5967
// // RSCodeGenerator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/10/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import Foundation import UIKit import AVFoundation import CoreImage let DIGITS_STRING = "0123456789" // Code generators are required to provide these two functions. protocol RSCodeGenerator { func generateCode(machineReadableCodeObject:AVMetadataMachineReadableCodeObject) -> UIImage? func generateCode(contents:String, machineReadableCodeObjectType:String) -> UIImage? } // Check digit are not required for all code generators. // UPC-E is using check digit to valid the contents to be encoded. // Code39Mod43, Code93 and Code128 is using check digit to encode barcode. @objc protocol RSCheckDigitGenerator { func checkDigit(contents:String) -> String } // Abstract code generator, provides default functions for validations and generations. class RSAbstractCodeGenerator : RSCodeGenerator { // Check whether the given contents are valid. func isValid(contents:String) -> Bool { let length = contents.length() if length > 0 { for i in 0..<length { let character = contents[i] if !DIGITS_STRING.contains(character!) { return false } } return true } return false } // Barcode initiator, subclass should return its own value. func initiator() -> String { return "" } // Barcode terminator, subclass should return its own value. func terminator() -> String { return "" } // Barcode content, subclass should return its own value. func barcode(contents:String) -> String { return "" } // Composer for combining barcode initiator, contents, terminator together. func completeBarcode(barcode:String) -> String { return self.initiator() + barcode + self.terminator() } // Drawer for completed barcode. func drawCompleteBarcode(completeBarcode:String) -> UIImage? { let length:Int = completeBarcode.length() if length <= 0 { return nil } // Values taken from CIImage generated AVMetadataObjectTypePDF417Code type image // Top spacing = 1.5 // Bottom spacing = 2 // Left & right spacing = 2 // Height = 28 let width = length + 4 let size = CGSizeMake(CGFloat(width), 28) UIGraphicsBeginImageContextWithOptions(size, true, 0) let context = UIGraphicsGetCurrentContext() CGContextSetShouldAntialias(context, false) UIColor.whiteColor().setFill() UIColor.blackColor().setStroke() CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height)) CGContextSetLineWidth(context, 1) for i in 0..<length { let character = completeBarcode[i] if character == "1" { let x = i + (2 + 1) CGContextMoveToPoint(context, CGFloat(x), 1.5) CGContextAddLineToPoint(context, CGFloat(x), size.height - 2) } } CGContextDrawPath(context, kCGPathFillStroke) let barcode = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return barcode } // RSCodeGenerator func generateCode(machineReadableCodeObject:AVMetadataMachineReadableCodeObject) -> UIImage? { return self.generateCode(machineReadableCodeObject.stringValue, machineReadableCodeObjectType: machineReadableCodeObject.type) } func generateCode(contents:String, machineReadableCodeObjectType:String) -> UIImage? { if self.isValid(contents) { return self.drawCompleteBarcode(self.completeBarcode(self.barcode(contents))) } return nil } // Class funcs // Get CIFilter name by machine readable code object type class func filterName(machineReadableCodeObjectType:String) -> String! { if machineReadableCodeObjectType == AVMetadataObjectTypeQRCode { return "CIQRCodeGenerator" } else if machineReadableCodeObjectType == AVMetadataObjectTypePDF417Code { return "CIPDF417BarcodeGenerator" } else if machineReadableCodeObjectType == AVMetadataObjectTypeAztecCode { return "CIAztecCodeGenerator" } else if machineReadableCodeObjectType == AVMetadataObjectTypeCode128Code { return "CICode128BarcodeGenerator" } else { return "" } } // Generate CI related code image class func generateCode(contents:String, filterName:String) -> UIImage { if filterName == "" { return UIImage() } let filter = CIFilter(name: filterName) filter.setDefaults() let inputMessage = contents.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) filter.setValue(inputMessage, forKey: "inputMessage") let outputImage = filter.outputImage let context = CIContext(options: nil) let cgImage = context.createCGImage(outputImage, fromRect: outputImage.extent()) return UIImage(CGImage: cgImage, scale: 1, orientation: UIImageOrientation.Up) } // Resize image class func resizeImage(source:UIImage, scale:CGFloat) -> UIImage { let width = source.size.width * scale let height = source.size.height * scale UIGraphicsBeginImageContext(CGSizeMake(width, height)) let context = UIGraphicsGetCurrentContext() CGContextSetInterpolationQuality(context, kCGInterpolationNone) source.drawInRect(CGRectMake(0, 0, width, height)) let target = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return target } }
gpl-3.0
b92db9ea9a7804a9c213dc49ecd20bfe
34.951807
134
0.648735
5.474312
false
false
false
false
youweit/Delicacy
Delicacy/DetailViewController.swift
1
1339
// // DetailViewController.swift // Delicacy // // Created by Youwei Teng on 9/7/15. // Copyright © 2015 Dcard. All rights reserved. // // TODO: with navigation transistion import UIKit class DetailViewController: UIViewController, UIViewControllerTransitioningDelegate { var articleCell: ArticleCell var backgroundImageView: UIImageView init (articleCell: ArticleCell) { self.articleCell = articleCell self.backgroundImageView = UIImageView(image: self.articleCell.coverImageView.image) self.backgroundImageView.contentMode = .ScaleAspectFill self.backgroundImageView.backgroundColor = UIColor.blackColor() self.backgroundImageView.tintColor = UIColor.whiteColor() super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("YOU SHOULD NOT USE STORYBOARD!") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("actionClose:"))) self.view.addSubview(self.backgroundImageView); self.backgroundImageView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self.view) } } func actionClose(tap: UITapGestureRecognizer) { presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } }
mit
b520aff53ea9a65a1a2ccf0824c44877
28.733333
104
0.7713
4.194357
false
false
false
false
xixijiushui/douyu
douyu/douyu/Classes/Home/ViewModel/RecommendViewModel.swift
1
3994
// // RecommendViewModel.swift // douyu // // Created by 赵伟 on 2016/11/8. // Copyright © 2016年 赵伟. All rights reserved. // import UIKit class RecommendViewModel: NSObject { lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() lazy var cycleModels : [CycleModel] = [CycleModel]() /// 大数据 private lazy var bigDataGroup : AnchorGroup = AnchorGroup() /// 颜值数据 private lazy var prettyGroup : AnchorGroup = AnchorGroup() } extension RecommendViewModel { func requestData(finishedCallBack : () -> ()) { let parameters = ["limit" : "4", "offset" : "0", "time" : NSDate.getCurrectTime()] // 创建组 let dGroup = dispatch_group_create() // 推荐数据 dispatch_group_enter(dGroup) NetworkTools.requestData(.get, urlString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : NSDate.getCurrectTime()]) { (result) in guard let resultData = result as? [String : AnyObject] else { return } guard let dataArray = resultData["data"] as? [[String : AnyObject]] else { return } self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" for dict in dataArray { let anchor = AnchorModel(dict: dict) self.bigDataGroup.anchors.append(anchor) } dispatch_group_leave(dGroup) } // 颜值数据 dispatch_group_enter(dGroup) NetworkTools.requestData(.get, urlString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in guard let resultData = result as? [String : AnyObject] else { return } guard let dataArray = resultData["data"] as? [[String : AnyObject]] else { return } self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" for dict in dataArray { let anchor = AnchorModel(dict: dict) self.prettyGroup.anchors.append(anchor) } dispatch_group_leave(dGroup) } // 游戏数据 dispatch_group_enter(dGroup) NetworkTools.requestData(.get, urlString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) { (result) in guard let resultData = result as? [String : AnyObject] else { return } guard let dataArray = resultData["data"] as? [[String : AnyObject]] else { return } for dict in dataArray { let group = AnchorGroup(dict: dict) if group.tag_name == "颜值" { continue } self.anchorGroups.append(group) } dispatch_group_leave(dGroup) } dispatch_group_notify(dGroup, dispatch_get_main_queue()) { self.anchorGroups.insert(self.prettyGroup, atIndex: 0) self.anchorGroups.insert(self.bigDataGroup, atIndex: 0) finishedCallBack() } } // 请求无线轮播的数据 func requestCycleData(finishCallback : () -> ()) { NetworkTools.requestData(.get, urlString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.401"]) { (result) in // 1.获取整体字典数据 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data的key获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // 3.字典转模型对象 for dict in dataArray { self.cycleModels.append(CycleModel(dict: dict)) } finishCallback() } } }
mit
48193c4175475163a9adfe3fcb399baa
35.462264
160
0.547219
4.612172
false
false
false
false
LYM-mg/DemoTest
indexView/indexView/One/索引条/控制器/IndexViewController.swift
1
6672
// // ViewController.swift // indexView // // Created by i-Techsys.com on 17/3/13. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit /** cell循环利用的ID */ private let KSettingCellID = "KSettingCellID" // MARK:- 通知 /// 通知中心 let MGNotificationCenter = NotificationCenter.default /** 通知:头部即将消失的的通知 */ let MGWillDisplayHeaderViewNotification = "MGWillDisplayHeaderViewNotification" /** 通知:头部完全消失的的通知 */ let MGDidEndDisplayingHeaderViewNotification = "MGDidEndDisplayingHeaderViewNotification" class IndexViewController: UIViewController { fileprivate lazy var dataArr = [MGCarGroup]() // MARK: - 懒加载属性 public lazy var tableView: UITableView = { [unowned self] in let tb = UITableView(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: MGScreenH)) tb.backgroundColor = UIColor(white: 0.9, alpha: 1.0) tb.autoresizingMask = [.flexibleWidth, .flexibleHeight] tb.dataSource = self tb.delegate = self tb.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: KSettingCellID) return tb }() fileprivate lazy var indexView: MGIndexView = MGIndexView(frame: nil, delegate: self) // MARK: - 属性 fileprivate lazy var tipLetterlabel: UILabel = { let tipLetterlabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) tipLetterlabel.center = self.view.center tipLetterlabel.textColor = UIColor.white tipLetterlabel.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) tipLetterlabel.font = UIFont.systemFont(ofSize: 28) tipLetterlabel.textAlignment = .center tipLetterlabel.isHidden = true self.view.addSubview(tipLetterlabel) return tipLetterlabel }() var letters = [String]() /** 记录右边边TableView是否滚动到的位置的Y坐标 */ fileprivate lazy var lastOffsetY: CGFloat = 0 /** 记录tableView是否向下滚动 */ fileprivate lazy var isScrollDown: Bool = true override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) loadData() indexView.selectedScaleAnimation = true view.addSubview(indexView) view.bringSubviewToFront(indexView) scrollViewDidScroll(tableView) // // UIApplication.shared.setStatusBarHidden(true, with: .none) } fileprivate func loadData() { // 初始化 // 1.获得plist的全路径 guard let path = Bundle.main.path(forResource: "cars_total.plist", ofType: nil) else { return } // 2.加载数组 guard let arr = NSArray(contentsOfFile: path) as? [[String : Any]] else { return } // 3.将dictArray里面的所有字典转成模型对象,放到新的数组中 for dict in arr { let group = MGCarGroup(dict: dict) dataArr.append(group) letters.append(group.title) } tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - 数据源 extension IndexViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return dataArr.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let group = self.dataArr[section] return group.carArrs.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: KSettingCellID, for: indexPath) // 这个判断selected,设置子试图颜色状态 let bgView = UIView() bgView.backgroundColor = UIColor.brown.withAlphaComponent(0.7) // 蓝色太难看了,设置为棕色 cell.selectedBackgroundView = bgView cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator // 设置数据 let group = self.dataArr[indexPath.section] let model = group.carArrs[indexPath.row] cell.textLabel?.text = model.name cell.imageView?.image = UIImage(named: model.icon) return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let group = self.dataArr[section]; return group.title } // MARK:- - =============== 以下方法用来滚动 滚动 滚动 ================= // 头部即将消失 func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if tableView.isDragging && !isScrollDown { // let hearderIndexPath = IndexPath(row: 0, section: section) MGNotificationCenter.post(name: NSNotification.Name(MGWillDisplayHeaderViewNotification), object: nil, userInfo: ["section": section]) } } // 头部完全消失 func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) { if tableView.isDragging && isScrollDown { MGNotificationCenter.post(name: NSNotification.Name(MGDidEndDisplayingHeaderViewNotification), object: nil, userInfo: ["section": section+1]) } } } // MARK: - 数据源和代理 extension IndexViewController: UITableViewDelegate{ func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 25 } func scrollViewDidScroll(_ scrollView: UIScrollView) { self.isScrollDown = (lastOffsetY < scrollView.contentOffset.y); lastOffsetY = scrollView.contentOffset.y } } // MARK: - MGIndexViewDelegate extension IndexViewController: MGIndexViewDelegate { func indexView(_ indexView: MGIndexView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { tableView.scrollToRow(at: IndexPath(row: 0, section: index), at: .top, animated: true) // 弹出首字母提示 showLetter(title: title) return index } fileprivate func showLetter(title: String) { self.tipLetterlabel.isHidden = false self.tipLetterlabel.text = title } func indexView(_ indexView: MGIndexView, cancelTouch: Set<UITouch>, with event: UIEvent?) { UIView.animate(withDuration: 0.8) { self.tipLetterlabel.isHidden = true } } func indexViewSectionIndexTitles(for indexView: MGIndexView) -> [String]? { return letters } }
mit
5c9e40938aed12a4ef1e1e08985ed139
34.723164
153
0.66013
4.542385
false
false
false
false
hirohisa/RxSwift
RxSwift/RxSwift/Concurrency/AsyncLock.swift
17
1933
// // AsyncLock.swift // Rx // // Created by Krunoslav Zaher on 3/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation // In case nobody holds this lock, the work will be queued and executed immediately // on thread that is requesting lock. // // In case there is somebody currently holding that lock, action will be enqueued. // When owned of the lock finishes with it's processing, it will also execute // and pending work. // // That means that enqueued work could possibly be executed later on a different thread. class AsyncLock : Disposable { typealias Action = () -> Void private var lock = NSRecursiveLock() private var queue: Queue<Action> = Queue(capacity: 2) private var isAcquired: Bool = false private var hasFaulted: Bool = false init() { } func wait(action: Action) { let isOwner = lock.calculateLocked { () -> Bool in if self.hasFaulted { return false } self.queue.enqueue(action) let isOwner = !self.isAcquired self.isAcquired = true return isOwner } if !isOwner { return } while true { let nextAction = lock.calculateLocked { () -> Action? in if self.queue.count > 0 { return self.queue.dequeue() } else { self.isAcquired = false return nil } } if let nextAction = nextAction { nextAction() } else { return } } } func dispose() { lock.performLocked { oldState in self.queue = Queue(capacity: 0) self.hasFaulted = true } } }
mit
cedc31609b85a6f973b36af065f936e2
24.786667
88
0.518883
5.033854
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Views/AlertView/AlertInternalView.swift
2
1469
import Foundation import WordPressShared /// Helper class, used internally by AlertView. Not designed for general usage. /// open class AlertInternalView: UIView { // MARK: - Public Properties open var onClick : (() -> ())? // MARK: - View Methods open override func awakeFromNib() { super.awakeFromNib() assert(backgroundView != nil) assert(alertView != nil) assert(titleLabel != nil) assert(descriptionLabel != nil) alertView.layer.cornerRadius = cornerRadius titleLabel.font = Styles.titleRegularFont descriptionLabel.font = Styles.detailsRegularFont titleLabel.textColor = Styles.titleColor descriptionLabel.textColor = Styles.detailsColor dismissButton.titleLabel?.font = Styles.buttonFont } /// Handles the Dismiss Button Tap. /// /// - Parameter sender: The button that was pressed. /// @IBAction fileprivate func buttonWasPressed(_ sender: AnyObject!) { onClick?() onClick = nil } // MARK: - Private Aliases fileprivate typealias Styles = WPStyleGuide.AlertView // MARK: - Private Constants fileprivate let cornerRadius = CGFloat(7) // MARK: - Outlets @IBOutlet var backgroundView: UIView! @IBOutlet var alertView: UIView! @IBOutlet var titleLabel: UILabel! @IBOutlet var descriptionLabel: UILabel! @IBOutlet var dismissButton: UIButton! }
gpl-2.0
151ddbc54e0204ed95246a64a0b33071
24.77193
79
0.656909
5.265233
false
false
false
false
mathewsheets/SwiftLearning
SwiftLearning.playground/Pages/Exercise 7.xcplaygroundpage/Contents.swift
1
2977
/*: [Table of Contents](@first) | [Previous](@previous) | [Next](@next) - - - * callout(Exercise): We need to model the set of possible iPhones manufactured. Replace each possible tuple property value with an enumeration that would be appropriate to the current non enumeration value. */ let iPhone = (modelName: "iPhone", modelNumbers: ["A1203"], hardwareStrings: ["iPhone1,1"], osVersions: [1, 2, 3]) let iPhone3G = (modelName: "iPhone 3G", modelNumbers: ["A1324", "A1241"], hardwareStrings: ["iPhone1,2"], osVersions: [2, 3, 4]) let iPhone3Gs = (modelName: "iPhone 3Gs", modelNumbers: ["A1325", "A1303"], hardwareStrings: ["iPhone2,1"], osVersions: [3, 4, 5, 6]) let iPhone4 = (modelName: "iPhone 4", modelNumbers: ["A1349", "A1332"], hardwareStrings: ["iPhone3,1", "iPhone3,2", "iPhone3,3"], osVersions: [4, 5, 6, 7]) let iPhone4s = (modelName: "iPhone 4s", modelNumbers: ["A1431", "A1387"], hardwareStrings: ["iPhone4,1"], osVersions: [5, 6, 7, 8, 9]) let iPhone5 = (modelName: "iPhone 5", modelNumbers: ["A1428", "A1429", "A1442"], hardwareStrings: ["iPhone5,1", "iPhone5,2"], osVersions: [6, 7, 8, 9]) let iPhone5c = (modelName: "iPhone 5c", modelNumbers: ["A1532", "A1456", "A1507", "A1529"], hardwareStrings: ["iPhone5,3", "iPhone5,4"], osVersions: [7, 8, 9]) let iPhone5s = (modelName: "iPhone 5s", modelNumbers: ["A1533", "A1453", "A1457", "A1530"], hardwareStrings: ["iPhone6,1", "iPhone6,2"], osVersions: [7, 8, 9]) let iPhone6 = (modelName: "iPhone 6", modelNumbers: ["A1549", "A1586"], hardwareStrings: ["iPhone7,2"], osVersions: [8, 9]) let iPhone6Plus = (modelName: "iPhone 6 Plus", modelNumbers: ["A1522", "A1524"], hardwareStrings: ["iPhone7,1"], osVersions: [8, 9]) let iPhone6s = (modelName: "iPhone 6s", modelNumbers: ["A1633", "A1688"], hardwareStrings: ["iPhone8,1"], osVersions: [9]) let iPhone6sPlus = (modelName: "iPhone 6s Plus", modelNumbers: ["A1634", "A1687"], hardwareStrings: ["iPhone8,2"], osVersions: [9]) let phones = [iPhone, iPhone3G, iPhone3Gs, iPhone4, iPhone4s, iPhone5, iPhone5c, iPhone5s, iPhone6, iPhone6Plus, iPhone6s, iPhone6sPlus] /*: **Constraints:** - Create the following Enumerations: - ModelName = Enumeration for all the model names - ModelNumber = Enumeration for all the model numbers - HardwareString = Enumeration for all hardware string - OSVersion = Enumeration for all os versions - Create the following Functions - Create a device passing in as arguments each enumeration - Validate the parameters using a guard statement - Throw an error that's appropriate to the invalid parameter value - Return a tuple similar to above only using the above enumerations - Get Device with ModelName - Get Device with ModelNumber - Get Device with HardwareString - Get Devices with OSVersion - - - [Table of Contents](@first) | [Previous](@previous) | [Next](@next) */
mit
13a7e83dc852c67cb611985060cfb681
77.368421
207
0.667786
3.490035
false
false
false
false
mlpqaz/V2ex
ZZV2ex/ZZV2ex/Common/V2ex+Define.swift
1
901
// // V2ex+Define.swift // ZZV2ex // // Created by ios on 2017/4/29. // Copyright © 2017年 张璋. All rights reserved. // import UIKit let SCREEN_WIDTH = UIScreen.main.bounds.size.width; let SCREEN_HEIGHT = UIScreen.main.bounds.size.height; func v2Font(_ fontSize: CGFloat) -> UIFont { return UIFont.systemFont(ofSize: fontSize); } //站点地址,客户端只有https,禁用http let V2EXURL = "https://www.v2ex.com/" //用户代理,使用这个切换是获取 m站点 还是www站数据 let USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4"; let MOBILE_CLIENT_HEADERS = ["user-agent":USER_AGENT] func dispatch_sync_safely_main_queue(_ block: ()-> ()) { if Thread.isMainThread { block() }else{ DispatchQueue.main.sync { block() } } }
apache-2.0
ab5d4562a4a2e0db986123f613043102
23.411765
156
0.663855
2.891986
false
false
false
false
Shark/GlowingRemote
GlowingRemote/DevicesViewController.swift
1
6289
// // ViewController.swift // GlowingRemote // // Created by Felix Seidel on 17/07/15. // Copyright © 2015 Felix Seidel. All rights reserved. // import UIKit import WatchConnectivity class DevicesViewController: UITableViewController { var devices : Array<Device>? var stateManager : StateManager? override func viewDidLoad() { super.viewDidLoad() let delegate = (UIApplication.sharedApplication().delegate) as! AppDelegate stateManager = delegate.stateManager } override func viewWillAppear(animated: Bool) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh", name: "StateChanged", object: nil) self.devices = stateManager?.devices if(self.devices == nil) { updateDevices() } } override func viewWillDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self, name: "refresh", object: nil) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2; } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if(section == 0) { return "RGB-Strips" } else { return "Steckdosen" } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let devPerSect = devicesPerSection(devices) if(section == 0) { return devPerSect["RGBStrip"]!.count } else { return devPerSect["RCSwitch"]!.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("state_cell")! let nameLabel : UILabel = cell.viewWithTag(1) as! UILabel let stateSwitch : UISwitch = cell.viewWithTag(2) as! UISwitch let devPerSect = devicesPerSection(devices) var currentDevice : Device if(indexPath.section == 0) { currentDevice = devPerSect["RGBStrip"]![indexPath.row] as! Device } else { currentDevice = devPerSect["RCSwitch"]![indexPath.row] as! Device } nameLabel.text = currentDevice.name stateSwitch.setOn(currentDevice.state.power, animated: true) stateSwitch.setValue(currentDevice, forKey: "device") stateSwitch.addTarget(self, action: "stateSwitchValueDidChange:", forControlEvents: .ValueChanged); return cell } func stateSwitchValueDidChange(sender: UISwitch!) { let device = sender.valueForKey("device") as! Device if sender.on { stateManager!.switchOn(device, completionHandler: {(Bool) -> Void in if(WCSession.defaultSession().reachable) { WCSession.defaultSession().sendMessage(["id": device.id, "power": device.state.power], replyHandler: nil, errorHandler: {(error) -> Void in print(error) }) } }) } else { stateManager!.switchOff(device, completionHandler: {(Bool) -> Void in if(WCSession.defaultSession().reachable) { WCSession.defaultSession().sendMessage(["id": device.id, "power": device.state.power], replyHandler: nil, errorHandler: {(error) -> Void in print(error) }) } }) } } private func devicesPerSection(devices : NSArray?) -> NSDictionary { let dict = NSMutableDictionary() dict.setValue(NSMutableArray(), forKey: "RCSwitch") dict.setValue(NSMutableArray(), forKey: "RGBStrip") if devices != nil { for device in devices! { let type = (device as! Device).type if(type == "RCSwitch") { dict["RCSwitch"]!.addObject(device) } else if(type == "RGBStrip") { dict["RGBStrip"]!.addObject(device) } } } return dict } func updateDevices() { stateManager!.updateDevices({ (success) -> Void in if(success) { self.devices = self.stateManager!.devices self.updateDeviceContext(self.devices!) } dispatch_async(dispatch_get_main_queue()) { if(success) { self.tableView.reloadData() } else { self.showDevicesNotAvailableAlert() } } }) } func updateStateRemotely() { stateManager!.updateState({ (success) -> Void in if(success) { self.devices = self.stateManager!.devices dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.updateDeviceContext(self.devices!) } } }) } func refresh() { self.devices = self.stateManager!.devices dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.updateDeviceContext(self.devices!) } } func updateDeviceContext(devices: Array<Device>) { let context = ["devices": devices] do { try WCSession.defaultSession().updateApplicationContext(context) } catch { print(error) } } @IBAction func unwindToDevices(segue: UIStoryboardSegue) { } private func showDevicesNotAvailableAlert() { dispatch_async(dispatch_get_main_queue()) { let baseUrl = self.stateManager?.apiBaseUrl?.absoluteString let alertController = UIAlertController(title: "Fehler", message: "Konnte Geräte nicht von \(baseUrl) laden.", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Default) { (action) in }) self.presentViewController(alertController, animated: true, completion: nil) } } }
isc
e2f7becd6fac6ceb074a5edb814f7ebb
33.734807
159
0.574837
5.132245
false
false
false
false
LYM-mg/DemoTest
indexView/Extesion/Category(扩展)/UIBUtton+Extension.swift
1
3184
// // UIBUtton+Extension.swift // chart2 // // Created by i-Techsys.com on 16/12/7. // Copyright © 2016年 i-Techsys. All rights reserved. // import UIKit extension UIButton { /// 遍历构造函数 convenience init(imageName:String?, bgImageName:String?){ self.init() // 1.设置按钮的属性 // 1.1图片 if let imageName = imageName { setImage(UIImage(named: imageName), for: .normal) setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted) } // 1.2背@objc 景 if let bgImageName = bgImageName { setBackgroundImage(UIImage(named: bgImageName), for: .normal) } // 2.设置尺寸 sizeToFit() } convenience init(imageName:String, target: Any, action:Selector) { self.init() // 1.设置按钮的属性 setImage(UIImage(named: imageName), for: .normal) // @objc setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted) sizeToFit() // 2.监听 addTarget(target, action: action, for: .touchUpInside) } convenience init(image:UIImage,highlightedImage: UIImage?, target: Any, action:Selector) { self.init() // 1.设置按钮的属性 setImage(image, for: .normal) if highlightedImage != nil { setImage(highlightedImage, for: .highlighted) } sizeToFit() // 2.监听 addTarget(target, action: action, for: .touchUpInside) } convenience init(title:String, target: Any, action:Selector) { self.init() setTitle(title, for: UIControl.State.normal) sizeToFit() addTarget(target, action: action, for: .touchUpInside) } convenience init(imageName:String, title: String, target: Any, action:Selector) { self.init() // 1.设置按钮的属性 setImage(UIImage(named: imageName), for: .normal) // setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted) setTitle(title, for: UIControl.State.normal) showsTouchWhenHighlighted = true titleLabel?.font = UIFont.systemFont(ofSize: 17) setTitleColor(UIColor.darkGray, for: UIControl.State.normal) sizeToFit() // 2.监听 addTarget(target, action: action, for: .touchUpInside) } convenience init(image: UIImage, title: String, target:Any, action:Selector) { self.init() // 1.设置按钮的属性 setImage(image, for: .normal) // setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted) setTitle(title, for: UIControl.State.normal) setTitleColor(.white, for: .normal) setTitleColor(.lightGray, for: .highlighted) showsTouchWhenHighlighted = true titleLabel?.font = UIFont.systemFont(ofSize: 18) imageEdgeInsets = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 0) sizeToFit() // 2.监听 addTarget(target, action: action, for: .touchUpInside) } }
mit
09f65e067a13e3c27350602a8121aeb0
30.947917
95
0.587871
4.338048
false
false
false
false
sambatech/player_sdk_ios
SambaPlayer/DownloadData.swift
1
3345
// // DownloadData.swift // SambaPlayer // // Created by Kesley Vaz on 29/11/18. // Copyright © 2018 Samba Tech. All rights reserved. // import Foundation public class DownloadData: NSObject, Codable { public var mediaId: String public var mediaTitle: String public var totalDownloadSizeInMB: Double public var sambaMedia: SambaMediaConfig? public var sambaSubtitle: SambaSubtitle? private enum CodingKeys: String, CodingKey { case mediaId case mediaTitle case totalDownloadSizeInMB } init(mediaId: String, mediaTitle: String, totalDownloadSizeInMB: Double, sambaMedia: SambaMediaConfig, sambaSubtitle: SambaSubtitle?) { self.mediaId = mediaId self.mediaTitle = mediaTitle self.totalDownloadSizeInMB = totalDownloadSizeInMB self.sambaMedia = sambaMedia self.sambaSubtitle = sambaSubtitle } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) mediaId = try container.decode(String.self, forKey: .mediaId) mediaTitle = try container.decode(String.self, forKey: .mediaTitle) totalDownloadSizeInMB = try container.decode(Double.self, forKey: .totalDownloadSizeInMB) sambaMedia = nil sambaSubtitle = nil } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(mediaId, forKey: .mediaId) try container.encode(mediaTitle, forKey: .mediaTitle) try container.encode(totalDownloadSizeInMB, forKey: .totalDownloadSizeInMB) } } public class DownloadState: NSObject { public var downloadPercentage: Float public var downloadData: DownloadData public var state: State public enum State: String { case WAITING case COMPLETED case CANCELED case IN_PROGRESS case FAILED case DELETED case PAUSED case RESUMED } init(downloadPercentage: Float, downloadData: DownloadData, state: State) { self.downloadPercentage = downloadPercentage self.downloadData = downloadData self.state = state } static func from(state: DownloadState.State, totalDownloadSize: Double, downloadPercentage: Float, media: SambaMediaConfig, sambaSubtitle: SambaSubtitle? = nil) -> DownloadState { let downloadData = DownloadData(mediaId: media.id, mediaTitle: media.title, totalDownloadSizeInMB: totalDownloadSize, sambaMedia: media, sambaSubtitle: sambaSubtitle) return DownloadState(downloadPercentage: downloadPercentage, downloadData: downloadData, state: state) } public static func from(notification: Notification) -> DownloadState? { guard let downloadState = notification.object as? DownloadState else { return nil } return downloadState } }
mit
03d15a0976a1e2bedccd15377cb354a4
33.474227
139
0.617823
4.683473
false
false
false
false
Alexzhxy/CVCalendar
CVCalendar Demo/CVCalendar Demo/ViewController.swift
5
8620
// // ViewController.swift // CVCalendar Demo // // Created by Мак-ПК on 1/3/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - Properties @IBOutlet weak var calendarView: CVCalendarView! @IBOutlet weak var menuView: CVCalendarMenuView! @IBOutlet weak var monthLabel: UILabel! @IBOutlet weak var daysOutSwitch: UISwitch! var shouldShowDaysOut = true var animationFinished = true // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() monthLabel.text = CVDate(date: NSDate()).globalDescription } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() calendarView.commitCalendarViewUpdate() menuView.commitMenuViewUpdate() } } // MARK: - CVCalendarViewDelegate & CVCalendarMenuViewDelegate extension ViewController: CVCalendarViewDelegate, CVCalendarMenuViewDelegate { /// Required method to implement! func presentationMode() -> CalendarMode { return .MonthView } /// Required method to implement! func firstWeekday() -> Weekday { return .Sunday } // MARK: Optional methods func shouldShowWeekdaysOut() -> Bool { return shouldShowDaysOut } func shouldAnimateResizing() -> Bool { return true // Default value is true } func didSelectDayView(dayView: CVCalendarDayView) { let date = dayView.date println("\(calendarView.presentedDate.commonDescription) is selected!") } func presentedDateUpdated(date: CVDate) { if monthLabel.text != date.globalDescription && self.animationFinished { let updatedMonthLabel = UILabel() updatedMonthLabel.textColor = monthLabel.textColor updatedMonthLabel.font = monthLabel.font updatedMonthLabel.textAlignment = .Center updatedMonthLabel.text = date.globalDescription updatedMonthLabel.sizeToFit() updatedMonthLabel.alpha = 0 updatedMonthLabel.center = self.monthLabel.center let offset = CGFloat(48) updatedMonthLabel.transform = CGAffineTransformMakeTranslation(0, offset) updatedMonthLabel.transform = CGAffineTransformMakeScale(1, 0.1) UIView.animateWithDuration(0.35, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.animationFinished = false self.monthLabel.transform = CGAffineTransformMakeTranslation(0, -offset) self.monthLabel.transform = CGAffineTransformMakeScale(1, 0.1) self.monthLabel.alpha = 0 updatedMonthLabel.alpha = 1 updatedMonthLabel.transform = CGAffineTransformIdentity }) { _ in self.animationFinished = true self.monthLabel.frame = updatedMonthLabel.frame self.monthLabel.text = updatedMonthLabel.text self.monthLabel.transform = CGAffineTransformIdentity self.monthLabel.alpha = 1 updatedMonthLabel.removeFromSuperview() } self.view.insertSubview(updatedMonthLabel, aboveSubview: self.monthLabel) } } func topMarker(shouldDisplayOnDayView dayView: CVCalendarDayView) -> Bool { return true } func dotMarker(shouldShowOnDayView dayView: CVCalendarDayView) -> Bool { let day = dayView.date.day let randomDay = Int(arc4random_uniform(31)) if day == randomDay { return true } return false } func dotMarker(colorOnDayView dayView: CVCalendarDayView) -> [UIColor] { let day = dayView.date.day let red = CGFloat(arc4random_uniform(600) / 255) let green = CGFloat(arc4random_uniform(600) / 255) let blue = CGFloat(arc4random_uniform(600) / 255) let color = UIColor(red: red, green: green, blue: blue, alpha: 1) let numberOfDots = Int(arc4random_uniform(3) + 1) switch(numberOfDots) { case 2: return [color, color] case 3: return [color, color, color] default: return [color] // return 1 dot } } func dotMarker(shouldMoveOnHighlightingOnDayView dayView: CVCalendarDayView) -> Bool { return true } } // MARK: - CVCalendarViewDelegate extension ViewController: CVCalendarViewDelegate { func preliminaryView(viewOnDayView dayView: DayView) -> UIView { let circleView = CVAuxiliaryView(dayView: dayView, rect: dayView.bounds, shape: CVShape.Circle) circleView.fillColor = .colorFromCode(0xCCCCCC) return circleView } func preliminaryView(shouldDisplayOnDayView dayView: DayView) -> Bool { if (dayView.isCurrentDay) { return true } return false } func supplementaryView(viewOnDayView dayView: DayView) -> UIView { let π = M_PI let ringSpacing: CGFloat = 3.0 let ringInsetWidth: CGFloat = 1.0 let ringVerticalOffset: CGFloat = 1.0 var ringLayer: CAShapeLayer! let ringLineWidth: CGFloat = 4.0 let ringLineColour: UIColor = .blueColor() var newView = UIView(frame: dayView.bounds) let diameter: CGFloat = (newView.bounds.width) - ringSpacing let radius: CGFloat = diameter / 2.0 let rect = CGRectMake(newView.frame.midX-radius, newView.frame.midY-radius-ringVerticalOffset, diameter, diameter) ringLayer = CAShapeLayer() newView.layer.addSublayer(ringLayer) ringLayer.fillColor = nil ringLayer.lineWidth = ringLineWidth ringLayer.strokeColor = ringLineColour.CGColor var ringLineWidthInset: CGFloat = CGFloat(ringLineWidth/2.0) + ringInsetWidth let ringRect: CGRect = CGRectInset(rect, ringLineWidthInset, ringLineWidthInset) let centrePoint: CGPoint = CGPointMake(ringRect.midX, ringRect.midY) let startAngle: CGFloat = CGFloat(-π/2.0) let endAngle: CGFloat = CGFloat(π * 2.0) + startAngle let ringPath: UIBezierPath = UIBezierPath(arcCenter: centrePoint, radius: ringRect.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: true) ringLayer.path = ringPath.CGPath ringLayer.frame = newView.layer.bounds return newView } func supplementaryView(shouldDisplayOnDayView dayView: DayView) -> Bool { if (Int(arc4random_uniform(3)) == 1) { return true } return false } } // MARK: - CVCalendarViewAppearanceDelegate extension ViewController: CVCalendarViewAppearanceDelegate { func dayLabelPresentWeekdayInitallyBold() -> Bool { return false } func spaceBetweenDayViews() -> CGFloat { return 2 } } // MARK: - IB Actions extension ViewController { @IBAction func switchChanged(sender: UISwitch) { if sender.on { calendarView.changeDaysOutShowingState(false) shouldShowDaysOut = true } else { calendarView.changeDaysOutShowingState(true) shouldShowDaysOut = false } } @IBAction func todayMonthView() { calendarView.toggleCurrentDayView() } /// Switch to WeekView mode. @IBAction func toWeekView(sender: AnyObject) { calendarView.changeMode(.WeekView) } /// Switch to MonthView mode. @IBAction func toMonthView(sender: AnyObject) { calendarView.changeMode(.MonthView) } @IBAction func loadPrevious(sender: AnyObject) { calendarView.loadPreviousView() } @IBAction func loadNext(sender: AnyObject) { calendarView.loadNextView() } } // MARK: - Convenience API Demo extension ViewController { func toggleMonthViewWithMonthOffset(offset: Int) { let calendar = NSCalendar.currentCalendar() let calendarManager = calendarView.manager let components = Manager.componentsForDate(NSDate()) // from today components.month += offset let resultDate = calendar.dateFromComponents(components)! self.calendarView.toggleViewWithDate(resultDate) } }
mit
eb9636ad90b64dee5b52298f66330f89
31.13806
162
0.62889
5.264059
false
false
false
false
brentdax/swift
test/SILGen/objc_witnesses.swift
2
4837
// RUN: %target-swift-emit-silgen -enable-sil-ownership -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import gizmo protocol Fooable { func foo() -> String! } // Witnesses Fooable.foo with the original ObjC-imported -foo method . extension Foo: Fooable {} class Phoûx : NSObject, Fooable { @objc func foo() -> String! { return "phoûx!" } } // witness for Foo.foo uses the foreign-to-native thunk: // CHECK-LABEL: sil private [transparent] [thunk] @$sSo3FooC14objc_witnesses7FooableA2cDP3foo{{[_0-9a-zA-Z]*}}FTW // CHECK: function_ref @$sSo3FooC3foo{{[_0-9a-zA-Z]*}}FTO // witness for Phoûx.foo uses the Swift vtable // CHECK-LABEL: $s14objc_witnesses008Phox_xraC3foo{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[IN_ADDR:%.*]] : // CHECK: [[VALUE:%.*]] = load_borrow [[IN_ADDR]] // CHECK: [[CLS_METHOD:%.*]] = class_method [[VALUE]] : $Phoûx, #Phoûx.foo!1 // CHECK: apply [[CLS_METHOD]]([[VALUE]]) // CHECK: end_borrow [[VALUE]] protocol Bells { init(bellsOn: Int) } extension Gizmo : Bells { } // CHECK: sil private [transparent] [thunk] @$sSo5GizmoC14objc_witnesses5BellsA2cDP{{[_0-9a-zA-Z]*}}fCTW // CHECK: bb0([[SELF:%[0-9]+]] : @trivial $*Gizmo, [[I:%[0-9]+]] : @trivial $Int, [[META:%[0-9]+]] : @trivial $@thick Gizmo.Type): // CHECK: [[INIT:%[0-9]+]] = function_ref @$sSo5GizmoC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thick Gizmo.Type) -> @owned Optional<Gizmo> // CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[I]], [[META]]) : $@convention(method) (Int, @thick Gizmo.Type) -> @owned Optional<Gizmo> // CHECK: switch_enum [[IUO_RESULT]] // CHECK: bb1: // CHECK-NEXT: [[FILESTR:%.*]] = string_literal utf8 " // CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1, // CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK: [[PRECOND:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]]) // CHECK: bb2([[UNWRAPPED_RESULT:%.*]] : @owned $Gizmo): // CHECK: store [[UNWRAPPED_RESULT]] to [init] [[SELF]] : $*Gizmo // Test extension of a native @objc class to conform to a protocol with a // subscript requirement. rdar://problem/20371661 protocol Subscriptable { subscript(x: Int) -> Any { get } } // CHECK-LABEL: sil private [transparent] [thunk] @$sSo7NSArrayC14objc_witnesses13SubscriptableA2cDPyypSicigTW : $@convention(witness_method: Subscriptable) (Int, @in_guaranteed NSArray) -> @out Any { // CHECK: function_ref @$sSo7NSArrayCyypSicigTO : $@convention(method) (Int, @guaranteed NSArray) -> @out Any // CHECK-LABEL: sil shared [serializable] [thunk] @$sSo7NSArrayCyypSicigTO : $@convention(method) (Int, @guaranteed NSArray) -> @out Any { // CHECK: objc_method {{%.*}} : $NSArray, #NSArray.subscript!getter.1.foreign extension NSArray: Subscriptable {} // witness is a dynamic thunk: protocol Orbital { var quantumNumber: Int { get set } } class Electron : Orbital { @objc dynamic var quantumNumber: Int = 0 } // CHECK-LABEL: sil private [transparent] [thunk] @$s14objc_witnesses8ElectronCAA7OrbitalA2aDP13quantumNumberSivgTW // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s14objc_witnesses8ElectronC13quantumNumberSivgTD // CHECK-LABEL: sil private [transparent] [thunk] @$s14objc_witnesses8ElectronCAA7OrbitalA2aDP13quantumNumberSivsTW // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s14objc_witnesses8ElectronC13quantumNumberSivsTD // witness is a dynamic thunk and is public: public protocol Lepton { var spin: Float { get } } public class Positron : Lepton { @objc public dynamic var spin: Float = 0.5 } // CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @$s14objc_witnesses8PositronCAA6LeptonA2aDP4spinSfvgTW // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s14objc_witnesses8PositronC4spinSfvgTD // Override of property defined in @objc extension class Derived : NSObject { @objc override var valence: Int { get { return 2 } set { } } } extension NSObject : Atom { @objc var valence: Int { get { return 1 } set { } } } // CHECK-LABEL: sil shared @$sSo8NSObjectC14objc_witnessesE7valenceSivM : $@yield_once @convention(method) (@guaranteed NSObject) -> @yields @inout Int { // CHECK: objc_method %0 : $NSObject, #NSObject.valence!getter.1.foreign // CHECK: yield // CHECK: objc_method %0 : $NSObject, #NSObject.valence!setter.1.foreign // CHECK: } protocol Atom : class { var valence: Int { get set } }
apache-2.0
bd3b5b16be11673871478ca4ed1e49d4
39.266667
200
0.674255
3.208499
false
false
false
false
Yoloabdo/REST-Udemy
REST apple/REST apple/MusicVideo.swift
1
3710
// // MusicVideo.swift // REST apple // // Created by Abdulrhman eaita on 4/3/16. // Copyright © 2016 Abdulrhman eaita. All rights reserved. // import Foundation class Videos { var _vname: String? var _vImageURL: String? var _vVideoURL: String? var _vRights: String? var _vArtist: String? var _vImId: String? var _vGenere: String? var _vLinkITunes: String? var _vReleaseDate: String? var _vPrice: String? var _vrank: Int? // this var gets created from the UI var vImageData: NSData? init(data: JSONDictionary) { // the name guard let name = data["im:name"] as? JSONDictionary, vName = name["label"] as? String else { print("couldn't parse Name ") return } // the video image guard let img = data["im:image"] as? JSONArray, image = img[2] as? JSONDictionary, imaglink = image["label"] as? String else { print("couldn't parse IMAGEURL ") return } // the video URL guard let video = data["link"] as? JSONArray, vURL = video[1] as? JSONDictionary, vHref = vURL["attributes"] as? JSONDictionary, vVideoURL = vHref["href"] as? String else { print("couldn't parse VideoURL ") return } // the rights guard let rights = data["rights"] as? JSONDictionary, right = rights["label"] as? String else { print("couldn't parse rights ") return } // the Artist name guard let artistName = data["im:artist"] as? JSONDictionary, artist = artistName["label"] as? String else { print("couldn't parse ArtistName ") return } // the video id guard let id = data["id"] as? JSONDictionary, attr = id["attributes"] as? JSONDictionary, vidID = attr["im:id"] as? String else { print("couldn't parse video id ") return } // the Genere guard let category = data["category"] as? JSONDictionary, catAttr = category["attributes"] as? JSONDictionary, genere = catAttr["label"] as? String else { print("couldn't parse video Genere ") return } // iTunes link guard let link = id["label"] as? String else { print("couldn't parse video iTunes link ") return } // release date guard let dateID = data["im:releaseDate"] as? JSONDictionary, dateAttr = dateID["attributes"] as? JSONDictionary, date = dateAttr["label"] as? String else { print("couldn't parse video ReleaseDate ") return } // price guard let imPrice = data["im:price"] as? JSONDictionary, priceLabel = imPrice["label"] as? String else { print("couldn't parse price ") return } _vname = vName _vImageURL = imaglink.stringByReplacingOccurrencesOfString("100x100", withString: "450x450") _vVideoURL = vVideoURL _vRights = right _vArtist = artist _vImId = vidID _vGenere = genere _vLinkITunes = link _vReleaseDate = date _vPrice = priceLabel } }
mit
b02f38baec35860aadec6ee28d1ec112
26.894737
100
0.496091
4.730867
false
false
false
false
milseman/swift
validation-test/Evolution/Inputs/struct_change_stored_to_computed.swift
38
548
#if BEFORE public struct ChangeStoredToComputed { public init() { celsius = 0 } public var celsius: Int public var fahrenheit: Int { get { return (celsius * 9) / 5 + 32 } set { celsius = ((newValue - 32) * 5) / 9 } } } #else public struct ChangeStoredToComputed { public init() { fahrenheit = 32 } public var celsius: Int { get { return ((fahrenheit - 32) * 5) / 9 } set { fahrenheit = (newValue * 9) / 5 + 32 } } public var fahrenheit: Int = 32 } #endif
apache-2.0
11ad661c54f53afa2bf2fd6eaf5b582e
12.7
42
0.54562
3.581699
false
false
false
false
toshiapp/toshi-ios-client
Toshi/Models/UserBootstrapParameters.swift
1
4177
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation import SweetFoundation /// Prepares user keys and data, signs and formats it properly as JSON to bootstrap a chat user. class UserBootstrapParameter { // This change might require re-creating Signal users lazy var password: String = { return UUID().uuidString }() let identityKey: String let lastResortPreKey: PreKeyRecord let prekeys: [PreKeyRecord] let registrationId: UInt32 let signalingKey: String let signedPrekey: SignedPreKeyRecord lazy var payload: [String: Any] = { var prekeys = [[String: Any]]() for prekey in self.prekeys { let prekeyParam: [String: Any] = [ "keyId": prekey.id, "publicKey": ((prekey.keyPair.publicKey() as NSData).prependKeyType() as Data).base64EncodedString() ] prekeys.append(prekeyParam) } let lastResortKey: [String: Any] = [ "keyId": Int(self.lastResortPreKey.id), "publicKey": ((self.lastResortPreKey.keyPair.publicKey() as NSData).prependKeyType() as Data).base64EncodedString() ] let signedPreKey: [String: Any] = [ "keyId": Int(self.signedPrekey.id), "publicKey": ((self.signedPrekey.keyPair.publicKey() as NSData).prependKeyType() as Data).base64EncodedString(), "signature": self.signedPrekey.signature.base64EncodedString() ] let payload: [String: Any] = [ "identityKey": self.identityKey, "lastResortKey": lastResortKey, "password": self.password, "preKeys": prekeys, "registrationId": Int(self.registrationId), "signalingKey": self.signalingKey, "signedPreKey": signedPreKey ] return payload }() // swiftlint:disable force_cast // Because this method relies heavily on obj-c classes, we need to force cast some values here. init() { let identityManager = OWSIdentityManager.shared() if identityManager.identityKeyPair() == nil { identityManager.generateNewIdentityKey() } guard let identityKeyPair = identityManager.identityKeyPair() else { CrashlyticsLogger.log("No identity key pair", attributes: [.occurred: "User bootstrap parameters init"]) fatalError("No ID key pair for current user!") } let storageManager = TSStorageManager.shared() identityKey = ((identityKeyPair.publicKey() as NSData).prependKeyType() as Data).base64EncodedString() lastResortPreKey = storageManager.getOrGenerateLastResortKey() prekeys = storageManager.generatePreKeyRecords() as! [PreKeyRecord] registrationId = TSAccountManager.getOrGenerateRegistrationId() signalingKey = CryptoTools.generateSecureRandomData(52).base64EncodedString() let keyPair = Curve25519.generateKeyPair() let keyToSign = (keyPair!.publicKey()! as NSData).prependKeyType()! as Data let signature = Ed25519.sign(keyToSign, with: identityManager.identityKeyPair()) as Data signedPrekey = SignedPreKeyRecord(id: Int32(0), keyPair: keyPair, signature: signature, generatedAt: Date())! for prekey in prekeys { storageManager.storePreKey(prekey.id, preKeyRecord: prekey) } storageManager.storeSignedPreKey(signedPrekey.id, signedPreKeyRecord: signedPrekey) } // swiftlint:enable force_cast }
gpl-3.0
aa0748fe5d88fe343364d7044aa49484
36.630631
127
0.669619
4.510799
false
false
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Extensions/WalletRepository.swift
1
22613
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import FeatureAuthenticationDomain import PlatformKit import RxRelay import RxSwift import ToolKit import WalletPayloadKit // TODO: Remove `NSObject` when `Wallet` is killed /// A bridge to `Wallet` since it is an ObjC object. @objc final class WalletRepository: NSObject, WalletRepositoryAPI, WalletCredentialsProviding { // MARK: - Types private enum JSSetter { enum Password { static let change = "MyWalletPhone.changePassword(\"%@\")" static let success = "objc_on_change_password_success" static let error = "objc_on_change_password_error" } /// Accepts "true" / "false" as parameter static let syncPubKeys = "MyWalletPhone.setSyncPubKeys(%@)" /// Accepts a String representing the language static let language = "MyWalletPhone.setLanguage(\"%@\")" /// Accepts a String representing the wallet payload static let payload = "MyWalletPhone.setEncryptedWalletData(\"%@\")" /// Fetches the user offline token static let legacyOfflineToken = "MyWalletPhone.KYC.lifetimeToken()" /// Fetches the user id static let legacyUserId = "MyWalletPhone.KYC.userId()" /// Updates user credentials: userId, lifetimeToken static let updateUserCredentials = "MyWalletPhone.KYC.updateUserCredentials(\"%@\", \"%@\")" // MARK: Account Credentials static let updateAccountCredentials = "MyWalletPhone.accountCredentials.update(\"%@\", \"%@\", \"%@\", \"%@\")" /// Updates nabu credentials: userId, lifetimeToken static let updateNabuCredentials = "MyWalletPhone.accountCredentials.updateNabu(\"%@\", \"%@\")" /// Updates exchange credentials: userId, lifetimeToken static let updateExchangeCredentials = "MyWalletPhone.accountCredentials.updateExchange(\"%@\", \"%@\")" /// Fetches the user offline token static let nabuOfflineToken = "MyWalletPhone.accountCredentials.nabuLifetimeToken()" /// Fetches the user id static let nabuUserId = "MyWalletPhone.accountCredentials.nabuUserId()" /// Fetches the exchange offline token static let exchangeOfflineToken = "MyWalletPhone.accountCredentials.exchangeLifetimeToken()" /// Fetches the exchange user id static let exchangeUserId = "MyWalletPhone.accountCredentials.exchangeUserId()" } private enum JSCallback { static let updateUserCredentialsSuccess = "objc_updateUserCredentials_success" static let updateUserCredentialsFailure = "objc_updateUserCredentials_error" static let updateAccountCredentialsSuccess = "objc_updateAccountCredentials_success" static let updateAccountCredentialsFailure = "objc_updateAccountCredentials_error" static let updateNabuCredentialsSuccess = "objc_updateNabuCredentials_success" static let updateNabuCredentialsFailure = "objc_updateNabuCredentials_error" static let updateExchangeCredentialsSuccess = "objc_updateExchangeCredentials_success" static let updateExchangeCredentialsFailure = "objc_updateExchangeCredentials_error" } // MARK: - Properties private let sessionTokenRelay = BehaviorRelay<String?>(value: nil) private let authenticatorTypeRelay = BehaviorRelay<WalletAuthenticatorType>(value: .standard) private let passwordRelay = BehaviorRelay<String?>(value: nil) private let reactiveWallet: ReactiveWalletAPI /// Streams the GUID if exists var guid: AnyPublisher<String?, Never> { .just(settings.guid) } /// Streams the cached shared key or `nil` if it is not cached var sharedKey: AnyPublisher<String?, Never> { .just(settings.sharedKey) } /// Streams the session token if exists var sessionToken: AnyPublisher<String?, Never> { sessionTokenRelay.take(1).asPublisher().ignoreFailure() } /// Streams the authenticator type var authenticatorType: AnyPublisher<WalletAuthenticatorType, Never> { authenticatorTypeRelay.take(1).asPublisher().ignoreFailure() } /// Streams the password if exists var password: AnyPublisher<String?, Never> { passwordRelay.take(1).asPublisher().ignoreFailure() } var hasPassword: AnyPublisher<Bool, Never> { password .map { $0 != nil } .eraseToAnyPublisher() } /// Streams the nabu offline token var offlineToken: AnyPublisher<NabuOfflineToken, MissingCredentialsError> { reactiveWallet.waitUntilInitializedFirst .mapError() .flatMap { [weak self] _ -> AnyPublisher<NabuOfflineToken, MissingCredentialsError> in guard let self = self else { return .failure(.offlineToken) } return self.getUnifiedOrLegacyNabuCredentials() } .handleEvents( receiveOutput: { [offlineTokenSubject] token in offlineTokenSubject.send(.success(token)) }, receiveCompletion: { [offlineTokenSubject] completion in switch completion { case .failure(let error): offlineTokenSubject.send(.failure(error)) case .finished: break } } ) .eraseToAnyPublisher() } lazy var offlineTokenPublisher: AnyPublisher< Result<NabuOfflineToken, MissingCredentialsError>, Never > = offlineTokenSubject.eraseToAnyPublisher() var offlineTokenSubject: PassthroughSubject< Result<NabuOfflineToken, MissingCredentialsError>, Never > = .init() private let settings: AppSettingsAPI private let jsScheduler: SerialDispatchQueueScheduler private let combineJSScheduler: DispatchQueue private unowned let jsContextProvider: JSContextProviderAPI private let featureFlagService: FeatureFlagsServiceAPI // MARK: - Setup init( jsContextProvider: JSContextProviderAPI, appSettings: AppSettingsAPI, reactiveWallet: ReactiveWalletAPI, jsScheduler: SerialDispatchQueueScheduler = MainScheduler.instance, combineJSScheduler: DispatchQueue = DispatchQueue.main, featureFlagService: FeatureFlagsServiceAPI ) { self.jsContextProvider = jsContextProvider settings = appSettings self.reactiveWallet = reactiveWallet self.jsScheduler = jsScheduler self.combineJSScheduler = combineJSScheduler self.featureFlagService = featureFlagService super.init() } // MARK: - Wallet Setters /// Sets the guid func set(guid: String) -> AnyPublisher<Void, Never> { perform { [weak self] in self?.settings.set(guid: guid) } } /// Sets the shared key func set(sharedKey: String) -> AnyPublisher<Void, Never> { perform { [weak self] in self?.settings.set(sharedKey: sharedKey) } } /// Sets the session token func set(sessionToken: String) -> AnyPublisher<Void, Never> { perform { [weak sessionTokenRelay] in sessionTokenRelay?.accept(sessionToken) } } /// Clear the session token func cleanSessionToken() -> AnyPublisher<Void, Never> { perform { [weak sessionTokenRelay] in sessionTokenRelay?.accept(nil) } } /// Sets the authenticator type func set(authenticatorType: WalletAuthenticatorType) -> AnyPublisher<Void, Never> { perform { [weak authenticatorTypeRelay] in authenticatorTypeRelay?.accept(authenticatorType) } } /// Sets the password func set(password: String) -> AnyPublisher<Void, Never> { perform { [weak passwordRelay] in passwordRelay?.accept(password) } } // MARK: - JS Setters func set(language: String) -> AnyPublisher<Void, Never> { perform { [weak jsContextProvider] in let escaped = language.escapedForJS() let script = String(format: JSSetter.language, escaped) jsContextProvider?.jsContext.evaluateScriptCheckIsOnMainQueue(script) } } func set(syncPubKeys: Bool) -> AnyPublisher<Void, Never> { perform { [weak jsContextProvider] in let value = syncPubKeys ? "true" : "false" let script = String(format: JSSetter.syncPubKeys, value) jsContextProvider?.jsContext.evaluateScriptCheckIsOnMainQueue(script) } } func set(offlineToken: NabuOfflineToken) -> AnyPublisher<Void, CredentialWritingError> { featureFlagService.isEnabled(.accountCredentialsMetadataMigration) .handleEvents( receiveSubscription: { [offlineTokenSubject] _ in offlineTokenSubject.send(.success(offlineToken)) } ) .flatMap { [weak self] isEnabled -> AnyPublisher<Void, CredentialWritingError> in guard let self = self else { return .failure(.offlineToken) } guard isEnabled else { return self.setLegacyUserCredentials(offlineToken: offlineToken) } // write to both old and new metadata. let unifiedSave = self.setUnifiedCredentialsOrJustNabu(offlineToken: offlineToken) let legacySave = self.setLegacyUserCredentials(offlineToken: offlineToken) return unifiedSave .zip(legacySave) .mapToVoid() .eraseToAnyPublisher() } .eraseToAnyPublisher() } func set(payload: String) -> AnyPublisher<Void, Never> { perform { [weak jsContextProvider] in let escaped = payload.escapedForJS() let script = String(format: JSSetter.payload, escaped) jsContextProvider?.jsContext.evaluateScriptCheckIsOnMainQueue(script) } } func changePassword(password: String) -> AnyPublisher<Void, PasswordRepositoryError> { set(password: password) .flatMap { [weak self] _ -> AnyPublisher<Void, PasswordRepositoryError> in guard let self = self else { return .failure(.unavailable) } return self.sync() } .eraseToAnyPublisher() } private func sync() -> AnyPublisher<Void, PasswordRepositoryError> { Deferred { Future { [weak self] promise in guard let self = self else { promise(.failure(.syncFailed)) return } guard let password = self.passwordRelay.value else { promise(.failure(.unavailable)) return } let script = String(format: JSSetter.Password.change, password) self.jsContextProvider.jsContext.invokeOnce(functionBlock: { promise(.success(())) }, forJsFunctionName: JSSetter.Password.success as NSString) self.jsContextProvider.jsContext.invokeOnce(functionBlock: { promise(.failure(.syncFailed)) }, forJsFunctionName: JSSetter.Password.error as NSString) self.jsContextProvider.jsContext.evaluateScriptCheckIsOnMainQueue(script) } } .subscribe(on: combineJSScheduler) .eraseToAnyPublisher() } // MARK: - Accessors /// Retrieves the nabu credentials from metadata via JS /// First tries to retrieves from the new `ACCOUNT_CREDENTIALS`, if that fails we fallback to `RETAIL_CORE` private func getUnifiedOrLegacyNabuCredentials() -> AnyPublisher<NabuOfflineToken, MissingCredentialsError> { featureFlagService.isEnabled(.accountCredentialsMetadataMigration) .flatMap { [weak self] isEnabled -> AnyPublisher<(String?, String?, String?, String?), WalletError> in guard let self = self else { return .failure(.unknown) } guard isEnabled else { let legacyUserId = self.getStringValueFromJS(script: JSSetter.legacyUserId) let legacyOfflineToken = self.getStringValueFromJS(script: JSSetter.legacyOfflineToken) return legacyUserId .zip(legacyOfflineToken) { ($0, $1, nil, nil) } .eraseToAnyPublisher() } // Try retrieving from unified credentials entry otherwise fallback to old entry let nabuUserId = self.getStringValueFromJS(script: JSSetter.nabuUserId) let nabuOfflineToken = self.getStringValueFromJS(script: JSSetter.nabuOfflineToken) let exchangeUserId = self.getStringValueFromJS(script: JSSetter.exchangeUserId) let exchangeOfflineToken = self.getStringValueFromJS(script: JSSetter.exchangeOfflineToken) let legacyUserId = self.getStringValueFromJS(script: JSSetter.legacyUserId) let legacyOfflineToken = self.getStringValueFromJS(script: JSSetter.legacyOfflineToken) return nabuUserId .zip(nabuOfflineToken, exchangeUserId, exchangeOfflineToken) .flatMap { userId, offlineToken, exchangeUserId, exchangeOfflineToken -> AnyPublisher<(String?, String?, String?, String?), WalletError> in guard let userId = userId, let offlineToken = offlineToken else { return legacyUserId .zip(legacyOfflineToken) { legacyUserId, legacyOfflineToken in (legacyUserId, legacyOfflineToken, nil, nil) } .eraseToAnyPublisher() } return .just((userId, offlineToken, exchangeUserId, exchangeOfflineToken)) } .eraseToAnyPublisher() } .mapError { _ in MissingCredentialsError.offlineToken } .flatMap { nabuUserId, nabuOfflineToken, exchangeUserId, exchangeOfflineToken -> AnyPublisher<NabuOfflineToken, MissingCredentialsError> in guard let userId = nabuUserId else { return .failure(.userId) } guard let offlineToken = nabuOfflineToken else { return .failure(.offlineToken) } let token = NabuOfflineToken( userId: userId, token: offlineToken, exchangeUserId: exchangeUserId, exchangeOfflineToken: exchangeOfflineToken ) return .just(token) } .eraseToAnyPublisher() } private func getStringValueFromJS(script: String) -> AnyPublisher<String?, WalletError> { let jsContextProvider = jsContextProvider return Deferred { Future { [jsContextProvider] promise in guard WalletManager.shared.wallet.isInitialized() else { promise(.failure(.notInitialized)) return } guard let jsValue = jsContextProvider.jsContext.evaluateScriptCheckIsOnMainQueue(script) else { promise(.success(nil)) return } guard !jsValue.isNull, !jsValue.isUndefined else { promise(.success(nil)) return } guard !jsValue.isNull, !jsValue.isUndefined else { promise(.success(nil)) return } guard let string = jsValue.toString() else { promise(.success(nil)) return } guard !string.isEmpty else { promise(.success(nil)) return } promise(.success(string)) } } .subscribe(on: combineJSScheduler) .eraseToAnyPublisher() } private func setLegacyUserCredentials( offlineToken: NabuOfflineToken ) -> AnyPublisher<Void, CredentialWritingError> { let jsContextProvider = jsContextProvider return Deferred { Future { [jsContextProvider] promise in jsContextProvider.jsContext.invokeOnce( functionBlock: { promise(.failure(.offlineToken)) }, forJsFunctionName: JSCallback.updateUserCredentialsFailure as NSString ) jsContextProvider.jsContext.invokeOnce( functionBlock: { promise(.success(())) }, forJsFunctionName: JSCallback.updateUserCredentialsSuccess as NSString ) let userId = offlineToken.userId.escapedForJS() let offlineToken = offlineToken.token.escapedForJS() let script = String(format: JSSetter.updateUserCredentials, userId, offlineToken) jsContextProvider.jsContext.evaluateScriptCheckIsOnMainQueue(script) } } .subscribe(on: combineJSScheduler) .eraseToAnyPublisher() } /// Sets the given offline token (userId, lifetimeToken) to new Metadata entry private func setNabuCredentials( offlineToken: NabuOfflineToken ) -> AnyPublisher<Void, CredentialWritingError> { let jsContextProvider = jsContextProvider return Deferred { Future { [jsContextProvider] promise in jsContextProvider.jsContext.invokeOnce( functionBlock: { promise(.failure(.offlineToken)) }, forJsFunctionName: JSCallback.updateNabuCredentialsFailure as NSString ) jsContextProvider.jsContext.invokeOnce( functionBlock: { promise(.success(())) }, forJsFunctionName: JSCallback.updateNabuCredentialsSuccess as NSString ) let nabuUserId = offlineToken.userId.escapedForJS() let nabuOfflineToken = offlineToken.token.escapedForJS() let script = String( format: JSSetter.updateNabuCredentials, nabuUserId, nabuOfflineToken ) jsContextProvider.jsContext.evaluateScriptCheckIsOnMainQueue(script) } } .subscribe(on: combineJSScheduler) .eraseToAnyPublisher() } /// Sets the unified credentials if exchangeUserId/OfflineToken are non-nil /// otherwise just sets the nabu credentials private func setUnifiedCredentialsOrJustNabu( offlineToken: NabuOfflineToken ) -> AnyPublisher<Void, CredentialWritingError> { guard let exchangeUserId = offlineToken.exchangeUserId, let exchangeToken = offlineToken.exchangeOfflineToken else { return setNabuCredentials(offlineToken: offlineToken) } let jsContextProvider = jsContextProvider return Deferred { Future { [jsContextProvider] promise in jsContextProvider.jsContext.invokeOnce( functionBlock: { promise(.failure(.offlineToken)) }, forJsFunctionName: JSCallback.updateAccountCredentialsFailure as NSString ) jsContextProvider.jsContext.invokeOnce( functionBlock: { promise(.success(())) }, forJsFunctionName: JSCallback.updateAccountCredentialsSuccess as NSString ) let nabuUserId = offlineToken.userId.escapedForJS() let nabuOfflineToken = offlineToken.token.escapedForJS() let exchangeUserId = exchangeUserId.escapedForJS() let exchangeToken = exchangeToken.escapedForJS() let script = String( format: JSSetter.updateAccountCredentials, nabuUserId, nabuOfflineToken, exchangeUserId, exchangeToken ) jsContextProvider.jsContext.evaluateScriptCheckIsOnMainQueue(script) } } .subscribe(on: combineJSScheduler) .eraseToAnyPublisher() } private func perform(_ operation: @escaping () -> Void) -> Completable { Completable .create { observer -> Disposable in operation() observer(.completed) return Disposables.create() } .subscribe(on: jsScheduler) } fileprivate func perform(_ operation: @escaping () -> Void) -> AnyPublisher<Void, Never> { Deferred { Future { promise in promise(.success(operation())) } } .subscribe(on: combineJSScheduler) .eraseToAnyPublisher() } fileprivate func perform<E: Error>(_ operation: @escaping () -> Void) -> AnyPublisher<Void, E> { let perform: AnyPublisher<Void, Never> = perform { operation() } return perform.mapError() } // MARK: - Legacy: PLEASE DONT USE THESE UNLESS YOU MUST HOOK LEGACY OBJ-C CODE @available(*, deprecated, message: "Please do not use this unless you absolutely need direct access") @objc var legacySessionToken: String? { get { sessionTokenRelay.value } set { sessionTokenRelay.accept(newValue) } } @available(*, deprecated, message: "Please do not use this unless you absolutely need direct access") @objc var legacyPassword: String? { get { passwordRelay.value } set { passwordRelay.accept(newValue) } } }
lgpl-3.0
4968689e8140af635eeee950cff75557
38.880071
119
0.59747
5.568087
false
false
false
false
geekaurora/ReactiveListViewKit
Example/ReactiveListViewKitDemo/UI Layer/FeedList/HotUsers/HotUsersCellViewController.swift
1
4080
// // HotUsersCellViewController.swift // ReactiveListViewKit // // Created by Cheng Zhang on 3/28/17. // Copyright © 2017 Cheng Zhang. All rights reserved. // import CZUtils import ReactiveListViewKit class HotUsersCellViewController: UIViewController, CZFeedCellViewSizeCalculatable { var diffId: String { return viewModel.diffId } private var viewModel: HotUsersCellViewModel var onAction: OnAction? private var containerStackView: UIStackView! private var sectionHeaderView: CZFeedListSupplementaryTextView! private var horizontalListView: CZHorizontalSectionAdapterView! private static let headerTitle = "Suggestions for you" private static let seeAllText = "See All" private static let suggestedUsersSectionViewBGColor = UIColor(white: 250.0 / 255.0, alpha: 1) required init(viewModel: CZFeedViewModelable?, onAction: OnAction?) { self.viewModel = viewModel as! HotUsersCellViewModel self.onAction = onAction super.init(nibName: nil, bundle: .main) } required init?(coder: NSCoder) { fatalError("Must call designated initializer init(viewMode:onAction:).") } func config(with viewModel: CZFeedViewModelable?) { guard let viewModel = viewModel as? HotUsersCellViewModel else {preconditionFailure()} let feedModels = viewModel.users.compactMap { user in CZFeedModel(viewClass: HotUserCellCardView.self, viewModel: HotUserCellViewModel(user)) } let horizontalListViewModel = CZHorizontalSectionAdapterViewModel(feedModels, viewHeight: 200) horizontalListView?.config(with: horizontalListViewModel) } static func sizeThatFits(_ containerSize: CGSize, viewModel: CZFeedViewModelable) -> CGSize { let size = CZFacadeViewHelper.sizeThatFits(containerSize, viewModel: viewModel, viewClass: HotUsersCellViewController.self) return size } func config(with viewModel: CZFeedViewModelable?, prevViewModel: CZFeedViewModelable?) {} override func viewDidLoad() { super.viewDidLoad() setupViews() config(with: viewModel) } } private extension HotUsersCellViewController { func setupViews () { view.backgroundColor = HotUsersCellViewController.suggestedUsersSectionViewBGColor // containerStackView containerStackView = UIStackView() containerStackView.axis = .vertical containerStackView.spacing = 5 containerStackView.alignment = .fill containerStackView.distribution = .fill containerStackView.overlayOnSuperview(view) // headerView let sectionHeaderViewModel = CZFeedListSupplementaryTextViewModel(title: HotUsersCellViewController.headerTitle, actionButtonText: HotUsersCellViewController.seeAllText, actionButtonClosure: { button in print("Tapped SeeAll button") }, inset: UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) ) sectionHeaderView = CZFeedListSupplementaryTextView(viewModel: sectionHeaderViewModel, onAction: onAction) // horizontalListView horizontalListView = CZHorizontalSectionAdapterView(onAction: onAction) horizontalListView.heightAnchor.constraint(equalToConstant: HotUserSection.userCardSize.height).isActive = true let arrangedSubViews: [UIView] = [CZDividerView(), sectionHeaderView, horizontalListView, CZDividerView()] arrangedSubViews.forEach{ containerStackView.addArrangedSubview($0) } } }
mit
1dd94faf95780326890a0339d660bbb4
42.393617
130
0.633243
5.84384
false
false
false
false