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
WeltN24/PiedPiper
Sources/PiedPiper/Promise.swift
1
6622
import Foundation /// This class is a Future computation, where you can attach failure and success callbacks. open class Promise<T>: Async { public typealias Value = T private var failureListeners: [(Error) -> Void] = [] private var successListeners: [(T) -> Void] = [] private var cancelListeners: [() -> Void] = [] private var error: Error? private var value: T? private var canceled = false private let successLock: ReadWriteLock = PThreadReadWriteLock() private let failureLock: ReadWriteLock = PThreadReadWriteLock() private let cancelLock: ReadWriteLock = PThreadReadWriteLock() /// The Future associated to this Promise private weak var _future: Future<T>? public var future: Future<T> { if let _future = _future { return _future } let newFuture = Future(promise: self) _future = newFuture return newFuture } /** Creates a new Promise */ public init() {} convenience init(_ value: T) { self.init() succeed(value) } convenience init(value: T?, error: Error) { self.init() if let value = value { succeed(value) } else { fail(error) } } convenience init(_ error: Error) { self.init() fail(error) } /** Mimics the given Future, so that it fails or succeeds when the stamps does so (in addition to its pre-existing behavior) Moreover, if the mimiced Future is canceled, the Promise will also cancel itself - parameter stamp: The Future to mimic - returns: The Promise itself */ @discardableResult public func mimic(_ stamp: Future<T>) -> Promise<T> { stamp.onCompletion { result in switch result { case .success(let value): self.succeed(value) case .error(let error): self.fail(error) case .cancelled: self.cancel() } } return self } /** Mimics the given Result, so that it fails or succeeds when the stamps does so (in addition to its pre-existing behavior) Moreover, if the mimiced Result is canceled, the Promise will also cancel itself - parameter stamp: The Result to mimic - returns: The Promise itself */ @discardableResult public func mimic(_ stamp: Result<T>) -> Promise<T> { switch stamp { case .success(let value): self.succeed(value) case .error(let error): self.fail(error) case .cancelled: self.cancel() } return self } private func clearListeners() { successLock.withWriteLock { successListeners.removeAll() } failureLock.withWriteLock { failureListeners.removeAll() } cancelLock.withWriteLock { cancelListeners.removeAll() } } /** Makes the Promise succeed with a value - parameter value: The value found for the Promise Calling this method makes all the listeners get the onSuccess callback */ public func succeed(_ value: T) { guard self.error == nil else { return } guard self.value == nil else { return } guard self.canceled == false else { return } self.value = value successLock.withReadLock { successListeners.forEach { listener in listener(value) } } clearListeners() } /** Makes the Promise fail with an error - parameter error: The optional error that caused the Promise to fail Calling this method makes all the listeners get the onFailure callback */ public func fail(_ error: Error) { guard self.error == nil else { return } guard self.value == nil else { return } guard self.canceled == false else { return } self.error = error failureLock.withReadLock { failureListeners.forEach { listener in listener(error) } } clearListeners() } /** Cancels the Promise Calling this method makes all the listeners get the onCancel callback (but not the onFailure callback) */ public func cancel() { guard self.error == nil else { return } guard self.value == nil else { return } guard self.canceled == false else { return } canceled = true cancelLock.withReadLock { cancelListeners.forEach { listener in listener() } } clearListeners() } /** Adds a listener for the cancel event of this Promise - parameter cancel: The closure that should be called when the Promise is canceled - returns: The updated Promise */ @discardableResult public func onCancel(_ callback: @escaping () -> Void) -> Promise<T> { if canceled { callback() } else { cancelLock.withWriteLock { cancelListeners.append(callback) } } return self } /** Adds a listener for the success event of this Promise - parameter success: The closure that should be called when the Promise succeeds, taking the value as a parameter - returns: The updated Promise */ @discardableResult public func onSuccess(_ callback: @escaping (T) -> Void) -> Promise<T> { if let value = value { callback(value) } else { successLock.withWriteLock { successListeners.append(callback) } } return self } /** Adds a listener for the failure event of this Promise - parameter success: The closure that should be called when the Promise fails, taking the error as a parameter - returns: The updated Promise */ @discardableResult public func onFailure(_ callback: @escaping (Error) -> Void) -> Promise<T> { if let error = error { callback(error) } else { failureLock.withWriteLock { failureListeners.append(callback) } } return self } /** Adds a listener for both success and failure events of this Promise - parameter completion: The closure that should be called when the Promise completes (succeeds or fails), taking a result with value .Success in case the Promise succeeded and .error in case the Promise failed as parameter. If the Promise is canceled, the result will be .Cancelled - returns: The updated Promise */ @discardableResult public func onCompletion(_ completion: @escaping (Result<T>) -> Void) -> Promise<T> { if let error = error { completion(.error(error)) } else if let value = value { completion(.success(value)) } else if canceled { completion(.cancelled) } else { onSuccess { completion(.success($0)) } onFailure { completion(.error($0)) } onCancel { completion(.cancelled) } } return self } }
mit
4f31e6adba51945cffe35543cbdc0622
23.894737
283
0.640894
4.554333
false
false
false
false
amirzia/MyTodoList
MyTodoList/TasksViewController.swift
1
2947
// // TasksViewController.swift // MyTodoList // // Created by AmirMohammad Ziaei on 6/5/1395 AP. // Copyright © 1395 :). All rights reserved. // import UIKit import CoreData class TasksViewController: UIViewController { @IBOutlet weak var tabScrollView: ACTabScrollView! static var viewControllers: [ContentViewController] = [] var contentViews: [UIView] = [] let categories = ["Todo", "Completed"] override func viewDidLoad() { super.viewDidLoad() tabScrollView.arrowIndicator = true tabScrollView.delegate = self tabScrollView.dataSource = self tabScrollView.backgroundColor = UIColor(red: 61.0 / 255, green: 66.0 / 255, blue: 77.0 / 255, alpha: 1.0) let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) for category in categories { let vc = storyboard.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController TasksViewController.viewControllers.append(vc) vc.category = category addChildViewController(vc) contentViews.append(vc.view) } if let navigationBar = self.navigationController?.navigationBar { navigationBar.translucent = false navigationBar.tintColor = UIColor.whiteColor() navigationBar.barTintColor = UIColor(red: 90.0 / 255, green: 200.0 / 255, blue: 250.0 / 255, alpha: 1) navigationBar.titleTextAttributes = NSDictionary(object: UIColor.whiteColor(), forKey: NSForegroundColorAttributeName) as? [String : AnyObject] navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) navigationBar.shadowImage = UIImage() } UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent } } extension TasksViewController: ACTabScrollViewDelegate, ACTabScrollViewDataSource { func tabScrollView(tabScrollView: ACTabScrollView, didChangePageTo index: Int) { } func tabScrollView(tabScrollView: ACTabScrollView, didScrollPageTo index: Int) { } func numberOfPagesInTabScrollView(tabScrollView: ACTabScrollView) -> Int { return categories.count } func tabScrollView(tabScrollView: ACTabScrollView, tabViewForPageAtIndex index: Int) -> UIView { let label = UILabel() label.text = categories[index].uppercaseString label.font = UIFont.systemFontOfSize(16, weight: UIFontWeightThin) label.textColor = UIColor(red: 77.0 / 255, green: 79.0 / 255, blue: 84.0 / 255, alpha: 1) label.textAlignment = .Center label.sizeToFit() label.frame.size = CGSize(width: label.frame.size.width + 28, height: label.frame.size.height + 36) return label } func tabScrollView(tabScrollView: ACTabScrollView, contentViewForPageAtIndex index: Int) -> UIView { return contentViews[index] } }
mit
cea6e96f5710bbec6430c8bd9666e6c5
39.356164
155
0.691785
4.984772
false
false
false
false
classmere/app
Classmere/Classmere/Models/Course.swift
1
891
import Foundation /** A model representation of a course at OSU. Reference Docs - https://github.com/classmere/api */ struct Course: Decodable { let subjectCode: String let courseNumber: Int let title: String? let credits: String? let description: String? let sections: [Section] var abbr: String { return subjectCode + " " + String(courseNumber) } init(subjectCode: String, courseNumber: Int) { self.subjectCode = subjectCode self.courseNumber = courseNumber self.title = nil self.credits = nil self.description = nil self.sections = [] } } extension Course: Hashable { var hashValue: Int { return subjectCode.hashValue ^ courseNumber.hashValue &* 16777619 } static func == (lhs: Course, rhs: Course) -> Bool { return lhs.hashValue == rhs.hashValue } }
gpl-3.0
65938dabd22c132d9d3e867277176d46
22.447368
73
0.634119
4.367647
false
false
false
false
cocoascientist/Passengr
Passengr/ShowDetailAnimator.swift
1
3772
// // ShowDetailAnimator.swift // Passengr // // Created by Andrew Shepard on 10/19/14. // Copyright (c) 2014 Andrew Shepard. All rights reserved. // import UIKit final class ShowDetailAnimator: NSObject, UIViewControllerAnimatedTransitioning { private let duration = 0.75 func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? UICollectionViewController else { return } guard let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? UICollectionViewController else { return } guard let fromCollectionView = fromViewController.collectionView else { return } guard let toCollectionView = toViewController.collectionView else { return } let containerView = transitionContext.containerView containerView.backgroundColor = AppStyle.Color.lightBlue guard let indexPath = fromCollectionView.indexPathsForSelectedItems?.first else { return } let originAttributes = fromCollectionView.layoutAttributesForItem(at: indexPath) let destinationAttributes = toCollectionView.layoutAttributesForItem(at: indexPath) let itemSize = DetailViewLayout.detailLayoutItemSize(for: UIScreen.main.bounds) let toViewMargins = toCollectionView.layoutMargins // let fromViewMargins = fromCollectionView.layoutMargins guard let originRect = originAttributes?.frame else { return } guard var destinationRect = destinationAttributes?.frame else { return } destinationRect = CGRect(x: originRect.minX, y: destinationRect.minY + toViewMargins.top, width: itemSize.width, height: itemSize.height) let firstRect = CGRect(x: destinationRect.origin.x, y: destinationRect.origin.y, width: destinationRect.size.width, height: originRect.size.height) // let secondRect = CGRect(x: destinationRect.origin.x, y: destinationRect.origin.y, width: destinationRect.size.width, height: destinationRect.size.height) let insets = UIEdgeInsets(top: 73.0, left: 0.0, bottom: 1.0, right: 0.0) guard let snapshot = fromCollectionView.resizableSnapshotView(from: originRect, afterScreenUpdates: false, withCapInsets: insets) else { return } snapshot.frame = containerView.convert(originRect, from: fromCollectionView) containerView.addSubview(snapshot) let animations: () -> Void = { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.33, animations: { fromViewController.view.alpha = 0.0 }) UIView.addKeyframe(withRelativeStartTime: 0.23, relativeDuration: 0.73, animations: { snapshot.frame = firstRect }) // UIView.addKeyframe(withRelativeStartTime: 0.36, relativeDuration: 0.64, animations: { // snapshot.frame = secondRect // }) } let completion: (Bool) -> Void = { finished in transitionContext.completeTransition(finished) toViewController.view.alpha = 1.0 fromViewController.view.removeFromSuperview() containerView.addSubview(toViewController.view) snapshot.removeFromSuperview() } UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: [], animations: animations, completion: completion) } }
mit
4ace9c6476be77ac160973ec8c13f856
49.972973
169
0.694327
5.613095
false
false
false
false
remaerd/Keys
Keys/AsymmetricKeys-iOS.swift
1
9852
// // AsymmetricKeys.swift // Keys // // Created by Sean Cheng on 8/8/15. // // import Foundation import CommonCrypto public extension PublicKey { func encrypt(_ data: Data) throws -> Data { let dataPointer = (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count) var encryptedDataLength = SecKeyGetBlockSize(self.key) var encryptedData = [UInt8](repeating: 0, count: Int(encryptedDataLength)) let result = SecKeyEncrypt(self.key, self.options.cryptoPadding, dataPointer, data.count, &encryptedData, &encryptedDataLength) if result != noErr { throw Exception.cannotEncryptData } return Data(bytes: UnsafePointer<UInt8>(encryptedData), count: encryptedDataLength) } func verify(_ data: Data, signature: Data) throws -> Bool { let hash = data.SHA1 var result : OSStatus var pointer : UnsafePointer<UInt8>? = nil hash.withUnsafeBytes({ (ptr) in pointer = ptr}) let signaturePointer = (signature as NSData).bytes.bindMemory(to: UInt8.self, capacity: signature.count) result = SecKeyRawVerify(self.key, self.options.signaturePadding, pointer!, hash.count, signaturePointer, signature.count) if result != 0 { return false } else { return true } } } public extension PrivateKey { func decrypt(_ data: Data) throws -> Data { let dataPointer = (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count) var decryptedDataLength = SecKeyGetBlockSize(self.key) var decryptedData = [UInt8](repeating: 0, count: Int(decryptedDataLength)) let result = SecKeyDecrypt(self.key, self.options.cryptoPadding, dataPointer, data.count, &decryptedData, &decryptedDataLength) if result != noErr { throw Exception.cannotDecryptData } return Data(bytes: UnsafePointer<UInt8>(decryptedData), count: decryptedDataLength) } func signature(_ data: Data) throws -> Data { let hash = data.SHA1 var signatureDataLength = SecKeyGetBlockSize(self.key) var signatureData = [UInt8](repeating: 0, count: Int(signatureDataLength)) var pointer : UnsafePointer<UInt8>? = nil hash.withUnsafeBytes({ (ptr) in pointer = ptr}) let status = SecKeyRawSign(self.key, self.options.signaturePadding, pointer!, hash.count, &signatureData, &signatureDataLength) if status != OSStatus(kCCSuccess) { throw Exception.cannotSignData } return Data(bytes: UnsafePointer<UInt8>(signatureData), count: signatureDataLength) } } public extension AsymmetricKeys { static func secKeyFromData(_ data:Data, publicKey:Bool) throws -> SecKey { func SecKeyBelowiOS9() throws -> SecKey { var query :[String:AnyObject] = [ String(kSecClass): kSecClassKey, String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecAttrApplicationTag): TemporaryKeyTag as AnyObject ] SecItemDelete(query as CFDictionary) query[String(kSecValueData)] = data as AnyObject? if publicKey == true { query[String(kSecAttrKeyClass)] = kSecAttrKeyClassPublic } else { query[String(kSecAttrKeyClass)] = kSecAttrKeyClassPrivate } var persistentKey : CFTypeRef? var result : OSStatus = 0 result = SecItemAdd(query as CFDictionary, &persistentKey) print(result) if result != noErr { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } query[String(kSecValueData)] = nil query[String(kSecReturnPersistentRef)] = nil query[String(kSecReturnRef)] = true as AnyObject? var keyPointer: AnyObject? result = SecItemCopyMatching(query as CFDictionary, &keyPointer) if result != noErr { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } return keyPointer as! SecKey } func SecKeyFromiOS10() throws -> SecKey { let error : UnsafeMutablePointer<Unmanaged<CFError>?>? = nil var query :[String:AnyObject] = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecAttrKeySizeInBits): 1024 as CFNumber ] if publicKey == true { query[String(kSecAttrKeyClass)] = kSecAttrKeyClassPublic } else { query[String(kSecAttrKeyClass)] = kSecAttrKeyClassPrivate } if #available(iOS 10.0, *) { let key = SecKeyCreateWithData(data as CFData, query as CFDictionary, error) if ((error) != nil || key == nil) { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } return key! } else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } } if #available(iOS 10.0, *) { return try SecKeyFromiOS10() } else { return try SecKeyBelowiOS9() } } } public extension PublicKey { init(publicKey key: Data, options: AsymmetricKeys.Options = AsymmetricKeys.Options.Default) throws { func stripPublicKeyHeader(_ data:Data) throws -> Data { var buffer = [UInt8](repeating: 0, count: data.count) (data as NSData).getBytes(&buffer, length: data.count) var index = 0 if buffer[index] != 0x30 { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } index += 1 if buffer[index] > 0x80 { index += Int(buffer[index] - UInt8(0x80) + UInt8(1)) } else { index += 1 } let seqiod : [UInt8] = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00] if memcmp(&buffer, seqiod, 15) == 1 { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } index += 15 if buffer[index] != 0x03 { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } index += 1 if buffer[index] > 0x80 { index += Int(buffer[index] - UInt8(0x80) + UInt8(1)) } else { index += 1 } if buffer[index] != 0 { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } index += 1 var noHeaderBuffer = [UInt8](repeating: 0, count: data.count - index) (data as NSData).getBytes(&noHeaderBuffer, range: NSRange(location: index, length: data.count - index)) return Data(bytes: UnsafePointer<UInt8>(noHeaderBuffer), count: noHeaderBuffer.count) } func generatePublicKeyFromData() throws -> SecKey { guard var keyString = String(data: key, encoding: String.Encoding.utf8) else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } if (keyString.hasPrefix("-----BEGIN PUBLIC KEY-----\n") && ( keyString.hasSuffix("-----END PUBLIC KEY-----\n") || keyString.hasSuffix("-----END PUBLIC KEY-----"))) { keyString = keyString.replacingOccurrences(of: "-----BEGIN PUBLIC KEY-----", with: "") keyString = keyString.replacingOccurrences(of: "-----END PUBLIC KEY-----", with: "") keyString = keyString.replacingOccurrences(of: "\r", with: "") keyString = keyString.replacingOccurrences(of: "\n", with: "") keyString = keyString.replacingOccurrences(of: "\t", with: "") keyString = keyString.replacingOccurrences(of: " ", with: "") guard let data = Data(base64Encoded: keyString) else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } let noHeaderKey = try stripPublicKeyHeader(data) return try AsymmetricKeys.secKeyFromData(noHeaderKey, publicKey: true) } throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } do { self.key = try generatePublicKeyFromData() } catch { throw error } self.options = options self.tag = nil } } public extension PrivateKey { init(privateKey key: Data, options: AsymmetricKeys.Options = AsymmetricKeys.Options.Default) throws { func stripPrivateKeyHeader(_ data: Data) throws -> Data { var buffer = [UInt8](repeating: 0, count: data.count) (data as NSData).getBytes(&buffer, length: data.count) var index = 22 if buffer[index] != 0x04 { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } index += 1 var length = buffer[index] index += 1 let det = length & 0x80 if det == 0 { length = length & 0x7f } else { var byteCount = length & 0x7f if Int(byteCount) + index > data.count { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } var accum : UInt8 = 0 var char = buffer[index] index += Int(byteCount) while byteCount != 0 { accum = (accum << 8) + char char += 1 byteCount -= 1 } length = accum } return data.subdata(in: Range<Data.Index>(uncheckedBounds: (index,index + Int(length)))) } func generatePrivateKeyFromData() throws -> SecKey { guard var keyString = String(data: key, encoding: String.Encoding.utf8) else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } if (keyString.hasPrefix("-----BEGIN RSA PRIVATE KEY-----\n") && ( keyString.hasSuffix("-----END RSA PRIVATE KEY-----\n") || keyString.hasSuffix("-----END RSA PRIVATE KEY-----"))) { keyString = keyString.replacingOccurrences(of:"-----BEGIN RSA PRIVATE KEY-----", with: "") keyString = keyString.replacingOccurrences(of:"-----END RSA PRIVATE KEY-----", with: "") keyString = keyString.replacingOccurrences(of:"\r", with: "") keyString = keyString.replacingOccurrences(of:"\n", with: "") keyString = keyString.replacingOccurrences(of:"\t", with: "") keyString = keyString.replacingOccurrences(of:" ", with: "") guard let data = Data(base64Encoded: keyString) else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } return try AsymmetricKeys.secKeyFromData(data, publicKey: false) } else { throw AsymmetricKeys.Exception.cannotCreateSecKeyFromData } } self.key = try generatePrivateKeyFromData() self.options = options self.tag = nil } }
bsd-3-clause
c1f4f7084cc9e4fffea1276e93307e3a
40.745763
186
0.666565
4.496577
false
false
false
false
ranacquat/fish
Shared/FSAlbumView.swift
1
21347
// // FSAlbumView.swift // Fusuma // // Created by Yuta Akizuki on 2015/11/14. // Copyright © 2015年 ytakzk. All rights reserved. // import UIKit import Photos @objc public protocol FSAlbumViewDelegate: class { func albumViewCameraRollUnauthorized() func albumViewCameraRollAuthorized() } final class FSAlbumView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, PHPhotoLibraryChangeObserver, UIGestureRecognizerDelegate { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var imageCropView: FSImageCropView! @IBOutlet weak var imageCropViewContainer: UIView! @IBOutlet weak var collectionViewConstraintHeight: NSLayoutConstraint! @IBOutlet weak var imageCropViewConstraintTop: NSLayoutConstraint! weak var delegate: FSAlbumViewDelegate? = nil var images: PHFetchResult<PHAsset>! var imageManager: PHCachingImageManager? var previousPreheatRect: CGRect = .zero let cellSize = CGSize(width: 100, height: 100) var phAsset: PHAsset! // Variables for calculating the position enum Direction { case scroll case stop case up case down } let imageCropViewOriginalConstraintTop: CGFloat = 50 let imageCropViewMinimalVisibleHeight: CGFloat = 100 var dragDirection = Direction.up var imaginaryCollectionViewOffsetStartPosY: CGFloat = 0.0 var cropBottomY: CGFloat = 0.0 var dragStartPos: CGPoint = CGPoint.zero let dragDiff: CGFloat = 20.0 static func instance() -> FSAlbumView { return UINib(nibName: "FSAlbumViewAdaptive", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSAlbumView } func initialize() { if images != nil { return } self.isHidden = false let panGesture = UIPanGestureRecognizer(target: self, action: #selector(FSAlbumView.panned(_:))) panGesture.delegate = self self.addGestureRecognizer(panGesture) collectionViewConstraintHeight.constant = self.frame.height - imageCropView.frame.height - imageCropViewOriginalConstraintTop imageCropViewConstraintTop.constant = 50 dragDirection = Direction.up imageCropViewContainer.layer.shadowColor = UIColor.black.cgColor imageCropViewContainer.layer.shadowRadius = 30.0 imageCropViewContainer.layer.shadowOpacity = 0.9 imageCropViewContainer.layer.shadowOffset = CGSize.zero collectionView.register(UINib(nibName: "FSAlbumViewCell", bundle: Bundle(for: self.classForCoder)), forCellWithReuseIdentifier: "FSAlbumViewCell") collectionView.backgroundColor = fusumaBackgroundColor // Never load photos Unless the user allows to access to photo album checkPhotoAuth() // Sorting condition let options = PHFetchOptions() options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ] images = PHAsset.fetchAssets(with: .image, options: options) if images.count > 0 { changeImage(images[0]) collectionView.reloadData() collectionView.selectItem(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: UICollectionViewScrollPosition()) } PHPhotoLibrary.shared().register(self) } deinit { if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized { PHPhotoLibrary.shared().unregisterChangeObserver(self) } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func panned(_ sender: UITapGestureRecognizer) { if sender.state == UIGestureRecognizerState.began { let view = sender.view let loc = sender.location(in: view) let subview = view?.hitTest(loc, with: nil) if subview == imageCropView && imageCropViewConstraintTop.constant == imageCropViewOriginalConstraintTop { return } dragStartPos = sender.location(in: self) cropBottomY = self.imageCropViewContainer.frame.origin.y + self.imageCropViewContainer.frame.height // Move if dragDirection == Direction.stop { dragDirection = (imageCropViewConstraintTop.constant == imageCropViewOriginalConstraintTop) ? Direction.up : Direction.down } // Scroll event of CollectionView is preferred. if (dragDirection == Direction.up && dragStartPos.y < cropBottomY + dragDiff) || (dragDirection == Direction.down && dragStartPos.y > cropBottomY) { dragDirection = Direction.stop imageCropView.changeScrollable(false) } else { imageCropView.changeScrollable(true) } } else if sender.state == UIGestureRecognizerState.changed { let currentPos = sender.location(in: self) if dragDirection == Direction.up && currentPos.y < cropBottomY - dragDiff { imageCropViewConstraintTop.constant = max(imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height, currentPos.y + dragDiff - imageCropViewContainer.frame.height) collectionViewConstraintHeight.constant = min(self.frame.height - imageCropViewMinimalVisibleHeight, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height) } else if dragDirection == Direction.down && currentPos.y > cropBottomY { imageCropViewConstraintTop.constant = min(imageCropViewOriginalConstraintTop, currentPos.y - imageCropViewContainer.frame.height) collectionViewConstraintHeight.constant = max(self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height) } else if dragDirection == Direction.stop && collectionView.contentOffset.y < 0 { dragDirection = Direction.scroll imaginaryCollectionViewOffsetStartPosY = currentPos.y } else if dragDirection == Direction.scroll { imageCropViewConstraintTop.constant = imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height + currentPos.y - imaginaryCollectionViewOffsetStartPosY collectionViewConstraintHeight.constant = max(self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height) } } else { imaginaryCollectionViewOffsetStartPosY = 0.0 if sender.state == UIGestureRecognizerState.ended && dragDirection == Direction.stop { imageCropView.changeScrollable(true) return } let currentPos = sender.location(in: self) if currentPos.y < cropBottomY - dragDiff && imageCropViewConstraintTop.constant != imageCropViewOriginalConstraintTop { // The largest movement imageCropView.changeScrollable(false) imageCropViewConstraintTop.constant = imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height collectionViewConstraintHeight.constant = self.frame.height - imageCropViewMinimalVisibleHeight UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) dragDirection = Direction.down } else { // Get back to the original position imageCropView.changeScrollable(true) imageCropViewConstraintTop.constant = imageCropViewOriginalConstraintTop collectionViewConstraintHeight.constant = self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) dragDirection = Direction.up } } } // MARK: - UICollectionViewDelegate Protocol func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FSAlbumViewCell", for: indexPath) as! FSAlbumViewCell let currentTag = cell.tag + 1 cell.tag = currentTag let asset = self.images[(indexPath as NSIndexPath).item] self.imageManager?.requestImage(for: asset, targetSize: cellSize, contentMode: .aspectFill, options: nil) { result, info in if cell.tag == currentTag { cell.image = result // CAT /* asset.requestContentEditingInput(with: nil) { (contentEditingInput: PHContentEditingInput?, _) -> Void in //Get full image let url = contentEditingInput!.fullSizeImageURL let orientation = contentEditingInput!.fullSizeImageOrientation var inputImage = CIImage(contentsOf: url!) inputImage = inputImage!.applyingOrientation(orientation) for (key, value) in inputImage!.properties { print("key: \(key)") print("value: \(value)") } } */ if let location = asset.location { Localizator().getAddress(location: location, completion: { answer in print("ADDRESS TRANSLATED IN FSALBUMVIEW") cell.imageDescription = "\(answer!)\n\(self.getDate(date: asset.creationDate!))" }) } } } return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images == nil ? 0 : images.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let width = (collectionView.frame.width - 3) / 4 return CGSize(width: width, height: width) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { changeImage(images[(indexPath as NSIndexPath).row]) imageCropView.changeScrollable(true) imageCropViewConstraintTop.constant = imageCropViewOriginalConstraintTop collectionViewConstraintHeight.constant = self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height UIView.animate(withDuration: 0.2, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.layoutIfNeeded() }, completion: nil) dragDirection = Direction.up collectionView.scrollToItem(at: indexPath, at: .top, animated: true) } // MARK: - ScrollViewDelegate func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == collectionView { self.updateCachedAssets() } } //MARK: - PHPhotoLibraryChangeObserver func photoLibraryDidChange(_ changeInstance: PHChange) { DispatchQueue.main.async { let collectionChanges = changeInstance.changeDetails(for: self.images) if collectionChanges != nil { self.images = collectionChanges!.fetchResultAfterChanges let collectionView = self.collectionView! if !collectionChanges!.hasIncrementalChanges || collectionChanges!.hasMoves { collectionView.reloadData() } else { collectionView.performBatchUpdates({ let removedIndexes = collectionChanges!.removedIndexes if (removedIndexes?.count ?? 0) != 0 { collectionView.deleteItems(at: removedIndexes!.aapl_indexPathsFromIndexesWithSection(0)) } let insertedIndexes = collectionChanges!.insertedIndexes if (insertedIndexes?.count ?? 0) != 0 { collectionView.insertItems(at: insertedIndexes!.aapl_indexPathsFromIndexesWithSection(0)) } let changedIndexes = collectionChanges!.changedIndexes if (changedIndexes?.count ?? 0) != 0 { collectionView.reloadItems(at: changedIndexes!.aapl_indexPathsFromIndexesWithSection(0)) } }, completion: nil) } self.resetCachedAssets() } } } } internal extension UICollectionView { func aapl_indexPathsForElementsInRect(_ rect: CGRect) -> [IndexPath] { let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElements(in: rect) if (allLayoutAttributes?.count ?? 0) == 0 {return []} var indexPaths: [IndexPath] = [] indexPaths.reserveCapacity(allLayoutAttributes!.count) for layoutAttributes in allLayoutAttributes! { let indexPath = layoutAttributes.indexPath indexPaths.append(indexPath) } return indexPaths } } internal extension IndexSet { func aapl_indexPathsFromIndexesWithSection(_ section: Int) -> [IndexPath] { var indexPaths: [IndexPath] = [] indexPaths.reserveCapacity(self.count) (self as NSIndexSet).enumerate({idx, stop in indexPaths.append(IndexPath(item: idx, section: section)) }) return indexPaths } } private extension FSAlbumView { func changeImage(_ asset: PHAsset) { self.imageCropView.image = nil self.phAsset = asset DispatchQueue.global(qos: .default).async(execute: { let options = PHImageRequestOptions() options.isNetworkAccessAllowed = true self.imageManager?.requestImage(for: asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .aspectFill, options: options) { result, info in DispatchQueue.main.async(execute: { self.imageCropView.imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) self.imageCropView.image = result }) } }) } // Check the status of authorization for PHPhotoLibrary func checkPhotoAuth() { PHPhotoLibrary.requestAuthorization { (status) -> Void in switch status { case .authorized: self.imageManager = PHCachingImageManager() if self.images != nil && self.images.count > 0 { self.changeImage(self.images[0]) } DispatchQueue.main.async { self.delegate?.albumViewCameraRollAuthorized() } case .restricted, .denied: DispatchQueue.main.async(execute: { () -> Void in self.delegate?.albumViewCameraRollUnauthorized() }) default: break } } } // MARK: - Asset Caching func resetCachedAssets() { imageManager?.stopCachingImagesForAllAssets() previousPreheatRect = CGRect.zero } func updateCachedAssets() { var preheatRect = self.collectionView!.bounds preheatRect = preheatRect.insetBy(dx: 0.0, dy: -0.5 * preheatRect.height) let delta = abs(preheatRect.midY - self.previousPreheatRect.midY) if delta > self.collectionView!.bounds.height / 3.0 { var addedIndexPaths: [IndexPath] = [] var removedIndexPaths: [IndexPath] = [] self.computeDifferenceBetweenRect(self.previousPreheatRect, andRect: preheatRect, removedHandler: {removedRect in let indexPaths = self.collectionView.aapl_indexPathsForElementsInRect(removedRect) removedIndexPaths += indexPaths }, addedHandler: {addedRect in let indexPaths = self.collectionView.aapl_indexPathsForElementsInRect(addedRect) addedIndexPaths += indexPaths }) let assetsToStartCaching = self.assetsAtIndexPaths(addedIndexPaths) let assetsToStopCaching = self.assetsAtIndexPaths(removedIndexPaths) self.imageManager?.startCachingImages(for: assetsToStartCaching, targetSize: cellSize, contentMode: .aspectFill, options: nil) self.imageManager?.stopCachingImages(for: assetsToStopCaching, targetSize: cellSize, contentMode: .aspectFill, options: nil) self.previousPreheatRect = preheatRect } } func computeDifferenceBetweenRect(_ oldRect: CGRect, andRect newRect: CGRect, removedHandler: (CGRect)->Void, addedHandler: (CGRect)->Void) { if newRect.intersects(oldRect) { let oldMaxY = oldRect.maxY let oldMinY = oldRect.minY let newMaxY = newRect.maxY let newMinY = newRect.minY if newMaxY > oldMaxY { let rectToAdd = CGRect(x: newRect.origin.x, y: oldMaxY, width: newRect.size.width, height: (newMaxY - oldMaxY)) addedHandler(rectToAdd) } if oldMinY > newMinY { let rectToAdd = CGRect(x: newRect.origin.x, y: newMinY, width: newRect.size.width, height: (oldMinY - newMinY)) addedHandler(rectToAdd) } if newMaxY < oldMaxY { let rectToRemove = CGRect(x: newRect.origin.x, y: newMaxY, width: newRect.size.width, height: (oldMaxY - newMaxY)) removedHandler(rectToRemove) } if oldMinY < newMinY { let rectToRemove = CGRect(x: newRect.origin.x, y: oldMinY, width: newRect.size.width, height: (newMinY - oldMinY)) removedHandler(rectToRemove) } } else { addedHandler(newRect) removedHandler(oldRect) } } func assetsAtIndexPaths(_ indexPaths: [IndexPath]) -> [PHAsset] { if indexPaths.count == 0 { return [] } var assets: [PHAsset] = [] assets.reserveCapacity(indexPaths.count) for indexPath in indexPaths { let asset = self.images[(indexPath as NSIndexPath).item] assets.append(asset) } return assets } func getDate(date:Date)->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" return dateFormatter.string(from: date) } }
mit
09b3ba7d3df5db40cd51f8261155196b
39.045028
250
0.579648
6.394248
false
false
false
false
cuappdev/tcat-ios
TCAT/Views/SummaryView.swift
1
7413
// // SummaryView.swift // TCAT // // Created by Matthew Barker on 2/26/17. // Copyright © 2017 cuappdev. All rights reserved. // import UIKit class SummaryView: UIView { private var iconView: UIView! private let labelsContainerView = UIView() private let liveIndicator = LiveIndicator(size: .small, color: .clear) private let mainLabel = UILabel() private let secondaryLabel = UILabel() private let tab = UIView() private let tabSize = CGSize(width: 32, height: 4) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(route: Route) { // View Initialization super.init(frame: .zero) // TODO: // This value ends up getting overwritten by constraints, which is what we want, // but for some reason if it is not set prior to writing the constraints, the // entire view comes out blank. I'm still investigating but it seems to be an, // issue with the Pulley Pod that we're using. frame.size = CGSize(width: UIScreen.main.bounds.width, height: 100) backgroundColor = Colors.backgroundWash roundCorners(corners: [.topLeft, .topRight], radius: 16) setupTab() setupLabelsContainerView(for: route) setIcon(for: route) setupConstraints() } func setupTab() { tab.backgroundColor = Colors.metadataIcon tab.layer.cornerRadius = tabSize.height / 2 tab.clipsToBounds = true addSubview(tab) } func setupLabelsContainerView(for route: Route) { setupMainLabel(for: route) setupSecondaryLabel(for: route) setupLabelConstraints() addSubview(labelsContainerView) } func setupMainLabel(for route: Route) { mainLabel.font = .getFont(.regular, size: 16) mainLabel.textColor = Colors.primaryText mainLabel.numberOfLines = 0 mainLabel.allowsDefaultTighteningForTruncation = true mainLabel.lineBreakMode = .byTruncatingTail configureMainLabelText(for: route) labelsContainerView.addSubview(mainLabel) } func setupSecondaryLabel(for route: Route) { secondaryLabel.font = .getFont(.regular, size: 12) secondaryLabel.textColor = Colors.metadataIcon secondaryLabel.text = "Trip Duration: \(route.totalDuration) minute\(route.totalDuration == 1 ? "" : "s")" labelsContainerView.addSubview(secondaryLabel) } func setupLabelConstraints() { let labelSpacing: CGFloat = 4 mainLabel.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview() } secondaryLabel.snp.makeConstraints { make in make.top.equalTo(mainLabel.snp.bottom).offset(labelSpacing).priority(.high) make.leading.trailing.equalTo(mainLabel) make.bottom.equalToSuperview() } } func setupConstraints() { let labelLeadingInset = 120 let labelsContainerViewToTabSpacing: CGFloat = 10 let labelsContainerViewToBottomSpacing: CGFloat = 16 let tabTopInset: CGFloat = 6 let textLabelPadding: CGFloat = 16 let walkIconSize = CGSize(width: iconView.intrinsicContentSize.width * 2, height: iconView.intrinsicContentSize.height * 2) tab.snp.makeConstraints { make in make.centerX.equalToSuperview() make.top.equalToSuperview().inset(tabTopInset) make.size.equalTo(tabSize) } labelsContainerView.snp.makeConstraints { make in make.top.equalTo(tab.snp.bottom).offset(labelsContainerViewToTabSpacing).priority(.high) make.leading.equalToSuperview().inset(labelLeadingInset) make.trailing.equalToSuperview().inset(textLabelPadding).priority(.high) make.bottom.equalToSuperview().inset(labelsContainerViewToBottomSpacing) } iconView.snp.makeConstraints { make in if iconView is UIImageView { make.size.equalTo(walkIconSize) } else if iconView is BusIcon { make.size.equalTo(iconView.intrinsicContentSize) } make.centerY.equalToSuperview() make.centerX.equalTo(labelLeadingInset/2) } } /// Update summary card data and position accordingly private func configureMainLabelText(for route: Route) { let mainLabelBoldFont: UIFont = .getFont(.semibold, size: 14) if let departDirection = (route.directions.filter { $0.type == .depart }).first { var color: UIColor = Colors.primaryText let content = "Depart at \(departDirection.startTimeWithDelayDescription) from \(departDirection.name)" // This changes font to standard size. Label's font is different. var attributedString = departDirection.startTimeWithDelayDescription.bold( in: content, from: mainLabel.font, to: mainLabelBoldFont) attributedString = departDirection.name.bold(in: attributedString, to: mainLabelBoldFont) mainLabel.attributedText = attributedString if let delay = departDirection.delay { color = delay >= 60 ? Colors.lateRed : Colors.liveGreen let range = (attributedString.string as NSString).range(of: departDirection.startTimeWithDelayDescription) attributedString.addAttribute(.foregroundColor, value: color, range: range) // Find time within label to place live indicator if let stringRect = mainLabel.boundingRect(of: departDirection.startTimeWithDelayDescription + " ") { // Add spacing to insert live indicator within text attributedString.insert(NSAttributedString(string: " "), at: range.location + range.length) liveIndicator.setColor(to: color) if !mainLabel.subviews.contains(liveIndicator) { mainLabel.addSubview(liveIndicator) } liveIndicator.snp.remakeConstraints { make in make.leading.equalToSuperview().inset(stringRect.maxX) make.centerY.equalTo(stringRect.midY) } mainLabel.attributedText = attributedString } } } else { let content = route.directions.first?.locationNameDescription ?? "Route Directions" let pattern = route.directions.first?.name ?? "" mainLabel.attributedText = pattern.bold(in: content, from: mainLabel.font, to: mainLabelBoldFont) } } func updateTimes(for route: Route) { configureMainLabelText(for: route) } private func setIcon(for route: Route) { let firstBusRoute = route.directions.compactMap { return $0.type == .depart ? $0.routeNumber : nil }.first if let first = firstBusRoute { iconView = BusIcon(type: .directionLarge, number: first) addSubview(iconView) } else { // Show walking glyph iconView = UIImageView(image: #imageLiteral(resourceName: "walk")) iconView.contentMode = .scaleAspectFit iconView.tintColor = Colors.metadataIcon addSubview(iconView) } } }
mit
05588a7a937147a5ef76a631665992d0
37.010256
131
0.635726
5.087165
false
false
false
false
mbuchetics/RealmDataSource
Carthage/Checkouts/datasource/Example/ExampleTableViewController.swift
1
10899
// // ExampleTableViewController // Example // // Created by Matthias Buchetics on 24/11/15. // Copyright © 2015 aaa - all about apps GmbH. All rights reserved. // import UIKit import DataSource enum Identifiers: String { case TextCell case PersonCell case ButtonCell } enum Button: String { case Add case Remove } class ExampleTableViewController: UITableViewController { var tableDataSource: TableViewDataSource! override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(Identifiers.ButtonCell.rawValue) tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 44 tableView.dataSource = tableDataSource tableView.reloadData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } // MARK: Examples /// demonstrates various ways to setup the same simple data source func setupExample1() { let dataSource1 = DataSource([ Section(rows: [ Row(identifier: Identifiers.TextCell.rawValue, data: "a"), Row(identifier: Identifiers.TextCell.rawValue, data: "b"), Row(identifier: Identifiers.TextCell.rawValue, data: "c"), Row(identifier: Identifiers.TextCell.rawValue, data: "d"), ]) ]) let dataSource2 = DataSource([ Section(rowIdentifier: Identifiers.TextCell.rawValue, rows: ["a", "b", "c", "d"]) ]) let dataSource3 = ["a", "b", "c", "d"] .toDataSourceSection(Identifiers.TextCell.rawValue) .toDataSource() let dataSource4 = ["a", "b", "c", "d"].toDataSource(Identifiers.TextCell.rawValue) tableDataSource = TableViewDataSource( dataSource: dataSource1, configurator: TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, indexPath: NSIndexPath) in cell.textLabel?.text = "\(indexPath.row): \(title)" }) debugPrint(dataSource1) debugPrint(dataSource2) debugPrint(dataSource3) debugPrint(dataSource4) } /// heterogenous data source with different row/cell types func setupExample2() { let dataSource = DataSource([ Section(title: "B", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [ Person(firstName: "Matthias", lastName: "Buchetics"), ]), Section(title: "M", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [ Person(firstName: "Hugo", lastName: "Maier"), Person(firstName: "Max", lastName: "Mustermann"), ]), Section(title: "Strings", rowIdentifier: Identifiers.TextCell.rawValue, rows: [ "some text", "another text" ]), Section(rowIdentifier: Identifiers.ButtonCell.rawValue, rows: [ Button.Add, Button.Remove ]), ]) debugPrint(dataSource) tableDataSource = TableViewDataSource( dataSource: dataSource, configurators: [ TableViewCellConfigurator(Identifiers.PersonCell.rawValue) { (person: Person, cell: PersonCell, _) in cell.firstNameLabel?.text = person.firstName cell.lastNameLabel?.text = person.lastName }, TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, _) in cell.textLabel?.text = title }, TableViewCellConfigurator(Identifiers.ButtonCell.rawValue) { (button: Button, cell: ButtonCell, _) in switch (button) { case .Add: cell.titleLabel?.text = "Add" cell.backgroundColor = UIColor(red: 0, green: 0.7, blue: 0.2, alpha: 0.8) case .Remove: cell.titleLabel?.text = "Remove" cell.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.8) } }, ]) } /// example how to combine and modify existing data sources func setupExample3() { let dataSource1 = DataSource([ Section(title: "B", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [ Person(firstName: "Matthias", lastName: "Buchetics"), ]), Section(title: "M", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [ Person(firstName: "Hugo", lastName: "Maier"), Person(firstName: "Max", lastName: "Mustermann"), ]), ]) let dataSource2 = DataSource( Section(title: "Strings", rowIdentifier: Identifiers.TextCell.rawValue, rows: ["some text", "another text"])) var compoundDataSource = DataSource(dataSources: [dataSource1, dataSource2]) compoundDataSource.appendDataSource(dataSource2) compoundDataSource.appendDataSource(dataSource1) compoundDataSource.removeSectionAtIndex(1) debugPrint(compoundDataSource) tableDataSource = TableViewDataSource( dataSource: compoundDataSource, configurators: [ TableViewCellConfigurator(Identifiers.PersonCell.rawValue) { (person: Person, cell: PersonCell, _) in cell.firstNameLabel?.text = person.firstName cell.lastNameLabel?.text = person.lastName }, TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, _) in cell.textLabel?.text = title } ]) } /// shows how to transform a dictionary into data source func setupExample4() { let data = [ "section 1": ["a", "b", "c"], "section 2": ["d", "e", "f"], "section 3": ["g", "h", "i"], ] let dataSource = data.toDataSource(Identifiers.TextCell.rawValue, orderedKeys: data.keys.sort()) tableDataSource = TableViewDataSource( dataSource: dataSource, configurator: TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, _) in cell.textLabel?.text = title }) } /// example with an empty section func setupExample5() { let dataSource = DataSource([ Section(title: "B", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [ Person(firstName: "Matthias", lastName: "Buchetics"), ]), Section(title: "M", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [ Person(firstName: "Hugo", lastName: "Maier"), Person(firstName: "Max", lastName: "Mustermann"), ]), Section(title: "Empty Section", rowIdentifier: Identifiers.TextCell.rawValue, rows: Array<String>()), Section(title: "Strings", rowIdentifier: Identifiers.TextCell.rawValue, rows: ["some text", "another text"]), ]) debugPrint(dataSource) tableDataSource = TableViewDataSource( dataSource: dataSource, configurators: [ TableViewCellConfigurator(Identifiers.PersonCell.rawValue) { (person: Person, cell: PersonCell, _) in cell.firstNameLabel?.text = person.firstName cell.lastNameLabel?.text = person.lastName }, TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, _) in cell.textLabel?.text = title }, ]) } /// example of an row creator closure func setupExample6() { let dataSource = DataSource([ Section(title: "test", rowCountClosure: { return 5 }, rowCreatorClosure: { (rowIndex) in return Row(identifier: Identifiers.TextCell.rawValue, data: ((rowIndex + 1) % 2 == 0) ? "even" : "odd") }), Section<Any>(title: "mixed", rowCountClosure: { return 5 }, rowCreatorClosure: { (rowIndex) in if rowIndex % 2 == 0 { return Row(identifier: Identifiers.TextCell.rawValue, data: "test") } else { return Row(identifier: Identifiers.PersonCell.rawValue, data: Person(firstName: "Max", lastName: "Mustermann")) } }) ]) debugPrint(dataSource) tableDataSource = TableViewDataSource( dataSource: dataSource, configurators: [ TableViewCellConfigurator(Identifiers.PersonCell.rawValue) { (person: Person, cell: PersonCell, _) in cell.firstNameLabel?.text = person.firstName cell.lastNameLabel?.text = person.lastName }, TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, _) in cell.textLabel?.text = title }, ]) } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let row = tableDataSource.dataSource.rowAtIndexPath(indexPath) let rowIdentifier = Identifiers.init(rawValue: row.identifier)! switch (rowIdentifier) { case .PersonCell: let person = row.anyData as! Person print("\(person) selected") case .ButtonCell: switch (row.anyData as! Button) { case .Add: print("add") case .Remove: print("remove") } default: print("\(row.identifier) selected") } } // need to fix section header and footer height if section is empty (only required for grouped table style) override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return tableView.heightForHeaderInSection(tableDataSource.sectionAtIndex(section)) } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return tableView.heightForFooterInSection(tableDataSource.sectionAtIndex(section)) } }
mit
71ae4366d46747661fea22b20a5e91c7
39.214022
150
0.573224
5.416501
false
true
false
false
Witcast/witcast-ios
Pods/PullToRefreshKit/Source/Classes/ElasticRefreshControl.swift
1
5426
// // ElasticRefreshControl.swift // SWTest // // Created by huangwenchen on 16/7/29. // Copyright © 2016年 Leo. All rights reserved. // import Foundation import UIKit @IBDesignable open class ElasticRefreshControl: UIView { //目标,height 80, 高度 40 open let spinner:UIActivityIndicatorView = UIActivityIndicatorView() var radius:CGFloat{ get{ return totalHeight / 4 - margin } } open var progress:CGFloat = 0.0{ didSet{ setNeedsDisplay() } } open var margin:CGFloat = 4.0{ didSet{ setNeedsDisplay() } } var arrowRadius:CGFloat{ get{ return radius * 0.5 - 0.2 * radius * adjustedProgress } } var adjustedProgress:CGFloat{ get{ return min(max(progress,0.0),1.0) } } let totalHeight:CGFloat = 80 open var arrowColor = UIColor.white{ didSet{ setNeedsDisplay() } } open var elasticTintColor = UIColor.init(white: 0.5, alpha: 0.6){ didSet{ setNeedsDisplay() } } var animating = false{ didSet{ if animating{ spinner.startAnimating() setNeedsDisplay() }else{ spinner.stopAnimating() setNeedsDisplay() } } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } func commonInit(){ self.isOpaque = false addSubview(spinner) sizeToFit() spinner.hidesWhenStopped = true spinner.activityIndicatorViewStyle = .gray } open override func layoutSubviews() { super.layoutSubviews() spinner.center = CGPoint(x: self.bounds.width / 2.0, y: 0.75 * totalHeight) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func sinCGFloat(_ angle:CGFloat)->CGFloat{ let result = sinf(Float(angle)) return CGFloat(result) } func cosCGFloat(_ angle:CGFloat)->CGFloat{ let result = cosf(Float(angle)) return CGFloat(result) } open override func draw(_ rect: CGRect) { //如果在Animating,则什么都不做 if animating { super.draw(rect) return } let context = UIGraphicsGetCurrentContext() let centerX = rect.width/2.0 let lineWidth = 2.5 - 1.0 * adjustedProgress //上面圆的信息 let upCenter = CGPoint(x: centerX, y: (0.75 - 0.5 * adjustedProgress) * totalHeight) let upRadius = radius - radius * 0.3 * adjustedProgress //下面圆的信息 let downRadius:CGFloat = radius - radius * 0.75 * adjustedProgress let downCenter = CGPoint(x: centerX, y: totalHeight - downRadius - margin) //偏移的角度 let offSetAngle:CGFloat = CGFloat.pi / 2.0 / 12.0 //计算上面圆的左/右的交点坐标 let upP1 = CGPoint(x: upCenter.x - upRadius * cosCGFloat(offSetAngle), y: upCenter.y + upRadius * sinCGFloat(offSetAngle)) let upP2 = CGPoint(x: upCenter.x + upRadius * cosCGFloat(offSetAngle), y: upCenter.y + upRadius * sinCGFloat(offSetAngle)) //计算下面的圆左/右叫点坐标 let downP1 = CGPoint(x: downCenter.x - downRadius * cosCGFloat(offSetAngle), y: downCenter.y - downRadius * sinCGFloat(offSetAngle)) //计算Control Point let controPonintLeft = CGPoint(x: downCenter.x - downRadius, y: (downCenter.y + upCenter.y)/2) let controPonintRight = CGPoint(x: downCenter.x + downRadius, y: (downCenter.y + upCenter.y)/2) //实际绘制 context?.setFillColor(elasticTintColor.cgColor) context?.addArc(center: upCenter, radius: upRadius, startAngle: -CGFloat.pi - offSetAngle, endAngle: offSetAngle, clockwise: false) context?.move(to: CGPoint(x: upP1.x, y: upP1.y)) context?.addQuadCurve(to: downP1, control: controPonintLeft) context?.addArc(center: downCenter, radius: downRadius, startAngle: -CGFloat.pi - offSetAngle, endAngle: offSetAngle, clockwise: true) context?.addQuadCurve(to: upP2, control: controPonintRight) context?.fillPath() //绘制箭头 context?.setStrokeColor(arrowColor.cgColor) context?.setLineWidth(lineWidth) context?.addArc(center: upCenter, radius: arrowRadius, startAngle: 0, endAngle: CGFloat.pi * 1.5, clockwise: false) context?.strokePath() context?.setFillColor(arrowColor.cgColor) context?.setLineWidth(0.0) context?.move(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius - lineWidth * 1.5)) context?.addLine(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius + lineWidth * 1.5)) context?.addLine(to: CGPoint(x: upCenter.x + lineWidth * 0.865 * 3, y: upCenter.y - arrowRadius)) context?.addLine(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius - lineWidth * 1.5)) context?.fillPath() } override open func sizeToFit() { var width = frame.size.width if width < 30.0{ width = 30.0 } self.frame = CGRect(x: frame.origin.x, y: frame.origin.y,width: width, height: totalHeight) } }
apache-2.0
e369f0ba0a2c5382b64a86a3cd639e6e
33.796053
142
0.599546
4.234588
false
false
false
false
noodlewerk/XLForm
Examples/Swift/SwiftExample/CustomSelectors/CustomSelectorsFormViewController.swift
33
3143
// // CustomSelectorsFormViewController.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import MapKit class CustomSelectorsFormViewController : XLFormViewController { private enum Tags : String { case SelectorMap = "selectorMap" case SelectorMapPopover = "selectorMapPopover" } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.initializeForm() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initializeForm() } func initializeForm() { let form : XLFormDescriptor var section : XLFormSectionDescriptor var row : XLFormRowDescriptor form = XLFormDescriptor(title: "Custom Selectors") section = XLFormSectionDescriptor.formSectionWithTitle("TextField Types") section.footerTitle = "CustomSelectorsFormViewController.swift" form.addFormSection(section) // Selector Push row = XLFormRowDescriptor(tag: Tags.SelectorMap.rawValue, rowType: XLFormRowDescriptorTypeSelectorPush, title: "Coordinate") row.action.viewControllerClass = MapViewController.self row.valueTransformer = CLLocationValueTrasformer.self row.value = CLLocation(latitude: -33, longitude: -56) section.addFormRow(row) if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad { // Selector PopOver row = XLFormRowDescriptor(tag: Tags.SelectorMapPopover.rawValue, rowType: XLFormRowDescriptorTypeSelectorPopover, title: "Coordinate PopOver") row.action.viewControllerClass = MapViewController.self row.valueTransformer = CLLocationValueTrasformer.self row.value = CLLocation(latitude: -33, longitude: -56) section.addFormRow(row) } self.form = form } }
mit
15b01a53cbd20f1b50a078d6b04b6ae4
40.906667
154
0.708877
5.212272
false
false
false
false
koogawa/FoursquareAPIClient
FoursquareAPIClient/FoursquareAuthClient.swift
1
1497
// // FoursquareAuthClient.swift // FoursquareAPIClient // // Created by koogawa on 2015/07/27. // Copyright (c) 2015 Kosuke Ogawa. All rights reserved. // import UIKit @objc public protocol FoursquareAuthClientDelegate { func foursquareAuthClientDidSucceed(accessToken: String) @objc optional func foursquareAuthClientDidFail(error: Error) } public class FoursquareAuthClient: NSObject { var clientId: String var callback: String var delegate: FoursquareAuthClientDelegate public init(clientId: String, callback: String, delegate: FoursquareAuthClientDelegate) { self.clientId = clientId self.callback = callback self.delegate = delegate } public func authorizeWithRootViewController(_ controller: UIViewController) { let viewController = FoursquareAuthViewController(clientId: clientId, callback: callback) viewController.delegate = self let naviController = UINavigationController(rootViewController: viewController) controller.present(naviController, animated: true, completion: nil) } } // MARK: - FoursquareAuthViewControllerDelegate extension FoursquareAuthClient: FoursquareAuthViewControllerDelegate { func foursquareAuthViewControllerDidSucceed(accessToken: String) { delegate.foursquareAuthClientDidSucceed(accessToken: accessToken) } func foursquareAuthViewControllerDidFail(error: Error) { delegate.foursquareAuthClientDidFail?(error: error) } }
mit
a96d4044eb1f3210bca25241d0589078
30.851064
97
0.757515
5.216028
false
false
false
false
bluesnap/bluesnap-ios
BluesnapSDK/BluesnapSDK/BSValidator.swift
1
21061
// // BSValidator.swift // BluesnapSDK // // Created by Shevie Chen on 04/04/2017. // Copyright © 2017 Bluesnap. All rights reserved. // import Foundation public class BSValidator: NSObject { // MARK: Constants static let ccnInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_CCN) static let cvvInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_CVV) static let expMonthInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_ExpMonth) static let expPastInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_ExpIsInThePast) static let expInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_EXP) static let nameInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_Name) static let emailInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_Email) static let streetInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_Street) static let cityInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_City) static let countryInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_Country) static let stateInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_State) static let zipCodeInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_ZipCode) static let postalCodeInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_PostalCode) static let defaultFieldColor = UIColor.black static let errorFieldColor = UIColor.red // MARK: private properties internal static var cardTypesRegex = [Int: (cardType: String, regexp: String)]() // MARK: validation functions (check UI field and hide/show errors as necessary) class func validateName(ignoreIfEmpty: Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool { var result : Bool = true let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces).capitalized ?? "" input.setValue(newValue) if let addressDetails = addressDetails { addressDetails.name = newValue } if newValue.count == 0 && ignoreIfEmpty { // ignore } else if !isValidName(newValue) { result = false } if result { input.hideError() } else { input.showError(nameInvalidMessage) } return result } class func validateEmail(ignoreIfEmpty: Bool, input: BSInputLine, addressDetails: BSBillingAddressDetails?) -> Bool { let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces) ?? "" input.setValue(newValue) if let addressDetails = addressDetails { addressDetails.email = newValue } var result : Bool = true if (ignoreIfEmpty && newValue.count == 0) { // ignore } else if (!isValidEmail(newValue)) { result = false } else { result = true } if result { input.hideError() } else { input.showError(emailInvalidMessage) } return result } // // no validation yet, this is just a preparation // class func validatePhone(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSShippingAddressDetails?) -> Bool { // // let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces) ?? "" // input.setValue(newValue) // if let addressDetails = addressDetails { // addressDetails.phone = newValue // } // return true // } class func validateStreet(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool { let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces) ?? "" input.setValue(newValue) if let addressDetails = addressDetails { addressDetails.address = newValue } var result : Bool = true if (ignoreIfEmpty && newValue.count == 0) { // ignore } else if !isValidStreet(newValue) { result = false } else { result = true } if result { input.hideError() } else { input.showError(streetInvalidMessage) } return result } class func validateCity(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool { let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces) ?? "" input.setValue(newValue) if let addressDetails = addressDetails { addressDetails.city = newValue } var result : Bool = true if (ignoreIfEmpty && newValue.count == 0) { // ignore } else if !isValidCity(newValue) { result = false } else { result = true } if result { input.hideError() } else { input.showError(cityInvalidMessage) } return result } class func validateCountry(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool { let newValue = addressDetails?.country ?? "" var result : Bool = true if (ignoreIfEmpty && newValue.count == 0) { // ignore } else if !isValidCountry(countryCode: newValue) { result = false } else { result = true } if result { input.hideError() } else { input.showError(countryInvalidMessage) } return result } class func validateZip(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool { var result : Bool = true let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces) ?? "" input.setValue(newValue) if let addressDetails = addressDetails { addressDetails.zip = newValue } if (ignoreIfEmpty && newValue.count == 0) { // ignore } else if !isValidZip(countryCode: addressDetails?.country ?? "", zip: newValue) { result = false } else { result = true } if result { input.hideError() } else { let errorText = getZipErrorText(countryCode: addressDetails?.country ?? "") input.showError(errorText) } return result } class func validateState(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool { let newValue = addressDetails?.state ?? "" var result : Bool = true if ((ignoreIfEmpty || input.isHidden) && newValue.count == 0) { // ignore } else if !isValidCountry(countryCode: addressDetails?.country ?? "") { result = false } else if !isValidState(countryCode: addressDetails?.country ?? "", stateCode: addressDetails?.state) { result = false } if result { input.hideError() } else { input.showError(stateInvalidMessage) } return result } class func validateExp(input: BSCcInputLine) -> Bool { var ok : Bool = true var msg : String = expInvalidMessage let newValue = input.expTextField.text ?? "" if let p = newValue.firstIndex(of: "/") { let mm = String(newValue[..<p]) let yy = BSStringUtils.removeNoneDigits(String(newValue[p ..< newValue.endIndex])) if (mm.count < 2) { ok = false } else if !isValidMonth(mm) { ok = false msg = expMonthInvalidMessage } else if (yy.count < 2) { ok = false } else { (ok, msg) = isCcValidExpiration(mm: mm, yy: yy) } } else { ok = false } if (ok) { input.hideExpError() } else { input.showExpError(msg) } return ok } class func validateCvv(input: BSCcInputLine, cardType: String) -> Bool { var result : Bool = true; let newValue = input.getCvv() ?? "" if newValue.count != getCvvLength(cardType: cardType) { result = false } if result { input.hideCvvError() } else { input.showCvvError(cvvInvalidMessage) } return result } class func validateCCN(input: BSCcInputLine) -> Bool { var result : Bool = true; let newValue : String! = input.getValue() if !isValidCCN(newValue) { result = false } if result { input.hideError() } else { input.showError(ccnInvalidMessage) } return result } /** Validate the shopper consent to store the credit card details in case it is mandatory. The shopper concent is mandatory only in case it is a choose new card as payment method flow (shopper configuration). */ class func validateStoreCard(isShopperRequirements: Bool, isSubscriptionCharge: Bool, isStoreCard: Bool, isExistingCC: Bool) -> Bool { return ((isShopperRequirements || isSubscriptionCharge) && !isExistingCC) ? isStoreCard : true } // MARK: field editing changed methods (to limit characters and sizes) class func nameEditingChanged(_ sender: BSInputLine) { var input : String = sender.getValue() ?? "" input = BSStringUtils.removeNoneAlphaCharacters(input) input = BSStringUtils.cutToMaxLength(input, maxLength: 100) input = input.capitalized sender.setValue(input) } // class func phoneEditingChanged(_ sender: BSInputLine) { // // var input : String = sender.getValue() ?? "" // input = BSStringUtils.cutToMaxLength(input, maxLength: 30) // sender.setValue(input) // } class func emailEditingChanged(_ sender: BSInputLine) { var input : String = sender.getValue() ?? "" input = BSStringUtils.removeNoneEmailCharacters(input) input = BSStringUtils.cutToMaxLength(input, maxLength: 120) sender.setValue(input) } class func addressEditingChanged(_ sender: BSInputLine) { var input : String = sender.getValue() ?? "" input = BSStringUtils.cutToMaxLength(input, maxLength: 100) sender.setValue(input) } class func cityEditingChanged(_ sender: BSInputLine) { var input : String = sender.getValue() ?? "" input = BSStringUtils.removeNoneAlphaCharacters(input) input = BSStringUtils.cutToMaxLength(input, maxLength: 50) sender.setValue(input) } class func zipEditingChanged(_ sender: BSInputLine) { var input : String = sender.getValue() ?? "" input = BSStringUtils.cutToMaxLength(input, maxLength: 20) sender.setValue(input) } class func ccnEditingChanged(_ sender: UITextField) { var input : String = sender.text ?? "" input = BSStringUtils.removeNoneDigits(input) input = BSStringUtils.cutToMaxLength(input, maxLength: 21) input = formatCCN(input) sender.text = input } class func expEditingChanged(_ sender: UITextField) { var input : String = sender.text ?? "" input = BSStringUtils.removeNoneDigits(input) input = BSStringUtils.cutToMaxLength(input, maxLength: 4) input = formatExp(input) sender.text = input } class func cvvEditingChanged(_ sender: UITextField) { var input : String = sender.text ?? "" input = BSStringUtils.removeNoneDigits(input) input = BSStringUtils.cutToMaxLength(input, maxLength: 4) sender.text = input } class func updateState(addressDetails: BSBaseAddressDetails!, stateInputLine: BSInputLine) { let selectedCountryCode = addressDetails.country ?? "" let selectedStateCode = addressDetails.state ?? "" var hideState : Bool = true stateInputLine.setValue("") let countryManager = BSCountryManager.getInstance() if countryManager.countryHasStates(countryCode: selectedCountryCode) { hideState = false if let stateName = countryManager.getStateName(countryCode: selectedCountryCode, stateCode: selectedStateCode){ stateInputLine.setValue(stateName) } } else { addressDetails.state = nil } stateInputLine.isHidden = hideState stateInputLine.hideError() } // MARK: Basic validation functions open class func isValidMonth(_ str: String) -> Bool { let validMonths = ["01","02","03","04","05","06","07","08","09","10","11","12"] return validMonths.contains(str) } open class func isCcValidExpiration(mm: String, yy: String) -> (Bool, String) { var ok = false var msg = expInvalidMessage if let month = Int(mm), let year = Int(yy) { var dateComponents = DateComponents() let currYear : Int! = getCurrentYear() if yy.count < 4 { dateComponents.year = year + (currYear / 100)*100 } else { dateComponents.year = year } dateComponents.month = month dateComponents.day = 1 let expDate = Calendar.current.date(from: dateComponents)! if dateComponents.year! > currYear + 10 { ok = false } else if expDate < Date() { ok = false msg = expPastInvalidMessage } else { ok = true } } return (ok, msg) } open class func isValidEmail(_ str: String) -> Bool { let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: str) } open class func isValidCCN(_ str: String) -> Bool { if str.count < 6 { return false } var isOdd : Bool! = true var sum : Int! = 0; for character in str.reversed() { if (character == " ") { // ignore } else if (character >= "0" && character <= "9") { var digit : Int! = Int(String(character))! isOdd = !isOdd if (isOdd == true) { digit = digit * 2 } if digit > 9 { digit = digit - 9 } sum = sum + digit } else { return false } } return sum % 10 == 0 } open class func isValidName(_ str: String) -> Bool { if let p = str.firstIndex(of: " ") { let firstName = str[..<p].trimmingCharacters(in: .whitespaces) let lastName = str[p..<str.endIndex].trimmingCharacters(in: .whitespaces) if firstName.count < 1 || lastName.count < 1 { return false } } else { return false } return true } open class func isValidCity(_ str: String) -> Bool { var result : Bool = false if (str.count < 3) { result = false } else { result = true } return result } open class func isValidStreet(_ str: String) -> Bool { var result : Bool = false if (str.count < 3) { result = false } else { result = true } return result } open class func isValidZip(countryCode: String, zip: String) -> Bool { var result : Bool = false if BSCountryManager.getInstance().countryHasNoZip(countryCode: countryCode) { result = true } else if (zip.count < 3) { result = false } else { result = true } return result } open class func isValidState(countryCode: String, stateCode: String?) -> Bool { var result : Bool = true if !isValidCountry(countryCode: countryCode) { result = false } else if BSCountryManager.getInstance().countryHasStates(countryCode: countryCode) { if stateCode == nil || (stateCode?.count != 2) { result = false } else { let stateName = BSCountryManager.getInstance().getStateName(countryCode: countryCode, stateCode: stateCode ?? "") result = stateName != nil } } else if stateCode?.count ?? 0 > 0 { result = false } return result } open class func isValidCountry(countryCode: String?) -> Bool { var result : Bool = true if countryCode == nil || BSCountryManager.getInstance().getCountryName(countryCode: countryCode!) == nil { result = false } return result } open class func getCvvLength(cardType: String) -> Int { var cvvLength = 3 if cardType.lowercased() == "amex" { cvvLength = 4 } return cvvLength } // MARK: formatting functions class func getCurrentYear() -> Int! { let date = Date() let calendar = Calendar.current let year = calendar.component(.year, from: date) return year } class func getCcLengthByCardType(_ cardType: String) -> Int! { var maxLength : Int = 16 if cardType == "amex" { maxLength = 15 } else if cardType == "dinersclub" { maxLength = 14 } return maxLength } open class func formatCCN(_ str: String) -> String { var result: String let myLength = str.count if (myLength > 4) { let idx1 = str.index(str.startIndex, offsetBy: 4) result = str[..<idx1] + " " if (myLength > 8) { let idx2 = str.index(idx1, offsetBy: 4) result += str[idx1..<idx2] + " " if (myLength > 12) { let idx3 = str.index(idx2, offsetBy: 4) result += str[idx2..<idx3] + " " + str[idx3...] } else { result += str[idx2...] } } else { result += str[idx1...] } } else { result = str } return result } open class func formatExp(_ str: String) -> String { var result: String let myLength = str.count if (myLength > 2) { let idx1 = str.index(str.startIndex, offsetBy: 2) result = str[..<idx1] + "/" + str[idx1...] } else { result = str } return result } open class func getCCTypeByRegex(_ str: String) -> String? { // remove blanks let ccn = BSStringUtils.removeWhitespaces(str) // Display the card type for the card Regex for index in 0...self.cardTypesRegex.count-1 { if let _ = ccn.range(of:self.cardTypesRegex[index]!.regexp, options: .regularExpression) { return self.cardTypesRegex[index]!.cardType } } return nil } // MARK: zip texts open class func getZipLabelText(countryCode: String, forBilling: Bool) -> String { if countryCode.uppercased() == BSCountryManager.US_COUNTRY_CODE { if forBilling { return BSLocalizedStrings.getString(BSLocalizedString.Label_Billing_Zip) } else { return BSLocalizedStrings.getString(BSLocalizedString.Label_Shipping_Zip) } } else { return BSLocalizedStrings.getString(BSLocalizedString.Label_Postal_Code) } } open class func getZipErrorText(countryCode: String) -> String { if countryCode.uppercased() == BSCountryManager.US_COUNTRY_CODE { return zipCodeInvalidMessage } else { return postalCodeInvalidMessage } } open class func getZipKeyboardType(countryCode: String) -> UIKeyboardType { if countryCode.uppercased() == BSCountryManager.US_COUNTRY_CODE { return .numberPad } else { return .numbersAndPunctuation } } }
mit
deea5fce27d05d8eaffdd5b5edc85dab
32.804173
138
0.566524
5.057637
false
false
false
false
linhaosunny/smallGifts
小礼品/小礼品/Classes/Module/Me/Views/MeFooterSectionView.swift
1
3770
// // MeFooterSectionView.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/25. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SnapKit class MeFooterSectionView: UIView { weak var delegate:MeFooterSectionViewDelegate? var lineViewLeftConstraint:Constraint? //MARK: 懒加载 lazy var singleGiftButton:UIButton = { () -> UIButton in let button = UIButton(type: .custom) button.tag = 0 button.setTitle("单品", for: .normal) button.titleLabel?.font = fontSize15 button.setTitleColor(UIColor.gray, for: .normal) return button }() lazy var strategyGiftButton:UIButton = { () -> UIButton in let button = UIButton(type: .custom) button.tag = 1 button.setTitle("攻略", for: .normal) button.titleLabel?.font = fontSize15 button.setTitleColor(UIColor.gray, for: .normal) return button }() lazy var lineView:UIView = { () -> UIView in let view = UIView() view.backgroundColor = SystemNavgationBarTintColor return view }() lazy var bottomLine:UIView = { () -> UIView in let view = UIView() view.backgroundColor = SystemGlobalLineColor return view }() //MARK: 构造方法 override init(frame: CGRect) { super.init(frame: frame) setupMeFooterSectionView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() setupMeFooterSectionViewSubView() } //MARK: 私有方法 private func setupMeFooterSectionView() { backgroundColor = UIColor.white addSubview(singleGiftButton) addSubview(strategyGiftButton) addSubview(lineView) addSubview(bottomLine) singleGiftButton.addTarget(self, action: #selector(buttonClick(button:)), for: .touchUpInside) strategyGiftButton.addTarget(self, action: #selector(buttonClick(button:)), for: .touchUpInside) } private func setupMeFooterSectionViewSubView() { DispatchQueue.once(token: "MeFooterSectionView.LayoutSubView") { singleGiftButton.snp.makeConstraints { (make) in make.left.top.equalToSuperview() make.bottom.equalTo(lineView.snp.top) make.width.equalTo(strategyGiftButton) } strategyGiftButton.snp.makeConstraints { (make) in make.top.right.equalToSuperview() make.left.equalTo(singleGiftButton.snp.right) make.bottom.equalTo(singleGiftButton) } lineView.snp.makeConstraints { (make) in lineViewLeftConstraint = make.left.equalToSuperview().constraint make.bottom.equalToSuperview() make.width.equalTo(singleGiftButton) make.height.equalTo(5.0) } bottomLine.snp.makeConstraints({ (make) in make.left.right.bottom.equalToSuperview() make.height.equalTo(0.8) }) } } //MARK: 内部处理方法 @objc private func buttonClick(button:UIButton) { let offset = CGFloat(button.tag)*button.bounds.width lineViewLeftConstraint?.update(offset: offset) super.updateConstraints() delegate?.meFooterSectionViewButtonClick(button: button) } } //MARK: 协议 protocol MeFooterSectionViewDelegate:NSObjectProtocol { func meFooterSectionViewButtonClick(button:UIButton) }
mit
6be3231a53bf87a7ece3e112e651d5a5
29.352459
104
0.608156
5.024423
false
false
false
false
JosephNK/SwiftyIamport
SwiftyIamportDemo/Controller/WKHtml5InicisViewController.swift
1
4296
// // WKHtml5InicisViewController.swift // SwiftyIamportDemo // // Created by JosephNK on 29/11/2018. // Copyright © 2018 JosephNK. All rights reserved. // import UIKit import SwiftyIamport import WebKit class WKHtml5InicisViewController: UIViewController { lazy var wkWebView: WKWebView = { var view = WKWebView() view.backgroundColor = UIColor.clear view.navigationDelegate = self return view }() override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(wkWebView) self.wkWebView.frame = self.view.bounds // 결제 환경 설정 IAMPortPay.sharedInstance.configure(scheme: "iamporttest", // info.plist에 설정한 scheme storeIdentifier: "imp68124833") // iamport 에서 부여받은 가맹점 식별코드 IAMPortPay.sharedInstance .setPGType(.html5_inicis) // PG사 타입 .setIdName(nil) // 상점아이디 ({PG사명}.{상점아이디}으로 생성시 사용) .setPayMethod(.card) // 결제 형식 .setWKWebView(self.wkWebView) // 현재 Controller에 있는 WebView 지정 .setRedirectUrl(nil) // m_redirect_url 주소 // 결제 정보 데이타 let parameters: IAMPortParameters = [ "merchant_uid": String(format: "merchant_%@", String(Int(NSDate().timeIntervalSince1970 * 1000))), "name": "결제테스트", "amount": "1004", "buyer_email": "[email protected]", "buyer_name": "구매자", "buyer_tel": "010-1234-5678", "buyer_addr": "서울특별시 강남구 삼성동", "buyer_postcode": "123-456", "custom_data": ["A1": 123, "B1": "Hello"] //"custom_data": "24" ] IAMPortPay.sharedInstance.setParameters(parameters).commit() // 결제 웹페이지(Local) 파일 호출 if let url = IAMPortPay.sharedInstance.urlFromLocalHtmlFile() { let request = URLRequest(url: url) self.wkWebView.load(request) } } } extension WKHtml5InicisViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let request = navigationAction.request IAMPortPay.sharedInstance.requestRedirectUrl(for: request, parser: { (data, response, error) -> Any? in // Background Thread 처리 var resultData: [String: Any]? if let httpResponse = response as? HTTPURLResponse { let statusCode = httpResponse.statusCode switch statusCode { case 200: resultData = [ "isSuccess": "OK" ] break default: break } } return resultData }) { (pasingData) in // Main Thread 처리 } let result = IAMPortPay.sharedInstance.requestAction(for: request) decisionHandler(result ? .allow : .cancel) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // 결제 환경으로 설정에 의한 웹페이지(Local) 호출 결과 IAMPortPay.sharedInstance.requestIAMPortPayWKWebViewDidFinishLoad(webView) { (error) in if error != nil { switch error! { case .custom(let reason): print("error: \(reason)") break } }else { print("OK") } } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("didFail") } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { print("didFailProvisionalNavigation \(error.localizedDescription)") } }
mit
1b0f5cca3df18975753ad7e25dd6dd2d
34.008621
157
0.544447
4.588701
false
false
false
false
ovchinnikoff/FolioReaderKit
FolioReaderKit/FREpubParser.swift
2
8772
// // FREpubParser.swift // FolioReaderKit // // Created by Heberti Almeida on 04/05/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit import SSZipArchive class FREpubParser: NSObject { let book = FRBook() var bookBasePath: String! var resourcesBasePath: String! /** Unzip and read an epub file. Returns a FRBook. */ func readEpub(epubPath withEpubPath: String) -> FRBook { // Unzip let bookName = withEpubPath.lastPathComponent.stringByDeletingPathExtension bookBasePath = kApplicationDocumentsDirectory.stringByAppendingPathComponent(bookName) SSZipArchive.unzipFileAtPath(withEpubPath, toDestination: bookBasePath) readContainer() readOpf() return book } /** Read an unziped epub file. Returns a FRBook. */ func readEpub(filePath withFilePath: String) -> FRBook { return book } /** Read and parse container.xml file. */ private func readContainer() { let containerPath = "META-INF/container.xml" let containerData = NSData(contentsOfFile: bookBasePath.stringByAppendingPathComponent(containerPath), options: .DataReadingMappedAlways, error: nil) var error: NSError? if let xmlDoc = AEXMLDocument(xmlData: containerData!, error: &error) { let opfResource = FRResource() opfResource.href = xmlDoc.root["rootfiles"]["rootfile"].attributes["full-path"] as! String opfResource.mediaType = FRMediaType.determineMediaType(xmlDoc.root["rootfiles"]["rootfile"].attributes["full-path"] as! String) book.opfResource = opfResource resourcesBasePath = bookBasePath.stringByAppendingPathComponent(book.opfResource.href.stringByDeletingLastPathComponent) } } /** Read and parse .opf file. */ private func readOpf() { let opfPath = bookBasePath.stringByAppendingPathComponent(book.opfResource.href) let opfData = NSData(contentsOfFile: opfPath, options: .DataReadingMappedAlways, error: nil) var error: NSError? if let xmlDoc = AEXMLDocument(xmlData: opfData!, error: &error) { for item in xmlDoc.root["manifest"]["item"].all! { let resource = FRResource() resource.id = item.attributes["id"] as! String resource.href = item.attributes["href"] as! String resource.fullHref = resourcesBasePath.stringByAppendingPathComponent(item.attributes["href"] as! String).stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! resource.mediaType = FRMediaType.mediaTypesByName[item.attributes["media-type"] as! String] book.resources.add(resource) } // Get the first resource with the NCX mediatype book.ncxResource = book.resources.findFirstResource(byMediaType: FRMediaType.NCX) if book.ncxResource == nil { println("ERROR: Could not find table of contents resource. The book don't have a NCX resource.") } // The book TOC book.tableOfContents = findTableOfContents() // Read metadata book.metadata = readMetadata(xmlDoc.root["metadata"].children) // Read the cover image let coverImageID = book.metadata.findMetaByName("cover") if (coverImageID != nil && book.resources.containsById(coverImageID!)) { book.coverImage = book.resources.getById(coverImageID!) } // Read Spine book.spine = readSpine(xmlDoc.root["spine"].children) } } /** Read and parse the Table of Contents. */ private func findTableOfContents() -> [FRTocReference] { let ncxPath = resourcesBasePath.stringByAppendingPathComponent(book.ncxResource.href) let ncxData = NSData(contentsOfFile: ncxPath, options: .DataReadingMappedAlways, error: nil) var error: NSError? var tableOfContent = [FRTocReference]() if let xmlDoc = AEXMLDocument(xmlData: ncxData!, error: &error) { for item in xmlDoc.root["navMap"]["navPoint"].all! { tableOfContent.append(readTOCReference(item)) } } return tableOfContent } private func readTOCReference(navpointElement: AEXMLElement) -> FRTocReference { let label = navpointElement["navLabel"]["text"].value as String! let reference = navpointElement["content"].attributes["src"] as! String! let hrefSplit = split(reference) {$0 == "#"} let fragmentID = hrefSplit.count > 1 ? hrefSplit[1] : "" let href = hrefSplit[0] let resource = book.resources.getByHref(href) let toc = FRTocReference(title: label, resource: resource!, fragmentID: fragmentID) if navpointElement["navPoint"].all != nil { for navPoint in navpointElement["navPoint"].all! { toc.children.append(readTOCReference(navPoint)) } } return toc } /** Read and parse <metadata>. */ private func readMetadata(tags: [AEXMLElement]) -> FRMetadata { let metadata = FRMetadata() for tag in tags { if tag.name == "dc:title" { metadata.titles.append(tag.value!) } if tag.name == "dc:identifier" { metadata.identifiers.append(Identifier(scheme: tag.attributes["opf:scheme"] != nil ? tag.attributes["opf:scheme"] as! String : "", value: tag.value!)) } if tag.name == "dc:language" { metadata.language = tag.value != nil ? tag.value! : "" } if tag.name == "dc:creator" { metadata.creators.append(Author(name: tag.value!, role: tag.attributes["opf:role"] != nil ? tag.attributes["opf:role"] as! String : "", fileAs: tag.attributes["opf:file-as"] != nil ? tag.attributes["opf:file-as"] as! String : "")) } if tag.name == "dc:contributor" { metadata.creators.append(Author(name: tag.value!, role: tag.attributes["opf:role"] != nil ? tag.attributes["opf:role"] as! String : "", fileAs: tag.attributes["opf:file-as"] != nil ? tag.attributes["opf:file-as"] as! String : "")) } if tag.name == "dc:publisher" { metadata.publishers.append(tag.value != nil ? tag.value! : "") } if tag.name == "dc:description" { metadata.descriptions.append(tag.value != nil ? tag.value! : "") } if tag.name == "dc:subject" { metadata.subjects.append(tag.value != nil ? tag.value! : "") } if tag.name == "dc:rights" { metadata.rights.append(tag.value != nil ? tag.value! : "") } if tag.name == "dc:date" { metadata.dates.append(Date(date: tag.value!, event: tag.attributes["opf:event"] != nil ? tag.attributes["opf:event"] as! String : "")) } if tag.name == "meta" { if tag.attributes["name"] != nil { metadata.metaAttributes.append(Meta(name: tag.attributes["name"] as! String, content: (tag.attributes["content"] != nil ? tag.attributes["content"] as! String : ""))) } if tag.attributes["property"] != nil && tag.attributes["id"] != nil { metadata.metaAttributes.append(Meta(id: tag.attributes["id"] as! String, property: tag.attributes["property"] as! String, value: tag.value != nil ? tag.value! : "")) } } } return metadata } /** Read and parse <spine>. */ private func readSpine(tags: [AEXMLElement]) -> FRSpine { let spine = FRSpine() for tag in tags { let idref = tag.attributes["idref"] as! String var linear = true if tag.attributes["linear"] != nil { linear = tag.attributes["linear"] as! String == "yes" ? true : false } if book.resources.containsById(idref) { spine.spineReferences.append(Spine(resource: book.resources.getById(idref)!, linear: linear)) } } return spine } }
gpl-2.0
5c2cb838fda3c0971ac2064cc56e71f2
38.692308
246
0.567601
4.733945
false
false
false
false
jpush/jchat-swift
ContacterModule/Model/JCVerificationInfo.swift
1
806
// // JCVerificationInfo.swift // JChat // // Created by JIGUANG on 14/04/2017. // Copyright © 2017 HXHG. All rights reserved. // import UIKit enum JCVerificationType: Int { case wait case accept case reject case receive } class JCVerificationInfo: NSObject { var id = 0 var username: String = "" var nickname: String = "" var appkey: String = "" var resaon: String = "" var state: Int = 0 static func create(username: String, nickname: String?, appkey: String, resaon: String?, state: Int) -> JCVerificationInfo { let info = JCVerificationInfo() info.username = username info.nickname = nickname ?? "" info.appkey = appkey info.resaon = resaon ?? "" info.state = state return info } }
mit
cc32b7c27137ca8ced2e6685703750c9
20.756757
129
0.609938
3.833333
false
false
false
false
GTMYang/GTMRouter
GTMRouter/String+GTMRouter.swift
1
1486
// // String+GTMRouter.swift // GTMRouter // // Created by luoyang on 2016/12/19. // Copyright © 2016年 luoyang. All rights reserved. // import Foundation extension String { var intValue:Int { get { if let val = Int(self) { return val } return 0 } } var floatValue:Float { get { if let val = Float(self) { return val } return 0 } } var doubleValue:Double { get { if let val = Double(self) { return val } return 0 } } var boolValue:Bool { get { if let val = Bool(self) { return val } return false } } public var escaped: String { get { let legalURLCharactersToBeEscaped: CFString = ":&=;+!@#$()',*" as CFString return CFURLCreateStringByAddingPercentEscapes(nil, self as CFString, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String } } public func asURL() -> URL? { let utf8Str = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) guard let urlString = utf8Str, let url = URL(string: urlString) else { print("GTMRouter ---> 字符串转URL出错,请检查URL字符串") return nil } return url } }
mit
6b9283d6037375d3b67e090aae0ead89
22.885246
167
0.509266
4.840532
false
false
false
false
googleapis/google-auth-library-swift
Sources/OAuth2/PlatformNativeTokenProvider.swift
1
5495
// Copyright 2021 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if os(macOS) || os(iOS) import Dispatch import Foundation import AuthenticationServices public struct NativeCredentials: Codable, CodeExchangeInfo, RefreshExchangeInfo { let clientID: String let authorizeURL: String let accessTokenURL: String let callbackScheme: String enum CodingKeys: String, CodingKey { case clientID = "client_id" case authorizeURL = "authorize_url" case accessTokenURL = "access_token_url" case callbackScheme = "callback_scheme" } var redirectURI: String { callbackScheme + ":/oauth2redirect" } var clientSecret: String { "" } } @available(macOS 10.15.4, iOS 13.4, *) public class PlatformNativeTokenProvider: TokenProvider { private var credentials: NativeCredentials private var session: Session? public var token: Token? // for parity with BrowserTokenProvider public convenience init?(credentials: String, token tokenfile: String) { let path = ProcessInfo.processInfo.environment["HOME"]! + "/.credentials/" + credentials let url = URL(fileURLWithPath: path) guard let credentialsData = try? Data(contentsOf: url) else { print("No credentials data at \(path).") return nil } self.init(credentials: credentialsData, token: tokenfile) } public init?(credentials: Data, token tokenfile: String) { let decoder = JSONDecoder() guard let credentials = try? decoder.decode(NativeCredentials.self, from: credentials) else { print("Error reading credentials") return nil } self.credentials = credentials if tokenfile != "" { do { let data = try Data(contentsOf: URL(fileURLWithPath: tokenfile)) let decoder = JSONDecoder() guard let token = try? decoder.decode(Token.self, from: data) else { return nil } self.token = token } catch { // ignore errors due to missing token files } } } public func saveToken(_ filename: String) throws { if let token = token { try token.save(filename) } } public func refreshToken(_ filename: String) throws { if let token = token, token.isExpired() { self.token = try Refresh(token: token).exchange(info: credentials) try saveToken(filename) } } private struct Session { let webAuthSession: ASWebAuthenticationSession let webAuthContext: ASWebAuthenticationPresentationContextProviding } // The presentation context provides a reference to a UIWindow that the auth // framework uese to display the confirmation modal and sign in controller. public func signIn( scopes: [String], context: ASWebAuthenticationPresentationContextProviding, completion: @escaping (Token?, AuthError?) -> Void ) { let state = UUID().uuidString let scope = scopes.joined(separator: " ") var urlComponents = URLComponents(string: credentials.authorizeURL)! urlComponents.queryItems = [ URLQueryItem(name: "client_id", value: credentials.clientID), URLQueryItem(name: "response_type", value: "code"), URLQueryItem(name: "redirect_uri", value: credentials.redirectURI), URLQueryItem(name: "state", value: state), URLQueryItem(name: "scope", value: scope), ] let session = ASWebAuthenticationSession( url: urlComponents.url!, callbackURLScheme: credentials.callbackScheme ) { url, err in defer { self.session = nil } if let e = err { completion(nil, .webSession(inner: e)) return } guard let u = url else { // If err is nil, url should not be, and vice versa. completion(nil, .unknownError) return } let code = Code(urlComponents: URLComponents(string: u.absoluteString)!) do { self.token = try code.exchange(info: self.credentials) completion(self.token!, nil) } catch let ae as AuthError { completion(nil, ae) } catch { completion(nil, .unknownError) } } session.presentationContextProvider = context if !session.canStart { // This happens if the context provider is not set, or if the session has // already been started. We enforce correct usage so ignore. return } let success = session.start() if !success { // This doesn't happen unless the context is not set, disappears (it's a // weak ref internally), or the session was previously started, ignore. return } self.session = Session(webAuthSession: session, webAuthContext: context) } // Canceling the session dismisses the view controller if it is showing. public func cancelSignIn() { session?.webAuthSession.cancel() self.session = nil } public func withToken(_ callback: @escaping (Token?, Error?) -> Void) throws { callback(token, nil) } } #endif
apache-2.0
a2526ce4f8e0bbf045ba83851f088f79
31.514793
81
0.672793
4.556385
false
false
false
false
hulinSun/MyRx
MyRx/Pods/ManualLayout/ManualLayout/UIScrollView+ManualLayout.swift
2
1725
// // UIScrollView+ManualLayout.swift // ManualLayout // // Created by Baris Sencan on 06/03/15. // Copyright (c) 2015 Baris Sencan. All rights reserved. // import UIKit public extension UIScrollView { // MARK: - Content Size public var contentWidth: CGFloat { get { return contentSize.width } set { contentSize.width = snapToPixel(pointCoordinate: newValue) } } public var contentHeight: CGFloat { get { return contentSize.height } set { contentSize.height = snapToPixel(pointCoordinate: newValue) } } // MARK: - Content Edges (For Convenience) public var contentTop: CGFloat { return 0 } public var contentLeft: CGFloat { return 0 } public var contentBottom: CGFloat { get { return contentHeight } set { contentHeight = newValue } } public var contentRight: CGFloat { get { return contentWidth } set { contentWidth = newValue } } // MARK: - Viewport Edges public var viewportTop: CGFloat { get { return contentOffset.y } set { contentOffset.y = snapToPixel(pointCoordinate: newValue) } } public var viewportLeft: CGFloat { get { return contentOffset.x } set { contentOffset.x = snapToPixel(pointCoordinate: newValue) } } public var viewportBottom: CGFloat { get { return contentOffset.y + height } set { contentOffset.y = snapToPixel(pointCoordinate: newValue - height) } } public var viewportRight: CGFloat { get { return contentOffset.x + width } set { contentOffset.x = snapToPixel(pointCoordinate: newValue - width) } } }
mit
ea350279e4564358bba7dcc4d888209a
16.602041
71
0.621449
4.445876
false
false
false
false
bigtreenono/NSPTools
RayWenderlich/Introduction to Swift/6 . Control Flow/ChallengeControlFlow.playground/section-1.swift
1
274
for x in 1...100 { let multipleOf3 = x % 3 == 0 let multipleOf5 = x % 5 == 0 if (multipleOf3 && multipleOf5) { println("FizzBuzz") } else if (multipleOf3) { println("Fizz") } else if (multipleOf5) { println("Buzz") } else { println("\(x)") } }
mit
b8bb384f60916e8f6ea05a02b41ddca9
20.076923
35
0.551095
3.149425
false
false
false
false
silence0201/Swift-Study
Swifter/01Selector.playground/Contents.swift
1
1310
//: Playground - noun: a place where people can play import Foundation class MyObject: NSObject { func callMe() { } func callMeWithParm(obj: AnyObject) { } func trun(by angle: Int, speed: Float) { } func selecotrs() -> [Selector] { let someMethod = #selector(callMe) let anotherMethod = #selector(callMeWithParm(obj:)) let method = #selector(trun(by:speed:)) return [someMethod, anotherMethod, method] } func otherSelector() -> [Selector] { let someMethod = #selector(callMe) let anotherMethod = #selector(callMeWithParm) let method = #selector(trun) return [someMethod, anotherMethod, method] } func commonFunc() { } func commonFunc(input: Int) -> Int { return input } func sameNameSelector() -> [Selector] { let method1 = #selector(commonFunc as () -> Void) let method2 = #selector(commonFunc as (Int) -> Int) return [method1, method2] } } let selectors = MyObject().selecotrs() print(selectors) let otherSelectors = MyObject().otherSelector() print(otherSelectors) let sameNameSelectors = MyObject().sameNameSelector() print(sameNameSelectors)
mit
ad1f5d7712d063ed494339e7a4eb897b
21.982456
59
0.591603
4.253247
false
false
false
false
czechboy0/XcodeServerSDK
XcodeServerSDK/Server Entities/BotSchedule.swift
1
3428
// // BotSchedule.swift // XcodeServerSDK // // Created by Mateusz Zając on 13.06.2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation public class BotSchedule : XcodeServerEntity { public enum Schedule : Int { case Periodical = 1 case Commit case Manual public func toString() -> String { switch self { case .Periodical: return "Periodical" case .Commit: return "On Commit" case .Manual: return "Manual" } } } public enum Period : Int { case Hourly = 1 case Daily case Weekly } public enum Day : Int { case Monday = 1 case Tuesday case Wednesday case Thursday case Friday case Saturday case Sunday } public let schedule: Schedule! public let period: Period? public let day: Day! public let hours: Int! public let minutes: Int! public required init(json: NSDictionary) throws { let schedule = Schedule(rawValue: try json.intForKey("scheduleType"))! self.schedule = schedule if schedule == .Periodical { let period = Period(rawValue: try json.intForKey("periodicScheduleInterval"))! self.period = period let minutes = json.optionalIntForKey("minutesAfterHourToIntegrate") let hours = json.optionalIntForKey("hourOfIntegration") switch period { case .Hourly: self.minutes = minutes! self.hours = nil self.day = nil case .Daily: self.minutes = minutes! self.hours = hours! self.day = nil case .Weekly: self.minutes = minutes! self.hours = hours! self.day = Day(rawValue: try json.intForKey("weeklyScheduleDay")) } } else { self.period = nil self.minutes = nil self.hours = nil self.day = nil } try super.init(json: json) } private init(schedule: Schedule, period: Period?, day: Day?, hours: Int?, minutes: Int?) { self.schedule = schedule self.period = period self.day = day self.hours = hours self.minutes = minutes super.init() } public class func manualBotSchedule() -> BotSchedule { return BotSchedule(schedule: .Manual, period: nil, day: nil, hours: nil, minutes: nil) } public class func commitBotSchedule() -> BotSchedule { return BotSchedule(schedule: .Commit, period: nil, day: nil, hours: nil, minutes: nil) } public override func dictionarify() -> NSDictionary { let dictionary = NSMutableDictionary() dictionary["scheduleType"] = self.schedule.rawValue dictionary["periodicScheduleInterval"] = self.period?.rawValue ?? 0 dictionary["weeklyScheduleDay"] = self.day?.rawValue ?? 0 dictionary["hourOfIntegration"] = self.hours ?? 0 dictionary["minutesAfterHourToIntegrate"] = self.minutes ?? 0 return dictionary } }
mit
5309869eedefe38686d279eaa0c1a52d
26.637097
94
0.537069
5.121076
false
false
false
false
brentdax/swift
test/IRGen/sil_generic_witness_methods_objc.swift
2
1721
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -enable-objc-interop -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // FIXME: These should be SIL tests, but we can't parse generic types in SIL // yet. @objc protocol ObjC { func method() } // CHECK-LABEL: define hidden swiftcc void @"$s32sil_generic_witness_methods_objc05call_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T) {{.*}} { // CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(method)", align 8 // CHECK: [[CAST:%.*]] = bitcast %objc_object* %0 to [[SELFTYPE:%?.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[SELFTYPE]]*, i8*)*)([[SELFTYPE]]* [[CAST]], i8* [[SEL]]) func call_objc_method<T: ObjC>(_ x: T) { x.method() } // CHECK-LABEL: define hidden swiftcc void @"$s32sil_generic_witness_methods_objc05call_f1_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T) {{.*}} { // CHECK: call swiftcc void @"$s32sil_generic_witness_methods_objc05call_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T) func call_call_objc_method<T: ObjC>(_ x: T) { call_objc_method(x) } // CHECK-LABEL: define hidden swiftcc void @"$s32sil_generic_witness_methods_objc05call_E19_existential_method{{[_0-9a-zA-Z]*}}F"(%objc_object*) {{.*}} { // CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(method)", align 8 // CHECK: [[CAST:%.*]] = bitcast %objc_object* %0 to [[SELFTYPE:%?.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[SELFTYPE]]*, i8*)*)([[SELFTYPE]]* [[CAST]], i8* [[SEL]]) func call_objc_existential_method(_ x: ObjC) { x.method() }
apache-2.0
727f40bd2862012b785181136d982274
52.78125
181
0.616502
3.084229
false
false
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/ButtonSwitchNodeGroup.swift
1
2371
// // ButtonSwitchNodeGroup.swift // ComponentSelectorTest // // Created by James Bean on 10/8/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit public class ButtonSwitchNodeGroup { public var id: String = "" public var buttonSwitchNodes: [ButtonSwitchNode] = [] public var buttonSwitchNodeByID: [String : ButtonSwitchNode] = [:] public var leaderButtonSwitchNode: ButtonSwitchNodeLeader? public var stateByID: [String : ButtonSwitchNodeState] = [:] public var line = CAShapeLayer() // refine // view public var colorHue: CGFloat = 214 { didSet { for buttonSwitchNode in buttonSwitchNodes { buttonSwitchNode.colorHue = colorHue } } } public init(id: String) { self.id = id } public func updateStateByID() { for buttonSwitchNode in buttonSwitchNodes { if buttonSwitchNode.text == id { stateByID["performer"] = buttonSwitchNode.switch_state } else { stateByID[buttonSwitchNode.text] = buttonSwitchNode.switch_state } } } public func addButtonSwitchNode(buttonSwitchNode: ButtonSwitchNode) { if let leader = buttonSwitchNode as? ButtonSwitchNodeLeader { buttonSwitchNodes.insert(buttonSwitchNode, atIndex: 0) leaderButtonSwitchNode = leader } else { buttonSwitchNodes.append(buttonSwitchNode) } buttonSwitchNodeByID[buttonSwitchNode.id] = buttonSwitchNode } public func buttonSwitchNodeWithID(id: String, andText text: String, isLeader: Bool = false) { // TODO: non-hack width let buttonSwitchNode: ButtonSwitchNode switch isLeader { case true: buttonSwitchNode = ButtonSwitchNodeLeader(width: 50, text: text, id: id) case false: buttonSwitchNode = ButtonSwitchNode(width: 50, text: text, id: id) } addButtonSwitchNode(buttonSwitchNode) } public func stateHasChangedFromLeaderButtonSwitchNode( leaderButtonSwitchNode: ButtonSwitchNodeLeader ) { // something } public func stateHasChangedFromFollowerButtonSwitchNode( followerButtonSwitchNode: ButtonSwitchNode ) { // something } }
gpl-2.0
4ce490d651ee23c50b3bbd4836687a65
29
98
0.635865
5.386364
false
false
false
false
InsectQY/HelloSVU_Swift
HelloSVU_Swift/Classes/Module/Map/Route/Main/Controller/RoutePageViewController.swift
1
3540
// // RoutePageViewController.swift // HelloSVU_Swift // // Created by Insect on 2017/10/3. //Copyright © 2017年 Insect. All rights reserved. // import UIKit let kTitleViewH: CGFloat = 30 class RoutePageViewController: BaseViewController { @IBOutlet private weak var originField: UITextField! @IBOutlet private weak var destinationField: UITextField! private lazy var originPoint = AMapGeoPoint() private lazy var destinationPoint = AMapGeoPoint() // MARK: - LazyLoad private lazy var pageView: QYPageView = { let style = QYPageStyle() style.normalColor = UIColor(r: 255, g: 255, b: 255) style.selectColor = UIColor(r: 255, g: 255, b: 255) style.titleViewHeight = kTitleViewH style.bottomLineHeight = 2 var childVcs = [UIViewController]() let vc = BusRouteViewController() childVcs.append(vc) let routeType: [routePlanType] = [.Walking,.Riding,.Driving] for type in routeType { let vc = BasePlanViewController() vc.routePlanType = type childVcs.append(vc) } let pageView = QYPageView(frame: CGRect(x: 0, y: 115, width: ScreenW, height: ScreenH - 115), titles: ["公交","步行","骑行","驾车"], titleStyle: style, childVcs: childVcs, parentVc: self) pageView.backgroundColor = UIColor(r: 74, g: 137, b: 255) return pageView }() // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() setUpUI() } } // MARK: - 设置 UI 界面 extension RoutePageViewController { private func setUpUI() { fd_prefersNavigationBarHidden = true view.addSubview(pageView) } // MARK: - 返回按钮点击事件 @IBAction func backBtnDidClick(_ sender: Any) { navigationController?.popViewController(animated: true) } } // MARK: - UITextFieldDelegate extension RoutePageViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { let searchVc = MapSearchViewController() if textField == originField { searchVc.searchBarText = "请输入起点" searchVc.poiSuggestion = {[weak self] (poi) in self?.originField.text = poi.name if let originPoint = poi.location { self?.originPoint = originPoint } self?.chooseNavType() } }else { searchVc.searchBarText = "请输入终点" searchVc.poiSuggestion = {[weak self] (poi) in self?.destinationField.text = poi.name if let destinationPoint = poi.location { self?.destinationPoint = destinationPoint } self?.chooseNavType() } } navigationController?.pushViewController(searchVc, animated: true) } } // MARK: - 事件处理 extension RoutePageViewController { private func chooseNavType() { if destinationField.text == "请输入终点" {return} startBusRoute() } private func startBusRoute() { let vc = childViewControllers[0] as! BusRouteViewController vc.searchRoutePlanningBus(0, originPoint, destinationPoint,(originField.text ?? ""),(destinationField.text ?? "")) } }
apache-2.0
96f90f0e8f0b718c56c28ec6a548dd78
28.067227
187
0.585718
4.955587
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Jetpack/Jetpack Scan/JetpackScanThreatDetailsViewController.swift
2
10638
import UIKit import WordPressFlux protocol JetpackScanThreatDetailsViewControllerDelegate: AnyObject { func willFixThreat(_ threat: JetpackScanThreat, controller: JetpackScanThreatDetailsViewController) func willIgnoreThreat(_ threat: JetpackScanThreat, controller: JetpackScanThreatDetailsViewController) } class JetpackScanThreatDetailsViewController: UIViewController { // MARK: - IBOutlets /// General info @IBOutlet private weak var generalInfoStackView: UIStackView! @IBOutlet private weak var icon: UIImageView! @IBOutlet private weak var generalInfoTitleLabel: UILabel! @IBOutlet private weak var generalInfoDescriptionLabel: UILabel! /// Problem @IBOutlet private weak var problemStackView: UIStackView! @IBOutlet private weak var problemTitleLabel: UILabel! @IBOutlet private weak var problemDescriptionLabel: UILabel! /// Technical details @IBOutlet private weak var technicalDetailsStackView: UIStackView! @IBOutlet private weak var technicalDetailsTitleLabel: UILabel! @IBOutlet private weak var technicalDetailsDescriptionLabel: UILabel! @IBOutlet private weak var technicalDetailsFileContainerView: UIView! @IBOutlet private weak var technicalDetailsFileLabel: UILabel! @IBOutlet private weak var technicalDetailsContextLabel: UILabel! /// Fix @IBOutlet private weak var fixStackView: UIStackView! @IBOutlet private weak var fixTitleLabel: UILabel! @IBOutlet private weak var fixDescriptionLabel: UILabel! /// Buttons @IBOutlet private weak var buttonsStackView: UIStackView! @IBOutlet private weak var fixThreatButton: FancyButton! @IBOutlet private weak var ignoreThreatButton: FancyButton! @IBOutlet private weak var warningButton: MultilineButton! @IBOutlet weak var ignoreActivityIndicatorView: UIActivityIndicatorView! // MARK: - Properties weak var delegate: JetpackScanThreatDetailsViewControllerDelegate? private let blog: Blog private let threat: JetpackScanThreat private let hasValidCredentials: Bool private lazy var viewModel: JetpackScanThreatViewModel = { return JetpackScanThreatViewModel(threat: threat, hasValidCredentials: hasValidCredentials) }() // MARK: - Init init(blog: Blog, threat: JetpackScanThreat, hasValidCredentials: Bool = false) { self.blog = blog self.threat = threat self.hasValidCredentials = hasValidCredentials super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() title = Strings.title configure(with: viewModel) } // MARK: - IBActions @IBAction private func fixThreatButtonTapped(_ sender: Any) { let alert = UIAlertController(title: viewModel.fixActionTitle, message: viewModel.fixDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.cancel, style: .cancel)) alert.addAction(UIAlertAction(title: Strings.ok, style: .default, handler: { [weak self] _ in guard let self = self else { return } self.delegate?.willFixThreat(self.threat, controller: self) self.trackEvent(.jetpackScanThreatFixTapped) })) present(alert, animated: true) trackEvent(.jetpackScanFixThreatDialogOpen) } @IBAction private func ignoreThreatButtonTapped(_ sender: Any) { guard let blogName = blog.settings?.name else { return } let alert = UIAlertController(title: viewModel.ignoreActionTitle, message: String(format: viewModel.ignoreActionMessage, blogName), preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.cancel, style: .cancel)) alert.addAction(UIAlertAction(title: Strings.ok, style: .default, handler: { [weak self] _ in guard let self = self else { return } self.ignoreThreatButton.isHidden = true self.ignoreActivityIndicatorView.startAnimating() self.delegate?.willIgnoreThreat(self.threat, controller: self) self.trackEvent(.jetpackScanThreatIgnoreTapped) })) present(alert, animated: true) trackEvent(.jetpackScanIgnoreThreatDialogOpen) } @IBAction func warningButtonTapped(_ sender: Any) { guard let siteID = blog.dotComID as? Int, let controller = JetpackWebViewControllerFactory.settingsController(siteID: siteID) else { displayNotice(title: Strings.jetpackSettingsNotice) return } let navVC = UINavigationController(rootViewController: controller) present(navVC, animated: true) } // MARK: - Private private func trackEvent(_ event: WPAnalyticsEvent) { WPAnalytics.track(event, properties: ["threat_signature": threat.signature]) } } extension JetpackScanThreatDetailsViewController { // MARK: - Configure func configure(with viewModel: JetpackScanThreatViewModel) { icon.image = viewModel.detailIconImage icon.tintColor = viewModel.detailIconImageColor generalInfoTitleLabel.text = viewModel.title generalInfoDescriptionLabel.text = viewModel.description problemTitleLabel.text = viewModel.problemTitle problemDescriptionLabel.text = viewModel.problemDescription if let attributedFileContext = self.viewModel.attributedFileContext { technicalDetailsTitleLabel.text = viewModel.technicalDetailsTitle technicalDetailsDescriptionLabel.text = viewModel.technicalDetailsDescription technicalDetailsFileLabel.text = viewModel.fileName technicalDetailsContextLabel.attributedText = attributedFileContext technicalDetailsStackView.isHidden = false } else { technicalDetailsStackView.isHidden = true } fixTitleLabel.text = viewModel.fixTitle fixDescriptionLabel.text = viewModel.fixDescription if let fixActionTitle = viewModel.fixActionTitle { fixThreatButton.setTitle(fixActionTitle, for: .normal) fixThreatButton.isEnabled = viewModel.fixActionEnabled fixThreatButton.isHidden = false } else { fixThreatButton.isHidden = true } if let ignoreActionTitle = viewModel.ignoreActionTitle { ignoreThreatButton.setTitle(ignoreActionTitle, for: .normal) ignoreThreatButton.isHidden = false } else { ignoreThreatButton.isHidden = true } if let warningActionTitle = viewModel.warningActionTitle { let attributedTitle = WPStyleGuide.Jetpack.highlightString(warningActionTitle.substring, inString: warningActionTitle.string) warningButton.setAttributedTitle(attributedTitle, for: .normal) warningButton.isHidden = false } else { warningButton.isHidden = true } applyStyles() } // MARK: - Styling private func applyStyles() { view.backgroundColor = .basicBackground styleGeneralInfoSection() styleProblemSection() styleTechnicalDetailsSection() styleFixSection() styleButtons() } private func styleGeneralInfoSection() { generalInfoTitleLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) generalInfoTitleLabel.textColor = .error generalInfoTitleLabel.numberOfLines = 0 generalInfoDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.body) generalInfoDescriptionLabel.textColor = .text generalInfoDescriptionLabel.numberOfLines = 0 } private func styleProblemSection() { problemTitleLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) problemTitleLabel.textColor = .text problemTitleLabel.numberOfLines = 0 problemDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.body) problemDescriptionLabel.textColor = .text problemDescriptionLabel.numberOfLines = 0 } private func styleTechnicalDetailsSection() { technicalDetailsTitleLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) technicalDetailsTitleLabel.textColor = .text technicalDetailsTitleLabel.numberOfLines = 0 technicalDetailsFileContainerView.backgroundColor = viewModel.fileNameBackgroundColor technicalDetailsFileLabel.font = viewModel.fileNameFont technicalDetailsFileLabel.textColor = viewModel.fileNameColor technicalDetailsFileLabel.numberOfLines = 0 technicalDetailsDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.body) technicalDetailsDescriptionLabel.textColor = .text technicalDetailsDescriptionLabel.numberOfLines = 0 technicalDetailsContextLabel.numberOfLines = 0 } private func styleFixSection() { fixTitleLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) fixTitleLabel.textColor = .text fixTitleLabel.numberOfLines = 0 fixDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.body) fixDescriptionLabel.textColor = .text fixDescriptionLabel.numberOfLines = 0 } private func styleButtons() { fixThreatButton.isPrimary = true ignoreThreatButton.isPrimary = false warningButton.setTitleColor(.text, for: .normal) warningButton.titleLabel?.lineBreakMode = .byWordWrapping warningButton.titleLabel?.numberOfLines = 0 warningButton.setImage(.gridicon(.plusSmall), for: .normal) } } extension JetpackScanThreatDetailsViewController { private enum Strings { static let title = NSLocalizedString("Threat details", comment: "Title for the Jetpack Scan Threat Details screen") static let ok = NSLocalizedString("OK", comment: "OK button for alert") static let cancel = NSLocalizedString("Cancel", comment: "Cancel button for alert") static let jetpackSettingsNotice = NSLocalizedString("Unable to visit Jetpack settings for site", comment: "Message displayed when visiting the Jetpack settings page fails.") } }
gpl-2.0
be949b9d5f14d93edda203782a1f88a7
36.992857
182
0.696183
5.890365
false
false
false
false
LiquidAnalytics/ld-api-examples
ios/LPKTutorialOne-Swift/LPKTutorialOne-Swift/ViewController.swift
1
3373
// // ViewController.swift // LPKTutorialOne-Swift // // Created by CARSON LI on 2016-06-30. // Copyright © 2016 Liquid Analytics. All rights reserved. // import UIKit import LiquidPlatformKit class ViewController: UIViewController, LSCSeasideApplicationDelegate { @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var progressBar: UIProgressView! @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var infoLabel: UILabel! @IBOutlet weak var dummyButton: UIButton! var loginCallback: ((String, String) -> Void)? override func viewDidLoad() { super.viewDidLoad() self.dummyButton.hidden = true self.infoLabel.text = "" self.progressBar.progress = 0.0 self.progressBar.hidden = true //load the DB in the background, typically there is a loading screen that goes here //so we don't block the main thread LDMDataManager.sharedInstance().executeAsynch { LDMDataManager.sharedInstance().openDatabaseWithName("MovieCollection") LSCSyncController.sharedInstance().startWithDelegate(self); if let deviceId = NSUserDefaults.standardUserDefaults().objectForKey("seasideCustomDeviceId") { print(deviceId) } self.loginButton.enabled = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginButtonPressed() { self.loginButton.enabled = false self.usernameField.enabled = false self.passwordField.enabled = false self.progressBar.hidden = false LDMDataManager.sharedInstance().executeAsynch { if let username = self.usernameField.text { if let password = self.passwordField.text { self.loginCallback!(username, password) } } } } func updateLoginStatusLabel(status: String?, enable: Bool) { dispatch_async(dispatch_get_main_queue()) { self.infoLabel.text = status; } } func authenticateWithMessage(message: String?, userEditable: Bool, providePasscode: Bool, callback: ((String, String) -> Void)?) { self.loginCallback = callback; dispatch_async(dispatch_get_main_queue()) { self.loginButton.enabled = true self.usernameField.enabled = true self.passwordField.enabled = true self.passwordField.text = ""; self.infoLabel.text = message; } } func registeringWithMessage(message: String?, syncingData: Bool, syncProgress: Float) { dispatch_async(dispatch_get_main_queue()) { self.infoLabel.text = message; self.progressBar.progress = syncProgress; } } func selectCommunity() { LSCSyncController.sharedInstance().communitySelected("MovieCollection"); } func registered() { dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier("showMovieSegue", sender: nil) } } }
apache-2.0
6338207ccd231abc2d9560341ab1335b
31.114286
134
0.614769
5.109091
false
false
false
false
nalexn/ViewInspector
Tests/ViewInspectorTests/ViewModifiers/TextInputModifiersTests.swift
1
6523
import XCTest import SwiftUI @testable import ViewInspector // MARK: - TextInputModifiersTests @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) final class TextInputModifiersTests: XCTestCase { #if os(iOS) || os(tvOS) || os(watchOS) func testTextContentType() throws { let sut = EmptyView().textContentType(.emailAddress) XCTAssertNoThrow(try sut.inspect().emptyView()) } #endif #if (os(iOS) || os(tvOS)) && !targetEnvironment(macCatalyst) func testTextContentTypeInspection() throws { let sut = AnyView(EmptyView()).textContentType(.emailAddress) XCTAssertEqual(try sut.inspect().anyView().textContentType(), .emailAddress) XCTAssertEqual(try sut.inspect().anyView().emptyView().textContentType(), .emailAddress) } #endif #if (os(iOS) || os(tvOS)) && !targetEnvironment(macCatalyst) func testKeyboardType() throws { let sut = EmptyView().keyboardType(.namePhonePad) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testKeyboardTypeInspection() throws { let sut = AnyView(EmptyView()).keyboardType(.namePhonePad) XCTAssertEqual(try sut.inspect().anyView().keyboardType(), .namePhonePad) XCTAssertEqual(try sut.inspect().anyView().emptyView().keyboardType(), .namePhonePad) } func testAutocapitalization() throws { let sut = EmptyView().autocapitalization(.words) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testAutocapitalizationInspection() throws { let sut = AnyView(EmptyView()).autocapitalization(.words) XCTAssertEqual(try sut.inspect().anyView().autocapitalization(), .words) XCTAssertEqual(try sut.inspect().anyView().emptyView().autocapitalization(), .words) } #endif func testFont() throws { let sut = EmptyView().font(.body) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testFontInspection() throws { let sut = AnyView(EmptyView()).font(.largeTitle) XCTAssertEqual(try sut.inspect().anyView().font(), .largeTitle) XCTAssertEqual(try sut.inspect().anyView().emptyView().font(), .largeTitle) } func testTextFontOverrideWithNativeModifier() throws { let sut = Group { Text("test").font(.callout) }.font(.footnote) let group = try sut.inspect().group() XCTAssertEqual(try group.font(), .footnote) XCTAssertThrows(try EmptyView().inspect().font(), "EmptyView does not have 'font' modifier") XCTAssertEqual(try group.text(0).attributes().font(), .callout) } func testTextFontOverrideWithInnerModifier() throws { let sut = AnyView(AnyView(Text("test")).font(.footnote)).font(.callout) let text = try sut.inspect().find(text: "test") XCTAssertEqual(try text.attributes().font(), .footnote) } func testLineLimit() throws { let sut = EmptyView().lineLimit(5) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testLineLimitInspection() throws { let sut = AnyView(EmptyView()).lineLimit(5) XCTAssertEqual(try sut.inspect().anyView().lineLimit(), 5) XCTAssertEqual(try sut.inspect().anyView().emptyView().lineLimit(), 5) } func testLineSpacing() throws { let sut = EmptyView().lineSpacing(5) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testLineSpacingInspection() throws { let sut = AnyView(EmptyView()).lineSpacing(4) XCTAssertEqual(try sut.inspect().anyView().lineSpacing(), 4) XCTAssertEqual(try sut.inspect().anyView().emptyView().lineSpacing(), 4) } func testMultilineTextAlignment() throws { let sut = EmptyView().multilineTextAlignment(.center) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testMultilineTextAlignmentInspection() throws { let sut = AnyView(EmptyView()).multilineTextAlignment(.center) XCTAssertEqual(try sut.inspect().anyView().multilineTextAlignment(), .center) XCTAssertEqual(try sut.inspect().anyView().emptyView().multilineTextAlignment(), .center) } func testMinimumScaleFactor() throws { let sut = EmptyView().minimumScaleFactor(5) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testMinimumScaleFactorInspection() throws { let sut = AnyView(EmptyView()).minimumScaleFactor(2) XCTAssertEqual(try sut.inspect().anyView().minimumScaleFactor(), 2) XCTAssertEqual(try sut.inspect().anyView().emptyView().minimumScaleFactor(), 2) } func testTruncationMode() throws { let sut = EmptyView().truncationMode(.tail) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testTruncationModeInspection() throws { let sut = AnyView(EmptyView()).truncationMode(.tail) XCTAssertEqual(try sut.inspect().anyView().truncationMode(), .tail) XCTAssertEqual(try sut.inspect().anyView().emptyView().truncationMode(), .tail) } func testAllowsTightening() throws { let sut = EmptyView().allowsTightening(true) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testAllowsTighteningInspection() throws { let sut = AnyView(EmptyView()).allowsTightening(true) XCTAssertTrue(try sut.inspect().anyView().allowsTightening()) XCTAssertTrue(try sut.inspect().anyView().emptyView().allowsTightening()) } #if !os(watchOS) func testDisableAutocorrection() throws { let sut = EmptyView().disableAutocorrection(false) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testDisableAutocorrectionInspection() throws { let sut = AnyView(EmptyView()).disableAutocorrection(false) XCTAssertEqual(try sut.inspect().anyView().disableAutocorrection(), false) XCTAssertEqual(try sut.inspect().anyView().emptyView().disableAutocorrection(), false) } #endif func testFlipsForRightToLeftLayoutDirection() throws { let sut = EmptyView().flipsForRightToLeftLayoutDirection(true) XCTAssertNoThrow(try sut.inspect().emptyView()) } func testFlipsForRightToLeftLayoutDirectionInspection() throws { let sut = EmptyView().flipsForRightToLeftLayoutDirection(true) XCTAssertEqual(try sut.inspect().emptyView().flipsForRightToLeftLayoutDirection(), true) } }
mit
99386de20c52c611209d3aa7708c4a08
39.018405
97
0.663958
5.205906
false
true
false
false
sunyit-ncsclub/Poly-tool
Poly Tool/PolyMenuController.swift
1
9204
// Created by Joe on 12/8/14. // Copyright (c) 2014 Joe Pasqualetti. All rights reserved. import UIKit let PolyMenuCellIdentifier = "PolyMenuCellIdentifier" let PolyMenuHeaderIdentifier = "PolyMenuHeaderIdentifier" let RefreshDisplayMessage = "Pull to Refresh" let RefreshCommandDisplayValue = "refresh" let SectionNameKey = "name" let MenuItemKey = "items" let MenuLocationKey = "locations" enum PolyCampusIndex :Int { case Albany = 0 case Utica = 1 } typealias CampusMenuItem = (key: String, value: String) typealias PolyCampusMenus = [[String : AnyObject]] class PolyMenuController: UICollectionViewController { var refreshControl: UIRefreshControl var backgroundImage: UIImageView var selectedCell: MenuItemCollectionViewCell? required init(coder aDecoder: NSCoder) { items = [] backgroundImage = UIImageView() refreshControl = UIRefreshControl() refreshControl.tintColor = Theme.highlightPrimary super.init(coder: aDecoder) } var items: PolyCampusMenus override func viewDidLoad() { if let c = collectionView { c.addSubview(refreshControl) c.backgroundColor = Theme.backgroundPrimary.colorWithAlphaComponent(0.60) c.alwaysBounceVertical = true } refreshControl.beginRefreshing() refreshControl.addTarget(self, action: "requestData", forControlEvents: .ValueChanged) requestData() view.backgroundColor = Theme.backgroundPrimary } func loadMenu(menuItems: JSON, time: NSDate) { if let campusMenu = menuItems as? PolyCampusMenus { self.items = menuItems as! PolyCampusMenus } else { println(menuItems) NetworkModel.invalidate("index.json") return toast("Found invalidate data. Sorry!", duration: 5.0) } if menuItems.count == 0 { refreshControl.endRefreshing() NetworkModel.invalidate("index.json") return toast("No data downloaded. Sorry!", duration: 5.0) } clearToast() collectionView?.reloadData() /* Format Last Refresh Date */ var f = NSDateFormatter() f.doesRelativeDateFormatting = true f.timeStyle = NSDateFormatterStyle.ShortStyle refreshControl.attributedTitle = NSAttributedString(string: "Last updated \(f.stringFromDate(time))") refreshControl.endRefreshing() } override func viewDidAppear(animated: Bool) { UIView.animateWithDuration(0.175, animations: { () -> Void in if let cell = self.selectedCell { cell.unhighlight() } }) } func failedMenuLoad(error: NSError, time: NSDate) { clearToast() items = [["name" : "Error Downloading…", "items" : [RefreshDisplayMessage], "locations" : [RefreshCommandDisplayValue] ]] as PolyCampusMenus // TODO offer a way to re-try downloads without closing the app. if let msg = error.localizedFailureReason { items = [["name" : "Error Downloading…", "items" : [RefreshDisplayMessage, msg], "locations" : [RefreshCommandDisplayValue, RefreshCommandDisplayValue] ]] as PolyCampusMenus } collectionView?.reloadData() println("Encountered error: \(error) at time \(time)") NetworkModel.invalidate("index.json") } func requestData() { refreshControl.beginRefreshing() NetworkModel.sendRelativeRequest(self.loadMenu, appendage:"index.json", failure: self.failedMenuLoad) } func reload(regions: Array<Dictionary<String, AnyObject>>) { collectionView?.reloadData() } func menuItem(path: NSIndexPath) -> String { if let i = items[path.section][MenuItemKey] as? Array<String> { return i[path.row] } else { return "Undetermined" } } func menuValue(path: NSIndexPath) -> String { if let i = items[path.section][MenuLocationKey] as? Array<String> { return i[path.row] } else { return "Undetermined" } } func itemTuple(path: NSIndexPath) -> CampusMenuItem { if let i = items[path.section][MenuItemKey] as? Array<String> { let item = i[path.row] if let location = items[path.section][MenuLocationKey] as? Array<String> { let value = location[path.row] return CampusMenuItem(item, value) } } return CampusMenuItem("Undetermined", "Undetermined") } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier(PolyMenuCellIdentifier, forIndexPath: indexPath) as! MenuItemCollectionViewCell cell.prepareForReuse() cell.textLabel?.textColor = Theme.textColor let menu = menuItem(indexPath) cell.textLabel?.text = menu cell.selectedBackgroundView = UIView() return cell } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let itemArray = items[section][MenuItemKey] as? Array<String> { return itemArray.count } else { return 0 } } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { var header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: PolyMenuHeaderIdentifier, forIndexPath: indexPath) as! UICollectionReusableView let section = indexPath.section if header.subviews.count == 0 { let labelFrame = CGRectInset(header.bounds, 10, 0) let label = UILabel(frame: labelFrame) label.font = UIFont.boldSystemFontOfSize(UIFont.systemFontSize() + 2) header.addSubview(label) header.bringSubviewToFront(label) } header.backgroundColor = Theme.subduedBackground if let label = header.subviews[0] as? UILabel { label.textColor = Theme.highlightPrimary if let section = items[indexPath.section][SectionNameKey] as? String { label.text = section } } return header } override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return items.count } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var indexPath: NSIndexPath if let cell = sender as? MenuItemCollectionViewCell { let indexPath = collectionView?.indexPathForCell(cell) as NSIndexPath! let campusLookup = PolyCampusIndex(rawValue: indexPath.section) let item = itemTuple(indexPath) if let nav = segue.destinationViewController as? UINavigationController { if let detail = nav.topViewController as? DetailWebController { if let url = NSURL(string: item.value) { detail.destination = url detail.title = item.key } } } } else { println("Could not set up segue with sender \(sender)") return } } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? MenuItemCollectionViewCell { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { selectedCell = cell.highlight() } else { cell.highlight() UIView.animateWithDuration(0.3, delay: 0.4, options: .TransitionNone, animations: { () -> Void in cell.unhighlight() return }, completion: { (complete: Bool) -> Void in }) } } } override func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) { if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? MenuItemCollectionViewCell { cell.highlight() } } override func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) { if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? MenuItemCollectionViewCell { cell.unhighlight() selectedCell = nil } } /** Side-step segues for contact and club views. */ override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { let cell = collectionView.cellForItemAtIndexPath(indexPath) let menu = itemTuple(indexPath) var campus: PolyCampusIndex if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? MenuItemCollectionViewCell { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { selectedCell = cell.highlight() } else { cell.highlight() UIView.animateWithDuration(0.3, delay: 0.4, options: .TransitionNone, animations: { () -> Void in cell.unhighlight() return }, completion: { (complete: Bool) -> Void in }) } } if menu.value.lastPathComponent == "contact-index.json" { let contacts = storyboard?.instantiateViewControllerWithIdentifier(ContactsControllerIdentifier) as! ContactsController contacts.destination = menu.value contacts.title = menu.key let nav = UINavigationController(rootViewController: contacts) showDetailViewController(nav, sender: self) return false } else if menu.value.lastPathComponent == "club-index.json" { let clubs = storyboard?.instantiateViewControllerWithIdentifier(ClubsControllerIdentifier) as! ClubsController clubs.destination = menu.value clubs.title = menu.key let nav = UINavigationController(rootViewController: clubs) showDetailViewController(nav, sender: self) return false } else if menu.value == RefreshCommandDisplayValue { requestData() return false } else { return true } } }
mit
bc9a2c9ba92ba2a406e35f77da6d0468
30.724138
177
0.741522
4.255319
false
false
false
false
modum-io/ios_client
PharmaSupplyChain/CodeScannerViewController.swift
1
11313
// // QRScanner.swift // PharmaSupplyChain // // Created by Yury Belevskiy on 27.11.16. // Copyright © 2016 Modum. All rights reserved. // import AVFoundation import UIKit class CodeScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { // MARK: Properties fileprivate var captureSession: AVCaptureSession? fileprivate var videoPreviewLayer: AVCaptureVideoPreviewLayer? fileprivate var isSensorMACDiscovered: Bool = false fileprivate var sensorMACAddress: String? fileprivate var isContractIDDiscovered: Bool = false fileprivate var contractID: String? /* Determines which codes to scan based on this flag: If set 'true', user has to only scan contract ID If set 'false', user has to scan contract ID and QR code on the sensor */ var isReceivingParcel: Bool = false // MARK: Outlets @IBOutlet weak fileprivate var infoLabel: UILabel! @IBOutlet weak fileprivate var typeOfCodeIcon: UIImageView! override func viewDidLoad() { super.viewDidLoad() /* checking user permissions for the camera */ let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) switch authStatus { case .authorized: initialize() case .denied, .restricted: showCameraNotAvailableAlert() case .notDetermined: AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { granted in DispatchQueue.main.async { [weak self] in if let codeScannerViewController = self { if granted { codeScannerViewController.initialize() } else { codeScannerViewController.showCameraNotAvailableAlert() } } } }) } } // MARK: AVCaptureMetadataOutputObjectsDelegate func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { if !metadataObjects.isEmpty { let metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject if metadataObject.type == AVMetadataObjectTypeQRCode, !isSensorMACDiscovered && !isReceivingParcel { if metadataObject.stringValue != nil && !isSensorMACDiscovered { if isValidMacAddress(metadataObject.stringValue) { isSensorMACDiscovered = true /* Separator symbols, ':', are removed from MAC address because advertised Bluetooth name of the sensor doesn't contain them */ sensorMACAddress = metadataObject.stringValue.removeNonHexSymbols() if isContractIDDiscovered { performSegue(withIdentifier: "goToParcelCreate", sender: self) } else { UIView.transition(with: infoLabel, duration: 1.0, options: [.curveEaseInOut, .transitionFlipFromRight], animations: { [weak self] in if let codeScannerController = self { codeScannerController.infoLabel.text = "Please, scan Track&Trace number" } }, completion: nil) UIView.transition(with: typeOfCodeIcon, duration: 1.0, options: [.curveEaseInOut, .transitionFlipFromRight], animations: { [weak self] in if let codeScannerController = self { codeScannerController.typeOfCodeIcon.image = UIImage(named: "barcode") } }, completion: nil) } } } } else if metadataObject.type == AVMetadataObjectTypeCode128Code, !isContractIDDiscovered { if metadataObject.stringValue != nil && !isContractIDDiscovered { isContractIDDiscovered = true contractID = metadataObject.stringValue if isReceivingParcel { performSegue(withIdentifier: "goToParcelReceive", sender: self) } else { if isSensorMACDiscovered { performSegue(withIdentifier: "goToParcelCreate", sender: self) } else { UIView.transition(with: infoLabel, duration: 1.0, options: [.curveEaseInOut, .transitionFlipFromRight], animations: { [weak self] in if let codeScannerController = self { codeScannerController.infoLabel.text = "Please, scan QR code on the sensor" } }, completion: nil) UIView.transition(with: typeOfCodeIcon, duration: 1.0, options: [.curveEaseInOut, .transitionFlipFromRight], animations: { [weak self] in if let codeScannerController = self { codeScannerController.typeOfCodeIcon.image = UIImage(named: "qr_code") } }, completion: nil) } } } } } } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let parcelCreateViewController = segue.destination as? ParcelCreateViewController { parcelCreateViewController.sensorMAC = sensorMACAddress parcelCreateViewController.tntNumber = contractID } else if let parcelReceiveViewController = segue.destination as? ParcelReceiveViewController { parcelReceiveViewController.tntNumber = contractID } } // MARK: Helper functions fileprivate func initialize() { /* instantiating video capture */ let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) var captureInput: AVCaptureInput? if let captureDevice = captureDevice { do { captureInput = try AVCaptureDeviceInput(device: captureDevice) } catch { log("Failed to instantiate AVCaptureInput with \(error.localizedDescription)") return } /* adding video camera as input */ captureSession = AVCaptureSession() if let captureSession = captureSession, let captureInput = captureInput { captureSession.addInput(captureInput) } let captureMetadataOutput = AVCaptureMetadataOutput() if let captureSession = captureSession { captureSession.addOutput(captureMetadataOutput) } captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode128Code] /* initialize video preview layer */ videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer?.frame = view.layer.bounds view.layer.addSublayer(videoPreviewLayer!) captureSession?.startRunning() view.bringSubview(toFront: infoLabel) } /* UI configuration */ /* adding gradient backgroud */ let leftColor = TEMPERATURE_LIGHT_BLUE.cgColor let middleColor = ROSE_COLOR.cgColor let rightColor = LIGHT_BLUE_COLOR.cgColor let gradientLayer = CAGradientLayer() gradientLayer.frame = view.bounds gradientLayer.colors = [leftColor, middleColor, rightColor] gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0) gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0) view.layer.insertSublayer(gradientLayer, at: 0) /* adding transparent overlay */ let overlayPath = UIBezierPath(rect: view.bounds) var transparentHole: UIBezierPath! if getDeviceScreenSize() == .small { transparentHole = UIBezierPath(rect: CGRect(x: 0, y: view.bounds.height/2.0 - 50.0, width: view.bounds.width, height: 200.0)) } else { transparentHole = UIBezierPath(rect: CGRect(x: 0, y: view.bounds.height/2.0 - 100.0, width: view.bounds.width, height: 300.0)) } overlayPath.append(transparentHole) overlayPath.usesEvenOddFillRule = true let fillLayer = CAShapeLayer() fillLayer.path = overlayPath.cgPath fillLayer.fillRule = kCAFillRuleEvenOdd fillLayer.fillColor = UIColor.black.withAlphaComponent(0.5).cgColor view.layer.addSublayer(fillLayer) view.bringSubview(toFront: infoLabel) view.bringSubview(toFront: typeOfCodeIcon) if isReceivingParcel { infoLabel.text = "Please, scan Track&Trace number" typeOfCodeIcon.image = UIImage(named: "barcode") } else { infoLabel.text = "Please, scan QR code on the sensor" typeOfCodeIcon.image = UIImage(named: "qr_code") } } fileprivate func showCameraNotAvailableAlert() { let cameraNotAvailableAlertController = UIAlertController(title: "Camera isn't avaialable", message: "Please, set \"Camera\" to \"On\"", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { [weak self] _ in if let codeScannerViewController = self { cameraNotAvailableAlertController.dismiss(animated: true, completion: nil) _ = codeScannerViewController.navigationController?.popToRootViewController(animated: true) } }) let goToSettingsAction = UIAlertAction(title: "Settings", style: .default, handler: { _ in if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.open(settingsURL, completionHandler: nil) } }) cameraNotAvailableAlertController.addAction(goToSettingsAction) cameraNotAvailableAlertController.addAction(cancelAction) present(cameraNotAvailableAlertController, animated: true, completion: nil) } }
apache-2.0
e6db299e6d71fd251ad3af42eb548863
44.429719
168
0.571871
6.434585
false
false
false
false
SandcastleApps/partyup
PartyUP/Advertisement.swift
1
4333
// // Advertisement.swift // PartyUP // // Created by Fritz Vander Heide on 2016-01-12. // Copyright © 2016 Sandcastle Application Development. All rights reserved. // import Foundation import AWSDynamoDB final class Advertisement: CustomDebugStringConvertible, Hashable { enum Style: Int { case Page, Overlay } enum FeedCategory: String { case All = "a", Venue = "v" } typealias FeedMask = [FeedCategory:NSRegularExpression] let administration: String let feeds: FeedMask let pages: [Int] let style: Style let media: String private let id: Character init(administration: String, media: String, id: Character, feeds: FeedMask, pages: [Int], style: Style = .Page) { self.administration = administration self.feeds = feeds self.pages = pages self.style = style self.media = media self.id = id Advertisement.ads.insert(self) } deinit { Advertisement.ads.remove(self) } var debugDescription: String { get { return "Administration = \(administration)\nFeeds = \(feeds)\nPages = \(pages)\nStyle = \(style)\nMedia = \(media)\n" } } func apropos(identifier: String, ofFeed feed: FeedCategory) -> Bool { return feeds[feed]?.firstMatchInString(identifier, options: [.Anchored], range: NSRange(location: 0, length: identifier.utf16.count)) != nil } //MARK - Internal Dynamo Representation internal convenience init(data: AdvertisementDB) { var feeder = FeedMask(minimumCapacity: 3) for filter in data.feeds { if let category = FeedCategory(rawValue: filter[filter.startIndex..<filter.startIndex.advancedBy(1)]), regex = try? NSRegularExpression(pattern: filter[filter.startIndex.advancedBy(2)..<filter.endIndex], options: []) { feeder[category] = regex } } self.init( administration: data.administration, media: data.media[data.media.startIndex.advancedBy(1)..<data.media.endIndex], id: data.media.characters.first ?? "a", feeds: feeder, pages: Array<Int>(data.pages), style: Style(rawValue: data.style) ?? .Page ) } internal var dynamo: AdvertisementDB { get { let db = AdvertisementDB() db.administration = administration db.feeds = Set<String>(feeds.map { $0.0.rawValue + ":" + $0.1.pattern }) db.pages = Set<Int>(pages) db.style = style.rawValue db.media = "\(id):\(media)" return db } } internal class AdvertisementDB: AWSDynamoDBObjectModel, AWSDynamoDBModeling { var administration: String! var feeds: Set<String> = [] var pages: Set<Int> = [] var style: Int = 0 var media: String! @objc static func dynamoDBTableName() -> String { return "Advertisements" } @objc static func hashKeyAttribute() -> String { return "administration" } @objc static func rangeKeyAttribute() -> String { return "media" } } var hashValue: Int { return administration.hashValue ^ media.hashValue ^ id.hashValue } private static var ads = Set<Advertisement>() static func apropos(identifier: String, ofFeed feed: FeedCategory) -> [Advertisement] { return ads.filter { $0.apropos(identifier, ofFeed: feed) } } static func refresh(places: [Address]) { ads.removeAll() places.forEach { fetch($0) } } static func fetch(place: Address) { let query = AWSDynamoDBQueryExpression() let hash = String(format: "%@$%@", place.province, place.country) query.keyConditionExpression = "#h = :hash" query.expressionAttributeNames = ["#h": "administration"] query.expressionAttributeValues = [":hash" : hash] AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper().query(AdvertisementDB.self, expression: query).continueWithBlock { (task) in if let result = task.result as? AWSDynamoDBPaginatedOutput { if let items = result.items as? [AdvertisementDB] { let wraps = items.map { Advertisement(data: $0) } dispatch_async(dispatch_get_main_queue()) { Advertisement.ads.unionInPlace(wraps) } } } return nil } } } func ==(lhs: Advertisement, rhs: Advertisement) -> Bool { return lhs.administration == rhs.administration && lhs.id == rhs.id && lhs.media == rhs.media }
mit
8b01c43ab938842e9139851ead35a6e3
28.469388
142
0.655817
3.874776
false
false
false
false
jverdi/Gramophone
Tests/LikesTests.swift
1
6556
// // LikesTests.swift // Gramophone // // Copyright (c) 2017 Jared Verdi. All Rights Reserved // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import Quick import Nimble import OHHTTPStubs import Result @testable import Gramophone class LikesSpec: QuickSpec { override func spec() { let mediaID = "1482048616133874767_989545" let path = "/v1/media/\(mediaID)/likes" describe("GET likes") { if enableStubbing { stub(condition: isHost(GramophoneTestsHost) && isPath(path) && isMethodGET()) { request in return OHHTTPStubsResponse( fileAtPath: OHPathForFile("likes.json", type(of: self))!, statusCode: 200, headers: GramophoneTestsHeaders ) } } let scopes: [Scope] = [.publicContent] it("requires the correct scopes") { TestingUtilities.testScopes(scopes: scopes) { gramophone, completion in gramophone.client.likes(mediaID: mediaID) { completion($0) } } } it("requires authentication") { TestingUtilities.testAuthentication(scopes: scopes) { gramophone, completion in gramophone.client.likes(mediaID: mediaID) { completion($0) } } } it("parses http successful response") { TestingUtilities.testSuccessfulRequest(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.likes(mediaID: mediaID) { completion($0) } } } it("parses into Like objects") { TestingUtilities.testSuccessfulRequestWithDataConfirmation(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.likes(mediaID: mediaID) { completion($0) { likes in expect(likes.items.count).to(equal(2)) expect(likes.items[0].ID).to(equal("24515474")) expect(likes.items[0].username).to(equal("richkern")) expect(likes.items[0].fullName).to(equal("Rich Kern")) expect(likes.items[0].profilePictureURL).to(equal(URL(string: "https://scontent.cdninstagram.com/t51.2885-19/11849395_467018326835121_804084785_a.jpg" )!)) } } } } } describe("POST like") { if enableStubbing { stub(condition: isHost(GramophoneTestsHost) && isPath(path) && isMethodPOST()) { request in return OHHTTPStubsResponse( fileAtPath: OHPathForFile("generic_success_response.json", type(of: self))!, statusCode: 200, headers: GramophoneTestsHeaders ) } } let scopes: [Scope] = [.publicContent, .likes] it("requires the correct scopes") { TestingUtilities.testScopes(scopes: scopes) { gramophone, completion in gramophone.client.like(mediaID: mediaID) { completion($0) } } } it("requires authentication") { TestingUtilities.testAuthentication(scopes: scopes) { gramophone, completion in gramophone.client.like(mediaID: mediaID) { completion($0) } } } it("parses http successful response") { TestingUtilities.testSuccessfulRequest(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.like(mediaID: mediaID) { completion($0) } } } } describe("DELETE like") { if enableStubbing { stub(condition: isHost(GramophoneTestsHost) && isPath(path) && isMethodDELETE()) { request in return OHHTTPStubsResponse( fileAtPath: OHPathForFile("generic_success_response.json", type(of: self))!, statusCode: 200, headers: GramophoneTestsHeaders ) } } let scopes: [Scope] = [.publicContent, .likes] it("requires the correct scopes") { TestingUtilities.testScopes(scopes: scopes) { gramophone, completion in gramophone.client.unlike(mediaID: mediaID) { completion($0) } } } it("requires authentication") { TestingUtilities.testAuthentication(scopes: scopes) { gramophone, completion in gramophone.client.unlike(mediaID: mediaID) { completion($0) } } } it("parses http successful response") { TestingUtilities.testSuccessfulRequest(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.unlike(mediaID: mediaID) { completion($0) } } } } } }
mit
4365e60e04b46ffbadef474876506440
41.849673
133
0.544539
5.378179
false
true
false
false
joelconnects/FlipTheBlinds
FlipTheBlinds/FromViewController.swift
1
3035
// // FromViewController.swift // FlipTheBlinds // // Created by Joel Bell on 1/2/17. // Copyright © 2017 Joel Bell. All rights reserved. // import UIKit // MARK: Main class FromViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() configImageView() configButton() } @objc func buttonTapped(_ sender: UIButton) { let toViewController = ToViewController() // POD: Set transitioningDelegate toViewController.transitioningDelegate = self self.present(toViewController, animated: true, completion: nil) } } // MARK: Configure View extension FromViewController { private func configImageView() { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.image = #imageLiteral(resourceName: "treeGlobeImage") view.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true imageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true imageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true } private func configButton() { let screenWidth = UIScreen.main.bounds.size.width let screenHeight = UIScreen.main.bounds.size.height let buttonSize: CGFloat = 60 let buttonYconstant: CGFloat = 50 let buttonXorigin = (screenWidth / 2) - (buttonSize / 2) let buttonYorigin = screenHeight - buttonSize - buttonYconstant let button = UIButton(type: .custom) button.alpha = 0.7 button.backgroundColor = UIColor.black button.setTitleColor(UIColor.white, for: UIControl.State()) button.setTitle("GO", for: UIControl.State()) button.frame = CGRect(x: buttonXorigin, y: buttonYorigin, width: buttonSize, height: buttonSize) button.layer.cornerRadius = 0.5 * button.bounds.size.width button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside) view.addSubview(button) } } // POD: Add Modal Extension extension FromViewController: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return FTBAnimationController(displayType: .present, direction: .up, speed: .moderate) } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return FTBAnimationController(displayType: .dismiss, direction: .down, speed: .moderate) } }
mit
2f01f7bfbf2239a6dc1be81a7d4a6283
29.34
170
0.661503
5.360424
false
false
false
false
itssofluffy/NanoMessage
Tests/NanoMessageTests/BusProtocolFamilyTests.swift
1
4579
/* BusProtocolFamilyTests.swift Copyright (c) 2016, 2017 Stephen Whittle All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import XCTest import Foundation import NanoMessage class BusProtocolFamilyTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testBus(address1: String, address2: String) { guard let address1URL = URL(string: address1) else { XCTAssert(false, "address1URL is invalid") return } guard let address2URL = URL(string: address2) else { XCTAssert(false, "address2URL is invalid") return } var completed = false do { let node0 = try BusSocket(url: address1URL, type: .Bind) let node1 = try BusSocket() let node2 = try BusSocket(urls: [address1URL, address2URL], type: .Connect) let _: Int = try node1.createEndPoint(url: address1URL, type: .Connect) let _: Int = try node1.createEndPoint(url: address2URL, type: .Bind) pauseForBind() try node0.sendMessage(Message(value: "A")) try node1.sendMessage(Message(value: "AB")) try node2.sendMessage(Message(value: "ABC")) let timeout = TimeInterval(seconds: 1) for _ in 0 ... 1 { let received = try node0.receiveMessage(timeout: timeout) XCTAssertGreaterThanOrEqual(received.bytes, 0, "node0.received.bytes < 0") let boolTest = (received.bytes == 2 || received.bytes == 3) ? true : false XCTAssertEqual(boolTest, true, "node0.received.bytes != 2 && node0.received.bytes != 3") } for _ in 0 ... 1 { let received = try node1.receiveMessage(timeout: timeout) XCTAssertGreaterThanOrEqual(received.bytes, 0, "node1.received.bytes < 0") let boolTest = (received.bytes == 1 || received.bytes == 3) ? true : false XCTAssertEqual(boolTest, true, "node1.received.bytes != 2 && node1.received.bytes != 3") } for _ in 0 ... 1 { let received = try node2.receiveMessage(timeout: timeout) XCTAssertGreaterThanOrEqual(received.bytes, 0, "node2.received.bytes < 0") let boolTest = (received.bytes == 1 || received.bytes == 2) ? true : false XCTAssertEqual(boolTest, true, "node2.received.bytes != 2 && node2.received.bytes != 2") } completed = true } catch let error as NanoMessageError { XCTAssert(false, "\(error)") } catch { XCTAssert(false, "an unexpected error '\(error)' has occured in the library libNanoMessage.") } XCTAssert(completed, "test not completed") } func testInProcessBus() { testBus(address1: "inproc:///tmp/bus_1.inproc", address2: "inproc:///tmp/bus_2.inproc") } func testInterProcessBus() { testBus(address1: "ipc:///tmp/bus_1.ipc", address2: "ipc:///tmp/bus_2.ipc") } #if os(Linux) static let allTests = [ ("testInProcessBus", testInProcessBus), ("testInterProcessBus", testInterProcessBus) ] #endif }
mit
38639d3e963bc4a9d7ca56ecb64848ef
39.522124
111
0.631361
4.45428
false
true
false
false
JockerLUO/ShiftLibra
ShiftLibra/ShiftLibra/Class/View/Option/View/SLCustomizeView.swift
1
4521
// // SLCustomizeView.swift // ShiftLibra // // Created by LUO on 2017/8/13. // Copyright © 2017年 JockerLuo. All rights reserved. // import UIKit import pop class SLCustomizeView: UIView { var closure : (()->())? var currency : SLCurrency? { didSet { labInfo.text = "\(customExchange):\(currency?.code ?? "") → CNY" labFrom.text = currency?.code ?? "" textTo.text = String(format: "%.4f", currency?.exchange ?? 1.0) } } @IBOutlet weak var labInfo: UILabel! @IBOutlet weak var labFrom: UILabel! @IBOutlet weak var labTo: UILabel! @IBOutlet weak var textFrom: UITextField! @IBOutlet weak var textTo: UITextField! @IBOutlet weak var btnCancel: UIButton! @IBOutlet weak var btnFinish: UIButton! @IBAction func btnCancelClick(_ sender: Any) { self.removeFromSuperview() } @IBAction func btnFinishClick(_ sender: Any) { guard let toVulue = (textTo.text as NSString?)?.doubleValue else { return } guard let fromVulue = (textFrom.text as NSString?)?.doubleValue else { return } let customizeList = SLOptionViewModel().customizeList var sql : String = "INSERT INTO T_Currency (name,code,query,exchange,name_English) VALUES('\(customCurrency)\(currency?.name! ?? "")','\(currency?.code! ?? "")★','customize',\(toVulue / fromVulue),'\(currency?.name_English ?? "")★')" if (customizeList?.count)! > 0 { for customizeCurrency in customizeList! { if customizeCurrency.code! == ((currency?.code)! + "★") { sql = "UPDATE T_Currency set exchange=\(toVulue / fromVulue) WHERE code='\(customizeCurrency)';" } } } SLSQLManager.shared.insertToSQL(sql: sql) self.removeFromSuperview() } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func setupUI() -> () { addSubview(bgView) addSubview(settingView) textTo.becomeFirstResponder() btnCancel.setTitle(btnCancelText, for: .normal) btnFinish.setTitle(btnFinishText, for: .normal) anim() } fileprivate lazy var bgView: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: SCREENH)) view.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5) return view }() fileprivate lazy var settingView: UIView = { let nib = UINib(nibName: "SLCustomizeView", bundle: nil) let nibView = nib.instantiate(withOwner: self, options: [:]).first as! UIView nibView.frame = CGRect(x: 0, y: -(homeHeaderHight + homeTableViewCellHight * 3), width: SCREENW, height: homeHeaderHight + homeTableViewCellHight * 3) return nibView }() override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if touches.first?.view == bgView { removeFromSuperview() } } } extension SLCustomizeView { @objc fileprivate func btnOtherClick() -> () { closure?() } @objc fileprivate func btnCancelClick() -> () { self.removeFromSuperview() } } extension SLCustomizeView : POPAnimationDelegate{ fileprivate func anim() -> () { let settingAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter) settingAnimation?.toValue = CGPoint(x: settingView.center.x, y: homeHeaderHight + settingView.bounds.height * 0.5) settingAnimation?.beginTime = CACurrentMediaTime() settingAnimation?.springBounciness = 0 settingView.pop_add(settingAnimation, forKey: nil) settingAnimation?.delegate = self } func pop_animationDidStop(_ anim: POPAnimation!, finished: Bool) { } }
mit
8ae9425916b756642a620e2bce6f178b
25.22093
241
0.537916
5.044743
false
false
false
false
wangyun-hero/sinaweibo-with-swift
sinaweibo/Classes/View/Compose/View/Emoticon/WYEmoticonToolBar.swift
1
3306
// // WYEmoticonToolBar.swift // sinaweibo // // Created by 王云 on 16/9/10. // Copyright © 2016年 王云. All rights reserved. // import UIKit /// 表情的类型 /// /// - RECENT: 最近 /// - DEFAULT: 默认 /// - EMOJI: emoji /// - LXH: 浪小花 enum HMEmotionType: Int { case RECENT = 0, DEFAULT, EMOJI, LXH } class WYEmoticonToolBar: UIView { var currentSelectedButton: UIButton? /// 表情类型切换按钮点击的时候执行的闭包 var emotionTypeChangedClosure: ((HMEmotionType)->())? override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI() { self.addSubview(stackView) stackView.snp_makeConstraints { (make ) in make.edges.equalTo(self) } //添加4个按钮 addChildBtns(imageName: "compose_emotion_table_left", title: "最近",type: .RECENT) addChildBtns(imageName: "compose_emotion_table_mid", title: "默认",type:.DEFAULT) addChildBtns(imageName: "compose_emotion_table_mid", title: "Emoji",type:.EMOJI) addChildBtns(imageName: "compose_emotion_table_right", title: "浪小花",type:.LXH) } //添加按钮的方法 private func addChildBtns (imageName:String , title:String ,type:HMEmotionType) { //初始化button let button = UIButton() //设置tag button.tag = type.rawValue //监听按钮的点击 button.addTarget(self, action: #selector(childButtonClick(btn:)), for: .touchUpInside) //设置标题 button.setTitle(title, for: .normal) //设置字体颜色 button.setTitleColor(UIColor.white, for: .normal) button.setTitleColor(UIColor.gray, for: .selected) //设置背景图片 button.setBackgroundImage(UIImage(named: "\(imageName)_normal"), for: UIControlState.normal) button.setBackgroundImage(UIImage(named: "\(imageName)_selected"), for: UIControlState.selected) stackView.addArrangedSubview(button) } // MARK: - 监听事件 @objc private func childButtonClick(btn: UIButton) { // 判断当前点击的按钮与选中的按钮是同一个按钮的话,就不执行后面的代码 if currentSelectedButton == btn { return } // 1. 让之前选中的按钮取消选中 currentSelectedButton?.isSelected = false // 2. 让当前点击的按钮选中 btn.isSelected = true // 3. 将当前选中的的按钮记录起来,记录起来原因是下次在点击其他按钮的时候,要取消当前按钮 currentSelectedButton = btn // 4. 在这个地方通知外界去滚动collectionView // 也就是说需要在此执行一个闭包 emotionTypeChangedClosure?(HMEmotionType(rawValue: btn.tag)!) } //MARK: - 懒加载控件 private lazy var stackView :UIStackView = { let stackView = UIStackView() //设置布局方向 stackView.distribution = .fillEqually return stackView }() }
mit
b7d9938130c51ca8820192b27a02e3d8
25.063636
104
0.603767
4.113343
false
false
false
false
soapyigu/LeetCode_Swift
DP/DifferentWaysAddParentheses.swift
1
1559
/** * Question Link: https://leetcode.com/problems/different-ways-to-add-parentheses/ * Primary idea: Divide and Conquer, calculate left and right separately and union results * * Note: Keep a memo dictionary to avoid duplicate calculations * Time Complexity: O(n^n), Space Complexity: O(n) * */ class DifferentWaysAddParentheses { var memo = [String: [Int]]() func diffWaysToCompute(_ input: String) -> [Int] { if let nums = memo[input] { return nums } var res = [Int]() let chars = Array(input.characters) for (i, char) in chars.enumerated() { if char == "+" || char == "*" || char == "-" { let leftResults = diffWaysToCompute(String(chars[0..<i])) let rightResults = diffWaysToCompute(String(chars[i + 1..<chars.count])) for leftRes in leftResults { for rightRes in rightResults { if char == "+" { res.append(leftRes + rightRes) } if char == "-" { res.append(leftRes - rightRes) } if char == "*" { res.append(leftRes * rightRes) } } } } } if res.count == 0 { res.append(Int(input)!) } memo[input] = res return res } }
mit
26c55d341a92835666833901dff76366
30.2
90
0.44644
4.796923
false
false
false
false
UncleJerry/Dailylife-with-a-fish
Fishing Days/RadioBox.swift
1
1615
// // RadioBox.swift // Fishing Days // // Created by 周建明 on 2017/4/1. // Copyright © 2017年 Uncle Jerry. All rights reserved. // import UIKit class RadioBox: FunctionButton { var selectedButton: UIImage? var selectedBG: UIImage = UIImage(named: "ButtonBG")! var unSelecteButton: UIImage? var image: String? var doesSelected: Bool = false { willSet{ // load the image name info if haven't loaded guard image != nil else { if self.currentImage?.size.width == CGFloat(22) { image = "Female" }else{ image = "Male" } return } } didSet{ if doesSelected { self.setImage(selectedButton ?? UIImage(named: image! + "S"), for: .normal) self.setBackgroundImage(selectedBG, for: .normal) // load the image if haven't loaded guard selectedButton != nil else { selectedButton = UIImage(named: image! + "S") return } }else{ self.setImage(unSelecteButton ?? UIImage(named: image!), for: .normal) self.setBackgroundImage(nil, for: .normal) // load the image if haven't loaded guard unSelecteButton != nil else { unSelecteButton = UIImage(named: image!) return } } } } }
mit
8efa0df22e7b6bf1a8980010fc10daeb
27.678571
91
0.473225
5.01875
false
false
false
false
nyin005/Forecast-App
Forecast/Forecast/HttpRequest/ViewModel/ReportViewModel.swift
1
4494
// // ReportViewModel.swift // Forecast // // Created by Perry Z Chen on 10/21/16. // Copyright © 2016 Perry Z Chen. All rights reserved. // /** TODO: 1. create a common request can receive a string value and returns the pie chart data or line chart data */ import Foundation class ReportViewModel: BaseViewModel { var results: String? var losListModel: ReportLosModel? var pieChartListModel: PieChartDataListModel? // 饼图数据 var lineChartRootModel: LineChartDataRootModel? // 线形图数据 var availableModel: AvailableModel? } extension ReportViewModel { // get los report chart func getLosReport(_ url: String,parameters: [String: AnyObject], success: @escaping ()->Void, failure:@escaping (_ str: String) -> Void) { // let URL = HttpMacro.getRequestURL(.ReportLOS) self.requestData(url: url, parameters: parameters, methods: .get) { (res: HttpResponseResult) in if res.success { self.results = res.resultString let listModel = ReportLosModel(JSONString: res.resultString)! as ReportLosModel if listModel.responseData != nil { for model in listModel.responseData! { model.LosValues?.sort(by: { (pre, after) -> Bool in pre.label!.compare(after.label!) == .orderedAscending }) } self.losListModel = listModel success() } else { failure((listModel.responseMsg)!) } } else { failure(res.resultString) } } } // 获取饼图数据 func getPieChartReport(_ url: String, parameters: [String: AnyObject], success: @escaping ()->Void, failure:@escaping (_ str:String ) -> Void) -> Void { // let URL = HttpMacro.Original.combineString(str: url) self.requestData(url: url, parameters: parameters, methods: .get) { (res: HttpResponseResult) in if res.success { self.results = res.resultString let listModel = PieChartDataListModel(JSONString: res.resultString) if listModel?.responseData != nil { self.pieChartListModel = listModel success() } else { failure((listModel?.responseMsg)!) } } else { failure(res.resultString) } } } // 获取线图数据 func getLineChartReport(_ url: String, parameters: [String: AnyObject], success: @escaping ()->Void, failure:@escaping (_ str:String ) -> Void) -> Void { // let URL = HttpMacro.Original.combineString(str: url) self.requestData(url: url, parameters: parameters, methods: .get) { (res: HttpResponseResult) in if res.success { self.results = res.resultString let utListModel = LineChartDataRootModel(JSONString: res.resultString) if utListModel?.responseData != nil { self.lineChartRootModel = utListModel success() } else { failure((utListModel?.responseMsg)!) } } else { failure(res.resultString) } } } func getAvailableReport(_ url: String, parameters: [String: AnyObject], success: @escaping ()->Void, failure:@escaping (_ str:String ) -> Void) -> Void { // let URL = HttpMacro.Original.combineString(str: url) self.requestData(url: url, parameters: parameters, methods: .get) { (res: HttpResponseResult) in if res.success { self.results = res.resultString let utListModel = AvailableModel(JSONString: res.resultString) if utListModel?.data != nil { self.availableModel = utListModel success() } else { failure((utListModel?.msg)!) } } else { failure(res.resultString) } } } func cancel() { self.cancelRequest() } }
gpl-3.0
38ac67227d3c93b1409f375184cca860
34.325397
157
0.521681
5.163573
false
false
false
false
sjchmiela/call-of-beacons
ios/CallOfBeacons/CallOfBeacons/COBBeacon.swift
1
3606
// // COBBeacon.swift // CallOfBeacons // // Created by Stanisław Chmiela on 02.06.2016. // Copyright © 2016 Stanisław Chmiela, Rafał Żelazko. All rights reserved. // import Foundation /// Beacon model with all the information we need class COBBeacon: Equatable, CustomStringConvertible, Hashable, Comparable { /// Major of the beacon var major: Int? /// Minor of the beacon var minor: Int? /// Name of the beacon (customizable in configuration.json) var name: String? /// Behavior of the beacon (based on which we'll decide how to handle it's proximity) var behaviorName: String? /// Proximity of the beacon to the gamer var proximity: CLProximity? /// Color of the beacon var color: String? /// toString of the beacon object var description: String { return "Beacon \(name ?? "")\n\t\(proximity?.description ?? "unknown") to \(behaviorName ?? "unknown")" } /// Behavior of the beacon var behavior: COBBeaconBehavior.Type? { if let behaviorName = behaviorName, let behaviorType = COBBeacon.behaviors[behaviorName] { return behaviorType } else { return nil } } var shouldPulse: Bool { return behaviorName == "flag" } /// Initialize out of JSON init(jsonData: JSON) { self.major = jsonData["major"].int self.minor = jsonData["minor"].int self.behaviorName = jsonData["behavior"].string self.name = jsonData["name"].string self.color = jsonData["color"].string } /// Initialize out of a beacon of another type. Merges the beacon with any known beacon found. init(beacon: CLBeacon) { self.major = beacon.major.integerValue self.minor = beacon.minor.integerValue self.proximity = beacon.proximity if let knownBeacon = COBBeacon.beaconWith(beacon.major.integerValue, minor: beacon.minor.integerValue) { self.name = knownBeacon.name self.behaviorName = knownBeacon.behaviorName self.color = knownBeacon.color } } var hashValue: Int { return 65535 * major! + minor! } } extension COBBeacon { /// All the known behaviorNames and their behaviors static let behaviors: [String: COBBeaconBehavior.Type] = { return [ "flag": COBFlagBehavior.self, "healthPoint": COBHealthPointBehavior.self ] }() /// All the known beacons static var knownBeacons: [COBBeacon] { return COBConfiguration.beacons.sort() } /// Find one beacon with these major and minor out of all the known beacons static func beaconWith(major: Int, minor: Int) -> COBBeacon? { if let index = knownBeacons.indexOf({$0.major == major && $0.minor == minor}) { return knownBeacons[index] } return nil } /// Turn array of beacons to parameters sendable through HTTP request static func beaconsToParameters(beacons: [COBBeacon]) -> [AnyObject] { return beacons.map({ (beacon) -> AnyObject in return [ "major": beacon.major!, "minor": beacon.minor!, "proximity": beacon.proximity?.rawValue ?? 0 ] }) } } /// Comparison implementation func ==(lhs: COBBeacon, rhs: COBBeacon) -> Bool { return lhs.major == rhs.major && lhs.minor == rhs.minor } func <(lhs: COBBeacon, rhs: COBBeacon) -> Bool { return lhs.major == rhs.major ? lhs.minor < rhs.minor : lhs.major < rhs.major }
mit
b1937cfd9f22bf2face87585e16e1659
31.45045
112
0.618162
4.423833
false
false
false
false
kstaring/swift
test/DebugInfo/thunks.swift
8
897
// RUN: %target-swift-frontend -emit-ir -g %s -o - | %FileCheck %s // RUN: %target-swift-frontend -emit-sil -emit-verbose-sil -g %s -o - | %FileCheck %s --check-prefix=SIL-CHECK // REQUIRES: objc_interop import Foundation class Foo : NSObject { dynamic func foo(_ f: (Int64) -> Int64, x: Int64) -> Int64 { return f(x) } } let foo = Foo() let y = 3 as Int64 let i = foo.foo(-, x: y) // CHECK: define {{.*}}@_TTRXFdCb_dVs5Int64_dS__XFo_dS__dS__ // CHECK-NOT: ret // CHECK: call {{.*}}, !dbg ![[LOC:.*]] // CHECK: ![[THUNK:.*]] = distinct !DISubprogram(linkageName: "_TTRXFdCb_dVs5Int64_dS__XFo_dS__dS__" // CHECK-NOT: line: // CHECK-SAME: ){{$}} // CHECK: ![[LOC]] = !DILocation(line: 0, scope: ![[THUNK]]) // SIL-CHECK: sil shared {{.*}}@_TTRXFdCb_dVs5Int64_dS__XFo_dS__dS__ // SIL-CHECK-NOT: return // SIL-CHECK: apply {{.*}}auto_gen
apache-2.0
9a2acab95c678ca784906d32a5c93071
33.5
110
0.566332
2.960396
false
false
false
false
natecook1000/swift
stdlib/public/SDK/Foundation/NSCoder.swift
2
8669
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims //===----------------------------------------------------------------------===// // NSCoder //===----------------------------------------------------------------------===// @available(macOS 10.11, iOS 9.0, *) internal func resolveError(_ error: NSError?) throws { if let error = error, error.code != NSCoderValueNotFoundError { throw error } } extension NSCoder { @available(*, unavailable, renamed: "decodeObject(of:forKey:)") public func decodeObjectOfClass<DecodedObjectType>( _ cls: DecodedObjectType.Type, forKey key: String ) -> DecodedObjectType? where DecodedObjectType : NSCoding, DecodedObjectType : NSObject { fatalError("This API has been renamed") } public func decodeObject<DecodedObjectType>( of cls: DecodedObjectType.Type, forKey key: String ) -> DecodedObjectType? where DecodedObjectType : NSCoding, DecodedObjectType : NSObject { let result = __NSCoderDecodeObjectOfClassForKey(self, cls, key, nil) return result as? DecodedObjectType } @available(*, unavailable, renamed: "decodeObject(of:forKey:)") @nonobjc public func decodeObjectOfClasses(_ classes: NSSet?, forKey key: String) -> AnyObject? { fatalError("This API has been renamed") } @nonobjc public func decodeObject(of classes: [AnyClass]?, forKey key: String) -> Any? { var classesAsNSObjects: NSSet? if let theClasses = classes { classesAsNSObjects = NSSet(array: theClasses.map { $0 as AnyObject }) } return __NSCoderDecodeObjectOfClassesForKey(self, classesAsNSObjects, key, nil).map { $0 as Any } } @nonobjc @available(macOS 10.11, iOS 9.0, *) public func decodeTopLevelObject() throws -> Any? { var error: NSError? let result = __NSCoderDecodeObject(self, &error) try resolveError(error) return result.map { $0 as Any } } @available(*, unavailable, renamed: "decodeTopLevelObject(forKey:)") public func decodeTopLevelObjectForKey(_ key: String) throws -> AnyObject? { fatalError("This API has been renamed") } @nonobjc @available(swift, obsoleted: 4) @available(macOS 10.11, iOS 9.0, *) public func decodeTopLevelObject(forKey key: String) throws -> AnyObject? { var error: NSError? let result = __NSCoderDecodeObjectForKey(self, key, &error) try resolveError(error) return result as AnyObject? } @nonobjc @available(swift, introduced: 4) @available(macOS 10.11, iOS 9.0, *) public func decodeTopLevelObject(forKey key: String) throws -> Any? { var error: NSError? let result = __NSCoderDecodeObjectForKey(self, key, &error) try resolveError(error) return result } @available(*, unavailable, renamed: "decodeTopLevelObject(of:forKey:)") public func decodeTopLevelObjectOfClass<DecodedObjectType>( _ cls: DecodedObjectType.Type, forKey key: String ) throws -> DecodedObjectType? where DecodedObjectType : NSCoding, DecodedObjectType : NSObject { fatalError("This API has been renamed") } @available(macOS 10.11, iOS 9.0, *) public func decodeTopLevelObject<DecodedObjectType>( of cls: DecodedObjectType.Type, forKey key: String ) throws -> DecodedObjectType? where DecodedObjectType : NSCoding, DecodedObjectType : NSObject { var error: NSError? let result = __NSCoderDecodeObjectOfClassForKey(self, cls, key, &error) try resolveError(error) return result as? DecodedObjectType } @nonobjc @available(*, unavailable, renamed: "decodeTopLevelObject(of:forKey:)") public func decodeTopLevelObjectOfClasses(_ classes: NSSet?, forKey key: String) throws -> AnyObject? { fatalError("This API has been renamed") } @nonobjc @available(macOS 10.11, iOS 9.0, *) public func decodeTopLevelObject(of classes: [AnyClass]?, forKey key: String) throws -> Any? { var error: NSError? var classesAsNSObjects: NSSet? if let theClasses = classes { classesAsNSObjects = NSSet(array: theClasses.map { $0 as AnyObject }) } let result = __NSCoderDecodeObjectOfClassesForKey(self, classesAsNSObjects, key, &error) try resolveError(error) return result.map { $0 as Any } } } //===----------------------------------------------------------------------===// // NSKeyedArchiver //===----------------------------------------------------------------------===// extension NSKeyedArchiver { @nonobjc @available(macOS 10.11, iOS 9.0, *) public func encodeEncodable<T : Encodable>(_ value: T, forKey key: String) throws { let plistEncoder = PropertyListEncoder() let plist = try plistEncoder.encodeToTopLevelContainer(value) self.encode(plist, forKey: key) } } //===----------------------------------------------------------------------===// // NSKeyedUnarchiver //===----------------------------------------------------------------------===// extension NSKeyedUnarchiver { @nonobjc @available(swift, obsoleted: 4) @available(macOS 10.11, iOS 9.0, *) public class func unarchiveTopLevelObjectWithData(_ data: NSData) throws -> AnyObject? { var error: NSError? let result = __NSKeyedUnarchiverUnarchiveObject(self, data, &error) try resolveError(error) return result as AnyObject? } @nonobjc @available(swift, introduced: 4) @available(macOS 10.11, iOS 9.0, *) public class func unarchiveTopLevelObjectWithData(_ data: Data) throws -> Any? { var error: NSError? let result = __NSKeyedUnarchiverUnarchiveObject(self, data as NSData, &error) try resolveError(error) return result } @nonobjc @available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) public static func unarchivedObject<DecodedObjectType>(ofClass cls: DecodedObjectType.Type, from data: Data) throws -> DecodedObjectType? where DecodedObjectType : NSCoding, DecodedObjectType : NSObject { var error: NSError? let result = __NSKeyedUnarchiverSecureUnarchiveObjectOfClass(cls as AnyClass, data, &error) if let error = error { throw error } return result as? DecodedObjectType } @nonobjc @available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) public static func unarchivedObject(ofClasses classes: [AnyClass], from data: Data) throws -> Any? { var error: NSError? let classesAsNSObjects = NSSet(array: classes.map { $0 as AnyObject }) let result = __NSKeyedUnarchiverSecureUnarchiveObjectOfClasses(classesAsNSObjects, data, &error) if let error = error { throw error } return result } @nonobjc private static let __plistClasses: [AnyClass] = [ NSArray.self, NSData.self, NSDate.self, NSDictionary.self, NSNumber.self, NSString.self ] @nonobjc @available(macOS 10.11, iOS 9.0, *) public func decodeDecodable<T : Decodable>(_ type: T.Type, forKey key: String) -> T? { guard let value = self.decodeObject(of: NSKeyedUnarchiver.__plistClasses, forKey: key) else { return nil } let plistDecoder = PropertyListDecoder() do { return try plistDecoder.decode(T.self, fromTopLevel: value) } catch { self.failWithError(error) return nil } } @nonobjc @available(macOS 10.11, iOS 9.0, *) public func decodeTopLevelDecodable<T : Decodable>(_ type: T.Type, forKey key: String) throws -> T? { guard let value = try self.decodeTopLevelObject(of: NSKeyedUnarchiver.__plistClasses, forKey: key) else { return nil } let plistDecoder = PropertyListDecoder() do { return try plistDecoder.decode(T.self, fromTopLevel: value) } catch { self.failWithError(error) throw error; } } } @available(*, deprecated, renamed:"NSCoding", message: "Please use NSCoding") typealias Coding = NSCoding @available(*, deprecated, renamed:"NSCoder", message: "Please use NSCoder") typealias Coder = NSCoder @available(*, deprecated, renamed:"NSKeyedUnarchiver", message: "Please use NSKeyedUnarchiver") typealias KeyedUnarchiver = NSKeyedUnarchiver @available(*, deprecated, renamed:"NSKeyedArchiver", message: "Please use NSKeyedArchiver") typealias KeyedArchiver = NSKeyedArchiver
apache-2.0
a7cab483ccd70248afc567befd126e1c
34.528689
206
0.655324
4.739748
false
false
false
false
russelhampton05/MenMew
App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/MessagePopupViewController.swift
1
5283
// // MessagePopupViewController.swift // App_Prototype_Alpha_001 // // Created by Jon Calanio on 11/12/16. // Copyright © 2016 Jon Calanio. All rights reserved. // import UIKit class MessagePopupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //IBOutlets @IBOutlet var requestLabel: UILabel! @IBOutlet var messageTableView: UITableView! @IBOutlet var confirmButton: UIButton! @IBOutlet var cancelButton: UIButton! @IBOutlet var popupView: UIView! //Variables var messages: [String] = [] var selectedMessage: String? var didCancel: Bool = false override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6) self.showAnimate() loadMessages() messageTableView.delegate = self messageTableView.dataSource = self loadTheme() } @IBAction func confirmButtonPressed(_ sender: Any) { removeAnimate() } @IBAction func cancelButtonPressed(_ sender: Any) { didCancel = true removeAnimate() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell") as UITableViewCell! cell?.textLabel!.text = messages[indexPath.row] cell?.backgroundColor = currentTheme!.primary! cell?.textLabel!.textColor = currentTheme!.highlight! let bgView = UIView() bgView.backgroundColor = currentTheme!.highlight! cell?.selectedBackgroundView = bgView cell?.textLabel?.highlightedTextColor = currentTheme!.primary! cell?.detailTextLabel?.highlightedTextColor = currentTheme!.primary! return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedMessage = messages[indexPath.row] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Popup view animation func showAnimate() { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 UIView.animate(withDuration: 0.25, animations: { self.view.alpha = 1.0 self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) } //Popup remove animation func removeAnimate() { UIView.animate(withDuration: 0.25, animations: { self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.view.alpha = 0.0 }, completion:{(finished : Bool) in if (finished) { if !self.didCancel { self.processMessage() } self.view.removeFromSuperview() } }) } func processMessage() { if let parent = self.parent as? OrderSummaryViewController { if selectedMessage != nil { if selectedMessage == "Request Refill" { selectedMessage = "Requesting refill at Table \(currentUser!.ticket!.tableNum!)" } else if selectedMessage == "Request Seating" { selectedMessage = "Requesting additional/change of seating at Table \(currentUser!.ticket!.tableNum!)" } else if selectedMessage == "Follow-up Order" { selectedMessage = "Requesting a follow up on Ticket \(currentUser!.ticket!.desc!) at Table \(currentUser!.ticket!.tableNum!)" } else if selectedMessage == "Other Request" { selectedMessage = "Requesting server assistance at Table \(currentUser!.ticket!.tableNum!)" } parent.sendMessage(message: selectedMessage!) } } } func loadMessages() { self.messages.append("Request Refill") self.messages.append("Request Seating") self.messages.append("Follow-up Order") self.messages.append("Other Request") } func loadTheme() { //Background and Tint view.tintColor = currentTheme!.highlight! popupView.backgroundColor = currentTheme!.primary! messageTableView.backgroundColor = currentTheme!.primary! messageTableView.sectionIndexBackgroundColor = currentTheme!.primary! //Labels requestLabel.textColor = currentTheme!.highlight! //Buttons confirmButton.backgroundColor = currentTheme!.highlight! confirmButton.setTitleColor(currentTheme!.primary!, for: .normal) cancelButton.backgroundColor = currentTheme!.highlight! cancelButton.setTitleColor(currentTheme!.primary!, for: .normal) } }
mit
3eb4e78e16968a645e1fb602b633bbe4
32.0125
145
0.604317
5.525105
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Missions Tab/Mission/MissionController.swift
1
13745
// // MissionController.swift // MEGameTracker // // Created by Emily Ivie on 3/6/16. // Copyright © 2016 urdnot. All rights reserved. // import UIKit import SafariServices // swiftlint:disable file_length // TODO: Refactor final public class MissionController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate { /// A list of all page components, later tracked by a LoadStatus struct. enum MissionPageComponent: LoadStatusComponent { case aliases case availability case unavailability case conversationRewards case decisions case description case mapLink case notes case objectives case originHint case relatedLinks case relatedMissions case sideEffects static func all() -> [MissionPageComponent] { return [ .aliases, .availability, .unavailability, .conversationRewards, .decisions, .description, .mapLink, .notes, .objectives, .originHint, .relatedLinks, .relatedMissions, .sideEffects, ] } } var shepardUuid: UUID? public var mission: Mission? { didSet { // TODO: fix this, I hate didSet if oldValue != nil && oldValue != mission { reloadDataOnChange() } } } public var originHint: String? { return mission?.name } @IBOutlet weak var nameLabel: UILabel? @IBOutlet weak var checkboxImageView: UIImageView? // Aliasable @IBOutlet weak var aliasesView: TextDataRow? lazy var aliasesType: AliasesType = { return AliasesType(controller: self, view: self.aliasesView) }() // Available @IBOutlet weak var availabilityView: TextDataRow? public var availabilityMessage: String? lazy var availabilityRowType: AvailabilityRowType = { return AvailabilityRowType(controller: self, view: self.availabilityView) }() // Unavailable @IBOutlet weak var unavailabilityView: TextDataRow? public var unavailabilityMessage: String? lazy var unavailabilityRowType: UnavailabilityRowType = { return UnavailabilityRowType(controller: self, view: self.unavailabilityView) }() // ConversationRewardsable @IBOutlet weak var conversationRewardsView: ValueDataRow? lazy var conversationRewardsType: ConversationRewardsRowType = { return ConversationRewardsRowType(controller: self, view: self.conversationRewardsView) }() // Decisionsable @IBOutlet public weak var decisionsView: DecisionsView? public var decisions: [Decision] = [] { didSet { mission?.relatedDecisionIds = decisions.map { $0.id } // local changes only } } // Describable @IBOutlet public weak var descriptionView: TextDataRow? lazy var descriptionType: DescriptionType = { return DescriptionType(controller: self, view: self.descriptionView) }() // MapLinkable @IBOutlet public weak var mapLinkView: ValueDataRow? lazy var mapLinkType: MapLinkType = { return MapLinkType(controller: self, view: self.mapLinkView) }() public var inMapId: String? { didSet { mission?.inMapId = inMapId // local changes only } } // Notesable @IBOutlet weak var notesView: NotesView? public var notes: [Note] = [] // Objectivesable @IBOutlet public weak var objectivesView: ObjectivesView? public var objectives: [MapLocationable] = [] // OriginHintable @IBOutlet public weak var originHintView: TextDataRow? lazy var originHintType: OriginHintType = { return OriginHintType(controller: self, view: self.originHintView) }() // RelatedLinksable @IBOutlet public weak var relatedLinksView: RelatedLinksView? public var relatedLinks: [String] = [] // RelatedMissionsable @IBOutlet public weak var relatedMissionsView: RelatedMissionsView? public var relatedMissions: [Mission] = [] // SideEffectsable @IBOutlet weak var sideEffectsView: SideEffectsView? public var sideEffects: [String]? = [] public var isMissionAvailable = false @IBAction func onClickCheckbox(_ sender: UIButton) { toggleCheckbox() } var isUpdating = false var pageLoadStatus = LoadStatus<MissionPageComponent>() override public func viewDidLoad() { super.viewDidLoad() setup() startListeners() } deinit { removeListeners() } func setup() { guard nameLabel != nil else { return } // make sure all outlets are connected pageLoadStatus.reset() startSpinner(inView: view) isUpdating = true defer { isUpdating = false } if mission?.inMissionId == nil, let missionId = mission?.id, let gameVersion = mission?.gameVersion { App.current.addRecentlyViewedMission(missionId: missionId, gameVersion: gameVersion) } if UIWindow.isInterfaceBuilder { fetchDummyData() } isMissionAvailable = mission?.isAvailableAndParentAvailable ?? false nameLabel?.text = mission?.name ?? "" if let type = mission?.missionType { parent?.navigationItem.title = mission?.pageTitle ?? type.stringValue } guard !UIWindow.isInterfaceBuilder else { return } shepardUuid = App.current.game?.shepard?.uuid setupAliases() setupAvailability() setupUnavailability() setCheckboxImage(isCompleted: mission?.isCompleted ?? false, isAvailable: isMissionAvailable) setupConversationRewards() setupDecisions() setupDescription() setupMapLink() setupNotes() setupObjectives() setupOriginHint() setupRelatedLinks() setupRelatedMissions() setupSideEffects() } func fetchDummyData() { mission = Mission.getDummy() } func conditionalSpinnerStop() { if pageLoadStatus.isComplete { stopSpinner(inView: view) } } func reloadDataOnChange() { self.setup() } func reloadOnShepardChange(_ x: Bool = false) { if shepardUuid != App.current.game?.shepard?.uuid { shepardUuid = App.current.game?.shepard?.uuid reloadDataOnChange() } } func startListeners() { guard !UIWindow.isInterfaceBuilder else { return } App.onCurrentShepardChange.cancelSubscription(for: self) _ = App.onCurrentShepardChange.subscribe(with: self) { [weak self] _ in DispatchQueue.main.async { self?.reloadOnShepardChange() } } // listen for changes to mission data Mission.onChange.cancelSubscription(for: self) _ = Mission.onChange.subscribe(with: self) { [weak self] changed in if self?.mission?.id == changed.id, let newMission = changed.object ?? Mission.get(id: changed.id) { DispatchQueue.main.async { self?.mission = newMission self?.reloadDataOnChange() // the didSet check will view these missions as identical and not fire } } } } func removeListeners() { guard !UIWindow.isInterfaceBuilder else { return } App.onCurrentShepardChange.cancelSubscription(for: self) Mission.onChange.cancelSubscription(for: self) } } extension MissionController { func toggleCheckbox() { guard let mission = self.mission else { return } let isCompleted = !mission.isCompleted let spinnerController = self as Spinnerable? DispatchQueue.main.async { spinnerController?.startSpinner(inView: self.view) // make UI changes now self.nameLabel?.attributedText = self.nameLabel?.attributedText?.toggleStrikethrough(isCompleted) self.setCheckboxImage(isCompleted: isCompleted, isAvailable: self.isMissionAvailable) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(1)) { // save changes to DB self.mission = mission.changed(isCompleted: isCompleted, isSave: true) spinnerController?.stopSpinner(inView: self.view) } } } func setCheckboxImage(isCompleted: Bool, isAvailable: Bool) { checkboxImageView?.image = isCompleted ? MissionCheckbox.filled.getImage() : MissionCheckbox.empty.getImage() if !isAvailable { checkboxImageView?.tintColor = MEGameTrackerColor.disabled } else { checkboxImageView?.tintColor = MEGameTrackerColor.renegade } } } extension MissionController: Aliasable { public var currentName: String? { return mission?.name } public var aliases: [String] { return mission?.aliases ?? [] } func setupAliases() { aliasesType.setupView() pageLoadStatus.markIsDone(.aliases) conditionalSpinnerStop() } } extension MissionController: Available { //public var availabilityMessage: String? // already declared func setupAvailability() { availabilityMessage = mission?.unavailabilityMessages.joined(separator: ", ") availabilityRowType.setupView() pageLoadStatus.markIsDone(.availability) conditionalSpinnerStop() } } extension MissionController: Unavailable { //public var unavailabilityMessage: String? // already declared func setupUnavailability() { unavailabilityMessage = mission?.isAvailable == true ? mission?.unavailabilityAfterMessages.joined(separator: ", ") : nil unavailabilityRowType.setupView() pageLoadStatus.markIsDone(.unavailability) conditionalSpinnerStop() } } extension MissionController: ConversationRewardsable { //public var originHint: String? // already declared //public var mission: Mission? // already declared func setupConversationRewards() { conversationRewardsType.setupView() pageLoadStatus.markIsDone(.conversationRewards) conditionalSpinnerStop() } } extension MissionController: Decisionsable { //public var originHint: String? // already declared //public var decisions: [Decision] // already declared func setupDecisions() { DispatchQueue.global(qos: .userInitiated).async { [weak self] in if let decisionIds = self?.mission?.relatedDecisionIds { self?.decisions = Decision.getAll(ids: decisionIds) self?.decisions = self?.decisions.sorted(by: Decision.sort) ?? [] } else { self?.decisions = [] } DispatchQueue.main.async { self?.decisionsView?.controller = self self?.decisionsView?.setup() self?.pageLoadStatus.markIsDone(.decisions) self?.conditionalSpinnerStop() } } } } extension MissionController: Describable { public var descriptionMessage: String? { return mission?.description } func setupDescription() { descriptionType.setupView() pageLoadStatus.markIsDone(.description) conditionalSpinnerStop() } } extension MissionController: MapLinkable { //public var originHint: String? // already declared //public var inMapId: String? // already declared public var mapLocation: MapLocationable? { return mission } public var isShowInParentMap: Bool { return mission?.isShowInParentMap ?? false } func setupMapLink() { DispatchQueue.main.async { [weak self] in self?.inMapId = self?.mission?.inMapId self?.mapLinkType.setupView() self?.pageLoadStatus.markIsDone(.mapLink) self?.conditionalSpinnerStop() } } } extension MissionController: Notesable { //public var originHint: String? // already declared //public var notes: [Note] // already declared func setupNotes() { mission?.getNotes { [weak self] notes in DispatchQueue.main.async { self?.notes = notes self?.notesView?.controller = self self?.notesView?.setup() self?.pageLoadStatus.markIsDone(.notes) self?.conditionalSpinnerStop() } } } public func getBlankNote() -> Note? { return mission?.newNote() } } extension MissionController: Objectivesable { //public var objectives: [MapLocationable] // already declared func setupObjectives() { DispatchQueue.global(qos: .userInitiated).async { [weak self] in self?.objectives = self?.mission?.getObjectives() ?? [] DispatchQueue.main.async { self?.objectivesView?.controller = self self?.objectivesView?.setup() self?.pageLoadStatus.markIsDone(.objectives) self?.conditionalSpinnerStop() } } } } extension MissionController: OriginHintable { //public var originHint: String? // already declared func setupOriginHint() { DispatchQueue.main.async { [weak self] in if let parentMission = self?.mission?.parentMission { self?.originHintType.overrideOriginPrefix = "Under" self?.originHintType.overrideOriginHint = parentMission.name } else { self?.originHintType.overrideOriginHint = "" // block other origin hint } self?.originHintType.setupView() self?.pageLoadStatus.markIsDone(.originHint) self?.conditionalSpinnerStop() } } } extension MissionController: RelatedLinksable { //public var relatedLinks: [String] // already declared func setupRelatedLinks() { DispatchQueue.global(qos: .userInitiated).async { [weak self] in self?.relatedLinks = self?.mission?.relatedLinks ?? [] DispatchQueue.main.async { self?.relatedLinksView?.controller = self self?.relatedLinksView?.setup() self?.pageLoadStatus.markIsDone(.relatedLinks) self?.conditionalSpinnerStop() } } } } extension MissionController: RelatedMissionsable { //public var relatedMissions: [Mission] // already declared func setupRelatedMissions() { DispatchQueue.global(qos: .userInitiated).async { [weak self] in self?.mission?.getRelatedMissions { (missions: [Mission]) in DispatchQueue.main.async { self?.relatedMissions = missions self?.relatedMissionsView?.controller = self self?.relatedMissionsView?.setup() self?.pageLoadStatus.markIsDone(.relatedMissions) self?.conditionalSpinnerStop() } } } } } extension MissionController: SideEffectsable { //public var sideEffects: [String] // already declared func setupSideEffects() { DispatchQueue.main.async { [weak self] in self?.sideEffects = self?.mission?.sideEffects ?? [] self?.sideEffectsView?.controller = self self?.sideEffectsView?.setup() self?.pageLoadStatus.markIsDone(.sideEffects) self?.conditionalSpinnerStop() } } } extension MissionController: Spinnerable {} // swiftlint:enable file_length
mit
78d72e6ba402b422394bdf506b8959da
27.455487
117
0.723661
4.084398
false
false
false
false
zvonler/PasswordElephant
external/github.com/apple/swift-protobuf/Tests/SwiftProtobufTests/Test_TextFormat_Map_proto3.swift
10
5757
// Tests/SwiftProtobufTests/Test_TextFormat_Map_proto3.swift - Exercise proto3 text format coding // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// This is a set of tests for text format protobuf files. /// // ----------------------------------------------------------------------------- import Foundation import XCTest import SwiftProtobuf class Test_TextFormat_Map_proto3: XCTestCase, PBTestHelpers { typealias MessageTestType = ProtobufUnittest_TestMap func test_Int32Int32() { assertTextFormatEncode("map_int32_int32 {\n key: 1\n value: 2\n}\n") {(o: inout MessageTestType) in o.mapInt32Int32 = [1:2] } assertTextFormatDecodeSucceeds("map_int32_int32 {key: 1, value: 2}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("map_int32_int32 {key: 1; value: 2}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("map_int32_int32 {key:1 value:2}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("map_int32_int32 {key:1 value:2}\nmap_int32_int32 {key:3 value:4}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2, 3:4] } assertTextFormatDecodeSucceeds("map_int32_int32 [{key:1 value:2}, {key:3 value:4}]") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2, 3:4] } assertTextFormatDecodeSucceeds("map_int32_int32 [{key:1 value:2}];map_int32_int32 {key:3 value:4}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2, 3:4] } assertTextFormatDecodeFails("map_int32_int32 [{key:1 value:2},]") assertTextFormatDecodeFails("map_int32_int32 [{key:1 value:2}") assertTextFormatDecodeFails("map_int32_int32 [{key:1 value:2 nonsense:3}") assertTextFormatDecodeFails("map_int32_int32 {key:1}") } func test_Int32Int32_numbers() { assertTextFormatDecodeSucceeds("1 {\n key: 1\n value: 2\n}\n") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("1 {key: 1, value: 2}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("1 {key: 1; value: 2}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("1 {key:1 value:2}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("1 {key:1 value:2}\n1 {key:3 value:4}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2, 3:4] } assertTextFormatDecodeSucceeds("1 [{key:1 value:2}, {key:3 value:4}]") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2, 3:4] } assertTextFormatDecodeSucceeds("1 [{key:1 value:2}];1 {key:3 value:4}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2, 3:4] } assertTextFormatDecodeFails("1 [{key:1 value:2},]") assertTextFormatDecodeFails("1 [{key:1 value:2}") assertTextFormatDecodeFails("1 [{key:1 value:2 nonsense:3}") assertTextFormatDecodeFails("1 {key:1}") // Using numbers for "key" and "value" in the map entries. assertTextFormatDecodeSucceeds("1 {\n 1: 1\n 2: 2\n}\n") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("1 {1: 1, 2: 2}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("1 {1: 1; 2: 2}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("1 {1:1 2:2}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2] } assertTextFormatDecodeSucceeds("1 {1:1 2:2}\n1 {1:3 2:4}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2, 3:4] } assertTextFormatDecodeSucceeds("1 [{1:1 2:2}, {1:3 2:4}]") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2, 3:4] } assertTextFormatDecodeSucceeds("1 [{1:1 2:2}];1 {1:3 2:4}") {(o: MessageTestType) in return o.mapInt32Int32 == [1:2, 3:4] } assertTextFormatDecodeFails("1 [{1:1 2:2},]") assertTextFormatDecodeFails("1 [{1:1 2:2}") assertTextFormatDecodeFails("1 [{1:1 2:2 3:3}") assertTextFormatDecodeFails("1 {1:1}") } func test_StringMessage() { let foo = ProtobufUnittest_ForeignMessage.with {$0.c = 999} assertTextFormatEncode("map_string_foreign_message {\n key: \"foo\"\n value {\n c: 999\n }\n}\n") {(o: inout MessageTestType) in o.mapStringForeignMessage = ["foo": foo] } } func test_StringMessage_numbers() { let foo = ProtobufUnittest_ForeignMessage.with {$0.c = 999} assertTextFormatDecodeSucceeds("18 {\n key: \"foo\"\n value {\n 1: 999\n }\n}\n") {(o: MessageTestType) in o.mapStringForeignMessage == ["foo": foo] } // Using numbers for "key" and "value" in the map entries. assertTextFormatDecodeSucceeds("18 {\n 1: \"foo\"\n 2 {\n 1: 999\n }\n}\n") {(o: MessageTestType) in o.mapStringForeignMessage == ["foo": foo] } } }
gpl-3.0
bd70cc62a1f9b413d898fe21805f2743
43.976563
142
0.589022
3.830339
false
true
false
false
MukeshKumarS/Swift
test/Sema/immutability.swift
3
18237
// RUN: %target-parse-verify-swift func markUsed<T>(t: T) {} let bad_property_1: Int { // expected-error {{'let' declarations cannot be computed properties}} get { return 42 } } let bad_property_2: Int = 0 { get { // expected-error {{use of unresolved identifier 'get'}} return 42 } } let no_initializer : Int func foreach_variable() { for i in 0..<42 { i = 11 // expected-error {{cannot assign to value: 'i' is a 'let' constant}} } } func takeClosure(fn : (Int)->Int) {} func passClosure() { takeClosure { a in a = 42 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} return a } takeClosure { $0 = 42 // expected-error{{cannot assign to value: '$0' is a 'let' constant}} return 42 } takeClosure { (a : Int) -> Int in a = 42 // expected-error{{cannot assign to value: 'a' is a 'let' constant}} return 42 } } class FooClass { class let type_let = 5 // expected-error {{class stored properties not yet supported in classes}} init() { self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}} } func bar() { self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}} } mutating init(a : Bool) {} // expected-error {{'mutating' may only be used on 'func' declarations}} {{3-12=}} mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}} func baz() {} var x : Int { get { return 32 } set(value) { value = 42 // expected-error {{cannot assign to value: 'value' is a 'let' constant}} } } subscript(i : Int) -> Int { get { i = 42 // expected-error {{cannot assign to value: 'i' is immutable}} return 1 } } } func let_decls() { // <rdar://problem/16927246> provide a fixit to change "let" to "var" if needing to mutate a variable let a = 42 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} a = 17 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} let (b,c) = (4, "hello") // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} markUsed(b); markUsed(c) b = 17 // expected-error {{cannot assign to value: 'b' is a 'let' constant}} let d = (4, "hello") // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} markUsed(d.0); markUsed(d.1) d.0 = 17 // expected-error {{cannot assign to property: 'd' is a 'let' constant}} let e = 42 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} ++e // expected-error {{cannot pass immutable value to mutating operator: 'e' is a 'let' constant}} // <rdar://problem/16306600> QoI: passing a 'let' value as an inout results in an unfriendly diagnostic let f = 96 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} var v = 1 swap(&f, &v) // expected-error {{cannot pass immutable value as inout argument: 'f' is a 'let' constant}} // <rdar://problem/19711233> QoI: poor diagnostic for operator-assignment involving immutable operand let g = 14 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} g /= 2 // expected-error {{left side of mutating operator isn't mutable: 'g' is a 'let' constant}} } struct SomeStruct { var iv = 32 static let type_let = 5 // expected-note {{change 'let' to 'var' to make it mutable}} {{10-13=var}} mutating static func f() { // expected-error {{static functions may not be declared mutating}} {{3-12=}} } mutating func g() { iv = 42 } mutating func g2() { iv = 42 } func h() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} iv = 12 // expected-error {{cannot assign to property: 'self' is immutable}} } var p: Int { // Getters default to non-mutating. get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = 37 // expected-error {{cannot assign to property: 'self' is immutable}} return 42 } // Setters default to mutating. set { iv = newValue } } // Defaults can be changed. var q : Int { mutating get { iv = 37 return 42 } nonmutating set { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = newValue // expected-error {{cannot assign to property: 'self' is immutable}} } } var r : Int { get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = 37 // expected-error {{cannot assign to property: 'self' is immutable}} return 42 } mutating // Redundant but OK. set { iv = newValue } } } markUsed(SomeStruct.type_let) // ok SomeStruct.type_let = 17 // expected-error {{cannot assign to property: 'type_let' is a 'let' constant}} struct TestMutableStruct { mutating func f() {} func g() {} var mutating_property : Int { mutating get {} set {} } var nonmutating_property : Int { get {} nonmutating set {} } // This property has a mutating getter and !mutating setter. var weird_property : Int { mutating get {} nonmutating set {} } @mutating func mutating_attr() {} // expected-error {{'mutating' is a declaration modifier, not an attribute}} {{3-4=}} @nonmutating func nonmutating_attr() {} // expected-error {{'nonmutating' is a declaration modifier, not an attribute}} {{3-4=}} } func test_mutability() { // Non-mutable method on rvalue is ok. TestMutableStruct().g() // Non-mutable method on let is ok. let x = TestMutableStruct() // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} x.g() // Mutable methods on let and rvalue are not ok. x.f() // expected-error {{cannot use mutating member on immutable value: 'x' is a 'let' constant}} TestMutableStruct().f() // expected-error {{cannot use mutating member on immutable value: function call returns immutable value}} _ = TestMutableStruct().weird_property // expected-error {{cannot use mutating getter on immutable value: function call returns immutable value}} let tms = TestMutableStruct() // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} _ = tms.weird_property // expected-error {{cannot use mutating getter on immutable value: 'tms' is a 'let' constant}} } func test_arguments(a : Int, var b : Int, // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{21-25=}} let c : Int) { // expected-warning {{Use of 'let' binding here is deprecated and will be removed in a future version of Swift}} {{21-25=}} a = 1 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} b = 2 // ok. c = 3 // expected-error {{cannot assign to value: 'c' is a 'let' constant}} } protocol ClassBoundProtocolMutating : class { mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}} func f() } protocol MutatingTestProto { mutating func mutatingfunc() func nonmutatingfunc() // expected-note {{protocol requires}} } class TestClass : MutatingTestProto { func mutatingfunc() {} // Ok, doesn't need to be mutating. func nonmutatingfunc() {} } struct TestStruct1 : MutatingTestProto { func mutatingfunc() {} // Ok, doesn't need to be mutating. func nonmutatingfunc() {} } struct TestStruct2 : MutatingTestProto { mutating func mutatingfunc() {} // Ok, can be mutating. func nonmutatingfunc() {} } struct TestStruct3 : MutatingTestProto { // expected-error {{type 'TestStruct3' does not conform to protocol 'MutatingTestProto'}} func mutatingfunc() {} // This is not ok, "nonmutatingfunc" doesn't allow mutating functions. mutating func nonmutatingfunc() {} // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } // <rdar://problem/16722603> invalid conformance of mutating setter protocol NonMutatingSubscriptable { subscript(i: Int) -> Int {get nonmutating set} // expected-note {{protocol requires subscript with type '(Int) -> Int'}} } struct MutatingSubscriptor : NonMutatingSubscriptable { // expected-error {{type 'MutatingSubscriptor' does not conform to protocol 'NonMutatingSubscriptable'}} subscript(i: Int) -> Int { get { return 42 } mutating set {} // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } } protocol NonMutatingGet { var a: Int { get } // expected-note {{protocol requires property 'a' with type 'Int'}} } struct MutatingGet : NonMutatingGet { // expected-error {{type 'MutatingGet' does not conform to protocol 'NonMutatingGet'}} var a: Int { mutating get { return 0 } } // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } func test_properties() { let rvalue = TestMutableStruct() // expected-note 4 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} markUsed(rvalue.nonmutating_property) // ok markUsed(rvalue.mutating_property) // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} markUsed(rvalue.weird_property) // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} rvalue.nonmutating_property = 1 // ok rvalue.mutating_property = 1 // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} rvalue.weird_property = 1 // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} var lvalue = TestMutableStruct() markUsed(lvalue.mutating_property) // ok markUsed(lvalue.nonmutating_property) // ok markUsed(lvalue.weird_property) // ok lvalue.mutating_property = 1 // ok lvalue.nonmutating_property = 1 // ok lvalue.weird_property = 1 // ok } struct DuplicateMutating { mutating mutating func f() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} } protocol SubscriptNoGetter { subscript (i: Int) -> Int { get } } func testSubscriptNoGetter(iis: SubscriptNoGetter) { var _: Int = iis[17] } func testSelectorStyleArguments1(x: Int, bar y: Int) { var x = x var y = y ++x; ++y } func testSelectorStyleArguments2(x: Int, bar y: Int) { ++x // expected-error {{cannot pass immutable value to mutating operator: 'x' is a 'let' constant}} ++y // expected-error {{cannot pass immutable value to mutating operator: 'y' is a 'let' constant}} } func invalid_inout(inout var x : Int) { // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{26-30=}} } func updateInt(inout x : Int) {} // rdar://15785677 - allow 'let' declarations in structs/classes be initialized in init() class LetClassMembers { let a : Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let b : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(arg : Int) { a = arg // ok, a is mutable in init() updateInt(&a) // ok, a is mutable in init() and has been initialized b = 17 // ok, b is mutable in init() } func f() { a = 42 // expected-error {{cannot assign to property: 'a' is a 'let' constant}} b = 42 // expected-error {{cannot assign to property: 'b' is a 'let' constant}} updateInt(&a) // expected-error {{cannot pass immutable value as inout argument: 'a' is a 'let' constant}} } } struct LetStructMembers { let a : Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let b : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(arg : Int) { a = arg // ok, a is mutable in init() updateInt(&a) // ok, a is mutable in init() and has been initialized b = 17 // ok, b is mutable in init() } func f() { a = 42 // expected-error {{cannot assign to property: 'a' is a 'let' constant}} b = 42 // expected-error {{cannot assign to property: 'b' is a 'let' constant}} updateInt(&a) // expected-error {{cannot pass immutable value as inout argument: 'a' is a 'let' constant}} } } func QoI() { let x = 97 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} x = 17 // expected-error {{cannot assign to value: 'x' is a 'let' constant}} var get_only: Int { get { return 7 } } get_only = 92 // expected-error {{cannot assign to value: 'get_only' is a get-only property}} } // <rdar://problem/17051675> Structure initializers in an extension cannot assign to constant properties struct rdar17051675_S { let x : Int init(newX: Int) { x = 42 } } extension rdar17051675_S { init(newY: Int) { x = 42 } } struct rdar17051675_S2<T> { let x : Int init(newX: Int) { x = 42 } } extension rdar17051675_S2 { init(newY: Int) { x = 42 } } // <rdar://problem/17400366> let properties should not be mutable in convenience initializers class ClassWithConvenienceInit { let x : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(newX: Int) { x = 42 } convenience init(newY: Int) { self.init(newX: 19) x = 67 // expected-error {{cannot assign to property: 'x' is a 'let' constant}} } } struct StructWithDelegatingInit { let x: Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(x: Int) { self.x = x } init() { self.init(x: 0); self.x = 22 } // expected-error {{cannot assign to property: 'x' is a 'let' constant}} } func test_recovery_missing_name_1(: Int) {} // expected-error {{expected ',' separator}} {{35-35=,}} expected-error {{expected parameter type following ':'}} func test_recovery_missing_name_2(: Int) {} // expected-error {{expected ',' separator}} {{35-35=,}} expected-error {{expected parameter type following ':'}} // <rdar://problem/16792027> compiler infinite loops on a really really mutating function struct F { mutating mutating mutating f() { // expected-error 2 {{duplicate modifier}} expected-note 2 {{modifier already specified here}} expected-error {{consecutive declarations on a line must be separated by ';'}} {{29-29=;}} expected-error 2 {{expected declaration}} } mutating nonmutating func g() { // expected-error {{method may not be declared both mutating and nonmutating}} {{12-24=}} } } protocol SingleIntProperty { var i: Int { get } } struct SingleIntStruct : SingleIntProperty { let i: Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} } extension SingleIntStruct { init(_ other: SingleIntStruct) { other.i = 999 // expected-error {{cannot assign to property: 'i' is a 'let' constant}} } } // <rdar://problem/19370429> QoI: fixit to add "mutating" when assigning to a member of self in a struct // <rdar://problem/17632908> QoI: Modifying struct member in non-mutating function produces difficult to understand error message struct TestSubscriptMutability { let let_arr = [1,2,3] // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} var var_arr = [1,2,3] func nonmutating1() { let_arr[1] = 1 // expected-error {{cannot assign through subscript: 'let_arr' is a 'let' constant}} } func nonmutating2() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} var_arr[1] = 1 // expected-error {{cannot assign through subscript: 'self' is immutable}} } func nonmutating3() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} self = TestSubscriptMutability() // expected-error {{cannot assign to value: 'self' is immutable}} } subscript(a : Int) -> TestSubscriptMutability { return TestSubscriptMutability() } func test() { self[1] = TestSubscriptMutability() // expected-error {{cannot assign through subscript: subscript is get-only}} self[1].var_arr = [] // expected-error {{cannot assign to property: subscript is get-only}} self[1].let_arr = [] // expected-error {{cannot assign to property: 'let_arr' is a 'let' constant}} } } func f(a : TestSubscriptMutability) { a.var_arr = [] // expected-error {{cannot assign to property: 'a' is a 'let' constant}} } struct TestSubscriptMutability2 { subscript(a : Int) -> Int { get { return 42 } set {} } func test() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} self[1] = 2 // expected-error {{cannot assign through subscript: 'self' is immutable}} } } struct TestBangMutability { let let_opt = Optional(1) // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} var var_opt = Optional(1) func nonmutating1() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} let_opt! = 1 // expected-error {{cannot assign through '!': 'let_opt' is a 'let' constant}} var_opt! = 1 // expected-error {{cannot assign through '!': 'self' is immutable}} self[]! = 2 // expected-error {{cannot assign through '!': subscript is get-only}} } mutating func nonmutating2() { let_opt! = 1 // expected-error {{cannot assign through '!': 'let_opt' is a 'let' constant}} var_opt! = 1 // ok self[]! = 2 // expected-error {{cannot assign through '!': subscript is get-only}} } subscript() -> Int? { return nil } } // <rdar://problem/21176945> mutation through ? not considered a mutation func testBindOptional() { var a : TestStruct2? = nil // Mutated through optional chaining. a?.mutatingfunc() }
apache-2.0
31bd569ac7878a22ae7fd08bd93f2acd
33.409434
262
0.633876
3.684987
false
true
false
false
illescasDaniel/Questions
Questions/Models/Topic.swift
1
5421
// // Quiz.swift // Questions // // Created by Daniel Illescas Romero on 24/05/2018. // Copyright © 2018 Daniel Illescas Romero. All rights reserved. // import Foundation struct Topic: Codable { let options: Options? let sets: [[Question]] } extension Topic { struct Options: Codable { let name: String? let timePerSetInSeconds: TimeInterval? let helpButtonEnabled: Bool? let questionsInRandomOrder: Bool? let showCorrectIncorrectAnswer: Bool? let multipleCorrectAnswersAsMandatory: Bool? // case displayFullResults // YET to implement } } extension Topic: Equatable { static func ==(lhs: Topic, rhs: Topic) -> Bool { let flatLhs = lhs.sets.flatMap { return $0 } let flatRhs = rhs.sets.flatMap { return $0 } return flatLhs == flatRhs } } extension Topic { enum ValidationError: Error { case emptySet(count: Int) case emptyQuestion(set: Int, question: Int) case emptyAnswer(set: Int, question: Int, answer: Int) case incorrectAnswersCount(set: Int, question: Int) case incorrectCorrectAnswersCount(set: Int, question: Int, count: Int?) case incorrectCorrectAnswerIndex(set: Int, question: Int, badIndex: Int, maximum: Int) } func validate() -> ValidationError? { guard !self.sets.contains(where: { $0.isEmpty }) else { return .emptySet(count: self.sets.count) } for (indexSet, setOfQuestions) in self.sets.enumerated() { // ~ Number of answers must be consistent in the same set of questions (otherwise don't make this restriction, you might need to make other changes too) let fullQuestionAnswersCount = setOfQuestions.first?.answers.count ?? 4 for (indexQuestion, fullQuestion) in setOfQuestions.enumerated() { if fullQuestion.correctAnswers == nil { fullQuestion.correctAnswers = [] } guard !fullQuestion.question.isEmpty else { return .emptyQuestion(set: indexSet+1, question: indexQuestion+1) } guard fullQuestion.answers.count == fullQuestionAnswersCount, Set(fullQuestion.answers).count == fullQuestionAnswersCount else { return .incorrectAnswersCount(set: indexSet+1, question: indexQuestion+1) } guard !fullQuestion.correctAnswers.contains(where: { $0 >= fullQuestionAnswersCount }), (fullQuestion.correctAnswers?.count ?? 0) < fullQuestionAnswersCount else { return .incorrectCorrectAnswersCount(set: indexSet+1, question: indexQuestion+1, count: fullQuestion.correctAnswers?.count) } if let singleCorrectAnswer = fullQuestion.correct { if singleCorrectAnswer >= fullQuestionAnswersCount { return .incorrectCorrectAnswerIndex(set: indexSet+1, question: indexQuestion+1, badIndex: Int(singleCorrectAnswer)+1, maximum: fullQuestionAnswersCount) } else { fullQuestion.correctAnswers?.insert(singleCorrectAnswer) } } guard let correctAnswers = fullQuestion.correctAnswers, correctAnswers.count < fullQuestionAnswersCount, correctAnswers.count > 0 else { return .incorrectCorrectAnswersCount(set: indexSet+1, question: indexQuestion+1, count: fullQuestion.correctAnswers?.count) } for (indexAnswer, answer) in fullQuestion.answers.enumerated() { if answer.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return .emptyAnswer(set: indexSet+1, question: indexQuestion+1, answer: indexAnswer+1) } } } } return nil } } extension Topic.ValidationError: LocalizedError { var errorDescription: String? { switch self { case .emptySet: return L10n.TopicsCreation_WebView_Validation_Sets_Empty case .emptyQuestion: return L10n.TopicsCreation_WebView_Validation_Questions_Empty case .emptyAnswer: return L10n.TopicsCreation_WebView_Validation_Answers_Empty case .incorrectAnswersCount: return L10n.TopicsCreation_WebView_Validation_Answers_IncorrectCount case .incorrectCorrectAnswersCount: return L10n.TopicsCreation_WebView_Validation_Answers_BadCorrectCount case .incorrectCorrectAnswerIndex: return L10n.TopicsCreation_WebView_Validation_Answers_BadCorrectIndex } } var recoverySuggestion: String? { switch self { case .emptySet(let count): return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Sets_Empty_Recovery, count) case .emptyQuestion(let set, let question): return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Questions_Empty_Recovery, set, question) case .emptyAnswer(let set, let question, let answer): return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Answers_Empty_Recovery, set, question, answer) case .incorrectAnswersCount(let set, let question): return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Answers_IncorrectCount_Recovery, set, question) case .incorrectCorrectAnswersCount(let set, let question, let count): return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Answers_BadCorrectCount_Recovery, set, question, count ?? 0) case .incorrectCorrectAnswerIndex(let set, let question, let badIndex, let maximum): return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Answers_BadCorrectIndex_Recovery, set, question, badIndex, maximum) } } } extension Topic { var inJSON: String { if let data = try? JSONEncoder().encode(self), let jsonQuiz = String(data: data, encoding: .utf8) { return jsonQuiz } return "" } }
mit
32ccb4116548eb2eb360cdda5cd3af8d
38.562044
158
0.755166
4.062969
false
false
false
false
takeo-asai/math-puzzle
problems/05.swift
1
356
// 10x + 50y + 100z + 500w = 1000 // x + y + z + w + s == 15 // s >= 0 (s: slack variable) var combinations: [(Int, Int, Int, Int)] = [] for w in 0 ... 2 { for z in 0 ... 10 { for y in 0 ... 15 { // 20 let x = 100 - 50*w - 10*z - 5*y if x <= 15 - y - z - w && x >= 0 { combinations += [(x, y, z, w)] } } } } print(combinations.count)
mit
69a2e15c7afeffda84edf576e117e773
18.777778
45
0.446629
2.357616
false
false
false
false
BellAppLab/Closures
Closure/Closure/Closure.swift
1
1044
// // Closure.swift // // import Foundation class Thing { let name: String var size: Int? init(name: String, size: Int?) { self.name = name self.size = size } func giveNameIfSize() -> String? { if self.size != nil { return self.name } return nil } } typealias IterationBlock = (Thing) -> Bool class Iterable { private let array: Array<Thing> var count: Int { return self.array.count } init(array: [Thing]) { self.array = array } func iterate(block: IterationBlock) { if self.count == 0 { return } for object in self.array { if block(object) { break } } } var description: String { var result = "Description:" self.iterate { (someThing) -> Bool in result += " " + someThing.name + ", " return false } return result } }
mit
7e6e352ad09da9f986969e6950a61c32
14.818182
49
0.468391
4.192771
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Settings/CellDescriptors/SettingsCellDescriptorFactory+Options.swift
1
17070
// // 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 LocalAuthentication import UIKit import WireSyncEngine import WireCommonComponents extension SettingsCellDescriptorFactory { // MARK: - Options Group var optionsGroup: SettingsCellDescriptorType { let descriptors = [ shareContactsDisabledSection, clearHistorySection, notificationVisibleSection, chatHeadsSection, soundAlertSection, callKitSection, muteCallSection, SecurityFlags.forceConstantBitRateCalls.isEnabled ? nil : VBRSection, soundsSection, externalAppsSection, popularDemandSendButtonSection, popularDemandDarkThemeSection, isAppLockAvailable ? appLockSection : nil, SecurityFlags.generateLinkPreviews.isEnabled ? linkPreviewSection : nil ].compactMap { $0 } return SettingsGroupCellDescriptor( items: descriptors, title: "self.settings.options_menu.title".localized, icon: .settingsOptions, accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description ) } // MARK: - Sections private var shareContactsDisabledSection: SettingsSectionDescriptorType { let settingsButton = SettingsButtonCellDescriptor( title: "self.settings.privacy_contacts_menu.settings_button.title".localized, isDestructive: false, selectAction: { _ in UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!) }) return SettingsSectionDescriptor( cellDescriptors: [settingsButton], header: "self.settings.privacy_contacts_section.title".localized, footer: "self.settings.privacy_contacts_menu.description_disabled.title".localized, visibilityAction: { _ in return AddressBookHelper.sharedHelper.isAddressBookAccessDisabled }) } private var clearHistorySection: SettingsSectionDescriptorType { let clearHistoryButton = SettingsButtonCellDescriptor( title: "self.settings.privacy.clear_history.title".localized, isDestructive: false, selectAction: { _ in // erase history is not supported yet }) return SettingsSectionDescriptor( cellDescriptors: [clearHistoryButton], header: .none, footer: "self.settings.privacy.clear_history.subtitle".localized, visibilityAction: { _ in return false } ) } private var notificationVisibleSection: SettingsSectionDescriptorType { let notificationToggle = SettingsPropertyToggleCellDescriptor( settingsProperty: settingsPropertyFactory.property(.notificationContentVisible), inverse: true ) return SettingsSectionDescriptor( cellDescriptors: [notificationToggle], header: "self.settings.notifications.push_notification.title".localized, footer: "self.settings.notifications.push_notification.footer".localized ) } private var chatHeadsSection: SettingsSectionDescriptorType { let chatHeadsToggle = SettingsPropertyToggleCellDescriptor( settingsProperty: settingsPropertyFactory.property(.chatHeadsDisabled), inverse: true ) return SettingsSectionDescriptor( cellDescriptors: [chatHeadsToggle], header: nil, footer: "self.settings.notifications.chat_alerts.footer".localized ) } private var soundAlertSection: SettingsSectionDescriptorType { return SettingsSectionDescriptor(cellDescriptors: [soundAlertGroup]) } private var callKitSection: SettingsSectionDescriptorType { let callKitToggle = SettingsPropertyToggleCellDescriptor( settingsProperty: settingsPropertyFactory.property(.disableCallKit), inverse: true ) return SettingsSectionDescriptor( cellDescriptors: [callKitToggle], header: "self.settings.callkit.title".localized, footer: "self.settings.callkit.description".localized, visibilityAction: .none ) } private var muteCallSection: SettingsSectionDescriptorType { let muteCallToggle = SettingsPropertyToggleCellDescriptor( settingsProperty: settingsPropertyFactory.property(.muteIncomingCallsWhileInACall), inverse: false ) return SettingsSectionDescriptor( cellDescriptors: [muteCallToggle], footer: L10n.Localizable.Self.Settings.MuteOtherCall.description, visibilityAction: .none ) } private var VBRSection: SettingsSectionDescriptorType { let VBRToggle = SettingsPropertyToggleCellDescriptor( settingsProperty: settingsPropertyFactory.property(.callingConstantBitRate), inverse: true, identifier: "VBRSwitch" ) return SettingsSectionDescriptor( cellDescriptors: [VBRToggle], header: .none, footer: "self.settings.vbr.description".localized, visibilityAction: .none ) } private var soundsSection: SettingsSectionDescriptorType { let callSoundProperty = settingsPropertyFactory.property(.callSoundName) let callSoundGroup = soundGroupForSetting( callSoundProperty, title: callSoundProperty.propertyName.settingsPropertyLabelText, customSounds: ZMSound.ringtones, defaultSound: ZMSound.WireCall ) let messageSoundProperty = settingsPropertyFactory.property(.messageSoundName) let messageSoundGroup = soundGroupForSetting( messageSoundProperty, title: messageSoundProperty.propertyName.settingsPropertyLabelText, customSounds: ZMSound.soundEffects, defaultSound: ZMSound.WireText ) let pingSoundProperty = settingsPropertyFactory.property(.pingSoundName) let pingSoundGroup = soundGroupForSetting( pingSoundProperty, title: pingSoundProperty.propertyName.settingsPropertyLabelText, customSounds: ZMSound.soundEffects, defaultSound: ZMSound.WirePing ) return SettingsSectionDescriptor( cellDescriptors: [callSoundGroup, messageSoundGroup, pingSoundGroup], header: "self.settings.sound_menu.sounds.title".localized ) } private var externalAppsSection: SettingsSectionDescriptorType? { var descriptors = [SettingsCellDescriptorType]() if BrowserOpeningOption.optionsAvailable { descriptors.append(browserOpeningGroup(for: settingsPropertyFactory.property(.browserOpeningOption))) } if MapsOpeningOption.optionsAvailable { descriptors.append(mapsOpeningGroup(for: settingsPropertyFactory.property(.mapsOpeningOption))) } if TweetOpeningOption.optionsAvailable { descriptors.append(twitterOpeningGroup(for: settingsPropertyFactory.property(.tweetOpeningOption))) } guard descriptors.count > 0 else { return nil } return SettingsSectionDescriptor( cellDescriptors: descriptors, header: "self.settings.external_apps.header".localized ) } private var popularDemandSendButtonSection: SettingsSectionDescriptorType { let sendButtonToggle = SettingsPropertyToggleCellDescriptor( settingsProperty: settingsPropertyFactory.property(.disableSendButton), inverse: true ) return SettingsSectionDescriptor( cellDescriptors: [sendButtonToggle], header: "self.settings.popular_demand.title".localized, footer: "self.settings.popular_demand.send_button.footer".localized ) } private var popularDemandDarkThemeSection: SettingsSectionDescriptorType { let darkThemeSection = SettingsCellDescriptorFactory.darkThemeGroup(for: settingsPropertyFactory.property(.darkMode)) return SettingsSectionDescriptor( cellDescriptors: [darkThemeSection], footer: "self.settings.popular_demand.dark_mode.footer".localized ) } private var appLockSection: SettingsSectionDescriptorType { let appLockToggle = SettingsPropertyToggleCellDescriptor(settingsProperty: settingsPropertyFactory.property(.lockApp)) appLockToggle.settingsProperty.enabled = !settingsPropertyFactory.isAppLockForced return SettingsSectionDescriptor( cellDescriptors: [appLockToggle], headerGenerator: { return nil }, footerGenerator: { return self.appLockSectionSubtitle } ) } private var linkPreviewSection: SettingsSectionDescriptorType { let linkPreviewToggle = SettingsPropertyToggleCellDescriptor( settingsProperty: settingsPropertyFactory.property(.disableLinkPreviews), inverse: true ) return SettingsSectionDescriptor( cellDescriptors: [linkPreviewToggle], header: nil, footer: "self.settings.privacy_security.disable_link_previews.footer".localized ) } // MARK: - Helpers static func darkThemeGroup(for property: SettingsProperty) -> SettingsCellDescriptorType { let cells = SettingsColorScheme.allCases.map { option -> SettingsPropertySelectValueCellDescriptor in return SettingsPropertySelectValueCellDescriptor( settingsProperty: property, value: SettingsPropertyValue(option.rawValue), title: option.displayString ) } let section = SettingsSectionDescriptor(cellDescriptors: cells.map { $0 as SettingsCellDescriptorType }) let preview: PreviewGeneratorType = { _ in let value = property.value().value() as? Int guard let option = value.flatMap({ SettingsColorScheme(rawValue: $0) }) else { return .text(SettingsColorScheme.defaultPreference.displayString) } return .text(option.displayString) } return SettingsGroupCellDescriptor(items: [section], title: property.propertyName.settingsPropertyLabelText, identifier: nil, previewGenerator: preview, accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description) } func twitterOpeningGroup(for property: SettingsProperty) -> SettingsCellDescriptorType { let cells = TweetOpeningOption.availableOptions.map { option -> SettingsPropertySelectValueCellDescriptor in return SettingsPropertySelectValueCellDescriptor( settingsProperty: property, value: SettingsPropertyValue(option.rawValue), title: option.displayString ) } let section = SettingsSectionDescriptor(cellDescriptors: cells.map { $0 as SettingsCellDescriptorType }) let preview: PreviewGeneratorType = { _ in let value = property.value().value() as? Int guard let option = value.flatMap({ TweetOpeningOption(rawValue: $0) }) else { return .text(TweetOpeningOption.none.displayString) } return .text(option.displayString) } return SettingsGroupCellDescriptor(items: [section], title: property.propertyName.settingsPropertyLabelText, identifier: nil, previewGenerator: preview, accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description) } func mapsOpeningGroup(for property: SettingsProperty) -> SettingsCellDescriptorType { let cells = MapsOpeningOption.availableOptions.map { option -> SettingsPropertySelectValueCellDescriptor in return SettingsPropertySelectValueCellDescriptor( settingsProperty: property, value: SettingsPropertyValue(option.rawValue), title: option.displayString ) } let section = SettingsSectionDescriptor(cellDescriptors: cells.map { $0 as SettingsCellDescriptorType }, header: nil, footer: "open_link.maps.footer".localized, visibilityAction: nil) let preview: PreviewGeneratorType = { _ in let value = property.value().value() as? Int guard let option = value.flatMap({ MapsOpeningOption(rawValue: $0) }) else { return .text(MapsOpeningOption.apple.displayString) } return .text(option.displayString) } return SettingsGroupCellDescriptor(items: [section], title: property.propertyName.settingsPropertyLabelText, identifier: nil, previewGenerator: preview, accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description) } func browserOpeningGroup(for property: SettingsProperty) -> SettingsCellDescriptorType { let cells = BrowserOpeningOption.availableOptions.map { option -> SettingsPropertySelectValueCellDescriptor in return SettingsPropertySelectValueCellDescriptor( settingsProperty: property, value: SettingsPropertyValue(option.rawValue), title: option.displayString ) } let section = SettingsSectionDescriptor(cellDescriptors: cells.map { $0 as SettingsCellDescriptorType }) let preview: PreviewGeneratorType = { _ in let value = property.value().value() as? Int guard let option = value.flatMap({ BrowserOpeningOption(rawValue: $0) }) else { return .text(BrowserOpeningOption.safari.displayString) } return .text(option.displayString) } return SettingsGroupCellDescriptor(items: [section], title: property.propertyName.settingsPropertyLabelText, identifier: nil, previewGenerator: preview, accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description) } static var appLockFormatter: DateComponentsFormatter { let formatter = DateComponentsFormatter() formatter.unitsStyle = .full formatter.allowedUnits = [.day, .hour, .minute, .second] formatter.zeroFormattingBehavior = .dropAll return formatter } private var appLockSectionSubtitle: String { let timeout = TimeInterval(settingsPropertyFactory.timeout) guard let amount = SettingsCellDescriptorFactory.appLockFormatter.string(from: timeout) else { return "" } let lockDescription = "self.settings.privacy_security.lock_app.subtitle.lock_description".localized(args: amount) let typeKey: String = { switch AuthenticationType.current { case .touchID: return "self.settings.privacy_security.lock_app.subtitle.touch_id" case .faceID: return "self.settings.privacy_security.lock_app.subtitle.face_id" default: return "self.settings.privacy_security.lock_app.subtitle.none" } }() var components = [lockDescription, typeKey.localized] if AuthenticationType.current == .unavailable { let reminderKey = "self.settings.privacy_security.lock_app.subtitle.custom_app_lock_reminder" components.append(reminderKey.localized) } return components.joined(separator: " ") } } // MARK: - Helpers extension SettingsCellDescriptorFactory { // Encryption at rest will trigger its own variant of AppLock. var isAppLockAvailable: Bool { return !SecurityFlags.forceEncryptionAtRest.isEnabled && settingsPropertyFactory.isAppLockAvailable } }
gpl-3.0
5300d712fd8f26d83cf16fb07554675b
42.21519
191
0.663093
6.120473
false
false
false
false
Ryce/HBRPagingView
HBRPagingView/HBRPagingView.swift
1
7669
// // The MIT License (MIT) // // Copyright (c) 2015 Hamon Riazy // // 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 @objc public protocol HBRPagingViewDelegate : NSObjectProtocol, UIScrollViewDelegate { @objc optional func pagingView(_ pagingView: HBRPagingView, shouldSelectPage page: UInt) -> Bool @objc optional func pagingView(_ pagingView: HBRPagingView, didSelectPage page: UInt) } public protocol HBRPagingViewDataSource : NSObjectProtocol { func pagingView(_ pagingView: HBRPagingView, viewForPage index: UInt) -> AnyObject func numberOfPages(_ pagingView: HBRPagingView) -> UInt } public class HBRPagingView: UIScrollView, UIScrollViewDelegate { public weak var pagingDelegate: HBRPagingViewDelegate? public weak var dataSource: HBRPagingViewDataSource? private var cachedPages = [UInt: AnyObject]() private var registeredClasses = [String: AnyClass]() override open func draw(_ rect: CGRect) { super.draw(rect) self.setupView() } open func reloadData() { self.setupView() } private func setupView() { self.isPagingEnabled = true self.delegate = self if self.dataSource == nil { return // BAIL } let nop = self.dataSource!.numberOfPages(self) if nop == 0 { return // BAIL } self.contentSize = CGSize(width: self.bounds.size.width * CGFloat(nop), height: self.bounds.size.height) let pageIndex = self.currentPage() if self.dataSource?.numberOfPages(self) >= pageIndex { if let page: AnyObject = self.dataSource?.pagingView(self, viewForPage: pageIndex) { self.addPage(page, forIndex: pageIndex) } if pageIndex > 0 { if let page: AnyObject = self.dataSource?.pagingView(self, viewForPage: pageIndex - 1) { self.addPage(page, forIndex: pageIndex - 1) } } if self.dataSource?.numberOfPages(self) > pageIndex { if let page: AnyObject = self.dataSource?.pagingView(self, viewForPage: pageIndex + 1) { self.addPage(page, forIndex: pageIndex + 1) } } } } private func addPage(_ page: AnyObject, forIndex pageIndex: UInt) { if let cachedPage: AnyObject = self.cachedPages[pageIndex] { if !cachedPage.isEqual(page) { self.cachedPages[pageIndex] = page if page.superview != self { self.addSubview(page as! UIView) } } } else { self.cachedPages[pageIndex] = page if page.superview != self { self.addSubview(page as! UIView) } } (page as! UIView).frame = CGRect(x: CGFloat(pageIndex) * self.bounds.size.width, y: 0, width: self.bounds.size.width, height: self.bounds.size.height) } open func register(_ pageClass: AnyClass, forPageReuseIdentifier identifier: String) { self.registeredClasses[identifier] = pageClass } open func dequeueReusablePage(with identifier: String, forIndex index: UInt) -> AnyObject { if self.registeredClasses[identifier] == nil { NSException(name: NSExceptionName(rawValue: "PageNotRegisteredException"), reason: "The identifier did not match any of the registered classes", userInfo: nil).raise() return HBRPagingViewPage() } if let page: AnyObject = self.cachedPages[index] { return page } else { for key: UInt in self.cachedPages.keys { let distance = fabs(Double(key) - Double(self.currentPage())) if distance > 1 && self.cachedPages[key]!.isKind(of: self.registeredClasses[identifier]!) { // still have to check if that same object has been used somewhere else let page: AnyObject = self.cachedPages[key]! self.cachedPages.removeValue(forKey: key) return page } } HBRPagingViewPage.self let objType = registeredClasses[identifier] as! HBRPagingViewPage.Type let newInstance = objType.init() newInstance.frame = self.bounds newInstance.contentView.frame = newInstance.bounds return newInstance } } open func scrollViewDidScroll(_ scrollView: UIScrollView) { if let numberOfPages = self.dataSource?.numberOfPages(self) { let offsetAmount = Int(fmin(fmax(0, self.contentOffset.x / self.bounds.size.width), CGFloat(numberOfPages))) let direction = ((offsetAmount - Int(self.currentPage())) == 0 ? 1 : -1) let index = Int(self.currentPage()) + direction if index >= Int(numberOfPages) { return } if let page: AnyObject = self.dataSource?.pagingView(self, viewForPage: UInt(index)) { self.addPage(page, forIndex: UInt(index)) } } } func currentPage() -> UInt { return UInt(round(self.contentOffset.x/self.bounds.size.width)) } } import UIKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } open class HBRPagingViewPage: UIView { open let contentView = UIView() open override func draw(_ rect: CGRect) { super.draw(rect) self.contentView.frame = self.bounds self.addSubview(self.contentView) } }
mit
7ba4cef5bc0d9fa1b5bb52cc94d5b5d7
36.965347
179
0.624593
4.763354
false
false
false
false
Constructor-io/constructorio-client-swift
AutocompleteClientTests/FW/Logic/Request/Mock/AbstractAutocompleteViewModel+Mock.swift
1
2213
// // AbstractAutocompleteViewModel+Mock.swift // AutocompleteClientTests // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import XCTest @testable import ConstructorAutocomplete public class MockAutocompleteViewModel: AbstractAutocompleteViewModel { public private(set) var searchTerm: String public var results: [AutocompleteViewModelSection] public var screenTitle: String public var modelSorter: (String, String) -> Bool = { return $0 < $1 } public weak var delegate: AutocompleteViewModelDelegate? public init() { self.results = [] self.searchTerm = "" self.screenTitle = "title" } public var lastResult: AutocompleteResult? internal func setupDataFromResult(result: AutocompleteResult) { self.searchTerm = result.query.query self.setResultFromDictionary(dictionary: result.response?.sections) self.lastResult = result self.delegate?.viewModel(self, didSetResult: result) } internal func setResultFromDictionary(dictionary: [String: [CIOAutocompleteResult]]?) { self.results = (dictionary ?? [:]).map { (section, items) in AutocompleteViewModelSection(items: items, sectionName: section) } .sorted { (s1, s2) in self.modelSorter(s1.sectionName, s2.sectionName) } } public func set(searchResult: AutocompleteResult, completionHandler: @escaping () -> Void) { if let lastResult = self.lastResult { if searchResult.isInitiatedAfter(result: lastResult) { self.setupDataFromResult(result: searchResult) } else { self.delegate?.viewModel(self, didIgnoreResult: searchResult) } } else { // no previous result, this one must be valid self.setupDataFromResult(result: searchResult) } DispatchQueue.main.async(execute: completionHandler) } public func getResult(atIndexPath indexPath: IndexPath) -> CIOAutocompleteResult { return results[indexPath.section].items[indexPath.row] } public func getSectionName(atIndex index: Int) -> String { return results[index].sectionName } }
mit
63a26b81efbaaa330080c7f613f530e7
33.030769
135
0.680832
4.767241
false
false
false
false
Holmusk/HMRequestFramework-iOS
HMRequestFramework-FullDemo/controller/profile/UserProfileVC.swift
1
9791
// // UserProfileVC.swift // HMRequestFramework-FullDemo // // Created by Hai Pham on 17/1/18. // Copyright © 2018 Holmusk. All rights reserved. // import HMReactiveRedux import HMRequestFramework import RxDataSources import RxSwift import SwiftFP import SwiftUIUtilities import UIKit public final class UserProfileVC: UIViewController { public typealias Section = SectionModel<String,UserInformation> public typealias DataSource = RxTableViewSectionedReloadDataSource<Section> @IBOutlet fileprivate weak var nameLbl: UILabel! @IBOutlet fileprivate weak var ageLbl: UILabel! @IBOutlet fileprivate weak var visibleLbl: UILabel! @IBOutlet fileprivate weak var tableView: UITableView! @IBOutlet fileprivate weak var persistBtn: UIButton! fileprivate var insertUserBtn: UIBarButtonItem? { return navigationItem.rightBarButtonItem } fileprivate let disposeBag = DisposeBag() fileprivate let decorator = UserProfileVCDecorator() public var viewModel: UserProfileViewModel? override public func viewDidLoad() { super.viewDidLoad() setupViews(self) bindViewModel(self) } } extension UserProfileVC: UITableViewDelegate { public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 1 } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() view.backgroundColor = .black return view } public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } } public extension UserProfileVC { fileprivate func setupViews(_ controller: UserProfileVC) { guard let tableView = controller.tableView else { return } tableView.registerNib(UserTextCell.self) controller.navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Insert new user", style: .done, target: nil, action: nil) } fileprivate func setupDataSource(_ controller: UserProfileVC) -> DataSource { let dataSource = DataSource(configureCell: {[weak controller] in if let controller = controller { return controller.configureCells($0, $1, $2, $3, controller) } else { return UITableViewCell() } }) dataSource.canMoveRowAtIndexPath = {(_, _) in false} dataSource.canEditRowAtIndexPath = {(_, _) in false} return dataSource } fileprivate func configureCells(_ source: TableViewSectionedDataSource<Section>, _ tableView: UITableView, _ indexPath: IndexPath, _ item: Section.Item, _ controller: UserProfileVC) -> UITableViewCell { guard let vm = controller.viewModel else { return UITableViewCell() } let decorator = controller.decorator if let cell = tableView.deque(UserTextCell.self, at: indexPath), let cm = vm.vmForUserTextCell(item) { cell.viewModel = cm cell.decorate(decorator, item) return cell } else { return UITableViewCell() } } } public extension UserProfileVC { fileprivate func bindViewModel(_ controller: UserProfileVC) { guard let vm = controller.viewModel, let tableView = controller.tableView, let insertUserBtn = controller.insertUserBtn, let persistBtn = controller.persistBtn, let nameLbl = controller.nameLbl, let ageLbl = controller.ageLbl, let visibleLbl = controller.visibleLbl else { return } vm.setupBindings() let disposeBag = controller.disposeBag let dataSource = controller.setupDataSource(controller) tableView.rx.setDelegate(controller).disposed(by: disposeBag) Observable.just(UserInformation.allValues()) .map({SectionModel(model: "", items: $0)}) .map({[$0]}) .observeOnMain() .bind(to: tableView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) vm.userNameStream() .mapNonNilOrElse({$0.value}, "No information yet") .observeOnMain() .bind(to: nameLbl.rx.text) .disposed(by: disposeBag) vm.userAgeStream() .mapNonNilOrElse({$0.value}, "No information yet") .observeOnMain() .bind(to: ageLbl.rx.text) .disposed(by: disposeBag) vm.userVisibilityStream() .mapNonNilOrElse({$0.value}, "No information yet") .observeOnMain() .bind(to: visibleLbl.rx.text) .disposed(by: disposeBag) insertUserBtn.rx.tap .throttle(0.3, scheduler: MainScheduler.instance) .bind(to: vm.insertUserTrigger()) .disposed(by: disposeBag) persistBtn.rx.tap .throttle(0.3, scheduler: MainScheduler.instance) .bind(to: vm.persistDataTrigger()) .disposed(by: disposeBag) } } public struct UserProfileVCDecorator: UserTextCellDecoratorType { public func inputFieldKeyboard(_ info: UserInformation) -> UIKeyboardType { switch info { case .age: return .numberPad case .name: return .default } } } public struct UserProfileModel { fileprivate let provider: SingletonType public init(_ provider: SingletonType) { self.provider = provider } public func dbUserStream() -> Observable<Try<User>> { return provider.trackedObjectManager.dbUserStream() } public func updateUserInDB(_ user: Try<User>) -> Observable<Try<Void>> { let requestManager = provider.dbRequestManager let prev = user.map({[$0]}) let qos: DispatchQoS.QoSClass = .background return requestManager.upsertInMemory(prev, qos).map({$0.map({_ in})}) } public func persistToDB<Prev>(_ prev: Try<Prev>) -> Observable<Try<Void>> { let requestManager = provider.dbRequestManager let qos: DispatchQoS.QoSClass = .background return requestManager.persistToDB(prev, qos) } public func userName(_ user: User) -> String { return "Name: \(user.name.getOrElse(""))" } public func userAge(_ user: User) -> String { return "Age: \(user.age.getOrElse(0))" } public func userVisibility(_ user: User) -> String { return "Visibility: \(user.visible.map({$0.boolValue}).getOrElse(false))" } } public struct UserProfileViewModel { fileprivate let provider: SingletonType fileprivate let model: UserProfileModel fileprivate let disposeBag: DisposeBag fileprivate let insertUser: PublishSubject<Void> fileprivate let persistData: PublishSubject<Void> public init(_ provider: SingletonType, _ model: UserProfileModel) { self.provider = provider self.model = model disposeBag = DisposeBag() insertUser = PublishSubject() persistData = PublishSubject() } public func setupBindings() { let provider = self.provider let disposeBag = self.disposeBag let model = self.model let actionTrigger = provider.reduxStore.actionTrigger() let insertTriggered = userOnInsertTriggered().share(replay: 1) let insertPerformed = insertTriggered .map(Try.success) .flatMapLatest({model.updateUserInDB($0)}) .share(replay: 1) let persistTriggered = persistDataStream().share(replay: 1) let persistPerformed = persistTriggered .map(Try.success) .flatMapLatest({model.persistToDB($0)}) .share(replay: 1) Observable<Error> .merge(insertPerformed.mapNonNilOrEmpty({$0.error}), persistPerformed.mapNonNilOrEmpty({$0.error})) .map(GeneralReduxAction.Error.Display.updateShowError) .observeOnMain() .bind(to: actionTrigger) .disposed(by: disposeBag) Observable<Bool> .merge(insertTriggered.map({_ in true}), insertPerformed.map({_ in false}), persistTriggered.map({_ in true}), persistPerformed.map({_ in false})) .map(GeneralReduxAction.Progress.Display.updateShowProgress) .observeOnMain() .bind(to: actionTrigger) .disposed(by: disposeBag) } public func vmForUserTextCell(_ info: UserInformation) -> UserTextCellViewModel? { let provider = self.provider switch info { case .age: let model = UserAgeTextCellModel(provider) return UserTextCellViewModel(provider, model) case .name: let model = UserNameTextCellModel(provider) return UserTextCellViewModel(provider, model) } } public func userNameStream() -> Observable<Try<String>> { let model = self.model return model.dbUserStream().map({$0.map({model.userName($0)})}) } public func userAgeStream() -> Observable<Try<String>> { let model = self.model return model.dbUserStream().map({$0.map({model.userAge($0)})}) } public func userVisibilityStream() -> Observable<Try<String>> { let model = self.model return model.dbUserStream().map({$0.map({model.userVisibility($0)})}) } public func insertUserTrigger() -> AnyObserver<Void> { return insertUser.asObserver() } public func insertUserStream() -> Observable<Void> { return insertUser.asObservable() } public func userOnInsertTriggered() -> Observable<User> { return insertUserStream().map({User.builder() .with(name: "Hai Pham - \(String.random(withLength: 5))") .with(id: UUID().uuidString) .with(age: NSNumber(value: Int.randomBetween(10, 99))) .with(visible: NSNumber(value: true)) .build() }) } public func persistDataTrigger() -> AnyObserver<Void> { return persistData.asObserver() } public func persistDataStream() -> Observable<Void> { return persistData.asObservable() } }
apache-2.0
83dc8d830d24693ccfa40c0905221fed
28.847561
84
0.676404
4.570495
false
false
false
false
loganSims/wsdot-ios-app
wsdot/MyRouteCamerasViewController.swift
2
2522
// // MyRouteCameras.swift // WSDOT // // Copyright (c) 2019 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import UIKit import RealmSwift import SafariServices class MyRouteCamerasViewController: CameraClusterViewController { var route: MyRouteItem! override func viewDidLoad() { super.viewDidLoad() loadCamerasOnRoute(force: true) } func loadCamerasOnRoute(force: Bool){ if route != nil { let serviceGroup = DispatchGroup(); requestCamerasUpdate(force, serviceGroup: serviceGroup) serviceGroup.notify(queue: DispatchQueue.main) { if !self.route.foundCameras { _ = MyRouteStore.getNearbyCameraIds(forRoute: self.route) } let nearbyCameras = CamerasStore.getCamerasByID(Array(self.route.cameraIds)) self.cameraItems.removeAll() self.cameraItems.append(contentsOf: nearbyCameras) self.tableView.reloadData() if self.cameraItems.count == 0 { self.tableView.isHidden = true } else { self.tableView.isHidden = false } } } } fileprivate func requestCamerasUpdate(_ force: Bool, serviceGroup: DispatchGroup) { serviceGroup.enter() CamerasStore.updateCameras(force, completion: { error in if (error != nil) { serviceGroup.leave() DispatchQueue.main.async { AlertMessages.getConnectionAlert(backupURL: nil) } } serviceGroup.leave() }) } }
gpl-3.0
e44a7bc25dff7ea6d43903189bf95bb9
30.924051
92
0.579302
5.221532
false
false
false
false
danieltskv/swift-memory-game
MemoryGame/MemoryGame/Model/MemoryGame.swift
1
3602
// // MemoryGameController.swift // MemoryGame // // Created by Daniel Tsirulnikov on 19.3.2016. // Copyright © 2016 Daniel Tsirulnikov. All rights reserved. // import Foundation import UIKit.UIImage // MARK: - MemoryGameDelegate protocol MemoryGameDelegate { func memoryGameDidStart(game: MemoryGame) func memoryGame(game: MemoryGame, showCards cards: [Card]) func memoryGame(game: MemoryGame, hideCards cards: [Card]) func memoryGameDidEnd(game: MemoryGame, elapsedTime: NSTimeInterval) } // MARK: - MemoryGame class MemoryGame { // MARK: - Properties static var defaultCardImages:[UIImage] = [ UIImage(named: "brand1")!, UIImage(named: "brand2")!, UIImage(named: "brand3")!, UIImage(named: "brand4")!, UIImage(named: "brand5")!, UIImage(named: "brand6")! ]; var cards:[Card] = [Card]() var delegate: MemoryGameDelegate? var isPlaying: Bool = false private var cardsShown:[Card] = [Card]() private var startTime:NSDate? var numberOfCards: Int { get { return cards.count } } var elapsedTime : NSTimeInterval { get { guard startTime != nil else { return -1 } return NSDate().timeIntervalSinceDate(startTime!) } } // MARK: - Methods func newGame(cardsData:[UIImage]) { cards = randomCards(cardsData) startTime = NSDate.init() isPlaying = true delegate?.memoryGameDidStart(self) } func stopGame() { isPlaying = false cards.removeAll() cardsShown.removeAll() startTime = nil } func didSelectCard(card: Card?) { guard let card = card else { return } delegate?.memoryGame(self, showCards: [card]) if unpairedCardShown() { let unpaired = unpairedCard()! if card.equals(unpaired) { cardsShown.append(card) } else { let unpairedCard = cardsShown.removeLast() let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.delegate?.memoryGame(self, hideCards:[card, unpairedCard]) } } } else { cardsShown.append(card) } if cardsShown.count == cards.count { finishGame() } } func cardAtIndex(index: Int) -> Card? { if cards.count > index { return cards[index] } else { return nil } } func indexForCard(card: Card) -> Int? { for index in 0...cards.count-1 { if card === cards[index] { return index } } return nil } private func finishGame() { isPlaying = false delegate?.memoryGameDidEnd(self, elapsedTime: elapsedTime) } private func unpairedCardShown() -> Bool { return cardsShown.count % 2 != 0 } private func unpairedCard() -> Card? { let unpairedCard = cardsShown.last return unpairedCard } private func randomCards(cardsData:[UIImage]) -> [Card] { var cards = [Card]() for i in 0...cardsData.count-1 { let card = Card.init(image: cardsData[i]) cards.appendContentsOf([card, Card.init(card: card)]) } cards.shuffle() return cards } }
apache-2.0
24d899f80ca07a3419ac2a88cfa21a56
24.546099
97
0.552069
4.587261
false
false
false
false
CleanCocoa/FatSidebar
FatSidebar/FatSidebarItem.swift
1
19052
// Copyright © 2017 Christian Tietze. All rights reserved. Distributed under the MIT License. import Cocoa extension NSLayoutConstraint { func prioritized(_ priority: Float) -> NSLayoutConstraint { self.priority = NSLayoutConstraint.Priority(rawValue: priority) return self } } extension NSScrollView { var scrolledY: CGFloat { return self.contentView.bounds.origin.y } } public class FatSidebarItem: NSView { public enum Style { /// Displays label below image case regular /// Displays image only, label in overlay view on hover case small(iconSize: CGFloat, padding: CGFloat) public var supportsHovering: Bool { switch self { case .regular: return false case .small: return true } } } public let callback: ((FatSidebarItem) -> Void)? public var selectionHandler: ((FatSidebarItem) -> Void)? public var editHandler: ((FatSidebarItem) -> Void)? public var doubleClickHandler: ((FatSidebarItem) -> Void)? public var animated: Bool let label: NSTextField public var title: String { set { label.stringValue = newValue } get { return label.stringValue } } let imageView: NSImageView public var image: NSImage? { set { imageView.image = newValue } get { return imageView.image } } public internal(set) var style: Style { didSet { layoutSubviews(style: style) redraw() } } public internal(set) var theme: FatSidebarTheme = DefaultTheme() { didSet { adjustLabelFont() redraw() } } convenience public init( title: String, image: NSImage? = nil, shadow: NSShadow? = nil, animated: Bool = false, style: Style = .regular, callback: ((FatSidebarItem) -> Void)?) { let configuration = FatSidebarItemConfiguration( title: title, image: image, shadow: shadow, animated: animated, callback: callback) self.init(configuration: configuration, style: style) } required public init(configuration: FatSidebarItemConfiguration, style: Style) { self.style = style self.label = NSTextField.newWrappingLabel( title: configuration.title, controlSize: .small) self.label.alignment = .center self.imageView = NSImageView() self.imageView.wantsLayer = true self.imageView.shadow = configuration.shadow self.imageView.image = configuration.image self.imageView.imageScaling = .scaleProportionallyUpOrDown self.animated = configuration.animated self.callback = configuration.callback super.init(frame: NSZeroRect) self.translatesAutoresizingMaskIntoConstraints = false layoutSubviews(style: style) } required public init?(coder: NSCoder) { fatalError("init(coder:) not implemented") } fileprivate func layoutSubviews(style: Style) { resetSubviews() switch style { case .regular: layoutRegularSubviews() case let .small(iconSize: iconSize, padding: padding): layoutSmallSubviews(iconSize: iconSize, padding: padding) } } private var topSpacing: NSView? private var bottomSpacing: NSView? private var imageContainer: NSView? private var styleLayoutConstraints: [NSLayoutConstraint] = [] private func resetSubviews() { self.removeConstraints(styleLayoutConstraints) styleLayoutConstraints = [] imageContainer?.removeFromSuperview() imageView.removeFromSuperview() label.removeFromSuperview() topSpacing?.removeFromSuperview() bottomSpacing?.removeFromSuperview() } fileprivate func layoutRegularSubviews() { self.imageView.translatesAutoresizingMaskIntoConstraints = false self.imageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical) self.imageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) self.addSubview(self.imageView) self.label.translatesAutoresizingMaskIntoConstraints = false self.addSubview(self.label) let topSpacing = NSView() topSpacing.translatesAutoresizingMaskIntoConstraints = false self.addSubview(topSpacing) self.topSpacing = topSpacing let topSpacingConstraints = [ // 1px width, horizontally centered NSLayoutConstraint(item: topSpacing, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 1), NSLayoutConstraint(item: topSpacing, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0), // 20% size NSLayoutConstraint(item: topSpacing, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0.2, constant: 1) ] self.styleLayoutConstraints.append(contentsOf: topSpacingConstraints) self.addConstraints(topSpacingConstraints) let bottomSpacing = NSView() bottomSpacing.translatesAutoresizingMaskIntoConstraints = false self.addSubview(bottomSpacing) self.bottomSpacing = bottomSpacing let bottomSpacingConstraints = [ // 1px width, horizontally centered NSLayoutConstraint(item: bottomSpacing, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 1), NSLayoutConstraint(item: bottomSpacing, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0), // 30% size NSLayoutConstraint(item: bottomSpacing, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0.3, constant: 1) ] self.styleLayoutConstraints.append(contentsOf: bottomSpacingConstraints) self.addConstraints(bottomSpacingConstraints) let viewsDict: [String : Any] = [ "topSpace" : topSpacing, "imageView" : self.imageView, "label" : self.label, "bottomSpace" : bottomSpacing ] let mainConstraints = [ NSLayoutConstraint.constraints( withVisualFormat: "V:|[topSpace][imageView][bottomSpace]|", options: [], metrics: nil, views: viewsDict), NSLayoutConstraint.constraints( withVisualFormat: "V:[label]-(>=4@1000)-|", options: [], metrics: nil, views: viewsDict), NSLayoutConstraint.constraints( withVisualFormat: "V:[label]-(4@250)-|", options: [], metrics: nil, views: viewsDict), ] .flattened() .appending(NSLayoutConstraint(item: self.label, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) .appending(NSLayoutConstraint(item: self.label, attribute: .centerY, relatedBy: .equal, toItem: bottomSpacing, attribute: .centerY, multiplier: 0.95, constant: 0).prioritized(250)) .appending(NSLayoutConstraint(item: self.imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) self.addConstraints(mainConstraints) self.styleLayoutConstraints.append(contentsOf: mainConstraints) label.setNeedsDisplay() } public override func layout() { if case .regular = self.style { self.label.preferredMaxLayoutWidth = NSWidth(self.label.alignmentRect(forFrame: self.frame)) } super.layout() } fileprivate func layoutSmallSubviews(iconSize: CGFloat, padding: CGFloat) { self.label.translatesAutoresizingMaskIntoConstraints = false self.addSubview(label) let imageContainer = NSView() imageContainer.identifier = .init(rawValue: "imageContainer") imageContainer.translatesAutoresizingMaskIntoConstraints = false self.addSubview(imageContainer) self.imageContainer = imageContainer self.imageView.translatesAutoresizingMaskIntoConstraints = false self.imageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical) self.imageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) imageContainer.addSubview(self.imageView) let viewsDict: [String : Any] = [ "container" : imageContainer, "imageView" : self.imageView, "label" : self.label, ] let mainConstraints: [NSLayoutConstraint] = [ NSLayoutConstraint.constraints( withVisualFormat: "V:|[container]|", options: [], metrics: nil, views: viewsDict), NSLayoutConstraint.constraints( withVisualFormat: "H:|[container]-1-[label]", // Open to the right options: [], metrics: nil, views: viewsDict), NSLayoutConstraint.constraints( withVisualFormat: "V:|-(\(padding))-[imageView]-(\(padding))-|", options: [], metrics: nil, views: viewsDict) ] .flattened() .appending(NSLayoutConstraint(item: self.label, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) .appending(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: iconSize)) .appending(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 1, constant: 0)) self.addConstraints(mainConstraints) self.styleLayoutConstraints.append(contentsOf: mainConstraints) imageContainer.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "H:|-(\(padding))-[imageView]-(\(padding))-|", options: [], metrics: nil, views: viewsDict)) } // MARK: - Custom Drawing fileprivate func adjustLabelFont() { self.label.font = theme.itemStyle.font ?? label.fittingSystemFont() } fileprivate func redraw() { self.needsDisplay = true self.label.textColor = theme.itemStyle.labelColor .color(isHighlighted: self.isHighlighted, isSelected: self.isSelected) self.label.cell?.backgroundStyle = theme.itemStyle.background.backgroundStyle } var borderWidth: CGFloat = 1 public override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) drawBackground(dirtyRect) drawBorders(dirtyRect) } fileprivate func drawBackground(_ dirtyRect: NSRect) { theme.itemStyle.background.color(isHighlighted: isHighlighted, isSelected: isSelected).setFill() dirtyRect.fill() } fileprivate func drawBorders(_ dirtyRect: NSRect) { if let leftBorderColor = theme.itemStyle.borders.left { let border = NSRect(x: 0, y: 0, width: borderWidth, height: dirtyRect.height) leftBorderColor.color(isHighlighted: isHighlighted, isSelected: isSelected).setFill() border.fill() } if let topBorderColor = theme.itemStyle.borders.top { let border = NSRect(x: 0, y: dirtyRect.maxY - borderWidth, width: dirtyRect.width, height: borderWidth) topBorderColor.color(isHighlighted: isHighlighted, isSelected: isSelected).setFill() border.fill() } if let rightBorderColor = theme.itemStyle.borders.right { let border = NSRect(x: dirtyRect.maxX - borderWidth, y: 0, width: borderWidth, height: dirtyRect.height) rightBorderColor.color(isHighlighted: isHighlighted, isSelected: isSelected).setFill() border.fill() } if let bottomBorderColor = theme.itemStyle.borders.bottom { let border = NSRect(x: 0, y: dirtyRect.minY, width: dirtyRect.width, height: borderWidth) bottomBorderColor.color(isHighlighted: isHighlighted, isSelected: isSelected).setFill() border.fill() } } // MARK: - Interaction public internal(set) var isSelected = false { didSet { redraw() overlay?.isSelected = isSelected } } public fileprivate(set) var isHighlighted = false { didSet { redraw() } } // MARK: Dragging /// Shared flag to make sure that when some item is being clicked, moving /// the mouse does not trigger hover effects on adjacent items. private static var startedDragging = false struct Dragging { static let threshold: TimeInterval = 0.4 let initialEvent: NSEvent var dragTimer: Timer? var isDragging = false } var dragging: Dragging? public override func mouseDown(with event: NSEvent) { isHighlighted = true let dragTimer = Timer.scheduledTimer( timeInterval: Dragging.threshold, target: self, selector: #selector(mouseHeld(_:)), userInfo: event, repeats: false) self.dragging = Dragging( initialEvent: event, dragTimer: dragTimer, isDragging: false) FatSidebarItem.startedDragging = true } @objc func mouseHeld(_ timer: Timer) { self.dragging?.isDragging = true guard let event = timer.userInfo as? NSEvent, let target = superview as? DragViewContainer else { return } target.reorder(subview: self, event: event) } public override func mouseUp(with event: NSEvent) { FatSidebarItem.startedDragging = false isHighlighted = false defer { dragging?.dragTimer?.invalidate() dragging = nil } if event.clickCount == 2 { doubleClickHandler?(self) return } guard let dragging = dragging, !dragging.isDragging else { return } selectionHandler?(self) sendAction() } public func sendAction() { callback?(self) } /// - note: Can be used as action from Interface Builder. @IBAction public func editFatSidebarItem(_ sender: Any?) { editHandler?(self) } /// - note: Can be used as action from Interface Builder. @IBAction public func removeFatSidebarItem(_ sender: Any?) { // Forward event from here because if the sidebar // would receive the NSMenuItem action, it wouldn't // be able to figure out the affected item. guard let sidebar = self.superview as? FatSidebarView else { preconditionFailure("Expected superview to be FatSidebarView") } sidebar.removeItem(self) } // MARK: - Mouse Hover private var overlay: FatSidebarItemOverlay? { didSet { guard overlay == nil, let oldOverlay = oldValue else { return } NotificationCenter.default.removeObserver(oldOverlay) } } private var isDisplayingOverlay: Bool { return overlay != nil } public override func mouseEntered(with event: NSEvent) { if FatSidebarItem.startedDragging { return } if isDisplayingOverlay { return } NotificationCenter.default.post( name: FatSidebarItemOverlay.hoverStarted, object: self) guard style.supportsHovering else { return } showHoverItem() } private func showHoverItem() { guard let superview = self.superview, let windowContentView = self.window?.contentView else { return } self.overlay = { let overlayFrame = superview.convert(self.frame, to: nil) let overlay = FatSidebarItemOverlay( title: self.title, image: self.image, style: self.style, callback: self.callback) overlay.wantsLayer = true overlay.layer?.zPosition = CGFloat(Float.greatestFiniteMagnitude) overlay.frame = overlayFrame overlay.base = self overlay.theme = self.theme overlay.isSelected = self.isSelected overlay.translatesAutoresizingMaskIntoConstraints = true overlay.editHandler = { [weak self] _ in guard let item = self else { return } item.editHandler?(item) } overlay.doubleClickHandler = { [weak self] _ in guard let item = self else { return } item.doubleClickHandler?(item) } overlay.selectionHandler = { [weak self] _ in guard let item = self else { return } item.selectionHandler?(item) } overlay.overlayFinished = { [weak self] in self?.overlay = nil } NotificationCenter.default.addObserver( overlay, selector: #selector(FatSidebarItemOverlay.hoverDidStart), name: FatSidebarItemOverlay.hoverStarted, object: nil) if let scrollView = enclosingScrollView { overlay.setupScrollSyncing(scrollView: scrollView) } windowContentView.addSubview( overlay, positioned: .above, relativeTo: windowContentView.subviews.first ?? self) (animated ? overlay.animator() : overlay) .frame = { // Proportional right spacing looks best in all circumstances: let rightPadding: CGFloat = self.frame.height * 0.1 var frame = overlayFrame frame.size.width += self.label.frame.width + rightPadding return frame }() return overlay }() } private var trackingArea: NSTrackingArea? public override func updateTrackingAreas() { super.updateTrackingAreas() if let oldTrackingArea = trackingArea { self.removeTrackingArea(oldTrackingArea) } let newTrackingArea = NSTrackingArea( rect: self.bounds, options: [.mouseEnteredAndExited, .activeInKeyWindow], owner: self, userInfo: nil) self.addTrackingArea(newTrackingArea) self.trackingArea = newTrackingArea } } extension Array { func appending(_ newElement: Element) -> [Element] { var result = self result.append(newElement) return result } } extension Array where Element: Sequence { func flattened() -> [Element.Element] { return self.flatMap { $0 } } }
mit
f96a0ed2acdabfb1795f532b8e1099eb
32.959002
192
0.623117
5.327461
false
false
false
false
OscarSwanros/swift
tools/SwiftSyntax/SwiftSyntax.swift
5
2090
//===--------------- SwiftLanguage.swift - Swift Syntax Library -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This file provides main entry point into the Syntax library. //===----------------------------------------------------------------------===// import Foundation /// A list of possible errors that could be encountered while parsing a /// Syntax tree. public enum ParserError: Error { case swiftcFailed(Int, String) case invalidFile } extension Syntax { /// Parses the Swift file at the provided URL into a full-fidelity `Syntax` /// tree. /// - Parameter url: The URL you wish to parse. /// - Returns: A top-level Syntax node representing the contents of the tree, /// if the parse was successful. /// - Throws: `ParseError.couldNotFindSwiftc` if `swiftc` could not be /// located, `ParseError.invalidFile` if the file is invalid. /// FIXME: Fill this out with all error cases. public static func parse(_ url: URL) throws -> SourceFileSyntax { let swiftcRunner = try SwiftcRunner(sourceFile: url) let result = try swiftcRunner.invoke() guard result.wasSuccessful else { throw ParserError.swiftcFailed(result.exitCode, result.stderr) } let decoder = JSONDecoder() let raw = try decoder.decode([RawSyntax].self, from: result.stdoutData) let topLevelNodes = raw.map { Syntax.fromRaw($0) } let eof = topLevelNodes.last! as! TokenSyntax let decls = Array(topLevelNodes.dropLast()) as! [DeclSyntax] let declList = SyntaxFactory.makeDeclList(decls) return SyntaxFactory.makeSourceFile(topLevelDecls: declList, eofToken: eof) } }
apache-2.0
3f968add517621439b1fd7a52c1438f8
42.541667
80
0.633493
4.675615
false
false
false
false
OscarSwanros/swift
benchmark/single-source/DropWhile.swift
2
7022
//===--- DropWhile.swift --------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //////////////////////////////////////////////////////////////////////////////// // WARNING: This file is manually generated from .gyb template and should not // be directly modified. Instead, make changes to DropWhile.swift.gyb and run // scripts/generate_harness/generate_harness.py to regenerate this file. //////////////////////////////////////////////////////////////////////////////// import TestsUtils let sequenceCount = 4096 let dropCount = 1024 let suffixCount = sequenceCount - dropCount let sumCount = suffixCount * (2 * sequenceCount - suffixCount - 1) / 2 public let DropWhile = [ BenchmarkInfo( name: "DropWhileCountableRange", runFunction: run_DropWhileCountableRange, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileSequence", runFunction: run_DropWhileSequence, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileAnySequence", runFunction: run_DropWhileAnySequence, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileAnySeqCntRange", runFunction: run_DropWhileAnySeqCntRange, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileAnySeqCRangeIter", runFunction: run_DropWhileAnySeqCRangeIter, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileAnyCollection", runFunction: run_DropWhileAnyCollection, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileArray", runFunction: run_DropWhileArray, tags: [.validation, .api, .Array]), BenchmarkInfo( name: "DropWhileCountableRangeLazy", runFunction: run_DropWhileCountableRangeLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileSequenceLazy", runFunction: run_DropWhileSequenceLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileAnySequenceLazy", runFunction: run_DropWhileAnySequenceLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileAnySeqCntRangeLazy", runFunction: run_DropWhileAnySeqCntRangeLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileAnySeqCRangeIterLazy", runFunction: run_DropWhileAnySeqCRangeIterLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileAnyCollectionLazy", runFunction: run_DropWhileAnyCollectionLazy, tags: [.validation, .api]), BenchmarkInfo( name: "DropWhileArrayLazy", runFunction: run_DropWhileArrayLazy, tags: [.validation, .api]), ] @inline(never) public func run_DropWhileCountableRange(_ N: Int) { let s = 0..<sequenceCount for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileSequence(_ N: Int) { let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil } for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileAnySequence(_ N: Int) { let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }) for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileAnySeqCntRange(_ N: Int) { let s = AnySequence(0..<sequenceCount) for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileAnySeqCRangeIter(_ N: Int) { let s = AnySequence((0..<sequenceCount).makeIterator()) for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileAnyCollection(_ N: Int) { let s = AnyCollection(0..<sequenceCount) for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileArray(_ N: Int) { let s = Array(0..<sequenceCount) for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileCountableRangeLazy(_ N: Int) { let s = (0..<sequenceCount).lazy for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileSequenceLazy(_ N: Int) { let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileAnySequenceLazy(_ N: Int) { let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileAnySeqCntRangeLazy(_ N: Int) { let s = (AnySequence(0..<sequenceCount)).lazy for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileAnySeqCRangeIterLazy(_ N: Int) { let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileAnyCollectionLazy(_ N: Int) { let s = (AnyCollection(0..<sequenceCount)).lazy for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } } @inline(never) public func run_DropWhileArrayLazy(_ N: Int) { let s = (Array(0..<sequenceCount)).lazy for _ in 1...20*N { var result = 0 for element in s.drop(while: {$0 < dropCount} ) { result += element } CheckResults(result == sumCount) } }
apache-2.0
417e03e2f84981a56b6f2a820a50750b
28.504202
91
0.624324
4.047262
false
false
false
false
devroo/onTodo
Swift/OptionalChaining.playground/section-1.swift
1
1219
// Playground - noun: a place where people can play import UIKit /* * 옵셔널 체인 (Optional Chaining) */ /* 스위프트(Swift)의 옵셔널 체인이 오브젝티브씨(Objective-C)에 있는 nil에 메시지 보내기와 유사하다. 그러나, 모든 타입(any type)에서 동작하고, 성공, 실패 여부를 확인할 수 있다는 점에서 차이가 있다. */ // 강제 랩핑 해제(Forced Unwrapping) 대안으로써 옵셔널 체인 class Person { var residence: Residence? } class Residence { var numberOfRooms = 1 } let john = Person() //let roomCount = john.residence!.numberOfRooms // 강제 랩핑 에러 (nil이기떄문에) if let roomCount = john.residence?.numberOfRooms { println("John's residence has \(roomCount) room(s).") } else { println("Unable to retrieve the number of rooms.") } // prints "Unable to retrieve the number of rooms." john.residence = Residence() if let roomCount = john.residence?.numberOfRooms { println("John's residence has \(roomCount) room(s).") } else { println("Unable to retrieve the number of rooms.") } // prints "John's residence has 1 room(s)." // 옵셔널 체인을 위한 모델(Model) 클래스(Class) 선언
gpl-2.0
773c88a2394994ce7bae208101bf2b5b
22.046512
130
0.684157
2.580729
false
false
false
false
bingoogolapple/SwiftNote-PartTwo
XML块代码解析/XML和JSON/ViewController.swift
1
7260
// // ViewController.swift // XML和JSON // // Created by bingoogol on 14/10/7. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { let CELL_ID = "MyCell" var tableView:UITableView! var model:Model = Model() var dataList:NSMutableArray = NSMutableArray() var currentVideo:Model! override func loadView() { self.view = UIView(frame: UIScreen.mainScreen().bounds) var frame = UIScreen.mainScreen().applicationFrame tableView = UITableView(frame: CGRectMake(0, frame.origin.y, frame.width, frame.height - 44), style: UITableViewStyle.Plain)! tableView.delegate = self tableView.dataSource = self tableView.rowHeight = 80 self.view.addSubview(tableView) var toolBar = UIToolbar(frame: CGRectMake(0, tableView.bounds.height + frame.origin.y, frame.width, 44)) var item1 = UIBarButtonItem(title: "load JSON", style: UIBarButtonItemStyle.Done, target: self, action: Selector("loadJSON")) var item2 = UIBarButtonItem(title: "load XML", style: UIBarButtonItemStyle.Done, target: self, action: Selector("loadXML")) var item3 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) toolBar.items = [item3,item1,item3,item2,item3] self.view.addSubview(toolBar) } func loadJSON() { var urlStr = "http://localhost:7777/swift/test.json" // 从web服务器直接加载数据 // 提示:NSData本身具有同步方法,但是在实际开发中,不要使用此方法。在使用NSData的同步方法时,无法指定超时时间,如果服务器连接不正常,会影响用户体验 // var data = NSData(contentsOfURL: NSURL(string: urlStr)!) // var result = NSString(data: data!, encoding: NSUTF8StringEncoding) // println(result) // 1.建立NSURL var url = NSURL(string: urlStr) // 2.建立NSURLRequest var request = NSURLRequest(URL: url!) // 3.利用NSURLConnection的同步方法加载数据 var error : NSError? var response : NSURLResponse? var data = NSURLConnection.sendSynchronousRequest(request,returningResponse: &response,error: &error) if data != nil { handlerJsonData(data!) } else if error == nil { println("空数据") } else { println("错误\(error!.localizedDescription)") } } func handlerJsonData(data:NSData) { // 在处理网络数据时,不需要将NSData转换成NSString。仅用于跟踪处理 var result = NSString(data: data, encoding: NSUTF8StringEncoding) // println(result!) var error:NSError? var array = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error) as NSArray // 如果开发网络应用,可以将反序列化出来的对象保存到沙箱,以便后续开发使用 var docs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) var path = (docs[0] as NSString).stringByAppendingPathComponent("json.plist") array.writeToFile(path, atomically: true) println(path) } func loadXML() { // testExtension() var urlStr = "http://localhost:7777/swift/test.xml" // 1.建立NSURL var url = NSURL(string: urlStr) // 2.建立NSURLRequest var request = NSURLRequest(URL: url!) // 3.利用NSURLConnection的同步方法加载数据 var error : NSError? var response : NSURLResponse? var data = NSURLConnection.sendSynchronousRequest(request,returningResponse: &response,error: &error) if data != nil { handlerXmlDataXmlParser(data!) } else if error == nil { println("空数据") } else { println("错误\(error!.localizedDescription)") } } func handlerXmlDataXmlParser(data:NSData) { MyXMLParser().xmlParserWithData(data, startElementName: "video", startElementBlock: { (dict:NSDictionary) in self.currentVideo = Model() self.currentVideo.videoId = (dict["videoId"] as NSString).integerValue }, endElementBlock: { (elementName:NSString, result:NSString) in if elementName.isEqualToString("video") { self.dataList.addObject(self.currentVideo) } else if elementName.isEqualToString("name") { self.currentVideo.name = result } else if elementName.isEqualToString("length") { self.currentVideo.length = result.integerValue } }, finishedParser: { for model in self.dataList { println("\((model as Model).name)") } }, errorParser: { self.dataList.removeAllObjects() self.currentVideo = nil }) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID) as VideoCell! if cell == nil { cell = VideoCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: CELL_ID) } cell.textLabel?.text = "title" cell.detailTextLabel?.text = "detail" cell.label3.text = "11:11" cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator // 加载图片 // 正式开发时从数据集中获取获取model var model = self.model if model.cacheImage == nil { // 异步加载时使用默认图片占位置,既能保证有图像,又能保证有地方 cell.imageView?.image = UIImage(named: "default.jpg") loadImageAsync(indexPath) } else { cell.imageView?.image = model.cacheImage } // println("加载数据") return cell } // 由于UITableViewCell是可重用的,为了避免用户频繁快速刷新表格,造成数据冲突,不能直接将UIImageView传入异步方法 // 正确地解决方法是:将表格行的indexPath传入异步方法,加载完成图像后,直接刷新指定行 func loadImageAsync(indexPath:NSIndexPath) { // 正式开发时从数据集中获取mode,再获取url var model = self.model var imagePath = "http://localhost:7777/swift/hehe.jpg" var imageUrl = NSURL(string: imagePath)! var request = NSURLRequest(URL: imageUrl) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in model.cacheImage = UIImage(data: data) self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Right) } } }
apache-2.0
85d64820cd4e131526f56e979071f306
40.099379
162
0.63951
4.584893
false
false
false
false
jkolb/midnightbacon
MidnightBacon/Modules/Submit/SegmentedControlHeader.swift
1
3908
// // SegmentedControlHeader.swift // MidnightBacon // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // 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 DrapierLayout protocol SegmentedControlHeaderDelegate : class { func numberOfSegmentsInSegmentedControlHeader(segmentedControlHeader: SegmentedControlHeader) -> Int func selectedIndexOfSegmentedControlHeader(segmentedControlHeader: SegmentedControlHeader) -> Int func segmentedControlHeader(segmentedControlHeader: SegmentedControlHeader, titleForSegmentAtIndex index: Int) -> String } class SegmentedControlHeader : UIView { weak var delegate: SegmentedControlHeaderDelegate? let segmentedControl = UISegmentedControl() let insets = UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0) override init(frame: CGRect) { super.init(frame: frame) addSubview(segmentedControl) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addSubview(segmentedControl) } override func willMoveToWindow(newWindow: UIWindow?) { super.willMoveToWindow(newWindow) if newWindow == nil { segmentedControl.removeAllSegments() } else { if let delegate = self.delegate { let numberOfSegments = delegate.numberOfSegmentsInSegmentedControlHeader(self) for var i = 0; i < numberOfSegments; ++i { let title = delegate.segmentedControlHeader(self, titleForSegmentAtIndex: i) segmentedControl.insertSegmentWithTitle(title, atIndex: i, animated: false) } segmentedControl.selectedSegmentIndex = delegate.selectedIndexOfSegmentedControlHeader(self) addSubview(segmentedControl) } else { segmentedControl.removeAllSegments() } } } override func layoutSubviews() { super.layoutSubviews() let layout = generateLayout(bounds) segmentedControl.frame = layout.segmentedControlFrame } override func sizeThatFits(size: CGSize) -> CGSize { let segmentedSize = segmentedControl.sizeThatFits(size) let fitSize = CGSize(width: size.width, height: segmentedSize.height + insets.top + insets.bottom) return fitSize } private struct ViewLayout { let segmentedControlFrame: CGRect } private func generateLayout(bounds: CGRect) -> ViewLayout { let segmentedControlFrame = segmentedControl.layout( Left(equalTo: bounds.left(insets)), Right(equalTo: bounds.right(insets)), CenterY(equalTo: bounds.centerY(insets)) ) return ViewLayout( segmentedControlFrame: segmentedControlFrame ) } }
mit
56b2618ce306d3c86449b0d2da8a5528
38.877551
124
0.691402
5.266846
false
false
false
false
SoneeJohn/WWDC
WWDC/TrackColorView.swift
2
1946
// // TrackColorView.swift // WWDC // // Created by Guilherme Rambo on 11/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa final class TrackColorView: NSView { private lazy var progressLayer: WWDCLayer = { let l = WWDCLayer() l.autoresizingMask = [.layerWidthSizable] return l }() override init(frame frameRect: NSRect) { super.init(frame: frameRect) wantsLayer = true layer?.cornerRadius = 2 layer?.masksToBounds = true progressLayer.frame = bounds layer?.addSublayer(progressLayer) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } var hasValidProgress = false { didSet { needsLayout = true } } var progress: Double = 0.5 { didSet { // hide when fully watched alphaValue = progress >= Constants.watchedVideoRelativePosition ? 0 : 1 if hasValidProgress && progress < 1 { layer?.borderWidth = 1 } else { layer?.borderWidth = 0 } needsLayout = true } } var color: NSColor = .black { didSet { layer?.borderColor = color.cgColor progressLayer.backgroundColor = color.cgColor } } override var intrinsicContentSize: NSSize { return NSSize(width: 4, height: -1) } override func layout() { super.layout() let progressHeight = hasValidProgress ? bounds.height * CGFloat(progress) : bounds.height guard !progressHeight.isNaN && !progressHeight.isInfinite else { return } let progressFrame = NSRect(x: 0, y: 0, width: bounds.width, height: progressHeight) progressLayer.frame = progressFrame } override func makeBackingLayer() -> CALayer { return WWDCLayer() } }
bsd-2-clause
f4678fa8edb3b8019b8e691ea21f89cf
22.433735
97
0.586118
4.874687
false
false
false
false
Onavoy/Torpedo
Torpedo/Classes/Runtime/Closures.swift
1
976
import Foundation @inline(never) public func measureBlock(_ block: @escaping (() -> Void)) -> Double { let begin = Date() block() let end = Date() let timeTaken = end.timeIntervalSince1970 - begin.timeIntervalSince1970 return timeTaken } @inline(never) public func measureBlockAverage(repeatCount: Int, _ block: @escaping (() -> Void)) -> Double { var results :[Double] = [] repeatCount.times { (currentIndex) in results.append(measureBlock(block)) } return DoubleUtils.average(results) } @discardableResult @inline(never) public func measureBlockLog(_ closureName: String, _ block: @escaping (() -> Void)) -> Double { let timeTaken = measureBlock(block) if timeTaken < 1.0 { let millsecondsTaken = timeTaken * 1000.0 print("\(closureName) took \(millsecondsTaken) milliseconds to execute") } else { print("\(closureName) took \(timeTaken) seconds to execute") } return timeTaken }
mit
3d4c31da39a047d81cf135d348d472e1
29.5
110
0.664959
4.337778
false
false
false
false
dsonara/DSImageCache
DSImageCache/Classes/Core/ImagePrefetcher.swift
1
10681
// // ImagePrefetcher.swift // DSImageCache // // Created by Dipak Sonara on 29/03/17. // Copyright © 2017 Dipak Sonara. All rights reserved. import UIKit /// Progress update block of prefetcher. /// /// - `skippedResources`: An array of resources that are already cached before the prefetching starting. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all. /// - `completedResources`: An array of resources that are downloaded and cached successfully. public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ()) /// Completion block of prefetcher. /// /// - `skippedResources`: An array of resources that are already cached before the prefetching starting. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all. /// - `completedResources`: An array of resources that are downloaded and cached successfully. public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ()) /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them. /// This is useful when you know a list of image resources and want to download them before showing. public class ImagePrefetcher { /// The maximum concurrent downloads to use when prefetching images. Default is 5. public var maxConcurrentDownloads = 5 private let prefetchResources: [Resource] private let optionsInfo: DSImageCacheOptionsInfo private var progressBlock: PrefetcherProgressBlock? private var completionHandler: PrefetcherCompletionHandler? private var tasks = [URL: RetrieveImageDownloadTask]() private var pendingResources: ArraySlice<Resource> private var skippedResources = [Resource]() private var completedResources = [Resource]() private var failedResources = [Resource]() private var stopped = false // The created manager used for prefetch. We will use the helper method in manager. private let manager: DSImageCacheManager private var finished: Bool { return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count && self.tasks.isEmpty } /** Init an image prefetcher with an array of URLs. The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process. The images already cached will be skipped without downloading again. - parameter urls: The URLs which should be prefetched. - parameter options: A dictionary could control some behaviors. See `DSImageCacheOptionsInfo` for more. - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled. - parameter completionHandler: Called when the whole prefetching process finished. - returns: An `ImagePrefetcher` object. - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as the downloader and cache target respectively. You can specify another downloader or cache by using a customized `DSImageCacheOptionsInfo`. Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method. */ public convenience init(urls: [URL], options: DSImageCacheOptionsInfo? = nil, progressBlock: PrefetcherProgressBlock? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { let resources: [Resource] = urls.map { $0 } self.init(resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Init an image prefetcher with an array of resources. The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable. After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process. The images already cached will be skipped without downloading again. - parameter resources: The resources which should be prefetched. See `Resource` type for more. - parameter options: A dictionary could control some behaviors. See `DSImageCacheOptionsInfo` for more. - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled. - parameter completionHandler: Called when the whole prefetching process finished. - returns: An `ImagePrefetcher` object. - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as the downloader and cache target respectively. You can specify another downloader or cache by using a customized `DSImageCacheOptionsInfo`. Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method. */ public init(resources: [Resource], options: DSImageCacheOptionsInfo? = nil, progressBlock: PrefetcherProgressBlock? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { prefetchResources = resources pendingResources = ArraySlice(resources) // We want all callbacks from main queue, so we ignore the call back queue in options let optionsInfoWithoutQueue = options?.removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil)) self.optionsInfo = optionsInfoWithoutQueue ?? DSImageCacheEmptyOptionsInfo let cache = self.optionsInfo.targetCache let downloader = self.optionsInfo.downloader manager = DSImageCacheManager(downloader: downloader, cache: cache) self.progressBlock = progressBlock self.completionHandler = completionHandler } /** Start to download the resources and cache them. This can be useful for background downloading of assets that are required for later use in an app. This code will not try and update any UI with the results of the process. */ public func start() { // Since we want to handle the resources cancellation in main thread only. DispatchQueue.main.safeAsync { guard !self.stopped else { assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.") self.handleComplete() return } guard self.maxConcurrentDownloads > 0 else { assertionFailure("There should be concurrent downloads value should be at least 1.") self.handleComplete() return } guard self.prefetchResources.count > 0 else { self.handleComplete() return } let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads) for _ in 0 ..< initialConcurentDownloads { if let resource = self.pendingResources.popFirst() { self.startPrefetching(resource) } } } } /** Stop current downloading progress, and cancel any future prefetching activity that might be occuring. */ public func stop() { DispatchQueue.main.safeAsync { if self.finished { return } self.stopped = true self.tasks.forEach { (_, task) -> () in task.cancel() } } } func downloadAndCache(_ resource: Resource) { let downloadTaskCompletionHandler: CompletionHandler = { (image, error, _, _) -> () in self.tasks.removeValue(forKey: resource.downloadURL) if let _ = error { self.failedResources.append(resource) } else { self.completedResources.append(resource) } self.reportProgress() if self.stopped { if self.tasks.isEmpty { self.failedResources.append(contentsOf: self.pendingResources) self.handleComplete() } } else { self.reportCompletionOrStartNext() } } let downloadTask = manager.downloadAndCacheImage( with: resource.downloadURL, forKey: resource.cacheKey, retrieveImageTask: RetrieveImageTask(), progressBlock: nil, completionHandler: downloadTaskCompletionHandler, options: optionsInfo) if let downloadTask = downloadTask { tasks[resource.downloadURL] = downloadTask } } func append(cached resource: Resource) { skippedResources.append(resource) reportProgress() reportCompletionOrStartNext() } func startPrefetching(_ resource: Resource) { if optionsInfo.forceRefresh { downloadAndCache(resource) } else { let alreadyInCache = manager.cache.isImageCached(forKey: resource.cacheKey, processorIdentifier: optionsInfo.processor.identifier).cached if alreadyInCache { append(cached: resource) } else { downloadAndCache(resource) } } } func reportProgress() { progressBlock?(skippedResources, failedResources, completedResources) } func reportCompletionOrStartNext() { if let resource = pendingResources.popFirst() { startPrefetching(resource) } else { guard tasks.isEmpty else { return } handleComplete() } } func handleComplete() { completionHandler?(skippedResources, failedResources, completedResources) completionHandler = nil progressBlock = nil } }
mit
ee3e019457b3a7dd83e355373c1302c7
42.414634
209
0.655899
5.953177
false
false
false
false
AnirudhDas/AniruddhaDas.github.io
MVVMDataBindingRestAPICall/MVVMDataBindingRestAPICall/MoviesService.swift
1
1280
// // FetchMoviesService.swift // MVVMDataBindingRestAPICall // // Created by Anirudh Das on 7/26/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import Foundation protocol MoviesProtocol { func fetchMovies(completionBlock: @escaping (_ movies: [Movie]?) -> Void) } class MoviesService: NSObject, MoviesProtocol { func fetchMovies(completionBlock: @escaping (_ movies: [Movie]?) -> Void) { let url: URL = URL(string: "https://itunes.apple.com/us/rss/topmovies/limit=25/json")! URLSession.shared.dataTask(with: url) { (data, response, error) in if error == nil, let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any], let feedDict = json?["feed"] as? [String: Any], let entryArray = feedDict["entry"] as? [[String: Any]] { var movies: [Movie] = [] for item in entryArray { if let name = item["im:name"] as? [String: Any], let label = name["label"] as? String { movies.append(Movie(name: label)) } } completionBlock(movies) } else { completionBlock(nil) } }.resume() } }
apache-2.0
8c9130e030b867f4dbae679215fff65d
37.757576
252
0.579359
4.047468
false
false
false
false
exoplatform/exo-ios
Pods/Kingfisher/Sources/Image/ImageProcessor.swift
1
36902
// // ImageProcessor.swift // Kingfisher // // Created by Wei Wang on 2016/08/26. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit #endif /// Represents an item which could be processed by an `ImageProcessor`. /// /// - image: Input image. The processor should provide a way to apply /// processing on this `image` and return the result image. /// - data: Input data. The processor should provide a way to apply /// processing on this `image` and return the result image. public enum ImageProcessItem { /// Input image. The processor should provide a way to apply /// processing on this `image` and return the result image. case image(KFCrossPlatformImage) /// Input data. The processor should provide a way to apply /// processing on this `image` and return the result image. case data(Data) } /// An `ImageProcessor` would be used to convert some downloaded data to an image. public protocol ImageProcessor { /// Identifier of the processor. It will be used to identify the processor when /// caching and retrieving an image. You might want to make sure that processors with /// same properties/functionality have the same identifiers, so correct processed images /// could be retrieved with proper key. /// /// - Note: Do not supply an empty string for a customized processor, which is already reserved by /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation string of /// your own for the identifier. var identifier: String { get } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: The parsed options when processing the item. /// - Returns: The processed image. /// /// - Note: The return value should be `nil` if processing failed while converting an input item to image. /// If `nil` received by the processing caller, an error will be reported and the process flow stops. /// If the processing flow is not critical for your flow, then when the input item is already an image /// (`.image` case) and there is any errors in the processing, you could return the input image itself /// to keep the processing pipeline continuing. /// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing /// a filter, the input image will be returned directly on watchOS. func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? } extension ImageProcessor { /// Appends an `ImageProcessor` to another. The identifier of the new `ImageProcessor` /// will be "\(self.identifier)|>\(another.identifier)". /// /// - Parameter another: An `ImageProcessor` you want to append to `self`. /// - Returns: The new `ImageProcessor` will process the image in the order /// of the two processors concatenated. public func append(another: ImageProcessor) -> ImageProcessor { let newIdentifier = identifier.appending("|>\(another.identifier)") return GeneralProcessor(identifier: newIdentifier) { item, options in if let image = self.process(item: item, options: options) { return another.process(item: .image(image), options: options) } else { return nil } } } } func ==(left: ImageProcessor, right: ImageProcessor) -> Bool { return left.identifier == right.identifier } func !=(left: ImageProcessor, right: ImageProcessor) -> Bool { return !(left == right) } typealias ProcessorImp = ((ImageProcessItem, KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?) struct GeneralProcessor: ImageProcessor { let identifier: String let p: ProcessorImp func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { return p(item, options) } } /// The default processor. It converts the input data to a valid image. /// Images of .PNG, .JPEG and .GIF format are supported. /// If an image item is given as `.image` case, `DefaultImageProcessor` will /// do nothing on it and return the associated image. public struct DefaultImageProcessor: ImageProcessor { /// A default `DefaultImageProcessor` could be used across. public static let `default` = DefaultImageProcessor() /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier = "" /// Creates a `DefaultImageProcessor`. Use `DefaultImageProcessor.default` to get an instance, /// if you do not have a good reason to create your own `DefaultImageProcessor`. public init() {} /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) case .data(let data): return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions) } } } /// Represents the rect corner setting when processing a round corner image. public struct RectCorner: OptionSet { /// Raw value of the rect corner. public let rawValue: Int /// Represents the top left corner. public static let topLeft = RectCorner(rawValue: 1 << 0) /// Represents the top right corner. public static let topRight = RectCorner(rawValue: 1 << 1) /// Represents the bottom left corner. public static let bottomLeft = RectCorner(rawValue: 1 << 2) /// Represents the bottom right corner. public static let bottomRight = RectCorner(rawValue: 1 << 3) /// Represents all corners. public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight] /// Creates a `RectCorner` option set with a given value. /// /// - Parameter rawValue: The value represents a certain corner option. public init(rawValue: Int) { self.rawValue = rawValue } var cornerIdentifier: String { if self == .all { return "" } return "_corner(\(rawValue))" } } #if !os(macOS) /// Processor for adding an blend mode to images. Only CG-based images are supported. public struct BlendImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Blend Mode will be used to blend the input image. public let blendMode: CGBlendMode /// Alpha will be used when blend image. public let alpha: CGFloat /// Background color of the output image. If `nil`, it will stay transparent. public let backgroundColor: KFCrossPlatformColor? /// Creates a `BlendImageProcessor`. /// /// - Parameters: /// - blendMode: Blend Mode will be used to blend the input image. /// - alpha: Alpha will be used when blend image. From 0.0 to 1.0. 1.0 means solid image, /// 0.0 means transparent image (not visible at all). Default is 1.0. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) { self.blendMode = blendMode self.alpha = alpha self.backgroundColor = backgroundColor var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))" if let color = backgroundColor { identifier.append("_\(color.hex)") } self.identifier = identifier } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } #endif #if os(macOS) /// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS. public struct CompositingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Compositing operation will be used to the input image. public let compositingOperation: NSCompositingOperation /// Alpha will be used when compositing image. public let alpha: CGFloat /// Background color of the output image. If `nil`, it will stay transparent. public let backgroundColor: KFCrossPlatformColor? /// Creates a `CompositingImageProcessor` /// /// - Parameters: /// - compositingOperation: Compositing operation will be used to the input image. /// - alpha: Alpha will be used when compositing image. /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image. /// Default is 1.0. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. public init(compositingOperation: NSCompositingOperation, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) { self.compositingOperation = compositingOperation self.alpha = alpha self.backgroundColor = backgroundColor var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))" if let color = backgroundColor { identifier.append("_\(color.hex)") } self.identifier = identifier } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.image( withCompositingOperation: compositingOperation, alpha: alpha, backgroundColor: backgroundColor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } #endif /// Processor for making round corner images. Only CG-based images are supported in macOS, /// if a non-CG image passed in, the processor will do nothing. /// /// - Note: The input image will be rendered with round corner pixels removed. If the image itself does not contain /// alpha channel (for example, a JPEG image), the processed image will contain an alpha channel in memory in order /// to show correctly. However, when cached to disk, Kingfisher respects the original image format by default. That /// means the alpha channel will be removed for these images. When you load the processed image from cache again, you /// will lose transparent corner. /// /// You could use `FormatIndicatedCacheSerializer.png` to force Kingfisher to serialize the image to PNG format in this /// case. /// public struct RoundCornerImageProcessor: ImageProcessor { /// Represents a radius specified in a `RoundCornerImageProcessor`. public enum Radius { /// The radius should be calculated as a fraction of the image width. Typically the associated value should be /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image width. case widthFraction(CGFloat) /// The radius should be calculated as a fraction of the image height. Typically the associated value should be /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image height. case heightFraction(CGFloat) /// Use a fixed point value as the round corner radius. case point(CGFloat) var radiusIdentifier: String { switch self { case .widthFraction(let f): return "w_frac_\(f)" case .heightFraction(let f): return "h_frac_\(f)" case .point(let p): return p.description } } } /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and /// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one. public let radius: Radius /// The target corners which will be applied rounding. public let roundingCorners: RectCorner /// Target size of output image should be. If `nil`, the image will keep its original size after processing. public let targetSize: CGSize? /// Background color of the output image. If `nil`, it will use a transparent background. public let backgroundColor: KFCrossPlatformColor? /// Creates a `RoundCornerImageProcessor`. /// /// - Parameters: /// - cornerRadius: Corner radius in point will be applied in processing. /// - targetSize: Target size of output image should be. If `nil`, /// the image will keep its original size after processing. /// Default is `nil`. /// - corners: The target corners which will be applied rounding. Default is `.all`. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. /// /// - Note: /// /// This initializer accepts a concrete point value for `cornerRadius`. If you do not know the image size, but still /// want to apply a full round-corner (making the final image a round one), or specify the corner radius as a /// fraction of one dimension of the target image, use the `Radius` version instead. /// public init( cornerRadius: CGFloat, targetSize: CGSize? = nil, roundingCorners corners: RectCorner = .all, backgroundColor: KFCrossPlatformColor? = nil ) { let radius = Radius.point(cornerRadius) self.init(radius: radius, targetSize: targetSize, roundingCorners: corners, backgroundColor: backgroundColor) } /// Creates a `RoundCornerImageProcessor`. /// /// - Parameters: /// - radius: The radius will be applied in processing. /// - targetSize: Target size of output image should be. If `nil`, /// the image will keep its original size after processing. /// Default is `nil`. /// - corners: The target corners which will be applied rounding. Default is `.all`. /// - backgroundColor: Background color to apply for the output image. Default is `nil`. public init( radius: Radius, targetSize: CGSize? = nil, roundingCorners corners: RectCorner = .all, backgroundColor: KFCrossPlatformColor? = nil ) { self.radius = radius self.targetSize = targetSize self.roundingCorners = corners self.backgroundColor = backgroundColor self.identifier = { var identifier = "" if let size = targetSize { identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" + "(\(radius.radiusIdentifier)_\(size)\(corners.cornerIdentifier))" } else { identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" + "(\(radius.radiusIdentifier)\(corners.cornerIdentifier))" } if let backgroundColor = backgroundColor { identifier += "_\(backgroundColor)" } return identifier }() } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): let size = targetSize ?? image.kf.size let cornerRadius: CGFloat switch radius { case .point(let point): cornerRadius = point case .widthFraction(let widthFraction): cornerRadius = size.width * widthFraction case .heightFraction(let heightFraction): cornerRadius = size.height * heightFraction } return image.kf.scaled(to: options.scaleFactor) .kf.image( withRoundRadius: cornerRadius, fit: size, roundingCorners: roundingCorners, backgroundColor: backgroundColor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Represents how a size adjusts itself to fit a target size. /// /// - none: Not scale the content. /// - aspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio. /// - aspectFill: Scales the content to fill the size of the view. public enum ContentMode { /// Not scale the content. case none /// Scales the content to fit the size of the view by maintaining the aspect ratio. case aspectFit /// Scales the content to fill the size of the view. case aspectFill } /// Processor for resizing images. /// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor` /// instead, which is more efficient and uses less memory. public struct ResizingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// The reference size for resizing operation in point. public let referenceSize: CGSize /// Target content mode of output image should be. /// Default is `.none`. public let targetContentMode: ContentMode /// Creates a `ResizingImageProcessor`. /// /// - Parameters: /// - referenceSize: The reference size for resizing operation in point. /// - mode: Target content mode of output image should be. /// /// - Note: /// The instance of `ResizingImageProcessor` will follow its `mode` property /// and try to resizing the input images to fit or fill the `referenceSize`. /// That means if you are using a `mode` besides of `.none`, you may get an /// image with its size not be the same as the `referenceSize`. /// /// **Example**: With input image size: {100, 200}, /// `referenceSize`: {100, 100}, `mode`: `.aspectFit`, /// you will get an output image with size of {50, 100}, which "fit"s /// the `referenceSize`. /// /// If you need an output image exactly to be a specified size, append or use /// a `CroppingImageProcessor`. public init(referenceSize: CGSize, mode: ContentMode = .none) { self.referenceSize = referenceSize self.targetContentMode = mode if mode == .none { self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))" } else { self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))" } } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.resize(to: referenceSize, for: targetContentMode) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for /// a better performance. A simulated Gaussian blur with specified blur radius will be applied. public struct BlurImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Blur radius for the simulated Gaussian blur. public let blurRadius: CGFloat /// Creates a `BlurImageProcessor` /// /// - parameter blurRadius: Blur radius for the simulated Gaussian blur. public init(blurRadius: CGFloat) { self.blurRadius = blurRadius self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): let radius = blurRadius * options.scaleFactor return image.kf.scaled(to: options.scaleFactor) .kf.blurred(withRadius: radius) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for adding an overlay to images. Only CG-based images are supported in macOS. public struct OverlayImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Overlay color will be used to overlay the input image. public let overlay: KFCrossPlatformColor /// Fraction will be used when overlay the color to image. public let fraction: CGFloat /// Creates an `OverlayImageProcessor` /// /// - parameter overlay: Overlay color will be used to overlay the input image. /// - parameter fraction: Fraction will be used when overlay the color to image. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. public init(overlay: KFCrossPlatformColor, fraction: CGFloat = 0.5) { self.overlay = overlay self.fraction = fraction self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.overlaying(with: overlay, fraction: fraction) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for tint images with color. Only CG-based images are supported. public struct TintImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Tint color will be used to tint the input image. public let tint: KFCrossPlatformColor /// Creates a `TintImageProcessor` /// /// - parameter tint: Tint color will be used to tint the input image. public init(tint: KFCrossPlatformColor) { self.tint = tint self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.tinted(with: tint) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for applying some color control to images. Only CG-based images are supported. /// watchOS is not supported. public struct ColorControlsProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Brightness changing to image. public let brightness: CGFloat /// Contrast changing to image. public let contrast: CGFloat /// Saturation changing to image. public let saturation: CGFloat /// InputEV changing to image. public let inputEV: CGFloat /// Creates a `ColorControlsProcessor` /// /// - Parameters: /// - brightness: Brightness changing to image. /// - contrast: Contrast changing to image. /// - saturation: Saturation changing to image. /// - inputEV: InputEV changing to image. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) { self.brightness = brightness self.contrast = contrast self.saturation = saturation self.inputEV = inputEV self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for applying black and white effect to images. Only CG-based images are supported. /// watchOS is not supported. public struct BlackWhiteProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor" /// Creates a `BlackWhiteProcessor` public init() {} /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7) .process(item: item, options: options) } } /// Processor for cropping an image. Only CG-based images are supported. /// watchOS is not supported. public struct CroppingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Target size of output image should be. public let size: CGSize /// Anchor point from which the output size should be calculate. /// The anchor point is consisted by two values between 0.0 and 1.0. /// It indicates a related point in current image. /// See `CroppingImageProcessor.init(size:anchor:)` for more. public let anchor: CGPoint /// Creates a `CroppingImageProcessor`. /// /// - Parameters: /// - size: Target size of output image should be. /// - anchor: The anchor point from which the size should be calculated. /// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image. /// - Note: /// The anchor point is consisted by two values between 0.0 and 1.0. /// It indicates a related point in current image, eg: (0.0, 0.0) for top-left /// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner. /// The `size` property of `CroppingImageProcessor` will be used along with /// `anchor` to calculate a target rectangle in the size of image. /// /// The target size will be automatically calculated with a reasonable behavior. /// For example, when you have an image size of `CGSize(width: 100, height: 100)`, /// and a target size of `CGSize(width: 20, height: 20)`: /// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`; /// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}` /// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}` public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) { self.size = size self.anchor = anchor self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.crop(to: size, anchorOn: anchor) case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) } } } /// Processor for downsampling an image. Compared to `ResizingImageProcessor`, this processor /// does not render the images to resize. Instead, it downsamples the input data directly to an /// image. It is a more efficient than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible /// as you can than the `ResizingImageProcessor`. /// /// Only CG-based images are supported. Animated images (like GIF) is not supported. public struct DownsamplingImageProcessor: ImageProcessor { /// Target size of output image should be. It should be smaller than the size of /// input image. If it is larger, the result image will be the same size of input /// data without downsampling. public let size: CGSize /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Creates a `DownsamplingImageProcessor`. /// /// - Parameter size: The target size of the downsample operation. public init(size: CGSize) { self.size = size self.identifier = "com.onevcat.Kingfisher.DownsamplingImageProcessor(\(size))" } /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { switch item { case .image(let image): guard let data = image.kf.data(format: .unknown) else { return nil } return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor) case .data(let data): return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor) } } } infix operator |>: AdditionPrecedence public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { return left.append(another: right) } extension KFCrossPlatformColor { var hex: String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 #if os(macOS) (usingColorSpace(.sRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a) #else getRed(&r, green: &g, blue: &b, alpha: &a) #endif let rInt = Int(r * 255) << 24 let gInt = Int(g * 255) << 16 let bInt = Int(b * 255) << 8 let aInt = Int(a * 255) let rgba = rInt | gInt | bInt | aInt return String(format:"#%08x", rgba) } }
lgpl-3.0
de6ac0a5e3eba9e2bf815c6c0f9662c2
41.270332
125
0.650805
4.817493
false
false
false
false
ThryvInc/subway-ios
SubwayMap/PredictionViewModel.swift
2
1895
// // PredictionViewModel.swift // SubwayMap // // Created by Elliot Schrock on 8/1/15. // Copyright (c) 2015 Thryv. All rights reserved. // import UIKit import SubwayStations // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } class PredictionViewModel: NSObject { var routeId: String! var direction: Direction! var prediction: Prediction! var onDeckPrediction: Prediction? var inTheHolePrediction: Prediction? var visits: [Visit]? init(routeId: String!, direction: Direction!) { self.routeId = routeId self.direction = direction } func setupWithPredictions(_ predictions: [Prediction]!){ var relevantPredictions = predictions.filter({(prediction) -> Bool in return prediction.direction!.rawValue == self.direction!.rawValue && prediction.route!.objectId == self.routeId }) relevantPredictions.sort { $0.secondsToArrival < $1.secondsToArrival } if relevantPredictions.count > 0 { prediction = relevantPredictions[0] } if relevantPredictions.count > 1 { onDeckPrediction = relevantPredictions[1] } if relevantPredictions.count > 2 { inTheHolePrediction = relevantPredictions[2] } } override func isEqual(_ object: Any?) -> Bool { if let predictionVM = object as? PredictionViewModel { return self.routeId == predictionVM.routeId && self.direction == predictionVM.direction }else{ return false } } }
mit
40f4c39102636128bd2e1aa9ae035bf2
28.153846
123
0.629024
4.71393
false
false
false
false
rnystrom/GitHawk
Classes/Section Controllers/SearchBar/SearchBarCell.swift
1
1772
// // SearchBarCell.swift // Freetime // // Created by Ryan Nystrom on 5/14/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit protocol SearchBarCellDelegate: class { func didChangeSearchText(cell: SearchBarCell, query: String) } final class SearchBarCell: UICollectionViewCell, UISearchBarDelegate { weak var delegate: SearchBarCellDelegate? private let searchBar = UISearchBar(frame: .zero) override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white searchBar.returnKeyType = .search searchBar.enablesReturnKeyAutomatically = false searchBar.searchBarStyle = .minimal searchBar.delegate = self contentView.addSubview(searchBar) searchBar.snp.makeConstraints { make in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.centerY.equalTo(contentView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layoutContentView() } // MARK: Public API func configure(query: String, placeholder: String) { searchBar.text = query searchBar.placeholder = placeholder } // MARK: Private API func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { delegate?.didChangeSearchText(cell: self, query: searchText) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } }
mit
d36323a01cb3a0a71ef3ffa4cf42e30f
25.044118
80
0.677583
5.133333
false
false
false
false
passt0r/MaliDeck
MaliDeck/CardViewController.swift
1
12532
// // CardViewController.swift // MaliDeck // // Created by Dmytro Pasinchuk on 06.11.16. // Copyright © 2016 Dmytro Pasinchuk. All rights reserved. // import UIKit class CardViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var choosedMember: BandMembersTableViewCell! var bandMembers = [Stats]() //members in band var bandWounds = [Int]() let factions = [Fraction.guilde.rawValue, Fraction.arcanists.rawValue, Fraction.resurrectionists.rawValue, Fraction.neverborn.rawValue, Fraction.outcasts.rawValue, Fraction.tenThunders.rawValue, Fraction.gremlins.rawValue] //factions list, need for Picker View var selectedFaction: Fraction? = nil @IBOutlet weak var factionChoosingPicker: UIPickerView! //choosing game format @IBOutlet weak var choosedGameFormat: UISegmentedControl! var gameFormat = [35, 50, 75] @IBOutlet weak var chooseFractionTitleView: UIVisualEffectView! @IBOutlet weak var bandNameTitleView: UIVisualEffectView! func visualEffectForTitle(titleView: UIVisualEffectView) { /* let bilImageView = UIImageView(image: UIImage(named: "bil")) bilImageView.frame = titleView.bounds bilImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] titleView.insertSubview(bilImageView, at: 0)*/ titleView.layer.cornerRadius = 20 titleView.clipsToBounds = true titleView.backgroundColor = UIColor(colorLiteralRed: 0.1, green: 0.8, blue: 0.1, alpha: 0.6) } @IBOutlet weak var bandMembersTableView: UITableView! //overriding setEditing property for parent ViewController to add setEditing property to bandMemberTableView override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if editing == true { navigationItem.rightBarButtonItem?.isEnabled = false } else { navigationItem.rightBarButtonItem?.isEnabled = true } bandMembersTableView.setEditing(editing, animated: animated) } override func viewDidLoad() { super.viewDidLoad() let editButton = editButtonItem navigationItem.leftBarButtonItem = editButton // addSamples() //implement at first launch of DB, need for test visualEffectForTitle(titleView: chooseFractionTitleView) visualEffectForTitle(titleView: bandNameTitleView) bandMembersTableView.delegate = self bandMembersTableView.dataSource = self factionChoosingPicker.dataSource = self factionChoosingPicker.delegate = self selectedFaction = Fraction(rawValue: factions[0]) let bilImageView = UIImageView(image: UIImage(named: "bil")) bilImageView.frame = UIScreen.main.bounds bandMembersTableView.backgroundColor = UIColor.clear bandMembersTableView.insertSubview(bilImageView, at: 0) bandMembersTableView.layer.cornerRadius = 10 bandMembersTableView.clipsToBounds = true //implement custom view of tableView and pickerView factionChoosingPicker.layer.cornerRadius = 15 factionChoosingPicker.clipsToBounds = true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait //why it is not work? } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func bandFiltration(by: Fraction) -> [Stats] { var filtratedBand = [Stats]() for member in bandMembers { if member.fraction == selectedFaction { filtratedBand.append(member) } } return filtratedBand } @IBAction func acceptButtonTouched(_ sender: UIButton) { bandMembers = bandFiltration(by: selectedFaction!) bandMembersTableView.reloadData() } //Getting data from AddingMembersTableViewController and prepare to insert data to band members table view @IBAction func unwindToAddingMemberViewTable(sender: UIStoryboardSegue) { if let sourceViewController = sender.source as? AddingMembersTableViewController, let bandMember = sourceViewController.bandMember /*getting data */{ //adding new band member to your band let newBandMember = sourceViewController.bandMembers[bandMember] if !bandMembers.isEmpty { //checking new member faction if newBandMember.fraction != bandMembers[bandMembers.count - 1].fraction { //if faction did not mach to the band faction sourceViewController.dismiss(animated: true, completion: {print("Adding invalid member")}) alert(reason: "Invalid member", message: "You can't adding member from \(newBandMember.fraction.rawValue) faction to \(bandMembers[bandMembers.count - 1].fraction.rawValue) band.") return } } if bandMembers.isEmpty { //if you have no band if let newBandMember = newBandMember as? Master { //check of adding a master } else { //if you did not have any master yet sourceViewController.dismiss(animated: true, completion: {print("Dismiss to add some band master")}) alert(reason: "No master", message: "You did not have any band master yet, add someone.") return } } if let newBandMember = newBandMember as? Master { //if user add master, check if band have other one for master in bandMembers { if let master = master as? Master { sourceViewController.dismiss(animated: true, completion: {print("Dismiss of reason of adding second band master")}) //dismiss adding view and show error massage after that alert(reason: "Another master choosing", message: "In your band you have \(master.name), you can't add an other master") //showing error massage //alert(reason: "Another master choosing", message: "In your band you have \(master.name), you can't add an other master") return } } } //checking price of new member and valid of adding him to band var summuryMembersPrice = 0 for member in bandMembers { summuryMembersPrice += member.cost } summuryMembersPrice += newBandMember.cost for master in bandMembers { //finding band master's cash if let master = master as? Master { let playerCash = gameFormat[choosedGameFormat.selectedSegmentIndex] + master.cash if playerCash < summuryMembersPrice { //if new member too cost sourceViewController.dismiss(animated: true, completion: {print("Dissmis of reason of overpricing")}) alert(reason: "Overprice", message: "Adding a new member is imposible, you need extra \(summuryMembersPrice - playerCash) soulstones") return } } } let newIndexPath = IndexPath(row: bandMembers.count, section: 0) let memberLeftHits = newBandMember.wounds bandWounds.append(memberLeftHits) //add wounds for checking wounds that left bandMembers.append(newBandMember) //add member to array //insert data to tableview bandMembersTableView.insertRows(at: [newIndexPath], with: .bottom) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AddingNewCharacter" { let destinationNavigationController = segue.destination as! UINavigationController let destinationViewController = destinationNavigationController.topViewController as! AddingMembersTableViewController destinationViewController.selectedFaction = selectedFaction } else if segue.identifier == "showStatCards" { let destinationNavigationController = segue.destination as! UINavigationController let destinationViewController = destinationNavigationController.topViewController as! StatCardViewController guard let selectedMember = sender as? BandMembersTableViewCell else { fatalError("Error with choosing member")} guard let indexforMember = bandMembersTableView.indexPath(for: selectedMember) else { fatalError("Error with finding index") } let choosingMember = bandMembers[indexforMember.row] destinationViewController.currentMember = choosingMember guard let hitLeft = Int(selectedMember.bandMemberHillPoint.text!) else { fatalError("Cannot convert hillPoint to int") } destinationViewController.hitsLeft = hitLeft } } @IBAction func unwindToStatCard(sender: UIStoryboardSegue) { guard let statCardController = sender.source as? StatCardViewController else { fatalError("Unexpected sender for unwindToStatCard()") } let newHills = statCardController.hitsLeft guard let indexOfSelectedRow = bandMembersTableView.indexPathForSelectedRow else { fatalError("Can't find selected row for update data") } /*let selectedRow = bandMembersTableView.cellForRow(at: indexOfSelectedRow) as! BandMembersTableViewCell selectedRow.bandMemberHillPoint.text = String(newHills)*/ //bandMembers[indexOfSelectedRow.row].wounds = newHills bandWounds[indexOfSelectedRow.row] = newHills bandMembersTableView.reloadRows(at: [indexOfSelectedRow], with: .automatic) } func numberOfSections(in tableView: UITableView) -> Int { // return the number of sections return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return the number of row in section return bandMembers.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat.init(50) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BandMember", for: indexPath) as! BandMembersTableViewCell cell.bandMemberName.text = bandMembers[indexPath.row].name cell.bandMemberHillPoint.text = String(bandWounds[indexPath.row]) return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { bandMembers.remove(at: indexPath.row) bandWounds.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } //error massage func alert(reason: String, message: String) { let alert = UIAlertController(title: reason, message: message, preferredStyle: .alert) alert.addAction(.init(title: "Ok, go next", style: .default, handler: nil)) self.present(alert, animated: true, completion: {print("Error displayed on Card View Controller")}) } //MARK: picker view controll func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return factions.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return factions[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedFaction = Fraction(rawValue: factions[row]) } }
gpl-3.0
d93d251dd770478bbd831cf2f5b5fdaa
44.402174
264
0.653978
5.62938
false
false
false
false
n8armstrong/CalendarView
CalendarView/Carthage/Checkouts/SwiftMoment/SwiftMoment/SwiftMoment/Moment.swift
1
16410
// // Moment.swift // SwiftMoment // // Created by Adrian on 19/01/15. // Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved. // // Swift adaptation of Moment.js http://momentjs.com // Github: https://github.com/moment/moment/ import Foundation /** Returns a moment representing the current instant in time at the current timezone - parameter timeZone: An NSTimeZone object - parameter locale: An NSLocale object - returns: A moment instance. */ public func moment(_ timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment { return Moment(timeZone: timeZone, locale: locale) } public func utc() -> Moment { let zone = TimeZone(abbreviation: "UTC")! return moment(zone) } /** Returns an Optional wrapping a Moment structure, representing the current instant in time. If the string passed as parameter cannot be parsed by the function, the Optional wraps a nil value. - parameter stringDate: A string with a date representation. - parameter timeZone: An NSTimeZone object - parameter locale: An NSLocale object - returns: <#return value description#> */ public func moment(_ stringDate: String, timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment? { let formatter = DateFormatter() formatter.timeZone = timeZone formatter.locale = locale let isoFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" // The contents of the array below are borrowed // and adapted from the source code of Moment.js // https://github.com/moment/moment/blob/develop/moment.js let formats = [ isoFormat, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd", "h:mm:ss A", "h:mm A", "MM/dd/yyyy", "MMMM d, yyyy", "MMMM d, yyyy LT", "dddd, MMMM D, yyyy LT", "yyyyyy-MM-dd", "yyyy-MM-dd", "GGGG-[W]WW-E", "GGGG-[W]WW", "yyyy-ddd", "HH:mm:ss.SSSS", "HH:mm:ss", "HH:mm", "HH" ] for format in formats { formatter.dateFormat = format if let date = formatter.date(from: stringDate) { return Moment(date: date, timeZone: timeZone, locale: locale) } } return nil } public func moment(_ stringDate: String, dateFormat: String, timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment? { let formatter = DateFormatter() formatter.dateFormat = dateFormat formatter.timeZone = timeZone formatter.locale = locale if let date = formatter.date(from: stringDate) { return Moment(date: date, timeZone: timeZone, locale: locale) } return nil } /** Builds a new Moment instance using an array with the following components, in the following order: [ year, month, day, hour, minute, second ] - parameter params: An array of integer values as date components - parameter timeZone: An NSTimeZone object - parameter locale: An NSLocale object - returns: An optional wrapping a Moment instance */ public func moment(_ params: [Int], timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment? { if params.count > 0 { var calendar = Calendar.current calendar.timeZone = timeZone var components = DateComponents() components.year = params[0] if params.count > 1 { components.month = params[1] if params.count > 2 { components.day = params[2] if params.count > 3 { components.hour = params[3] if params.count > 4 { components.minute = params[4] if params.count > 5 { components.second = params[5] } } } } } if let date = calendar.date(from: components) { return moment(date, timeZone: timeZone, locale: locale) } } return nil } public func moment(_ dict: [String: Int], timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment? { if dict.count > 0 { var params = [Int]() if let year = dict["year"] { params.append(year) } if let month = dict["month"] { params.append(month) } if let day = dict["day"] { params.append(day) } if let hour = dict["hour"] { params.append(hour) } if let minute = dict["minute"] { params.append(minute) } if let second = dict["second"] { params.append(second) } return moment(params, timeZone: timeZone, locale: locale) } return nil } public func moment(_ milliseconds: Int) -> Moment { return moment(TimeInterval(milliseconds / 1000)) } public func moment(_ seconds: TimeInterval) -> Moment { let interval = TimeInterval(seconds) let date = Date(timeIntervalSince1970: interval) return Moment(date: date) } public func moment(_ date: Date, timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) -> Moment { return Moment(date: date, timeZone: timeZone, locale: locale) } public func moment(_ moment: Moment) -> Moment { let date = moment.date let timeZone = moment.timeZone let locale = moment.locale return Moment(date: date, timeZone: timeZone, locale: locale) } public func past() -> Moment { return Moment(date: Date.distantPast ) } public func future() -> Moment { return Moment(date: Date.distantFuture ) } public func since(_ past: Moment) -> Duration { return moment().intervalSince(past) } public func maximum(_ moments: Moment...) -> Moment? { if moments.count > 0 { var max: Moment = moments[0] for moment in moments { if moment > max { max = moment } } return max } return nil } public func minimum(_ moments: Moment...) -> Moment? { if moments.count > 0 { var min: Moment = moments[0] for moment in moments { if moment < min { min = moment } } return min } return nil } /** Internal structure used by the family of moment() functions. Instead of modifying the native NSDate class, this is a wrapper for the NSDate object. To get this wrapper object, simply call moment() with one of the supported input types. */ public struct Moment: Comparable { public let minuteInSeconds = 60 public let hourInSeconds = 3600 public let dayInSeconds = 86400 public let weekInSeconds = 604800 public let monthInSeconds = 2592000 public let yearInSeconds = 31536000 public let date: Date public let timeZone: TimeZone public let locale: Locale init(date: Date = Date(), timeZone: TimeZone = TimeZone.current, locale: Locale = Locale.autoupdatingCurrent) { self.date = date self.timeZone = timeZone self.locale = locale } /// Returns the year of the current instance. public var year: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.year, from: date) return components.year! } /// Returns the month (1-12) of the current instance. public var month: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.month, from: date) return components.month! } /// Returns the name of the month of the current instance, in the current locale. public var monthName: String { let formatter = DateFormatter() formatter.locale = locale return formatter.monthSymbols[month - 1] } public var day: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.day, from: date) return components.day! } public var hour: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.hour, from: date) return components.hour! } public var minute: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.minute, from: date) return components.minute! } public var second: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.second, from: date) return components.second! } public var weekday: Int { var cal = Calendar.current cal.timeZone = timeZone cal.locale = locale let components = (cal as NSCalendar).components(.weekday, from: date) return components.weekday! } public var weekdayName: String { let formatter = DateFormatter() formatter.locale = locale formatter.dateFormat = "EEEE" formatter.timeZone = timeZone return formatter.string(from: date) } public var weekdayOrdinal: Int { var cal = Calendar.current cal.locale = locale cal.timeZone = timeZone let components = (cal as NSCalendar).components(.weekdayOrdinal, from: date) return components.weekdayOrdinal! } public var weekOfYear: Int { var cal = Calendar.current cal.locale = locale cal.timeZone = timeZone let components = (cal as NSCalendar).components(.weekOfYear, from: date) return components.weekOfYear! } public var quarter: Int { var cal = Calendar.current cal.locale = locale cal.timeZone = timeZone let components = (cal as NSCalendar).components(.quarter, from: date) return components.quarter! } // Methods public func get(_ unit: TimeUnit) -> Int? { switch unit { case .Seconds: return second case .Minutes: return minute case .Hours: return hour case .Days: return day case .Weeks: return weekOfYear case .Months: return month case .Quarters: return quarter case .Years: return year } } public func get(_ unitName: String) -> Int? { if let unit = TimeUnit(rawValue: unitName) { return get(unit) } return nil } public func format(_ dateFormat: String = "yyyy-MM-dd HH:mm:ss ZZZZ") -> String { let formatter = DateFormatter() formatter.dateFormat = dateFormat formatter.timeZone = timeZone formatter.locale = locale return formatter.string(from: date) } public func isEqualTo(_ moment: Moment) -> Bool { return (date == moment.date) } public func intervalSince(_ moment: Moment) -> Duration { let interval = date.timeIntervalSince(moment.date) return Duration(value: Int(interval)) } public func add(_ value: Int, _ unit: TimeUnit) -> Moment { var interval = value switch unit { case .Years: interval = value * Int(1.years.interval) case .Quarters: interval = value * Int(1.quarters.interval) case .Months: interval = value * Int(1.months.interval) case .Weeks: interval = value * Int(1.weeks.interval) case .Days: interval = value * Int(1.days.interval) case .Hours: interval = value * Int(1.hours.interval) case .Minutes: interval = value * Int(1.minutes.interval) case .Seconds: interval = value } return add(TimeInterval(interval), .Seconds) } public func add(_ value: TimeInterval, _ unit: TimeUnit) -> Moment { let seconds = convert(value, unit) let interval = TimeInterval(seconds) let newDate = date.addingTimeInterval(interval) return Moment(date: newDate, timeZone: timeZone) } public func add(_ value: Int, _ unitName: String) -> Moment { if let unit = TimeUnit(rawValue: unitName) { return add(value, unit) } return self } public func add(_ duration: Duration) -> Moment { return add(duration.interval, .Seconds) } public func subtract(_ value: TimeInterval, _ unit: TimeUnit) -> Moment { return add(-value, unit) } public func subtract(_ value: Int, _ unit: TimeUnit) -> Moment { return add(-value, unit) } public func subtract(_ value: Int, _ unitName: String) -> Moment { if let unit = TimeUnit(rawValue: unitName) { return subtract(value, unit) } return self } public func subtract(_ duration: Duration) -> Moment { return subtract(duration.interval, .Seconds) } public func isCloseTo(_ moment: Moment, precision: TimeInterval = 300) -> Bool { // "Being close" is measured using a precision argument // which is initialized a 300 seconds, or 5 minutes. let delta = intervalSince(moment) return abs(delta.interval) < precision } public func startOf(_ unit: TimeUnit) -> Moment { var cal = Calendar.current cal.locale = locale cal.timeZone = timeZone var newDate: Date? var components = (cal as NSCalendar).components([.year, .month, .weekday, .day, .hour, .minute, .second], from: date) switch unit { case .Seconds: return self case .Years: components.month = 1 fallthrough case .Quarters, .Months, .Weeks: if unit == .Weeks { components.day = components.day! - (components.weekday! - 2) } else { components.day = 1 } fallthrough case .Days: components.hour = 0 fallthrough case .Hours: components.minute = 0 fallthrough case .Minutes: components.second = 0 } newDate = cal.date(from: components) return newDate == nil ? self : Moment(date: newDate!, timeZone: timeZone) } public func startOf(_ unitName: String) -> Moment { if let unit = TimeUnit(rawValue: unitName) { return startOf(unit) } return self } public func endOf(_ unit: TimeUnit) -> Moment { return startOf(unit).add(1, unit).subtract(1.seconds) } public func endOf(_ unitName: String) -> Moment { if let unit = TimeUnit(rawValue: unitName) { return endOf(unit) } return self } public func epoch() -> TimeInterval { return date.timeIntervalSince1970 } // Private methods func convert(_ value: Double, _ unit: TimeUnit) -> Double { switch unit { case .Seconds: return value case .Minutes: return value * 60 case .Hours: return value * 3600 // 60 minutes case .Days: return value * 86400 // 24 hours case .Weeks: return value * 605800 // 7 days case .Months: return value * 2592000 // 30 days case .Quarters: return value * 7776000 // 3 months case .Years: return value * 31536000 // 365 days } } } extension Moment: CustomStringConvertible { public var description: String { return format() } } extension Moment: CustomDebugStringConvertible { public var debugDescription: String { return description } }
mit
25c599bde17e25c33a9838a0dcdc2697
28.620939
113
0.584765
4.5596
false
false
false
false
certificate-helper/TLS-Inspector
TLS Inspector/Features/RecentLookups.swift
1
2880
import Foundation private let LIST_KEY = "RECENT_DOMAINS" /// Class for managing recently inspected domains class RecentLookups { /// Return all recently inspected domains public static func GetRecentLookups() -> [String] { guard let list = AppDefaults.array(forKey: LIST_KEY) as? [String] else { return [] } return list } /// Add a new recently inspected domain. If the domain was already in the list, it is moved to index 0. /// - Parameter domain: The domain to add. Case insensitive. public static func AddLookup(_ url: URL) { var list: [String] = [] if let savedList = AppDefaults.array(forKey: LIST_KEY) as? [String] { list = savedList } guard let host = url.host else { LogError("Unable to add URL \(url) to lookup list: host is nil") return } var port = 443 if let urlPort = url.port { port = urlPort } var domain = host if port != 443 { domain += ":\(port)" } if let index = list.firstIndex(of: domain.lowercased()) { list.remove(at: index) } if list.count >= 5 { list.remove(at: 4) } LogDebug("Adding query '\(domain.lowercased())' to recent lookup list") list.insert(domain.lowercased(), at: 0) AppDefaults.set(list, forKey: LIST_KEY) } /// Remove the recently inspected domain at the specified index. /// - Parameter index: The index to remove. public static func RemoveLookup(index: Int) { guard var list = AppDefaults.array(forKey: LIST_KEY) as? [String] else { return } if index > list.count || index < 0 { return } list.remove(at: index) AppDefaults.set(list, forKey: LIST_KEY) } /// Remove the specified recently inspected domain. /// - Parameter domain: The domain to remove. Case insensitive. public static func RemoveLookup(domain: String) { guard var list = AppDefaults.array(forKey: LIST_KEY) as? [String] else { return } guard let index = IndexOfDomain(domain) else { return } list.remove(at: index) AppDefaults.set(list, forKey: LIST_KEY) } /// Remove all recently inspected domains. public static func RemoveAllLookups() { AppDefaults.set([], forKey: LIST_KEY) } /// Get the index of the specified domain. Returns nil if not found. /// - Parameter domain: The domain to search for. Case insenstivie. public static func IndexOfDomain(_ domain: String) -> Int? { guard let list = AppDefaults.array(forKey: LIST_KEY) as? [String] else { return nil } return list.firstIndex(of: domain.lowercased()) } }
gpl-3.0
6b58e053b9794a163642ed4a3ff73a20
29.967742
107
0.584375
4.337349
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Shield/Shield_Shapes.swift
1
44420
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension Shield { // MARK: Enums public enum AttackLayer: String, CustomStringConvertible, Codable { case application = "APPLICATION" case network = "NETWORK" public var description: String { return self.rawValue } } public enum AttackPropertyIdentifier: String, CustomStringConvertible, Codable { case destinationUrl = "DESTINATION_URL" case referrer = "REFERRER" case sourceAsn = "SOURCE_ASN" case sourceCountry = "SOURCE_COUNTRY" case sourceIpAddress = "SOURCE_IP_ADDRESS" case sourceUserAgent = "SOURCE_USER_AGENT" case wordpressPingbackReflector = "WORDPRESS_PINGBACK_REFLECTOR" case wordpressPingbackSource = "WORDPRESS_PINGBACK_SOURCE" public var description: String { return self.rawValue } } public enum AutoRenew: String, CustomStringConvertible, Codable { case disabled = "DISABLED" case enabled = "ENABLED" public var description: String { return self.rawValue } } public enum ProactiveEngagementStatus: String, CustomStringConvertible, Codable { case disabled = "DISABLED" case enabled = "ENABLED" case pending = "PENDING" public var description: String { return self.rawValue } } public enum SubResourceType: String, CustomStringConvertible, Codable { case ip = "IP" case url = "URL" public var description: String { return self.rawValue } } public enum SubscriptionState: String, CustomStringConvertible, Codable { case active = "ACTIVE" case inactive = "INACTIVE" public var description: String { return self.rawValue } } public enum Unit: String, CustomStringConvertible, Codable { case bits = "BITS" case bytes = "BYTES" case packets = "PACKETS" case requests = "REQUESTS" public var description: String { return self.rawValue } } // MARK: Shapes public struct AssociateDRTLogBucketRequest: AWSEncodableShape { /// The Amazon S3 bucket that contains your AWS WAF logs. public let logBucket: String public init(logBucket: String) { self.logBucket = logBucket } public func validate(name: String) throws { try self.validate(self.logBucket, name: "logBucket", parent: name, max: 63) try self.validate(self.logBucket, name: "logBucket", parent: name, min: 3) try self.validate(self.logBucket, name: "logBucket", parent: name, pattern: "^([a-z]|(\\d(?!\\d{0,2}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})))([a-z\\d]|(\\.(?!(\\.|-)))|(-(?!\\.))){1,61}[a-z\\d]$") } private enum CodingKeys: String, CodingKey { case logBucket = "LogBucket" } } public struct AssociateDRTLogBucketResponse: AWSDecodableShape { public init() {} } public struct AssociateDRTRoleRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the role the DRT will use to access your AWS account. Prior to making the AssociateDRTRole request, you must attach the AWSShieldDRTAccessPolicy managed policy to this role. For more information see Attaching and Detaching IAM Policies. public let roleArn: String public init(roleArn: String) { self.roleArn = roleArn } public func validate(name: String) throws { try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:aws:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+") } private enum CodingKeys: String, CodingKey { case roleArn = "RoleArn" } } public struct AssociateDRTRoleResponse: AWSDecodableShape { public init() {} } public struct AssociateHealthCheckRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the health check to associate with the protection. public let healthCheckArn: String /// The unique identifier (ID) for the Protection object to add the health check association to. public let protectionId: String public init(healthCheckArn: String, protectionId: String) { self.healthCheckArn = healthCheckArn self.protectionId = protectionId } public func validate(name: String) throws { try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, max: 2048) try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, min: 1) try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, pattern: "^arn:aws:route53:::healthcheck/\\S{36}$") try self.validate(self.protectionId, name: "protectionId", parent: name, max: 36) try self.validate(self.protectionId, name: "protectionId", parent: name, min: 1) try self.validate(self.protectionId, name: "protectionId", parent: name, pattern: "[a-zA-Z0-9\\\\-]*") } private enum CodingKeys: String, CodingKey { case healthCheckArn = "HealthCheckArn" case protectionId = "ProtectionId" } } public struct AssociateHealthCheckResponse: AWSDecodableShape { public init() {} } public struct AssociateProactiveEngagementDetailsRequest: AWSEncodableShape { /// A list of email addresses and phone numbers that the DDoS Response Team (DRT) can use to contact you for escalations to the DRT and to initiate proactive customer support. To enable proactive engagement, the contact list must include at least one phone number. The contacts that you provide here replace any contacts that were already defined. If you already have contacts defined and want to use them, retrieve the list using DescribeEmergencyContactSettings and then provide it here. public let emergencyContactList: [EmergencyContact] public init(emergencyContactList: [EmergencyContact]) { self.emergencyContactList = emergencyContactList } public func validate(name: String) throws { try self.emergencyContactList.forEach { try $0.validate(name: "\(name).emergencyContactList[]") } try self.validate(self.emergencyContactList, name: "emergencyContactList", parent: name, max: 10) try self.validate(self.emergencyContactList, name: "emergencyContactList", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case emergencyContactList = "EmergencyContactList" } } public struct AssociateProactiveEngagementDetailsResponse: AWSDecodableShape { public init() {} } public struct AttackDetail: AWSDecodableShape { /// List of counters that describe the attack for the specified time period. public let attackCounters: [SummarizedCounter]? /// The unique identifier (ID) of the attack. public let attackId: String? /// The array of AttackProperty objects. public let attackProperties: [AttackProperty]? /// The time the attack ended, in Unix time in seconds. For more information see timestamp. public let endTime: Date? /// List of mitigation actions taken for the attack. public let mitigations: [Mitigation]? /// The ARN (Amazon Resource Name) of the resource that was attacked. public let resourceArn: String? /// The time the attack started, in Unix time in seconds. For more information see timestamp. public let startTime: Date? /// If applicable, additional detail about the resource being attacked, for example, IP address or URL. public let subResources: [SubResourceSummary]? public init(attackCounters: [SummarizedCounter]? = nil, attackId: String? = nil, attackProperties: [AttackProperty]? = nil, endTime: Date? = nil, mitigations: [Mitigation]? = nil, resourceArn: String? = nil, startTime: Date? = nil, subResources: [SubResourceSummary]? = nil) { self.attackCounters = attackCounters self.attackId = attackId self.attackProperties = attackProperties self.endTime = endTime self.mitigations = mitigations self.resourceArn = resourceArn self.startTime = startTime self.subResources = subResources } private enum CodingKeys: String, CodingKey { case attackCounters = "AttackCounters" case attackId = "AttackId" case attackProperties = "AttackProperties" case endTime = "EndTime" case mitigations = "Mitigations" case resourceArn = "ResourceArn" case startTime = "StartTime" case subResources = "SubResources" } } public struct AttackProperty: AWSDecodableShape { /// The type of distributed denial of service (DDoS) event that was observed. NETWORK indicates layer 3 and layer 4 events and APPLICATION indicates layer 7 events. public let attackLayer: AttackLayer? /// Defines the DDoS attack property information that is provided. The WORDPRESS_PINGBACK_REFLECTOR and WORDPRESS_PINGBACK_SOURCE values are valid only for WordPress reflective pingback DDoS attacks. public let attackPropertyIdentifier: AttackPropertyIdentifier? /// The array of Contributor objects that includes the top five contributors to an attack. public let topContributors: [Contributor]? /// The total contributions made to this attack by all contributors, not just the five listed in the TopContributors list. public let total: Int64? /// The unit of the Value of the contributions. public let unit: Unit? public init(attackLayer: AttackLayer? = nil, attackPropertyIdentifier: AttackPropertyIdentifier? = nil, topContributors: [Contributor]? = nil, total: Int64? = nil, unit: Unit? = nil) { self.attackLayer = attackLayer self.attackPropertyIdentifier = attackPropertyIdentifier self.topContributors = topContributors self.total = total self.unit = unit } private enum CodingKeys: String, CodingKey { case attackLayer = "AttackLayer" case attackPropertyIdentifier = "AttackPropertyIdentifier" case topContributors = "TopContributors" case total = "Total" case unit = "Unit" } } public struct AttackSummary: AWSDecodableShape { /// The unique identifier (ID) of the attack. public let attackId: String? /// The list of attacks for a specified time period. public let attackVectors: [AttackVectorDescription]? /// The end time of the attack, in Unix time in seconds. For more information see timestamp. public let endTime: Date? /// The ARN (Amazon Resource Name) of the resource that was attacked. public let resourceArn: String? /// The start time of the attack, in Unix time in seconds. For more information see timestamp. public let startTime: Date? public init(attackId: String? = nil, attackVectors: [AttackVectorDescription]? = nil, endTime: Date? = nil, resourceArn: String? = nil, startTime: Date? = nil) { self.attackId = attackId self.attackVectors = attackVectors self.endTime = endTime self.resourceArn = resourceArn self.startTime = startTime } private enum CodingKeys: String, CodingKey { case attackId = "AttackId" case attackVectors = "AttackVectors" case endTime = "EndTime" case resourceArn = "ResourceArn" case startTime = "StartTime" } } public struct AttackVectorDescription: AWSDecodableShape { /// The attack type. Valid values: UDP_TRAFFIC UDP_FRAGMENT GENERIC_UDP_REFLECTION DNS_REFLECTION NTP_REFLECTION CHARGEN_REFLECTION SSDP_REFLECTION PORT_MAPPER RIP_REFLECTION SNMP_REFLECTION MSSQL_REFLECTION NET_BIOS_REFLECTION SYN_FLOOD ACK_FLOOD REQUEST_FLOOD HTTP_REFLECTION UDS_REFLECTION MEMCACHED_REFLECTION public let vectorType: String public init(vectorType: String) { self.vectorType = vectorType } private enum CodingKeys: String, CodingKey { case vectorType = "VectorType" } } public struct Contributor: AWSDecodableShape { /// The name of the contributor. This is dependent on the AttackPropertyIdentifier. For example, if the AttackPropertyIdentifier is SOURCE_COUNTRY, the Name could be United States. public let name: String? /// The contribution of this contributor expressed in Protection units. For example 10,000. public let value: Int64? public init(name: String? = nil, value: Int64? = nil) { self.name = name self.value = value } private enum CodingKeys: String, CodingKey { case name = "Name" case value = "Value" } } public struct CreateProtectionRequest: AWSEncodableShape { /// Friendly name for the Protection you are creating. public let name: String /// The ARN (Amazon Resource Name) of the resource to be protected. The ARN should be in one of the following formats: For an Application Load Balancer: arn:aws:elasticloadbalancing:region:account-id:loadbalancer/app/load-balancer-name/load-balancer-id For an Elastic Load Balancer (Classic Load Balancer): arn:aws:elasticloadbalancing:region:account-id:loadbalancer/load-balancer-name For an AWS CloudFront distribution: arn:aws:cloudfront::account-id:distribution/distribution-id For an AWS Global Accelerator accelerator: arn:aws:globalaccelerator::account-id:accelerator/accelerator-id For Amazon Route 53: arn:aws:route53:::hostedzone/hosted-zone-id For an Elastic IP address: arn:aws:ec2:region:account-id:eip-allocation/allocation-id public let resourceArn: String public init(name: String, resourceArn: String) { self.name = name self.resourceArn = resourceArn } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 128) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "[ a-zA-Z0-9_\\\\.\\\\-]*") try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 2048) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 1) try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "^arn:aws.*") } private enum CodingKeys: String, CodingKey { case name = "Name" case resourceArn = "ResourceArn" } } public struct CreateProtectionResponse: AWSDecodableShape { /// The unique identifier (ID) for the Protection object that is created. public let protectionId: String? public init(protectionId: String? = nil) { self.protectionId = protectionId } private enum CodingKeys: String, CodingKey { case protectionId = "ProtectionId" } } public struct CreateSubscriptionRequest: AWSEncodableShape { public init() {} } public struct CreateSubscriptionResponse: AWSDecodableShape { public init() {} } public struct DeleteProtectionRequest: AWSEncodableShape { /// The unique identifier (ID) for the Protection object to be deleted. public let protectionId: String public init(protectionId: String) { self.protectionId = protectionId } public func validate(name: String) throws { try self.validate(self.protectionId, name: "protectionId", parent: name, max: 36) try self.validate(self.protectionId, name: "protectionId", parent: name, min: 1) try self.validate(self.protectionId, name: "protectionId", parent: name, pattern: "[a-zA-Z0-9\\\\-]*") } private enum CodingKeys: String, CodingKey { case protectionId = "ProtectionId" } } public struct DeleteProtectionResponse: AWSDecodableShape { public init() {} } public struct DeleteSubscriptionRequest: AWSEncodableShape { public init() {} } public struct DeleteSubscriptionResponse: AWSDecodableShape { public init() {} } public struct DescribeAttackRequest: AWSEncodableShape { /// The unique identifier (ID) for the attack that to be described. public let attackId: String public init(attackId: String) { self.attackId = attackId } public func validate(name: String) throws { try self.validate(self.attackId, name: "attackId", parent: name, max: 128) try self.validate(self.attackId, name: "attackId", parent: name, min: 1) try self.validate(self.attackId, name: "attackId", parent: name, pattern: "[a-zA-Z0-9\\\\-]*") } private enum CodingKeys: String, CodingKey { case attackId = "AttackId" } } public struct DescribeAttackResponse: AWSDecodableShape { /// The attack that is described. public let attack: AttackDetail? public init(attack: AttackDetail? = nil) { self.attack = attack } private enum CodingKeys: String, CodingKey { case attack = "Attack" } } public struct DescribeDRTAccessRequest: AWSEncodableShape { public init() {} } public struct DescribeDRTAccessResponse: AWSDecodableShape { /// The list of Amazon S3 buckets accessed by the DRT. public let logBucketList: [String]? /// The Amazon Resource Name (ARN) of the role the DRT used to access your AWS account. public let roleArn: String? public init(logBucketList: [String]? = nil, roleArn: String? = nil) { self.logBucketList = logBucketList self.roleArn = roleArn } private enum CodingKeys: String, CodingKey { case logBucketList = "LogBucketList" case roleArn = "RoleArn" } } public struct DescribeEmergencyContactSettingsRequest: AWSEncodableShape { public init() {} } public struct DescribeEmergencyContactSettingsResponse: AWSDecodableShape { /// A list of email addresses and phone numbers that the DDoS Response Team (DRT) can use to contact you if you have proactive engagement enabled, for escalations to the DRT and to initiate proactive customer support. public let emergencyContactList: [EmergencyContact]? public init(emergencyContactList: [EmergencyContact]? = nil) { self.emergencyContactList = emergencyContactList } private enum CodingKeys: String, CodingKey { case emergencyContactList = "EmergencyContactList" } } public struct DescribeProtectionRequest: AWSEncodableShape { /// The unique identifier (ID) for the Protection object that is described. When submitting the DescribeProtection request you must provide either the ResourceArn or the ProtectionID, but not both. public let protectionId: String? /// The ARN (Amazon Resource Name) of the AWS resource for the Protection object that is described. When submitting the DescribeProtection request you must provide either the ResourceArn or the ProtectionID, but not both. public let resourceArn: String? public init(protectionId: String? = nil, resourceArn: String? = nil) { self.protectionId = protectionId self.resourceArn = resourceArn } public func validate(name: String) throws { try self.validate(self.protectionId, name: "protectionId", parent: name, max: 36) try self.validate(self.protectionId, name: "protectionId", parent: name, min: 1) try self.validate(self.protectionId, name: "protectionId", parent: name, pattern: "[a-zA-Z0-9\\\\-]*") try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 2048) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 1) try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "^arn:aws.*") } private enum CodingKeys: String, CodingKey { case protectionId = "ProtectionId" case resourceArn = "ResourceArn" } } public struct DescribeProtectionResponse: AWSDecodableShape { /// The Protection object that is described. public let protection: Protection? public init(protection: Protection? = nil) { self.protection = protection } private enum CodingKeys: String, CodingKey { case protection = "Protection" } } public struct DescribeSubscriptionRequest: AWSEncodableShape { public init() {} } public struct DescribeSubscriptionResponse: AWSDecodableShape { /// The AWS Shield Advanced subscription details for an account. public let subscription: Subscription? public init(subscription: Subscription? = nil) { self.subscription = subscription } private enum CodingKeys: String, CodingKey { case subscription = "Subscription" } } public struct DisableProactiveEngagementRequest: AWSEncodableShape { public init() {} } public struct DisableProactiveEngagementResponse: AWSDecodableShape { public init() {} } public struct DisassociateDRTLogBucketRequest: AWSEncodableShape { /// The Amazon S3 bucket that contains your AWS WAF logs. public let logBucket: String public init(logBucket: String) { self.logBucket = logBucket } public func validate(name: String) throws { try self.validate(self.logBucket, name: "logBucket", parent: name, max: 63) try self.validate(self.logBucket, name: "logBucket", parent: name, min: 3) try self.validate(self.logBucket, name: "logBucket", parent: name, pattern: "^([a-z]|(\\d(?!\\d{0,2}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})))([a-z\\d]|(\\.(?!(\\.|-)))|(-(?!\\.))){1,61}[a-z\\d]$") } private enum CodingKeys: String, CodingKey { case logBucket = "LogBucket" } } public struct DisassociateDRTLogBucketResponse: AWSDecodableShape { public init() {} } public struct DisassociateDRTRoleRequest: AWSEncodableShape { public init() {} } public struct DisassociateDRTRoleResponse: AWSDecodableShape { public init() {} } public struct DisassociateHealthCheckRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the health check that is associated with the protection. public let healthCheckArn: String /// The unique identifier (ID) for the Protection object to remove the health check association from. public let protectionId: String public init(healthCheckArn: String, protectionId: String) { self.healthCheckArn = healthCheckArn self.protectionId = protectionId } public func validate(name: String) throws { try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, max: 2048) try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, min: 1) try self.validate(self.healthCheckArn, name: "healthCheckArn", parent: name, pattern: "^arn:aws:route53:::healthcheck/\\S{36}$") try self.validate(self.protectionId, name: "protectionId", parent: name, max: 36) try self.validate(self.protectionId, name: "protectionId", parent: name, min: 1) try self.validate(self.protectionId, name: "protectionId", parent: name, pattern: "[a-zA-Z0-9\\\\-]*") } private enum CodingKeys: String, CodingKey { case healthCheckArn = "HealthCheckArn" case protectionId = "ProtectionId" } } public struct DisassociateHealthCheckResponse: AWSDecodableShape { public init() {} } public struct EmergencyContact: AWSEncodableShape & AWSDecodableShape { /// Additional notes regarding the contact. public let contactNotes: String? /// The email address for the contact. public let emailAddress: String /// The phone number for the contact. public let phoneNumber: String? public init(contactNotes: String? = nil, emailAddress: String, phoneNumber: String? = nil) { self.contactNotes = contactNotes self.emailAddress = emailAddress self.phoneNumber = phoneNumber } public func validate(name: String) throws { try self.validate(self.contactNotes, name: "contactNotes", parent: name, max: 1024) try self.validate(self.contactNotes, name: "contactNotes", parent: name, min: 1) try self.validate(self.contactNotes, name: "contactNotes", parent: name, pattern: "^[\\w\\s\\.\\-,:/()+@]*$") try self.validate(self.emailAddress, name: "emailAddress", parent: name, max: 150) try self.validate(self.emailAddress, name: "emailAddress", parent: name, min: 1) try self.validate(self.emailAddress, name: "emailAddress", parent: name, pattern: "^\\S+@\\S+\\.\\S+$") try self.validate(self.phoneNumber, name: "phoneNumber", parent: name, max: 16) try self.validate(self.phoneNumber, name: "phoneNumber", parent: name, min: 1) try self.validate(self.phoneNumber, name: "phoneNumber", parent: name, pattern: "^\\+[1-9]\\d{1,14}$") } private enum CodingKeys: String, CodingKey { case contactNotes = "ContactNotes" case emailAddress = "EmailAddress" case phoneNumber = "PhoneNumber" } } public struct EnableProactiveEngagementRequest: AWSEncodableShape { public init() {} } public struct EnableProactiveEngagementResponse: AWSDecodableShape { public init() {} } public struct GetSubscriptionStateRequest: AWSEncodableShape { public init() {} } public struct GetSubscriptionStateResponse: AWSDecodableShape { /// The status of the subscription. public let subscriptionState: SubscriptionState public init(subscriptionState: SubscriptionState) { self.subscriptionState = subscriptionState } private enum CodingKeys: String, CodingKey { case subscriptionState = "SubscriptionState" } } public struct Limit: AWSDecodableShape { /// The maximum number of protections that can be created for the specified Type. public let max: Int64? /// The type of protection. public let type: String? public init(max: Int64? = nil, type: String? = nil) { self.max = max self.type = type } private enum CodingKeys: String, CodingKey { case max = "Max" case type = "Type" } } public struct ListAttacksRequest: AWSEncodableShape { /// The end of the time period for the attacks. This is a timestamp type. The sample request above indicates a number type because the default used by WAF is Unix time in seconds. However any valid timestamp format is allowed. public let endTime: TimeRange? /// The maximum number of AttackSummary objects to be returned. If this is left blank, the first 20 results will be returned. This is a maximum value; it is possible that AWS WAF will return the results in smaller batches. That is, the number of AttackSummary objects returned could be less than MaxResults, even if there are still more AttackSummary objects yet to return. If there are more AttackSummary objects to return, AWS WAF will always also return a NextToken. public let maxResults: Int? /// The ListAttacksRequest.NextMarker value from a previous call to ListAttacksRequest. Pass null if this is the first call. public let nextToken: String? /// The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources for this account will be included. public let resourceArns: [String]? /// The start of the time period for the attacks. This is a timestamp type. The sample request above indicates a number type because the default used by WAF is Unix time in seconds. However any valid timestamp format is allowed. public let startTime: TimeRange? public init(endTime: TimeRange? = nil, maxResults: Int? = nil, nextToken: String? = nil, resourceArns: [String]? = nil, startTime: TimeRange? = nil) { self.endTime = endTime self.maxResults = maxResults self.nextToken = nextToken self.resourceArns = resourceArns self.startTime = startTime } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10000) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 0) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 4096) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^.*$") try self.resourceArns?.forEach { try validate($0, name: "resourceArns[]", parent: name, max: 2048) try validate($0, name: "resourceArns[]", parent: name, min: 1) try validate($0, name: "resourceArns[]", parent: name, pattern: "^arn:aws.*") } } private enum CodingKeys: String, CodingKey { case endTime = "EndTime" case maxResults = "MaxResults" case nextToken = "NextToken" case resourceArns = "ResourceArns" case startTime = "StartTime" } } public struct ListAttacksResponse: AWSDecodableShape { /// The attack information for the specified time range. public let attackSummaries: [AttackSummary]? /// The token returned by a previous call to indicate that there is more data available. If not null, more results are available. Pass this value for the NextMarker parameter in a subsequent call to ListAttacks to retrieve the next set of items. AWS WAF might return the list of AttackSummary objects in batches smaller than the number specified by MaxResults. If there are more AttackSummary objects to return, AWS WAF will always also return a NextToken. public let nextToken: String? public init(attackSummaries: [AttackSummary]? = nil, nextToken: String? = nil) { self.attackSummaries = attackSummaries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case attackSummaries = "AttackSummaries" case nextToken = "NextToken" } } public struct ListProtectionsRequest: AWSEncodableShape { /// The maximum number of Protection objects to be returned. If this is left blank the first 20 results will be returned. This is a maximum value; it is possible that AWS WAF will return the results in smaller batches. That is, the number of Protection objects returned could be less than MaxResults, even if there are still more Protection objects yet to return. If there are more Protection objects to return, AWS WAF will always also return a NextToken. public let maxResults: Int? /// The ListProtectionsRequest.NextToken value from a previous call to ListProtections. Pass null if this is the first call. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10000) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 0) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 4096) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^.*$") } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListProtectionsResponse: AWSDecodableShape { /// If you specify a value for MaxResults and you have more Protections than the value of MaxResults, AWS Shield Advanced returns a NextToken value in the response that allows you to list another group of Protections. For the second and subsequent ListProtections requests, specify the value of NextToken from the previous response to get information about another batch of Protections. AWS WAF might return the list of Protection objects in batches smaller than the number specified by MaxResults. If there are more Protection objects to return, AWS WAF will always also return a NextToken. public let nextToken: String? /// The array of enabled Protection objects. public let protections: [Protection]? public init(nextToken: String? = nil, protections: [Protection]? = nil) { self.nextToken = nextToken self.protections = protections } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case protections = "Protections" } } public struct Mitigation: AWSDecodableShape { /// The name of the mitigation taken for this attack. public let mitigationName: String? public init(mitigationName: String? = nil) { self.mitigationName = mitigationName } private enum CodingKeys: String, CodingKey { case mitigationName = "MitigationName" } } public struct Protection: AWSDecodableShape { /// The unique identifier (ID) for the Route 53 health check that's associated with the protection. public let healthCheckIds: [String]? /// The unique identifier (ID) of the protection. public let id: String? /// The friendly name of the protection. For example, My CloudFront distributions. public let name: String? /// The ARN (Amazon Resource Name) of the AWS resource that is protected. public let resourceArn: String? public init(healthCheckIds: [String]? = nil, id: String? = nil, name: String? = nil, resourceArn: String? = nil) { self.healthCheckIds = healthCheckIds self.id = id self.name = name self.resourceArn = resourceArn } private enum CodingKeys: String, CodingKey { case healthCheckIds = "HealthCheckIds" case id = "Id" case name = "Name" case resourceArn = "ResourceArn" } } public struct SubResourceSummary: AWSDecodableShape { /// The list of attack types and associated counters. public let attackVectors: [SummarizedAttackVector]? /// The counters that describe the details of the attack. public let counters: [SummarizedCounter]? /// The unique identifier (ID) of the SubResource. public let id: String? /// The SubResource type. public let type: SubResourceType? public init(attackVectors: [SummarizedAttackVector]? = nil, counters: [SummarizedCounter]? = nil, id: String? = nil, type: SubResourceType? = nil) { self.attackVectors = attackVectors self.counters = counters self.id = id self.type = type } private enum CodingKeys: String, CodingKey { case attackVectors = "AttackVectors" case counters = "Counters" case id = "Id" case type = "Type" } } public struct Subscription: AWSDecodableShape { /// If ENABLED, the subscription will be automatically renewed at the end of the existing subscription period. When you initally create a subscription, AutoRenew is set to ENABLED. You can change this by submitting an UpdateSubscription request. If the UpdateSubscription request does not included a value for AutoRenew, the existing value for AutoRenew remains unchanged. public let autoRenew: AutoRenew? /// The date and time your subscription will end. public let endTime: Date? /// Specifies how many protections of a given type you can create. public let limits: [Limit]? /// If ENABLED, the DDoS Response Team (DRT) will use email and phone to notify contacts about escalations to the DRT and to initiate proactive customer support. If PENDING, you have requested proactive engagement and the request is pending. The status changes to ENABLED when your request is fully processed. If DISABLED, the DRT will not proactively notify contacts about escalations or to initiate proactive customer support. public let proactiveEngagementStatus: ProactiveEngagementStatus? /// The start time of the subscription, in Unix time in seconds. For more information see timestamp. public let startTime: Date? /// The length, in seconds, of the AWS Shield Advanced subscription for the account. public let timeCommitmentInSeconds: Int64? public init(autoRenew: AutoRenew? = nil, endTime: Date? = nil, limits: [Limit]? = nil, proactiveEngagementStatus: ProactiveEngagementStatus? = nil, startTime: Date? = nil, timeCommitmentInSeconds: Int64? = nil) { self.autoRenew = autoRenew self.endTime = endTime self.limits = limits self.proactiveEngagementStatus = proactiveEngagementStatus self.startTime = startTime self.timeCommitmentInSeconds = timeCommitmentInSeconds } private enum CodingKeys: String, CodingKey { case autoRenew = "AutoRenew" case endTime = "EndTime" case limits = "Limits" case proactiveEngagementStatus = "ProactiveEngagementStatus" case startTime = "StartTime" case timeCommitmentInSeconds = "TimeCommitmentInSeconds" } } public struct SummarizedAttackVector: AWSDecodableShape { /// The list of counters that describe the details of the attack. public let vectorCounters: [SummarizedCounter]? /// The attack type, for example, SNMP reflection or SYN flood. public let vectorType: String public init(vectorCounters: [SummarizedCounter]? = nil, vectorType: String) { self.vectorCounters = vectorCounters self.vectorType = vectorType } private enum CodingKeys: String, CodingKey { case vectorCounters = "VectorCounters" case vectorType = "VectorType" } } public struct SummarizedCounter: AWSDecodableShape { /// The average value of the counter for a specified time period. public let average: Double? /// The maximum value of the counter for a specified time period. public let max: Double? /// The number of counters for a specified time period. public let n: Int? /// The counter name. public let name: String? /// The total of counter values for a specified time period. public let sum: Double? /// The unit of the counters. public let unit: String? public init(average: Double? = nil, max: Double? = nil, n: Int? = nil, name: String? = nil, sum: Double? = nil, unit: String? = nil) { self.average = average self.max = max self.n = n self.name = name self.sum = sum self.unit = unit } private enum CodingKeys: String, CodingKey { case average = "Average" case max = "Max" case n = "N" case name = "Name" case sum = "Sum" case unit = "Unit" } } public struct TimeRange: AWSEncodableShape { /// The start time, in Unix time in seconds. For more information see timestamp. public let fromInclusive: Date? /// The end time, in Unix time in seconds. For more information see timestamp. public let toExclusive: Date? public init(fromInclusive: Date? = nil, toExclusive: Date? = nil) { self.fromInclusive = fromInclusive self.toExclusive = toExclusive } private enum CodingKeys: String, CodingKey { case fromInclusive = "FromInclusive" case toExclusive = "ToExclusive" } } public struct UpdateEmergencyContactSettingsRequest: AWSEncodableShape { /// A list of email addresses and phone numbers that the DDoS Response Team (DRT) can use to contact you if you have proactive engagement enabled, for escalations to the DRT and to initiate proactive customer support. If you have proactive engagement enabled, the contact list must include at least one phone number. public let emergencyContactList: [EmergencyContact]? public init(emergencyContactList: [EmergencyContact]? = nil) { self.emergencyContactList = emergencyContactList } public func validate(name: String) throws { try self.emergencyContactList?.forEach { try $0.validate(name: "\(name).emergencyContactList[]") } try self.validate(self.emergencyContactList, name: "emergencyContactList", parent: name, max: 10) try self.validate(self.emergencyContactList, name: "emergencyContactList", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case emergencyContactList = "EmergencyContactList" } } public struct UpdateEmergencyContactSettingsResponse: AWSDecodableShape { public init() {} } public struct UpdateSubscriptionRequest: AWSEncodableShape { /// When you initally create a subscription, AutoRenew is set to ENABLED. If ENABLED, the subscription will be automatically renewed at the end of the existing subscription period. You can change this by submitting an UpdateSubscription request. If the UpdateSubscription request does not included a value for AutoRenew, the existing value for AutoRenew remains unchanged. public let autoRenew: AutoRenew? public init(autoRenew: AutoRenew? = nil) { self.autoRenew = autoRenew } private enum CodingKeys: String, CodingKey { case autoRenew = "AutoRenew" } } public struct UpdateSubscriptionResponse: AWSDecodableShape { public init() {} } }
apache-2.0
bdd989c63cc50e8c5b111cd464e1a95d
45.319082
770
0.651914
5.026593
false
false
false
false
jmieville/ToTheMoonAndBack-PitchPerfect
PitchPerfect/PlaySoundsViewController.swift
1
2162
// // PlaySoundsViewController.swift // PitchPerfect // // Created by Jean-Marc Kampol Mieville on 5/30/2559 BE. // Copyright © 2559 Jean-Marc Kampol Mieville. All rights reserved. // import AVFoundation import UIKit class PlaySoundsViewController: UIViewController { //Outlets @IBOutlet weak var snailButton: UIButton! @IBOutlet weak var rabbitButton: UIButton! @IBOutlet weak var chipmunkButton: UIButton! @IBOutlet weak var darthVaderButton: UIButton! @IBOutlet weak var echoButton: UIButton! @IBOutlet weak var revertButton: UIButton! @IBOutlet weak var stopButton: UIButton! var recordedAudioURL: NSURL! var audioFile: AVAudioFile! var audioEngine: AVAudioEngine! var audioPlayerNode: AVAudioPlayerNode! var stopTimer: Timer! enum ButtonType: Int { case Slow = 0, Fast, Chipmunk, Vader, Echo, Reverb } @IBAction func playSoundForButton(sender: UIButton) { print("Play Sound Button Pressed") switch(ButtonType(rawValue: sender.tag)!) { case .Slow: playSound(rate: 0.5) case .Fast: playSound(rate: 1.5) case .Chipmunk: playSound(pitch: 1000) case .Vader: playSound(pitch: -1000) case .Echo: playSound(echo: true) case .Reverb: playSound(reverb: true) } configureUI(playState: .Playing) } @IBAction func StopButtonPressed(sender: UIButton) { print("Stop Sound Button Pressed") stopAudio() } override func viewDidLoad() { super.viewDidLoad() print("PlaySoundsViewController loaded") setupAudio() } override func viewWillAppear(_ animated: Bool) { configureUI(playState: .NotPlaying) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "stopRecording") { let playSoundsVC = segue.destination as! PlaySoundsViewController let recordedAudioURL = sender as! NSURL playSoundsVC.recordedAudioURL = recordedAudioURL } } }
mit
0922bd9e5bd642fc7bc7c5bd4694f08e
27.813333
77
0.636742
4.749451
false
false
false
false
Trioser/Calculator
Calculator/ViewController.swift
1
4171
// // ViewController.swift // Calculator // // Created by Richard E Millet on 1/28/15. // Copyright (c) 2015 remillet. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. history.text = "" display.text = "0.0" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // // My changes // let enterSymbol = "⏎" let memoryKey = "M" var activeTyping : Bool = false var calculatorBrain = CalculatorBrain() @IBOutlet weak var display: UILabel! @IBOutlet weak var history: UILabel! // Settable/Gettable aka "Computed" property private var displayValue : Double? { set { activeTyping = false if newValue == nil { display.text = " " } else { display.text = "\(newValue!)" } } get { return NSNumberFormatter().numberFromString(display.text!)?.doubleValue } } @IBAction func memorySet(sender: UIButton) { if let currentDisplayValue = displayValue { activeTyping = false calculatorBrain.setMemoryVariable(memoryKey, value: currentDisplayValue) displayValue = calculatorBrain.evaluate() } else { println("Current display value is not valid for memory set key.") } } @IBAction func memoryGet(sender: UIButton) { if activeTyping { enter(enterSymbol) } display.text = memoryKey enter(enterSymbol) } @IBAction func operate(sender: UIButton) { if activeTyping { enter(sender.currentTitle) } if let operatorString = sender.currentTitle { if let result = calculatorBrain.performOperation(operatorString) { displayValue = result } else { displayValue = nil } } history.text! = calculatorBrain.description } func doSort(nameList: Array<String>, operation: (String, String) -> Bool) -> Array<String> { var arraySize: Int = nameList.count var result = nameList var finished: Bool = false while (finished == false) { finished = true var index: Int = 0 while (index < arraySize - 1) { if (operation(result[index], result[index + 1])) { finished = false var swap = result[index] result[index] = result[index + 1] result[index + 1] = swap } index++ } } return result } @IBAction func appendDecimalPoint(sender: UIButton) { if (activeTyping == true) { if (display.text!.rangeOfString(".") == nil) { display.text = display.text! + "." } } else { display.text = "0." activeTyping = true } } // // An example sort routine showing closure syntax // @IBAction func arraySort() { let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] println("Unsorted: \(names)") let sortedNames = doSort(names, {return $0 > $1}) // equvalent of {(s1: String, s2: String) -> Bool in s2 > s1} println("Sorted: \(sortedNames)") let reverseSortedName = doSort(names, {return $1 > $0}) // {(s1: String, s2: String) -> Bool in s2 > s1}) println("Reverse sorted: \(reverseSortedName)") } @IBAction func appendPi(sender: UIButton) { if activeTyping { enter(enterSymbol) } display.text = piSymbol enter(enterSymbol) } @IBAction func clearEntry(sender: UIButton) { displayValue = 0 } @IBAction func clear(sender: UIButton) { displayValue = 0 history.text = "" calculatorBrain.clear() } @IBAction func appendDigit(sender: UIButton) { let digit = sender.currentTitle! println("digit = \(digit)") if (activeTyping == true) { display.text = display.text! + digit } else { display.text = digit activeTyping = true } } @IBAction func enter(sender: UIButton) { enter(sender.currentTitle) } private func enter(op: String?) { // history.text! += display.text! // // if let historyOp = op { // history.text! += historyOp // } activeTyping = false if let operand = displayValue { displayValue = calculatorBrain.pushOperand(displayValue) } else { displayValue = calculatorBrain.pushOperand(display.text!) } history.text! = calculatorBrain.description } }
apache-2.0
5f2b70a44566400ba2f775fe91975fa5
21.657609
113
0.662029
3.431276
false
false
false
false
ihomway/RayWenderlichCourses
Advanced Swift 3/Advanced Swift 3.playground/Pages/Protocols and Generics Challenge.xcplaygroundpage/Contents.swift
1
2283
//: [Previous](@previous) import Foundation // Challenge // // Inventory contains an array of different models that conform // to the Item protocol. Make all of the necessary changes to // the Item protocol and Inventory to make Inventory Equatable. // // Test it out by uncommenting the code below. protocol Item { var name: String { get } var weight: Int { get } func isEqual(to another:Item) -> Bool } extension Item { func isEqual(to another:Item) -> Bool { return name == another.name && weight == another.weight } } struct Inventory: Equatable { var items: [Item] static func ==(lhs: Inventory, rhs: Inventory) -> Bool { return lhs.items.count == rhs.items.count && !zip(lhs.items, rhs.items).contains(where: { let (item1, item2) = $0 return !item1.isEqual(to: item2) }) } } struct Armor: Item, Equatable { let name: String let weight: Int let armorClass: Int static func ==(lhs: Armor, rhs: Armor) -> Bool { return lhs.name == rhs.name && lhs.weight == rhs.weight && lhs.armorClass == rhs.armorClass } } struct Weapon: Item, Equatable { let name: String let weight: Int let damage: Int static func ==(lhs: Weapon, rhs: Weapon) -> Bool { return lhs.name == rhs.name && lhs.weight == rhs.weight && lhs.damage == rhs.damage } } struct Scroll: Item, Equatable { let name: String var weight: Int { return 1 } let magicWord: String static func ==(lhs: Scroll, rhs: Scroll) -> Bool { return lhs.name == rhs.name && lhs.magicWord == rhs.magicWord } } // Test code var tankEquipment = Inventory(items: [Armor(name: "Plate", weight: 180, armorClass: 2), Weapon(name: "Sword", weight: 20, damage: 30)]) var rogueEquipment = Inventory(items: [Armor(name: "Leather", weight: 40, armorClass: 7), Weapon(name: "Dagger", weight: 5, damage: 7)]) var wizardEquipment = Inventory(items: [Weapon(name: "Dagger", weight: 5, damage: 7), Scroll(name: "Create Water", magicWord: "Mizu!"), Scroll(name: "Vortex of Teeth", magicWord: "Sakana!"), Scroll(name: "Fireball", magicWord: "Utte!")]) tankEquipment == tankEquipment wizardEquipment == wizardEquipment tankEquipment != wizardEquipment tankEquipment != rogueEquipment tankEquipment == wizardEquipment tankEquipment == rogueEquipment //: [Next](@next)
mit
d5b55b7bad9f89b230cbe02ecd7a129a
23.031579
63
0.680245
3.323144
false
false
false
false
wolf81/Nimbl3Survey
Nimbl3Survey/PageIndicatorView.swift
1
6542
// // PageIndicatorView.swift // Nimbl3Survey // // Created by Wolfgang Schreurs on 24/03/2017. // Copyright © 2017 Wolftrail. All rights reserved. // import UIKit import GLKit protocol PageIndicatorViewDelegate: class { func pageIndicatorViewNavigateNextAction(_ view: PageIndicatorView) func pageIndicatorViewNavigatePreviousAction(_ view: PageIndicatorView) func pageIndicatorView(_ view: PageIndicatorView, touchedIndicatorAtIndex index: Int) } class PageIndicatorView: UIControl { private let horizontalMargin: CGFloat = 2 var animationDuration: TimeInterval = 0.2 weak var delegate: PageIndicatorViewDelegate? private var indicatorTouchRects = [CGRect]() // MARK: - Initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } private func commonInit() { self.backgroundColor = UIColor(white: 0, alpha: 0) self.layer.masksToBounds = true } // MARK: - Properties override var frame: CGRect { didSet { self.layer.cornerRadius = fmin(bounds.width / 2, 10) } } var count: Int = NSNotFound { didSet { self.index = 0 setNeedsDisplay() } } var index: Int = NSNotFound { didSet { setNeedsDisplay() UIView.transition(with: self, duration: 0.2, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: { self.layer.displayIfNeeded() }, completion: nil) } } var indicatorColor: UIColor = UIColor.white { didSet { setNeedsDisplay() } } var lineWidth: CGFloat = 2 { didSet { setNeedsDisplay() } } var verticalMargin: CGFloat = 10 { didSet { setNeedsDisplay() } } // MARK: - Drawing override func draw(_ rect: CGRect) { guard self.count != NSNotFound else { return } guard let ctx = UIGraphicsGetCurrentContext() else { return } ctx.saveGState() ctx.clear(rect) let highlighted = (self.isSelected || self.isHighlighted) if highlighted { let backgroundColor = UIColor(white: 0, alpha: 0.5) ctx.setFillColor(backgroundColor.cgColor) ctx.fill(rect) } let foregroundColor = highlighted ? self.indicatorColor.withAlphaComponent(0.5) : self.indicatorColor ctx.setFillColor(foregroundColor.cgColor) ctx.setStrokeColor(foregroundColor.cgColor) ctx.setLineWidth(self.lineWidth) let x: CGFloat = (rect.origin.x + (rect.width / 2)) let r: CGFloat = (rect.width / 2) - lineWidth - self.horizontalMargin let h = (rect.width - lineWidth - (self.horizontalMargin * 2)) let totalHeight = CGFloat(self.count) * h + fmax(CGFloat((self.count - 1)), CGFloat(0)) * verticalMargin var y: CGFloat = (rect.origin.y + rect.size.height / 2) - (totalHeight / 2) + h / 2 for i in (0 ..< count) { let origin = CGPoint(x: x, y: y) let fill = (i == self.index) drawCircleInContext(ctx, atOrigin: origin, withRadius: r, fill: fill) let touchRect = touchRectForCircleAtOrigin(origin, withRadius: r, inRect: rect) self.indicatorTouchRects.append(touchRect) y += (h + verticalMargin) } ctx.restoreGState() } // MARK: - Layout override func sizeThatFits(_ size: CGSize) -> CGSize { let width = min(16 + (self.horizontalMargin * 2), size.width) return CGSize(width: width, height: size.height) } // MARK: - State changes override var isSelected: Bool { didSet { setNeedsDisplay() UIView.transition(with: self, duration: self.animationDuration, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: { self.layer.displayIfNeeded() }, completion: nil) } } override var isHighlighted: Bool { didSet { setNeedsDisplay() UIView.transition(with: self, duration: self.animationDuration, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: { self.layer.displayIfNeeded() }, completion: nil) } } // MARK: - User interaction override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) guard let touch = touches.first else { return } let point = touch.location(in: self) if let touchedRect = (self.indicatorTouchRects.filter { $0.contains(point) }).first { if let index = self.indicatorTouchRects.index(of: touchedRect) { self.delegate?.pageIndicatorView(self, touchedIndicatorAtIndex: index) } } else { if point.y > (self.indicatorTouchRects.first?.minY)! { self.delegate?.pageIndicatorViewNavigatePreviousAction(self) } else if point.y < (self.indicatorTouchRects.last?.maxY)! { self.delegate?.pageIndicatorViewNavigateNextAction(self) } } } // MARK: - Private private func touchRectForCircleAtOrigin(_ origin: CGPoint, withRadius radius: CGFloat, inRect rect: CGRect) -> CGRect { let yOffset = (self.verticalMargin / 2) + self.lineWidth var touchRect = CGRect() touchRect.origin.y = origin.y - radius - yOffset touchRect.origin.x = 0 touchRect.size.height = (radius * 2) + (yOffset * 2) touchRect.size.width = rect.width return touchRect } private func drawCircleInContext(_ ctx: CGContext, atOrigin origin: CGPoint, withRadius radius: CGFloat, fill: Bool) { let endAngle = CGFloat(GLKMathDegreesToRadians(360)) ctx.addArc(center: origin, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true) if fill { ctx.drawPath(using: .fillStroke) } else { ctx.strokePath() } } }
bsd-2-clause
50bc6c2b19af4f048a1f2c1e284e5f7c
29.142857
150
0.583244
4.918045
false
false
false
false
wuyezhiguhun/DDSwift
DDSwift/百思不得姐/Main/View/DDBsbdjTabBar.swift
1
2548
// // DDBsbdjTabBar.swift // DDSwift // // Created by yutongmac on 2017/7/6. // Copyright © 2017年 王允顶. All rights reserved. // import UIKit class DDBsbdjTabBar: UITabBar { override func layoutSubviews() { super.layoutSubviews() let btnW = self.frame.size.width / (CGFloat)((self.items?.count)! + 1) let btnH = self.frame.size.height var x: Float = 0.0 var i = 0 for tabBarBtn in self.subviews { if tabBarBtn.isKind(of: NSClassFromString("UITabBarButton")!) { if i == 0 && _previousClickedTabBarBtn == nil { _previousClickedTabBarBtn = tabBarBtn as? UIControl } if i == 2 { i = i + 1 } x = Float(i) * Float(btnW) tabBarBtn.frame = CGRect(x: CGFloat(x), y: 0.0, width: btnW, height: btnH) i = i + 1 } } self.publishButton.center = CGPoint(x: self.frame.width * 0.5, y: self.frame.height * 0.5) } func publishButtonClick() -> Void { let publishView = DDBsbdjPublishView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)) UIApplication.shared.keyWindow?.addSubview(publishView) publishView.frame = (UIApplication.shared.keyWindow?.bounds)! } var _publishButton : UIButton? var publishButton : UIButton { get { if _publishButton == nil { _publishButton = UIButton(type: UIButtonType.custom) _publishButton?.setImage(UIImage(named: "tabBar_publish_icon"), for: UIControlState.normal) _publishButton?.setImage(UIImage(named: "tabBar_publish_click_icon"), for: UIControlState.highlighted) _publishButton?.sizeToFit() _publishButton?.addTarget(self, action: #selector(publishButtonClick), for: UIControlEvents.touchUpInside) self.addSubview(_publishButton!) } return _publishButton! } set { _publishButton = publishButton } } var _previousClickedTabBarBtn : UIControl? var previousClickedTabBarBtn : UIControl { get { if _previousClickedTabBarBtn == nil { _previousClickedTabBarBtn = UIControl() } return _previousClickedTabBarBtn! } set { _previousClickedTabBarBtn = previousClickedTabBarBtn } } }
mit
d982922dc158376611df507142c516f3
32.407895
122
0.562032
4.728119
false
false
false
false
zhangchn/swelly
swelly/ViewController.swift
1
6187
// // ViewController.swift // swelly // // Created by ZhangChen on 05/10/2016. // // import Cocoa class ViewController: NSViewController { @IBOutlet weak var termView : TermView! @IBOutlet weak var connectButton : NSButton! @IBOutlet weak var siteAddressField: NSTextField! @IBOutlet weak var newConnectionView: NSView! var site : Site = Site() var windowDelegate = MainWindowDelegate() var idleTimer: Timer! var reconnectTimer: Timer! weak var currentConnectionViewController : ConnectionViewController? override func viewWillAppear() { super.viewWillAppear() termView.adjustFonts() } override func viewDidAppear() { super.viewDidAppear() self.view.window?.makeFirstResponder(termView) self.view.window?.delegate = windowDelegate self.view.window?.isReleasedWhenClosed = false self.view.window?.backgroundColor = .black let identifier = "login-segue" if (!self.termView.connected) { self.performSegue(withIdentifier: identifier, sender: self) } // let newConnectionAlert = NSAlert(error: NSError(domain: "", code: 0, userInfo: nil)) // newConnectionAlert.alertStyle = .informational // newConnectionAlert.accessoryView = newConnectionView // newConnectionAlert.messageText = "Connect to BBS..." // newConnectionAlert.icon = nil // newConnectionAlert.beginSheetModal(for: self.view.window!) { (resp: NSApplication.ModalResponse) in // self.performSegue(withIdentifier: NSStoryboard.SegueIdentifier.init("login-segue"), sender: self) // } } override func viewDidLoad() { super.viewDidLoad() windowDelegate.controller = self idleTimer = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { [weak self](timer) in self?.termView?.connection?.sendAntiIdle() } } deinit { idleTimer.invalidate() } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } var connectObserver : AnyObject? var disconnectObserver: AnyObject? func connectTo(site address:String, as user: String, using protoc: ConnectionProtocol) { site.address = address site.connectionProtocol = protoc let connection = Connection(site: site) connection.userName = user connection.setup() let term = Terminal() term.delegate = termView connection.terminal = term termView.connection = connection connectObserver = NotificationCenter.default.addObserver(forName: .connectionDidConnect, object: connection, queue: .main) { [weak self] (note) in if let self = self, let connWindow = self.currentConnectionViewController?.view.window { self.view.window?.endSheet(connWindow) } } disconnectObserver = NotificationCenter.default.addObserver(forName: .connectionDidDisconnect, object: connection, queue: .main) { [weak self](note) in if let ob1 = self?.connectObserver { NotificationCenter.default.removeObserver(ob1) } if let ob2 = self?.disconnectObserver { NotificationCenter.default.removeObserver(ob2) } if let vc = self?.currentConnectionViewController { vc.resetUI() } else { let identifier = "login-segue" self?.performSegue(withIdentifier: identifier, sender: self!) } } } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if (segue.identifier ?? "") == "login-segue" { if let vc = segue.destinationController as? ConnectionViewController { vc.terminalViewController = self currentConnectionViewController = vc } } } @IBOutlet var leadingConstraint: NSLayoutConstraint! @IBOutlet var trailingConstraint: NSLayoutConstraint! @IBOutlet var aspectConstraint: NSLayoutConstraint! func disableConstraintsForFullScreen() { aspectConstraint.isActive = false } func enableConstraintsFromFullScreen() { aspectConstraint.isActive = true } } class MainWindowDelegate: NSObject, NSWindowDelegate { weak var controller: ViewController! /* func windowShouldClose(_ sender: NSWindow) -> Bool { sender.setIsVisible(false) return false } */ func windowWillEnterFullScreen(_ notification: Notification) { controller.disableConstraintsForFullScreen() } func windowWillExitFullScreen(_ notification: Notification) { controller.enableConstraintsFromFullScreen() } } class ConnectionViewController : NSViewController { weak var terminalViewController: ViewController! @IBOutlet weak var addressField: NSTextField! @IBOutlet weak var userNameField: NSTextField! @IBOutlet weak var connectionTypeControl: NSSegmentedControl! @IBOutlet weak var confirmButton: NSButton! @IBOutlet weak var cancelButton: NSButton! override func viewDidLoad() { self.userNameField.stringValue = (NSApp.delegate as! AppDelegate).username ?? "" self.addressField.stringValue = (NSApp.delegate as! AppDelegate).site ?? "" } @IBAction func didPressConnect(_ sender: Any) { self.confirmButton.title = "Connecting" self.confirmButton.isEnabled = false (NSApp.delegate as! AppDelegate).username = self.userNameField.stringValue (NSApp.delegate as! AppDelegate).site = self.addressField.stringValue terminalViewController.connectTo(site: addressField.stringValue, as: userNameField.stringValue, using: connectionTypeControl.selectedSegment == 0 ? .telnet : .ssh) } func resetUI() { self.confirmButton.title = "Connect" self.confirmButton.isEnabled = true } @IBAction func didPressCancel(_ sender: Any) { terminalViewController.view.window?.endSheet(view.window!) } }
gpl-2.0
9fa3f8a5f36a2dd316db53965f696bc0
34.97093
171
0.658477
5.130182
false
false
false
false
eugeneego/utilities-ios
Sources/Network/Http/Serializers/JsonHttpSerializer.swift
1
1198
// // JsonHttpSerializer // Legacy // // Copyright (c) 2015 Eugene Egorov. // License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE // import Foundation public enum JsonHttpSerializerError: Error { case serialization(Error) case deserialization(Error) } public struct JsonHttpSerializer: HttpSerializer { public typealias Value = Any public typealias Error = JsonHttpSerializerError public let contentType: String = "application/json" public init() {} public func serialize(_ value: Value?) -> Result<Data, HttpSerializationError> { guard let value = value else { return .success(Data()) } return Result( catching: { try JSONSerialization.data(withJSONObject: value, options: []) }, unknown: { .error(Error.serialization($0)) } ) } public func deserialize(_ data: Data?) -> Result<Value, HttpSerializationError> { guard let data = data, !data.isEmpty else { return .success([:]) } return Result( catching: { try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) }, unknown: { .error(Error.deserialization($0)) } ) } }
mit
0b9c68e2a25a5d33b99b17262e46a1d6
28.219512
99
0.657763
4.555133
false
false
false
false
kingcos/Swift-X-Algorithms
LeetCode/035-Search-Insert-Position/035-Search-Insert-Position.playground/Contents.swift
1
750
import UIKit class Solution_1 { // 44 ms func searchInsert(_ nums: [Int], _ target: Int) -> Int { if let index = nums.firstIndex(of: target) { return index } var nums = nums nums.append(target) return nums.sorted().firstIndex(of: target) ?? 0 } } class Solution_2 { // 40 ms func searchInsert(_ nums: [Int], _ target: Int) -> Int { if let last = nums.last, last < target { return nums.count } for i in 0..<nums.count-1 { if nums[i] == target { return i } if target >= nums[i] && target <= nums[i+1] { return i + 1 } } return 0 } }
mit
58769e6402ca15af25d9a5587a2fcf86
22.4375
60
0.454667
3.947368
false
false
false
false
chinlam91/edx-app-ios
Source/NetworkManager.swift
2
11715
// // CourseOutline.swift // edX // // Created by Jake Lim on 5/09/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public enum HTTPMethod: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case DELETE = "DELETE" case PATCH = "PATCH" } public enum RequestBody { case JSONBody(JSON) case DataBody(data : NSData, contentType : String) case EmptyBody } public enum ResponseDeserializer<Out> { case JSONResponse((NSHTTPURLResponse, JSON) -> Result<Out>) case DataResponse((NSHTTPURLResponse, NSData) -> Result<Out>) case NoContent(NSHTTPURLResponse -> Result<Out>) } public struct NetworkRequest<Out> { let method : HTTPMethod let path : String // Absolute URL or URL relative to the API base let requiresAuth : Bool let body : RequestBody let query: [String:JSON] let deserializer : ResponseDeserializer<Out> public init(method : HTTPMethod, path : String, requiresAuth : Bool = false, body : RequestBody = .EmptyBody, query : [String:JSON] = [:], deserializer : ResponseDeserializer<Out>) { self.method = method self.path = path self.requiresAuth = requiresAuth self.body = body self.query = query self.deserializer = deserializer } //Apparently swift doesn't allow a computed property in a struct func pageSize() -> Int? { if let pageSize = query["page_size"] { return pageSize.intValue } else { return nil } } } extension NetworkRequest: CustomDebugStringConvertible { public var debugDescription: String { return "\(_stdlib_getDemangledTypeName(self.dynamicType)) {\(method):\(path)}" } } public struct NetworkResult<Out> { public let request: NSURLRequest? public let response: NSHTTPURLResponse? public let data: Out? public let baseData : NSData? public let error: NSError? public init(request : NSURLRequest?, response : NSHTTPURLResponse?, data : Out?, baseData : NSData?, error : NSError?) { self.request = request self.response = response self.data = data self.error = error self.baseData = baseData } } public class NetworkTask : Removable { let request : Request private init(request : Request) { self.request = request } public func remove() { request.cancel() } } @objc public protocol AuthorizationHeaderProvider { var authorizationHeaders : [String:String] { get } } public class NetworkManager : NSObject { public typealias JSONInterceptor = (response : NSHTTPURLResponse, json : JSON) -> Result<JSON> private let authorizationHeaderProvider: AuthorizationHeaderProvider? private let baseURL : NSURL private let cache : ResponseCache private var jsonInterceptors : [JSONInterceptor] = [] public init(authorizationHeaderProvider: AuthorizationHeaderProvider? = nil, baseURL : NSURL, cache : ResponseCache) { self.authorizationHeaderProvider = authorizationHeaderProvider self.baseURL = baseURL self.cache = cache } /// Allows you to add a processing pass to any JSON response. /// Typically used to check for errors that can be sent by any request public func addJSONInterceptor(interceptor : (response : NSHTTPURLResponse, json : JSON) -> Result<JSON>) { jsonInterceptors.append(interceptor) } public func URLRequestWithRequest<Out>(request : NetworkRequest<Out>) -> Result<NSURLRequest> { return NSURL(string: request.path, relativeToURL: baseURL).toResult().flatMap { url -> Result<NSURLRequest> in let URLRequest = NSURLRequest(URL: url) if request.query.count == 0 { return Success(URLRequest) } var queryParams : [String:String] = [:] for (key, value) in request.query { if let stringValue = value.rawString(options : NSJSONWritingOptions()) { queryParams[key] = stringValue } } // Alamofire has a kind of contorted API where you can encode parameters over URLs // or through the POST body, but you can't do both at the same time. // // So first we encode the get parameters let (paramRequest, error) = ParameterEncoding.URL.encode(URLRequest, parameters: queryParams) if let error = error { return Failure(error) } else { return Success(paramRequest) } } .flatMap { URLRequest in let mutableURLRequest = URLRequest.mutableCopy() as! NSMutableURLRequest if request.requiresAuth { for (key, value) in self.authorizationHeaderProvider?.authorizationHeaders ?? [:] { mutableURLRequest.setValue(value, forHTTPHeaderField: key) } } mutableURLRequest.HTTPMethod = request.method.rawValue // Now we encode the body switch request.body { case .EmptyBody: return Success(mutableURLRequest) case let .DataBody(data: data, contentType: contentType): mutableURLRequest.HTTPBody = data mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") return Success(mutableURLRequest) case let .JSONBody(json): let (bodyRequest, error) = ParameterEncoding.JSON.encode(mutableURLRequest, parameters: json.dictionaryObject ?? [:]) if let error = error { return Failure(error) } else { return Success(bodyRequest) } } } } private static func deserialize<Out>(deserializer : ResponseDeserializer<Out>, interceptors : [JSONInterceptor], response : NSHTTPURLResponse?, data : NSData?) -> Result<Out> { if let response = response { switch deserializer { case let .JSONResponse(f): if let data = data, raw : AnyObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) { let json = JSON(raw) let result = interceptors.reduce(Success(json)) {(current : Result<JSON>, interceptor : (response : NSHTTPURLResponse, json : JSON) -> Result<JSON>) -> Result<JSON> in return current.flatMap {interceptor(response : response, json: $0)} } return result.flatMap { return f(response, $0) } } else { return Failure(NSError.oex_unknownError()) } case let .DataResponse(f): return data.toResult().flatMap { f(response, $0) } case let .NoContent(f): return f(response) } } else { return Failure() } } public func taskForRequest<Out>(request : NetworkRequest<Out>, handler: NetworkResult<Out> -> Void) -> Removable { let URLRequest = URLRequestWithRequest(request) let interceptors = jsonInterceptors let task = URLRequest.map {URLRequest -> NetworkTask in let task = Manager.sharedInstance.request(URLRequest) let serializer = { (URLRequest : NSURLRequest, response : NSHTTPURLResponse?, data : NSData?) -> (AnyObject?, NSError?) in let result = NetworkManager.deserialize(request.deserializer, interceptors: interceptors, response: response, data: data) return (Box((value : result.value, original : data)), result.error) } task.response(serializer: serializer) { (request, response, object, error) in let parsed = (object as? Box<(value : Out?, original : NSData?)>)?.value let result = NetworkResult<Out>(request: request, response: response, data: parsed?.value, baseData: parsed?.original, error: error) handler(result) } task.resume() return NetworkTask(request: task) } switch task { case let .Success(t): return t.value case let .Failure(error): dispatch_async(dispatch_get_main_queue()) { handler(NetworkResult(request: nil, response: nil, data: nil, baseData : nil, error: error)) } return BlockRemovable {} } } private func combineWithPersistentCacheFetch<Out>(stream : Stream<Out>, request : NetworkRequest<Out>) -> Stream<Out> { if let URLRequest = URLRequestWithRequest(request).value { let cacheStream = Sink<Out>() let interceptors = jsonInterceptors cache.fetchCacheEntryWithRequest(URLRequest, completion: {(entry : ResponseCacheEntry?) -> Void in if let entry = entry { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {[weak cacheStream] in let result = NetworkManager.deserialize(request.deserializer, interceptors: interceptors, response: entry.response, data: entry.data) dispatch_async(dispatch_get_main_queue()) {[weak cacheStream] in cacheStream?.close() cacheStream?.send(result) } }) } else { cacheStream.close() } }) return stream.cachedByStream(cacheStream) } else { return stream } } public func streamForRequest<Out>(request : NetworkRequest<Out>, persistResponse : Bool = false, autoCancel : Bool = true) -> Stream<Out> { let stream = Sink<NetworkResult<Out>>() let task = self.taskForRequest(request) {[weak stream, weak self] result in if let response = result.response, request = result.request where persistResponse { self?.cache.setCacheResponse(response, withData: result.baseData, forRequest: request, completion: nil) } stream?.close() stream?.send(result) } var result : Stream<Out> = stream.flatMap {(result : NetworkResult<Out>) -> Result<Out> in return result.data.toResult(result.error) } if persistResponse { result = combineWithPersistentCacheFetch(result, request: request) } if autoCancel { result = result.autoCancel(task) } return result } } extension NetworkManager { func addStandardInterceptors() { addJSONInterceptor { (response, json) -> Result<JSON> in if let statusCode = OEXHTTPStatusCode(rawValue: response.statusCode) where statusCode.is4xx { if json["has_access"].bool == false { let access = OEXCoursewareAccess(dictionary : json.dictionaryObject) return Failure(OEXCoursewareAccessError(coursewareAccess: access, displayInfo: nil)) } return Success(json) } else { return Success(json) } } } }
apache-2.0
760dae7b986be250c6de4a43a99abe10
37.409836
187
0.583525
5.218263
false
false
false
false
Virpik/T
src/UI/[UIColor]/[UIColor][T][Components].swift
1
766
// // [UIColor][T][Components].swift // T // // Created by Virpik on 19/02/2018. // import Foundation public extension UIColor { // public typealias RGBAComponents = UIColor.RGBAComponents } public extension UIColor { // public typealias RGBAComponents = UIColor.RGBAComponents public var rgbaComponents: RGBAComponents { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) return RGBAComponents(r: r, g: g, b: b, a: a) } public convenience init(_ components: RGBAComponents) { self.init(red: components.r, green: components.g, blue: components.b, alpha: components.a) } }
mit
139fb5f6e2186c76bea580d179a029f0
22.212121
98
0.605744
3.908163
false
false
false
false
sopinetchat/SopinetChat-iOS
Pod/Factories/SChatAvatarImageFactory.swift
1
6935
// // SChatAvatarImageFactory.swift // Pods // // Created by David Moreno Lora on 22/5/16. // // import Foundation public class SChatAvatarImageFactory: NSObject { // MARK: Public public static func avatarImageWithPlaceholder(placeholderImage: UIImage, diameter: UInt) -> SChatAvatarImage { let circlePlaceholderImage = SChatAvatarImageFactory.sChatCircularImage(placeholderImage, withDiameter: diameter, highlightedColor: nil) return SChatAvatarImage.avatarImageWithPlaceholder(circlePlaceholderImage) } public static func avatarImageWithImage(image: UIImage, diameter: UInt) -> SChatAvatarImage { let avatar = SChatAvatarImageFactory.circularAvatarImage(image, withDiameter: diameter) let highlightedAvatar = SChatAvatarImageFactory.circularAvatarHighlightedImage(image, withDiameter: diameter) return SChatAvatarImage(avatarImage: avatar, highlightedImage: highlightedAvatar, placeholderImage: avatar) } public static func circularAvatarImage(image: UIImage, withDiameter diameter: UInt) -> UIImage { return SChatAvatarImageFactory.sChatCircularImage(image, withDiameter: diameter, highlightedColor: nil) } public static func circularAvatarHighlightedImage(image: UIImage, withDiameter diameter: UInt) -> UIImage { return SChatAvatarImageFactory.sChatCircularImage(image, withDiameter: diameter, highlightedColor: UIColor(white: 0.1, alpha: 0.3)) } public static func avatarImageWithUserInitials(userInitials: String, backgroundColor: UIColor, textColor: UIColor, font: UIFont, diameter: UInt) -> SChatAvatarImage { let avatarImage = SChatAvatarImageFactory.sChatImageWithInitials(userInitials, backgroundColor: backgroundColor, textColor: textColor, font: font, diameter: diameter) let avatarHighlightedImage = SChatAvatarImageFactory.sChatCircularImage(avatarImage, withDiameter: diameter, highlightedColor: UIColor(white: 0.1, alpha: 0.3)) return SChatAvatarImage(avatarImage: avatarImage, highlightedImage: avatarHighlightedImage, placeholderImage: avatarHighlightedImage) } // MARK: Private private static func sChatImageWithInitials(initials: String, backgroundColor: UIColor, textColor: UIColor, font: UIFont, diameter: UInt) -> UIImage { assert(diameter > 0, "The diameter should be greater than 0 in sChatImageWithInitials function.") let frame = CGRectMake(0.0, 0.0, CGFloat(diameter), CGFloat(diameter)) let attributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor] let textFrame = (initials as! NSString).boundingRectWithSize(frame.size, options: [NSStringDrawingOptions.UsesLineFragmentOrigin, NSStringDrawingOptions.UsesFontLeading], attributes: attributes, context: nil) let frameMidPoint = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame)) let textFrameMidPoint = CGPointMake(CGRectGetMidX(textFrame), CGRectGetMidY(textFrame)) let dx: CGFloat = frameMidPoint.x - textFrameMidPoint.x let dy: CGFloat = frameMidPoint.y - textFrameMidPoint.y let drawPoint = CGPointMake(dx, dy) var image: UIImage? = nil UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.mainScreen().scale) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, backgroundColor.CGColor) CGContextFillRect(context, frame) (initials as! NSString).drawAtPoint(drawPoint, withAttributes: attributes) image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return SChatAvatarImageFactory.sChatCircularImage(image!, withDiameter: diameter, highlightedColor: nil) } private static func sChatCircularImage(image: UIImage?, withDiameter diameter: UInt, highlightedColor: UIColor?) -> UIImage { assert(image != nil, "The image is nil in sChatCircularImage function") assert(diameter > 0, "The diameter should be greater than 0 in sChatCircularImage") let frame = CGRectMake(0.0, 0.0, CGFloat(diameter), CGFloat(diameter)) var newImage: UIImage? = nil UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.mainScreen().scale) let context = UIGraphicsGetCurrentContext() let imgPath = UIBezierPath(ovalInRect: frame) imgPath.addClip() image?.drawInRect(frame) if let _highlightedColor = highlightedColor { CGContextSetFillColorWithColor(context, _highlightedColor.CGColor) CGContextFillEllipseInRect(context, frame) } newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } }
gpl-3.0
edd42eda04c25ec938f253871b4bbba6
45.864865
166
0.514636
7.90764
false
false
false
false
sudeepunnikrishnan/ios-sdk
Instamojo/Request.swift
1
24897
// // Request.swift // Instamojo // // Created by Sukanya Raj on 20/02/17. // Copyright © 2017 Sukanya Raj. All rights reserved. // import UIKit public class Request: NSObject { var order: Order? var mode: Mode var orderID: String? var accessToken: String? var card: Card? var virtualPaymentAddress: String? var upiSubmissionResponse: UPISubmissionResponse? var orderRequestCallBack: OrderRequestCallBack? var juspayRequestCallBack: JuspayRequestCallBack? var upiCallBack: UPICallBack? public enum Mode { case OrderCreate case FetchOrder case Juspay case UPISubmission case UPIStatusCheck } /** * Network Request to create an order ID from Instamojo server. * * @param order Order model with all the mandatory fields set. * @param orderRequestCallBack OrderRequestCallBack interface for the Asynchronous Network Call. */ public init(order: Order, orderRequestCallBack: OrderRequestCallBack) { self.mode = Mode.OrderCreate self.order = order self.orderRequestCallBack = orderRequestCallBack } /** * Network Request to get order details from Juspay for JuspaySafeBrowser. * * @param order Order model with all the mandatory fields set. * @param card Card with all the proper validations done. * @param jusPayRequestCallBack JusPayRequestCallBack for Asynchronous network call. */ public init(order: Order, card: Card, jusPayRequestCallBack: JuspayRequestCallBack) { self.mode = Mode.Juspay self.order = order self.card = card self.juspayRequestCallBack = jusPayRequestCallBack } /** * Network request for UPISubmission Submission * * @param order Order * @param virtualPaymentAddress String * @param upiCallback UPICallback */ public init(order: Order, virtualPaymentAddress: String, upiCallBack: UPICallBack) { self.mode = Mode.UPISubmission self.order = order self.virtualPaymentAddress = virtualPaymentAddress self.upiCallBack = upiCallBack } /** * Network Request to check the status of the transaction * * @param order Order * @param upiSubmissionResponse UPISubmissionResponse * @param upiCallback UPICallback */ init(order: Order, upiSubmissionResponse: UPISubmissionResponse, upiCallback: UPICallBack ) { self.mode = Mode.UPIStatusCheck self.order = order self.upiSubmissionResponse = upiSubmissionResponse self.upiCallBack = upiCallback } /** * Network request to fetch the order * @param accessToken String * @param orderID String * @param orderRequestCallBack OrderRequestCallBack */ public init(orderID: String, accessToken: String, orderRequestCallBack: OrderRequestCallBack ) { self.mode = Mode.FetchOrder self.orderID = orderID self.accessToken = accessToken self.orderRequestCallBack = orderRequestCallBack } public func execute() { switch self.mode { case Mode.OrderCreate: createOrder() break case Mode.FetchOrder: fetchOrder() break case Mode.Juspay: juspayRequest() break case Mode.UPISubmission: executeUPIRequest() break case Mode.UPIStatusCheck: upiStatusCheck() break } } func createOrder() { let url: String = Urls.getOrderCreateUrl() let params: [String: Any] = ["name": order!.buyerName!, "email": order!.buyerEmail!, "amount": order!.amount!, "description": order!.orderDescription!, "phone": order!.buyerPhone!, "currency": order!.currency!, "transaction_id": order!.transactionID!, "redirect_url": order!.redirectionUrl!, "advanced_payment_options": "true", "mode": order!.mode!, "webhook_url": order!.webhook!] let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "POST" request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted) request.addValue(getUserAgent(), forHTTPHeaderField: "User-Agent") request.addValue("Bearer " + order!.authToken!, forHTTPHeaderField: "Authorization") request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") let session = URLSession.shared let task = session.dataTask(with: request as URLRequest, completionHandler: {data, _, error -> Void in if error == nil { do { if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { if jsonResponse["payment_options"] != nil { //Payment Options Recieved self.updateTransactionDetails(jsonResponse: jsonResponse) self.orderRequestCallBack?.onFinish(order: self.order!, error: "") } else { if jsonResponse["error"] != nil { if let errorMessage = jsonResponse["error"] as? String { self.orderRequestCallBack?.onFinish(order: self.order!, error:errorMessage) } } else { if jsonResponse["success"] != nil { if let success = jsonResponse["success"] as? Bool { if !success { if let errorMessage = jsonResponse["message"] as? String { self.orderRequestCallBack?.onFinish(order: self.order!, error: errorMessage) } } } } else { self.orderRequestCallBack?.onFinish(order: self.order!, error: "Error while creating an order") } } } } } catch { Logger.logError(tag: "Caught Exception", message: String(describing: error)) self.orderRequestCallBack?.onFinish(order: self.order!, error: String(describing: error)) } } else { self.orderRequestCallBack?.onFinish(order: self.order!, error: "Error while creating an order") print(error!.localizedDescription) } }) task.resume() } func updateTransactionDetails(jsonResponse: [String:Any]) { //update order details let orders = jsonResponse["order"] as? [String:Any] self.order!.id = orders?["id"] as? String self.order!.transactionID = orders?["transaction_id"] as? String self.order!.resourceURI = orders?["resource_uri"] as? String //update payment_options let paymentOptions = jsonResponse["payment_options"] as? [String:Any] //card_options of this order if paymentOptions?["card_options"] != nil { let card_options = paymentOptions?["card_options"] as? [String:Any] let submissionData = card_options?["submission_data"] as? [String : Any] let merchandID = submissionData?["merchant_id"] as? String let orderID = submissionData?["order_id"] as? String let submission_url = card_options?["submission_url"] as? String let cardOptions = CardOptions(orderID: orderID!, url: submission_url!, merchantID: merchandID!) self.order!.cardOptions = cardOptions } //netbanking_options of this order if paymentOptions?["netbanking_options"] != nil { let netbanking_options = paymentOptions?["netbanking_options"] as? [String:Any] let submission_url = netbanking_options?["submission_url"] as? String if let choicesArray = netbanking_options?["choices"] as? [[String: Any]] { var choices = [NetBankingBanks]() for i in 0 ..< choicesArray.count { let bank_name = choicesArray[i]["name"] as? String let bank_code = choicesArray[i]["id"] as? String let netBanks = NetBankingBanks.init(bankName: bank_name!, bankCode: bank_code!) choices.append(netBanks) } if choices.count > 0 { self.order!.netBankingOptions = NetBankingOptions(url: submission_url!, banks: choices) } } } //emi_options of this order if paymentOptions?["emi_options"] != nil { let emi_options = paymentOptions?["emi_options"] as? [String: Any] let submission_url = emi_options?["submission_url"] as? String if let emi_list = emi_options?["emi_list"] as? [[String : Any]] { var emis = [EMIBank]() for i in 0 ..< emi_list.count { let bank_name = emi_list[i]["bank_name"] as? String let bank_code = emi_list[i]["bank_code"] as? String var rates = [Int: Int]() if let ratesRaw = emi_list[i]["rates"] as? [[String : Any]] { for j in 0 ..< ratesRaw.count { let tenure = ratesRaw[j]["tenure"] as? Int let interest = ratesRaw[j]["interest"] as? Int if let _ = tenure { if let _ = interest { rates.updateValue(interest!, forKey: tenure!) } } } let sortedRates = rates.sorted(by: { $0.0 < $1.0 }) if rates.count > 0 { let emiBank = EMIBank(bankName: bank_name!, bankCode: bank_code!, rate: sortedRates) emis.append(emiBank) } } } let submissionData = emi_options?["submission_data"] as? [String : Any] let merchantID = submissionData?["merchant_id"] as? String let orderID = submissionData?["order_id"] as? String if emis.count > 0 { self.order?.emiOptions = EMIOptions(merchantID: merchantID!, orderID: orderID!, url: submission_url!, emiBanks: emis) } } } //wallet_options of this order if paymentOptions?["wallet_options"] != nil { let wallet_options = paymentOptions?["wallet_options"] as? [String: Any] let submission_url = wallet_options?["submission_url"] as? String if let choicesArray = wallet_options?["choices"] as? [[String: Any]] { var wallets = [Wallet]() for i in 0 ..< choicesArray.count { let name = choicesArray[i]["name"] as? String let walletID = choicesArray[i]["id"] as! Int let walletImage = choicesArray[i]["image"] as? String wallets.append(Wallet(name: name!, imageUrl: walletImage!, walletID: walletID.stringValue)) Logger.logDebug(tag: "String value", message: walletID.stringValue) } if wallets.count > 0 { self.order?.walletOptions = WalletOptions(url: submission_url!, wallets: wallets) } } } //upi_options of this order if paymentOptions?["upi_options"] != nil { let upi_options = paymentOptions?["upi_options"] as? [String: Any] self.order?.upiOptions = UPIOptions(url: (upi_options?["submission_url"] as? String)!) } } func fetchOrder() { let url: String = Urls.getOrderFetchURL(orderID: self.orderID!) let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "GET" let session = URLSession.shared request.addValue(getUserAgent(), forHTTPHeaderField: "User-Agent") request.addValue("Bearer " + self.accessToken!, forHTTPHeaderField: "Authorization") let task = session.dataTask(with: request as URLRequest, completionHandler: {data, _, error -> Void in if error == nil { let response = String(data: data!, encoding: String.Encoding.utf8) as String! do { if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { self.parseOrder(response: jsonResponse) self.orderRequestCallBack?.onFinish(order: self.order!, error: "") }else{ self.orderRequestCallBack?.onFinish(order:Order.init(), error: response!) } } catch { self.orderRequestCallBack?.onFinish(order:Order.init(), error: response!) } } else { self.orderRequestCallBack?.onFinish(order: Order.init(), error: "Error while making Instamojo request ") print(error!.localizedDescription) } }) task.resume() } func parseOrder(response: [String : Any]) { let orderResponse = response["order"] as? [String : Any] let id = orderResponse?["id"] as? String ?? "" let transactionID = orderResponse?["transaction_id"] as? String ?? "" let name = orderResponse?["name"] as? String ?? "" let email = orderResponse?["email"] as? String ?? "" let phone = orderResponse?["phone"] as? String ?? "" let amount = orderResponse?["amount"] as? String ?? "" let description = orderResponse?["description"] as? String ?? "" let currency = orderResponse?["currency"] as? String ?? "" let redirect_url = orderResponse?["redirect_url"] as? String ?? "" let webhook_url = orderResponse?["webhook_url"] as? String ?? "" let resource_uri = orderResponse?["resource_uri"] as? String ?? "" self.order = Order.init(authToken: accessToken!, transactionID: transactionID, buyerName: name, buyerEmail: email, buyerPhone: phone, amount: amount, description: description, webhook: webhook_url) self.order?.redirectionUrl = redirect_url self.order?.currency = currency self.order?.resourceURI = resource_uri self.order?.id = id self.updateTransactionDetails(jsonResponse: response) } func juspayRequest() { Logger.logDebug(tag: "Juspay Request", message: "Juspay Request On Start") let url: String = self.order!.cardOptions.url let session = URLSession.shared var params = ["order_id": self.order!.cardOptions.orderID, "merchant_id": self.order!.cardOptions.merchantID, "payment_method_type": "Card", "card_number": self.card!.cardNumber, "name_on_card": self.card!.cardHolderName, "card_exp_month": self.card!.getExpiryMonth(), "card_exp_year": self.card!.getExpiryYear(), "card_security_code": self.card!.cvv, "save_to_locker": self.card!.savedCard ? "true" : "false", "redirect_after_payment": "true", "format": "json"] as [String : Any] if self.order!.emiOptions != nil && self.order!.emiOptions.selectedBankCode != nil { params.updateValue("true", forKey: "is_emi") params.updateValue(self.order!.emiOptions.selectedBankCode, forKey :"emi_bank") params.updateValue(self.order!.emiOptions.selectedTenure, forKey: "emi_tenure") } Logger.logDebug(tag: "Params", message: String(describing: params)) let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "POST" request.setBodyContent(parameters: params) request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTask(with: request as URLRequest, completionHandler: {data, _, error -> Void in Logger.logDebug(tag: "Juspay Request", message: "Network call completed") if error == nil { do { if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { Logger.logDebug(tag: "Juspay Request", message: String(describing: jsonResponse)) if jsonResponse["payment"] != nil { let payment = jsonResponse["payment"] as? [String : Any] let authentication = payment?["authentication"] as? [String : Any] let url = authentication?["url"] as? String let orderID = jsonResponse["order_id"] as? String let txn_id = jsonResponse["txn_id"] as? String let browserParams = BrowserParams() browserParams.url = url browserParams.orderId = orderID browserParams.clientId = self.order?.clientID browserParams.transactionId = txn_id browserParams.endUrlRegexes = Urls.getEndUrlRegex() self.juspayRequestCallBack?.onFinish(params: browserParams, error: "") } else { Logger.logDebug(tag: "Juspay Request", message: "Error on request") self.juspayRequestCallBack?.onFinish(params: BrowserParams.init(), error: "Error while making Instamojo request") } } } catch { let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) print("Error could not parse JSON: '\(String(describing: jsonStr))'") self.juspayRequestCallBack?.onFinish(params: BrowserParams.init(), error: "Error while making Instamojo request") Logger.logError(tag: "Caught Exception", message: String(describing: error)) } } else { self.juspayRequestCallBack?.onFinish(params: BrowserParams.init(), error: "Error while making Instamojo request") print(error!.localizedDescription) } }) task.resume() } func executeUPIRequest() { let url: String = self.order!.upiOptions.url let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "POST" let session = URLSession.shared let params = ["virtual_address": self.virtualPaymentAddress!] request.setBodyContent(parameters: params) request.addValue(getUserAgent(), forHTTPHeaderField: "User-Agent") request.addValue("Bearer " + order!.authToken!, forHTTPHeaderField: "Authorization") request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in if error == nil { do { if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { let upiSubmissionResponse = self.parseUPIResponse(response: jsonResponse) if upiSubmissionResponse.statusCode == Constants.FailedPayment { self.upiCallBack?.onSubmission(upiSubmissionResponse: UPISubmissionResponse.init(), exception: "Payment failed. Please try again.") } else { self.upiCallBack?.onSubmission(upiSubmissionResponse:upiSubmissionResponse, exception: "") } } } catch { self.upiCallBack?.onSubmission(upiSubmissionResponse: UPISubmissionResponse.init(), exception: "Error while making UPI Submission request. Please try again.") Logger.logError(tag: "Caught Exception", message: String(describing: error)) } } else { self.upiCallBack?.onSubmission(upiSubmissionResponse: UPISubmissionResponse.init(), exception: "Error while making UPI Submission request. Please try again.") print(error!.localizedDescription) } }) task.resume() } func parseUPIResponse(response: [String : Any]) -> UPISubmissionResponse { let paymentID = response["payment_id"] as? String let statusCode = response["status_code"] as? Int let payerVirtualAddress = response["payer_virtual_address"] as? String let statusCheckURL = response["status_check_url"] as? String let upiBank = response["upi_bank"] as? String let statusMessage = response["status_message"] as? String if var payeeVirtualAddress = response["payeeVirtualAddress"] as? String { if payeeVirtualAddress.isEmpty { payeeVirtualAddress = "" } } return UPISubmissionResponse.init(paymentID: paymentID!, statusCode: statusCode!, payerVirtualAddress: payerVirtualAddress!, payeeVirtualAddress: payerVirtualAddress!, statusCheckURL: statusCheckURL!, upiBank: upiBank!, statusMessage: statusMessage!) } func upiStatusCheck() { let url: String = self.upiSubmissionResponse!.statusCheckURL let request = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "GET" let session = URLSession.shared request.addValue(getUserAgent(), forHTTPHeaderField: "User-Agent") request.addValue("Bearer " + order!.authToken!, forHTTPHeaderField: "Authorization") let task = session.dataTask(with: request as URLRequest, completionHandler: {data, _, error -> Void in if error == nil { do { if let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { Logger.logDebug(tag: "UPI Status", message: String(describing: jsonResponse)) let statusCode = jsonResponse["status_code"] as? Int if statusCode == Constants.PendingPayment { self.upiCallBack?.onStatusCheckComplete(paymentComplete: false, status: statusCode!) } else if statusCode == Constants.FailedPayment { self.upiCallBack?.onStatusCheckComplete(paymentComplete: false, status: statusCode!) } else { self.upiCallBack?.onStatusCheckComplete(paymentComplete: true, status: statusCode!) } } } catch { self.upiCallBack?.onStatusCheckComplete(paymentComplete: false, status: Constants.PaymentError) Logger.logError(tag: "Caught Exception", message: String(describing: error)) } } else { self.upiCallBack?.onStatusCheckComplete(paymentComplete: false, status: Constants.PaymentError) print(error!.localizedDescription) } }) task.resume() } func getUserAgent() -> String { let versionName: String = (Bundle.main.infoDictionary?["CFBundleVersion"] as? String)! + ";" let versionCode: String = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String)! let appID = Bundle.main.bundleIdentifier! + ";" return "Instamojo IOS SDK;" + UIDevice.current.model + ";" + "Apple;" + UIDevice.current.systemVersion + ";" + appID + versionName + versionCode } } public extension NSMutableURLRequest { func setBodyContent(parameters: [String : Any]) { let parameterArray = parameters.map { (key, value) -> String in return "\(key)=\((value as AnyObject))" } httpBody = parameterArray.joined(separator: "&").data(using: String.Encoding.utf8) } } public extension Int { var stringValue: String { return "\(self)" } }
lgpl-3.0
fd8905b93f0d9ad3e8f6883d6fb3f4c9
48.692615
488
0.576719
5.175884
false
false
false
false
AlwaysRightInstitute/SwiftyHTTP
SwiftSockets/ActiveSocket.swift
1
12137
// // ActiveSocket.swift // SwiftSockets // // Created by Helge Hess on 6/11/14. // Copyright (c) 2014-2015 Always Right Institute. All rights reserved. // #if os(Linux) import Glibc #else import Darwin #endif import Dispatch public typealias ActiveSocketIPv4 = ActiveSocket<sockaddr_in> /** * Represents an active STREAM socket based on the standard Unix sockets * library. * * An active socket can be either a socket gained by calling accept on a * passive socket or by explicitly connecting one to an address (a client * socket). * Therefore an active socket has two addresses, the local and the remote one. * * There are three methods to perform a close, this is rooted in the fact that * a socket actually is full-duplex, it provides a send and a receive channel. * The stream-mode is updated according to what channels are open/closed. * Initially the socket is full-duplex and you cannot reopen a channel that was * shutdown. If you have shutdown both channels the socket can be considered * closed. * * Sample: * let socket = ActiveSocket<sockaddr_in>() * .onRead { * let (count, block) = $0.read() * if count < 1 { * print("EOF, or great error handling.") * return * } * print("Answer to ring,ring is: \(count) bytes: \(block)") * } * socket.connect(sockaddr_in(address:"127.0.0.1", port: 80)) * socket.write("Ring, ring!\r\n") */ public class ActiveSocket<T: SocketAddress>: Socket<T> { public var remoteAddress : T? = nil public var queue : dispatch_queue_t? = nil var readSource : dispatch_source_t? = nil var sendCount : Int = 0 var closeRequested : Bool = false var didCloseRead : Bool = false var readCB : ((ActiveSocket, Int) -> Void)? = nil // let the socket own the read buffer, what is the best buffer type? //var readBuffer : [CChar] = [CChar](count: 4096 + 2, repeatedValue: 42) var readBufferPtr = UnsafeMutablePointer<CChar>.alloc(4096 + 2) var readBufferSize : Int = 4096 { // available space, a bit more for '\0' didSet { if readBufferSize != oldValue { readBufferPtr.dealloc(oldValue + 2) readBufferPtr = UnsafeMutablePointer<CChar>.alloc(readBufferSize + 2) } } } public var isConnected : Bool { guard isValid else { return false } return remoteAddress != nil } /* init */ override public init(fd: FileDescriptor) { // required, otherwise the convenience one fails to compile super.init(fd: fd) } /* Still crashes Swift 2b3 compiler (when the method below is removed) public convenience init?() { self.init(type: SOCK_STREAM) // assumption is that we inherit this // though it should work right away? } */ public convenience init?(type: Int32 = sys_SOCK_STREAM) { // TODO: copy of Socket.init(type:), but required to compile. Not sure // what's going on with init inheritance here. Do I *have to* read the // manual??? let lfd = socket(T.domain, type, 0) guard lfd != -1 else { return nil } self.init(fd: FileDescriptor(lfd)) } public convenience init (fd: FileDescriptor, remoteAddress: T?, queue: dispatch_queue_t? = nil) { self.init(fd: fd) self.remoteAddress = remoteAddress self.queue = queue isSigPipeDisabled = fd.isValid // hm, hm? } deinit { readBufferPtr.dealloc(readBufferSize + 2) } /* close */ override public func close() { if debugClose { debugPrint("closing socket \(self)") } guard isValid else { // already closed if debugClose { debugPrint(" already closed.") } return } // always shutdown receiving end, should call shutdown() // TBD: not sure whether we have a locking issue here, can read&write // occur on different threads in GCD? if !didCloseRead { if debugClose { debugPrint(" stopping events ...") } stopEventHandler() // Seen this crash - if close() is called from within the readCB? readCB = nil // break potential cycles if debugClose { debugPrint(" shutdown read channel ...") } sysShutdown(fd.fd, sys_SHUT_RD); didCloseRead = true } if sendCount > 0 { if debugClose { debugPrint(" sends pending, requesting close ...") } closeRequested = true return } queue = nil // explicitly release, might be a good idea ;-) if debugClose { debugPrint(" super close.") } super.close() } /* connect */ public func connect(address: T, onConnect: ( ActiveSocket<T> ) -> Void) -> Bool { // FIXME: make connect() asynchronous via GCD guard !isConnected else { // TBD: could be tolerant if addresses match print("Socket is already connected \(self)") return false } guard fd.isValid else { return false } // Note: must be 'var' for ptr stuff, can't use let var addr = address let lfd = fd.fd let rc = withUnsafePointer(&addr) { ptr -> Int32 in let bptr = UnsafePointer<sockaddr>(ptr) // cast return sysConnect(lfd, bptr, socklen_t(addr.len)) //only returns block } guard rc == 0 else { print("Could not connect \(self) to \(addr)") return false } remoteAddress = addr onConnect(self) return true } /* read */ public func onRead(cb: ((ActiveSocket, Int) -> Void)?) -> Self { let hadCB = readCB != nil let hasNewCB = cb != nil if !hasNewCB && hadCB { stopEventHandler() } readCB = cb if hasNewCB && !hadCB { startEventHandler() } return self } // This doesn't work, can't override a stored property // Leaving this feature alone for now, doesn't have real-world importance // @lazy override var boundAddress: T? = getRawAddress() /* description */ override func descriptionAttributes() -> String { // must be in main class, override not available in extensions var s = super.descriptionAttributes() if remoteAddress != nil { s += " remote=\(remoteAddress!)" } return s } } extension ActiveSocket : OutputStreamType { // writing public func write(string: String) { string.withCString { (cstr: UnsafePointer<Int8>) -> Void in let len = Int(strlen(cstr)) if len > 0 { self.asyncWrite(cstr, length: len) } } } } public extension ActiveSocket { // writing // no let in extensions: let debugAsyncWrites = false var debugAsyncWrites : Bool { return false } public var canWrite : Bool { guard isValid else { assert(isValid, "Socket closed, can't do async writes anymore") return false } guard !closeRequested else { assert(!closeRequested, "Socket is being shutdown already!") return false } return true } public func write(data: dispatch_data_t) { sendCount += 1 if debugAsyncWrites { debugPrint("async send[\(data)]") } // in here we capture self, which I think is right. dispatch_write(fd.fd, data, queue!) { asyncData, error in if self.debugAsyncWrites { debugPrint("did send[\(self.sendCount)] data \(data) error \(error)") } self.sendCount = self.sendCount - 1 // -- fails? if self.sendCount == 0 && self.closeRequested { if self.debugAsyncWrites { debugPrint("closing after async write ...") } self.close() self.closeRequested = false } } } public func asyncWrite<T>(buffer: [T]) -> Bool { // While [T] seems to convert to ConstUnsafePointer<T>, this method // has the added benefit of being able to derive the buffer length guard canWrite else { return false } let writelen = buffer.count let bufsize = writelen * sizeof(T) guard bufsize > 0 else { // Nothing to write .. return true } if queue == nil { debugPrint("No queue set, using main queue") queue = dispatch_get_main_queue() } // the default destructor is supposed to copy the data. Not good, but // handling ownership is going to be messy #if os(Linux) let asyncData = dispatch_data_create(buffer, bufsize, queue!, nil) #else /* os(Darwin) */ // TBD guard let asyncData = dispatch_data_create(buffer, bufsize, queue!, nil) else { return false } #endif /* os(Darwin) */ write(asyncData) return true } public func asyncWrite<T>(buffer: UnsafePointer<T>, length:Int) -> Bool { // FIXME: can we remove this dupe of the [T] version? guard canWrite else { return false } let writelen = length let bufsize = writelen * sizeof(T) guard bufsize > 0 else { // Nothing to write .. return true } if queue == nil { debugPrint("No queue set, using main queue") queue = dispatch_get_main_queue() } // the default destructor is supposed to copy the data. Not good, but // handling ownership is going to be messy #if os(Linux) let asyncData = dispatch_data_create(buffer, bufsize, queue!, nil); #else /* os(Darwin) */ guard let asyncData = dispatch_data_create(buffer, bufsize, queue!, nil) else { return false } #endif /* os(Darwin) */ write(asyncData) return true } public func send<T>(buffer: [T], length: Int? = nil) -> Int { // var writeCount : Int = 0 let bufsize = length ?? buffer.count // this is funky let ( _, writeCount ) = fd.write(buffer, count: bufsize) return writeCount } } public extension ActiveSocket { // Reading // Note: Swift doesn't allow the readBuffer in here. public func read() -> ( size: Int, block: UnsafePointer<CChar>, error: Int32){ let bptr = UnsafePointer<CChar>(readBufferPtr) guard fd.isValid else { print("Called read() on closed socket \(self)") readBufferPtr[0] = 0 return ( -42, bptr, EBADF ) } var readCount: Int = 0 let bufsize = readBufferSize // FIXME: If I just close the Terminal which hosts telnet this continues // to read garbage from the server. Even with SIGPIPE off. readCount = sysRead(fd.fd, readBufferPtr, bufsize) guard readCount >= 0 else { readBufferPtr[0] = 0 return ( readCount, bptr, errno ) } readBufferPtr[readCount] = 0 // convenience return ( readCount, bptr, 0 ) } /* setup read event handler */ func stopEventHandler() { if readSource != nil { dispatch_source_cancel(readSource!) readSource = nil // abort()s if source is not resumed ... } } func startEventHandler() -> Bool { guard readSource == nil else { print("Read source already setup?") return true // already setup } /* do we have a queue? */ if queue == nil { debugPrint("No queue set, using main queue") queue = dispatch_get_main_queue() } /* setup GCD dispatch source */ readSource = dispatch_source_create( DISPATCH_SOURCE_TYPE_READ, UInt(fd.fd), // is this going to bite us? 0, queue! ) guard readSource != nil else { print("Could not create dispatch source for socket \(self)") return false } // TBD: do we create a retain cycle here (self vs self.readSource) readSource!.onEvent { [unowned self] _, readCount in if let cb = self.readCB { cb(self, Int(readCount)) } } /* actually start listening ... */ #if os(Linux) // TBD: what is the better way? dispatch_resume(unsafeBitCast(readSource!, dispatch_object_t.self)) #else /* os(Darwin) */ dispatch_resume(readSource!) #endif /* os(Darwin) */ return true } } public extension ActiveSocket { // ioctl var numberOfBytesAvailableForReading : Int? { return fd.numberOfBytesAvailableForReading } }
mit
26a9ae35af82e33aaac44a00fedee388
26.837156
83
0.613661
4.205475
false
false
false
false
saagarjha/iina
iina/JavascriptAPIUtils.swift
1
6645
// // JavascriptAPIUtils.swift // iina // // Created by Collider LI on 2/3/2019. // Copyright © 2019 lhc. All rights reserved. // import Foundation import JavaScriptCore fileprivate func searchBinary(_ file: String, in url: URL) -> URL? { let url = url.appendingPathComponent(file) return FileManager.default.fileExists(atPath: url.path) ? url : nil } fileprivate extension Process { var descriptionDict: [String: Any] { return [ "status": terminationStatus ] } } @objc protocol JavascriptAPIUtilsExportable: JSExport { func fileInPath(_ file: String) -> Bool func resolvePath(_ path: String) -> String? func exec(_ file: String, _ args: [String], _ cwd: JSValue?, _ stdoutHook_: JSValue?, _ stderrHook_: JSValue?) -> JSValue? func ask(_ title: String) -> Bool func prompt(_ title: String) -> String? func chooseFile(_ title: String, _ options: [String: Any]) -> Any } class JavascriptAPIUtils: JavascriptAPI, JavascriptAPIUtilsExportable { override func extraSetup() { context.evaluateScript(""" iina.utils.ERROR_BINARY_NOT_FOUND = -1; iina.utils.ERROR_RUNTIME = -2; """) } func fileInPath(_ file: String) -> Bool { guard permitted(to: .accessFileSystem) else { return false } if file.isEmpty { return false } if let _ = searchBinary(file, in: Utility.binariesURL) ?? searchBinary(file, in: Utility.exeDirURL) { return true } if let path = parsePath(file).path { return FileManager.default.fileExists(atPath: path) } return false } func resolvePath(_ path: String) -> String? { guard permitted(to: .accessFileSystem) else { return nil } return parsePath(path).path } func exec(_ file: String, _ args: [String], _ cwd: JSValue?, _ stdoutHook_: JSValue?, _ stderrHook_: JSValue?) -> JSValue? { guard permitted(to: .accessFileSystem) else { return nil } return createPromise { [unowned self] resolve, reject in var path = "" var args = args if !file.contains("/") { if let url = searchBinary(file, in: Utility.binariesURL) ?? searchBinary(file, in: Utility.exeDirURL) { // a binary included in IINA's bundle? path = url.absoluteString } else { // assume it's a system command path = "/bin/bash" args.insert(file, at: 0) args = ["-c", args.map { $0.replacingOccurrences(of: " ", with: "\\ ") .replacingOccurrences(of: "'", with: "\\'") .replacingOccurrences(of: "\"", with: "\\\"") }.joined(separator: " ")] } } else { // it should be an existing file if file.first == "/" { // an absolute path? path = file } else { path = parsePath(file).path ?? "" } // make sure the file exists guard FileManager.default.fileExists(atPath: path) else { reject.call(withArguments: [-1, "Cannot find the binary \(file)"]) return } } // If this binary belongs to the plugin but doesn't have exec permission, try fix it if !FileManager.default.isExecutableFile(atPath: path) && ( path.hasPrefix(self.pluginInstance.plugin.dataURL.path) || path.hasPrefix(self.pluginInstance.plugin.tmpURL.path)) { do { try FileManager.default.setAttributes([.posixPermissions: NSNumber(integerLiteral: 0o755)], ofItemAtPath: path) } catch { reject.call(withArguments: [-2, "The binary is not executable, and execute permission cannot be added"]) return } } let (stdout, stderr) = (Pipe(), Pipe()) let process = Process() process.environment = ["LC_ALL": "en_US.UTF-8"] process.launchPath = path process.arguments = args if let cwd = cwd, cwd.isString, let cwdPath = parsePath(cwd.toString()).path { process.currentDirectoryPath = cwdPath } process.standardOutput = stdout process.standardError = stderr var stdoutContent = "" var stderrContent = "" var stdoutHook: JSValue? var stderrHook: JSValue? if let hookVal = stdoutHook_, hookVal.isObject { stdoutHook = hookVal } if let hookVal = stderrHook_, hookVal.isObject { stderrHook = hookVal } stdout.fileHandleForReading.readabilityHandler = { file in guard let output = String(data: file.availableData, encoding: .utf8) else { return } stdoutContent += output stdoutHook?.call(withArguments: [output]) } stderr.fileHandleForReading.readabilityHandler = { file in guard let output = String(data: file.availableData, encoding: .utf8) else { return } stderrContent += output stderrHook?.call(withArguments: [output]) } process.launch() self.pluginInstance.queue.async { process.waitUntilExit() stderr.fileHandleForReading.readabilityHandler = nil stdout.fileHandleForReading.readabilityHandler = nil resolve.call(withArguments: [[ "status": process.terminationStatus, "stdout": stdoutContent, "stderr": stderrContent ] as [String: Any]]) } } } func ask(_ title: String) -> Bool { let panel = NSAlert() panel.messageText = title panel.addButton(withTitle: NSLocalizedString("general.ok", comment: "OK")) panel.addButton(withTitle: NSLocalizedString("general.cancel", comment: "Cancel")) return panel.runModal() == .alertFirstButtonReturn } func prompt(_ title: String) -> String? { let panel = NSAlert() panel.messageText = title let input = NSTextField(frame: NSRect(x: 0, y: 0, width: 240, height: 60)) input.lineBreakMode = .byWordWrapping input.usesSingleLineMode = false panel.accessoryView = input panel.addButton(withTitle: NSLocalizedString("general.ok", comment: "OK")) panel.addButton(withTitle: NSLocalizedString("general.cancel", comment: "Cancel")) panel.window.initialFirstResponder = input if panel.runModal() == .alertFirstButtonReturn { return input.stringValue } return nil } func chooseFile(_ title: String, _ options: [String: Any]) -> Any { let chooseDir = options["chooseDir"] as? Bool ?? false let allowedFileTypes = options["allowedFileTypes"] as? [String] return createPromise { resolve, reject in Utility.quickOpenPanel(title: title, chooseDir: chooseDir, allowedFileTypes: allowedFileTypes) { result in resolve.call(withArguments: [result.path]) } } } }
gpl-3.0
8fbb31271a19785497d8d0f9b5a42471
33.247423
126
0.631096
4.37393
false
false
false
false
OldBulls/swift-weibo
ZNWeibo/ZNWeibo/AppDelegate.swift
1
1809
// // AppDelegate.swift // ZNWeibo // // Created by 金宝和信 on 16/7/6. // Copyright © 2016年 zn. All rights reserved. // import UIKit import QorumLogs //第三方打印log @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var defaultViewController :UIViewController? { let isLogin = UserAccountViewModel.shareIntance.isLogin return isLogin ? WelcomeViewController() : MainViewController() } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. // QorumLogs.enabled = true // QorumLogs.test() //设置全局颜色 UITabBar.appearance().tintColor = UIColor.orangeColor() UINavigationBar.appearance().tintColor = UIColor.orangeColor() //创建window window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.rootViewController = defaultViewController window?.makeKeyAndVisible() return true } } //MARK: - 自定义全局Log func ZNLog<T>(message:T, fileName:String = #file, funcName:String = #function, lineNum:Int = #line) { #if DEBUG //添加flat标签步骤:点击项目-->Build Setting-->swfit flag-->点击箭头-->点击Debug添加--> -D DEBUG //lastPathComponent 获取字符串最后一个 "/"后面的字符串 var file = (fileName as NSString).lastPathComponent as NSString let index = file.rangeOfString(".") file = file.substringToIndex(index.location) print("\(file):\(funcName)(\(lineNum)行)-\(message)") #endif }
mit
cc872e5c7833c2f7bcc0293768189a90
25.061538
127
0.636364
4.881844
false
false
false
false
vornet/mapdoodle-ios
MapDoodle/Classes/PathDoodle.swift
1
1818
// // PathDoodle.swift // Pods // // Created by Vorn Mom on 8/2/16. // // import Foundation import MapKit public class PathDoodle : Doodle { public var id: String! public var points: [GeoPoint] var style: PathDoodleStyle var shouldRedraw: Bool = true var isBeingRemoved: Bool = false private var mapView: MKMapView! private var polyline: MKPolyline! init(style: PathDoodleStyle, points: [GeoPoint]) { self.style = style self.points = points } public func draw(context: DoodleContext) { if mapView == nil { mapView = context.mapView } if isBeingRemoved { return; } if polyline == nil || shouldRedraw { if polyline != nil { context.mapView.removeOverlay(polyline) } var coordinates = self.points.map({ geoPoint -> CLLocationCoordinate2D in CLLocationCoordinate2D(latitude: geoPoint.latitude, longitude: geoPoint.longitude)}) self.polyline = MKPolyline(coordinates: &coordinates, count: coordinates.count) context.mapView.addOverlay(self.polyline) } } public func remove() { if (isBeingRemoved) { return; } isBeingRemoved = true if polyline != nil && mapView != nil { mapView.removeOverlay(polyline); polyline = nil } } public var bounds: [GeoPoint] { get { return LocationUtil.getBounds(points) } } public func setupPolylineRenderer(polyline: MKPolyline) -> MKPolylineRenderer? { var polylineRenderer: MKPolylineRenderer? = nil if self.polyline === polyline { polylineRenderer = MKPolylineRenderer(overlay: polyline) polylineRenderer!.strokeColor = style.color polylineRenderer!.lineWidth = CGFloat(style.thickness / 2.5) } return polylineRenderer } }
mit
d450d3b9904046eacda40d469512cc16
21.7375
164
0.652365
4.349282
false
false
false
false
mohamede1945/quran-ios
Quran/PageBookmarkDataSource.swift
2
2143
// // PageBookmarkDataSource.swift // Quran // // Created by Mohamed Afifi on 11/1/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import Foundation import GenericDataSources class PageBookmarkDataSource: BaseBookmarkDataSource<PageBookmark, BookmarkTableViewCell> { let numberFormatter = NumberFormatter() override func ds_collectionView(_ collectionView: GeneralCollectionView, configure cell: BookmarkTableViewCell, with item: PageBookmark, at indexPath: IndexPath) { let ayah = Quran.startAyahForPage(item.page) let suraFormat = NSLocalizedString("quran_sura_title", tableName: "Android", comment: "") let suraName = Quran.nameForSura(ayah.sura) cell.iconImage.image = #imageLiteral(resourceName: "bookmark-filled").withRenderingMode(.alwaysTemplate) cell.iconImage.tintColor = .bookmark() cell.name.text = String(format: suraFormat, suraName) cell.descriptionLabel.text = item.creationDate.bookmarkTimeAgo() cell.startPage.text = numberFormatter.format(NSNumber(value: item.page)) } func reloadData() { DispatchQueue.default .promise2(execute: self.persistence.retrievePageBookmarks) .then(on: .main) { items -> Void in self.items = items self.ds_reusableViewDelegate?.ds_reloadSections(IndexSet(integer: 0), with: .automatic) }.cauterize(tag: "BookmarksPersistence.retrievePageBookmarks") } }
gpl-3.0
e755d0b5550f106250b69d69de35dd12
40.211538
112
0.678955
4.62851
false
false
false
false
iadmir/Signal-iOS
Signal/src/views/OWSAlerts.swift
1
2387
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation @objc class OWSAlerts: NSObject { let TAG = "[OWSAlerts]" /// Cleanup and present alert for no permissions public class func showNoMicrophonePermissionAlert() { let alertTitle = NSLocalizedString("CALL_AUDIO_PERMISSION_TITLE", comment:"Alert title when calling and permissions for microphone are missing") let alertMessage = NSLocalizedString("CALL_AUDIO_PERMISSION_MESSAGE", comment:"Alert message when calling and permissions for microphone are missing") let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) let dismissAction = UIAlertAction(title: CommonStrings.dismissButton, style: .cancel) let settingsString = NSLocalizedString("OPEN_SETTINGS_BUTTON", comment: "Button text which opens the settings app") let settingsAction = UIAlertAction(title: settingsString, style: .default) { _ in UIApplication.shared.openSystemSettings() } alertController.addAction(dismissAction) alertController.addAction(settingsAction) UIApplication.shared.frontmostViewController?.present(alertController, animated: true, completion: nil) } public class func showAlert(withTitle title: String) { self.showAlert(withTitle: title, message: nil, buttonTitle: nil) } public class func showAlert(withTitle title: String, message: String) { self.showAlert(withTitle: title, message: message, buttonTitle: nil) } public class func showAlert(withTitle title: String, message: String? = nil, buttonTitle: String? = nil) { assert(title.characters.count > 0) let actionTitle = (buttonTitle != nil ? buttonTitle : NSLocalizedString("OK", comment: "")) let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: nil)) UIApplication.shared.frontmostViewController?.present(alert, animated: true, completion: nil) } public class func cancelAction() -> UIAlertAction { let action = UIAlertAction(title: CommonStrings.cancelButton, style: .cancel) { _ in Logger.debug("Cancel item") // Do nothing. } return action } }
gpl-3.0
51876ec8032a64b06f4dd9524dba771f
45.803922
158
0.707164
5.025263
false
false
false
false
yzpniceboy/KeychainAccess
Lib/KeychainAccessTests/KeychainAccessTests.swift
6
27962
// // KeychainAccessTests.swift // KeychainAccessTests // // Created by kishikawa katsumi on 2014/12/24. // Copyright (c) 2014 kishikawa katsumi. All rights reserved. // import Foundation import XCTest import KeychainAccess class KeychainAccessTests: XCTestCase { override func setUp() { super.setUp() Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared").removeAll() Keychain(service: "Twitter").removeAll() Keychain(server: NSURL(string: "https://example.com")!, protocolType: .HTTPS).removeAll() Keychain().removeAll() } override func tearDown() { super.tearDown() } func locally(x: () -> ()) { x() } // MARK: func testGenericPassword() { locally { // Add Keychain items let keychain = Keychain(service: "Twitter") keychain.set("kishikawa_katsumi", key: "username") keychain.set("password_1234", key: "password") let username = keychain.get("username") XCTAssertEqual(username!, "kishikawa_katsumi") let password = keychain.get("password") XCTAssertEqual(password!, "password_1234") } locally { // Update Keychain items let keychain = Keychain(service: "Twitter") keychain.set("katsumi_kishikawa", key: "username") keychain.set("1234_password", key: "password") let username = keychain.get("username") XCTAssertEqual(username!, "katsumi_kishikawa") let password = keychain.get("password") XCTAssertEqual(password!, "1234_password") } locally { // Remove Keychain items let keychain = Keychain(service: "Twitter") keychain.remove("username") keychain.remove("password") XCTAssertNil(keychain.get("username")) XCTAssertNil(keychain.get("password")) } } func testGenericPasswordSubscripting() { locally { // Add Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = "kishikawa_katsumi" keychain["password"] = "password_1234" let username = keychain["username"] XCTAssertEqual(username!, "kishikawa_katsumi") let password = keychain["password"] XCTAssertEqual(password!, "password_1234") } locally { // Update Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = "katsumi_kishikawa" keychain["password"] = "1234_password" let username = keychain["username"] XCTAssertEqual(username!, "katsumi_kishikawa") let password = keychain["password"] XCTAssertEqual(password!, "1234_password") } locally { // Remove Keychain items let keychain = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared") keychain["username"] = nil keychain["password"] = nil XCTAssertNil(keychain["username"]) XCTAssertNil(keychain["password"]) } } // MARK: func testInternetPassword() { locally { // Add Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain.set("kishikawa_katsumi", key: "username") keychain.set("password_1234", key: "password") let username = keychain.get("username") XCTAssertEqual(username!, "kishikawa_katsumi") let password = keychain.get("password") XCTAssertEqual(password!, "password_1234") } locally { // Update Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain.set("katsumi_kishikawa", key: "username") keychain.set("1234_password", key: "password") let username = keychain.get("username") XCTAssertEqual(username!, "katsumi_kishikawa") let password = keychain.get("password") XCTAssertEqual(password!, "1234_password") } locally { // Remove Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain.remove("username") keychain.remove("password") XCTAssertNil(keychain.get("username")) XCTAssertNil(keychain.get("password")) } } func testInternetPasswordSubscripting() { locally { // Add Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = "kishikawa_katsumi" keychain["password"] = "password_1234" let username = keychain["username"] XCTAssertEqual(username!, "kishikawa_katsumi") let password = keychain["password"] XCTAssertEqual(password!, "password_1234") } locally { // Update Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = "katsumi_kishikawa" keychain["password"] = "1234_password" let username = keychain["username"] XCTAssertEqual(username!, "katsumi_kishikawa") let password = keychain["password"] XCTAssertEqual(password!, "1234_password") } locally { // Remove Keychain items let keychain = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS) keychain["username"] = nil keychain["password"] = nil XCTAssertNil(keychain["username"]) XCTAssertNil(keychain["password"]) } } // MARK: func testDefaultInitializer() { let keychain = Keychain() XCTAssertEqual(keychain.service, "") XCTAssertNil(keychain.accessGroup) } func testInitializerWithService() { let keychain = Keychain(service: "com.example.github-token") XCTAssertEqual(keychain.service, "com.example.github-token") XCTAssertNil(keychain.accessGroup) } func testInitializerWithAccessGroup() { let keychain = Keychain(accessGroup: "12ABCD3E4F.shared") XCTAssertEqual(keychain.service, "") XCTAssertEqual(keychain.accessGroup!, "12ABCD3E4F.shared") } func testInitializerWithServiceAndAccessGroup() { let keychain = Keychain(service: "com.example.github-token", accessGroup: "12ABCD3E4F.shared") XCTAssertEqual(keychain.service, "com.example.github-token") XCTAssertEqual(keychain.accessGroup!, "12ABCD3E4F.shared") } func testInitializerWithServer() { let URL = NSURL(string: "https://kishikawakatsumi.com")! let keychain = Keychain(server: URL, protocolType: .HTTPS) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.Default) } func testInitializerWithServerAndAuthenticationType() { let URL = NSURL(string: "https://kishikawakatsumi.com")! let keychain = Keychain(server: URL, protocolType: .HTTPS, authenticationType: .HTMLForm) XCTAssertEqual(keychain.server, URL) XCTAssertEqual(keychain.protocolType, ProtocolType.HTTPS) XCTAssertEqual(keychain.authenticationType, AuthenticationType.HTMLForm) } // MARK: func testContains() { let keychain = Keychain(service: "Twitter") XCTAssertFalse(keychain.contains("username"), "not stored username") XCTAssertFalse(keychain.contains("password"), "not stored password") keychain.set("kishikawakatsumi", key: "username") XCTAssertTrue(keychain.contains("username"), "stored username") XCTAssertFalse(keychain.contains("password"), "not stored password") keychain.set("password1234", key: "password") XCTAssertTrue(keychain.contains("username"), "stored username") XCTAssertTrue(keychain.contains("password"), "stored password") } // MARK: func testSetString() { let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain.get("username"), "not stored username") XCTAssertNil(keychain.get("password"), "not stored password") keychain.set("kishikawakatsumi", key: "username") XCTAssertEqual(keychain.get("username")!, "kishikawakatsumi", "stored username") XCTAssertNil(keychain.get("password"), "not stored password") keychain.set("password1234", key: "password") XCTAssertEqual(keychain.get("username")!, "kishikawakatsumi", "stored username") XCTAssertEqual(keychain.get("password")!, "password1234", "stored password") } func testSetData() { let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = NSJSONSerialization.dataWithJSONObject(JSONObject, options: nil, error: nil) let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain.getData("JSONData"), "not stored JSON data") keychain.set(JSONData!, key: "JSONData") XCTAssertEqual(keychain.getData("JSONData")!, JSONData!, "stored JSON data") } func testRemoveString() { let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain.get("username"), "not stored username") XCTAssertNil(keychain.get("password"), "not stored password") keychain.set("kishikawakatsumi", key: "username") XCTAssertEqual(keychain.get("username")!, "kishikawakatsumi", "stored username") keychain.set("password1234", key: "password") XCTAssertEqual(keychain.get("password")!, "password1234", "stored password") keychain.remove("username") XCTAssertNil(keychain.get("username"), "removed username") XCTAssertEqual(keychain.get("password")!, "password1234", "left password") keychain.remove("password") XCTAssertNil(keychain.get("username"), "removed username") XCTAssertNil(keychain.get("password"), "removed password") } func testRemoveData() { let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = NSJSONSerialization.dataWithJSONObject(JSONObject, options: nil, error: nil) let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain.getData("JSONData"), "not stored JSON data") keychain.set(JSONData!, key: "JSONData") XCTAssertEqual(keychain.getData("JSONData")!, JSONData!, "stored JSON data") keychain.remove("JSONData") XCTAssertNil(keychain.getData("JSONData"), "removed JSON data") } // MARK: func testSubscripting() { let keychain = Keychain(service: "Twitter") XCTAssertNil(keychain["username"], "not stored username") XCTAssertNil(keychain["password"], "not stored password") XCTAssertNil(keychain[string: "username"], "not stored username") XCTAssertNil(keychain[string: "password"], "not stored password") keychain["username"] = "kishikawakatsumi" XCTAssertEqual(keychain["username"]!, "kishikawakatsumi", "stored username") XCTAssertEqual(keychain[string: "username"]!, "kishikawakatsumi", "stored username") keychain["password"] = "password1234" XCTAssertEqual(keychain["password"]!, "password1234", "stored password") XCTAssertEqual(keychain[string: "password"]!, "password1234", "stored password") keychain["username"] = nil XCTAssertNil(keychain["username"], "removed username") XCTAssertEqual(keychain["password"]!, "password1234", "left password") XCTAssertNil(keychain[string: "username"], "removed username") XCTAssertEqual(keychain[string: "password"]!, "password1234", "left password") keychain["password"] = nil XCTAssertNil(keychain["username"], "removed username") XCTAssertNil(keychain["password"], "removed password") XCTAssertNil(keychain[string: "username"], "removed username") XCTAssertNil(keychain[string: "password"], "removed password") let JSONObject = ["username": "kishikawakatsumi", "password": "password1234"] let JSONData = NSJSONSerialization.dataWithJSONObject(JSONObject, options: nil, error: nil) XCTAssertNil(keychain[data:"JSONData"], "not stored JSON data") keychain[data: "JSONData"] = JSONData XCTAssertEqual(keychain[data:"JSONData"]!, JSONData!, "stored JSON data") } // MARK: #if os(iOS) func testErrorHandling() { if let error = Keychain(service: "Twitter", accessGroup: "12ABCD3E4F.shared").removeAll() { XCTAssertNil(error, "no error occurred") } if let error = Keychain(service: "Twitter").removeAll() { XCTAssertNil(error, "no error occurred") } if let error = Keychain(server: NSURL(string: "https://kishikawakatsumi.com")!, protocolType: .HTTPS).removeAll() { XCTAssertNil(error, "no error occurred") } if let error = Keychain().removeAll() { XCTAssertNil(error, "no error occurred") } locally { // Add Keychain items let keychain = Keychain(service: "Twitter") if let error = keychain.set("kishikawa_katsumi", key: "username") { XCTAssertNil(error, "no error occurred") } if let error = keychain.set("password_1234", key: "password") { XCTAssertNil(error, "no error occurred") } let username = keychain.getStringOrError("username") switch username { // enum case .Success: XCTAssertEqual(username.value!, "kishikawa_katsumi") case .Failure: XCTFail("unknown error occurred") } if let error = username.error { // error object XCTFail("unknown error occurred") } else { XCTAssertEqual(username.value!, "kishikawa_katsumi") } if username.succeeded { // check succeeded property XCTAssertEqual(username.value!, "kishikawa_katsumi") } else { XCTFail("unknown error occurred") } if username.failed { // failed property XCTFail("unknown error occurred") } else { XCTAssertEqual(username.value!, "kishikawa_katsumi") } let password = keychain.getStringOrError("password") switch password { // enum case .Success: XCTAssertEqual(password.value!, "password_1234") case .Failure: XCTFail("unknown error occurred") } if let error = password.error { // error object XCTFail("unknown error occurred") } else { XCTAssertEqual(password.value!, "password_1234") } if password.succeeded { // check succeeded property XCTAssertEqual(password.value!, "password_1234") } else { XCTFail("unknown error occurred") } if password.failed { // failed property XCTFail("unknown error occurred") } else { XCTAssertEqual(password.value!, "password_1234") } } locally { // Update Keychain items let keychain = Keychain(service: "Twitter") if let error = keychain.set("katsumi_kishikawa", key: "username") { XCTAssertNil(error, "no error occurred") } if let error = keychain.set("1234_password", key: "password") { XCTAssertNil(error, "no error occurred") } let username = keychain.getStringOrError("username") switch username { // enum case .Success: XCTAssertEqual(username.value!, "katsumi_kishikawa") case .Failure: XCTFail("unknown error occurred") } if let error = username.error { // error object XCTFail("unknown error occurred") } else { XCTAssertEqual(username.value!, "katsumi_kishikawa") } if username.succeeded { // check succeeded property XCTAssertEqual(username.value!, "katsumi_kishikawa") } else { XCTFail("unknown error occurred") } if username.failed { // failed property XCTFail("unknown error occurred") } else { XCTAssertEqual(username.value!, "katsumi_kishikawa") } let password = keychain.getStringOrError("password") switch password { // enum case .Success: XCTAssertEqual(password.value!, "1234_password") case .Failure: XCTFail("unknown error occurred") } if let error = password.error { // check error object XCTFail("unknown error occurred") } else { XCTAssertEqual(password.value!, "1234_password") } if password.succeeded { // check succeeded property XCTAssertEqual(password.value!, "1234_password") } else { XCTFail("unknown error occurred") } if password.failed { // check failed property XCTFail("unknown error occurred") } else { XCTAssertEqual(password.value!, "1234_password") } } locally { // Remove Keychain items let keychain = Keychain(service: "Twitter") if let error = keychain.remove("username") { XCTAssertNil(error, "no error occurred") } if let error = keychain.remove("password") { XCTAssertNil(error, "no error occurred") } XCTAssertNil(keychain.get("username")) XCTAssertNil(keychain.get("password")) } } #endif // MARK: func testSetStringWithCustomService() { let username_1 = "kishikawakatsumi" let password_1 = "password1234" let username_2 = "kishikawa_katsumi" let password_2 = "password_1234" let username_3 = "k_katsumi" let password_3 = "12341234" let service_1 = "" let service_2 = "com.kishikawakatsumi.KeychainAccess" let service_3 = "example.com" Keychain().removeAll() Keychain(service: service_1).removeAll() Keychain(service: service_2).removeAll() Keychain(service: service_3).removeAll() XCTAssertNil(Keychain().get("username"), "not stored username") XCTAssertNil(Keychain().get("password"), "not stored password") XCTAssertNil(Keychain(service: service_1).get("username"), "not stored username") XCTAssertNil(Keychain(service: service_1).get("password"), "not stored password") XCTAssertNil(Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(Keychain(service: service_3).get("username"), "not stored username") XCTAssertNil(Keychain(service: service_3).get("password"), "not stored password") Keychain().set(username_1, key: "username") XCTAssertEqual(Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertNil(Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(Keychain(service: service_3).get("username"), "not stored username") Keychain(service: service_1).set(username_1, key: "username") XCTAssertEqual(Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertNil(Keychain(service: service_2).get("username"), "not stored username") XCTAssertNil(Keychain(service: service_3).get("username"), "not stored username") Keychain(service: service_2).set(username_2, key: "username") XCTAssertEqual(Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_2).get("username")!, username_2, "stored username") XCTAssertNil(Keychain(service: service_3).get("username"), "not stored username") Keychain(service: service_3).set(username_3, key: "username") XCTAssertEqual(Keychain().get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_1).get("username")!, username_1, "stored username") XCTAssertEqual(Keychain(service: service_2).get("username")!, username_2, "stored username") XCTAssertEqual(Keychain(service: service_3).get("username")!, username_3, "stored username") Keychain().set(password_1, key: "password") XCTAssertEqual(Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertNil(Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(Keychain(service: service_3).get("password"), "not stored password") Keychain(service: service_1).set(password_1, key: "password") XCTAssertEqual(Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertNil(Keychain(service: service_2).get("password"), "not stored password") XCTAssertNil(Keychain(service: service_3).get("password"), "not stored password") Keychain(service: service_2).set(password_2, key: "password") XCTAssertEqual(Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_2).get("password")!, password_2, "stored password") XCTAssertNil(Keychain(service: service_3).get("password"), "not stored password") Keychain(service: service_3).set(password_3, key: "password") XCTAssertEqual(Keychain().get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_1).get("password")!, password_1, "stored password") XCTAssertEqual(Keychain(service: service_2).get("password")!, password_2, "stored password") XCTAssertEqual(Keychain(service: service_3).get("password")!, password_3, "stored password") Keychain().remove("username") XCTAssertNil(Keychain().get("username"), "removed username") XCTAssertNil(Keychain(service: service_1).get("username"), "removed username") XCTAssertEqual(Keychain(service: service_2).get("username")!, username_2, "left username") XCTAssertEqual(Keychain(service: service_3).get("username")!, username_3, "left username") Keychain(service: service_1).remove("username") XCTAssertNil(Keychain().get("username"), "removed username") XCTAssertNil(Keychain(service: service_1).get("username"), "removed username") XCTAssertEqual(Keychain(service: service_2).get("username")!, username_2, "left username") XCTAssertEqual(Keychain(service: service_3).get("username")!, username_3, "left username") Keychain(service: service_2).remove("username") XCTAssertNil(Keychain().get("username"), "removed username") XCTAssertNil(Keychain(service: service_1).get("username"), "removed username") XCTAssertNil(Keychain(service: service_2).get("username"), "removed username") XCTAssertEqual(Keychain(service: service_3).get("username")!, username_3, "left username") Keychain(service: service_3).remove("username") XCTAssertNil(Keychain().get("username"), "removed username") XCTAssertNil(Keychain(service: service_1).get("username"), "removed username") XCTAssertNil(Keychain(service: service_2).get("username"), "removed username") XCTAssertNil(Keychain(service: service_3).get("username"), "removed username") Keychain().remove("password") XCTAssertNil(Keychain().get("password"), "removed password") XCTAssertNil(Keychain(service: service_1).get("password"), "removed password") XCTAssertEqual(Keychain(service: service_2).get("password")!, password_2, "left password") XCTAssertEqual(Keychain(service: service_3).get("password")!, password_3, "left password") Keychain(service: service_1).remove("password") XCTAssertNil(Keychain().get("password"), "removed password") XCTAssertNil(Keychain(service: service_1).get("password"), "removed password") XCTAssertEqual(Keychain(service: service_2).get("password")!, password_2, "left password") XCTAssertEqual(Keychain(service: service_3).get("password")!, password_3, "left password") Keychain(service: service_2).remove("password") XCTAssertNil(Keychain().get("password"), "removed password") XCTAssertNil(Keychain(service: service_1).get("password"), "removed password") XCTAssertNil(Keychain(service: service_2).get("password"), "removed password") XCTAssertEqual(Keychain(service: service_3).get("password")!, password_3, "left password") Keychain(service: service_3).remove("password") XCTAssertNil(Keychain().get("password"), "removed password") XCTAssertNil(Keychain(service: service_2).get("password"), "removed password") XCTAssertNil(Keychain(service: service_2).get("password"), "removed password") XCTAssertNil(Keychain(service: service_2).get("password"), "removed password") } }
mit
d1c612796052e49d47b5ef88b88172cc
41.690076
123
0.594807
5.205138
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Toolbox/EventInfo/Model/EventLogItem.swift
1
1162
// // EventLogItem.swift // DereGuide // // Created by zzk on 2017/1/24. // Copyright © 2017年 zzk. All rights reserved. // import Foundation import SwiftyJSON class EventLogItem: NSObject { var date : String! var _storage: [Int: Int] subscript (border: Int) -> Int { return _storage[border] ?? 0 } /** * Instantiate the instance using the passed json values to set the properties values */ init?(fromJson json: JSON, borders: [Int]) { if json.isEmpty { return nil } _storage = [Int: Int]() date = json["date"].stringValue for border in [1, 2, 3] { _storage[border] = json[String(border)].intValue } for border in borders { _storage[border] = json[String(border)].intValue } super.init() // fix remote mismatching if borders.contains(40000) && _storage[40000] == 0 { _storage[40000] = json["50000"].intValue } else if borders.contains(50000) && _storage[50000] == 0 { _storage[50000] = json["40000"].intValue } } }
mit
f4478d4cd7ce7422d8989efa8b6f9ec0
24.195652
89
0.54616
4.095406
false
false
false
false
radubozga/Freedom
speech/Swift/Speech-gRPC-Streaming/Pods/ROGoogleTranslate/Source/ROGoogleTranslate.swift
1
3760
// // ROGoogleTranslate.swift // ROGoogleTranslate // // Created by Robin Oster on 20/10/16. // Copyright © 2016 prine.ch. All rights reserved. // import Foundation public struct ROGoogleTranslateParams { public init() { } public init(source:String, target:String, text:String) { self.source = source self.target = target self.text = text } public var source = "de" public var target = "en" public var text = "Ich glaube, du hast den Text zum Übersetzen vergessen" } /// Offers easier access to the Google Translate API open class ROGoogleTranslate { /// Store here the Google Translate API Key public var apiKey = "" /// /// Initial constructor /// public init() { } /// /// Translate a phrase from one language into another /// /// - parameter params: ROGoogleTranslate Struct contains all the needed parameters to translate with the Google Translate API /// - parameter callback: The translated string will be returned in the callback /// open func translate(params:ROGoogleTranslateParams, callback:@escaping (_ translatedText:String) -> ()) { guard apiKey != "" else { print("Warning: You should set the api key before calling the translate method.") return } if let urlEncodedText = params.text.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { if let url = URL(string: "https://www.googleapis.com/language/translate/v2?key=\(self.apiKey)&q=\(urlEncodedText)&source=\(params.source)&target=\(params.target)&format=text") { let httprequest = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in guard error == nil else { print("Something went wrong: \(error?.localizedDescription)") return } if let httpResponse = response as? HTTPURLResponse { guard httpResponse.statusCode == 200 else { print("Something went wrong: \(data)") return } do { // Pyramid of optional json retrieving. I know with SwiftyJSON it would be easier, but I didn't want to add an external library if let data = data { if let json = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary { if let jsonData = json["data"] as? [String : Any] { if let translations = jsonData["translations"] as? [NSDictionary] { if let translation = translations.first as? [String : Any] { if let translatedText = translation["translatedText"] as? String { callback(translatedText) } } } } } } } catch { print("Serialization failed: \(error.localizedDescription)") } } }) httprequest.resume() } } } }
apache-2.0
dbe9a94800686e477d829fb73950a0a7
38.145833
189
0.490154
5.899529
false
false
false
false
ngominhtrint/Twittient
Twittient/TimeAgo.swift
1
1439
// // TimeAgo.swift // Twittient // // Created by TriNgo on 3/25/16. // Copyright © 2016 TriNgo. All rights reserved. // import Foundation public func timeAgoSince(date: NSDate) -> String { let calendar = NSCalendar.currentCalendar() let now = NSDate() let unitFlags: NSCalendarUnit = [.Second, .Minute, .Hour, .Day, .WeekOfYear, .Month, .Year] let components = calendar.components(unitFlags, fromDate: date, toDate: now, options: []) if components.year >= 2 { return "\(components.year)y" } if components.year >= 1 { return "1y" } if components.month >= 2 { return "\(components.month)m" } if components.month >= 1 { return "1m" } if components.weekOfYear >= 2 { return "\(components.weekOfYear)w" } if components.weekOfYear >= 1 { return "1w" } if components.day >= 2 { return "\(components.day)d" } if components.day >= 1 { return "1d" } if components.hour >= 2 { return "\(components.hour)h" } if components.hour >= 1 { return "1h" } if components.minute >= 2 { return "\(components.minute)min" } if components.minute >= 1 { return "1min" } if components.second >= 3 { return "\(components.second)s" } return "now" }
apache-2.0
c7ec3735cc36f23c2dab97af79b5e3a7
18.173333
95
0.535466
3.928962
false
false
false
false
himadrisj/SiriPay
Client/SiriPay/SiriPay/SPOTPViewController.swift
1
2161
// // SPOTPViewController.swift // SiriPay // // Created by Jatin Arora on 10/09/16. // Copyright // import Foundation class SPOTPViewController : UIViewController { @IBOutlet weak var nextButton: UIBarButtonItem! var otpString: String? @IBOutlet weak var otpField: UITextField! override func viewDidLoad() { if (!UserDefaults.standard.bool(forKey: kDefaults_SignedIn)) { SPPaymentController.sharedInstance.requestOTPForSignIn(email: TEST_EMAIL, mobileNo: TEST_MOBILE) { (result, error) in } } } @IBAction func nextButtonTapped(_ sender: AnyObject) { SPPaymentController.sharedInstance.doSignIn(otp: otpField.text!) { (error) in if error == nil { UserDefaults.standard.set(true, forKey: kDefaults_SignedIn) UserDefaults.standard.synchronize() self.performSegue(withIdentifier: "SiriPaySegueIdentifier", sender: nil) } else { CTSOauthManager.readPasswordSigninOuthData(); print("Wrong OTP with error = \(error)") let alert = UIAlertController(title: "Wrong OTP", message:"Please try again", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } } } } extension SPOTPViewController : UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField.text?.characters.count == 3 { nextButton.isEnabled = true } return true } }
mit
e8946e3a5134496ebb4f2175f449896b
29.43662
139
0.536789
5.657068
false
false
false
false
peterlafferty/LuasLife
LuasLifeKit/GetLinesRequest.swift
1
2106
// // GetLinesRequest.swift // LuasLife // // Created by Peter Lafferty on 29/02/2016. // Copyright © 2016 Peter Lafferty. All rights reserved. // import Foundation import Alamofire import Decodable public struct URLs { fileprivate static let bundleIdentifier = "com.peterlafferty.LuasLifeKit" public static var getLines = URL(string: "http://localhost/index.php/lines")! public static var getRoutes = URL(string: "http://localhost/index.php/routes?line-id=1")! //public static var getRoutes = "https://data.dublinked.ie/cgi-bin/rtpi/routeinformation?format=json&operator=LUAS&routeid=RED" // swiftlint:disable:this line_length public static var getStops = URL(string: "http://localhost/index.php/stops?route-id=1")! public static var getRealTimeInfo = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid=LUAS21&routeid=RED&maxresults=100&operator=Luas" // swiftlint:disable:this line_length } /// This struct represents the lines on the Luas. public struct GetLinesRequest { let url: URL let completionHandler: (Result<[Line]>) -> Void /** Initialises the request with the url and completion handler - parameter url: the url to use - parameter completionHandler: a closure to call when the request has completed The current routes are: - Green - Red */ public init(url: URL = URLs.getLines, completionHandler: @escaping (Result<[Line]>) -> Void) { self.url = url self.completionHandler = completionHandler } public func start() { Alamofire.request(url).responseJSON { (response) -> Void in switch response.result { case .success(let data): do { let lines = try [Line].decode(data => "results") self.completionHandler(.success(lines)) } catch { self.completionHandler(.error(error)) } case .failure(let error): self.completionHandler(.error(error)) } } } }
mit
6dcde0d07d63f18833dc7e72804923ef
33.508197
196
0.64133
4.151874
false
false
false
false
a20251313/LTMorphingLabelDemo_formother
LTMorphingLabel/LTMorphingLabel+Burn.swift
1
7213
// // LTMorphingLabel+Burn.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2014 Lex Tang, http://LexTang.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the “Software”), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import QuartzCore extension LTMorphingLabel { func _burningImageForCharLimbo(charLimbo: LTCharacterLimbo, withProgress progress: CGFloat) -> (UIImage, CGRect) { let maskedHeight = charLimbo.rect.size.height * max(0.01, progress) let maskedSize = CGSizeMake( charLimbo.rect.size.width, maskedHeight) UIGraphicsBeginImageContextWithOptions(maskedSize, false, UIScreen.mainScreen().scale) let rect = CGRectMake(0, 0, charLimbo.rect.size.width, maskedHeight) String(charLimbo.char).drawInRect(rect, withAttributes: [ NSFontAttributeName: self.font, NSForegroundColorAttributeName: self.textColor ]) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); let newRect = CGRectMake( charLimbo.rect.origin.x, charLimbo.rect.origin.y, charLimbo.rect.size.width, maskedHeight) return (newImage, newRect) } func BurnLoad() { _startClosures["Burn\(LTMorphingPhaseStart)"] = { self.emitterView.removeAllEmit() } _progressClosures["Burn\(LTMorphingPhaseManipulateProgress)"] = { (index: Int, progress: Float, isNewChar: Bool) in if !isNewChar { return min(1.0, max(0.0, progress)) } let j = Float(sin(Float(index))) * 1.5 return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j)) } _effectClosures["Burn\(LTMorphingPhaseDisappear)"] = { (char:Character, index: Int, progress: Float) in return LTCharacterLimbo( char: char, rect: self._originRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: 0.0 ) } _effectClosures["Burn\(LTMorphingPhaseAppear)"] = { (char:Character, index: Int, progress: Float) in if char != " " { let rect = self._newRects[index] let emitterPosition = CGPointMake( rect.origin.x + rect.size.width / 2.0, CGFloat(progress) * rect.size.height / 1.6 + rect.origin.y * 1.4) self.emitterView.createEmitter("c\(index)", duration: self.morphingDuration) { (layer, cell) in layer.emitterSize = CGSizeMake(rect.size.width , 1) layer.renderMode = kCAEmitterLayerAdditive layer.emitterMode = kCAEmitterLayerOutline cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 200.0 cell.scaleSpeed = self.font.pointSize / 100.0 cell.birthRate = Float(self.font.pointSize) cell.contents = UIImage(named: "Fire")?.CGImage cell.emissionLongitude = 0 cell.emissionRange = CGFloat(M_PI_4) cell.alphaSpeed = -1.0 cell.yAcceleration = 10 cell.velocity = CGFloat(10 + Int(arc4random_uniform(3))) cell.velocityRange = 10 cell.spin = 0 cell.spinRange = 0 cell.lifetime = self.morphingDuration }.update { (layer, cell) in layer.emitterPosition = emitterPosition }.play() self.emitterView.createEmitter("s\(index)", duration: self.morphingDuration) { (layer, cell) in layer.emitterSize = CGSizeMake(rect.size.width , 10) layer.renderMode = kCAEmitterLayerUnordered layer.emitterMode = kCAEmitterLayerOutline cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 40.0 cell.scaleSpeed = self.font.pointSize / 100.0 cell.birthRate = Float(self.font.pointSize) / Float(arc4random_uniform(10) + 20) cell.contents = UIImage(named: "Smoke")?.CGImage cell.emissionLongitude = 0 cell.emissionRange = CGFloat(M_PI_4) cell.alphaSpeed = self.morphingDuration / -3.0 cell.yAcceleration = 10 cell.velocity = CGFloat(20 + Int(arc4random_uniform(15))) cell.velocityRange = 20 cell.spin = CGFloat(Float(arc4random_uniform(30)) / 10.0) cell.spinRange = 5 cell.lifetime = self.morphingDuration }.update { (layer, cell) in layer.emitterPosition = emitterPosition }.play() } return LTCharacterLimbo( char: char, rect: self._newRects[index], alpha: 1.0, size: self.font.pointSize, drawingProgress: CGFloat(progress) ) } _drawingClosures["Burn\(LTMorphingPhaseDraw)"] = { (charLimbo: LTCharacterLimbo) in if charLimbo.drawingProgress > 0.0 { let (charImage, rect) = self._burningImageForCharLimbo(charLimbo, withProgress: charLimbo.drawingProgress) charImage.drawInRect(rect) return true } return false } _skipFramesClosures["Burn\(LTMorphingPhaseSkipFrames)"] = { return 1 } } }
mit
a38182990e3b7167d76145bbc7a2bbdb
41.886905
122
0.555309
5.120824
false
false
false
false
zhangliangzhi/iosStudyBySwift
SavePassword/SavePassword/AddViewController.swift
1
6375
// // AddViewController.swift // SavePassword // // Created by ZhangLiangZhi on 2016/12/21. // Copyright © 2016年 xigk. All rights reserved. // import UIKit import CloudKit class AddViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate { @IBOutlet weak var localTitle: UILabel! @IBOutlet weak var localURL: UILabel! @IBOutlet weak var localNote: UILabel! @IBOutlet weak var localSave: UIButton! @IBOutlet weak var localCancle: UIButton! @IBOutlet weak var sortID: UITextField! @IBOutlet weak var tfTitle: UITextField! @IBOutlet weak var urltxt: UITextField! @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() sortID.delegate = self tfTitle.delegate = self urltxt.delegate = self textView.delegate = self self.title = NSLocalizedString("Add", comment: "") // 加监听 NotificationCenter.default.addObserver(self, selector: #selector(tvBegin), name: .UITextViewTextDidBeginEditing, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(tvEnd), name: .UITextViewTextDidEndEditing, object: nil) // init data urltxt.text = "www." initLocalize() textView.text = NSLocalizedString("Account", comment: "") + ": \n\n" + NSLocalizedString("Password", comment: "") + ":" initSortID() tfTitle.becomeFirstResponder() } func initSortID() { if arrData.count == 0 { sortID.text = String(1) }else { let lastID:Int64 = arrData[arrData.count-1]["ID"] as! Int64 sortID.text = String( lastID + 1) } } override func viewWillAppear(_ animated: Bool) { // initLocalize() } func initLocalize() { localTitle.text = NSLocalizedString("Title", comment: "") + ":" localURL.text = NSLocalizedString("URL", comment: "") + ":" localNote.text = NSLocalizedString("Note", comment: "") localCancle.setTitle(NSLocalizedString("Cancel", comment: ""), for: .normal) localSave.setTitle(NSLocalizedString("Save", comment: ""), for: .normal) sortID.placeholder = NSLocalizedString("Enter Sort ID", comment: "") tfTitle.placeholder = NSLocalizedString("Enter Title", comment: "") urltxt.placeholder = NSLocalizedString("Enter URL", comment: "") } func tvBegin() { // print("text view begin") } func tvEnd() { // print("text view end") } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == sortID { tfTitle.becomeFirstResponder() }else if textField == tfTitle { urltxt.becomeFirstResponder() }else if textField == urltxt { textView.becomeFirstResponder() }else{ } return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { // 延迟1毫秒 执行 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1 * NSEC_PER_SEC))/Double(1000*NSEC_PER_SEC) , execute: { self.textView.resignFirstResponder() }) } return true } // 保存数据 @IBAction func saveAction(_ sender: Any) { var id:String = sortID.text! var title:String = tfTitle.text! var url:String = urltxt.text! let spData:String = textView.text! id = id.trimmingCharacters(in: .whitespaces) title = title.trimmingCharacters(in: .whitespaces) url = url.trimmingCharacters(in: .whitespaces) // id 是否为空 if id == "" { self.view.makeToast(NSLocalizedString("IDnot", comment: ""), duration: 3.0, position: .center) initSortID() return } let iID = Int64(id) if iID == nil { self.view.makeToast(NSLocalizedString("IDnot", comment: ""), duration: 3.0, position: .center) initSortID() return } // id是否重复 // for i in 0..<arrData.count { // let getID = arrData[i].value(forKey: "ID") // let igetID:Int64 = getID as! Int64 // if iID == igetID { // self.view.makeToast(NSLocalizedString("IDre", comment: ""), duration: 3.0, position: .center) // return // } // } self.view.isUserInteractionEnabled = false let one = CKRecord(recordType: "SavePassword") one["ID"] = iID as CKRecordValue? one["title"] = title as CKRecordValue? one["url"] = url as CKRecordValue? one["spdata"] = spData as CKRecordValue? CKContainer.default().privateCloudDatabase.save(one) { (record:CKRecord?, err:Error?) in if err == nil { print("save sucess") // 保存成功 DispatchQueue.main.async { arrData.append(one) // self.view.makeToast(NSLocalizedString("savesucess", comment: ""), duration: 3.0, position: .center) self.navigationController!.popViewController(animated: true) } }else { // 保存不成功 print("save fail", err?.localizedDescription) DispatchQueue.main.async { self.view.isUserInteractionEnabled = true // 弹框网络不行 let alert = UIAlertController(title: "⚠️ iCloud ⚠️", message: err?.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "ok", style: .default, handler: { (action:UIAlertAction) in })) self.present(alert, animated: true, completion: nil) } } } } // 取消 @IBAction func cancleAction(_ sender: Any) { navigationController!.popViewController(animated: true) } }
mit
fc9562cd6e54bc3fbc29019a5bce7ce4
32.625668
143
0.558683
4.870643
false
false
false
false
huonw/swift
test/IRGen/function-target-features.swift
33
1785
// This test verifies that we produce target-cpu and target-features attributes // on functions. // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +avx | %FileCheck %s -check-prefix=AVX-FEATURE // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +avx512f -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +avx512er | %FileCheck %s -check-prefix=TWO-AVX // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-cpu -Xcc -Xclang -Xcc corei7 | %FileCheck %s -check-prefix=CORE-CPU // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-cpu -Xcc -Xclang -Xcc corei7 -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +avx | %FileCheck %s -check-prefix=CORE-CPU-AND-FEATURES // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-cpu -Xcc -Xclang -Xcc x86-64 | %FileCheck %s -check-prefix=X86-64-CPU // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -o - %s -Xcc -Xclang -Xcc -target-cpu -Xcc -Xclang -Xcc corei7-avx -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc -avx | %FileCheck %s -check-prefix=AVX-MINUS-FEATURE // REQUIRES: CPU=x86_64 func test() { } // AVX-FEATURE: "target-features"{{.*}}+avx // TWO-AVX: "target-features"= // TWO-AVX-DAG: +avx512er // TWO-AVX-DAG: +avx512f // CORE-CPU: "target-cpu"="corei7" // CORE-CPU-AND-FEATURES: "target-cpu"="corei7" "target-features"={{.*}}+avx // X86-64-CPU: "target-cpu"="x86-64" // AVX-MINUS-FEATURE: "target-features"={{.*}}-avx
apache-2.0
ccb4c0321963ccdc29db66940ec0b8f4
76.608696
253
0.705322
2.931034
false
true
false
false
abiaoLHB/LHBWeiBo-Swift
LHBWeibo/LHBWeibo/MainWibo/Compose/ComposeTextView.swift
1
1115
// // ComposeTextView.swift // LHBWeibo // // Created by LHB on 16/8/24. // Copyright © 2016年 LHB. All rights reserved. // import UIKit import SnapKit class ComposeTextView: UITextView { //MARK: - 懒加载属性 lazy var placeHolderLabel : UILabel = UILabel() //从xib加载写这个方法里也行 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } //写这个方法里也行 override func awakeFromNib() { addSubview(placeHolderLabel) placeHolderLabel.snp_makeConstraints { (make) in make.top.equalTo(5) make.left.equalTo(10) } placeHolderLabel.textColor = UIColor.lightGrayColor() placeHolderLabel.font = font placeHolderLabel.text = "分享新鲜事..." //设置内容的内边距 textContainerInset = UIEdgeInsets(top: 5, left: 8, bottom: 0, right: 8) } } //MARK: - 设置UI界面 extension ComposeTextView{ private func setupUI(){ font = UIFont.systemFontOfSize(17.0) } }
apache-2.0
577afd9c5ffdda1739f960c7129b327b
20.93617
79
0.603883
4.256198
false
false
false
false