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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ryanspillsbury90/HaleMeditates | ios/Hale Meditates/WebViewController.swift | 1 | 4169 |
//
// WebViewController.swift
//
// Created by Ryan Pillsbury on 7/5/15.
// Copyright (c) 2015 koait. All rights reserved.
//
import UIKit
import MediaPlayer
class WebViewController: UIViewController, UIWebViewDelegate, UIGestureRecognizerDelegate, UINavigationBarDelegate, ScrollViewListener {
var url: NSURL?
var request: NSURLRequest?
@IBOutlet weak var webView: WebView!
@IBOutlet weak var loaderView: UIActivityIndicatorView!
@IBOutlet weak var navBar: UINavigationBar!
var timer: NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
self.webView.delegate = self;
self.webView.scrollViewDelegate = self;
if (url != nil) {
request = NSURLRequest(URL: url!);
webView.loadRequest(request!);
}
let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
tapGesture.delegate = self;
self.webView.addGestureRecognizer(tapGesture);
let navitem = UINavigationItem();
let _ = UIButton(type: UIButtonType.Custom)
navBar.pushNavigationItem(navitem, animated: false);
self.navigationItem.title = "";
navBar.pushNavigationItem(self.navigationItem, animated: false);
navBar.tintColor = UIColor.blackColor();
navBar.delegate = self;
}
func handleTap(sender: UITapGestureRecognizer) {
timer?.invalidate();
showNavBar();
scheduleNavigationBarToHide();
}
func scrolled() {
self.hideNavBar();
}
func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool {
self.dismissViewControllerAnimated(true, completion: nil);
return false;
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if (otherGestureRecognizer is UITapGestureRecognizer) {
let tapRecognizer = (otherGestureRecognizer as! UITapGestureRecognizer)
}
return true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func webViewDidFinishLoad(webView: UIWebView) {
self.loaderView.stopAnimating();
scheduleNavigationBarToHide();
}
func scheduleNavigationBarToHide() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "hideNavBar:", userInfo: nil, repeats: false);
}
func hideNavBar(timer: NSTimer) {
self.hideNavBar();
}
func showNavBar() {
if (self.navBar.frame.origin.y < 0 ) {
UIView.animateWithDuration(0.4, animations: ({
self.navBar.frame = CGRectMake(0, 0, self.navBar.frame.width, self.navBar.frame.height)
}));
}
}
func hideNavBar() {
if (self.navBar.frame.origin.y >= 0 ) {
UIView.animateWithDuration(0.4, animations: ({
self.navBar.frame = CGRectMake(0, -self.navBar.frame.height, self.navBar.frame.width, self.navBar.frame.height)
}));
}
}
func webViewDidStartLoad(webView: UIWebView) {
loaderView.startAnimating();
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
protocol ScrollViewListener {
// func startedScrolling(to: CGFloat, from: CGFloat);
func scrolled()
}
class WebView: UIWebView {
var lastOffSetY: CGFloat = 0;
var scrollViewDelegate: ScrollViewListener?
override func scrollViewDidScroll(scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView);
self.scrollViewDelegate?.scrolled();
}
} | mit | 1d33f5a5960fd785d93fcc6ee3963b94 | 30.353383 | 172 | 0.651235 | 5.178882 | false | false | false | false |
OpenMindBR/swift-diversidade-app | Diversidade/CentersViewController.swift | 1 | 5590 | //
// CentersViewController.swift
// Diversidade
//
// Created by Francisco José A. C. Souza on 24/02/16.
// Copyright © 2016 Francisco José A. C. Souza. All rights reserved.
//
import UIKit
import MapKit
import Alamofire
import SwiftyJSON
class CentersViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var menuItem: UIBarButtonItem!
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
let searchRadius = 1000
var nucleos:[Nucleo]?
override func viewDidLoad() {
super.viewDidLoad()
self.configureSideMenu(self.menuItem)
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.requestWhenInUseAuthorization()
mapView.showsUserLocation = true
mapView.showsCompass = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool) {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
if let placemark = placemarks?.first,
let state = placemark.administrativeArea {
self.fetchPlacesForRegion(state)
}
})
let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 6000, 6000)
mapView.setRegion(region, animated: true)
locationManager.stopUpdatingLocation()
locationManager.stopMonitoringSignificantLocationChanges()
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? PlaceAnnotation {
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView {
dequeedView.annotation = annotation
view = dequeedView
}
else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
let button = UIButton(type: .DetailDisclosure)
button.addTarget(self, action: #selector(CentersViewController.onDisclosureButtonTap(_:)), forControlEvents: .TouchUpInside)
button.tag = Int(annotation.placeId)!
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.pinTintColor = UIColor(red: 155.0/255, green: 47.0/255, blue: 245.0/255, alpha: 1.0)
view.rightCalloutAccessoryView = button as UIView
}
return view
}
return nil
}
func fetchPlacesForRegion(region: String){
let requestUrl = UrlFormatter.urlForCentersWithState(region)
Alamofire.request(.GET, requestUrl).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json: Array<JSON> = JSON(value).arrayValue
let places = json.map({ (nucleo) -> PlaceAnnotation in
let id = nucleo["id"].stringValue
let name = nucleo["name"].stringValue
let address = nucleo["address"].stringValue
let latitude = nucleo["latitude"].doubleValue
let longitude = nucleo["longitude"].doubleValue
let coord = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
return PlaceAnnotation(placeId: id, placeName: name, placeAddress: address, coordinate: coord)
})
self.mapView.addAnnotations(places)
}
case .Failure(let error):
print(error)
}
}
}
func onDisclosureButtonTap(sender: UIButton) {
performSegueWithIdentifier("toDetalheNucleo", sender: sender.tag)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let viewController = segue.destinationViewController as? DetailCenterViewController {
viewController.centerId = sender as? Int
}
}
}
| mit | 1938e9c42728c7975de683d7cb8a4761 | 35.756579 | 140 | 0.593879 | 6.242458 | false | false | false | false |
mleiv/SerializableData | SerializableDataDemo/SerializableDataDemo/Core Data/SimpleSerializedCoreDataStorable.swift | 1 | 11464 | //
// CoreDataStorable.swift
//
// Copyright 2017 Emily Ivie
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
import CoreData
public protocol SimpleSerializedCoreDataStorable: SerializedDataStorable, SerializedDataRetrievable {
// MARK: Required
/// Type of the core data entity.
associatedtype EntityType: NSManagedObject
/// Alters the predicate to retrieve only the row equal to this object.
func setIdentifyingPredicate(
fetchRequest: NSFetchRequest<EntityType>
)
/// Sets core data values to match struct values (specific).
func setAdditionalColumnsOnSave(
coreItem: EntityType
)
/// Initializes value type from core data object with serialized data.
init?(coreItem: EntityType)
// MARK: Optional
/// A reference to the current core data manager.
static var defaultManager: SimpleSerializedCoreDataManageable { get }
/// Returns the CoreData row that is equal to this object.
func entity(context: NSManagedObjectContext?) -> EntityType?
/// String description of EntityType.
static var entityName: String { get }
/// String description of serialized data column in entity
static var serializedDataKey: String { get }
/// Sets core data values to match struct values (general).
///
/// DON'T OVERRIDE.
func setColumnsOnSave(
coreItem: EntityType
)
/// Gets the struct to match the core data request.
static func get(
with manager: SimpleSerializedCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Self?
/// Gets the struct to match the core data request.
static func getCount(
with manager: SimpleSerializedCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Int
/// Gets all structs that match the core data request.
static func getAll(
with manager: SimpleSerializedCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> [Self]
/// Saves the struct to core data.
mutating func save(
with manager: SimpleSerializedCoreDataManageable?
) -> Bool
/// Saves all the structs to core data.
static func saveAll(
items: [Self],
with manager: SimpleSerializedCoreDataManageable?
) -> Bool
/// Deletes the struct's core data equivalent.
mutating func delete(
with manager: SimpleSerializedCoreDataManageable?
) -> Bool
/// Deletes all rows that match the core data request.
static func deleteAll(
with manager: SimpleSerializedCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Bool
}
extension SimpleSerializedCoreDataStorable {
/// The closure type for editing fetch requests.
public typealias AlterFetchRequest<T: NSManagedObject> = ((NSFetchRequest<T>) -> Void)
/// Convenience - get the static version for easy instance reference.
public var defaultManager: SimpleSerializedCoreDataManageable {
return Self.defaultManager
}
/// (Protocol default)
/// Returns the CoreData row that is equal to this object.
public func entity(context: NSManagedObjectContext?) -> EntityType? {
let manager = type(of: defaultManager).init(context: context)
return manager.getObject(item: self)
}
/// (Protocol default)
/// String description of EntityType
public static var entityName: String { return EntityType.description() }
/// (Protocol default)
/// String description of serialized data column in entity
public static var serializedDataKey: String { return "serializedData" }
/// (Protocol default)
/// Initializes value type from core data object with serialized data.
public init?(coreItem: EntityType) {
// Warning: make sure parent runs this in the correct context/thread for this entity
if let serializedData = coreItem.value(forKey: Self.serializedDataKey) as? Data {
self.init(serializedData: serializedData)
return
}
return nil
}
/// Sets core data values to match struct values (general).
///
/// DON'T OVERRIDE.
public func setColumnsOnSave(
coreItem: EntityType
) {
coreItem.setValue(self.serializedData, forKey: Self.serializedDataKey)
setAdditionalColumnsOnSave(coreItem: coreItem)
}
/// (Protocol default)
/// Gets the struct to match the core data request.
public static func get(
with manager: SimpleSerializedCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Self? {
return _get(with: manager, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of get:manager:AlterFetchRequest<EntityType> (manager not required).
public static func get(
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Self? {
return get(with: nil, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of get:manager:AlterFetchRequest<EntityType> (no parameters required).
public static func get(
with manager: SimpleSerializedCoreDataManageable? = nil
) -> Self? {
return get(with: manager) { _ in }
}
/// Root version of get:manager:AlterFetchRequest<EntityType> (you can still call this if you override that).
///
/// DO NOT OVERRIDE.
internal static func _get(
with manager: SimpleSerializedCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Self? {
let manager = manager ?? defaultManager
let one: Self? = manager.getValue(alterFetchRequest: alterFetchRequest)
return one
}
/// (Protocol default)
/// Gets the struct to match the core data request.
public static func getCount(
with manager: SimpleSerializedCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Int {
let manager = manager ?? defaultManager
return manager.getCount(alterFetchRequest: alterFetchRequest)
}
/// Convenience version of getCount:manager:AlterFetchRequest<EntityType> (manager not required).
public static func getCount(
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Int {
return getCount(with: nil, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of getCount:manager:AlterFetchRequest<EntityType> (AlterFetchRequest<EntityType> not required).
public static func getCount(
with manager: SimpleSerializedCoreDataManageable?
) -> Int {
return getCount(with: manager, alterFetchRequest: { _ in })
}
/// Convenience version of getCount:manager:AlterFetchRequest<EntityType> (no parameters required).
public static func getCount() -> Int {
return getCount(with: nil) { (fetchRequest: NSFetchRequest<EntityType>) in }
}
/// (Protocol default)
/// Gets all structs that match the core data request.
public static func getAll(
with manager: SimpleSerializedCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> [Self] {
return _getAll(with: manager, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of getAll:manager:AlterFetchRequest<EntityType> (manager not required).
public static func getAll(
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> [Self] {
return getAll(with: nil, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of getAll:manager:AlterFetchRequest<EntityType> (no parameters required).
public static func getAll(
with manager: SimpleSerializedCoreDataManageable? = nil
) -> [Self] {
return getAll(with: manager) { _ in }
}
/// Root version of getAll:manager:AlterFetchRequest<EntityType> (you can still call this if you override that).
///
/// DO NOT OVERRIDE.
internal static func _getAll(
with manager: SimpleSerializedCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> [Self] {
let manager = manager ?? defaultManager
let all: [Self] = manager.getAllValues(alterFetchRequest: alterFetchRequest)
return all
}
/// (Protocol default)
/// Saves the struct to core data.
public mutating func save(
with manager: SimpleSerializedCoreDataManageable?
) -> Bool {
let manager = manager ?? defaultManager
let isSaved = manager.saveValue(item: self)
return isSaved
}
/// Convenience version of save:manager (no parameters required).
public mutating func save() -> Bool {
return save(with: nil)
}
/// (Protocol default)
/// Saves all the structs to core data.
public static func saveAll(
items: [Self],
with manager: SimpleSerializedCoreDataManageable?
) -> Bool {
guard !items.isEmpty else { return true }
let manager = manager ?? defaultManager
let isSaved = manager.saveAllValues(items: items)
return isSaved
}
/// Convenience version of saveAll:items:manager (manager not required).
public static func saveAll(
items: [Self]
) -> Bool {
return saveAll(items: items, with: nil)
}
/// (Protocol default)
/// Deletes the struct's core data equivalent.
public mutating func delete(
with manager: SimpleSerializedCoreDataManageable?
) -> Bool {
let manager = manager ?? defaultManager
let isDeleted = manager.deleteValue(item: self)
return isDeleted
}
/// Convenience version of delete:manager (no parameters required).
public mutating func delete() -> Bool {
return delete(with: nil)
}
/// (Protocol default)
/// Deletes all rows that match the core data request.
public static func deleteAll(
with manager: SimpleSerializedCoreDataManageable?,
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Bool {
let manager = manager ?? defaultManager
let isDeleted = manager.deleteAll(alterFetchRequest: alterFetchRequest)
return isDeleted
}
/// Convenience version of deleteAll:manager:AlterFetchRequest<EntityType> (manager not required).
public static func deleteAll(
alterFetchRequest: @escaping AlterFetchRequest<EntityType>
) -> Bool {
return deleteAll(with: nil, alterFetchRequest: alterFetchRequest)
}
/// Convenience version of deleteAll:manager:AlterFetchRequest<EntityType> (AlterFetchRequest<EntityType> not required).
public static func deleteAll(
with manager: SimpleSerializedCoreDataManageable?
) -> Bool {
return deleteAll(with: manager) { _ in }
}
/// Convenience version of deleteAll:manager:AlterFetchRequest<EntityType> (no parameters required).
public static func deleteAll() -> Bool {
return deleteAll(with: nil) { _ in }
}
}
| mit | 9ab94838f736a603504b2211c980e7e4 | 35.164038 | 124 | 0.674546 | 5.498321 | false | false | false | false |
alexaubry/BulletinBoard | Sources/Support/Views/Internal/BulletinBackgroundView.swift | 1 | 3233 | /**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/**
* The view to display behind the bulletin.
*/
class BulletinBackgroundView: UIView {
let style: BLTNBackgroundViewStyle
// MARK: - Content View
enum ContentView {
case dim(UIView, CGFloat)
case blur(UIVisualEffectView, UIBlurEffect)
var instance: UIView {
switch self {
case .dim(let dimmingView, _):
return dimmingView
case .blur(let blurView, _):
return blurView
}
}
}
private(set) var contentView: ContentView!
// MARK: - Initialization
init(style: BLTNBackgroundViewStyle) {
self.style = style
super.init(frame: .zero)
initialize()
}
override init(frame: CGRect) {
style = .dimmed
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
style = .dimmed
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
translatesAutoresizingMaskIntoConstraints = false
func makeDimmingView() -> UIView {
let dimmingView = UIView()
dimmingView.alpha = 0.0
dimmingView.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
dimmingView.translatesAutoresizingMaskIntoConstraints = false
return dimmingView
}
switch style.rawValue {
case .none:
let dimmingView = makeDimmingView()
addSubview(dimmingView)
contentView = .dim(dimmingView, 0.0)
case .dimmed:
let dimmingView = makeDimmingView()
addSubview(dimmingView)
contentView = .dim(dimmingView, 1.0)
case .blurred(let blurredBackground, _):
let blurEffect = UIBlurEffect(style: blurredBackground)
let blurEffectView = UIVisualEffectView(effect: nil)
blurEffectView.translatesAutoresizingMaskIntoConstraints = false
addSubview(blurEffectView)
contentView = .blur(blurEffectView, blurEffect)
}
let contentViewInstance = contentView.instance
contentViewInstance.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
contentViewInstance.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
contentViewInstance.topAnchor.constraint(equalTo: topAnchor).isActive = true
contentViewInstance.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
// MARK: - Interactions
/// Shows the background view. Animatable.
func show() {
switch contentView! {
case .dim(let dimmingView, let maxAlpha):
dimmingView.alpha = maxAlpha
case .blur(let blurView, let blurEffect):
blurView.effect = blurEffect
}
}
/// Hides the background view. Animatable.
func hide() {
switch contentView! {
case .dim(let dimmingView, _):
dimmingView.alpha = 0
case .blur(let blurView, _):
blurView.effect = nil
}
}
}
| mit | ff34172e9de45547590c5c67dd65838c | 23.126866 | 94 | 0.606867 | 5.406355 | false | false | false | false |
visenze/visearch-sdk-swift | ViSearchSDK/Carthage/Checkouts/visenze-tracking-swift/ViSenzeAnalytics/ViSenzeAnalytics/Classes/Request/VaDeviceData.swift | 1 | 9443 | //
// VaDeviceData.swift
// ViSenzeAnalytics
//
// Created by Hung on 9/9/20.
// Copyright © 2020 ViSenze. All rights reserved.
//
import UIKit
// https://stackoverflow.com/questions/26028918/how-to-determine-the-current-iphone-device-model
public extension UIDevice {
static let modelName: String = {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity
#if os(iOS)
switch identifier {
case "iPod5,1": return "iPod touch (5th generation)"
case "iPod7,1": return "iPod touch (6th generation)"
case "iPod9,1": return "iPod touch (7th generation)"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone10,1", "iPhone10,4": return "iPhone 8"
case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3", "iPhone10,6": return "iPhone X"
case "iPhone11,2": return "iPhone XS"
case "iPhone11,4", "iPhone11,6": return "iPhone XS Max"
case "iPhone11,8": return "iPhone XR"
case "iPhone12,1": return "iPhone 11"
case "iPhone12,3": return "iPhone 11 Pro"
case "iPhone12,5": return "iPhone 11 Pro Max"
case "iPhone12,8": return "iPhone SE (2nd generation)"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad (3rd generation)"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad (4th generation)"
case "iPad6,11", "iPad6,12": return "iPad (5th generation)"
case "iPad7,5", "iPad7,6": return "iPad (6th generation)"
case "iPad7,11", "iPad7,12": return "iPad (7th generation)"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad11,4", "iPad11,5": return "iPad Air (3rd generation)"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad mini 3"
case "iPad5,1", "iPad5,2": return "iPad mini 4"
case "iPad11,1", "iPad11,2": return "iPad mini (5th generation)"
case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)"
case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)"
case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro (11-inch) (1st generation)"
case "iPad8,9", "iPad8,10": return "iPad Pro (11-inch) (2nd generation)"
case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch) (1st generation)"
case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)"
case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro (12.9-inch) (3rd generation)"
case "iPad8,11", "iPad8,12": return "iPad Pro (12.9-inch) (4th generation)"
case "AppleTV5,3": return "Apple TV"
case "AppleTV6,2": return "Apple TV 4K"
case "AudioAccessory1,1": return "HomePod"
case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))"
default: return identifier
}
#elseif os(tvOS)
switch identifier {
case "AppleTV5,3": return "Apple TV 4"
case "AppleTV6,2": return "Apple TV 4K"
case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))"
default: return identifier
}
#endif
}
return mapToDevice(identifier: identifier)
}()
}
public class VaDeviceData: NSObject {
public static let UNKNOWN = "Unknown"
public let platform: String = "Mobile"
public let os: String
// OS version
public let osv: String
public let appBundleId: String
public let appName: String
public let appVersion: String
public let deviceBrand: String
public let deviceModel: String
public let userAgent: String
public let sdkVersion: String
public let sdk: String = "iOS SDK"
public let screenResolution: String
// these can change anytime
public var language: String
public static let sharedInstance = VaDeviceData()
private override init(){
let info = Bundle.main.infoDictionary
let executable = (info?[kCFBundleExecutableKey as String] as? String) ??
(ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ??
VaDeviceData.UNKNOWN
let bundle = info?[kCFBundleIdentifierKey as String] as? String ?? VaDeviceData.UNKNOWN
let appVersion = info?["CFBundleShortVersionString"] as? String ?? VaDeviceData.UNKNOWN
let appBuild = info?[kCFBundleVersionKey as String] as? String ?? VaDeviceData.UNKNOWN
let appBundleName = info?[kCFBundleNameKey as String] as? String ?? VaDeviceData.UNKNOWN
let appDisplayName = info?["CFBundleDisplayName"] as? String ?? appBundleName
let osVersion = ProcessInfo.processInfo.operatingSystemVersion
let osVersionString = "\(osVersion.majorVersion).\(osVersion.minorVersion).\(osVersion.patchVersion)"
let osName: String = {
#if os(iOS)
#if targetEnvironment(macCatalyst)
return "macOS(Catalyst)"
#else
return "iOS"
#endif
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(macOS)
return "macOS"
#elseif os(Linux)
return "Linux"
#elseif os(Windows)
return "Windows"
#else
return "Unknown"
#endif
}()
let osNameVersion = "\(osName) \(osVersionString)"
self.sdkVersion = Bundle(for:VaDeviceData.self).infoDictionary?["CFBundleShortVersionString"] as? String ?? VaDeviceData.UNKNOWN
let trackerVersionString = "ViSenzeTracker/\(self.sdkVersion)"
/// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) ViSenzeTracker/5.0.0`
self.userAgent = "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(trackerVersionString)"
self.os = StringHelper.limitMaxLength(osName, 32)
self.osv = StringHelper.limitMaxLength(osVersionString, 32)
self.appBundleId = StringHelper.limitMaxLength(bundle, 32)
self.appVersion = StringHelper.limitMaxLength(appVersion, 32)
self.appName = StringHelper.limitMaxLength(appDisplayName, 32)
self.deviceBrand = "Apple"
self.deviceModel = StringHelper.limitMaxLength(UIDevice.modelName, 32)
let nWidth = Int(UIScreen.main.nativeBounds.width)
let nHeight = Int(UIScreen.main.nativeBounds.height)
self.screenResolution = "\(nWidth)x\(nHeight)"
self.language = Locale.current.languageCode ?? VaDeviceData.UNKNOWN
super.init()
}
}
| mit | 8f26706e70fccb137cc69f02418770b5 | 47.92228 | 171 | 0.528596 | 4.449576 | false | false | false | false |
vl4298/mah-income | Mah Income/Mah Income/CollectionView Layout/CardBaseCollectionViewLayout.swift | 1 | 4124 | //
// CardBaseCollectionViewLayout.swift
// Mah Income
//
// Created by Van Luu on 4/17/17.
// Copyright © 2017 Van Luu. All rights reserved.
//
import UIKit
typealias AttributeHandler = (UICollectionViewLayoutAttributes, CGFloat?) -> (Void)
class CardBaseCollectionViewLayout: UICollectionViewFlowLayout {
fileprivate var handlerAttributeWithFactor: AttributeHandler!
init(attributeHandler: @escaping AttributeHandler) {
super.init()
self.handlerAttributeWithFactor = attributeHandler
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override class var layoutAttributesClass: Swift.AnyClass {
return CategoryLayoutAttribute.self
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = self.collectionView else { return CGPoint.zero }
var offsetAdjust: CGFloat = 10000
let horizontalCenter = proposedContentOffset.x + collectionView.bounds.width/2
let proposedRect = CGRect(x: proposedContentOffset.x,
y: 0,
width: collectionView.bounds.width,
height: collectionView.bounds.height)
guard let attributesArray = super.layoutAttributesForElements(in: proposedRect) else { return proposedContentOffset }
for attribute in attributesArray {
if case UICollectionElementCategory.supplementaryView = attribute.representedElementCategory { continue }
let itemHorizontalCenter = attribute.center.x
if fabs(itemHorizontalCenter - horizontalCenter) < fabs(offsetAdjust) {
offsetAdjust = itemHorizontalCenter - horizontalCenter
}
}
return CGPoint(x: proposedContentOffset.x + offsetAdjust, y: proposedContentOffset.y + offsetAdjust)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributesArray = super.layoutAttributesForElements(in: rect) else { return nil }
guard let collectionView = self.collectionView else { return attributesArray }
let visibleRect = CGRect(x: collectionView.contentOffset.x,
y: collectionView.contentOffset.y,
width: collectionView.bounds.width,
height: collectionView.bounds.height)
for attribute in attributesArray {
apply(layoutAttribute: attribute, for: visibleRect)
}
return attributesArray
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let attribute = super.layoutAttributesForItem(at: indexPath) else { return nil }
guard let collectionView = self.collectionView else { return attribute }
let visibleRect = CGRect(x: collectionView.contentOffset.x,
y: collectionView.contentOffset.y,
width: collectionView.bounds.width,
height: collectionView.bounds.height)
apply(layoutAttribute: attribute, for: visibleRect)
return attribute
}
func apply(layoutAttribute attribute: UICollectionViewLayoutAttributes, for visibleRect: CGRect) {
guard let collectionView = self.collectionView else { return}
let activeDistance = collectionView.bounds.width
// skip supplementary kind
if case UICollectionElementCategory.supplementaryView = attribute.representedElementCategory { return }
let distanceFromVisibleRectToItem: CGFloat = visibleRect.midX - attribute.center.x
if fabs(distanceFromVisibleRectToItem) < activeDistance {
let normalizeDistance = (fabs(distanceFromVisibleRectToItem) / activeDistance)
handlerAttributeWithFactor(attribute, normalizeDistance)
} else {
handlerAttributeWithFactor(attribute, nil)
}
}
}
| mit | be9ce0933478a86a36f9793bc513aaf2 | 36.825688 | 146 | 0.703856 | 5.873219 | false | false | false | false |
SpriteKitAlliance/SKAButton | Source/SKAButton.swift | 1 | 14965 | //
// SKAButton.swift
// SKAToolKit
//
// Copyright (c) 2015 Sprite Kit Alliance
//
// 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 SpriteKit
/**
Insets for the texture/color of the node
- Note: Inset direction will move the texture/color towards that edge at the given amount.
- SKButtonEdgeInsets(top: 10, right: 0, bottom: 0, left: 0)
Top will move the texture/color towards the top
- SKButtonEdgeInsets(top: 10, right: 0, bottom: 10, left: 0)
Top and Bottom will cancel each other out
*/
struct SKButtonEdgeInsets {
let top:CGFloat
let right:CGFloat
let bottom:CGFloat
let left:CGFloat
init() {
top = 0.0
right = 0.0
bottom = 0.0
left = 0.0
}
init(top:CGFloat, right:CGFloat, bottom:CGFloat, left:CGFloat) {
self.top = top
self.right = right
self.bottom = bottom
self.left = left
}
}
/**
SKSpriteNode set up to mimic the utility of UIButton
- Note: Supports Texture per state, normal Texture per state, and color per state
*/
class SKAButtonSprite : SKAControlSprite {
fileprivate var textures = [SKAControlState: SKTexture]()
fileprivate var normalTextures = [SKAControlState: SKTexture]()
fileprivate var colors = [SKAControlState: SKColor]()
fileprivate var colorBlendFactors = [SKAControlState: CGFloat]()
fileprivate var backgroundColor = SKColor.clear
fileprivate var childNode: SKSpriteNode //Child node to act as our real node, the child node gets all of the updates the normal node would, and we keep the actual node as a clickable area only.
/// Will restore the size of the texture node to the button size every time the button is updated
var restoreSizeAfterAction = true
var touchTarget:CGSize
// MARK: - Initializers
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
childNode = SKSpriteNode(texture: nil, color: color, size: size)
touchTarget = size
super.init(texture: texture, color: color, size: size)
///Set the default color and texture for Normal State
setColor(color, forState: .Normal)
setTexture(texture, forState: .Normal)
setColorBlendFactor(0.0, forState: .Normal)
self.addChild(childNode)
}
/**
Use this method for initing with normal Map textures, SKSpriteNode's version will not persist the .Normal Textures correctly
*/
convenience init(texture: SKTexture?, normalMap: SKTexture?) {
self.init(texture: texture, color: UIColor.clear, size: texture?.size() ?? CGSize())
setNormalTexture(normalMap, forState: .Normal)
}
required init?(coder aDecoder: NSCoder) {
childNode = SKSpriteNode()
touchTarget = CGSize()
super.init(coder: aDecoder)
self.addChild(childNode)
}
/**
Update the button based on the state of the button. Since the button can hold more than one state at a time,
determine the most important state and display the correct texture/color
- Note: Disabled > Highlighted > Selected > Normal
- Warning: SKActions can override setting the textures
- Returns: void
*/
override func updateControl() {
var newNormalTexture:SKTexture?
var newTexture:SKTexture?
var newColor = childNode.color
var newColorBlendFactor = colorBlendFactors[.Normal] ?? colorBlendFactor
if controlState.contains(.Disabled) {
if let disabledNormal = normalTextures[.Disabled] {
newNormalTexture = disabledNormal
}
if let disabled = textures[.Disabled] {
newTexture = disabled
}
if let disabledColor = colors[.Disabled] {
newColor = disabledColor
}
if let colorBlend = colorBlendFactors[.Disabled] {
newColorBlendFactor = colorBlend
}
} else if controlState.contains(.Highlighted){
if let highlightedNormal = normalTextures[.Highlighted] {
newNormalTexture = highlightedNormal
}
if let highlighted = textures[.Highlighted] {
newTexture = highlighted
}
if let highlightedColor = colors[.Highlighted] {
newColor = highlightedColor
}
if let colorBlend = colorBlendFactors[.Highlighted] {
newColorBlendFactor = colorBlend
}
} else if controlState.contains(.Selected) {
if let selectedNormal = normalTextures[.Selected] {
newNormalTexture = selectedNormal
}
if let selected = textures[.Selected] {
newTexture = selected
}
if let selectedColor = colors[.Selected] {
newColor = selectedColor
}
if let colorBlend = colorBlendFactors[.Selected] {
newColorBlendFactor = colorBlend
}
} else {
//If .Normal
if let normalColor = colors[.Normal] {
newColor = normalColor
}
if let colorBlend = colorBlendFactors[.Normal] {
newColorBlendFactor = colorBlend
}
}
//Don't need to check if .Normal for textures, if nil set to .Normal textures
if newNormalTexture == nil {
newNormalTexture = normalTextures[.Normal]
}
if newTexture == nil {
newTexture = textures[.Normal]
}
childNode.normalTexture = newNormalTexture
childNode.texture = newTexture
childNode.color = newColor
childNode.colorBlendFactor = newColorBlendFactor
if restoreSizeAfterAction {
childNode.size = childNode.size
}
}
// MARK: - Control States
/**
Sets the node's background color for the specified control state
- Parameter color: The specified color
- Parameter state: The specified control state to trigger the color change
- Returns: void
*/
func setColor(_ color:SKColor?, forState state:SKAControlState) {
if let color = color {
colors[state] = color
} else {
for controlState in SKAControlState.AllOptions {
if colors.keys.contains(controlState) {
colors.removeValue(forKey: controlState)
}
}
}
updateControl()
}
/**
Sets the node's colorBlendFactor for the specified control state
- Parameter colorBlend: The specified colorBlendFactor
- Parameter state: The specefied control state to trigger the color change
- Returns: void
*/
func setColorBlendFactor(_ colorBlend:CGFloat?, forState state:SKAControlState){
if let colorBlend = colorBlend {
colorBlendFactors[state] = colorBlend
} else {
for controlState in SKAControlState.AllOptions {
if colorBlendFactors.keys.contains(controlState) {
colorBlendFactors.removeValue(forKey: controlState)
}
}
}
updateControl()
}
/**
Sets the node's texture for the specified control state
- Parameter texture: The specified texture, if nil it clears the texture for the control state
- Parameter state: The specified control state to trigger the texture change
- Returns: void
*/
func setTexture(_ texture:SKTexture?, forState state:SKAControlState) {
if let texture = texture {
textures[state] = texture
} else {
for controlState in SKAControlState.AllOptions {
if textures.keys.contains(controlState) {
textures.removeValue(forKey: controlState)
}
}
}
updateControl()
}
/**
Sets the node's normal texture for the specified control state
- Parameter texture: The specified texture, if nil it clears the texture for the control state
- Parameter state: The specified control state to trigger the normal texture change
- Returns: void
*/
func setNormalTexture(_ texture:SKTexture?, forState state:SKAControlState) {
if let texture = texture {
normalTextures[state] = texture
} else {
for controlState in SKAControlState.AllOptions {
if normalTextures.keys.contains(controlState) {
normalTextures.removeValue(forKey: controlState)
}
}
}
updateControl()
}
/// Private variable to tell us when to update the button size or the child size
fileprivate var updatingTargetSize = false
/**
Insets for the texture/color of the node
- Note: Inset direction will move the texture/color towards that edge at the given amount.
- SKButtonEdgeInsets(top: 10, right: 0, bottom: 0, left: 0)
Top will move the texture/color towards the top
- SKButtonEdgeInsets(top: 10, right: 0, bottom: 10, left: 0)
Top and Bottom will cancel each other out
*/
var insets = SKButtonEdgeInsets() {
didSet{
childNode.position = CGPoint(x: -insets.left + insets.right, y: -insets.bottom + insets.top)
}
}
/**
Sets the touchable area for the button
- Parameter size: The size of the touchable area
- Returns: void
*/
func setButtonTargetSize(_ size:CGSize) {
updatingTargetSize = true
self.size = size
}
/**
Sets the touchable area for the button
- Parameter size: The size of the touchable area
- Parameter insets: The edge insets for the texture/color of the node
- Returns: void
- Note: Inset direction will move the texture/color towards that edge at the given amount.
*/
func setButtonTargetSize(_ size:CGSize, insets:SKButtonEdgeInsets) {
self.insets = insets
self.setButtonTargetSize(size)
}
// MARK: Shortcuts
/**
Shortcut to handle button highlighting
Sets the colorBlendFactor to 0.2 for the Hightlighted State
Sets the color to a slightly lighter version of the Normal State color for the Highlighted State
*/
func setAdjustsSpriteOnHighlight() {
setColorBlendFactor(0.2, forState: .Highlighted)
setColor(lightenColor(colors[.Normal] ?? color), forState: .Highlighted)
}
/**
Shortcut to handle button disabling
Sets the colorBlendFactor to 0.2 for the Disabled State
Sets the color to a slightly darker version of the Normal State color for the Disabled State
*/
func setAdjustsSpriteOnDisable() {
setColorBlendFactor(0.2, forState: .Disabled)
setColor(darkenColor(colors[.Normal] ?? color), forState: .Disabled)
}
// MARK: Override basic functions and pass them to our child node
override func action(forKey key: String) -> SKAction? {
return childNode.action(forKey: key)
}
override func run(_ action: SKAction) {
childNode.run(action)
}
override func run(_ action: SKAction, completion block: @escaping () -> Void) {
childNode.run(action, completion: block)
}
override func run(_ action: SKAction, withKey key: String) {
childNode.run(action, withKey: key)
}
override func removeAction(forKey key: String) {
childNode.removeAction(forKey: key)
updateControl()
}
override func removeAllActions() {
childNode.removeAllActions()
updateControl()
}
override func removeAllChildren() {
childNode.removeAllChildren()
}
override var texture: SKTexture? {
get {
return childNode.texture
}
set {
childNode.texture = newValue
}
}
override var normalTexture: SKTexture? {
get {
return childNode.normalTexture
}
set {
childNode.normalTexture = newValue
}
}
override var color: SKColor {
get {
return childNode.color
}
set {
super.color = SKColor.clear
childNode.color = newValue
}
}
override var colorBlendFactor: CGFloat {
get {
return childNode.colorBlendFactor
}
set {
super.colorBlendFactor = 0.0
childNode.colorBlendFactor = newValue
}
}
override var size: CGSize {
willSet {
if updatingTargetSize {
if self.size != newValue {
super.size = newValue
}
updatingTargetSize = false
} else {
childNode.size = newValue
}
}
}
// Mark: Color Functions
/**
Takes a color and slightly darkens it (if it can)
- Parameter color: Color to darken
- Returns: UIColor - Darkened Color
*/
fileprivate func darkenColor(_ color: UIColor) -> UIColor {
var redComponent: CGFloat = 0.0
var blueComponent: CGFloat = 0.0
var greenComponent: CGFloat = 0.0
var alphaComponent: CGFloat = 0.0
if color.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha: &alphaComponent) {
let defaultValue: CGFloat = 0.0
redComponent = max(redComponent - 0.2, defaultValue)
blueComponent = max(blueComponent - 0.2, defaultValue)
greenComponent = max(greenComponent - 0.2, defaultValue)
alphaComponent = max(alphaComponent - 0.2, defaultValue)
return UIColor(colorLiteralRed: Float(redComponent),
green: Float(greenComponent),
blue: Float(blueComponent),
alpha: Float(alphaComponent))
} else {
return color
}
}
/**
Takes a color and slightly lightens it (if it can)
- Parameter color: Color to darken
- Returns: UIColor - Lightened Color
*/
fileprivate func lightenColor(_ color: UIColor) -> UIColor {
var redComponent: CGFloat = 1.0
var blueComponent: CGFloat = 1.0
var greenComponent: CGFloat = 1.0
var alphaComponent: CGFloat = 1.0
if color.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha: &alphaComponent) {
let defaultValue: CGFloat = 1.0
redComponent = min(redComponent + 0.2, defaultValue)
blueComponent = min(blueComponent + 0.2, defaultValue)
greenComponent = min(greenComponent + 0.2, defaultValue)
alphaComponent = min(alphaComponent + 0.2, defaultValue)
return UIColor(colorLiteralRed: Float(redComponent),
green: Float(greenComponent),
blue: Float(blueComponent),
alpha: Float(alphaComponent))
} else {
return color
}
}
/// Remove unneeded textures
deinit {
textures.removeAll()
normalTextures.removeAll()
removeAllChildren()
}
}
| mit | cdfbd5ac5bf24845c087e1845b21499c | 29.540816 | 195 | 0.675576 | 4.75986 | false | false | false | false |
slq0378/SimpleMemo | Memo/Memo/MemoCell.swift | 10 | 2836 | //
// MemoCell.swift
// EverMemo
//
// Created by 李俊 on 15/8/5.
// Copyright (c) 2015年 李俊. All rights reserved.
//
import UIKit
class MemoCell: UICollectionViewCell, UIGestureRecognizerDelegate {
var deleteMemo: ((memo: Memo) -> ())?
var memo: Memo? {
didSet{
contentLabel.text = memo!.text
contentLabel.preferredMaxLayoutWidth = itemWidth - 2 * margin
}
}
private let contentLabel: LJLabel = {
let label = LJLabel()
label.numberOfLines = 0
label.preferredMaxLayoutWidth = itemWidth - 2 * margin
label.font = UIFont.systemFontOfSize(15)
// label.textColor = UIColor.darkGrayColor()
label.verticalAlignment = .Top
label.sizeToFit()
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.whiteColor()
setUI()
// 设置阴影
layer.shadowOffset = CGSize(width: 0, height: 1);
layer.shadowOpacity = 0.2;
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setUI(){
contentView.addSubview(contentLabel)
contentLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 5))
contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 5))
contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: -5))
contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: -5))
addGestureRecognizer()
}
private var getsureRecognizer: UIGestureRecognizer?
private func addGestureRecognizer() {
getsureRecognizer = UILongPressGestureRecognizer(target: self, action: "longPress")
getsureRecognizer!.delegate = self
contentView.addGestureRecognizer(getsureRecognizer!)
}
func longPress(){
// 添加一个判断,防止触发两次
if getsureRecognizer?.state == .Began{
deleteMemo?(memo: memo!)
}
}
override func prepareForReuse() {
deleteMemo = nil
}
}
| mit | bdf42f2a2f9d410ff6647bdd33d7fb62 | 28.389474 | 182 | 0.609241 | 5.208955 | false | false | false | false |
oacastefanita/PollsFramework | PollsFramework/Classes/Utils/Extensions.swift | 1 | 10110 | #if os(iOS) || os(watchOS)
import UIKit
#endif
import CryptoSwift
//Primitive data types used to get all properties and values for any given object
let primitiveDataTypes: Dictionary<String, Any> = [
"c" : Int8.self,
"s" : Int16.self,
"i" : Int32.self,
"q" : Int.self, //also: Int64, NSInteger, only true on 64 bit platforms
"S" : UInt16.self,
"I" : UInt32.self,
"Q" : UInt.self, //also UInt64, only true on 64 bit platforms
"B" : Bool.self,
"d" : Double.self,
"f" : Float.self,
"{" : Decimal.self
]
#if os(iOS) || os(watchOS)
#elseif os(OSX)
//MARK: NSImage to PNG
extension NSBitmapImageRep {
var png: Data? {
return representation(using: .png, properties: [:])
}
}
extension Data {
var bitmap: NSBitmapImageRep? {
return NSBitmapImageRep(data: self)
}
}
extension NSImage {
var png: Data? {
return tiffRepresentation?.bitmap?.png
}
func savePNG(to url: URL) -> Bool {
do {
try png?.write(to: url)
return true
} catch {
print(error)
return false
}
}
}
#endif
///Iterate through the enum values
func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyIterator {
let next = withUnsafeBytes(of: &i) { $0.load(as: T.self) }
if next.hashValue != i { return nil }
i += 1
return next
}
}
extension NSObject
{
//MARK: Reflexion methods used to retrieve all object properties and values
#if os(iOS) || os(watchOS) || os(tvOS)
public var className: String {
return String(describing: type(of: self))
}
public class var className: String {
return String(describing: self)
}
#endif
public class func classFromString(_ className: String) -> AnyClass? {
let namespace = Bundle(identifier: "org.cocoapods.PollsFramework")!.infoDictionary!["CFBundleExecutable"] as! String
var cls = NSClassFromString("\(className)")
if cls == nil{
cls = NSClassFromString("\(namespace).\(className)")
}
return cls;
}
public func getUsedProperties()->[String]{
var s = [String]()
for c in Mirror(reflecting: self).children
{
if let name = c.label{
s.append(name)
}
if let value = c.value as Any! {
if let st: String = value as? String {
s.append(String(describing: st))
}
if let st: Int = value as? Int {
s.append(String(describing: st))
}
if let st: Bool = value as? Bool {
s.append(String(describing: st))
}
}
}
return s
}
class func getNameOf(property: objc_property_t) -> String? {
guard let name: NSString = NSString(utf8String: property_getName(property)) else { return nil }
return name as String
}
public class func getTypesOfProperties(in clazz: NSObject.Type) -> Dictionary<String, Any>? {
var count = UInt32()
var types: Dictionary<String, Any> = [:]
guard let properties = class_copyPropertyList(clazz, &count) else {
return types
}
for i in 0..<Int(count) {
guard let property: objc_property_t = properties[i], let name = getNameOf(property: property) else { continue }
let type = getTypeOf(property: property)
types[name] = type
}
free(properties)
return types
}
class func getTypeOf(property: objc_property_t) -> Any {
guard let attributesAsNSString: NSString = NSString(utf8String: property_getAttributes(property)!) else { return Any.self }
let attributes = attributesAsNSString as String
let slices = attributes.components(separatedBy: "\"")
guard slices.count > 1 else { return getPrimitiveDataType(withAttributes: attributes) }
let objectClassName = slices[1]
let objectClass = NSClassFromString(objectClassName) as! NSObject.Type
return objectClass
}
class func getPrimitiveDataType(withAttributes attributes: String) -> Any {
let start = attributes.index(attributes.startIndex, offsetBy: 1)
let end = attributes.index(attributes.startIndex, offsetBy: 2)
let range = start..<end
let letter = attributes.substring(with:range)
let type = primitiveDataTypes[letter]
return type ?? NSObject.self
}
}
#if os(iOS) || os(tvOS)
extension UIView {
func snapshot() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
drawHierarchy(in: bounds, afterScreenUpdates: true)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!
}
}
public extension UIWindow {
/// Replaces the root controller with the given view controller
func replaceRootViewControllerWith(_ replacementController: UIViewController, animated: Bool, completion: (() -> Void)?) {
let snapshotImageView = UIImageView(image: self.snapshot())
self.addSubview(snapshotImageView)
let dismissCompletion = { () -> Void in // dismiss all modal view controllers
self.rootViewController = replacementController
self.bringSubview(toFront: snapshotImageView)
if animated {
UIView.animate(withDuration: 0.4, animations: { () -> Void in
snapshotImageView.alpha = 0
}, completion: { (success) -> Void in
snapshotImageView.removeFromSuperview()
completion?()
})
}
else {
snapshotImageView.removeFromSuperview()
completion?()
}
}
if self.rootViewController!.presentedViewController != nil {
self.rootViewController!.dismiss(animated: false, completion: dismissCompletion)
}
else {
dismissCompletion()
}
}
/// Retrives the visible view controller of the window
public var visibleViewController: UIViewController? {
return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
}
public static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? {
if let nc = vc as? UINavigationController {
return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
} else if let tc = vc as? UITabBarController {
return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
} else {
if let pvc = vc?.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(pvc)
} else {
return vc
}
}
}
}
#endif
extension Date
{
/// Calculate age from Date
var age:Int {
return NSCalendar.current.dateComponents(Set<Calendar.Component>([.year]), from: self, to: Date()).year!
}
/// Create String using the "dateFormatForServer" format
///
/// - Returns: A string containing the Date using the "dateFormatForServer" format
func dateForServer() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormatForServer
let outputDate = dateFormatter.string(from: self)
return outputDate
}
}
extension String{
/// Returns the Date from value of the string using the "dateFormatForServer" as format
///
/// - Returns: <#return value description#>
func dateFromServer() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormatForServer
let date = dateFormatter.date(from: self) as Date!
if date == nil{
return nil
}
return date!
}
//MARK: Phone validation
func isValidPhone() -> Bool {
if(self.characters.count < 6){
return false
}
let charcter = CharacterSet(charactersIn: "0123456789").inverted
var filtered:String!
let inputString:[String] = self.components(separatedBy: charcter)
filtered = inputString.joined(separator: "")
return self == filtered
}
//MARK: Validation regex for email
func isValidEmail() -> Bool {
// println("validate calendar: \(testStr)")
let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
//Base64 encription and decription
func encryptedAndBase64(_ key:String, iv:String) -> String {
let passEnc:[UInt8] = try! AES(key: key, iv: iv).encrypt(pad(self.data(using: String.Encoding.utf8)!.bytes))
return Data(bytes: passEnc).base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn)
}
private func pad(_ value: [UInt8]) -> [UInt8] {
var value = value
let BLOCK_SIZE = 16
let length: Int = value.count
let padSize = BLOCK_SIZE - (length % BLOCK_SIZE)
let padArray = [UInt8](repeating: 0, count: padSize)
value.append(contentsOf: padArray)
return value
}
func decryptedAndBase64(_ key:String, iv:String) -> String {
let baseToData = Data(base64Encoded: self, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)
let decrypted:[UInt8] = try! AES(key: key, iv: iv).decrypt((baseToData?.bytes)!)
return NSString(data: Data(bytes: decrypted), encoding:String.Encoding.utf8.rawValue)! as String
}
}
| mit | fb6b88f332c389ad1156d3f2fd288b7d | 34.598592 | 160 | 0.59634 | 4.644006 | false | false | false | false |
WSDOT/wsdot-ios-app | wsdot/AmtrakCascadesServiceStopItem.swift | 2 | 1327 | //
// AmtrakCascadesServiceItem.swift
// WSDOT
//
// Copyright (c) 2016 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 Foundation
// Stop item represents an item from the Amtrak API. It is eitehr an arriavl or desprature.
class AmtrakCascadesServiceStopItem{
var stationId: String = ""
var stationName: String = ""
var trainNumber: Int = -1
var tripNumer: Int = -1
var sortOrder: Int = -1
var arrivalComment: String? = nil
var departureComment: String? = nil
var scheduledArrivalTime: Date? = nil
var scheduledDepartureTime: Date? = nil
var updated = Date(timeIntervalSince1970: 0)
}
| gpl-3.0 | 4fb9b8298f02c3eebedf945034163066 | 31.365854 | 92 | 0.706104 | 4.009063 | false | false | false | false |
shridharmalimca/iOSDev | iOS/Swift 3.0/Core Data/CoreDataTutorial/CoreDataTutorial/AppDelegate.swift | 2 | 4701 | //
// AppDelegate.swift
// CoreDataTutorial
//
// Created by Shridhar Mali on 2/1/17.
// Copyright © 2017 Shridhar Mali. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var isAddPatient: Bool = false
var selectedPatient = NSManagedObject()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreDataTutorial")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| apache-2.0 | 05bf35384a1af1665f289906afa6612b | 48.473684 | 285 | 0.685745 | 5.875 | false | false | false | false |
Flinesoft/BartyCrouch | Sources/BartyCrouchConfiguration/Options/UpdateOptions/TranslateOptions.swift | 1 | 2010 | import BartyCrouchUtility
import Foundation
import MungoHealer
import Toml
public enum Translator: String {
case microsoftTranslator
case deepL
}
public struct TranslateOptions {
public let paths: [String]
public let subpathsToIgnore: [String]
public let secret: Secret
public let sourceLocale: String
}
extension TranslateOptions: TomlCodable {
static func make(toml: Toml) throws -> TranslateOptions {
let update: String = "update"
let translate: String = "translate"
if let secretString: String = toml.string(update, translate, "secret") {
let translator = toml.string(update, translate, "translator") ?? ""
let paths = toml.filePaths(update, translate, singularKey: "path", pluralKey: "paths")
let subpathsToIgnore = toml.array(update, translate, "subpathsToIgnore") ?? Constants.defaultSubpathsToIgnore
let sourceLocale: String = toml.string(update, translate, "sourceLocale") ?? "en"
let secret: Secret
switch Translator(rawValue: translator) {
case .microsoftTranslator, .none:
secret = .microsoftTranslator(secret: secretString)
case .deepL:
secret = .deepL(secret: secretString)
}
return TranslateOptions(
paths: paths,
subpathsToIgnore: subpathsToIgnore,
secret: secret,
sourceLocale: sourceLocale
)
}
else {
throw MungoError(
source: .invalidUserInput,
message: "Incomplete [update.translate] options provided, ignoring them all."
)
}
}
func tomlContents() -> String {
var lines: [String] = ["[update.translate]"]
lines.append("paths = \(paths)")
lines.append("subpathsToIgnore = \(subpathsToIgnore)")
switch secret {
case let .deepL(secret):
lines.append("secret = \"\(secret)\"")
case let .microsoftTranslator(secret):
lines.append("secret = \"\(secret)\"")
}
lines.append("sourceLocale = \"\(sourceLocale)\"")
return lines.joined(separator: "\n")
}
}
| mit | 6b801ab7df9d06075eebcdd3b4994eea | 28.130435 | 115 | 0.668159 | 4.294872 | false | false | false | false |
jeden/kocomojo-kit | KocomojoKit/KocomojoKit/api/Jsonizable.swift | 1 | 2436 | //
// Jsonizable.swift
// KocomojoKit
//
// Created by Antonio Bello on 1/26/15.
// Copyright (c) 2015 Elapsus. All rights reserved.
//
import Foundation
public protocol JsonDecodable {
class func decode(json: JsonType) -> Self?
}
public protocol JsonEncodable {
func encode() -> JsonDictionary
}
public protocol Jsonizable : JsonDecodable, JsonEncodable {
}
public typealias JsonType = AnyObject
public typealias JsonDictionary = Dictionary<String, JsonType>
public typealias JsonArray = Array<JsonType>
public func JsonString(object: JsonType?) -> String? { return object as? String }
public func JsonInt(object: JsonType?) -> Int? { return object as? Int }
public func JsonDouble(object: JsonType?) -> Double? { return object as? Double }
public func JsonBool(object: JsonType?) -> Bool? { return object as? Bool }
public func JsonDate(object: JsonType?) -> NSDate? { return NSDate.dateFromIso8610(JsonString(object)) }
public func JsonObject(object: JsonType?) -> JsonDictionary? { return object as? JsonDictionary }
public func JsonArrayType(object: JsonType?) -> JsonArray? { return object as? JsonArray }
public func JsonEntity<T: JsonDecodable>(object: JsonType?) -> T? {
if let object: JsonType = object {
return T.decode(object)
}
return .None
}
infix operator >>> { associativity left precedence 150 }
public func >>> <A, B>(a: A?, f: A -> B?) -> B? {
if let x = a {
return f(x)
}
return .None
}
infix operator <^> { associativity left }
public func <^> <A, B>(f: A -> B, a: A?) -> B? {
if let x = a {
return f(x)
}
return .None
}
infix operator <&&> { associativity left }
public func <&&> <A, B>(f: (A -> B)?, a: A?) -> B? {
if let x = a {
if let fx = f {
return fx(x)
}
}
return .None
}
infix operator <||> { associativity left }
public func <||> <A, B>(f: (A? -> B)? , a: A?) -> B? {
if let fx = f {
return fx(a != nil ? a : .None)
}
return .None
}
extension NSDate {
public class func dateFromIso8610(jsonDate: String?) -> NSDate? {
if let jsonDate = jsonDate {
let iso8610DateFormatter = NSDateFormatter()
iso8610DateFormatter.timeStyle = .FullStyle
iso8610DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
return iso8610DateFormatter.dateFromString(jsonDate)
}
return .None
}
} | mit | c1185255a52357ad0b8ef3e472eacf1c | 27.011494 | 104 | 0.630542 | 3.702128 | false | false | false | false |
SunLiner/FleaMarket | FleaMarketGuideSwift/FleaMarketGuideSwift/Classes/NewFeature/FlowLayout/ALinFlowLayout.swift | 1 | 663 | //
// ALinFlowLayout.swift
// FleaMarketGuideSwift
//
// Created by ALin on 16/6/12.
// Copyright © 2016年 ALin. All rights reserved.
//
import UIKit
class ALinFlowLayout: UICollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
scrollDirection = .Horizontal
minimumLineSpacing = 0
minimumInteritemSpacing = 0
itemSize = collectionView!.bounds.size
collectionView!.showsVerticalScrollIndicator = false
collectionView!.showsHorizontalScrollIndicator = false
collectionView!.bounces = false
collectionView!.pagingEnabled = true
}
}
| mit | 79117f75b020e5c0e4eb474d7ce87ef6 | 24.384615 | 62 | 0.675758 | 5.322581 | false | false | false | false |
nuclearace/SwiftDiscord | Sources/SwiftDiscord/Gateway/DiscordEvent.swift | 1 | 4218 | // The MIT License (MIT)
// Copyright (c) 2016 Erik Little
// 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.
///
/// An enum that represents the dispatch events Discord sends.
///
/// If one of these events is handled specifically by the client then it will be turned into an event with the form
/// `myEventName`. If it is not handled, then the associated enum string will be the event name.
///
public enum DiscordDispatchEvent : String {
/// Ready (Handled)
case ready = "READY"
/// Resumed (Handled)
case resumed = "RESUMED"
// Messaging
/// Message Create (Handled)
case messageCreate = "MESSAGE_CREATE"
/// Message Delete (Not handled)
case messageDelete = "MESSAGE_DELETE"
/// Message Delete Bulk (Not handled)
case messageDeleteBulk = "MESSAGE_DELETE_BULK"
/// Message Reaction Add (Not handled)
case messageReactionAdd = "MESSAGE_REACTION_ADD"
/// Message Reaction Remove All (Not handled)
case messageReactionRemoveAll = "MESSAGE_REACTION_REMOVE_ALL"
/// Message Reaction Remove (Not handled)
case messageReactionRemove = "MESSAGE_REACTION_REMOVE"
/// Message Update (Not handled)
case messageUpdate = "MESSAGE_UPDATE"
// Guilds
/// Guild Ban Add (Not handled)
case guildBanAdd = "GUILD_BAN_ADD"
/// Guild Ban Remove (Not handled)
case guildBanRemove = "GUILD_BAN_REMOVE"
/// Guild Create (Handled)
case guildCreate = "GUILD_CREATE"
/// GuildDelete (Handled)
case guildDelete = "GUILD_DELETE"
/// Guild Emojis Update (Handled)
case guildEmojisUpdate = "GUILD_EMOJIS_UPDATE"
/// Guild Integrations Update (Not handled)
case guildIntegrationsUpdate = "GUILD_INTEGRATIONS_UPDATE"
/// Guild Member Add (Handled)
case guildMemberAdd = "GUILD_MEMBER_ADD"
/// Guild Member Remove (Handled)
case guildMemberRemove = "GUILD_MEMBER_REMOVE"
/// Guild Member Update (Handled)
case guildMemberUpdate = "GUILD_MEMBER_UPDATE"
/// Guild Members Chunk (Handled)
case guildMembersChunk = "GUILD_MEMBERS_CHUNK"
/// Guild Role Create (Handled)
case guildRoleCreate = "GUILD_ROLE_CREATE"
/// Guild Role Delete (Handled)
case guildRoleDelete = "GUILD_ROLE_DELETE"
/// Guild Role Update (Handled)
case guildRoleUpdate = "GUILD_ROLE_UPDATE"
/// Guild Update (Handled)
case guildUpdate = "GUILD_UPDATE"
// Channels
/// Channel Create (Handled)
case channelCreate = "CHANNEL_CREATE"
/// Channel Delete (Handled)
case channelDelete = "CHANNEL_DELETE"
/// Channel Pins Update (Not Handled)
case channelPinsUpdate = "CHANNEL_PINS_UPDATE"
/// Channel Update (Handled)
case channelUpdate = "CHANNEL_UPDATE"
// Voice
/// Voice Server Update (Handled but no event emitted)
case voiceServerUpdate = "VOICE_SERVER_UPDATE"
/// Voice State Update (Handled)
case voiceStateUpdate = "VOICE_STATE_UPDATE"
/// Presence Update (Handled)
case presenceUpdate = "PRESENCE_UPDATE"
/// Typing Start (Not handled)
case typingStart = "TYPING_START"
// Webhooks
/// Webhooks Update (Not handled)
case webhooksUpdate = "WEBHOOKS_UPDATE"
}
| mit | 00cead8dc4ac16d967b71715ed77bde9 | 31.446154 | 119 | 0.700569 | 4.357438 | false | false | false | false |
S7Vyto/Mobile | iOS/SVNewsletter/SVNewsletter/Modules/Newsletter/View/NewsletterTableViewCell.swift | 1 | 3022 | //
// NewsletterTableViewCell.swift
// SVNewsletter
//
// Created by Sam on 22/11/2016.
// Copyright © 2016 Semyon Vyatkin. All rights reserved.
//
import UIKit
let backgroundColors = [
0: [UIColor.rgb(169.0, 166.0, 168.0).cgColor, UIColor.rgb(209.0, 207.0, 209.0).cgColor],
1: [UIColor.rgb(51.0, 43.0, 77.0).cgColor, UIColor.rgb(51.0, 43.0, 77.0).cgColor]
]
class NewsletterTableViewCell: UITableViewCell {
@IBOutlet weak private var descLabel: UILabel!
static var identifier: String {
return NSStringFromClass(self).replacingOccurrences(of: "SVNewsletter.", with: "")
}
override var bounds: CGRect {
didSet {
self.contentView.bounds = bounds
}
}
var desc: String? {
didSet {
descLabel.text = desc
}
}
var isTouched: Bool = false {
didSet {
if oldValue != isTouched {
updateContentAppearance(isTouched)
}
}
}
private lazy var backgroundLayer: CAGradientLayer = {
let bgLayer = CAGradientLayer()
bgLayer.shouldRasterize = true
bgLayer.rasterizationScale = UIScreen.main.scale
bgLayer.isOpaque = true
bgLayer.opacity = 0.08
bgLayer.masksToBounds = true
bgLayer.cornerRadius = 4.0
bgLayer.shadowColor = UIColor.black.cgColor
bgLayer.shadowOffset = CGSize(width: 1.5, height: 1.5)
bgLayer.shadowRadius = 6.0
bgLayer.shadowOpacity = 0.5
bgLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
bgLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
bgLayer.colors = backgroundColors[0]!
return bgLayer
}()
// MARK: - Cell LifeCycle
override func awakeFromNib() {
super.awakeFromNib()
configAppearance()
}
override func layoutSubviews() {
super.layoutSubviews()
let rect = CGRect(x: 10.0, y: 5.0, width: self.bounds.size.width - 20.0, height: self.bounds.size.height - 10.0)
backgroundLayer.frame = rect
backgroundLayer.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: 2.0).cgPath
}
// MARK: - Cell Appearance
private func configAppearance() {
self.selectionStyle = .none
self.backgroundColor = UIColor.clear
self.layer.masksToBounds = true
self.layer.insertSublayer(backgroundLayer, at: 0)
}
private func updateContentAppearance(_ isSelected: Bool) {
let index = isSelected ? 1 : 0
UIView.animate(withDuration: 0.3,
animations: { [weak self] in
self?.backgroundLayer.colors = backgroundColors[index]!
}) { [weak self] completed in
if completed {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
self?.isTouched = false
})
}
}
}
}
| apache-2.0 | 5e4636e4eccbcdf1b9ce4430ce616faf | 28.910891 | 120 | 0.575637 | 4.455752 | false | false | false | false |
v-braun/VBPiledView | VBPiledView/VBPiledView/VBPiledView.swift | 1 | 4267 | //
// VBPiledView.swift
// VBPiledView
//
// Created by Viktor Braun ([email protected]) on 02.07.16.
// Copyright © 2016 dev-things. All rights reserved.
//
public protocol VBPiledViewDataSource{
func piledView(_ numberOfItemsForPiledView: VBPiledView) -> Int
func piledView(_ viewForPiledView: VBPiledView, itemAtIndex index: Int) -> UIView
}
open class VBPiledView: UIView, UIScrollViewDelegate {
fileprivate let _scrollview = UIScrollView()
open var dataSource : VBPiledViewDataSource?
override init(frame: CGRect) {
super.init(frame: frame)
initInternal();
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initInternal();
}
override open func layoutSubviews() {
_scrollview.frame = self.bounds
self.layoutContent()
super.layoutSubviews()
}
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
layoutContent()
}
fileprivate func initInternal(){
_scrollview.showsVerticalScrollIndicator = true
_scrollview.showsHorizontalScrollIndicator = false
_scrollview.isScrollEnabled = true
_scrollview.delegate = self
self.addSubview(_scrollview)
}
open var expandedContentHeightInPercent : Float = 80
open var collapsedContentHeightInPercent : Float = 5
fileprivate func layoutContent(){
guard let data = dataSource else {return}
let currentScrollPoint = CGPoint(x:0, y: _scrollview.contentOffset.y)
let contentMinHeight = (CGFloat(collapsedContentHeightInPercent) * _scrollview.bounds.height) / 100
let contentMaxHeight = (CGFloat(expandedContentHeightInPercent) * _scrollview.bounds.height) / 100
var lastElementH = CGFloat(0)
var lastElementY = currentScrollPoint.y
let subViewNumber = data.piledView(self)
_scrollview.contentSize = CGSize(width: self.bounds.width, height: _scrollview.bounds.height * CGFloat(subViewNumber))
for index in 0..<subViewNumber {
let v = data.piledView(self, itemAtIndex: index)
if !v.isDescendant(of: _scrollview){
_scrollview.addSubview(v)
}
let y = lastElementY + lastElementH
let currentViewUntransformedLocation = CGPoint(x: 0, y: (CGFloat(index) * _scrollview.bounds.height) + _scrollview.bounds.height)
let prevViewUntransformedLocation = CGPoint(x: 0, y: currentViewUntransformedLocation.y - _scrollview.bounds.height)
let slidingWindow = CGRect(origin: currentScrollPoint, size: _scrollview.bounds.size)
var h = contentMinHeight
if index == subViewNumber-1 {
h = _scrollview.bounds.size.height
if(currentScrollPoint.y > CGFloat(index) * _scrollview.bounds.size.height){
h = h + (currentScrollPoint.y - CGFloat(index) * _scrollview.bounds.size.height)
}
}
else if slidingWindow.contains(currentViewUntransformedLocation){
let relativeScrollPos = currentScrollPoint.y - (CGFloat(index) * _scrollview.bounds.size.height)
let scaleFactor = (relativeScrollPos * 100) / _scrollview.bounds.size.height
let diff = (scaleFactor * contentMaxHeight) / 100
h = contentMaxHeight - diff
}
else if slidingWindow.contains(prevViewUntransformedLocation){
h = contentMaxHeight - lastElementH
if currentScrollPoint.y < 0 {
h = h + abs(currentScrollPoint.y)
}
else if(h < contentMinHeight){
h = contentMinHeight
}
}
else if slidingWindow.origin.y > currentViewUntransformedLocation.y {
h = 0
}
v.frame = CGRect(origin: CGPoint(x: 0, y: y), size: CGSize(width: _scrollview.bounds.width, height: h))
lastElementH = v.frame.size.height
lastElementY = v.frame.origin.y
}
}
}
| mit | ba8235d43bf0b200bf6865338c0a5346 | 36.752212 | 141 | 0.609236 | 4.989474 | false | false | false | false |
mmick66/KDRearrangeableCollectionViewFlowLayout | KDRearrangeableCollectionViewFlowLayout/KDRearrangeableCollectionViewFlowLayout.swift | 1 | 13361 | //
// KDRearrangeableCollectionViewFlowLayout.swift
// KDRearrangeableCollectionViewFlowLayout
//
// Created by Michael Michailidis on 16/03/2015.
// Copyright (c) 2015 Karmadust. All rights reserved.
//
import UIKit
protocol KDRearrangeableCollectionViewDelegate : UICollectionViewDelegate {
func canMoveItem(at indexPath : IndexPath) -> Bool
func moveDataItem(from source : IndexPath, to destination: IndexPath) -> Void
}
extension KDRearrangeableCollectionViewDelegate {
func canMoveItem(at indexPath : IndexPath) -> Bool {
return true
}
}
enum KDDraggingAxis {
case free
case x
case y
case xy
}
class KDRearrangeableCollectionViewFlowLayout: UICollectionViewFlowLayout, UIGestureRecognizerDelegate {
var animating : Bool = false
var draggable : Bool = true
var collectionViewFrameInCanvas : CGRect = CGRect.zero
var hitTestRectagles = [String:CGRect]()
var canvas : UIView? {
didSet {
if canvas != nil {
self.calculateBorders()
}
}
}
var axis : KDDraggingAxis = .free
struct Bundle {
var offset : CGPoint = CGPoint.zero
var sourceCell : UICollectionViewCell
var representationImageView : UIView
var currentIndexPath : IndexPath
}
var bundle : Bundle?
override init() {
super.init()
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
func setup() {
if let collectionView = self.collectionView {
let longPressGestureRecogniser = UILongPressGestureRecognizer(target: self, action: #selector(KDRearrangeableCollectionViewFlowLayout.handleGesture(_:)))
longPressGestureRecogniser.minimumPressDuration = 0.2
longPressGestureRecogniser.delegate = self
collectionView.addGestureRecognizer(longPressGestureRecogniser)
if self.canvas == nil {
self.canvas = self.collectionView!.superview
}
}
}
override func prepare() {
super.prepare()
self.calculateBorders()
}
fileprivate func calculateBorders() {
if let collectionView = self.collectionView {
collectionViewFrameInCanvas = collectionView.frame
if self.canvas != collectionView.superview {
collectionViewFrameInCanvas = self.canvas!.convert(collectionViewFrameInCanvas, from: collectionView)
}
var leftRect : CGRect = collectionViewFrameInCanvas
leftRect.size.width = 20.0
hitTestRectagles["left"] = leftRect
var topRect : CGRect = collectionViewFrameInCanvas
topRect.size.height = 20.0
hitTestRectagles["top"] = topRect
var rightRect : CGRect = collectionViewFrameInCanvas
rightRect.origin.x = rightRect.size.width - 20.0
rightRect.size.width = 20.0
hitTestRectagles["right"] = rightRect
var bottomRect : CGRect = collectionViewFrameInCanvas
bottomRect.origin.y = bottomRect.origin.y + rightRect.size.height - 20.0
bottomRect.size.height = 20.0
hitTestRectagles["bottom"] = bottomRect
}
}
// MARK: - UIGestureRecognizerDelegate
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if draggable == false {
return false
}
guard let ca = self.canvas else {
return false
}
guard let cv = self.collectionView else {
return false
}
let pointPressedInCanvas = gestureRecognizer.location(in: ca)
for cell in cv.visibleCells {
guard let indexPath:IndexPath = cv.indexPath(for: cell) else {
return false
}
let cellInCanvasFrame = ca.convert(cell.frame, from: cv)
if cellInCanvasFrame.contains(pointPressedInCanvas ) {
if cv.delegate is KDRearrangeableCollectionViewDelegate {
let d = cv.delegate as! KDRearrangeableCollectionViewDelegate
if d.canMoveItem(at: indexPath) == false {
return false
}
}
if let kdcell = cell as? KDRearrangeableCollectionViewCell {
// Override he dragging setter to apply and change in style that you want
kdcell.dragging = true
}
UIGraphicsBeginImageContextWithOptions(cell.bounds.size, cell.isOpaque, 0)
cell.layer.render(in: UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let representationImage = UIImageView(image: img)
representationImage.frame = cellInCanvasFrame
let offset = CGPoint(x: pointPressedInCanvas.x - cellInCanvasFrame.origin.x, y: pointPressedInCanvas.y - cellInCanvasFrame.origin.y)
self.bundle = Bundle(offset: offset, sourceCell: cell, representationImageView:representationImage, currentIndexPath: indexPath)
break
}
}
return (self.bundle != nil)
}
func checkForDraggingAtTheEdgeAndAnimatePaging(_ gestureRecognizer: UILongPressGestureRecognizer) {
if self.animating == true {
return
}
if let bundle = self.bundle {
var nextPageRect : CGRect = self.collectionView!.bounds
if self.scrollDirection == UICollectionViewScrollDirection.horizontal {
if bundle.representationImageView.frame.intersects(hitTestRectagles["left"]!) {
nextPageRect.origin.x -= nextPageRect.size.width
if nextPageRect.origin.x < 0.0 {
nextPageRect.origin.x = 0.0
}
}
else if bundle.representationImageView.frame.intersects(hitTestRectagles["right"]!) {
nextPageRect.origin.x += nextPageRect.size.width
if nextPageRect.origin.x + nextPageRect.size.width > self.collectionView!.contentSize.width {
nextPageRect.origin.x = self.collectionView!.contentSize.width - nextPageRect.size.width
}
}
}
else if self.scrollDirection == UICollectionViewScrollDirection.vertical {
if bundle.representationImageView.frame.intersects(hitTestRectagles["top"]!) {
nextPageRect.origin.y -= nextPageRect.size.height
if nextPageRect.origin.y < 0.0 {
nextPageRect.origin.y = 0.0
}
}
else if bundle.representationImageView.frame.intersects(hitTestRectagles["bottom"]!) {
nextPageRect.origin.y += nextPageRect.size.height
if nextPageRect.origin.y + nextPageRect.size.height > self.collectionView!.contentSize.height {
nextPageRect.origin.y = self.collectionView!.contentSize.height - nextPageRect.size.height
}
}
}
if !nextPageRect.equalTo(self.collectionView!.bounds){
let delayTime = DispatchTime.now() + Double(Int64(0.8 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime, execute: {
self.animating = false
self.handleGesture(gestureRecognizer)
});
self.animating = true
self.collectionView!.scrollRectToVisible(nextPageRect, animated: true)
}
}
}
@objc func handleGesture(_ gesture: UILongPressGestureRecognizer) -> Void {
guard let bundle = self.bundle else {
return
}
func endDraggingAction(_ bundle: Bundle) {
bundle.sourceCell.isHidden = false
if let kdcell = bundle.sourceCell as? KDRearrangeableCollectionViewCell {
kdcell.dragging = false
}
bundle.representationImageView.removeFromSuperview()
// if we have a proper data source then we can reload and have the data displayed correctly
if let cv = self.collectionView, cv.delegate is KDRearrangeableCollectionViewDelegate {
cv.reloadData()
}
self.bundle = nil
}
let dragPointOnCanvas = gesture.location(in: self.canvas)
switch gesture.state {
case .began:
bundle.sourceCell.isHidden = true
self.canvas?.addSubview(bundle.representationImageView)
var imageViewFrame = bundle.representationImageView.frame
var point = CGPoint.zero
point.x = dragPointOnCanvas.x - bundle.offset.x
point.y = dragPointOnCanvas.y - bundle.offset.y
imageViewFrame.origin = point
bundle.representationImageView.frame = imageViewFrame
break
case .changed:
// Update the representation image
var imageViewFrame = bundle.representationImageView.frame
var point = CGPoint(x: dragPointOnCanvas.x - bundle.offset.x, y: dragPointOnCanvas.y - bundle.offset.y)
if self.axis == .x {
point.y = imageViewFrame.origin.y
}
if self.axis == .y {
point.x = imageViewFrame.origin.x
}
imageViewFrame.origin = point
bundle.representationImageView.frame = imageViewFrame
var dragPointOnCollectionView = gesture.location(in: self.collectionView)
if self.axis == .x {
dragPointOnCollectionView.y = bundle.representationImageView.center.y
}
if self.axis == .y {
dragPointOnCollectionView.x = bundle.representationImageView.center.x
}
if let indexPath : IndexPath = self.collectionView?.indexPathForItem(at: dragPointOnCollectionView) {
self.checkForDraggingAtTheEdgeAndAnimatePaging(gesture)
if (indexPath == bundle.currentIndexPath) == false {
// If we have a collection view controller that implements the delegate we call the method first
if let delegate = self.collectionView!.delegate as? KDRearrangeableCollectionViewDelegate {
delegate.moveDataItem(from: bundle.currentIndexPath, to: indexPath)
}
self.collectionView!.moveItem(at: bundle.currentIndexPath, to: indexPath)
self.bundle!.currentIndexPath = indexPath
}
}
break
case .ended:
endDraggingAction(bundle)
break
case .cancelled:
endDraggingAction(bundle)
break
case .failed:
endDraggingAction(bundle)
break
case .possible:
break
}
}
}
| mit | b87183e83c863e115d350e08fd406a88 | 30.887828 | 165 | 0.509318 | 6.782234 | false | false | false | false |
wjk930726/weibo | weiBo/weiBo/iPhone/AppDelegate/AppDelegate+AppService.swift | 1 | 1592 | //
// AppDelegate+AppService.swift
// weiBo
//
// Created by 王靖凯 on 2017/11/16.
// Copyright © 2017年 王靖凯. All rights reserved.
//
import UIKit
import XCGLogger
extension AppDelegate {
/// 初始化 window
internal func initWindow() {
window = UIWindow()
let root = WBRootViewController()
window?.rootViewController = root
window?.makeKeyAndVisible()
UITabBar.appearance().tintColor = globalColor
UINavigationBar.appearance().tintColor = globalColor
if #available(iOS 11.0, *) {
// UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
}
}
/// 初始化XCGLogger对象,并进行设置
internal func initLogger(logger: XCGLogger) {
logger.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: "path/to/file", fileLevel: .debug)
}
/// 一些请求
internal func requestForSomething() {
NetworkManager.shared.requestForWeather(parameters: ["location": "ip"]) { obj in
if let dict = obj {
let res = Results.deserialize(from: dict)
WBUserInfo.shared.weatherInfo = res?.results?.first
} else {
NetworkManager.shared.requestForWeather(parameters: ["location": "beijing"], networkCompletionHandler: { obj in
let res = Results.deserialize(from: obj)
WBUserInfo.shared.weatherInfo = res?.results?.first
})
}
}
}
}
| mit | 0ace1ae38d888c5638bad01973508c1e | 31.787234 | 166 | 0.61194 | 4.785714 | false | false | false | false |
Starscream27/Logger | Logger/Logger.swift | 1 | 2383 | //
// Logger.swift
// Logger
//
// Created by Mathieu Meylan on 14/01/15.
// The MIT License (MIT)
//
// Copyright (c) 2014 Mathieu Meylan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
class Logger: NSObject {
class func debug(message: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__) {
#if DEBUG
self.__log__(message, "DEBUG", fileName, functionName, line)
#endif
}
class func notice(message: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__) {
self.__log__(message, "NOTICE", fileName, functionName, line)
}
class func warn(message: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__) {
self.__log__(message, "WARN", fileName, functionName, line)
}
class func error(message: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__) {
self.__log__(message, "ERROR", fileName, functionName, line)
}
private class func __log__(message: String, _ header:String, _ fileName: String, _ functionName: String , _ line: Int) {
NSLog("\(header) [\(fileName.lastPathComponent.stringByDeletingPathExtension).\(functionName):\(line)]: "+message)
}
}
| mit | 8d938628beacde3df735631fc19215f9 | 47.632653 | 128 | 0.683592 | 4.309222 | false | false | false | false |
firebase/quickstart-ios | config/ConfigExample/Extensions.swift | 1 | 3503 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
extension UIColor {
var highlighted: UIColor { withAlphaComponent(0.8) }
var image: UIImage {
let pixel = CGSize(width: 1, height: 1)
return UIGraphicsImageRenderer(size: pixel).image { context in
self.setFill()
context.fill(CGRect(origin: .zero, size: pixel))
}
}
}
extension NSMutableAttributedString {
/// Convenience init for generating attributred string with SF Symbols
/// - Parameters:
/// - text: The text for the attributed string.
/// Add a `%@` at the location for the SF Symbol.
/// - symbol: the name of the SF symbol
convenience init(text: String, textColor: UIColor = .label, symbol: String? = nil,
symbolColor: UIColor = .label) {
var symbolAttachment: NSAttributedString?
if let symbolName = symbol, let symbolImage = UIImage(systemName: symbolName) {
let configuredSymbolImage = symbolImage.withTintColor(
symbolColor,
renderingMode: .alwaysOriginal
)
let imageAttachment = NSTextAttachment(image: configuredSymbolImage)
symbolAttachment = NSAttributedString(attachment: imageAttachment)
}
let splitStrings = text.components(separatedBy: "%@")
let attributedString = NSMutableAttributedString()
if let symbolAttachment = symbolAttachment, let range = text.range(of: "%@") {
let shouldAddSymbolAtEnd = range.contains(text.endIndex)
splitStrings.enumerated().forEach { index, string in
let attributedPart = NSAttributedString(string: string)
attributedString.append(attributedPart)
if index < splitStrings.endIndex - 1 {
attributedString.append(symbolAttachment)
} else if index == splitStrings.endIndex - 1, shouldAddSymbolAtEnd {
attributedString.append(symbolAttachment)
}
}
}
let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: textColor]
attributedString.addAttributes(
attributes,
range: NSRange(location: 0, length: attributedString.length)
)
self.init(attributedString: attributedString)
}
func setColorForText(text: String, color: UIColor) {
let range = mutableString.range(of: text, options: .caseInsensitive)
addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
}
extension UIViewController {
public func displayError(_ error: Error?, from function: StaticString = #function) {
guard let error = error else { return }
print("🚨 Error in \(function): \(error.localizedDescription)")
let message = "\(error.localizedDescription)\n\n Ocurred in \(function)"
let errorAlertController = UIAlertController(
title: "Error",
message: message,
preferredStyle: .alert
)
errorAlertController.addAction(UIAlertAction(title: "OK", style: .default))
present(errorAlertController, animated: true, completion: nil)
}
}
| apache-2.0 | aa1e900d69156e32b5ddd0b7d6bb1d4a | 37.043478 | 86 | 0.702857 | 4.660453 | false | false | false | false |
xiaoxinghu/swift-org | Sources/Regex.swift | 1 | 3774 | //
// Regex.swift
// SwiftOrg
//
// Created by Xiaoxing Hu on 14/08/16.
// Copyright © 2016 Xiaoxing Hu. All rights reserved.
//
import Foundation
#if !os(Linux)
typealias RegularExpression = NSRegularExpression
typealias TextCheckingResult = NSTextCheckingResult
#else
extension TextCheckingResult {
func rangeAt(_ idx: Int) -> NSRange {
return range(at: idx)
}
}
#endif
var expressions = [String: RegularExpression]()
public extension String {
/// Cache regex (for performance and resource sake)
///
/// - Parameters:
/// - regex: regex pattern
/// - options: options
/// - Returns: the regex
private func getExpression(_ regex: String, options: RegularExpression.Options) -> RegularExpression {
let expression: RegularExpression
if let exists = expressions[regex] {
expression = exists
} else {
expression = try! RegularExpression(pattern: regex, options: options)
expressions[regex] = expression
}
return expression
}
private func getMatches(_ match: TextCheckingResult) -> [String?] {
var matches = [String?]()
switch match.numberOfRanges {
case 0:
return []
case let n where n > 0:
for i in 0..<n {
let r = match.rangeAt(i)
matches.append(r.length > 0 ? NSString(string: self).substring(with: r) : nil)
}
default:
return []
}
return matches
}
public func match(_ regex: String, options: RegularExpression.Options = []) -> [String?]? {
let expression = self.getExpression(regex, options: options)
if let match = expression.firstMatch(in: self, options: [], range: NSMakeRange(0, self.utf16.count)) {
return getMatches(match)
}
return nil
}
public func matchSplit(_ regex: String, options: RegularExpression.Options) -> [String] {
let expression = self.getExpression(regex, options: options)
let matches = expression.matches(in: self, options: [], range: NSMakeRange(0, self.utf16.count))
var splitted = [String]()
var cursor = 0
for m in matches {
if m.range.location > cursor {
splitted.append(self.substring(with: self.characters.index(self.startIndex, offsetBy: cursor)..<self.characters.index(self.startIndex, offsetBy: m.range.location)))
}
splitted.append(NSString(string: self).substring(with: m.range))
cursor = (m.range.toRange()?.upperBound)! + 1
}
if cursor <= self.characters.count {
splitted.append(self.substring(with: self.characters.index(self.startIndex, offsetBy: cursor)..<self.endIndex))
}
return splitted
}
public func tryMatch(_ regex: String,
options: RegularExpression.Options = [],
match: ([String?]) -> Void,
or: (String) -> Void) {
let expression = self.getExpression(regex, options: options)
let matches = expression.matches(in: self, options: [], range: NSMakeRange(0, self.utf16.count))
var cursor = 0
for m in matches {
if m.range.location > cursor {
or(self.substring(with: self.characters.index(self.startIndex, offsetBy: cursor)..<self.characters.index(self.startIndex, offsetBy: m.range.location)))
}
match(getMatches(m))
cursor = (m.range.toRange()?.upperBound)!
}
if cursor < self.characters.count {
or(self.substring(with: self.characters.index(self.startIndex, offsetBy: cursor)..<self.endIndex))
}
}
}
| mit | 30a0d3b3bf34d539ea1f25f48baa43a5 | 35.278846 | 180 | 0.595547 | 4.486326 | false | false | false | false |
lee0741/Glider | Glider/CommentController.swift | 1 | 4165 | //
// CommentController.swift
// Glider
//
// Created by Yancen Li on 2/24/17.
// Copyright © 2017 Yancen Li. All rights reserved.
//
import UIKit
class CommentController: UITableViewController, UIViewControllerPreviewingDelegate {
let defaults = UserDefaults.standard
let infoCellId = "storyInfoCell"
let commentCellId = "commentCell"
var comments = [Comment]()
var story: Story?
var itemId: Int?
override func viewDidLoad() {
super.viewDidLoad()
configUi()
Comment.getComments(from: itemId!) { comments, story in
self.story = story
self.comments = comments
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.tableView.reloadData()
}
}
// MARK: - Config UI
func configUi() {
title = "Comment"
tableView.register(HomeCell.self, forCellReuseIdentifier: infoCellId)
tableView.register(CommentCell.self, forCellReuseIdentifier: commentCellId)
tableView.separatorColor = .separatorColor
let shareBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(CommentController.shareAction))
navigationItem.setRightBarButton(shareBarButtonItem, animated: true)
UIApplication.shared.statusBarStyle = .lightContent
UIApplication.shared.isNetworkActivityIndicatorVisible = true
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self as UIViewControllerPreviewingDelegate, sourceView: view)
}
}
// MARK: - Share Action
func shareAction() {
let defaultText = "Discuss on HN: \(story!.title) https://news.ycombinator.com/item?id=\(story!.id)"
let activityController = UIActivityViewController(activityItems: [defaultText], applicationActivities: nil)
self.present(activityController, animated: true, completion: nil)
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return story == nil ? comments.count : comments.count+1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard story != nil else {
return tableView.dequeueReusableCell(withIdentifier: commentCellId) as! CommentCell
}
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: infoCellId) as! HomeCell
cell.story = story
cell.layoutIfNeeded()
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: commentCellId, for: indexPath) as! CommentCell
cell.comment = comments[indexPath.row-1]
cell.layoutIfNeeded()
return cell
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0,
let url = URL(string: story!.url) {
let safariController = MySafariViewContoller(url: url)
present(safariController, animated: true, completion: nil)
}
}
// MARK: - 3D Touch
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location) else {
return nil
}
if indexPath.row == 0,
let cell = tableView.cellForRow(at: indexPath),
let url = URL(string: story!.url) {
let safariController = MySafariViewContoller(url: url)
previewingContext.sourceRect = cell.frame
return safariController
} else {
return nil
}
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
present(viewControllerToCommit, animated: true, completion: nil)
}
}
| mit | 04f28462859e292a5f95b3bd88a0b185 | 32.047619 | 141 | 0.712776 | 5.059538 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk | Sources/PagedPublication/PagedPublicationView+ContentsView.swift | 1 | 8011 | //
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2018 ShopGun. All rights reserved.
import UIKit
import Verso
extension PagedPublicationView {
/// The view containing the pages and the page number label
/// This will fill the entirety of the publicationView, but will use layoutMargins for pageLabel alignment
class ContentsView: UIView {
struct Properties {
var pageLabelString: String?
var isBackgroundBlack: Bool = false
var showAdditionalLoading: Bool = false
}
var properties = Properties()
func update(properties: Properties) {
self.properties = properties
updatePageNumberLabel(with: properties.pageLabelString)
var spinnerFrame = additionalLoadingSpinner.frame
spinnerFrame.origin.x = self.layoutMarginsGuide.layoutFrame.maxX - spinnerFrame.width
spinnerFrame.origin.y = pageNumberLabel.frame.midY - (spinnerFrame.height / 2)
additionalLoadingSpinner.frame = spinnerFrame
additionalLoadingSpinner.color = properties.isBackgroundBlack ? .white : UIColor(white: 0, alpha: 0.7)
additionalLoadingSpinner.alpha = properties.showAdditionalLoading ? 1 : 0
}
// MARK: Views
var versoView = VersoView()
fileprivate var pageNumberLabel = PageNumberLabel()
fileprivate var additionalLoadingSpinner: UIActivityIndicatorView = {
let view = UIActivityIndicatorView(style: .white)
view.hidesWhenStopped = false
view.startAnimating()
return view
}()
// MARK: UIView Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
versoView.frame = frame
addSubview(versoView)
addSubview(pageNumberLabel)
addSubview(additionalLoadingSpinner)
// initial state is invisible
pageNumberLabel.alpha = 0
additionalLoadingSpinner.alpha = 0
setNeedsLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
versoView.frame = bounds
self.update(properties: self.properties)
}
}
}
// MARK: -
private typealias ContentsPageNumberLabel = PagedPublicationView.ContentsView
extension ContentsPageNumberLabel {
fileprivate func updatePageNumberLabel(with text: String?) {
if let pageLabelString = text {
// update the text & show label
if pageNumberLabel.text != pageLabelString && self.pageNumberLabel.text != nil && self.pageNumberLabel.alpha != 0 {
UIView.transition(with: pageNumberLabel, duration: 0.15, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: {
self.pageNumberLabel.text = text
self.layoutPageNumberLabel()
})
} else {
pageNumberLabel.text = text
self.layoutPageNumberLabel()
}
showPageNumberLabel()
} else {
// hide the label
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dimPageNumberLabel), object: nil)
UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState], animations: {
self.pageNumberLabel.alpha = 0
})
}
}
fileprivate func layoutPageNumberLabel() {
// layout page number label
var lblFrame = pageNumberLabel.frame
lblFrame.size = pageNumberLabel.sizeThatFits(bounds.size)
lblFrame.size.width = ceil(lblFrame.size.width)
lblFrame.size.height = round(lblFrame.size.height)
lblFrame.origin.x = round(bounds.midX - (lblFrame.width / 2))
// change the bottom offset of the pageLabel when on iPhoneX
let pageLabelBottomOffset: CGFloat
if #available(iOS 11.0, *),
UIDevice.current.userInterfaceIdiom == .phone,
UIScreen.main.nativeBounds.height == 2436 { // iPhoneX
// position above the home indicator on iPhoneX
pageLabelBottomOffset = bounds.maxY - safeAreaLayoutGuide.layoutFrame.maxY
} else {
pageLabelBottomOffset = 11
}
lblFrame.origin.y = round(bounds.maxY - pageLabelBottomOffset - lblFrame.height)
pageNumberLabel.frame = lblFrame
}
@objc
fileprivate func dimPageNumberLabel() {
UIView.animate(withDuration: 1.0, delay: 0, options: [.beginFromCurrentState], animations: {
self.pageNumberLabel.alpha = 0.2
}, completion: nil)
}
fileprivate func showPageNumberLabel() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dimPageNumberLabel), object: nil)
UIView.animate(withDuration: 0.5, delay: 0, options: [.beginFromCurrentState], animations: {
self.pageNumberLabel.alpha = 1.0
}, completion: nil)
self.perform(#selector(dimPageNumberLabel), with: nil, afterDelay: 1.0)
}
fileprivate class PageNumberLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
layer.cornerRadius = 6
layer.masksToBounds = true
textColor = .white
layer.backgroundColor = UIColor(white: 0, alpha: 0.3).cgColor
textAlignment = .center
// monospaced numbers
let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFont.TextStyle.headline)
let features: [[UIFontDescriptor.FeatureKey: Any]] = [
[.featureIdentifier: kNumberSpacingType,
.typeIdentifier: kMonospacedNumbersSelector],
[.featureIdentifier: kStylisticAlternativesType,
.typeIdentifier: kStylisticAltOneOnSelector],
[.featureIdentifier: kStylisticAlternativesType,
.typeIdentifier: kStylisticAltTwoOnSelector]
]
let monospacedNumbersFontDescriptor = fontDescriptor.addingAttributes([.featureSettings: features])
//TODO: dynamic font size
font = UIFont(descriptor: monospacedNumbersFontDescriptor, size: 16)
numberOfLines = 1
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var labelEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 4, left: 22, bottom: 4, right: 22)
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
var rect = super.textRect(forBounds: bounds.inset(by: labelEdgeInsets), limitedToNumberOfLines: numberOfLines)
rect.origin.x -= labelEdgeInsets.left
rect.origin.y -= labelEdgeInsets.top
rect.size.width += labelEdgeInsets.left + labelEdgeInsets.right
rect.size.height += labelEdgeInsets.top + labelEdgeInsets.bottom
return rect
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: labelEdgeInsets))
}
}
}
| mit | 22b4a12bcfdc5c06057af78485234e8a | 37.566502 | 147 | 0.593051 | 5.616212 | false | false | false | false |
theprangnetwork/PSAnimation | PSBackgroundColorAnimation.swift | 1 | 946 |
// PSAnimation by Pranjal Satija
import UIKit
struct PSBackgroundColorAnimation: PSAnimation {
var duration: Double
var toValue: AnyObject
func performOnView(view: UIView, completion: (() -> ())?) {
guard let toValue = (toValue as? UIColor)?.CGColor else {
fatalError("PSBackgroundColorAnimation: toValue must be of type UIColor")
}
let animation = CABasicAnimation(keyPath: "backgroundColor")
animation.fromValue = view.layer.backgroundColor
animation.toValue = toValue
CATransaction.setAnimationDuration(duration)
if let completion = completion {
CATransaction.setCompletionBlock(completion)
}
CATransaction.begin()
view.layer.addAnimation(animation, forKey: nil)
view.layer.backgroundColor = toValue
CATransaction.commit()
}
} | apache-2.0 | f699fe0a5fae4fa874ada3e72d1caa0a | 26.852941 | 85 | 0.61945 | 5.698795 | false | false | false | false |
giridharvc7/ScreenRecord | ScreenRecordDemo/MasterViewController.swift | 1 | 3840 | //
// MasterViewController.swift
// ScreenRecordDemo
//
// Created by Giridhar on 21/06/17.
// Copyright © 2017 Jambav. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [Any]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navigationItem.leftBarButtonItem = editButtonItem
let screenRecord = ScreenRecordCoordinator()
screenRecord.viewOverlay.stopButtonColor = UIColor.red
let randomNumber = arc4random_uniform(9999);
screenRecord.startRecording(withFileName: "coolScreenRecording\(randomNumber)", recordingHandler: { (error) in
print("Recording in progress")
}) { (error) in
print("Recording Complete")
}
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
navigationItem.rightBarButtonItem = addButton
if let split = splitViewController {
let controllers = split.viewControllers
detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(_ animated: Bool) {
clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc
func insertNewObject(_ sender: Any) {
objects.insert(NSDate(), at: 0)
let indexPath = IndexPath(row: 0, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
objects.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| mit | 3f7ea5cd3fef9eca25e0e5325a405f25 | 35.216981 | 139 | 0.665798 | 5.5 | false | false | false | false |
isnine/HutHelper-Open | HutHelper/SwiftApp/User/UseInfoViewModel.swift | 1 | 2849 | //
// UseInfoViewModel.swift
// HutHelperSwift
//
// Created by 张驰 on 2020/1/13.
// Copyright © 2020 张驰. All rights reserved.
//
import Foundation
import Alamofire
import Moya
import HandyJSON
import SwiftyJSON
class UseInfoViewModel {
var classesDatas: [ClassModel] = []
}
// - MARK: 网络请求
extension UseInfoViewModel {
// 获取所有班级
func getAllClassesRequst(callback: @escaping () -> Void) {
Alamofire.request(getAllclassesAPI).responseJSON { (response) in
guard response.result.isSuccess else {
return
}
let value = response.value
let json = JSON(value!)
if json["code"] == 200 {
if let datas = json["data"].dictionaryObject {
for (key, value) in datas {
var data = ClassModel()
data.depName = key
data.classes = value as! [String]
self.classesDatas.append(data)
callback()
}
}
}
}
}
// 修改个人信息
func alterUseInfo(type: UserInfoAPI, callback: @escaping (_ result: Bool) -> Void) {
UserInfoProvider .request(type) { (result) in
if case let .success(response) = result {
let data = try? response.mapJSON()
let json = JSON(data!)
print(json)
if json["code"] == 200 {
callback(true)
} else if json["code"] == -1 {
}
}
}
}
// 修改头像
func alterUseHeadImg(image: UIImage, callback: @escaping (_ result: String?) -> Void) {
let imageData = UIImage.jpegData(image)(compressionQuality: 0.5)
Alamofire.upload(multipartFormData: { (multipartFormData) in
let now = Date()
let timeForMatter = DateFormatter()
timeForMatter.dateFormat = "yyyyMMddHHmmss"
let id = timeForMatter.string(from: now)
multipartFormData.append(imageData!, withName: "file", fileName: "\(id).jpg", mimeType: "image/jpeg")
}, to: getUploadImages(type: 3)) { (encodingResult) in
print("个人图片上传地址:\(getUploadImages(type: 3))")
switch encodingResult {
case .success(let upload, _, _):
upload.responseString { response in
if let data = response.data {
let json = JSON(data)
if json["code"] == 200 {
callback(json["data"].stringValue)
}
}
}
case .failure:
print("上传失败")
}
}
}
}
| lgpl-2.1 | d576f03ac79fa64537ae66cae428073a | 32.02381 | 113 | 0.497116 | 4.799308 | false | false | false | false |
ashfurrow/Moya | Examples/Multi-Target/ViewController.swift | 1 | 5096 | import UIKit
import Moya
let provider = MoyaProvider<MultiTarget>(plugins: [NetworkLoggerPlugin(configuration: .init(logOptions: .verbose))])
class ViewController: UITableViewController {
var progressView = UIView()
var repos = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
progressView.frame = CGRect(origin: .zero, size: CGSize(width: 0, height: 2))
progressView.backgroundColor = .blue
navigationController?.navigationBar.addSubview(progressView)
downloadRepositories("ashfurrow")
}
fileprivate func showAlert(_ title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
// MARK: - API Stuff
func downloadRepositories(_ username: String) {
provider.request(MultiTarget(GitHub.userRepositories(username))) { result in
do {
let response = try result.get()
let value = try response.mapNSArray()
self.repos = value
self.tableView.reloadData()
} catch {
let printableError = error as CustomStringConvertible
let errorMessage = printableError.description
self.showAlert("GitHub Fetch", message: errorMessage)
}
}
}
func downloadZen() {
provider.request(MultiTarget(GitHub.zen)) { result in
var message = "Couldn't access API"
if case let .success(response) = result {
let jsonString = try? response.mapString()
message = jsonString ?? message
}
self.showAlert("Zen", message: message)
}
}
func uploadGiphy() {
provider.request(MultiTarget(Giphy.upload(gif: Giphy.animatedBirdData)),
callbackQueue: DispatchQueue.main,
progress: progressClosure,
completion: progressCompletionClosure)
}
func downloadMoyaLogo() {
provider.request(MultiTarget(GitHubUserContent.downloadMoyaWebContent("logo_github.png")),
callbackQueue: DispatchQueue.main,
progress: progressClosure,
completion: progressCompletionClosure)
}
// MARK: - Progress Helpers
lazy var progressClosure: ProgressBlock = { response in
UIView.animate(withDuration: 0.3) {
self.progressView.frame.size.width = self.view.frame.size.width * CGFloat(response.progress)
}
}
lazy var progressCompletionClosure: Completion = { result in
let color: UIColor
switch result {
case .success:
color = .green
case .failure:
color = .red
}
UIView.animate(withDuration: 0.3) {
self.progressView.backgroundColor = color
self.progressView.frame.size.width = self.view.frame.size.width
}
UIView.animate(withDuration: 0.3, delay: 1, options: [],
animations: {
self.progressView.alpha = 0
},
completion: { _ in
self.progressView.backgroundColor = .blue
self.progressView.frame.size.width = 0
self.progressView.alpha = 1
}
)
}
// MARK: - User Interaction
@IBAction func giphyWasPressed(_ sender: UIBarButtonItem) {
uploadGiphy()
}
@IBAction func searchWasPressed(_ sender: UIBarButtonItem) {
var usernameTextField: UITextField?
let promptController = UIAlertController(title: "Username", message: nil, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
if let username = usernameTextField?.text {
self.downloadRepositories(username)
}
}
promptController.addAction(okAction)
promptController.addTextField { textField in
usernameTextField = textField
}
present(promptController, animated: true, completion: nil)
}
@IBAction func zenWasPressed(_ sender: UIBarButtonItem) {
downloadZen()
}
@IBAction func downloadWasPressed(_ sender: UIBarButtonItem) {
downloadMoyaLogo()
}
// MARK: - Table View
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repos.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
let repo = repos[indexPath.row] as? NSDictionary
cell.textLabel?.text = repo?["name"] as? String
return cell
}
}
| mit | c3fe1807e1b1ddc53e948b9969bbf073 | 33.666667 | 116 | 0.606358 | 5.336126 | false | false | false | false |
ashfurrow/pragma-2015-rx-workshop | Session 4/Signup Demo/Pods/RxSwift/RxSwift/Observables/Implementations/AsObservable.swift | 12 | 1188 | //
// AsObservable.swift
// Rx
//
// Created by Krunoslav Zaher on 2/27/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class AsObservableSink<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.E
override init(observer: O, cancel: Disposable) {
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
observer?.on(event)
switch event {
case .Error, .Completed:
self.dispose()
default: break
}
}
}
class AsObservable<Element> : Producer<Element> {
let source: Observable<Element>
init(source: Observable<Element>) {
self.source = source
}
func omega() -> Observable<Element> {
return self
}
func eval() -> Observable<Element> {
return source
}
override func run<O: ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = AsObservableSink(observer: observer, cancel: cancel)
setSink(sink)
return source.subscribeSafe(sink)
}
} | mit | 20f93e34142e8d82e40af7fd0bb8c366 | 22.313725 | 139 | 0.600168 | 4.212766 | false | false | false | false |
Nyx0uf/MPDRemote | src/common/extensions/CGContext+Extensions.swift | 1 | 2860 | // CGContext+Extensions.swift
// Copyright (c) 2017 Nyx0uf
//
// 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 CoreGraphics
// MARK: - Public constants
public let kNYXNumberOfComponentsPerARBGPixel = 4
public let kNYXNumberOfComponentsPerRGBAPixel = 4
extension CGContext
{
// MARK: - ARGB bitmap context
class func ARGBBitmapContext(width: Int, height: Int, withAlpha: Bool, wideGamut: Bool) -> CGContext?
{
let alphaInfo = withAlpha ? CGImageAlphaInfo.premultipliedFirst : CGImageAlphaInfo.noneSkipFirst
let bmContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * kNYXNumberOfComponentsPerARBGPixel, space: wideGamut ? CGColorSpace.NYXAppropriateColorSpace() : CGColorSpaceCreateDeviceRGB(), bitmapInfo: alphaInfo.rawValue)
return bmContext
}
// MARK: - RGBA bitmap context
class func RGBABitmapContext(width: Int, height: Int, withAlpha: Bool, wideGamut: Bool) -> CGContext?
{
let alphaInfo = withAlpha ? CGImageAlphaInfo.premultipliedLast : CGImageAlphaInfo.noneSkipLast
let bmContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * kNYXNumberOfComponentsPerRGBAPixel, space: wideGamut ? CGColorSpace.NYXAppropriateColorSpace() : CGColorSpaceCreateDeviceRGB(), bitmapInfo: alphaInfo.rawValue)
return bmContext
}
}
extension CGColorSpace
{
class func NYXAppropriateColorSpace() -> CGColorSpace
{
if UIScreen.main.traitCollection.displayGamut == .P3
{
if let p3ColorSpace = CGColorSpace(name: CGColorSpace.displayP3)
{
return p3ColorSpace
}
}
return CGColorSpaceCreateDeviceRGB()
}
}
struct RGBAPixel
{
var r: UInt8
var g: UInt8
var b: UInt8
var a: UInt8
init(r: UInt8, g: UInt8, b: UInt8, a: UInt8)
{
self.r = r
self.g = g
self.b = b
self.a = a
}
}
| mit | 68f5c46333a5f8eeaf7517b01617c68f | 34.75 | 270 | 0.761189 | 4.068279 | false | false | false | false |
CodePath-Parse/MiAR | Playgrounds/SceneKit.playground/Contents.swift | 2 | 3895 | //: Playground - noun: a place where people can play
import SceneKit
import PlaygroundSupport
struct Angle {
static func rad(_ angle: Float) -> CGFloat {
return CGFloat(angle)
}
static func deg(_ angle: Float) -> CGFloat {
return CGFloat(Float.pi * angle / 180)
}
}
extension SCNVector3 {
func four(_ value: CGFloat) -> SCNVector4 {
return SCNVector4Make(self.x, self.y, self.z, Float(value))
}
}
extension SCNVector4 {
func three() -> SCNVector3 {
return SCNVector3Make(self.x, self.y, self.z)
}
}
extension SCNMatrix4 {
static public func *(left: SCNMatrix4, right: SCNMatrix4) -> SCNMatrix4 {
return SCNMatrix4Mult(left, right)
}
static public func *(left: SCNMatrix4, right: SCNVector4) -> SCNVector4 {
let x = left.m11*right.x + left.m21*right.y + left.m31*right.z
let y = left.m12*right.x + left.m22*right.y + left.m32*right.z
let z = left.m13*right.x + left.m23*right.y + left.m33*right.z
return SCNVector4(x: x, y: y, z: z, w: right.w * left.m44)
}
func inverted() -> SCNMatrix4 {
return SCNMatrix4Invert(self)
}
}
class Responder {
init(node: SCNNode) {
self.node = node
}
var node: SCNNode
// Create the rotation
let x = SCNVector3Make(1, 0, 0)
let y = SCNVector3Make(0, 1, 0)
let z = SCNVector3Make(0, 0, 1)
@objc func rotateX() {
rotate(node, around: x, by: Angle.deg(5), duration: 0.5)
}
@objc func rotateY() {
rotate(node, around: y, by: Angle.deg(5), duration: 0.5)
}
@objc func rotateZ() {
rotate(node, around: z, by: Angle.deg(5), duration: 0.5)
}
func rotate(_ node: SCNNode, around axis: SCNVector3, by angle: CGFloat, duration: TimeInterval, completionBlock: (()->())?) {
let rotation = SCNMatrix4MakeRotation(Float(angle), axis.x, axis.y, axis.z)
let newTransform = node.worldTransform * rotation
// Animate the transaction
SCNTransaction.begin()
// Set the duration and the completion block
SCNTransaction.animationDuration = duration
SCNTransaction.completionBlock = completionBlock
// Set the new transform
if let parent = node.parent {
node.transform = parent.convertTransform(newTransform, from: nil)
} else {
node.transform = newTransform
}
SCNTransaction.commit()
}
func rotate(_ node: SCNNode, around axis: SCNVector3, by angle: CGFloat, duration: TimeInterval) {
rotate(node, around: axis, by: angle, duration: duration, completionBlock: nil)
}
}
// Create a view, a scene and enable live view
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 600))
let view = SCNView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
containerView.addSubview(view)
let scene = SCNScene()
view.scene = scene
view.autoenablesDefaultLighting = true
PlaygroundPage.current.liveView = containerView
// Create the box
let box = SCNBox(width: 50, height: 50, length: 50, chamferRadius: 5)
let boxNode = SCNNode(geometry: box)
let subnode = SCNNode()
subnode.transform = SCNMatrix4MakeRotation(Float(Angle.deg(30)), 1, 1, 0)
boxNode.rotation = SCNVector4Make(1, 0, 0, Float(Angle.deg(30)))
scene.rootNode.addChildNode(subnode)
subnode.addChildNode(boxNode)
let responder = Responder(node: boxNode)
let buttonX = UIButton()
buttonX.titleLabel?.text = "Rotate X"
buttonX.addTarget(responder, action: #selector(Responder.rotateX), for: .touchUpInside)
let buttonY = UIButton()
buttonY.titleLabel?.text = "Rotate Y"
buttonY.addTarget(responder, action: #selector(Responder.rotateY), for: .touchUpInside)
let stackView = UIStackView(arrangedSubviews: [buttonX, buttonY])
stackView.distribution = .equalSpacing
stackView.axis = .horizontal
containerView.addSubview(stackView)
| apache-2.0 | f6a6616b09f371bf9b9eb61179ab3195 | 29.193798 | 130 | 0.664955 | 3.709524 | false | false | false | false |
28stephlim/Heartbeat-Analyser | VoiceMemos/Controller/ApexSupineOutputViewController.swift | 2 | 5038 | //
// ApexSupineOutputViewController.swift
// VoiceMemos
//
// Created by Stephanie Lim on 02/10/2016.
// Copyright © 2016 Zhouqi Mo. All rights reserved.
//
import UIKit
import FDWaveformView
import Foundation
class ApexSupineOutputViewController: UIViewController {
var URL : NSURL!
///TEST ONLY/////
////CHANGE AFTER////////
var apexsup = "nothing"
var supine = ["AS-ESM", "AS-HSM","AS-LSM", "AS-MSC","AS-MSM","AS-Normal","AS-SplitS1"]
//var supine = ["AS-SplitS1"]
//unwind segue
@IBAction func unwindtoASOutput(segue: UIStoryboardSegue){
}
//Setting up waveform view and waeform target connection
@IBOutlet weak var WaveformView: FDWaveformView!
//Diagnosis labels target connections
@IBOutlet weak var Diagnosis1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//preparing data for 2nd VC
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "asout" {
let VC2 : ApexSupineConditionViewController = segue.destinationViewController as! ApexSupineConditionViewController
VC2.condition = apexsup
VC2.URL = self.URL
}
}
override func viewDidAppear(animated: Bool) {
self.WaveformView.audioURL = URL
self.WaveformView.progressSamples = 0
self.WaveformView.doesAllowScroll = true
self.WaveformView.doesAllowStretch = true
self.WaveformView.doesAllowScrubbing = false
self.WaveformView.wavesColor = UIColor.blueColor()
signalCompare(self.supine)
}
func signalCompare(type: [String]){
let bundle = NSBundle.mainBundle()
var matchArray = [Float]()
var match: Float = 0.0
for name in type {
let sequenceURL = bundle.URLForResource(name, withExtension: "aiff")!
match = compareFingerprint(self.URL, sequenceURL)
print("Match = \(match)")
matchArray.append(match)
}
let maxMatch = matchArray.maxElement() //this is the max match
let maxLocationIndex = matchArray.indexOf(maxMatch!) //this is the index of the max match if you want to use it for something
//var maxLocationInt = matchArray.startIndex.distanceTo(maxLocationIndex!) //this is the index cast as an int if you need to use it
if (maxMatch<0.6) {
self.Diagnosis1.text = "Error have occured. Please re-record the audio file."
}
else{
self.Diagnosis1.text = type[maxLocationIndex!]
apexsup = type[maxLocationIndex!]
}
}
}
/*
self.Diagnosis1.text = type[0] + ": \(matchArray[0])"
self.Diagnosis2.text = type[1] + ": \(matchArray[1])"
self.Diagnosis3.text = type[2] + ": \(matchArray[2])"
self.Diagnosis4.text = type[3] + ": \(matchArray[3])"
if (typeSize>4){
self.Diagnosis5.text = type[4] + ": \(matchArray[4])"
self.Diagnosis6.text = type[5] + ": \(matchArray[5])"
if (typeSize>6){ // These if statements make sure the data shows properly since we have
self.Diagnosis7.text = type[6] + ": \(matchArray[6])" //different amounts of audio files for each category
}
}
self.apexsup = type[maxLocationIndex!]
switch maxLocationInt {
case 0:
self.Diagnosis1.textColor = UIColor.redColor()
case 1:
self.Diagnosis2.textColor = UIColor.redColor()
case 2:
self.Diagnosis3.textColor = UIColor.redColor()
case 3:
self.Diagnosis4.textColor = UIColor.redColor()
case 4:
self.Diagnosis5.textColor = UIColor.redColor()
case 5:
self.Diagnosis6.textColor = UIColor.redColor()
case 6:
self.Diagnosis7.textColor = UIColor.redColor()
default:
print("error has occurred changing text colour") //This probably wont happen
}
//let diagnosisAlert = UIAlertController(title: "Diagnosis", message: "\(type[maxLocation!])", preferredStyle: .Alert)
//let okButton = UIAlertAction(title: "OK", style: .Default){(diagnosisAlert: UIAlertAction!)->Void in }
//diagnosisAlert.addAction(okButton)
//self.presentViewController(diagnosisAlert, animated: true, completion: nil)
})
}
*/
| mit | 843183249e2f65f43c2e3dbf31415cee | 32.805369 | 146 | 0.575342 | 4.747408 | false | false | false | false |
VBVMI/VerseByVerse-iOS | VBVMI/Model/Video.swift | 1 | 2574 | import Foundation
import CoreData
import Decodable
@objc(Video)
open class Video: _Video {
class func decodeJSON(_ JSONDict: NSDictionary, context: NSManagedObjectContext, index: Int) throws -> (Video) {
guard let identifier = JSONDict["ID"] as? String else {
throw APIDataManagerError.missingID
}
guard let video = Video.findFirstOrCreateWithDictionary(["identifier": identifier], context: context) as? Video else {
throw APIDataManagerError.modelCreationFailed
}
video.identifier = try JSONDict => "ID"
video.thumbnailSource = try JSONDict => "thumbnailSource"
video.videoIndex = Int32(index)
video.serviceVideoIdentifier = try? JSONDict => "serviceVideoID"
video.service = try? JSONDict => "service"
let channelDescription: String = try JSONDict => "description"
video.descriptionText = channelDescription.stringByDecodingHTMLEntities
video.thumbnailAltText = nullOrString(try JSONDict => "thumbnailAltText")
if let dateString: String = try JSONDict => "postedDate" {
video.postedDate = Date.dateFromTimeString(dateString)
}
if let dateString: String = try JSONDict => "recordedDate" {
video.recordedDate = Date.dateFromTimeString(dateString)
}
video.averageRating = try JSONDict => "averageRating"
video.videoSource = try JSONDict => "videoSource"
video.videoLength = try JSONDict => "videoLength"
video.url = nullOrString(try JSONDict => "url")
let studyTitle: String = try JSONDict => "title"
video.title = studyTitle.stringByDecodingHTMLEntities
video.averageRating = nullOrString(try JSONDict => "averageRating")
// if let topicsArray: [NSDictionary] = try JSONDict => "topics" as? [NSDictionary] {
// //Then lets process the topics
// var myTopics = Set<Topic>()
//
// topicsArray.forEach({ (topicJSONDict) -> () in
// do {
// if let topic = try Topic.decodeJSON(topicJSONDict, context: context) {
// myTopics.insert(topic)
// }
// } catch let error {
// logger.error("Error decoding Topic \(error)... Skippping...")
// }
// })
//
// video.topics = myTopics
// }
return video
}
}
| mit | 81dddc0ca9dab4790e4d471c29b8c7b1 | 37.41791 | 126 | 0.58042 | 4.998058 | false | true | false | false |
Fenrikur/ef-app_ios | Eurofurence/Director/ApplicationDirector.swift | 1 | 4519 | import EurofurenceModel
import UIKit
class ApplicationDirector: RootModuleDelegate, TutorialModuleDelegate, PreloadModuleDelegate {
private var performAnimations: Bool {
return animate && UIApplication.shared.applicationState == .active
}
private let animate: Bool
private let moduleRepository: ModuleRepository
private let navigationControllerFactory: NavigationControllerFactory
private let tabModuleProviding: TabModuleProviding
private let linkLookupService: ContentLinksService
private let urlOpener: URLOpener
private let orderingPolicy: ModuleOrderingPolicy
private let windowWireframe: WindowWireframe
private var newsController: UIViewController?
private var scheduleViewController: UIViewController?
private var knowledgeListController: UIViewController?
private var dealersViewController: UIViewController?
private var mapsModule: UIViewController?
private var tabController: UITabBarController?
private var tabBarDirector: TabBarDirector?
init(animate: Bool,
moduleRepository: ModuleRepository,
linkLookupService: ContentLinksService,
urlOpener: URLOpener,
orderingPolicy: ModuleOrderingPolicy,
windowWireframe: WindowWireframe,
navigationControllerFactory: NavigationControllerFactory,
tabModuleProviding: TabModuleProviding) {
self.animate = animate
self.moduleRepository = moduleRepository
self.navigationControllerFactory = navigationControllerFactory
self.tabModuleProviding = tabModuleProviding
self.linkLookupService = linkLookupService
self.urlOpener = urlOpener
self.orderingPolicy = orderingPolicy
self.windowWireframe = windowWireframe
moduleRepository.makeRootModule(self)
}
// MARK: Public
func openAnnouncement(_ announcement: AnnouncementIdentifier) {
tabBarDirector?.openAnnouncement(announcement)
}
func openEvent(_ event: EventIdentifier) {
tabBarDirector?.openEvent(event)
}
func openDealer(_ dealer: DealerIdentifier) {
tabBarDirector?.openDealer(dealer)
}
func openMessage(_ message: MessageIdentifier) {
tabBarDirector?.openMessage(message)
}
func openKnowledgeGroups() {
tabBarDirector?.openKnowledgeGroups()
}
func showInvalidatedAnnouncementAlert() {
tabBarDirector?.showInvalidatedAnnouncementAlert()
}
func openKnowledgeEntry(_ knowledgeEntry: KnowledgeEntryIdentifier) {
tabBarDirector?.openKnowledgeEntry(knowledgeEntry)
}
func openKnowledgeEntry(_ knowledgeEntry: KnowledgeEntryIdentifier, parentGroup: KnowledgeGroupIdentifier) {
tabBarDirector?.openKnowledgeEntry(knowledgeEntry, parentGroup: parentGroup)
}
// MARK: RootModuleDelegate
func rootModuleDidDetermineTutorialShouldBePresented() {
showTutorial()
}
func rootModuleDidDetermineStoreShouldRefresh() {
showPreloadModule()
}
func rootModuleDidDetermineRootModuleShouldBePresented() {
showTabModule()
}
// MARK: TutorialModuleDelegate
func tutorialModuleDidFinishPresentingTutorial() {
showPreloadModule()
}
// MARK: PreloadModuleDelegate
func preloadModuleDidCancelPreloading() {
showTutorial()
}
func preloadModuleDidFinishPreloading() {
showTabModule()
}
// MARK: Private
private func showPreloadModule() {
let preloadViewController = moduleRepository.makePreloadModule(self)
windowWireframe.setRoot(preloadViewController)
}
private func showTutorial() {
let tutorialViewController = moduleRepository.makeTutorialModule(self)
windowWireframe.setRoot(tutorialViewController)
}
private func showTabModule() {
tabBarDirector = TabBarDirector(animate: animate,
moduleRepository: moduleRepository,
linkLookupService: linkLookupService,
urlOpener: urlOpener,
orderingPolicy: orderingPolicy,
windowWireframe: windowWireframe,
navigationControllerFactory: navigationControllerFactory,
tabModuleProviding: tabModuleProviding)
}
}
| mit | 211d5e88ffc0db635df6678aee90704e | 31.985401 | 112 | 0.686878 | 6.704748 | false | false | false | false |
vczhou/twitter_feed | TwitterDemo/TwitterClient.swift | 1 | 6996 | //
// TwitterClient.swift
// TwitterDemo
//
// Created by Victoria Zhou on 2/22/17.
// Copyright © 2017 Victoria Zhou. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
class TwitterClient: BDBOAuth1SessionManager {
static let sharedInstance = TwitterClient(baseURL: URL(string: "https://api.twitter.com")!, consumerKey: "PdPOZuL0M99HamGyjwZesURzT", consumerSecret: "OYHSMf5kre6891O1aHVcSKgUvBfdXDmHcQTtvhFcskpsga1ovI")!
var loginSuccess: (() -> ())?
var loginFailure: ((Error) -> ())?
func login(success: @escaping () -> (), failure: @escaping (Error) -> ()) {
loginSuccess = success
loginFailure = failure
TwitterClient.sharedInstance.deauthorize()
TwitterClient.sharedInstance.fetchRequestToken(withPath: "oauth/request_token", method: "GET", callbackURL: URL(string: "twitterdemo://oauth"), scope: nil,success: { (requestToken: BDBOAuth1Credential?) -> Void in
let authURL = URL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken!.token!)")
UIApplication.shared.open(authURL!)
}) { (error: Error?) -> Void in
print("Failed to get request token")
self.loginFailure?(error!)
}
}
func logout() {
User.currentUser = nil
deauthorize()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: User.userDidLogoutNotification), object: nil)
}
func handleOpenUrl(url: URL) {
let requestToken = BDBOAuth1Credential(queryString: url.query)
fetchAccessToken(withPath: "oauth/access_token", method: "POST", requestToken: requestToken, success: { (accessToken: BDBOAuth1Credential?) -> Void in
print("Got access token")
self.currentAccount(sucess: { (user: User) -> () in
User.currentUser = user
self.loginSuccess?()
}, failure: { (error: Error) -> () in
print(error.localizedDescription)
self.loginFailure?(error)
})
}) { (error: Error?) -> Void in
print("Failed to get access token")
self.loginFailure?(error!)
}
}
func currentAccount(sucess: @escaping (User) -> (), failure: @escaping (Error) -> ()) {
get("1.1/account/verify_credentials.json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in
let userDictionary = response as! NSDictionary
let user = User(dictionary: userDictionary)
sucess(user)
}, failure: { (task: URLSessionDataTask?, error: Error) -> Void in
print("Failed to verify credentials")
failure(error)
})
}
func homeTimeline(success: @escaping ([Tweet]) -> (), failure: @escaping (Error) -> ()) {
get("1.1/statuses/home_timeline.json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in
let dictionaries = response as! [NSDictionary]
let tweets = Tweet.tweetsWithArray(dictionaries: dictionaries)
success(tweets)
}, failure: { (task: URLSessionDataTask?, error: Error) -> Void in
print("Failed to get home timeline")
failure(error)
})
}
func userTimeline(screenname: String, success: @escaping ([Tweet]) -> (), failure: @escaping (Error) -> ()) {
let params = ["screen_name": screenname]
get("1.1/statuses/user_timeline.json", parameters: params, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in
let dictionaries = response as! [NSDictionary]
let tweets = Tweet.tweetsWithArray(dictionaries: dictionaries)
success(tweets)
}, failure: { (task: URLSessionDataTask?, error: Error) -> Void in
print("Failed to get home timeline")
failure(error)
})
}
func retweet(id: Int, success: @escaping(Tweet) -> (), failure: @escaping (Error) -> ()) {
post("1.1/statuses/retweet/\(id).json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in
let tweet = Tweet(dictionary: response as! NSDictionary)
success(tweet)
}, failure: { (task: URLSessionDataTask?, error: Error) -> Void in
print("Failed to retweet on id: \(id)")
failure(error)
})
}
func unretweet(id: Int, success: @escaping(Tweet) -> (), failure: @escaping (Error) -> ()) {
post("1.1/statuses/unretweet/\(id).json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in
let tweet = Tweet(dictionary: response as! NSDictionary)
success(tweet)
}, failure: { (task: URLSessionDataTask?, error: Error) -> Void in
print("Failed to unretweet on id: \(id)")
failure(error)
})
}
func favorite(id: Int, success: @escaping(NSDictionary) -> (), failure: @escaping (Error) -> ()) {
post("1.1/favorites/create.json?id=\(id)", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in
let favSuccess = response as! NSDictionary
success(favSuccess)
}, failure: { (task: URLSessionDataTask?, error: Error) -> Void in
print("Failed to favorite on id: \(id)")
failure(error)
})
}
func unfavorite(id: Int, success: @escaping(NSDictionary) -> (), failure: @escaping (Error) -> ()) {
post("1.1/favorites/destroy.json?id=\(id)", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in
let unfavSuccess = response as! NSDictionary
success(unfavSuccess)
}, failure: { (task: URLSessionDataTask?, error: Error) -> Void in
print("Failed to unfavorite on id: \(id)")
failure(error)
})
}
func tweet(tweet: String, isReply: Bool, id: Int, success: @escaping(Tweet) -> (), failure: @escaping (Error) -> ()) {
var params = ["status": tweet]
if(isReply) {
params.updateValue("\(id)", forKey: "in_reply_to_status_id")
}
post("1.1/statuses/update.json", parameters: params, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in
let status = response as! NSDictionary
let tweet = Tweet(dictionary: status)
success(tweet)
}, failure: { (task: URLSessionDataTask?, error: Error) -> Void in
print("Failed to post tweet on id: \(id)")
print(error.localizedDescription)
failure(error)
})
}
}
| apache-2.0 | cd70e809bffbec7b0279f8501f871d2f | 42.179012 | 221 | 0.58356 | 4.472506 | false | false | false | false |
tschob/HSAudioPlayer | HSAudioPlayer/Core/Public/Track/HSURLAudioPlayerItem.swift | 1 | 4751 | //
// HSURLAudioPlayerItem.swift
// HSAudioPlayer
//
// Created by Hans Seiffert on 02.08.16.
// Copyright © 2016 Hans Seiffert. All rights reserved.
//
import Foundation
import AVFoundation
import MediaPlayer
public class HSURLAudioPlayerItem: HSAudioPlayerItem {
// MARK: - Properties
public var url : NSURL?
// MARK: - Initialization
public convenience init?(urlString: String) {
self.init(url: NSURL(string: urlString))
}
public convenience init?(url: NSURL?) {
guard url != nil else {
return nil
}
self.init()
self.url = url
}
public class func playerItems(urlStrings: [String], startPosition: Int) -> (playerItems: [HSURLAudioPlayerItem], startPosition: Int) {
return self.playerItems(HSURLAudioPlayerItem.convertToURLs(urlStrings), startPosition: startPosition)
}
public class func playerItems(urls: [NSURL?], startPosition: Int) -> (playerItems: [HSURLAudioPlayerItem], startPosition: Int) {
var reducedPlayerItems = [HSURLAudioPlayerItem]()
var reducedStartPosition = startPosition
// Iterate through all given URLs and create the player items
for index in 0..<urls.count {
let _url = urls[index]
if let _playerItem = HSURLAudioPlayerItem(url: _url) {
reducedPlayerItems.append(_playerItem)
} else if (index <= startPosition && reducedStartPosition > 0) {
// There is a problem with the URL. Ignore the URL and shift the start position if it is higher than the current index
reducedStartPosition -= 1
}
}
return (playerItems: reducedPlayerItems, startPosition: reducedStartPosition)
}
// MARK: - Lifecycle
override func prepareForPlaying(avPlayerItem: AVPlayerItem) {
super.prepareForPlaying(avPlayerItem)
// Listen to the timedMetadata initialization. We can extract the meta data then
self.avPlayerItem?.addObserver(self, forKeyPath: Keys.TimedMetadata, options: NSKeyValueObservingOptions.Initial, context: nil)
}
override func cleanupAfterPlaying() {
// Remove the timedMetadata observer as the AVPlayerItem will be released now
self.avPlayerItem?.removeObserver(self, forKeyPath: Keys.TimedMetadata, context: nil)
super.cleanupAfterPlaying()
}
public override func getAVPlayerItem() -> AVPlayerItem? {
if let _url = self.url {
return AVPlayerItem(URL: _url)
}
return nil
}
// MARK: - Now playing info
public override func initNowPlayingInfo() {
super.initNowPlayingInfo()
self.nowPlayingInfo?[MPMediaItemPropertyTitle] = self.url?.lastPathComponent
}
// MARK: - Helper
public override func identifier() -> String? {
if let _urlAbsoluteString = self.url?.absoluteString {
return _urlAbsoluteString
}
return super.identifier()
}
public class func convertToURLs(strings: [String]) -> [NSURL?] {
var urls: [NSURL?] = []
for string in strings {
urls.append(NSURL(string: string))
}
return urls
}
public class func firstPlayableItem(urls: [NSURL?], startPosition: Int) -> (playerItem: HSURLAudioPlayerItem, index: Int)? {
// Iterate through all URLs and check whether it's not nil
for index in startPosition..<urls.count {
if let _playerItem = HSURLAudioPlayerItem(url: urls[index]) {
// Create the player item from the first playable URL and return it.
return (playerItem: _playerItem, index: index)
}
}
// There is no playable URL -> reuturn nil then
return nil
}
// MARK: - PRIVATE -
private struct Keys {
static let TimedMetadata = "timedMetadata"
}
private func extractMetadata() {
HSAudioPlayerLog("Extracting meta data of player item with url: \(url)")
for metadataItem in (self.avPlayerItem?.asset.commonMetadata ?? []) {
if let _key = metadataItem.commonKey {
switch _key {
case AVMetadataCommonKeyTitle : self.nowPlayingInfo?[MPMediaItemPropertyTitle] = metadataItem.stringValue
case AVMetadataCommonKeyAlbumName : self.nowPlayingInfo?[MPMediaItemPropertyAlbumTitle] = metadataItem.stringValue
case AVMetadataCommonKeyArtist : self.nowPlayingInfo?[MPMediaItemPropertyArtist] = metadataItem.stringValue
case AVMetadataCommonKeyArtwork :
if let
_data = metadataItem.dataValue,
_image = UIImage(data: _data) {
self.nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: _image)
}
default : continue
}
}
}
// Inform the player about the updated meta data
HSAudioPlayer.sharedInstance.didUpdateMetadata()
}
}
// MARK: - KVO
extension HSURLAudioPlayerItem {
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if (keyPath == Keys.TimedMetadata) {
// Extract the meta data if the timedMetadata changed
self.extractMetadata()
}
}
}
| mit | 770b4b88bb053783e6526f0d29c160ae | 30.456954 | 161 | 0.730526 | 4.080756 | false | false | false | false |
velvetroom/columbus | Source/View/Store/VStoreStatusReadyListCell.swift | 1 | 1002 | import UIKit
class VStoreStatusReadyListCell:UICollectionViewCell
{
weak var imageView:UIImageView!
weak var labelTitle:UILabel!
weak var labelDescr:UILabel!
weak var layoutDescrHeight:NSLayoutConstraint!
private(set) weak var controller:CStore?
let attributesDescr:[NSAttributedStringKey:Any]
override init(frame:CGRect)
{
attributesDescr = VStoreStatusReadyListCell.factoryAttributesDescr(
fontSize:VStoreStatusReadyListCell.Constants.descrFontSize)
super.init(frame:frame)
backgroundColor = UIColor.white
clipsToBounds = true
factoryViews()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: internal
func config(
controller:CStore,
model:MStorePerkProtocol)
{
self.controller = controller
imageView.image = model.icon
labelTitle.text = model.title
addDescr(model:model)
}
}
| mit | 431ff6052abb0a9a960cdf1ed0f460b7 | 23.439024 | 75 | 0.649701 | 5.164948 | false | false | false | false |
Beaconstac/iOS-SDK | BeaconstacSampleApp/Pods/EddystoneScanner/EddystoneScanner/RSSIFilters/RunningAverageFilter.swift | 1 | 2688 | //
// RunningAverageFilter.swift
// EddystoneScanner
//
// Created by Sachin Vas on 26/02/18.
// Copyright © 2018 Amit Prabhu. All rights reserved.
//
import Foundation
///
/// The running average algorithm takes 20 seconds worth of samples
/// and ignores the top and bottom 10 percent of the RSSI readings
/// and takes the mean of the remainder.
/// Similar to how iOS averages samples. https://stackoverflow.com/a/37391517/3106978
/// Very slow, there is a considerable lag before it moves on to the next beacon.
/// Suitable for applications where the device is stationary
///
internal class RunningAverageFilter: RSSIFilter {
// Measurement struct used by the RunningAverageFilter
internal struct Measurement: Comparable, Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(rssi)
hasher.combine(timeStamp)
}
static func <(lhs: Measurement, rhs: Measurement) -> Bool {
return lhs.rssi < rhs.rssi
}
static func ==(lhs: Measurement, rhs: Measurement) -> Bool {
return lhs.rssi == rhs.rssi
}
var rssi: Int
var timeStamp: TimeInterval
}
/// Stores the filter type
internal var filterType: RSSIFilterType
/// Filtered RSSI value
internal var filteredRSSI: Int? {
get {
guard measurements.count > 0 else {
return nil
}
let size = measurements.count
var startIndex = measurements.startIndex
var endIndex = measurements.endIndex
if (size > 2) {
startIndex = measurements.startIndex + measurements.index(measurements.startIndex, offsetBy: size / 10 + 1)
endIndex = measurements.startIndex + measurements.index(measurements.startIndex, offsetBy: size - size / 10 - 2)
}
var sum = 0.0
for i in startIndex..<endIndex {
sum += Double(measurements[i].rssi)
}
let runningAverage = sum / Double(endIndex - startIndex + 1)
return Int(runningAverage)
}
}
internal var measurements: [Measurement] = []
internal init() {
self.filterType = .runningAverage
}
internal func calculate(forRSSI rssi: Int) {
let measurement = Measurement(rssi: rssi, timeStamp: Date().timeIntervalSince1970)
measurements.append(measurement)
measurements = measurements.filter({ ($0.timeStamp - Date().timeIntervalSince1970) < 20000 })
measurements.sort(by: { $0 > $1 })
}
}
| mit | a31892adc12930025d9497b5cafab805 | 30.988095 | 128 | 0.602903 | 4.894353 | false | false | false | false |
instacrate/tapcrate-api | Sources/api/Controllers/CustomerController.swift | 1 | 2529 | //
// UserController.swift
// tapcrate-api
//
// Created by Hakon Hanesand on 11/12/16.
//
//
import Vapor
import HTTP
import AuthProvider
enum FetchType: String, TypesafeOptionsParameter {
case stripe
case shipping
static let key = "type"
static let values = [FetchType.stripe.rawValue, FetchType.shipping.rawValue]
static var defaultValue: FetchType? = nil
}
final class CustomerController {
func detail(_ request: Request) throws -> ResponseRepresentable {
let customer = try request.customer()
try Customer.ensure(action: .read, isAllowedOn: customer, by: request)
if let expander: Expander<Customer> = try request.extract() {
return try expander.expand(for: customer, mappings: { (relation, identifier: Identifier) -> [NodeRepresentable] in
switch relation.path {
case "cards":
return try Stripe.paymentInformation(for: customer.stripeId())
case "shipping":
return try customer.shippingAddresses().all()
default:
throw Abort.custom(status: .badRequest, message: "Could not find expansion for \(relation.path) on \(type(of: self)).")
}
}).makeResponse()
}
return try customer.makeResponse()
}
func create(_ request: Request) throws -> ResponseRepresentable {
let customer: Customer = try request.extractModel()
try Customer.ensure(action: .create, isAllowedOn: customer, by: request)
if try Customer.makeQuery().filter("email", customer.email).count() > 0 {
throw Abort.custom(status: .badRequest, message: "Username is taken.")
}
try customer.save()
request.multipleUserAuth.authenticate(customer)
return try customer.makeResponse()
}
func modify(_ request: Request, customer: Customer) throws -> ResponseRepresentable {
try Customer.ensure(action: .write, isAllowedOn: customer, by: request)
let customer: Customer = try request.patchModel(customer)
try customer.save()
return try customer.makeResponse()
}
}
extension CustomerController: ResourceRepresentable {
func makeResource() -> Resource<Customer> {
return Resource(
index: detail,
store: create,
update: modify
)
}
}
| mit | f1e3abe5029f3892013d9969c81fe40f | 29.841463 | 139 | 0.601423 | 4.988166 | false | false | false | false |
geekskool/JSONSwift | JSONSwift/JsonTest.swift | 1 | 800 | //
// JsonTest.swift
// JSONSwift
//
// Created by Ankit Goel on 18/09/15.
// Copyright © 2015 geekschool. All rights reserved.
//
import Foundation
let file = "file.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = dir.stringByAppendingPathComponent(file);
//writing
do {
try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
//reading
do {
let text2 = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
} | mit | 2179adac89990f51e0de5eb030e8a235 | 26.586207 | 153 | 0.689612 | 4.205263 | false | false | false | false |
jisudong555/swift | weibo/weibo/Classes/Home/HomeViewController.swift | 1 | 8675 | //
// HomeViewController.swift
// weibo
//
// Created by jisudong on 16/4/8.
// Copyright © 2016年 jisudong. All rights reserved.
//
import UIKit
class HomeViewController: BaseViewController {
var statuses: [Status]?
{
didSet {
tableView.reloadData()
}
}
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.init(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1)
if !userLogin {
visitorView?.setupVisitorView(true, imageName: "visitordiscover_feed_image_house", message: "关注一些人,回这里看看有什么惊喜")
return
}
setupNavigationBar()
// 注册通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(changeTitleArrow), name: PopoverAnimatorWillDismiss, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showPhotoBrowser(_:)), name: SDStatusPictureViewSelected, object: nil)
tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: StatusCellReuseIdentifier.Forward.rawValue)
tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusCellReuseIdentifier.Normal.rawValue)
// tableView.estimatedRowHeight = 200
// tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
refreshControl = HomeRefreshControl()
refreshControl?.addTarget(self, action: #selector(loadData), forControlEvents: UIControlEvents.ValueChanged)
loadData()
// let instance = NetworkingManager.sharedInstance()
// let instance1 = NetworkingManager.sharedInstance()
// let instance2 = NetworkingManager()
//
// print("NetworkingManager: \(instance), \(instance1), \(instance2)")
}
func showPhotoBrowser(noti: NSNotification)
{
guard let indexPath = noti.userInfo![SDStatusPictureViewIndexKey] as? NSIndexPath else
{
return
}
guard let urls = noti.userInfo![SDStatusPictureViewURLsKey] as? [NSURL] else
{
return
}
let vc = PhotoBrowserController(index: indexPath.item, ulrs: urls)
presentViewController(vc, animated: true, completion: nil)
}
private var pullupRefreshFlag = false
@objc private func loadData()
{
var since_id = statuses?.first?.id ?? 0
var max_id = 0
if pullupRefreshFlag
{
since_id = 0
max_id = statuses?.last?.id ?? 0
}
Status.loadStatues(since_id, max_id: max_id) { (models, error) in
self.refreshControl?.endRefreshing()
if error != nil
{
return
}
if since_id > 0
{
self.statuses = models! + self.statuses!
self.showNewStatusCount(models?.count ?? 0)
} else if max_id > 0
{
self.statuses = self.statuses! + models!
} else
{
self.statuses = models
}
}
}
private func showNewStatusCount(count : Int)
{
newStatusLabel.hidden = false
newStatusLabel.text = (count == 0) ? "没有刷新到新的微博数据" : "刷新到\(count)条微博数据"
UIView.animateWithDuration(2, animations: { () -> Void in
self.newStatusLabel.transform = CGAffineTransformMakeTranslation(0, self.newStatusLabel.frame.height)
}) { (_) -> Void in
UIView.animateWithDuration(2, animations: { () -> Void in
self.newStatusLabel.transform = CGAffineTransformIdentity
}, completion: { (_) -> Void in
self.newStatusLabel.hidden = true
})
}
}
func changeTitleArrow()
{
let titleButton = navigationItem.titleView as! TitleButton
titleButton.selected = !titleButton.selected
}
private func setupNavigationBar()
{
navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_friendattention", target: self, action: #selector(leftItemClick))
navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_pop", target: self, action: #selector(rightItemClick))
let titleBtn = TitleButton()
titleBtn.setTitle("素东", forState: UIControlState.Normal)
titleBtn.addTarget(self, action: #selector(titleButtonClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
navigationItem.titleView = titleBtn
}
func titleButtonClick(button: TitleButton)
{
button.selected = !button.selected
let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
let vc = sb.instantiateInitialViewController()
vc?.transitioningDelegate = popoverAnimator
vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
presentViewController(vc!, animated: true, completion: nil)
}
func leftItemClick()
{
print(#function)
}
func rightItemClick()
{
print(#function)
let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
let vc = sb.instantiateInitialViewController()
presentViewController(vc!, animated: true, completion: nil)
}
private lazy var popoverAnimator: PopoverAnimator = {
let pa = PopoverAnimator()
let popoverFrameW: CGFloat = 200.0
let popoverFrameX = (UIScreen.mainScreen().bounds.size.width - popoverFrameW) * 0.5
pa.presentFrame = CGRect(x: popoverFrameX, y: 56, width: popoverFrameW, height: 300)
return pa
}()
/// 刷新提醒控件
private lazy var newStatusLabel: UILabel =
{
let label = UILabel()
let height: CGFloat = 44
// label.frame = CGRect(x: 0, y: -2 * height, width: UIScreen.mainScreen().bounds.width, height: height)
label.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: height)
label.backgroundColor = UIColor.orangeColor()
label.textColor = UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
// 加载 navBar 上面,不会随着 tableView 一起滚动
self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
label.hidden = true
return label
}()
// 缓存cell高度
private var cellHeightCache = [Int: CGFloat]()
override func didReceiveMemoryWarning() {
cellHeightCache.removeAll()
}
}
extension HomeViewController
{
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return statuses?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let status = statuses![indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellReuseIdentifier.cellID(status), forIndexPath: indexPath) as! StatusCell
cell.status = status
let count = statuses?.count ?? 0
if indexPath.row == (count - 1)
{
pullupRefreshFlag = true
loadData()
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let status = statuses![indexPath.row]
// if let cacheHeight = cellHeightCache[status.id]
// {
// print("缓存中获取")
// return cacheHeight
// }
print("重新计算")
var height: CGFloat = 0
switch StatusCellReuseIdentifier.cellID(status) {
case StatusCellReuseIdentifier.Normal.rawValue:
height = StatusNormalCell.cellHeightWithModel(status)
default:
height = StatusForwardCell.cellHeightWithModel(status)
}
cellHeightCache[status.id] = height
return height
}
}
| mit | 31dea2a76590ea7c0941f3e5bf7e490a | 31.295455 | 159 | 0.602393 | 5.298943 | false | false | false | false |
jlandon/Alexandria | Sources/Alexandria/UIViewController+Extensions.swift | 2 | 2714 | //
// UIViewController+Extensions.swift
//
// Created by Jonathan Landon on 4/15/15.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Oven Bits, LLC
//
// 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
extension UIViewController {
/// Retrieve the view controller currently on-screen
///
/// Based off code here: http://stackoverflow.com/questions/24825123/get-the-current-view-controller-from-the-app-delegate
@available(iOSApplicationExtension, unavailable)
public static var current: UIViewController? {
if let controller = UIApplication.shared.keyWindow?.rootViewController {
return findCurrent(controller)
}
return nil
}
private static func findCurrent(_ controller: UIViewController) -> UIViewController {
if let controller = controller.presentedViewController {
return findCurrent(controller)
}
else if let controller = controller as? UISplitViewController, let lastViewController = controller.viewControllers.first, controller.viewControllers.count > 0 {
return findCurrent(lastViewController)
}
else if let controller = controller as? UINavigationController, let topViewController = controller.topViewController, controller.viewControllers.count > 0 {
return findCurrent(topViewController)
}
else if let controller = controller as? UITabBarController, let selectedViewController = controller.selectedViewController, (controller.viewControllers?.count ?? 0) > 0 {
return findCurrent(selectedViewController)
}
else {
return controller
}
}
}
| mit | e4640636acc7f0e598b4cdd548df801f | 44.233333 | 178 | 0.722918 | 5.091932 | false | false | false | false |
stasel/WWDC2015 | StasSeldin/StasSeldin/Model/StasProfile.swift | 1 | 5789 | //
// StasProfile.swift
// StasSeldin
//
// Created by Stas Seldin on 22/04/2015.
// Copyright (c) 2015 Stas Seldin. All rights reserved.
//
import Foundation
class StasProfile {
class func getProfile() -> (Profile) {
let me = Profile(name: FullName(firstName: "Stas", lastName: "Seldin"))
me.dateOfBirth = Date.dateFromComponents(year: 1989, month: 5, day: 26) as Date
me.picture = "Profile"
me.about = "I'm a young student with love and passion to create wonderful things using my programming skills."
me.backgroundPic = "Background"
// ***************** Contact info **********************
me.contact.email = "[email protected]"
me.contact.faceTime = "[email protected]"
me.contact.phoneNumber = "+31 6 12 34 56 78"
me.contact.address = Address(street: .Street("Amsterdam"), city: "Amsterdam", country: "The Netherlands")
// ***************** social media **********************
me.socialMedia.faceBook = "https://www.facebook.com/stasel"
me.socialMedia.gitHub = "https://github.com/stasel"
me.socialMedia.linkedIn = "https://linkedin.com/in/stasel"
me.socialMedia.stackOverflow = "http://stackoverflow.com/users/757338/stasel"
// ***************** education **********************
let openu = EducationRecord(degree: .BachelorsDegree("Computer sicence"), fromYear: 2012, toYear: nil, instituteName: "Open University of Israel")
me.education += [openu]
// ***************** work experience **********************
let varonis = WorkRecord(company: "Varonis Systems", role: "iOS and web developer", fromYear: 2013)
varonis.description = "Developing mobile clients for our secure enterprise data collaboration and file syncing software called “DatAnywhere”. Currently specializing in iOS development using Objective C and Swift. Building the iOS client introduced me to varies challenges: uploading and downloading files, battery life optimization, minimizing network bandwidth, supporting older iOS versions."
let matrix = WorkRecord(company: "Matrix IT", role: "Web developer", fromYear: 2010, toYear: 2013)
matrix.description = "Developed on demand enterprise level applications for Israeli health organizations. Using ASP.NET, C#, SQL, HTML, CSS and JavaScript."
let idf = WorkRecord(company: "Israeli Defence Forces", role: "Development team leader", fromYear: 2008, toYear: 2010)
idf.description = "In charge of a small developing team (2-3 developers). The team developed a large variety of software and scripts in many different languages: Warehouse management software (C#), Network monitoring tool (Perl & ASP.NET), automation scrips in Perl and batch."
me.workExperience+=[varonis,matrix,idf]
// ***************** Projects **********************
let yotamDesc = "A unique software which helps to research and prevent the Thalassemia disease. The software was designed to handle a big amount of data such as: blood test results, genetic test results, patient’s origin and more. The software analyzes the data and provides a detailed statistical information about the disease."
let yotam = Project(projectName: "Genetic research software", projectDescription: yotamDesc)
yotam.screenShots+=["Yotam"]
let webetterDesc = "Or the rise and the fall of my first start-up. After winning a hackathon, our team got the opportunity to travel to San Francisco and present our idea to the Silicon Valley. WeBetter is a platform to help organizations to find volunteers through our platform. It makes easier for people to find places to volunteer as well."
let webetter = Project(projectName: "WeBetter.do", projectDescription: webetterDesc)
webetter.screenShots+=["Webetter"]
let snifferDesc = "During my military service, I built a network monitoring software for our base in order to help the Sys Admins managing the network. It was some kind of “probe” that got into a computer, collected the data and reported back to the main database .The software was a great success and managed to monitor more than 1000 computers in our base."
let sniffer = Project(projectName: "The Sniffer", projectDescription: snifferDesc)
sniffer.screenShots+=["Sniffer"]
let chateeDesc = "Currently still in a development. Using the power of Node.js, cloud computing and web sockets protocol I am developing a mind blowing chatting service. (Of course the iOS app is also in development). I wish I could tell you more."
let chatee = Project(projectName: "Revolutionary chatting service", projectDescription: chateeDesc)
chatee.screenShots+=["Chatee"]
me.projects += [yotam, webetter, sniffer, chatee]
// ***************** Skills **********************
me.skills += ["HTML", "CSS", "JavaScript", "Swift", "Objective C", "C#", "node.js","Java", "C", "Rest design", "Design patterns", "SQL", "MongoDB"]
// ***************** Hobbies **********************
let swimming = Hobby(name: "Swimming")
swimming.picture = "Swimming"
let coding = Hobby(name: "Writing some code")
coding.picture = "Coding"
let friends = Hobby(name: "Hanging out with friends")
friends.picture = "Friends"
let family = Hobby(name: "My Girlfriend and our Cat")
family.picture = "Family"
let traveling = Hobby(name: "Traveling")
traveling.picture = "Traveling"
me.hobbies += [traveling, coding, swimming, friends, family]
return me
}
}
| mit | a1ed919ef974c725349b8364c06702e4 | 66.988235 | 402 | 0.651324 | 4.459105 | false | false | false | false |
asbhat/stanford-ios10-apps | FaceIt/FaceIt/VCLLoggingViewController.swift | 1 | 3704 | //
// VCLLoggingViewController.swift
//
// Created by CS193p Instructor.
// Copyright © 2015-17 Stanford University. All rights reserved.
//
import UIKit
class VCLLoggingViewController : UIViewController {
private struct LogGlobals {
var prefix = ""
var instanceCounts = [String:Int]()
var lastLogTime = Date()
var indentationInterval: TimeInterval = 1
var indentationString = "__"
}
private static var logGlobals = LogGlobals()
private static func logPrefix(for className: String) -> String {
if logGlobals.lastLogTime.timeIntervalSinceNow < -logGlobals.indentationInterval {
logGlobals.prefix += logGlobals.indentationString
print("")
}
logGlobals.lastLogTime = Date()
return logGlobals.prefix + className
}
private static func bumpInstanceCount(for className: String) -> Int {
logGlobals.instanceCounts[className] = (logGlobals.instanceCounts[className] ?? 0) + 1
return logGlobals.instanceCounts[className]!
}
private var instanceCount: Int!
private func logVCL(_ msg: String) {
let className = String(describing: type(of: self))
if instanceCount == nil {
instanceCount = VCLLoggingViewController.bumpInstanceCount(for: className)
}
print("\(VCLLoggingViewController.logPrefix(for: className))(\(instanceCount!)) \(msg)")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
logVCL("init(coder:) - created via InterfaceBuilder ")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
logVCL("init(nibName:bundle:) - create in code")
}
deinit {
logVCL("left the heap")
}
override func awakeFromNib() {
logVCL("awakeFromNib()")
}
override func viewDidLoad() {
super.viewDidLoad()
logVCL("viewDidLoad()")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
logVCL("viewWillAppear(animated = \(animated))")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
logVCL("viewDidAppear(animated = \(animated))")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
logVCL("viewWillDisappear(animated = \(animated))")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
logVCL("viewDidDisappear(animated = \(animated))")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
logVCL("didReceiveMemoryWarning()")
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
logVCL("viewWillLayoutSubviews() bounds.size = \(view.bounds.size)")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
logVCL("viewDidLayoutSubviews() bounds.size = \(view.bounds.size)")
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
logVCL("viewWillTransition(to: \(size), with: coordinator)")
coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.logVCL("begin animate(alongsideTransition:completion:)")
}, completion: { context -> Void in
self.logVCL("end animate(alongsideTransition:completion:)")
})
}
}
| apache-2.0 | efaa8b41b349221e77151713d9ea0492 | 33.287037 | 118 | 0.661086 | 5.297568 | false | false | false | false |
alex-alex/S2Geometry | Sources/S2LatLng.swift | 1 | 5512 | //
// S2LatLng.swift
// S2Geometry
//
// Created by Alex Studnicka on 7/1/16.
// Copyright © 2016 Alex Studnicka. MIT License.
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
public struct S2LatLng: Equatable {
/// Approximate "effective" radius of the Earth in meters.
public static let earthRadiusMeters: Double = 6367000
public let lat: S1Angle
public let lng: S1Angle
public static func latitude(point p: S2Point) -> S1Angle {
// We use atan2 rather than asin because the input vector is not necessarily
// unit length, and atan2 is much more accurate than asin near the poles.
return S1Angle(radians: atan2(p.z, sqrt(p.x * p.x + p.y * p.y)))
}
public static func longitude(point p: S2Point) -> S1Angle {
// Note that atan2(0, 0) is defined to be zero.
return S1Angle(radians: atan2(p.y, p.x))
}
public init(lat: S1Angle = S1Angle(), lng: S1Angle = S1Angle()) {
self.lat = lat
self.lng = lng
}
public static func fromRadians(lat: Double, lng: Double) -> S2LatLng {
return S2LatLng(lat: S1Angle(radians: lat), lng: S1Angle(radians: lng))
}
public static func fromDegrees(lat: Double, lng: Double) -> S2LatLng {
return S2LatLng(lat: S1Angle(degrees: lat), lng: S1Angle(degrees: lng))
}
public static func fromE5(lat: Int64, lng: Int64) -> S2LatLng {
return S2LatLng(lat: S1Angle(e5: lat), lng: S1Angle(e5: lng))
}
public static func fromE6(lat: Int64, lng: Int64) -> S2LatLng {
return S2LatLng(lat: S1Angle(e6: lat), lng: S1Angle(e6: lng))
}
public static func fromE7(lat: Int64, lng: Int64) -> S2LatLng {
return S2LatLng(lat: S1Angle(e7: lat), lng: S1Angle(e7: lng))
}
/// Convert a point (not necessarily normalized) to an S2LatLng.
public init(point p: S2Point) {
// The latitude and longitude are already normalized. We use atan2 to
// compute the latitude because the input vector is not necessarily unit
// length, and atan2 is much more accurate than asin near the poles.
// Note that atan2(0, 0) is defined to be zero.
self.init(lat: S2LatLng.latitude(point: p), lng: S2LatLng.longitude(point: p))
}
/**
Return true if the latitude is between -90 and 90 degrees inclusive and the
longitude is between -180 and 180 degrees inclusive.
*/
public var isValid: Bool {
return abs(lat.radians) <= M_PI_2 && abs(lng.radians) <= M_PI
}
/**
Returns a new S2LatLng based on this instance for which `isValid` will be `true`.
- Latitude is clipped to the range `[-90, 90]`
- Longitude is normalized to be in the range `[-180, 180]`
If the current point is valid then the returned point will have the same coordinates.
*/
public var normalized: S2LatLng {
// drem(x, 2 * S2.M_PI) reduces its argument to the range
// [-S2.M_PI, S2.M_PI] inclusive, which is what we want here.
return S2LatLng.fromRadians(lat: max(-M_PI_2, min(M_PI_2, lat.radians)), lng: remainder(lng.radians, 2 * M_PI))
}
/// Convert an S2LatLng to the equivalent unit-length vector (S2Point).
public var point: S2Point {
let phi = lat.radians
let theta = lng.radians
let cosphi = cos(phi)
return S2Point(x: cos(theta) * cosphi, y: sin(theta) * cosphi, z: sin(phi))
}
/// Return the distance (measured along the surface of the sphere) to the given point.
public func getDistance(to o: S2LatLng) -> S1Angle {
// This implements the Haversine formula, which is numerically stable for
// small distances but only gets about 8 digits of precision for very large
// distances (e.g. antipodal points). Note that 8 digits is still accurate
// to within about 10cm for a sphere the size of the Earth.
//
// This could be fixed with another sin() and cos() below, but at that point
// you might as well just convert both arguments to S2Points and compute the
// distance that way (which gives about 15 digits of accuracy for all
// distances).
let lat1 = lat.radians
let lat2 = o.lat.radians
let lng1 = lng.radians
let lng2 = o.lng.radians
let dlat = sin(0.5 * (lat2 - lat1))
let dlng = sin(0.5 * (lng2 - lng1))
let x = dlat * dlat + dlng * dlng * cos(lat1) * cos(lat2)
return S1Angle(radians: 2 * atan2(sqrt(x), sqrt(max(0.0, 1.0 - x))))
// Return the distance (measured along the surface of the sphere) to the
// given S2LatLng. This is mathematically equivalent to:
//
// S1Angle::FromRadians(ToPoint().Angle(o.ToPoint())
//
// but this implementation is slightly more efficient.
}
/// Returns the surface distance to the given point assuming a constant radius.
public func getDistance(to o: S2LatLng, radius: Double = S2LatLng.earthRadiusMeters) -> Double {
// TODO(dbeaumont): Maybe check that radius >= 0 ?
return getDistance(to: o).radians * radius
}
/// Returns true if both the latitude and longitude of the given point are within {@code maxError} radians of this point.
public func approxEquals(to other: S2LatLng, maxError: Double = 1e-9) -> Bool {
return (abs(lat.radians - other.lat.radians) < maxError) && (abs(lng.radians - other.lng.radians) < maxError)
}
}
public func ==(lhs: S2LatLng, rhs: S2LatLng) -> Bool {
return lhs.lat == rhs.lat && lhs.lng == rhs.lng
}
public func +(lhs: S2LatLng, rhs: S2LatLng) -> S2LatLng {
return S2LatLng(lat: lhs.lat + rhs.lat, lng: lhs.lng + rhs.lng)
}
public func -(lhs: S2LatLng, rhs: S2LatLng) -> S2LatLng {
return S2LatLng(lat: lhs.lat - rhs.lat, lng: lhs.lng - rhs.lng)
}
public func *(lhs: S2LatLng, m: Double) -> S2LatLng {
return S2LatLng(lat: lhs.lat * m, lng: lhs.lng * m)
}
| mit | 5752bffb822fccebd5da895e43ec9e31 | 35.256579 | 122 | 0.690982 | 3.046434 | false | false | false | false |
jacobwhite/firefox-ios | SyncTelemetry/SyncTelemetry.swift | 5 | 4132 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Alamofire
import Foundation
import XCGLogger
import SwiftyJSON
import Shared
private let log = Logger.browserLogger
private let ServerURL = "https://incoming.telemetry.mozilla.org".asURL!
private let AppName = "Fennec"
public enum TelemetryDocType: String {
case core = "core"
case sync = "sync"
}
public protocol SyncTelemetryEvent {
func record(_ prefs: Prefs)
}
open class SyncTelemetry {
private static var prefs: Prefs?
private static var telemetryVersion: Int = 4
open class func initWithPrefs(_ prefs: Prefs) {
assert(self.prefs == nil, "Prefs already initialized")
self.prefs = prefs
}
open class func recordEvent(_ event: SyncTelemetryEvent) {
guard let prefs = prefs else {
assertionFailure("Prefs not initialized")
return
}
event.record(prefs)
}
open class func send(ping: SyncTelemetryPing, docType: TelemetryDocType) {
let docID = UUID().uuidString
let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
let buildID = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
let channel = AppConstants.BuildChannel.rawValue
let path = "/submit/telemetry/\(docID)/\(docType.rawValue)/\(AppName)/\(appVersion)/\(channel)/\(buildID)"
let url = ServerURL.appendingPathComponent(path)
var request = URLRequest(url: url)
log.debug("Ping URL: \(url)")
log.debug("Ping payload: \(ping.payload.stringValue() ?? "")")
// Don't add the common ping format for the mobile core ping.
let pingString: String?
if docType != .core {
var json = JSON(commonPingFormat(forType: docType))
json["payload"] = ping.payload
pingString = json.stringValue()
} else {
pingString = ping.payload.stringValue()
}
guard let body = pingString?.data(using: .utf8) else {
log.error("Invalid data!")
assertionFailure()
return
}
guard channel != "default" else {
log.debug("Non-release build; not sending ping")
return
}
request.httpMethod = "POST"
request.httpBody = body
request.addValue(Date().toRFC822String(), forHTTPHeaderField: "Date")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
SessionManager.default.request(request).response { response in
log.debug("Ping response: \(response.response?.statusCode ?? -1).")
}
}
private static func commonPingFormat(forType type: TelemetryDocType) -> [String: Any] {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let date = formatter.string(from: NSDate() as Date)
let displayVersion = [
AppInfo.appVersion,
"b",
AppInfo.buildNumber
].joined()
let version = ProcessInfo.processInfo.operatingSystemVersion
let osVersion = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
return [
"type": type.rawValue,
"id": UUID().uuidString,
"creationDate": date,
"version": SyncTelemetry.telemetryVersion,
"application": [
"architecture": "arm",
"buildId": AppInfo.buildNumber,
"name": AppInfo.displayName,
"version": AppInfo.appVersion,
"displayVersion": displayVersion,
"platformVersion": osVersion,
"channel": AppConstants.BuildChannel.rawValue
]
]
}
}
public protocol SyncTelemetryPing {
var payload: JSON { get }
}
| mpl-2.0 | 86d9b7bcce3d11111cc08431002ab8f9 | 33.433333 | 114 | 0.620523 | 4.776879 | false | false | false | false |
MadAppGang/SmartLog | iOS/Pods/CoreStore/Sources/CSBaseDataTransaction.swift | 2 | 10005 | //
// CSBaseDataTransaction.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// 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 CoreData
// MARK: - CSBaseDataTransaction
/**
The `CSBaseDataTransaction` serves as the Objective-C bridging type for `BaseDataTransaction`.
- SeeAlso: `BaseDataTransaction`
*/
@objc
public class CSBaseDataTransaction: NSObject {
// MARK: Object management
/**
Indicates if the transaction has pending changes
*/
@objc
public var hasChanges: Bool {
return self.swiftTransaction.hasChanges
}
/**
Creates a new `NSManagedObject` with the specified entity type.
- parameter into: the `CSInto` clause indicating the destination `NSManagedObject` entity type and the destination configuration
- returns: a new `NSManagedObject` instance of the specified entity type.
*/
@objc
public func createInto(_ into: CSInto) -> Any {
return self.swiftTransaction.create(into.bridgeToSwift)
}
/**
Returns an editable proxy of a specified `NSManagedObject`.
- parameter object: the `NSManagedObject` type to be edited
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@objc
public func editObject(_ object: NSManagedObject?) -> Any? {
return self.swiftTransaction.edit(object)
}
/**
Returns an editable proxy of the object with the specified `NSManagedObjectID`.
- parameter into: a `CSInto` clause specifying the entity type
- parameter objectID: the `NSManagedObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@objc
public func editInto(_ into: CSInto, objectID: NSManagedObjectID) -> Any? {
return self.swiftTransaction.edit(into.bridgeToSwift, objectID)
}
/**
Deletes a specified `NSManagedObject`.
- parameter object: the `NSManagedObject` to be deleted
*/
@objc
public func deleteObject(_ object: NSManagedObject?) {
self.swiftTransaction.delete(object)
}
/**
Deletes the specified `NSManagedObject`s.
- parameter objects: the `NSManagedObject`s to be deleted
*/
@objc
public func deleteObjects(_ objects: [NSManagedObject]) {
self.swiftTransaction.delete(objects)
}
/**
Refreshes all registered objects `NSManagedObject`s in the transaction.
*/
@objc
public func refreshAndMergeAllObjects() {
self.swiftTransaction.refreshAndMergeAllObjects()
}
// MARK: Inspecting Pending Objects
/**
Returns all pending `NSManagedObject`s of the specified type that were inserted to the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: an `NSSet` of pending `NSManagedObject`s of the specified type that were inserted to the transaction.
*/
@objc
public func insertedObjectsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObject> {
return self.swiftTransaction.insertedObjects(entity)
}
/**
Returns all pending `NSManagedObjectID`s that were inserted to the transaction. This method should not be called after the `-commit*:` method was called.
- returns: an `NSSet` of pending `NSManagedObjectID`s that were inserted to the transaction.
*/
@objc
public func insertedObjectIDs() -> Set<NSManagedObjectID> {
return self.swiftTransaction.insertedObjectIDs()
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were inserted to the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: an `NSSet` of pending `NSManagedObjectID`s of the specified type that were inserted to the transaction.
*/
@objc
public func insertedObjectIDsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
return self.swiftTransaction.insertedObjectIDs(entity)
}
/**
Returns all pending `NSManagedObject`s of the specified type that were updated in the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: an `NSSet` of pending `NSManagedObject`s of the specified type that were updated in the transaction.
*/
@objc
public func updatedObjectsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObject> {
return self.swiftTransaction.updatedObjects(entity)
}
/**
Returns all pending `NSManagedObjectID`s that were updated in the transaction. This method should not be called after the `-commit*:` method was called.
- returns: an `NSSet` of pending `NSManagedObjectID`s that were updated in the transaction.
*/
@objc
public func updatedObjectIDs() -> Set<NSManagedObjectID> {
return self.swiftTransaction.updatedObjectIDs()
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were updated in the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: an `NSSet` of pending `NSManagedObjectID`s of the specified type that were updated in the transaction.
*/
@objc
public func updatedObjectIDsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
return self.swiftTransaction.updatedObjectIDs(entity)
}
/**
Returns all pending `NSManagedObject`s of the specified type that were deleted from the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: an `NSSet` of pending `NSManagedObject`s of the specified type that were deleted from the transaction.
*/
@objc
public func deletedObjectsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObject> {
return self.swiftTransaction.deletedObjects(entity)
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were deleted from the transaction. This method should not be called after the `-commit*:` method was called.
- returns: an `NSSet` of pending `NSManagedObjectID`s of the specified type that were deleted from the transaction.
*/
@objc
public func deletedObjectIDs() -> Set<NSManagedObjectID> {
return self.swiftTransaction.deletedObjectIDs()
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were deleted from the transaction. This method should not be called after the `-commit*:` method was called.
- parameter entity: the `NSManagedObject` subclass to filter
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were deleted from the transaction.
*/
@objc
public func deletedObjectIDsOfType(_ entity: NSManagedObject.Type) -> Set<NSManagedObjectID> {
return self.swiftTransaction.deletedObjectIDs(entity)
}
// MARK: NSObject
public override var hash: Int {
return ObjectIdentifier(self.swiftTransaction).hashValue
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSBaseDataTransaction else {
return false
}
return self.swiftTransaction === object.swiftTransaction
}
// MARK: Internal
internal let swiftTransaction: BaseDataTransaction
internal init(_ swiftValue: BaseDataTransaction) {
self.swiftTransaction = swiftValue
super.init()
}
// MARK: Deprecated
@available(*, deprecated, message: "Use -[insertedObjectsOfType:] and pass the specific entity class")
@objc
public func insertedObjects() -> Set<NSManagedObject> {
return self.swiftTransaction.insertedObjects()
}
@available(*, deprecated, message: "Use -[updatedObjectsOfType:] and pass the specific entity class")
@objc
public func updatedObjects() -> Set<NSManagedObject> {
return self.swiftTransaction.updatedObjects()
}
@available(*, deprecated, message: "Use -[deletedObjectsOfType:] and pass the specific entity class")
@objc
public func deletedObjects() -> Set<NSManagedObject> {
return self.swiftTransaction.deletedObjects()
}
}
| mit | 798a6315e98cd09ad89755ae97ee5649 | 34.985612 | 181 | 0.679628 | 5.218571 | false | false | false | false |
hkellaway/Gloss | Sources/Gloss/ExtensionDictionary.swift | 1 | 3846 | //
// ExtensionDictionary.swift
// Gloss
//
// Copyright (c) 2015 Harlan Kellaway
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Dictionary {
// MARK: - Public Functions
/**
Retrieves value from dictionary given a key path delimited with
provided delimiter to indicate a nested value.
For example, a dictionary with [ "outer" : [ "inner" : "value" ] ]
could retrive 'value' via path "outer.inner", given a
delimiter of ''.
- parameter keyPath: Key path delimited by delimiter.
- parameter delimiter: Delimiter.
- parameter logger: Logger.
- returns: Value retrieved from dic
*/
public func valueForKeyPath(keyPath: String, withDelimiter delimiter: String = GlossKeyPathDelimiter, logger: Logger = GlossLogger()) -> Any? {
let keys = keyPath.components(separatedBy: delimiter)
guard keys.first as? Key != nil else {
logger.log(message: "Unable to use keyPath '\(keyPath)' as key on type: \(Key.self)")
return nil
}
return self.findValue(keys: keys)
}
// MARK: - Internal functions
/**
Creates a dictionary from a list of elements.
This allows use of map, flatMap and filter.
- parameter elements: Elements to add to the new dictionary.
*/
internal init(elements: [Element]) {
self.init()
for (key, value) in elements {
self[key] = value
}
}
/**
Flat map for dictionary.
- parameter transform: Transform function.
- returns: New dictionary of transformed values.
*/
internal func flatMap<KeyPrime : Hashable, ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime : ValuePrime] {
return Dictionary<KeyPrime,ValuePrime>(elements: try compactMap({ (key, value) in
return try transform(key, value)
}))
}
// MARK: - Private functions
/**
Retrieves value from dictionary given a key path delimited with
provided delimiter by going down the dictionary stack tree
- parameter keys: Array of keys splited by delimiter
- parameter depthLevel: Indicates current depth level in the dictionary tree
- returns: object retrieved from dic
*/
private func findValue(keys: [String], depthLevel: Int = 0) -> Any? {
if let currentKey = keys[depthLevel] as? Key {
if depthLevel == keys.count-1 {
return self[currentKey]
} else if let newDict = self[currentKey] as? Dictionary {
return newDict.findValue(keys: keys, depthLevel: depthLevel+1)
}
}
return nil
}
}
| mit | 4116c042d7190918d3b6ac309caabe79 | 34.943925 | 157 | 0.651846 | 4.801498 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/Filter/FilterSheetViewController.swift | 1 | 1299 | class FilterSheetViewController: UIViewController {
private let viewTitle: String
private let filters: [FilterProvider]
private let changedFilter: (ReaderAbstractTopic) -> Void
init(viewTitle: String,
filters: [FilterProvider],
changedFilter: @escaping (ReaderAbstractTopic) -> Void) {
self.viewTitle = viewTitle
self.filters = filters
self.changedFilter = changedFilter
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = FilterSheetView(viewTitle: viewTitle,
filters: filters,
presentationController: self,
changedFilter: changedFilter)
}
}
extension FilterSheetViewController: DrawerPresentable {
func handleDismiss() {
WPAnalytics.track(.readerFilterSheetDismissed)
}
var scrollableView: UIScrollView? {
return (view as? FilterSheetView)?.tableView
}
var collapsedHeight: DrawerHeight {
if traitCollection.verticalSizeClass == .compact {
return .maxHeight
} else {
return .contentHeight(0)
}
}
}
| gpl-2.0 | 9e9b422841609549a95fc4ca23ca1fad | 28.522727 | 66 | 0.617398 | 5.504237 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | the-blue-alliance-ios/View Controllers/MyTBA/MyTBAViewController.swift | 1 | 8351 | import CoreData
import FirebaseAuth
import GoogleSignIn
import MyTBAKit
import Photos
import PureLayout
import TBAData
import TBAKit
import UIKit
import UserNotifications
class MyTBAViewController: ContainerViewController {
private let myTBA: MyTBA
private let pasteboard: UIPasteboard?
private let photoLibrary: PHPhotoLibrary?
private let statusService: StatusService
private let urlOpener: URLOpener
private(set) var signInViewController: MyTBASignInViewController = MyTBASignInViewController()
private(set) var favoritesViewController: MyTBATableViewController<Favorite, MyTBAFavorite>
private(set) var subscriptionsViewController: MyTBATableViewController<Subscription, MyTBASubscription>
private var signInView: UIView! {
return signInViewController.view
}
private lazy var signOutBarButtonItem: UIBarButtonItem = {
return UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(logoutTapped))
}()
private var signOutActivityIndicatorBarButtonItem = UIBarButtonItem.activityIndicatorBarButtonItem()
var isLoggingOut: Bool = false {
didSet {
DispatchQueue.main.async {
self.updateInterface()
}
}
}
private var isLoggedIn: Bool {
return myTBA.isAuthenticated
}
init(myTBA: MyTBA, pasteboard: UIPasteboard? = nil, photoLibrary: PHPhotoLibrary? = nil, statusService: StatusService, urlOpener: URLOpener, dependencies: Dependencies) {
self.myTBA = myTBA
self.pasteboard = pasteboard
self.photoLibrary = photoLibrary
self.statusService = statusService
self.urlOpener = urlOpener
favoritesViewController = MyTBATableViewController<Favorite, MyTBAFavorite>(myTBA: myTBA, dependencies: dependencies)
subscriptionsViewController = MyTBATableViewController<Subscription, MyTBASubscription>(myTBA: myTBA, dependencies: dependencies)
super.init(viewControllers: [favoritesViewController, subscriptionsViewController],
segmentedControlTitles: ["Favorites", "Subscriptions"],
dependencies: dependencies)
title = RootType.myTBA.title
tabBarItem.image = RootType.myTBA.icon
favoritesViewController.delegate = self
subscriptionsViewController.delegate = self
GIDSignIn.sharedInstance()?.presentingViewController = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// TODO: Fix the white status bar/white UINavigationController during sign in
// https://github.com/the-blue-alliance/the-blue-alliance-ios/issues/180
// modalPresentationCapturesStatusBarAppearance = true
styleInterface()
myTBA.authenticationProvider.add(observer: self)
}
// MARK: - Private Methods
private func styleInterface() {
addChild(signInViewController)
view.addSubview(signInView)
for edge in [ALEdge.top, ALEdge.bottom] {
signInView.autoPinEdge(toSuperviewSafeArea: edge)
}
for edge in [ALEdge.leading, ALEdge.trailing] {
signInView.autoPinEdge(toSuperviewEdge: edge)
}
updateInterface()
}
private func updateInterface() {
if isLoggingOut {
rightBarButtonItems = [signOutActivityIndicatorBarButtonItem]
} else {
rightBarButtonItems = isLoggedIn ? [signOutBarButtonItem] : []
}
// Disable interaction with our view while logging out
view.isUserInteractionEnabled = !isLoggingOut
signInView.isHidden = isLoggedIn
}
private func logout() {
let signOutOperation = myTBA.unregister { [weak self] (_, error) in
self?.isLoggingOut = false
if let error = error as? MyTBAError, error.code != 404 {
self?.errorRecorder.record(error)
self?.showErrorAlert(with: "Unable to sign out of myTBA - \(error.localizedDescription)")
} else {
// Run on main thread, since we delete our Core Data objects on the main thread.
DispatchQueue.main.async {
self?.logoutSuccessful()
}
}
}
guard let op = signOutOperation else { return }
isLoggingOut = true
OperationQueue.main.addOperation(op)
}
private func logoutSuccessful() {
GIDSignIn.sharedInstance().signOut()
try! Auth.auth().signOut()
// Cancel any ongoing requests
for vc in [favoritesViewController, subscriptionsViewController] as! [Refreshable] {
vc.cancelRefresh()
}
// Remove all locally stored myTBA data
removeMyTBAData()
}
func removeMyTBAData() {
persistentContainer.viewContext.deleteAllObjectsForEntity(entity: Favorite.entity())
persistentContainer.viewContext.deleteAllObjectsForEntity(entity: Subscription.entity())
// Clear notifications
persistentContainer.viewContext.performSaveOrRollback(errorRecorder: errorRecorder)
}
// MARK: - Interface Methods
@objc func logoutTapped() {
let signOutAlertController = UIAlertController(title: "Log Out?", message: "Are you sure you want to sign out of myTBA?", preferredStyle: .alert)
signOutAlertController.addAction(UIAlertAction(title: "Log Out", style: .default, handler: { (_) in
self.logout()
}))
signOutAlertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(signOutAlertController, animated: true, completion: nil)
}
}
extension MyTBAViewController: MyTBATableViewControllerDelegate {
func eventSelected(_ event: Event) {
let viewController = EventViewController(event: event, pasteboard: pasteboard, photoLibrary: photoLibrary, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, dependencies: dependencies)
if let splitViewController = splitViewController {
let navigationController = UINavigationController(rootViewController: viewController)
splitViewController.showDetailViewController(navigationController, sender: nil)
} else if let navigationController = navigationController {
navigationController.pushViewController(viewController, animated: true)
}
}
func teamSelected(_ team: Team) {
let viewController = TeamViewController(team: team, pasteboard: pasteboard, photoLibrary: photoLibrary, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, dependencies: dependencies)
if let splitViewController = splitViewController {
let navigationController = UINavigationController(rootViewController: viewController)
splitViewController.showDetailViewController(navigationController, sender: nil)
} else if let navigationController = navigationController {
navigationController.pushViewController(viewController, animated: true)
}
}
func matchSelected(_ match: Match) {
let viewController = MatchViewController(match: match, pasteboard: pasteboard, photoLibrary: photoLibrary, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, dependencies: dependencies)
if let splitViewController = splitViewController {
let navigationController = UINavigationController(rootViewController: viewController)
splitViewController.showDetailViewController(navigationController, sender: nil)
} else if let navigationController = navigationController {
navigationController.pushViewController(viewController, animated: true)
}
}
}
extension MyTBAViewController: MyTBAAuthenticationObservable {
@objc func authenticated() {
if let viewController = currentViewController() {
viewController.refresh()
}
updateInterfaceMain()
}
@objc func unauthenticated() {
updateInterfaceMain()
}
func updateInterfaceMain() {
DispatchQueue.main.async { [weak self] in
self?.updateInterface()
}
}
}
| mit | ca54f8d07529757f58c40c8dbccd3fd8 | 36.959091 | 208 | 0.691654 | 5.82357 | false | false | false | false |
nghialv/Sapporo | Sapporo/Sources/Core/Sapporo+UIScrollViewDelegate.swift | 1 | 2077 | //
// Sapporo+UIScrollViewDelegate.swift
// Example
//
// Created by Le VanNghia on 4/3/16.
// Copyright © 2016 Le Van Nghia. All rights reserved.
//
import UIKit
extension Sapporo {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
delegate?.scrollViewDidScroll?(scrollView)
guard loadmoreEnabled else {
return
}
let offset = scrollView.contentOffset
let y = direction == .vertical ? offset.y + scrollView.bounds.height - scrollView.contentInset.bottom : offset.x + scrollView.bounds.width - scrollView.contentInset.right
let h = direction == .vertical ? scrollView.contentSize.height : scrollView.contentSize.width
if y > h - loadmoreDistanceThreshold {
loadmoreEnabled = false
loadmoreHandler?()
}
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
delegate?.scrollViewWillBeginDragging?(scrollView)
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
delegate?.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
delegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate)
}
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
delegate?.scrollViewWillBeginDecelerating?(scrollView)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
delegate?.scrollViewDidEndDecelerating?(scrollView)
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
delegate?.scrollViewDidEndScrollingAnimation?(scrollView)
}
public func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
delegate?.scrollViewDidScrollToTop?(scrollView)
}
}
| mit | 041d6706f41e4bee7bf32579c4f4cebf | 36.745455 | 178 | 0.708574 | 6.105882 | false | false | false | false |
jhwayne/Minimo | SwifferApp/SwifferApp/ComposeViewController.swift | 1 | 2928 | //
// ComposeViewController.swift
// SwifferApp
//
// Created by Training on 29/06/14.
// Copyright (c) 2014 Training. All rights reserved.
//
import UIKit
class ComposeViewController: UIViewController, UITextViewDelegate {
@IBOutlet var sweetTextView: UITextView! = UITextView()
@IBOutlet var charRemainingLabel: UILabel! = UILabel()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
sweetTextView.layer.borderColor = UIColor.blackColor().CGColor
sweetTextView.layer.borderWidth = 0.5
sweetTextView.layer.cornerRadius = 5
sweetTextView.delegate = self
sweetTextView.becomeFirstResponder()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sendSweet(sender: AnyObject) {
var query = PFQuery(className:"Posts")
query.whereKey("DisplayToday", equalTo:"Yes")
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject!, error: NSError!) -> Void in
if (error != nil || object == nil) {
}
else {
// The find succeeded.
let ID = object["PostID"] as Int
var sweet:PFObject = PFObject(className: "Sweets")
sweet["content"] = self.sweetTextView.text
sweet["sweeter"] = PFUser.currentUser()
sweet["PostID"] = ID
sweet.saveInBackground()
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}
func textView(textView: UITextView!,
shouldChangeTextInRange range: NSRange,
replacementText text: String!) -> Bool{
var newLength:Int = (textView.text as NSString).length + (text as NSString).length - range.length
var remainingChar:Int = 140 - newLength
charRemainingLabel.text = "\(remainingChar)"
return (newLength > 140) ? false : true
}
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | e3c1582f52a1a0ec4b3d9dcb83b4d284 | 29.5 | 109 | 0.599044 | 5.483146 | false | false | false | false |
yarec/FeedParser | FeedParser/FeedParser.swift | 1 | 14024 | //
// FeedParser.swift
// FeedParser
//
// Created by Andreas Geitmann on 18.11.14.
// Copyright (c) 2014 simutron IT-Service. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public protocol FeedParserDelegate {
func didStartFeedParsing(parser:FeedParser)
func didFinishFeedParsing(parser:FeedParser, newsFeed:NewsFeed?)
func anErrorOccured(parser:FeedParser, error:NSError)
}
enum ParseMode {
case FEED, ENTRY, IMAGE
}
public class FeedParser: NSObject, NSXMLParserDelegate {
public var newsFeed:NewsFeed = NewsFeed()
public var delegate:FeedParserDelegate?
var parseMode:ParseMode = ParseMode.FEED
var currentContent:String = ""
var tmpEntry:NewsFeedEntry = NewsFeedEntry()
var lastParseMode:ParseMode?
var tmpImage:NewsImage?
// MARK: - Public Functions
public func parseFeedFromUrl(urlString:String) {
self.delegate?.didStartFeedParsing(self)
self.newsFeed.url = urlString
var feedUrl = NSURL(string: urlString)
var parser = NSXMLParser(contentsOfURL: feedUrl!)
parser?.delegate = self
parser?.parse()
}
public func parseFeedFromFile(fileString:String) {
self.delegate?.didStartFeedParsing(self)
self.newsFeed.url = fileString
let feedUrl = NSURL(fileURLWithPath: fileString)
let parser = NSXMLParser(contentsOfURL: feedUrl)
parser?.delegate = self
parser?.parse()
}
// MARK: - NSXMLParserDelegate
public func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
self.currentContent = ""
switch self.newsFeed.feedType {
case FeedType.ATOM:
switch elementName {
case "entry":
self.tmpEntry = NewsFeedEntry()
self.parseMode = ParseMode.ENTRY
case "link":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.link = attributeDict["href"]! //as! String
break
case ParseMode.ENTRY:
self.tmpEntry.link = attributeDict["href"]! //as! String
break
case ParseMode.IMAGE:
break
}
case "enclosure", "media:content":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
break
case ParseMode.IMAGE:
self.lastParseMode = self.parseMode
self.parseMode = ParseMode.IMAGE
self.tmpImage = NewsImage()
self.tmpImage?.url = attributeDict["url"]! //as! String
}
case "title", "updated", "id", "summary", "content", "author", "name":
// Element is not needed for parsing
break
default:
log("ATOM Element's name is \(elementName)")
log("ATOM Element's attributes are \(attributeDict)")
}
case FeedType.RSS:
switch elementName {
case "item":
self.tmpEntry = NewsFeedEntry()
self.parseMode = ParseMode.ENTRY
case "image":
self.lastParseMode = self.parseMode
self.parseMode = ParseMode.IMAGE
self.tmpImage = NewsImage()
case "enclosure", "media:content":
self.lastParseMode = self.parseMode
self.parseMode = ParseMode.IMAGE
self.tmpImage = NewsImage()
self.tmpImage?.url = attributeDict["url"]! //as! String
default:
log("Element's name is \(elementName)")
log("Element's attributes are \(attributeDict)")
}
default:
switch elementName {
case "feed":
self.newsFeed.feedType = FeedType.ATOM
case "channel":
self.newsFeed.feedType = FeedType.RSS
case "title", "updated", "id", "summary", "content":
// Element is not needed for parsing
break
default:
log("RSS Element's name is \(elementName)")
log("RSS Element's attributes are \(attributeDict)")
}
}
}
public func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName:String?) {
switch self.newsFeed.feedType {
case FeedType.ATOM:
switch elementName {
case "title":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.title = self.currentContent
case ParseMode.ENTRY:
self.tmpEntry.title = self.currentContent
case ParseMode.IMAGE:
self.tmpImage?.title = self.currentContent
break
}
case "updated":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.lastUpdated = self.parseRFC3339DateFromString(self.currentContent)
break
case ParseMode.ENTRY:
self.tmpEntry.lastUpdated = self.parseRFC3339DateFromString(self.currentContent)
break
case ParseMode.IMAGE:
break
}
case "id":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.id = self.currentContent
break
case ParseMode.ENTRY:
self.tmpEntry.id = self.currentContent
break
case ParseMode.IMAGE:
break
}
case "summary":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
self.tmpEntry.summary = self.currentContent
break
case ParseMode.IMAGE:
break
}
case "content":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
self.tmpEntry.content = self.currentContent
break
case ParseMode.IMAGE:
break
}
case "entry":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
self.newsFeed.entries[self.tmpEntry.id] = self.tmpEntry
break
case ParseMode.IMAGE:
break
}
case "image", "enclosure", "media:content":
self.parseMode = self.lastParseMode!
if (self.parseMode == ParseMode.FEED) {
self.newsFeed.images.append(self.tmpImage!)
} else if (self.parseMode == ParseMode.ENTRY) {
self.tmpEntry.images.append(self.tmpImage!)
}
case "link", "feed", "author", "name":
// Content not used, value is stored in attribute
break
default:
log("UNKNOWN END ATOM Element \(elementName)")
}
case FeedType.RSS:
switch elementName {
case "guid":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.id = self.currentContent
case ParseMode.ENTRY:
self.tmpEntry.id = self.currentContent
case ParseMode.IMAGE:
break
}
case "link":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.link = self.currentContent
case ParseMode.ENTRY:
self.tmpEntry.link = self.currentContent
case ParseMode.IMAGE:
self.tmpImage?.link? = self.currentContent
}
case "title":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.title = self.currentContent
case ParseMode.ENTRY:
self.tmpEntry.title = self.currentContent
case ParseMode.IMAGE:
self.tmpImage?.title? = self.currentContent
}
case "url":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
break
case ParseMode.IMAGE:
self.tmpImage?.url = self.currentContent
}
case "description":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.summary = self.currentContent
break
case ParseMode.ENTRY:
self.tmpEntry.summary = self.currentContent
break
case ParseMode.IMAGE:
break
}
case "pubDate":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.lastUpdated = self.parseRFC822DateFromString(self.currentContent)
break
case ParseMode.ENTRY:
self.tmpEntry.lastUpdated = self.parseRFC822DateFromString(self.currentContent)
break
case ParseMode.IMAGE:
break
}
case "language":
switch self.parseMode {
case ParseMode.FEED:
self.newsFeed.language = self.currentContent
case ParseMode.ENTRY:
break
case ParseMode.IMAGE:
break
}
case "image", "enclosure", "media:content":
self.parseMode = self.lastParseMode!
if (self.parseMode == ParseMode.FEED) {
self.newsFeed.images.append(self.tmpImage!)
} else if (self.parseMode == ParseMode.ENTRY) {
self.tmpEntry.images.append(self.tmpImage!)
}
case "item":
switch self.parseMode {
case ParseMode.FEED:
break
case ParseMode.ENTRY:
if self.tmpEntry.id.isEmpty {
self.newsFeed.entries[self.tmpEntry.link] = self.tmpEntry
} else {
self.newsFeed.entries[self.tmpEntry.id] = self.tmpEntry
}
break
case ParseMode.IMAGE:
break
}
case "channel", "rss":
// Content not used, value is stored in attribute
break
default:
log("UNKNOWN END RSS Element \(elementName)")
}
default:
log("UNKNOWN feedType \(self.newsFeed.feedType)")
}
}
public func parser(parser: NSXMLParser, foundCharacters string: String?) {
self.currentContent += string!
}
public func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
log("Error: \(parseError.description)")
self.delegate?.anErrorOccured(self, error: parseError)
}
public func parserDidEndDocument(parser: NSXMLParser) {
self.delegate?.didFinishFeedParsing(self, newsFeed: self.newsFeed)
}
// MARK: - Private Functions
private func parseRFC3339DateFromString(string:String) -> NSDate {
let enUSPOSIXLocale = NSLocale(localeIdentifier: "en_US_POSIX")
let rfc3339DateFormatter = NSDateFormatter()
rfc3339DateFormatter.locale = enUSPOSIXLocale
rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
rfc3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let date:NSDate? = rfc3339DateFormatter.dateFromString(string)
if let isDate = date {
return isDate
}
return NSDate()
}
private func parseRFC822DateFromString(string:String) -> NSDate {
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
let date:NSDate? = dateFormat.dateFromString(string)
if let isDate = date {
return isDate
}
return NSDate()
}
private func log(str:String){
// println(str)
}
}
| apache-2.0 | 7c637b8317d7ef2afb47cf0ef96ce149 | 36.698925 | 180 | 0.507772 | 5.853088 | false | false | false | false |
pankcuf/DataContext | DataContext/Classes/TableDataImpl.swift | 1 | 4842 | //
// TableDataImpl.swift
// DataContext
//
// Created by Vladimir Pirogov on 27/03/17.
// Copyright © 2016 Vladimir Pirogov. All rights reserved.
//
import Foundation
import UIKit
open class TableDataImpl: NSObject, UITableViewDataSource, UITableViewDelegate {
/// Table Delegates
@objc(tableView:heightForRowAtIndexPath:) open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let ctx = tableView.tableView(tableView, contextForRowAt: indexPath)
return ctx?.getDefaultHeight() ?? 0
}
@objc(tableView:estimatedHeightForRowAtIndexPath:) open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
let ctx = tableView.tableView(tableView, contextForRowAt: indexPath)
return ctx?.getDefaultHeight() ?? 0
}
@objc(tableView:willDisplayCell:forRowAtIndexPath:) open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard self.tableView(tableView, heightForRowAt: indexPath) != UITableViewAutomaticDimension else { return }
cell.context = tableView.tableView(tableView, contextForRowAt: indexPath)
cell.contextDelegate = tableView
}
open func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let headerSectionContext = tableView.tableView(tableView, contextFor: section)?.headerContext,
headerSectionContext.getDefaultHeight() != UITableViewAutomaticDimension else { return }
view.context = headerSectionContext
view.contextDelegate = tableView
}
open func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
guard let footerSectionContext = tableView.tableView(tableView, contextFor: section)?.footerContext,
footerSectionContext.getDefaultHeight() != UITableViewAutomaticDimension else { return }
view.context = footerSectionContext
view.contextDelegate = tableView
}
@objc(numberOfSectionsInTableView:) open func numberOfSections(in tableView: UITableView) -> Int {
return tableView.tableDataContext()?.sectionContext.count ?? 0
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableView.tableView(tableView, contextFor: section)?.rowContext.count ?? 0
}
@objc(tableView:cellForRowAtIndexPath:) open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = indexPath.section
let row = indexPath.row
let ctx = tableView.tableView(tableView, contextFor: section)!
let rows = ctx.rowContext
let cellContext = rows[row]
let reuseId = cellContext.reuseId
let cell = tableView.dequeueReusableCell(withIdentifier: reuseId)!
if self.tableView(tableView, heightForRowAt: indexPath) == UITableViewAutomaticDimension {
cell.context = tableView.tableView(tableView, contextForRowAt: indexPath)
cell.contextDelegate = tableView
cell.contentView.setNeedsLayout()
cell.contentView.layoutIfNeeded()
}
return cell
}
open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let headerSectionContext = tableView.tableView(tableView, contextFor: section)?.headerContext {
if let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerSectionContext.reuseId) {
if self.tableView(tableView, heightForHeaderInSection: section) == UITableViewAutomaticDimension {
header.context = headerSectionContext
header.contextDelegate = tableView
header.contentView.setNeedsLayout()
header.contentView.layoutIfNeeded()
}
return header
}
}
return nil
}
open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if let footerSectionContext = tableView.tableView(tableView, contextFor: section)?.footerContext {
if let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: footerSectionContext.reuseId) {
if self.tableView(tableView, heightForFooterInSection: section) == UITableViewAutomaticDimension {
footer.context = footerSectionContext
footer.contextDelegate = tableView
footer.contentView.setNeedsLayout()
footer.contentView.layoutIfNeeded()
}
return footer
}
}
return nil
}
open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return tableView.tableView(tableView, contextFor: section)?.headerContext?.getDefaultHeight() ?? 0
}
open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return tableView.tableView(tableView, contextFor: section)?.footerContext?.getDefaultHeight() ?? 0
}
}
| mit | 338adad7a895aaf81ffd1c041e1318a9 | 33.091549 | 166 | 0.757488 | 5.037461 | false | false | false | false |
slightair/ff14booklet | iOS/ff14booklet/WeatherForecastLocationCell.swift | 1 | 1251 | //
// WeatherForecastLocationCell.swift
// ff14booklet
//
// Created by tomohiro-moro on 9/14/14.
// Copyright (c) 2014 slightair. All rights reserved.
//
import UIKit
class WeatherForecastLocationCell: UITableViewCell {
@IBOutlet var locationLabel: UILabel!
@IBOutlet var forecastImageView1: UIImageView!
@IBOutlet var forecastImageView2: UIImageView!
@IBOutlet var forecastImageView3: UIImageView!
@IBOutlet var forecastImageView4: UIImageView!
@IBOutlet var forecastLabel1: UILabel!
@IBOutlet var forecastLabel2: UILabel!
@IBOutlet var forecastLabel3: UILabel!
@IBOutlet var forecastLabel4: UILabel!
func updateWithLocation(location: WeatherForecastLocation) {
self.locationLabel.text = location.location.title()
for i in 1...4 {
let imageView = self.valueForKey("forecastImageView\(i)") as? UIImageView
let label = self.valueForKey("forecastLabel\(i)") as? UILabel
let weather = location.forecasts[i - 1]
label?.text = weather.title()
if let imageURL = weather.imageURL() {
imageView?.sd_setImageWithURL(imageURL)
} else {
imageView?.image = nil
}
}
}
}
| mit | 89515cd5d001575db63151eb4f4ed8c4 | 31.921053 | 85 | 0.661871 | 4.516245 | false | false | false | false |
ngageoint/mage-ios | Mage/ObservationFormReorder.swift | 1 | 6765 | //
// ObservationFormReorder.swift
// MAGE
//
// Created by Daniel Barela on 1/19/21.
// Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import MaterialComponents.MDCContainerScheme;
@objc protocol ObservationFormReorderDelegate {
func formsReordered(observation: Observation);
func cancelReorder();
}
class ObservationFormReorder: UITableViewController {
let cellReuseIdentifier = "formCell";
let observation: Observation;
let delegate: ObservationFormReorderDelegate;
var observationForms: [[String: Any]] = [];
var observationProperties: [String: Any] = [ : ];
var scheme: MDCContainerScheming?;
private lazy var event: Event? = {
guard let eventId = observation.eventId, let context = observation.managedObjectContext else {
return nil
}
return Event.getEvent(eventId: eventId, context: context)
}()
private lazy var eventForms: [Form]? = {
return event?.forms
}()
private lazy var descriptionHeaderView: UILabel = {
let label = UILabel(forAutoLayout: ());
label.text = "The first form in this list is the primary form, which determines how MAGE displays the observation on the map and in the feed. The forms will be displayed, as ordered, in all other views.";
label.numberOfLines = 0;
label.lineBreakMode = .byWordWrapping;
return label;
}()
private lazy var headerView: UIView = {
let view = UIView();
view.addSubview(descriptionHeaderView);
descriptionHeaderView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8))
return view;
}()
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(observation: Observation, delegate: ObservationFormReorderDelegate, containerScheme: MDCContainerScheming?) {
self.observation = observation
self.delegate = delegate;
self.scheme = containerScheme;
super.init(style: .grouped)
self.title = "Reorder Forms";
self.view.accessibilityLabel = "Reorder Forms";
tableView.register(cellClass: ObservationFormTableViewCell.self)
if let properties = self.observation.properties as? [String: Any] {
if (properties.keys.contains(ObservationKey.forms.key)) {
observationForms = properties[ObservationKey.forms.key] as! [[String: Any]];
}
self.observationProperties = properties;
} else {
self.observationProperties = [ObservationKey.forms.key:[]];
observationForms = [];
}
}
func applyTheme(withContainerScheme containerScheme: MDCContainerScheming?) {
guard let containerScheme = containerScheme else {
return
}
self.scheme = containerScheme;
self.tableView.backgroundColor = containerScheme.colorScheme.backgroundColor;
self.view.backgroundColor = containerScheme.colorScheme.backgroundColor;
self.descriptionHeaderView.font = containerScheme.typographyScheme.overline;
self.descriptionHeaderView.textColor = containerScheme.colorScheme.onBackgroundColor.withAlphaComponent(0.6)
}
override func viewDidLoad() {
super.viewDidLoad();
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Apply", style: .done, target: self, action: #selector(self.saveFormOrder(sender:)));
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(self.cancel(sender:)));
self.tableView.isEditing = true;
self.tableView.rowHeight = UITableView.automaticDimension;
self.tableView.estimatedRowHeight = 64;
self.tableView.tableFooterView = UIView();
self.view.addSubview(headerView);
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
applyTheme(withContainerScheme: scheme);
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let newSize = headerView.systemLayoutSizeFitting(CGSize(width: self.tableView.bounds.width, height: 0), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
headerView.autoSetDimensions(to: newSize);
tableView.contentInset = UIEdgeInsets(top: headerView.frame.size.height, left: 0, bottom: 0, right: 0);
headerView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: -1 * newSize.height, left: 0, bottom: 0, right: 0), excludingEdge: .bottom);
}
@objc func cancel(sender: UIBarButtonItem) {
delegate.cancelReorder();
}
@objc func saveFormOrder(sender: UIBarButtonItem) {
observationProperties[ObservationKey.forms.key] = observationForms;
self.observation.properties = observationProperties;
delegate.formsReordered(observation: self.observation);
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Drag to reorder forms";
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObject = self.observationForms[sourceIndexPath.row]
observationForms.remove(at: sourceIndexPath.row)
observationForms.insert(movedObject, at: destinationIndexPath.row)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return observationForms.count;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let formCell : ObservationFormTableViewCell = tableView.dequeue(cellClass: ObservationFormTableViewCell.self, forIndexPath: indexPath);
let observationForm = observationForms[indexPath.row];
if let eventForm: Form = self.eventForms?.first(where: { (form) -> Bool in
return form.formId?.intValue == observationForm[EventKey.formId.key] as? Int
}) {
formCell.configure(observationForm: observationForm, eventForm: eventForm, scheme: self.scheme);
}
return formCell
}
}
| apache-2.0 | 56c35c3ea107a38b53557604240de787 | 41.540881 | 212 | 0.68835 | 5.30094 | false | false | false | false |
andrewBatutin/SwiftYamp | SwiftYamp/Models/CloseFrame.swift | 1 | 2492 | //
// CloseFrame.swift
// SwiftYamp
//
// Created by Andrey Batutin on 6/13/17.
// Copyright © 2017 Andrey Batutin. All rights reserved.
//
import Foundation
import ByteBackpacker
public enum CloseCodeType: UInt8{
case Unknown = 0x00
case VersionNotSupported = 0x01
case Timeout = 0x02
case Redirect = 0x03
}
public struct CloseFrame: Equatable, YampFrame, YampTypedFrame{
private let typeIndex = 0x00
private let closeCodeIndex = 0x01
private let sizeIndex = 0x02
private let messageIndex = 0x04
public var frameType:FrameType{
return type.type
}
let type:BaseFrame = BaseFrame(type: FrameType.Close)
let closeCode:CloseCodeType
let size:UInt16
var message:String = "" // (optional)
public static func ==(lhs: CloseFrame, rhs: CloseFrame) -> Bool {
return lhs.type == rhs.type && lhs.closeCode == rhs.closeCode && lhs.size == rhs.size && lhs.message == rhs.message
}
public init(closeCode: CloseCodeType) {
self.closeCode = closeCode
self.size = 0
}
public init(closeCode: CloseCodeType, message: String?) {
self.closeCode = closeCode
self.size = UInt16(message?.characters.count ?? 0)
self.message = message ?? ""
}
public init(data: Data) throws{
let dataSize = data.count
if dataSize < messageIndex { throw SerializationError.WrongDataFrameSize(dataSize) }
guard let cCode = CloseCodeType(rawValue: data[closeCodeIndex]) else {
throw SerializationError.CloseCodeTypeNotFound(data[closeCodeIndex])
}
closeCode = cCode
size = UInt16(bigEndian: data.subdata(in: sizeIndex..<messageIndex).withUnsafeBytes{$0.pointee})
let offset:Int = messageIndex + Int(size)
if dataSize != offset { throw SerializationError.WrongDataFrameSize(dataSize) }
let s = data.subdata(in: messageIndex..<offset)
message = String(data: s, encoding: String.Encoding.utf8) ?? ""
}
public func toData() throws -> Data{
var r = ByteBackpacker.pack(self.type.type.rawValue)
r = r + ByteBackpacker.pack(self.closeCode.rawValue)
r = r + ByteBackpacker.pack(self.size, byteOrder: .bigEndian)
guard let encStr = self.message.data(using: .utf8) else{
throw SerializationError.UnexpectedError
}
var res = Data(bytes: r)
res.append(encStr)
return res
}
}
| mit | bfe022adbb57f0db84ea2ff0a7b003c3 | 31.776316 | 123 | 0.648334 | 4.25812 | false | false | false | false |
ifLab/WeCenterMobile-iOS | WeCenterMobile/Controller/HotTopicViewController.swift | 1 | 4005 | //
// HotTopicViewController.swift
// WeCenterMobile
//
// Created by Bill Hu on 15/12/9.
// Copyright © 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import UIKit
class HotTopicViewController: MSRSegmentedViewController, MSRSegmentedViewControllerDelegate {
override class var positionOfSegmentedControl: MSRSegmentedControlPosition {
return .Top
}
override func loadView() {
super.loadView()
let theme = SettingsManager.defaultManager.currentTheme
segmentedControl.indicator = MSRSegmentedControlUnderlineIndicator()
segmentedControl.tintColor = theme.titleTextColor
segmentedControl.indicator.tintColor = theme.subtitleTextColor
(segmentedControl.backgroundView as! UIToolbar).barStyle = theme.toolbarStyle
view.backgroundColor = theme.backgroundColorA
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Navigation-Root"), style: .Plain, target: self, action: "showSidebar")
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Publishment-Article_Question"), style: .Plain, target: self, action: "didPressPublishButton")
msr_navigationBar!.msr_shadowImageView?.hidden = true
scrollView.msr_setTouchesShouldCancel(true, inContentViewWhichIsKindOfClass: UIButton.self)
scrollView.delaysContentTouches = false
scrollView.panGestureRecognizer.requireGestureRecognizerToFail(appDelegate.mainViewController.sidebar.screenEdgePanGestureRecognizer)
delegate = self
}
var firstAppear = true
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if firstAppear {
firstAppear = false
let titles: [(TopicObjectListType, String)] = [
(.Focus, "我关注的"),
(.All, "全部"),
(.Month, "最近30天"),
(.Week, "最近7天")]
let vcs: [UIViewController] = titles.map {
(type, title) in
let vc = HotTopicListViewController(type: type)
vc.title = title
return vc
}
setViewControllers(vcs, animated: false)
}
}
func msr_segmentedViewController(segmentedViewController: MSRSegmentedViewController, didSelectViewController viewController: UIViewController?) {
(viewController as? HotTopicListViewController)?.segmentedViewControllerDidSelectSelf(segmentedViewController)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return SettingsManager.defaultManager.currentTheme.statusBarStyle
}
func showSidebar() {
appDelegate.mainViewController.sidebar.expand()
}
func didPressPublishButton() {
let ac = UIAlertController(title: "发布什么?", message: "选择发布的内容种类。", preferredStyle: .ActionSheet)
let presentPublishmentViewController: (String, PublishmentViewControllerPresentable) -> Void = {
[weak self] title, object in
let vc = NSBundle.mainBundle().loadNibNamed("PublishmentViewControllerA", owner: nil, options: nil).first as! PublishmentViewController
vc.dataObject = object
vc.headerLabel.text = title
self?.presentViewController(vc, animated: true, completion: nil)
}
ac.addAction(UIAlertAction(title: "问题", style: .Default) {
action in
presentPublishmentViewController("发布问题", Question.temporaryObject())
})
ac.addAction(UIAlertAction(title: "文章", style: .Default) {
action in
presentPublishmentViewController("发布文章", Article.temporaryObject())
})
ac.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
| gpl-2.0 | 56b9d9a9d32a31ff85f98eab85c9aae6 | 43.044944 | 176 | 0.676531 | 5.421853 | false | false | false | false |
nathawes/swift | test/Serialization/comments.swift | 23 | 6564 | // Test the case when we have a single file in a module.
//
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc -emit-module-source-info-path %t/comments.swiftsourceinfo %s
// RUN: llvm-bcanalyzer %t/comments.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftsourceinfo | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -enable-swiftsourceinfo -source-filename %s -I %t | %FileCheck %s -check-prefix=FIRST
// Test the case when we have a multiple files in a module.
//
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/first.swiftmodule -emit-module-doc -emit-module-doc-path %t/first.swiftdoc -primary-file %s %S/Inputs/def_comments.swift -emit-module-source-info-path %t/first.swiftsourceinfo
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/second.swiftmodule -emit-module-doc -emit-module-doc-path %t/second.swiftdoc %s -primary-file %S/Inputs/def_comments.swift -emit-module-source-info-path %t/second.swiftsourceinfo
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc %t/first.swiftmodule %t/second.swiftmodule -emit-module-source-info-path %t/comments.swiftsourceinfo
// RUN: llvm-bcanalyzer %t/comments.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftsourceinfo | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -enable-swiftsourceinfo -source-filename %s -I %t > %t.printed.txt
// RUN: %FileCheck %s -check-prefix=FIRST < %t.printed.txt
// RUN: %FileCheck %s -check-prefix=SECOND < %t.printed.txt
// BCANALYZER-NOT: UnknownCode
/// first_decl_generic_class_1 Aaa.
public class first_decl_generic_class_1<T> {
/// deinit of first_decl_generic_class_1 Aaa.
deinit {
}
}
/// first_decl_class_1 Aaa.
public class first_decl_class_1 {
/// decl_func_1 Aaa.
public func decl_func_1() {}
/**
* decl_func_3 Aaa.
*/
public func decl_func_2() {}
/// decl_func_3 Aaa.
/** Bbb. */
public func decl_func_3() {}
}
/// Comment for bar1
extension first_decl_class_1 {
func bar1(){}
}
/// Comment for bar2
extension first_decl_class_1 {
func bar2(){}
}
public protocol P1 { }
/// Comment for no member extension
extension first_decl_class_1 : P1 {}
// FIRST: comments.swift:26:14: Class/first_decl_generic_class_1 RawComment=[/// first_decl_generic_class_1 Aaa.\n]
// FIRST: comments.swift:28:3: Destructor/first_decl_generic_class_1.deinit RawComment=[/// deinit of first_decl_generic_class_1 Aaa.\n]
// FIRST: comments.swift:33:14: Class/first_decl_class_1 RawComment=[/// first_decl_class_1 Aaa.\n]
// FIRST: comments.swift:36:15: Func/first_decl_class_1.decl_func_1 RawComment=[/// decl_func_1 Aaa.\n]
// FIRST: comments.swift:41:15: Func/first_decl_class_1.decl_func_2 RawComment=[/**\n * decl_func_3 Aaa.\n */]
// FIRST: comments.swift:45:15: Func/first_decl_class_1.decl_func_3 RawComment=[/// decl_func_3 Aaa.\n/** Bbb. */]
// SECOND: comments.swift:49:1: Extension/ RawComment=[/// Comment for bar1\n] BriefComment=[Comment for bar1]
// SECOND: comments.swift:54:1: Extension/ RawComment=[/// Comment for bar2\n] BriefComment=[Comment for bar2]
// SECOND: comments.swift:61:1: Extension/ RawComment=[/// Comment for no member extension\n] BriefComment=[Comment for no member extension]
// SECOND: Inputs/def_comments.swift:2:14: Class/second_decl_class_1 RawComment=[/// second_decl_class_1 Aaa.\n]
// SECOND: Inputs/def_comments.swift:5:15: Struct/second_decl_struct_1
// SECOND: Inputs/def_comments.swift:7:9: Accessor/second_decl_struct_1.<getter for second_decl_struct_1.instanceVar>
// SECOND: Inputs/def_comments.swift:8:9: Accessor/second_decl_struct_1.<setter for second_decl_struct_1.instanceVar>
// SECOND: Inputs/def_comments.swift:10:17: Enum/second_decl_struct_1.NestedEnum
// SECOND: Inputs/def_comments.swift:11:22: TypeAlias/second_decl_struct_1.NestedTypealias
// SECOND: Inputs/def_comments.swift:14:13: Enum/second_decl_enum_1
// SECOND: Inputs/def_comments.swift:15:10: EnumElement/second_decl_enum_1.Case1
// SECOND: Inputs/def_comments.swift:16:10: EnumElement/second_decl_enum_1.Case2
// SECOND: Inputs/def_comments.swift:20:12: Constructor/second_decl_class_2.init
// SECOND: Inputs/def_comments.swift:23:17: Protocol/second_decl_protocol_1
// SECOND: Inputs/def_comments.swift:24:20: AssociatedType/second_decl_protocol_1.NestedTypealias
// SECOND: Inputs/def_comments.swift:25:5: Subscript/second_decl_protocol_1.subscript
// SECOND: Inputs/def_comments.swift:25:35: Accessor/second_decl_protocol_1.<getter for second_decl_protocol_1.subscript>
// SECOND: Inputs/def_comments.swift:25:39: Accessor/second_decl_protocol_1.<setter for second_decl_protocol_1.subscript>
// SECOND: Inputs/def_comments.swift:28:13: Var/decl_var_2 RawComment=none BriefComment=none DocCommentAsXML=none
// SECOND: Inputs/def_comments.swift:28:25: Var/decl_var_3 RawComment=none BriefComment=none DocCommentAsXML=none
// SECOND: Inputs/def_comments.swift:28:25: Var/decl_var_3 RawComment=none BriefComment=none DocCommentAsXML=none
// SECOND: NonExistingSource.swift:100000:13: Func/functionAfterPoundSourceLoc
// Test the case when we have to import via a .swiftinterface file.
//
// RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/Hidden)
// RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/Hidden/comments.swiftmodule -emit-module-interface-path %t/comments.swiftinterface -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc -emit-module-source-info-path %t/comments.swiftsourceinfo %s -enable-library-evolution -swift-version 5
// RUN: llvm-bcanalyzer %t/comments.swiftdoc | %FileCheck %s -check-prefix=BCANALYZER
// RUN: llvm-bcanalyzer %t/comments.swiftsourceinfo | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -enable-swiftsourceinfo -source-filename %s -I %t -swift-version 5 | %FileCheck %s -check-prefix=FIRST
| apache-2.0 | 845ae04162ba72e672909e7847dc2dae | 64.64 | 333 | 0.747105 | 3.230315 | false | true | false | false |
robpeach/test | SwiftPages/PagedScrollViewController.swift | 1 | 9648 | //
// PagedScrollViewController.swift
// Britannia v2
//
// Created by Rob Mellor on 11/07/2016.
// Copyright © 2016 Robert Mellor. All rights reserved.
//
import UIKit
import SDWebImage
class PagedScrollViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
var arrGallery : NSMutableArray!
var imageCache : [String:UIImage]!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet var lblPhotoCount: UILabel!
var pageViews: [UIImageView?] = []
var intPage : NSInteger!
@IBOutlet var viewLower: UIView!
@IBOutlet var viewUpper: UIView!
@IBOutlet weak var newPageView: UIView!
//var newPageView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
scrollView.needsUpdateConstraints()
scrollView.setNeedsLayout()
scrollView.layoutIfNeeded()
//
//
//Manually added constraints at runtime
let constraintTS = NSLayoutConstraint(item: scrollView, attribute: .Top, relatedBy: .Equal, toItem: viewUpper, attribute: .Bottom, multiplier: 1.0, constant: 0)
let constraintBS = NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: viewLower, attribute: .Top, multiplier: 1.0, constant: 0)
let constraintLS = NSLayoutConstraint(item: scrollView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1.0, constant: 0)
let constraintRS = NSLayoutConstraint(item: scrollView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1.0, constant: 0)
view.addConstraint(constraintTS)
view.addConstraint(constraintBS)
view.addConstraint(constraintLS)
view.addConstraint(constraintRS)
}
override func viewWillAppear(animated: Bool) {
centerScrollViewContents()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
centerScrollViewContents()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let pageCount = arrGallery.count
for _ in 0..<pageCount {
pageViews.append(nil)
}
let pagesScrollViewSize = scrollView.frame.size
scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * CGFloat(arrGallery.count), pagesScrollViewSize.height)
scrollView.contentOffset.x = CGFloat(intPage) * self.view.frame.size.width
lblPhotoCount.text = String(format: "%d of %d Photos",intPage+1, arrGallery.count)
loadVisiblePages()
let recognizer = UITapGestureRecognizer(target: self, action:#selector(PagedScrollViewController.handleTap(_:)))
// 4
recognizer.delegate = self
scrollView.addGestureRecognizer(recognizer)
scrollView.showsVerticalScrollIndicator = false
viewUpper.alpha = 1.0
viewLower.alpha = 1.0
}
func handleTap(recognizer: UITapGestureRecognizer) {
viewUpper.alpha = 1.0
viewLower.alpha = 1.0
}
func loadPage(page: Int) {
if page < 0 || page >= arrGallery.count {
// If it's outside the range of what you have to display, then do nothing
return
}
if let page = pageViews[page] {
// Do nothing. The view is already loaded.
} else {
var frame = scrollView.bounds
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0.0
let rowData: NSDictionary = arrGallery[page] as! NSDictionary
let urlString: String = rowData["pic"] as! String
let imgURL = NSURL(string: urlString)
// If this image is already cached, don't re-download
if let img = imageCache[urlString] {
let newPageView = UIImageView(image: img)
newPageView.contentMode = .ScaleAspectFit
newPageView.frame = frame
scrollView.addSubview(newPageView)
pageViews[page] = newPageView
}
else {
SDWebImageManager.sharedManager().downloadImageWithURL(imgURL, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in
if error == nil {
// let image = UIImage(data: data!)
//On Main Thread
dispatch_async(dispatch_get_main_queue()){
self?.imageCache[urlString] = image
// Update the cell
let newPageView = UIImageView(image: image)
newPageView.contentMode = .ScaleAspectFit
newPageView.frame = frame
self?.scrollView.addSubview(newPageView)
// 4
self?.pageViews[page] = newPageView
}
}
else {
print("Error: \(error!.localizedDescription)")
}
})
}
}
}
func purgePage(page: Int) {
if page < 0 || page >= arrGallery.count {
// If it's outside the range of what you have to display, then do nothing
return
}
if let pageView = pageViews[page] {
pageView.removeFromSuperview()
pageViews[page] = nil
}
}
func loadVisiblePages() {
// First, determine which page is currently visible
let pageWidth = scrollView.frame.size.width
let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))
intPage = page
// Update the page control
lblPhotoCount.text = String(format: "%d of %d Photos",intPage+1, arrGallery.count)
// Work out which pages you want to load
let firstPage = max(0,page - 1)
let lastPage = min(page + 1, arrGallery.count - 1)
// Purge anything before the first page
for index in 0..<firstPage {
purgePage(index)
}
// Load pages in our range
for index in firstPage...lastPage {
loadPage(index)
}
// Purge anything after the last page
for index in (lastPage + 1)..<(arrGallery.count) {
purgePage(index)
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
// Load the pages that are now on screen
if scrollView.contentSize.width > 320{
viewLower.alpha = 1
viewUpper.alpha = 1
loadVisiblePages()
}
}
@IBAction func btnBackTapped(sender: AnyObject) {
scrollView.delegate = nil
if let navController = self.navigationController {
navController.popToRootViewControllerAnimated(true)
}
}
@IBAction func btnShareTapped(sender: AnyObject) {
var sharingItems = [AnyObject]()
let rowData: NSDictionary = arrGallery[intPage] as! NSDictionary
// Grab the artworkUrl60 key to get an image URL for the app's thumbnail
let urlString: String = rowData["pic"] as! String
// let imgURL = NSURL(string: urlString)
let img = imageCache[urlString]
sharingItems.append(img!)
// sharingItems.append(imgURL!)
let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
}
@IBAction func btnGalleryTapped(sender: AnyObject) {
scrollView.delegate = nil
if let navController = self.navigationController {
navController.popViewControllerAnimated(true)
}
}
func centerScrollViewContents() {
let boundsSize = scrollView.bounds.size
var contentsFrame = newPageView.frame
if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}
if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.height - self.topLayoutGuide.length) / 2.0
} else {
contentsFrame.origin.y = 0.0
}
newPageView.frame = contentsFrame
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
//LightContent
return UIStatusBarStyle.LightContent
//Default
//return UIStatusBarStyle.Default
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | c06e302c831f4434f2e8926011118974 | 31.156667 | 170 | 0.561107 | 5.628355 | false | false | false | false |
gpancio/iOS-Prototypes | GPUIKit/GPUIKit/Classes/ExpandableTableViewCell.swift | 1 | 2300 | //
// ExpandableTableViewCell.swift
// GPUIKit
//
// Created by Graham Pancio on 2016-04-27.
// Copyright © 2016 Graham Pancio. All rights reserved.
//
import UIKit
public class ExpandableTableViewCell: UITableViewCell {
@IBOutlet weak var stackView: UIStackView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var showDetailIcon: UILabel!
@IBOutlet weak var detailsTextView: UITextView!
@IBOutlet weak var checkbox: CheckBox!
public var title: String? {
didSet {
titleLabel?.text = title
}
}
public var detail: String? {
didSet {
detailsTextView?.text = detail
}
}
override public func awakeFromNib() {
super.awakeFromNib()
stackView.arrangedSubviews.last?.hidden = true
}
public override func prepareForReuse() {
super.prepareForReuse()
stackView.arrangedSubviews.last?.hidden = true
}
override public func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 1,
options: UIViewAnimationOptions.CurveEaseIn,
animations: { () -> Void in
self.stackView.arrangedSubviews.last?.hidden = !selected
},
completion: nil)
let rotate: CGFloat = selected ? CGFloat(M_PI_2) : 0
UIView.animateWithDuration(0.35,
animations: {
self.showDetailIcon.transform = CGAffineTransformMakeRotation(rotate)
if (selected) {
self.stackView.arrangedSubviews.first?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.30)
self.stackView.arrangedSubviews.last?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.30)
} else {
self.stackView.arrangedSubviews.first?.backgroundColor = UIColor.clearColor()
self.stackView.arrangedSubviews.last?.backgroundColor = UIColor.clearColor()
}
}
)
}
}
| mit | a5936bade04d464e0b3d8c27ac33bac2 | 31.842857 | 127 | 0.595041 | 5.5 | false | false | false | false |
yanif/circator | MetabolicCompassWatchExtension/WaterInterfaceController.swift | 1 | 1468 | //
// WaterInterfaceController.swift
// Circator
//
// Created by Mariano on 3/30/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import WatchKit
import Foundation
import HealthKit
struct waterAmountVariable {
var waterAmount: Double
}
var waterEnterButton = waterAmountVariable(waterAmount:250.0)
class WaterInterfaceController: WKInterfaceController {
@IBOutlet var waterPicker: WKInterfacePicker!
@IBOutlet var EnterButton: WKInterfaceButton!
var water = 0.0
let healthKitStore:HKHealthStore = HKHealthStore()
let healthManager:HealthManager = HealthManager()
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
var tempItems: [WKPickerItem] = []
for i in 0...8 {
let item = WKPickerItem()
item.contentImage = WKImage(imageName: "WaterInCups\(i)")
tempItems.append(item)
}
waterPicker.setItems(tempItems)
waterPicker.setSelectedItemIndex(2)
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func onWaterEntry(value: Int) {
water = Double(value)*250
}
@IBAction func waterSaveButton() {
waterEnterButton.waterAmount = water
pushControllerWithName("WaterTimesInterfaceController", context: self)
}
}
| apache-2.0 | 1a46defb20de0e35a5825379db277c3d | 24.736842 | 78 | 0.665303 | 4.657143 | false | false | false | false |
eofster/Telephone | UseCases/ServiceAddress.swift | 1 | 2513 | //
// ServiceAddress.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone 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.
//
// Telephone 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.
//
public final class ServiceAddress: NSObject {
@objc public let host: String
@objc public let port: String
@objc public var stringValue: String {
let h = host.isIP6Address ? "[\(host)]" : host
return port.isEmpty ? h : "\(h):\(port)"
}
public override var description: String { return stringValue }
@objc public init(host: String, port: String) {
self.host = trimmingSquareBrackets(host)
self.port = port
}
@objc public convenience init(host: String) {
self.init(host: host, port: "")
}
@objc(initWithString:) public convenience init(_ string: String) {
let address = beforeSemicolon(string)
if trimmingSquareBrackets(address).isIP6Address {
self.init(host: address)
} else if let range = address.range(of: ":", options: .backwards) {
self.init(host: String(address[..<range.lowerBound]), port: String(address[range.upperBound...]))
} else {
self.init(host: address)
}
}
}
extension ServiceAddress {
public override func isEqual(_ object: Any?) -> Bool {
guard let address = object as? ServiceAddress else { return false }
return isEqual(to: address)
}
public override var hash: Int {
var hasher = Hasher()
hasher.combine(host)
hasher.combine(port)
return hasher.finalize()
}
private func isEqual(to address: ServiceAddress) -> Bool {
return host == address.host && port == address.port
}
}
private func beforeSemicolon(_ string: String) -> String {
if let index = string.firstIndex(of: ";") {
return String(string[..<index])
} else {
return string
}
}
private func trimmingSquareBrackets(_ string: String) -> String {
return string.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
}
| gpl-3.0 | a79b81fc48da8769f4f0853cbe20c34d | 30.78481 | 109 | 0.648746 | 4.314433 | false | false | false | false |
moked/iuob | iUOB 2/Controllers/Schedule Builder/SummaryVC.swift | 1 | 10389 | //
// SummaryVC.swift
// iUOB 2
//
// Created by Miqdad Altaitoon on 12/19/16.
// Copyright © 2016 Miqdad Altaitoon. All rights reserved.
//
import UIKit
import NYAlertViewController
import MBProgressHUD
/// all magic here. find the true number of combinations between the courses
class SummaryVC: UIViewController {
// MARK: - Properties
var filteredCourseSectionDict = [String: [Section]]()
var sectionCombination = [[Section]]() /// all sections
@IBOutlet weak var schedulesFoundLabel: UILabel!
@IBOutlet weak var nextButtonOutlet: UIBarButtonItem!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.nextButtonOutlet.isEnabled = false
builderAlgorithm()
googleAnalytics()
}
func googleAnalytics() {
if let tracker = GAI.sharedInstance().defaultTracker {
tracker.set(kGAIScreenName, value: NSStringFromClass(type(of: self)).components(separatedBy: ".").last!)
let builder: NSObject = GAIDictionaryBuilder.createScreenView().build()
tracker.send(builder as! [NSObject : AnyObject])
}
}
/**
this function do everything, but it should be refactored for more efficencey + readablilty
example of what this algorithm do:
let say we have 3 courses which have 3, 2, 5 section respectivly:
course [0]: [0][1][2]
course [1]: [0][1]
course [2]: [0][1][2][3][4]
we will have (3 * 2 * 5 = 30) possible combinations between them.
so insted of going through all sections recuresvly, I refactured the recurseve function into an iteration loop which is much faster.
in order to do it, we need 2 arrays. On to store the current indeces that we have. And the other one to store the actual size for each of the sections array.
It will go like this:
comb 1: [0][0][0]
comb 2: [0][0][1]
comb 3: [0][0][2]
...
comb 30: [2][1][4]
*/
func builderAlgorithm() {
self.schedulesFoundLabel.text = "Calculating..."
MBProgressHUD.showAdded(to: self.view, animated: true)
DispatchQueue.global(qos: .background).async { // do calucaltion in background thread
var allCombinationCount = 1 // all possible combination to iterate through
var indicesArray:[Int] = [] // array to store current indeces for each of the course' sections
var indicesSizeArray:[Int] = [] // array to store the true size for each of the course' sections
let lazyMapCollection = self.filteredCourseSectionDict.keys
let keysArray = Array(lazyMapCollection.map { String($0)! })
/* initilaizing arrays */
for i in 0..<keysArray.count {
allCombinationCount *= self.filteredCourseSectionDict[keysArray[i]]!.count
indicesArray.append(0) // init. zero index for all courses/sections
indicesSizeArray.append(self.filteredCourseSectionDict[keysArray[i]]!.count) // init sizes
}
/* go through all possible combinations */
for _ in 0..<allCombinationCount {
var sectionsToCompare: [Section] = [] // reset each time
for j in 0..<keysArray.count {
sectionsToCompare.append(self.filteredCourseSectionDict[keysArray[j]]![indicesArray[j]])
}
// compare sectionsToCompare, if no clashes, add to new array. to find clshes, double for loop
var isSectionClash = false
for i in 0..<sectionsToCompare.count-1 {
if isSectionClash {break}
for j in i+1..<sectionsToCompare.count {
if isSectionClash {break}
let sectionA = sectionsToCompare[i]
let sectionB = sectionsToCompare[j]
/* compare section A and B. if same day & same cross in time -> CLASH */
for timingA in sectionA.timing {
for timingB in sectionB.timing {
for dayA in timingA.day.characters {
for dayB in timingB.day.characters {
if dayA == dayB {
// if same day -> check timing
let timeStartArrA = timingA.timeFrom.components(separatedBy: ":")
let timeStartArrB = timingB.timeFrom.components(separatedBy: ":")
let timeEndArrA = timingA.timeTo.components(separatedBy: ":")
let timeEndArrB = timingB.timeTo.components(separatedBy: ":")
if timeStartArrA.count > 1 && timeStartArrB.count > 1 && timeEndArrA.count > 1 && timeEndArrB.count > 1 {
let sectionAStartTime = Float(Float(timeStartArrA[0])! + (Float(timeStartArrA[1])! / 60.0))
let sectionBStartTime = Float(Float(timeStartArrB[0])! + (Float(timeStartArrB[1])! / 60.0))
let sectionAEndTime = Float(Float(timeEndArrA[0])! + (Float(timeEndArrA[1])! / 60.0))
let sectionBEndTime = Float(Float(timeEndArrB[0])! + (Float(timeEndArrB[1])! / 60.0))
if (sectionAStartTime >= sectionBStartTime && sectionAStartTime <= sectionBEndTime) ||
(sectionAEndTime >= sectionBStartTime && sectionAEndTime <= sectionBEndTime) ||
(sectionBStartTime >= sectionAStartTime && sectionBStartTime <= sectionAEndTime) ||
(sectionBEndTime >= sectionAStartTime && sectionBEndTime <= sectionAEndTime) {
// if start or end time is between other lectures times -> CLASH
isSectionClash = true
}
}
}
}
}
}
}
}
}
if !isSectionClash {
self.sectionCombination.append(sectionsToCompare)
}
/* state machine to determin each index of arrays */
for index in 0..<self.filteredCourseSectionDict.count {
if indicesArray[index] + 1 == indicesSizeArray[index] {
indicesArray[index] = 0 // reset
} else {
indicesArray[index] += 1 // increment current index
break
}
}
}
DispatchQueue.main.async {
MBProgressHUD.hide(for: self.view, animated: true)
self.schedulesFoundLabel.text = "\(self.sectionCombination.count)"
if self.sectionCombination.count == 0 {
self.nextButtonOutlet.isEnabled = false
self.showAlert(title: "Not found", msg: "No schedule found. Please go back and choose other options or other courses")
} else {
self.nextButtonOutlet.isEnabled = true
}
}
}
}
func showAlert(title: String, msg: String) {
let alertViewController = NYAlertViewController()
alertViewController.title = title
alertViewController.message = msg
alertViewController.buttonCornerRadius = 20.0
alertViewController.view.tintColor = self.view.tintColor
//alertViewController.cancelButtonColor = UIColor.redColor()
alertViewController.destructiveButtonColor = UIColor(netHex:0xFFA739)
alertViewController.swipeDismissalGestureEnabled = true
alertViewController.backgroundTapDismissalGestureEnabled = true
let cancelAction = NYAlertAction(
title: "Close",
style: .cancel,
handler: { (action: NYAlertAction?) -> Void in
self.dismiss(animated: true, completion: nil)
}
)
alertViewController.addAction(cancelAction)
// Present the alert view controller
self.present(alertViewController, animated: true, completion: nil)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "OptionsListSegue" {
let nextScene = segue.destination as? OptionsListVC
nextScene!.sectionCombination = sectionCombination
}
}
}
| mit | 3c7d3105da9604ba2d359965fb16e000 | 41.4 | 162 | 0.473142 | 6.209205 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/ToneGenerator/NotesSoundType.swift | 1 | 2748 | /*
* Copyright 2019 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.
*/
import Foundation
/// A tone generator sound type that plays a note only when the value changes or a period of time
/// has gone by without having played a note.
class NotesSoundType: SoundType {
/// The minimum percent change in value that can trigger a sound.
let minimumPercentChange = 10.0
/// The minimum change in time (milliseconds) that can trigger a sound.
let minimumTimeChange: Int64 = 125
/// The maximum time (milliseconds) that can go by without a sound.
let maximumTimeWithoutSound: Int64 = 1000
/// The timestamp of the last value that played a sound.
var previousTimestamp = Date().millisecondsSince1970
/// The last value that played a sound.
var previousValue: Double?
init() {
let name = String.notes
super.init(name: name)
shouldAnimateToNextFrequency = false
}
override func frequency(from value: Double,
valueMin: Double,
valueMax: Double,
timestamp: Int64) -> Double? {
guard let previousValue = previousValue else {
self.previousValue = value
return nil
}
let valueDifference = value - previousValue
let valueRange = valueMax - valueMin
let valuePercentChange = abs(valueDifference / valueRange * 100.0)
let timestampDifference = timestamp - previousTimestamp
// If the `value` hasn't changed more than `minimumPercentChange`, suppress new notes for up to
// `maximumTimeWithoutSound`. If the `value` has changed more than `minimumPercentChange`,
// suppress new notes for `minimumTimeChange`.
let percentChangeAboveMinimum = valuePercentChange >= minimumPercentChange
let timeChangeAboveMinimum = timestampDifference > minimumTimeChange
let timeChangeAboveMaximum = timestampDifference > maximumTimeWithoutSound
if percentChangeAboveMinimum && timeChangeAboveMinimum || timeChangeAboveMaximum {
previousTimestamp = timestamp
self.previousValue = value
return frequencyMin +
(value - valueMin) / (valueMax - valueMin) * (frequencyMax - frequencyMin)
}
return nil
}
}
| apache-2.0 | 6ec12424ef59d3978d2752a55ad2e642 | 37.166667 | 99 | 0.709971 | 4.729776 | false | false | false | false |
kazuhiro4949/PagingKit | Sources/Menu Cells/Overlay/OverlayMenuCell.swift | 1 | 5728 | //
// OverlayMenuCell.swift
// iOS Sample
//
// Copyright (c) 2017 Kazuhiro Hayashi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public class OverlayMenuCell: PagingMenuViewCell {
public weak var referencedMenuView: PagingMenuView?
public weak var referencedFocusView: PagingMenuFocusView?
public var hightlightTextColor: UIColor? {
set {
highlightLabel.textColor = newValue
}
get {
return highlightLabel.textColor
}
}
public var normalTextColor: UIColor? {
set {
titleLabel.textColor = newValue
}
get {
return titleLabel.textColor
}
}
public var hightlightTextFont: UIFont? {
set {
highlightLabel.font = newValue
}
get {
return highlightLabel.font
}
}
public var normalTextFont: UIFont? {
set {
titleLabel.font = newValue
}
get {
return titleLabel.font
}
}
public static let sizingCell = OverlayMenuCell()
let maskInsets = UIEdgeInsets(top: 6, left: 8, bottom: 6, right: 8)
let textMaskView: UIView = {
let view = UIView()
view.backgroundColor = .black
return view
}()
let highlightLabel = UILabel()
let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addConstraints()
highlightLabel.mask = textMaskView
highlightLabel.textColor = .white
}
required init?(coder: NSCoder) {
super.init(coder: coder)
addConstraints()
highlightLabel.mask = textMaskView
highlightLabel.textColor = .white
}
override public func layoutSubviews() {
super.layoutSubviews()
textMaskView.bounds = bounds.inset(by: maskInsets)
}
public func configure(title: String) {
titleLabel.text = title
highlightLabel.text = title
}
public func updateMask(animated: Bool = true) {
guard let menuView = referencedMenuView, let focusView = referencedFocusView else {
return
}
setFrame(menuView, maskFrame: focusView.frame, animated: animated)
}
func setFrame(_ menuView: PagingMenuView, maskFrame: CGRect, animated: Bool) {
textMaskView.frame = menuView.convert(maskFrame, to: highlightLabel).inset(by: maskInsets)
if let expectedOriginX = menuView.getExpectedAlignmentPositionXIfNeeded() {
textMaskView.frame.origin.x += expectedOriginX
}
}
public func calculateWidth(from height: CGFloat, title: String) -> CGFloat {
configure(title: title)
var referenceSize = UIView.layoutFittingCompressedSize
referenceSize.height = height
let size = systemLayoutSizeFitting(referenceSize, withHorizontalFittingPriority: UILayoutPriority.defaultLow, verticalFittingPriority: UILayoutPriority.defaultHigh)
return size.width
}
}
extension OverlayMenuCell {
private func addConstraints() {
addSubview(titleLabel)
addSubview(highlightLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
highlightLabel.translatesAutoresizingMaskIntoConstraints = false
[titleLabel, highlightLabel].forEach {
let trailingConstraint = NSLayoutConstraint(
item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: $0,
attribute: .trailing,
multiplier: 1,
constant: 16)
let leadingConstraint = NSLayoutConstraint(
item: $0,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 16)
let bottomConstraint = NSLayoutConstraint(
item: self,
attribute: .top,
relatedBy: .equal,
toItem: $0,
attribute: .top,
multiplier: 1,
constant: 8)
let topConstraint = NSLayoutConstraint(
item: $0,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottom,
multiplier: 1,
constant: 8)
addConstraints([topConstraint, bottomConstraint, trailingConstraint, leadingConstraint])
}
}
}
| mit | 0682c5f92cbd9194846e4469b8e3dd8e | 31.731429 | 172 | 0.608764 | 5.424242 | false | false | false | false |
pneyrinck/corecontrol | controls/swift/CCFader.swift | 1 | 11491 | //
// CCFader.swift
// Example
//
// Created by Bernice Ling on 2/26/16.
// Copyright © 2016 Neyrinck. All rights reserved.
//
import UIKit
struct CCTaperMark
{
var name: String
var position: Float
init(name: String, position: Float) {
self.name = name
self.position = position
}
};
@objcMembers
class CCFader: UIControl{
var capButton: CCFaderCap!
var groove: CCButton!
var displayValue: UILabel!
var logicBar: UIView!
var capTouched: Bool!
var position: Float!
var hasLabelFontSize: Float!
var hashLabelWidth: Float!
var grooveTop: Float!
var grooveBottom: Float!
var grooveLeft: Float!
var grooveRight: Float!
var grooveHCenter: Float!
var gutterBottom: Float!
var gutterTop: Float!
var gutterHeight: Float!
var capVCenterOffset: Float!
var recordMode: Bool!
var faderIsVertical: Bool!
var grooveWidth : Float?
var highlightColor: UIColor
{
didSet {
capButton.highlightColor = self.highlightColor;
capButton.setNeedsDisplay();
}
}
override var isHighlighted: Bool {
didSet {
capButton.isHighlighted = self.isHighlighted;
capButton.setNeedsDisplay();
}
}
var capHeight:NSNumber = 78 {
didSet {
updateSettings()
}
}
var faderCapState:CCButtonState!{
didSet {
if (capButton != nil)
{
capButton.setState(faderCapState, forIndex: 0)
}
}
}
var grooveState:CCButtonState!{
didSet {
if (groove != nil)
{
groove.setState(grooveState, forIndex: 0)
}
}
}
override init(frame: CGRect) {
self.highlightColor = UIColor.clear
super.init(frame: frame)
}
required init?(coder decoder: NSCoder) {
self.highlightColor = UIColor.clear
super.init(coder: decoder)
capTouched = false
position = 0
hashLabelWidth = 22
hasLabelFontSize = 12
self.updateSettings()
}
override func layoutSubviews() {
self.updateSettings()
}
func updateSettings() {
let viewSize: CGSize = self.bounds.size
let faderWasVertical = faderIsVertical
// decide if fader should be displayed vertically or horizontally
if (viewSize.height > viewSize.width) {
faderIsVertical = true
} else {
faderIsVertical = false
}
if faderIsVertical != faderWasVertical {
if capButton != nil {
capButton.removeFromSuperview()
capButton = nil
}
if groove != nil {
groove.removeFromSuperview()
groove = nil
}
}
if faderIsVertical == true {
drawVerticalFader(viewSize)
} else {
drawHorizontalFader(viewSize)
}
}
func drawHorizontalFader(_ viewSize: CGSize){
grooveLeft = Float(self.bounds.origin.x)
grooveRight = Float(self.bounds.origin.x) + Float(viewSize.width)
// draw cap
let capRect: CGRect = CGRect(x: 0.0,y: 0.0,width: 44.0, height: self.frame.height)
if capButton == nil {
capButton = CCFaderCap(frame: capRect)
} else {
capButton.frame.size = capRect.size
}
if faderCapState != nil {
capButton.setState(faderCapState, forIndex: 0)
}
capButton.layer.masksToBounds = false
capButton.layer.shadowColor = UIColor.black.cgColor
capButton.layer.shadowOpacity = 0.7
capButton.layer.shadowRadius = 5
capButton.layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
capButton.clipsToBounds = false
capButton.gradientIsLeftToRight = true;
// draw groove
var h:CGFloat!
if (grooveWidth != nil) {
h = CGFloat(grooveWidth!)
} else {
h = CGFloat(6.0)
}
let y = self.frame.height/2 - h/2
let w = viewSize.width - capRect.size.width
let x = capRect.size.width / 2
let grooveRect: CGRect = CGRect(x: x,y: y,width: w,height: h)
if groove == nil {
groove = CCButton(frame: grooveRect)
} else {
groove.frame = grooveRect
}
if groove.superview == nil {
self.addSubview(groove)
}
if capButton.superview == nil {
self.insertSubview(capButton, aboveSubview: groove)
}
self.setNeedsDisplay()
self.updateCapPosition()
}
func drawVerticalFader(_ viewSize: CGSize){
// we vertically stretch the groove pict to fit exactly inside the view height
grooveTop = Float(self.bounds.origin.y)
grooveBottom = Float(self.bounds.origin.y) + Float(viewSize.height)
let capRect: CGRect = CGRect(x: 0.0,y: 0.0,width: self.bounds.width, height: CGFloat(capHeight))
if capButton == nil {
capButton = CCFaderCap(frame: capRect)
} else {
capButton.frame.size = capRect.size
}
if faderCapState != nil {
capButton.setState(faderCapState, forIndex: 0)
}
capButton.layer.masksToBounds = false
capButton.layer.shadowColor = UIColor.black.cgColor
capButton.layer.shadowOpacity = 0.7
capButton.layer.shadowRadius = 5
capButton.layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
capButton.clipsToBounds = false
var w:CGFloat!
if (grooveWidth != nil) {
w = CGFloat(grooveWidth!)
} else {
w = CGFloat(6.0)
}
let h = viewSize.height - capRect.size.height
let y = capRect.size.height / 2
let x = self.frame.width/2 - w/2
let grooveRect: CGRect = CGRect(x: x,y: y,width: w,height: h)
if groove == nil {
groove = CCButton(frame: grooveRect)
} else {
groove.frame = grooveRect
}
if grooveState != nil {
groove.setState(grooveState, forIndex: 0)
}
if groove.superview == nil {
self.addSubview(groove)
}
if capButton.superview == nil {
self.insertSubview(capButton, aboveSubview: groove)
}
self.setNeedsDisplay()
// force redraw of labels and groove
self.updateCapPosition()
}
func handleDoubleTap() {
NotificationCenter.default.post(name: Foundation.Notification.Name(rawValue: "FaderViewDoubleTap"), object: self)
}
func updateCapPosition(){
var animate: Bool?
if capTouched == true {
animate = false
} else {
animate = true
}
animate = true
let capSize: CGSize = capButton.frame.size
let w = capSize.width
let h = capSize.height
var x:CGFloat;
var y:CGFloat
if (faderIsVertical == true){
x = 0.0;
y = CGFloat(self.getYPosForFaderValue(position))
} else {
x = CGFloat(self.getXPosForFaderValue(position))
y = 0.0
}
// what is the purpose of logicBarRect and logicBar?
var logicBarRect: CGRect = CGRect(x: 0,y: 0,width: 0.0,height: 0.0)
if logicBar != nil {
logicBarRect = logicBar.frame
x = x + CGFloat(hashLabelWidth)
}
let capRect: CGRect = CGRect(x: x,y: y,width: w,height: h)
if (faderIsVertical == true){
logicBarRect.origin.y = CGFloat(grooveTop) + (1 - CGFloat(position)) * (CGFloat(grooveBottom) - CGFloat(grooveTop))
logicBarRect.size.height = CGFloat(position) * (CGFloat(grooveBottom) - CGFloat(grooveTop)) - 4
}
if (faderIsVertical == false){
logicBarRect.origin.x = CGFloat(grooveLeft) + (1 - CGFloat(position)) * (CGFloat(grooveRight) - CGFloat(grooveLeft))
logicBarRect.size.width = CGFloat(position) * (CGFloat(grooveRight) - CGFloat(grooveLeft)) - 4
}
if animate == true {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.09)
UIView.setAnimationCurve(.easeInOut)
UIView.setAnimationDelay(0.0)
}
capButton.frame = capRect
if logicBar != nil {
logicBar.frame = logicBarRect
}
if animate == true {
UIView.commitAnimations()
}
}
func getYPosForFaderValue(_ value: Float) -> Float {
return ((1 - value) * (Float(self.bounds.size.height) - Float(capButton.frame.size.height)))
}
func getXPosForFaderValue(_ value: Float) -> Float {
return (value * (Float(self.bounds.size.width) - Float(capButton.frame.size.width)))
}
func setPosition(_ to: Float) {
if !capTouched {
position = to
self.updateCapPosition()
}
}
func getChannelIndex() -> Int {
return 0
}
func getYPosForScaleValue(_ value: Float) -> Float {
return Float(self.getYPosForFaderValue(value)) + Float(capButton.frame.size.height) / 2
}
func getFaderValueForYPos(_ yPos: Float) -> Float {
let capSize: CGSize = capButton.frame.size
let viewSize: CGSize = self.bounds.size
let value: Float = 1.0 - ((yPos) / (Float(viewSize.height) - Float(capSize.height)))
return value
}
func setValue(_ to: Float) {
if (capTouched == true){
position = to
self.updateCapPosition()
}
}
func setTouchValue(_ to: Float) {
if (capTouched != false) {
position = to
self.updateCapPosition()
self.sendActions(for: .valueChanged)
}
}
func setTouchDelta(_ deltapx: Float) {
if (capTouched != false) {
var delta: Float;
if (faderIsVertical == true){
delta = deltapx / (Float(self.bounds.size.height) - Float(capButton.frame.size.height))
} else {
delta = deltapx / (Float(self.bounds.size.width) - Float(capButton.frame.size.width))
}
let p = position
position = p! - delta;
position = (position < 0) ? 0 : position
position = (position > 1.0) ? 1.0 : position
self.updateCapPosition()
self.sendActions(for: .valueChanged)
}
}
func getPosition() -> Float {
return position
}
func getCapHeight() -> Float {
return Float(capButton.frame.size.height)
}
func getCapWidth() -> Float {
return Float(capButton.frame.size.width)
}
func getFaderWidth() -> Float {
return Float(self.bounds.size.width)
}
func getFaderHeight() -> Float {
return Float(self.bounds.size.height)
}
func setCapTouched(isTouched:Bool)
{
if capTouched==isTouched
{
return;
}
capTouched = isTouched;
if (capTouched == true)
{
self.sendActions(for: .editingDidBegin)
}
else
{
self.sendActions(for: .editingDidEnd)
}
}
}
| gpl-2.0 | 3567bcd9ba9c0c8682a9aef8a2505009 | 26.753623 | 128 | 0.558573 | 4.431161 | false | false | false | false |
walokra/Haikara | Haikara/Controllers/FilterNewsSourcesViewController.swift | 1 | 15870 | //
// FilterNewsSourcesViewController.swift
// highkara
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Marko Wallin <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class FilterNewsSourcesViewController: UIViewController {
let viewName = "Settings_FilterNewsSourcesView"
struct MainStoryboard {
struct TableViewCellIdentifiers {
static let listCategoryCell = "tableCell"
}
}
let searchController = UISearchController(searchResultsController: nil)
@IBOutlet weak var tableTitleView: UIView!
@IBOutlet weak var tableView: UITableView!
// @IBOutlet weak var searchFooter: SearchFooter!
let settings = Settings.sharedInstance
var defaults: UserDefaults?
var navigationItemTitle: String = NSLocalizedString("SETTINGS_FILTERED_TITLE", comment: "")
var errorTitle: String = NSLocalizedString("ERROR", comment: "Title for error alert")
var searchPlaceholderText: String = NSLocalizedString("FILTER_SEARCH_PLACEHOLDER", comment: "Search sources to filter")
var newsSources = [NewsSources]()
var filteredTableData = [NewsSources]()
var searchText: String? = ""
let payWallItems = [Paywall.Free, Paywall.Partial, Paywall.Monthly, Paywall.Strict]
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
searchText = searchController.searchBar.text
searchController.isActive = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tabBarController!.title = navigationItemTitle
self.navigationItem.title = navigationItemTitle
if !(searchText?.isEmpty)! {
searchController.searchBar.text = searchText
searchController.isActive = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.defaults = settings.defaults
setObservers()
setTheme()
setContentSize()
sendScreenView(viewName)
if self.newsSources.isEmpty {
getNewsSources()
}
#if DEBUG
print("newsSources filtered=\(String(describing: settings.newsSourcesFiltered[settings.region]))")
#endif
self.tableView!.delegate = self
self.tableView.dataSource = self
// Setup the Search Controller
searchController.searchResultsUpdater = self
if #available(iOS 9.1, *) {
searchController.obscuresBackgroundDuringPresentation = false
} else {
searchController.dimsBackgroundDuringPresentation = false
}
searchController.searchBar.placeholder = searchPlaceholderText
if #available(iOS 11.0, *) {
navigationItem.searchController = searchController
} else {
// Fallback on earlier versions
}
// self.definesPresentationContext = true
// Setup the Scope Bar
// searchController.searchBar.scopeButtonTitles = [payWallItems[0].description, payWallItems[1].description, payWallItems[2].description, payWallItems[3].description]
// searchController.searchBar.showsScopeBar = true
// searchController.searchBar.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.sizeToFit()
searchController.searchBar.barStyle = Theme.barStyle
searchController.searchBar.barTintColor = Theme.searchBarTintColor
searchController.searchBar.backgroundColor = Theme.backgroundColor
self.tableTitleView.addSubview(searchController.searchBar)
// Setup the search footer
// tableView.tableFooterView = searchFooter
}
func setObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(FilterNewsSourcesViewController.setRegionNewsSources(_:)), name: .regionChangedNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FilterNewsSourcesViewController.resetNewsSourcesFiltered(_:)), name: .settingsResetedNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FilterNewsSourcesViewController.setTheme(_:)), name: .themeChangedNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FilterNewsSourcesViewController.setContentSize(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil)
}
func setTheme() {
Theme.loadTheme()
view.backgroundColor = Theme.backgroundColor
tableView.backgroundColor = Theme.backgroundColor
tableTitleView.backgroundColor = Theme.backgroundColor
}
@objc func setTheme(_ notification: Notification) {
#if DEBUG
print("FilterNewsSourcesViewController, Received themeChangedNotification")
#endif
setTheme()
searchController.searchBar.barStyle = Theme.barStyle
searchController.searchBar.barTintColor = Theme.searchBarTintColor
searchController.searchBar.backgroundColor = Theme.backgroundColor
self.tableView.reloadData()
}
func setContentSize() {
tableView.reloadData()
}
@objc func setContentSize(_ notification: Notification) {
#if DEBUG
print("DetailViewController, Received UIContentSizeCategoryDidChangeNotification")
#endif
setContentSize()
}
@objc func setRegionNewsSources(_ notification: Notification) {
#if DEBUG
print("FilterNewsSourcesViewController, regionChangedNotification")
#endif
getNewsSources()
}
@objc func resetNewsSourcesFiltered(_ notification: Notification) {
#if DEBUG
print("FilterNewsSourcesViewController, Received resetNewsSourcesFiltered")
#endif
if (settings.newsSources.isEmpty) {
getNewsSourcesFromAPI()
} else {
self.newsSources = settings.newsSources
}
self.tableView!.reloadData()
}
func searchBarIsEmpty() -> Bool {
// Returns true if the text is empty or nil
return searchController.searchBar.text?.isEmpty ?? true
}
// func filterContentForSearchText(_ searchText: String, scope: Paywall = Paywall.All) {
// filteredTableData.removeAll(keepingCapacity: false)
//
// filteredTableData = newsSources.filter({( newsSource : NewsSources) -> Bool in
// let doesPaywallMatch = (scope == Paywall.All) || (newsSource.paywall == scope.type)
//
// if searchBarIsEmpty() {
// return doesPaywallMatch
// } else {
// return doesPaywallMatch && newsSource.sourceName.lowercased().contains(searchText.lowercased())
// }
// })
// tableView.reloadData()
// }
func filterContentForSearchText(_ searchText: String) {
filteredTableData.removeAll(keepingCapacity: false)
filteredTableData = newsSources.filter({( newsSource : NewsSources) -> Bool in
return newsSource.sourceName.lowercased().contains(searchText.lowercased())
})
tableView.reloadData()
}
// func isFiltering() -> Bool {
// let searchBarScopeIsFiltering = searchController.searchBar.selectedScopeButtonIndex != 0
// return searchController.isActive && (!searchBarIsEmpty() || searchBarScopeIsFiltering)
// }
func isFiltering() -> Bool {
return searchController.isActive && !searchBarIsEmpty()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getNewsSources(){
// Get news sources for selected region from settings' store
if let newsSources: [NewsSources] = self.settings.newsSourcesByLang[self.settings.region] {
#if DEBUG
print("filter view, getNewsSources: getting news sources for '\(self.settings.region)' from settings")
print("newsSources=\(newsSources)")
#endif
if let updated: Date = self.settings.newsSourcesUpdatedByLang[self.settings.region] {
let calendar = Calendar.current
var comps = DateComponents()
comps.day = 1
let updatedPlusWeek = (calendar as NSCalendar).date(byAdding: comps, to: updated, options: NSCalendar.Options())
let today = Date()
#if DEBUG
print("today=\(today), updated=\(updated), updatedPlusWeek=\(String(describing: updatedPlusWeek))")
#endif
if updatedPlusWeek!.isLessThanDate(today) {
getNewsSourcesFromAPI()
return
}
}
self.settings.newsSources = newsSources
self.newsSources = newsSources
self.tableView!.reloadData()
return
}
#if DEBUG
print("filter view, getNewsSources: getting news sources for lang from API")
#endif
// If news sources for selected region is not found, fetch from API
getNewsSourcesFromAPI()
}
func getNewsSourcesFromAPI() {
HighFiApi.listSources(
{ (result) in
self.settings.newsSources = result
self.newsSources = result
self.settings.newsSourcesByLang.updateValue(self.settings.newsSources, forKey: self.settings.region)
do {
let archivedObject = try NSKeyedArchiver.archivedData(withRootObject: self.settings.newsSourcesByLang as Dictionary<String, Array<NewsSources>>, requiringSecureCoding: false)
self.defaults!.set(archivedObject, forKey: "newsSourcesByLang")
}
catch {
#if DEBUG
print("error: \(error)")
#endif
}
self.settings.newsSourcesUpdatedByLang.updateValue(Date(), forKey: self.settings.region)
self.defaults!.set(self.settings.newsSourcesUpdatedByLang, forKey: "newsSourcesUpdatedByLang")
// #if DEBUG
// print("news sources updated, \(String(describing: self.settings.newsSourcesUpdatedByLang[self.settings.region]))")
// #endif
self.defaults!.synchronize()
// #if DEBUG
// print("categoriesByLang=\(self.settings.categoriesByLang[self.settings.region])")
// #endif
self.tableView!.reloadData()
return
}
, failureHandler: {(error)in
self.handleError(error, title: self.errorTitle)
}
)
}
// stop observing
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension FilterNewsSourcesViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering() {
// searchFooter.setIsFilteringToShow(filteredItemCount: filteredTableData.count, of: newsSources.count)
return filteredTableData.count
}
// searchFooter.setNotFiltering()
return newsSources.count
}
private func mapPaywallToDesc(newsSource: NewsSources) -> String {
var paywallInfo = ""
payWallItems.forEach { (item) in
if (newsSource.paywall != "free" && item.type == newsSource.paywall) {
paywallInfo = " (" + item.description + ")"
}
}
return paywallInfo
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: MainStoryboard.TableViewCellIdentifiers.listCategoryCell, for: indexPath)
var tableItem: NewsSources
if isFiltering() {
tableItem = filteredTableData[indexPath.row] as NewsSources
} else {
tableItem = newsSources[indexPath.row] as NewsSources
}
cell.textLabel!.text = tableItem.sourceName + mapPaywallToDesc(newsSource: tableItem)
cell.textLabel!.textColor = Theme.cellTitleColor
cell.textLabel!.font = settings.fontSizeXLarge
if (settings.newsSourcesFiltered[settings.region]?.firstIndex(of: tableItem.sourceID) != nil) {
cell.backgroundColor = Theme.selectedColor
cell.accessibilityTraits = UIAccessibilityTraits.selected
} else {
if (indexPath.row % 2 == 0) {
cell.backgroundColor = Theme.evenRowColor
} else {
cell.backgroundColor = Theme.oddRowColor
}
}
Shared.hideWhiteSpaceBeforeCell(tableView, cell: cell)
return cell
}
}
extension FilterNewsSourcesViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var selectedNewsSource: NewsSources
if isFiltering() {
selectedNewsSource = self.filteredTableData[indexPath.row]
} else {
selectedNewsSource = self.newsSources[indexPath.row]
}
#if DEBUG
print("didSelectRowAtIndexPath, selectedNewsSource=\(selectedNewsSource.sourceName), \(selectedNewsSource.sourceID)")
#endif
self.trackEvent("removeSource", category: "ui_Event", action: "removeSource", label: "settings", value: selectedNewsSource.sourceID as NSNumber)
let removed = self.settings.removeSource(selectedNewsSource.sourceID)
self.newsSources[indexPath.row].selected = removed
defaults!.set(settings.newsSourcesFiltered, forKey: "newsSourcesFiltered")
defaults!.synchronize()
self.tableView!.reloadData()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let selectionColor = UIView() as UIView
selectionColor.backgroundColor = Theme.tintColor
cell.selectedBackgroundView = selectionColor
}
}
extension FilterNewsSourcesViewController: UISearchResultsUpdating {
// MARK: - UISearchResultsUpdating Delegate
// func updateSearchResults(for searchController: UISearchController) {
// let searchBar = searchController.searchBar
// let scope = payWallItems[searchBar.selectedScopeButtonIndex]
// filterContentForSearchText(searchController.searchBar.text!, scope: scope)
// }
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
//extension FilterNewsSourcesViewController: UISearchBarDelegate {
// // MARK: - UISearchBar Delegate
// func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
// filterContentForSearchText(searchBar.text!, scope: payWallItems[selectedScope])
// }
//}
| mit | a98ac805f7fdcf5782bd4cfd20c2847a | 36.785714 | 194 | 0.676875 | 5.291764 | false | false | false | false |
walokra/Haikara | Haikara/Models/Paywall.swift | 1 | 2576 | //
// PaywallType.swift
// highkara
//
// The MIT License (MIT)
//
// Copyright (c) 2018 Marko Wallin <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
var paywallTextAll: String = NSLocalizedString("PAYWALL_TEXT_ALL", comment: "News source paywall type")
var paywallTextFree: String = NSLocalizedString("PAYWALL_TEXT_FREE", comment: "News source paywall type")
var paywallTextPartial: String = NSLocalizedString("PAYWALL_TEXT_PARTIAL", comment: "News source paywall type")
var paywallTextMonthly: String = NSLocalizedString("PAYWALL_TEXT_MONTHLY", comment: "News source paywall type")
var paywallTextStrict: String = NSLocalizedString("PAYWALL_TEXT_STRICT", comment: "News source paywall type")
enum Paywall: String {
case All = "all"
case Free = "free"
case Partial = "partial"
case Monthly = "monthly-limit"
case Strict = "strict-paywall"
// func type() -> String {
// return self.rawValue
// }
var type: String {
switch self {
case .All: return "all"
case .Free: return "free"
case .Partial: return "partial"
case .Monthly: return "monthly-limit"
case .Strict: return "strict-paywall"
}
}
var description: String {
switch self {
case .All: return paywallTextAll
case .Free: return paywallTextFree
case .Partial: return paywallTextPartial
case .Monthly: return paywallTextMonthly
case .Strict: return paywallTextStrict
}
}
}
| mit | c4a2e3fff67adf7edaf267d7839352d6 | 38.030303 | 111 | 0.701475 | 4.236842 | false | false | false | false |
BBBInc/AlzPrevent-ios | researchline/ColorReadingActivityViewController.swift | 1 | 9293 | //
// ColorReadingViewController.swift
//
// Created by Leo Kang on 11/20/15.
// Copyright © 2015 bbb. All rights reserved.
//
import UIKit
import Alamofire
class ColorReadingActivityViewController: UIViewController {
@IBOutlet weak var redView: UIView!
@IBOutlet weak var orangeView: UIView!
@IBOutlet weak var yellowView: UIView!
@IBOutlet weak var greenView: UIView!
@IBOutlet weak var blueView: UIView!
@IBOutlet weak var purpleView: UIView!
@IBOutlet weak var renderedWord: UITextField!
@IBOutlet weak var resultView: UIImageView!
@IBOutlet weak var successLabel: UILabel!
@IBOutlet weak var failureLabel: UILabel!
@IBOutlet weak var descriptionText: UITextView!
@IBOutlet weak var startButton: UIButton!
var resultCorrectMap = [Int: Int]()
var resultTimeMap = [Int: NSTimeInterval]()
var resultTrials = [Bool]()
var resultFailImage: UIImage = UIImage(named: "X")!
var resultSuccessImage: UIImage = UIImage(named: "O")!
var taskName = "Color Reading"
var activityId: String? = ""
@IBAction func clickStartButton(sender: AnyObject) {
suffleTimer = NSTimer.scheduledTimerWithTimeInterval(2, target:self, selector: #selector(ColorReadingActivityViewController.suffle), userInfo: nil, repeats: false)
descriptionText.hidden = true
startButton.hidden = true
startFlag = true
answerFlag = true
}
@IBAction func clickBlue(sender: AnyObject) {
processClick(0)
}
@IBAction func clickGreen(sender: AnyObject) {
processClick(1)
}
@IBAction func clickOrange(sender: AnyObject) {
processClick(2)
}
@IBAction func clickPurple(sender: AnyObject) {
processClick(3)
}
@IBAction func clickRed(sender: AnyObject) {
processClick(4)
}
@IBAction func clickYellow(sender: AnyObject) {
processClick(5)
}
internal func processClick(number: Int){
timeoutTimer?.invalidate()
if(answerFlag || !startFlag){
return
}
answerFlag = true
resultView.hidden = false
let interval = NSDate().timeIntervalSinceDate(start!)
resultTimeMap[trial] = interval
var result = ""
if(answer == number){
resultView.image = resultSuccessImage
resultCorrectMap[1]? += 1
successLabel.text = "Success: \(resultCorrectMap[1]!)"
result = "correct"
resultTrials.append(true)
}else{
resultView.image = resultFailImage
resultCorrectMap[0]? += 1
failureLabel.text = "Failure: \(resultCorrectMap[0]!)"
result = "fail"
resultTrials.append(false)
}
trial += 1
debugPrint("\(trial)th trial result is \(result) while \(interval)")
suffleTimer = NSTimer.scheduledTimerWithTimeInterval(1.5, target:self, selector: #selector(ColorReadingActivityViewController.suffle), userInfo: nil, repeats: false)
}
var suffleTimer: NSTimer? = nil
var resultHideTimer: NSTimer? = nil
var timeoutTimer: NSTimer? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.hidesBottomBarWhenPushed = true
let activityKey = "id_\(self.taskName)"
debugPrint(activityKey)
self.activityId = Constants.userDefaults.stringForKey(activityKey)
debugPrint(activityId)
renderedWord.hidden = true
resultView.hidden = true
successLabel.hidden = true
failureLabel.hidden = true
resultCorrectMap[0] = 0
resultCorrectMap[1] = 0
redView.layer.cornerRadius = 5
redView.layer.borderWidth = 1
redView.layer.borderColor = UIColor.blackColor().CGColor
orangeView.layer.cornerRadius = 5
orangeView.layer.borderWidth = 1
orangeView.layer.borderColor = UIColor.blackColor().CGColor
yellowView.layer.cornerRadius = 5
yellowView.layer.borderWidth = 1
yellowView.layer.borderColor = UIColor.blackColor().CGColor
greenView.layer.cornerRadius = 5
greenView.layer.borderWidth = 1
greenView.layer.borderColor = UIColor.blackColor().CGColor
blueView.layer.cornerRadius = 5
blueView.layer.borderWidth = 1
blueView.layer.borderColor = UIColor.blackColor().CGColor
purpleView.layer.cornerRadius = 5
purpleView.layer.borderWidth = 1
purpleView.layer.borderColor = UIColor.blackColor().CGColor
}
var answerFlag = false
var startFlag = false
var value = 0
var answer = 0
var color = 0
var trial = 0
var start: NSDate? = nil
var isTimeout = false
internal func suffle(){
suffleTimer?.invalidate()
if(trial >= 5){
finish()
return
}
renderedWord.hidden = false
resultView.hidden = true
answerFlag = false
value = Int.init(arc4random_uniform(UInt32(36)))
color = value / 6
answer = value % 6
if(color == 0){
renderedWord.text = "Blue"
}else if(color == 1){
renderedWord.text = "Green"
}else if(color == 2){
renderedWord.text = "Orange"
}else if(color == 3){
renderedWord.text = "Purple"
}else if(color == 4){
renderedWord.text = "Red"
}else if(color == 5){
renderedWord.text = "Yellow"
}
if(answer == 0){
renderedWord.textColor = UIColor.blueColor();
}else if(answer == 1){
renderedWord.textColor = UIColor.greenColor();
}else if(answer == 2){
renderedWord.textColor = UIColor.orangeColor();
}else if(answer == 3){
renderedWord.textColor = UIColor.purpleColor();
}else if(answer == 4){
renderedWord.textColor = UIColor.redColor();
}else if(answer == 5){
renderedWord.textColor = UIColor.yellowColor();
}
start = NSDate()
isTimeout = false
timeoutTimer = NSTimer.scheduledTimerWithTimeInterval(3, target:self, selector: #selector(ColorReadingActivityViewController.timeout), userInfo: nil, repeats: false)
}
internal func timeout() {
timeoutTimer?.invalidate()
isTimeout = true
answerFlag = true
resultView.hidden = false
let interval = NSDate().timeIntervalSinceDate(start!)
resultTimeMap[trial] = interval
resultTrials.append(false)
trial += 1
resultCorrectMap[0]? += 1
debugPrint("\(trial)th trial result is fail by timeout")
resultView.image = resultFailImage
suffleTimer = NSTimer.scheduledTimerWithTimeInterval(1.5, target:self, selector: #selector(ColorReadingActivityViewController.suffle), userInfo: nil, repeats: false)
}
internal func hideResult(){
resultView.hidden = true
}
internal func finish(){
timeoutTimer?.invalidate()
descriptionText.text = "Test is finished. Your success score is \(resultCorrectMap[1]!)."
descriptionText.hidden = false
renderedWord.hidden = true
resultView.hidden = true
startFlag = false
var jsonResult = ""
for i in 0...(resultTimeMap.count-1) {
let timestamp = resultTimeMap[i]
let correct: String = String.init(resultTrials[i])
let trialJson = "{\"name\":\"\(taskName)\",\"timestamp\":\"\(timestamp!)\",\"correct\":\"\(correct)\",\"trial\":\"\(i)\"}";
if(i == 0){
jsonResult = "[\(trialJson)"
}else{
jsonResult = "\(jsonResult),\(trialJson)"
}
}
jsonResult += "]"
debugPrint(jsonResult)
Alamofire.request(.POST, Constants.activity, headers: [
"deviceKey": Constants.deviceKey,
"deviceType": Constants.deviceType,
"signKey": Constants.signKey()], parameters: [
"value": jsonResult,
"activityId": activityId!
])
.responseJSON { (response: Response) -> Void in
switch response.result{
case.Success(let json):
debugPrint(json)
if(json["success"] as? Int == 0){
break
}
break
default:
break
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| bsd-3-clause | 5f896f6b4a9c5ff651e6cb385c575edd | 31.950355 | 173 | 0.590185 | 5.122381 | false | false | false | false |
nodes-ios/NStackSDK | NStackSDK/NStackSDK/Classes/Other/UIButton+NStackLocalizable.swift | 1 | 2324 | //
// UIButton+NStackLocalizable.swift
// NStackSDK
//
// Created by Nicolai Harbo on 30/07/2019.
// Copyright © 2019 Nodes ApS. All rights reserved.
//
import Foundation
import UIKit
extension UIButton: NStackLocalizable {
private static var _backgroundColor = [String: UIColor?]()
private static var _userInteractionEnabled = [String: Bool]()
private static var _translationIdentifier = [String: TranslationIdentifier]()
@objc public func localize(for stringIdentifier: String) {
guard let identifier = SectionKeyHelper.transform(stringIdentifier) else { return }
NStack.sharedInstance.translationsManager?.localize(component: self, for: identifier)
}
@objc public func setLocalizedValue(_ localizedValue: String) {
setTitle(localizedValue, for: .normal)
}
public var translatableValue: String? {
get {
return titleLabel?.text
}
set {
titleLabel?.text = newValue
}
}
public var translationIdentifier: TranslationIdentifier? {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIButton._translationIdentifier[tmpAddress]
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIButton._translationIdentifier[tmpAddress] = newValue
}
}
public var originalBackgroundColor: UIColor? {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIButton._backgroundColor[tmpAddress] ?? .clear
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIButton._backgroundColor[tmpAddress] = newValue
}
}
public var originalIsUserInteractionEnabled: Bool {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UIButton._userInteractionEnabled[tmpAddress] ?? false
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UIButton._userInteractionEnabled[tmpAddress] = newValue
}
}
public var backgroundViewToColor: UIView? {
return titleLabel
}
}
| mit | 4f1a9cc440976ac2f3bf3ed51e4eb570 | 30.821918 | 93 | 0.632372 | 4.870021 | false | false | false | false |
FlaneurApp/FlaneurOpen | Example/FlaneurOpen/GooglePlacesDemoViewController.swift | 1 | 3794 | //
// GooglePlacesDemoViewController.swift
// FlaneurOpen
//
// Created by Mickaël Floc'hlay on 24/05/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import GooglePlaces
class GooglePlacesDemoViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var filterSegmentedControl: UISegmentedControl!
@IBOutlet weak var consoleTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let plist = Bundle.main.path(forResource: "FlaneurOpenSecretInfo", ofType: "plist") {
if let myProperties = NSDictionary(contentsOfFile: plist) {
if let googlePlacesAPIKey = myProperties.object(forKey: "GooglePlacesFlaneurOpenAPIKey") as? String {
if GMSPlacesClient.provideAPIKey(googlePlacesAPIKey) {
debugPrint("OK")
} else {
debugPrint("NOK -- Unauthorized")
}
} else {
debugPrint("NOK -- Couldn't find the specified key")
}
} else {
debugPrint("NOK -- Couldn't parse file at path", plist)
}
} else {
debugPrint("NOK -- Couldn't find file. Did you run the script from the README?")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func filter(withIndex segmentIndex: Int) -> GMSAutocompleteFilter {
let filter = GMSAutocompleteFilter()
switch segmentIndex {
case 0:
filter.type = .address
case 1:
filter.type = .city
case 2:
filter.type = .establishment
case 3:
filter.type = .geocode
case 4:
filter.type = .noFilter
case 5:
filter.type = .region
default:
debugPrint("Invalid index \(segmentIndex)")
}
return filter
}
func log(_ logMessage: String) {
consoleTextView.text = logMessage
}
func appendLog(_ logMessage: String) {
consoleTextView.text = consoleTextView.text + "\n---\n" + logMessage
}
@IBAction func searchAction(_ sender: Any) {
if let queryString = searchBar.text {
log("Searching for \(queryString)...")
let autocompleteFilter = filter(withIndex: filterSegmentedControl.selectedSegmentIndex)
GMSPlacesClient.shared().autocompleteQuery(queryString,
bounds: nil,
filter: autocompleteFilter) { (results, error) in
if let error = error {
self.log("Autocomplete error:\n\(error)")
return
}
if let results = results {
self.log("Found \(results.count) results")
for result in results {
self.appendLog("Result \(result.attributedFullText) with placeID \(String(describing: result.placeID))")
}
}
}
} else {
log("Can't search empty string")
}
}
}
| mit | 342f1218d94787b8a6b06312bdab538c | 37.30303 | 168 | 0.49077 | 6.019048 | false | false | false | false |
idomizrachi/Regen | regen/Dependencies/Stencil/_SwiftSupport.swift | 1 | 1185 | import Foundation
#if !swift(>=4.1)
public extension Sequence {
func compactMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
return try flatMap(transform)
}
}
#endif
#if !swift(>=4.1)
public extension Collection {
func index(_ index: Self.Index, offsetBy offset: Int) -> Self.Index {
let indexDistance = Self.IndexDistance(offset)
return self.index(index, offsetBy: indexDistance)
}
}
#endif
#if !swift(>=4.1)
public extension TemplateSyntaxError {
public static func == (lhs: TemplateSyntaxError, rhs: TemplateSyntaxError) -> Bool {
return lhs.reason == rhs.reason &&
lhs.description == rhs.description &&
lhs.token == rhs.token &&
lhs.stackTrace == rhs.stackTrace &&
lhs.templateName == rhs.templateName
}
}
#endif
#if !swift(>=4.1)
public extension Variable {
public static func == (lhs: Variable, rhs: Variable) -> Bool {
return lhs.variable == rhs.variable
}
}
#endif
#if !swift(>=4.2)
extension ArraySlice where Element: Equatable {
func firstIndex(of element: Element) -> Int? {
return index(of: element)
}
}
#endif
| mit | 46c1e2b71d685bd331e5a543790a2d7e | 24.76087 | 119 | 0.662447 | 3.923841 | false | false | false | false |
mircealungu/Zeeguu-API-iOS | ZeeguuAPI/ZeeguuAPI/Article.swift | 2 | 13941 | //
// Article.swift
// Zeeguu Reader
//
// Created by Jorrit Oosterhof on 08-12-15.
// Copyright © 2015 Jorrit Oosterhof.
//
// 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
/// Adds support for comparing `Article` objects using the equals operator (`==`)
///
/// - parameter lhs: The left `Article` operand of the `==` operator (left hand side) <pre><b>lhs</b> == rhs</pre>
/// - parameter rhs: The right `Article` operand of the `==` operator (right hand side) <pre>lhs == <b>rhs</b></pre>
/// - returns: A `Bool` that states whether the two `Article` objects are equal
public func ==(lhs: Article, rhs: Article) -> Bool {
return lhs.feed == rhs.feed && lhs.title == rhs.title && lhs.url == rhs.url && lhs.date == rhs.date && lhs.summary == rhs.summary
}
/// The `Article` class represents an article. It holds the source (`feed`), `title`, `url`, `date`, `summary` and more about the article.
public class Article: CustomStringConvertible, Equatable, ZGSerializable {
// MARK: Properties -
/// The `Feed` from which this article was retrieved
public var feed: Feed
/// The title of this article
public var title: String
/// The url of this article
public var url: String
/// The publication date of this article
public var date: NSDate
/// The summary of this article
public var summary: String
/// Whether this article has been read by the user. This propery is purely for use within an app. This boolean will not be populated from the server.
public var isRead: Bool
/// Whether this article has been starred by the user. This propery is purely for use within an app. This boolean will not be populated from the server.
public var isStarred: Bool
/// Whether this article has been liked by the user. This propery is purely for use within an app. This boolean will not be populated from the server.
public var isLiked: Bool
/// The difficulty that the user has given to this article. This propery is purely for use within an app. This boolean will not be populated from the server.
public var userDifficulty: ArticleDifficulty
/// Whether this article has been read completely by the user. This propery is purely for use within an app. This boolean will not be populated from the server.
public var hasReadAll: Bool
private var imageURL: String?
private var image: UIImage?
private var contents: String?
private var difficulty: ArticleDifficulty?
/// Whether the contents of this article have been retrieved yet
public var isContentLoaded: Bool {
return contents != nil
}
/// Whether the difficulty of this article has been calculated yet
public var isDifficultyLoaded: Bool {
return difficulty != nil
}
/// The description of this `Article` object. The value of this property will be used whenever the system tries to print this `Article` object or when the system tries to convert this `Article` object to a `String`.
public var description: String {
let str = feed.description.stringByReplacingOccurrencesOfString("\n", withString: "\n\t")
return "Article: {\n\tfeed: \"\(str)\",\n\ttitle: \"\(title)\",\n\turl: \"\(url)\",\n\tdate: \"\(date)\",\n\tsummary: \"\(summary)\",\n\tcontents: \"\(contents)\"\n}"
}
// MARK: Static methods -
/// Get difficulty for all given articles
///
/// Note: This method uses the default difficulty computer.
///
/// - parameter articles: The articles for which to get difficulties. Please note that all `Article` objects are references and once `completion` is called, the given `Article` objects have difficulties.
/// - parameter completion: A block that will indicate success. If `success` is `true`, all `Article` objects have been given their difficulty. Otherwise nothing has happened to the `Article` objects. If `articles` is empty, `success` is `false`.
public static func getDifficultiesForArticles(articles: [Article], completion: (success: Bool) -> Void) {
self.getContentsForArticles(articles, withDifficulty: true, completion: completion)
}
/// Get contents for all given articles
///
/// - parameter articles: The articles for which to get contents. Please note that all `Article` objects are references and once `completion` is called, the given `Article` objects have contents.
/// - parameter withDifficulty: Whether to calculate difficulty for the retrieved contents. Setting this to `true` will send the language code of the first article's feed as the language of all contents.
/// - parameter completion: A block that will indicate success. If `success` is `true`, all `Article` objects have been given their contents. Otherwise nothing has happened to the `Article` objects. If `articles` is empty, `success` is `false`.
public static func getContentsForArticles(articles: [Article], withDifficulty: Bool = false, completion: (success: Bool) -> Void) {
let urls = articles.flatMap({ $0.isContentLoaded && (!withDifficulty || $0.isDifficultyLoaded) ? nil : $0.url })
if urls.count == 0 {
return completion(success: false) // No articles to get content for
}
let langCode: String? = withDifficulty ? articles[0].feed.language : nil
ZeeguuAPI.sharedAPI().getContentFromURLs(urls, langCode: langCode, maxTimeout: urls.count * 10) { (contents) in
if let contents = contents {
for i in 0 ..< contents.count {
articles[i]._updateContents(contents[i], withDifficulty: withDifficulty)
}
return completion(success: true)
}
completion(success: false)
}
}
// MARK: Constructors -
/**
Construct a new `Article` object.
- parameter feed: The `Feed` from which this article was retrieved
- parameter title: The title of the article
- parameter url: The url of the article
- parameter date: The publication date of the article
- parameter summary: The summary of the article
*/
public init(feed: Feed, title: String, url: String, date: String, summary: String) {
self.feed = feed
self.title = title;
self.url = url;
let formatter = NSDateFormatter()
let enUSPosixLocale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.locale = enUSPosixLocale
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let date = formatter.dateFromString(date)
self.date = date!
self.summary = summary
self.isRead = false
self.isStarred = false
self.isLiked = false
self.userDifficulty = .Unknown
self.hasReadAll = false
}
/**
Construct a new `Article` object from the data in the dictionary.
- parameter dictionary: The dictionary that contains the data from which to construct an `Article` object.
*/
@objc public required init?(dictionary dict: [String: AnyObject]) {
var savedDate = dict["date"] as? NSDate
if let date = dict["date"] as? String {
let formatter = NSDateFormatter()
let enUSPosixLocale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.locale = enUSPosixLocale
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let date = formatter.dateFromString(date)
savedDate = date
}
guard let feed = dict["feed"] as? Feed,
title = dict["title"] as? String,
url = dict["url"] as? String,
date = savedDate,
summary = dict["summary"] as? String else {
return nil
}
self.feed = feed
self.title = title
self.url = url
self.date = date
self.summary = summary
self.isRead = dict["isRead"] as? Bool == true
self.isStarred = dict["isStarred"] as? Bool == true
self.imageURL = dict["imageURL"] as? String
self.image = dict["image"] as? UIImage
self.contents = dict["contents"] as? String
if let difficulty = dict["difficulty"] as? String {
self.difficulty = ArticleDifficulty(rawValue: difficulty)
}
self.isLiked = dict["isLiked"] as? Bool == true
if let str = dict["userDifficulty"] as? String, userDifficulty = ArticleDifficulty(rawValue: str) {
self.userDifficulty = userDifficulty
} else {
self.userDifficulty = .Unknown
}
self.hasReadAll = dict["hasReadAll"] as? Bool == true
}
// MARK: Methods -
/**
The dictionary representation of this `Article` object.
- returns: A dictionary that contains all data of this `Article` object.
*/
@objc public func dictionaryRepresentation() -> [String: AnyObject] {
var dict = [String: AnyObject]()
dict["feed"] = self.feed
dict["title"] = self.title
dict["url"] = self.url
dict["date"] = self.date
dict["summary"] = self.summary
dict["isRead"] = self.isRead
dict["isStarred"] = self.isStarred
dict["imageURL"] = self.imageURL
dict["image"] = self.image
dict["contents"] = self.contents
dict["difficulty"] = self.difficulty?.rawValue
dict["isLiked"] = self.isLiked
dict["userDifficulty"] = self.userDifficulty.rawValue
dict["hasReadAll"] = self.hasReadAll
return dict
}
/**
Get the contents of this article. This method will make sure that the contents are cached within this `Article` object, so calling this method again will not retrieve the contents again, but will return the cached version instead.
- parameter completion: A closure that will be called once the contents have been retrieved. If there were no contents to retrieve, `contents` is the empty string. Otherwise, it contains the article contents.
*/
public func getContents(completion: (contents: String) -> Void) {
if let c = contents {
return completion(contents: c)
}
_getContents { (contents) in
if let c = contents {
return completion(contents: c.0)
}
completion(contents: "")
}
}
/**
Get the image of this article. This method will make sure that the image url is cached within this `Article` object, so calling this method again will not retrieve the image again, but will return the cached version instead.
- parameter completion: A closure that will be called once the image has been retrieved. If there was no image to retrieve, `image` is `nil`. Otherwise, it contains the article image.
*/
public func getImage(completion: (image: UIImage?) -> Void) {
_getContents { (contents) in
if let c = contents, imURL = NSURL(string: c.1) {
let request = NSMutableURLRequest(URL: imURL)
ZeeguuAPI.sharedAPI().sendAsynchronousRequestWithDataResponse(request) { (data, error) -> Void in
if let res = data {
return completion(image: UIImage(data: res))
}
if ZeeguuAPI.sharedAPI().enableDebugOutput {
print("Could not get image with url '\(self.imageURL)', error: \(error)")
}
completion(image: nil)
}
} else {
completion(image: nil)
}
}
}
/**
Get the difficulty of this article. This method will make sure that the difficulty is cached within this `Article` object, so calling this method again will not calculate the difficulty again, but will return the cached version instead.
- parameter completion: A closure that will be called once the difficulty has been calculated. If there was no difficulty to calculate, `difficulty` is `ArticleDifficulty.Unknown`. Otherwise, it contains the article difficulty.
*/
public func getDifficulty(difficultyComputer: String = "default", completion: (difficulty: ArticleDifficulty) -> Void) {
if let diff = difficulty {
return completion(difficulty: diff)
}
if difficultyComputer == "default" {
_getContents(true) { (contents) in
if let c = contents {
return completion(difficulty: c.2)
}
completion(difficulty: .Unknown)
}
} else {
getContents({ (contents) in
if contents == "" {
return completion(difficulty: .Unknown)
}
ZeeguuAPI.sharedAPI().getDifficultyForTexts([contents], langCode: self.feed.language, difficultyComputer: difficultyComputer, completion: { (difficulties) in
if let diffs = difficulties {
self.difficulty = diffs[0]
return completion(difficulty: diffs[0])
}
completion(difficulty: .Unknown)
})
})
}
}
// MARK: -
private func _updateContents(contents: (String, String, ArticleDifficulty), withDifficulty: Bool) {
if contents.0 != "" {
self.contents = contents.0
}
if contents.1 != "" {
self.imageURL = contents.1
}
if withDifficulty {
self.difficulty = contents.2
}
}
private func _getContents(withDifficulty: Bool = false, completion: (contents: (String, String, ArticleDifficulty)?) -> Void) {
if let con = contents, imURL = imageURL, diff = difficulty where withDifficulty == true {
completion(contents: (con, imURL, diff))
} else if let con = contents, imURL = imageURL where withDifficulty == false {
completion(contents: (con, imURL, difficulty == nil ? .Unknown : difficulty!))
} else {
ZeeguuAPI.sharedAPI().getContentFromURLs([url]) { (contents) in
if let content = contents?[0] {
self._updateContents(content, withDifficulty: withDifficulty)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(contents: content)
})
} else {
if ZeeguuAPI.sharedAPI().enableDebugOutput {
print("Failure, no content")
}
}
}
}
}
}
| mit | 15291a2290998a2d5e471b2db231a1f2 | 41.242424 | 247 | 0.709613 | 3.912433 | false | false | false | false |
reTXT/thrift | lib/cocoa/src/TMap.swift | 1 | 4418 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import Foundation
public struct TMap<Key : TSerializable, Value : TSerializable> : CollectionType, DictionaryLiteralConvertible, TSerializable {
public static var thriftType : TType { return .MAP }
public typealias Storage = Dictionary<Key, Value>
public typealias Index = Storage.Index
public typealias Element = Storage.Element
public var storage : Storage
public var startIndex : Index {
return storage.startIndex
}
public var endIndex: Index {
return storage.endIndex
}
public var keys: LazyMapCollection<[Key : Value], Key> {
return storage.keys
}
public var values: LazyMapCollection<[Key : Value], Value> {
return storage.values
}
public init() {
storage = Storage()
}
public init(dictionaryLiteral elements: (Key, Value)...) {
storage = Storage()
for (key, value) in elements {
storage[key] = value
}
}
public init(_ dictionary: [Key: Value]) {
storage = dictionary
}
public init(minimumCapacity: Int) {
storage = Storage(minimumCapacity: minimumCapacity)
}
public subscript (position: Index) -> Element {
get {
return storage[position]
}
}
public func indexForKey(key: Key) -> Index? {
return storage.indexForKey(key)
}
public subscript (key: Key) -> Value? {
get {
return storage[key]
}
set {
storage[key] = newValue
}
}
public mutating func updateValue(value: Value, forKey key: Key) -> Value? {
return updateValue(value, forKey: key)
}
public mutating func removeAtIndex(index: DictionaryIndex<Key, Value>) -> (Key, Value) {
return removeAtIndex(index)
}
public mutating func removeValueForKey(key: Key) -> Value? {
return storage.removeValueForKey(key)
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
storage.removeAll(keepCapacity: keepCapacity)
}
public var hashValue : Int {
let prime = 31
var result = 1
for (key, value) in storage {
result = prime * result + key.hashValue
result = prime * result + value.hashValue
}
return result
}
public static func readValueFromProtocol(proto: TProtocol) throws -> TMap {
let (keyType, valueType, size) = try proto.readMapBegin()
if keyType != Key.thriftType || valueType != Value.thriftType {
throw NSError(
domain: TProtocolErrorDomain,
code: Int(TProtocolError.InvalidData.rawValue),
userInfo: [TProtocolErrorExtendedErrorKey: NSNumber(int: TProtocolExtendedError.UnexpectedType.rawValue)])
}
var map = TMap()
for _ in 0..<size {
let key = try Key.readValueFromProtocol(proto)
let value = try Value.readValueFromProtocol(proto)
map.storage[key] = value
}
try proto.readMapEnd()
return map
}
public static func writeValue(value: TMap, toProtocol proto: TProtocol) throws {
try proto.writeMapBeginWithKeyType(Key.thriftType, valueType: Value.thriftType, size: value.count)
for (key, value) in value.storage {
try Key.writeValue(key, toProtocol: proto)
try Value.writeValue(value, toProtocol: proto)
}
try proto.writeMapEnd()
}
}
extension TMap : CustomStringConvertible, CustomDebugStringConvertible {
public var description : String {
return storage.description
}
public var debugDescription : String {
return storage.debugDescription
}
}
public func ==<Key, Value>(lhs: TMap<Key,Value>, rhs: TMap<Key, Value>) -> Bool {
if lhs.count != rhs.count {
return false
}
return lhs.storage == rhs.storage
}
| apache-2.0 | 9345148bfe3717008924d563aa0d3d70 | 26.271605 | 126 | 0.685604 | 4.435743 | false | false | false | false |
TeamProxima/predictive-fault-tracker | mobile/SieHack/Pods/Charts/Source/Charts/Renderers/BarChartRenderer.swift | 15 | 22905 | //
// BarChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class BarChartRenderer: BarLineScatterCandleBubbleRenderer
{
fileprivate class Buffer
{
var rects = [CGRect]()
}
open weak var dataProvider: BarChartDataProvider?
public init(dataProvider: BarChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
// [CGRect] per dataset
fileprivate var _buffers = [Buffer]()
open override func initBuffers()
{
if let barData = dataProvider?.barData
{
// Matche buffers count to dataset count
if _buffers.count != barData.dataSetCount
{
while _buffers.count < barData.dataSetCount
{
_buffers.append(Buffer())
}
while _buffers.count > barData.dataSetCount
{
_buffers.removeLast()
}
}
for i in stride(from: 0, to: barData.dataSetCount, by: 1)
{
let set = barData.dataSets[i] as! IBarChartDataSet
let size = set.entryCount * (set.isStacked ? set.stackSize : 1)
if _buffers[i].rects.count != size
{
_buffers[i].rects = [CGRect](repeating: CGRect(), count: size)
}
}
}
else
{
_buffers.removeAll()
}
}
fileprivate func prepareBuffer(dataSet: IBarChartDataSet, index: Int)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData,
let animator = animator
else { return }
let barWidthHalf = barData.barWidth / 2.0
let buffer = _buffers[index]
var bufferIndex = 0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
let phaseY = animator.phaseY
var barRect = CGRect()
var x: Double
var y: Double
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
let vals = e.yValues
x = e.x
y = e.y
if !containsStacks || vals == nil
{
let left = CGFloat(x - barWidthHalf)
let right = CGFloat(x + barWidthHalf)
var top = isInverted
? (y <= 0.0 ? CGFloat(y) : 0)
: (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted
? (y >= 0.0 ? CGFloat(y) : 0)
: (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if top > 0
{
top *= CGFloat(phaseY)
}
else
{
bottom *= CGFloat(phaseY)
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
else
{
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// fill the stack
for k in 0 ..< vals!.count
{
let value = vals![k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let left = CGFloat(x - barWidthHalf)
let right = CGFloat(x + barWidthHalf)
var top = isInverted
? (y <= yStart ? CGFloat(y) : CGFloat(yStart))
: (y >= yStart ? CGFloat(y) : CGFloat(yStart))
var bottom = isInverted
? (y >= yStart ? CGFloat(y) : CGFloat(yStart))
: (y <= yStart ? CGFloat(y) : CGFloat(yStart))
// multiply the height of the rect with the phase
top *= CGFloat(phaseY)
bottom *= CGFloat(phaseY)
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
}
}
}
open override func drawData(context: CGContext)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
for i in 0 ..< barData.dataSetCount
{
guard let set = barData.getDataSetByIndex(i) else { continue }
if set.isVisible
{
if !(set is IBarChartDataSet)
{
fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset")
}
drawDataSet(context: context, dataSet: set as! IBarChartDataSet, index: i)
}
}
}
fileprivate var _barShadowRectBuffer: CGRect = CGRect()
open func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int)
{
guard
let dataProvider = dataProvider,
let viewPortHandler = self.viewPortHandler
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
prepareBuffer(dataSet: dataSet, index: index)
trans.rectValuesToPixel(&_buffers[index].rects)
let borderWidth = dataSet.barBorderWidth
let borderColor = dataSet.barBorderColor
let drawBorder = borderWidth > 0.0
context.saveGState()
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
guard
let animator = animator,
let barData = dataProvider.barData
else { return }
let barWidth = barData.barWidth
let barWidthHalf = barWidth / 2.0
var x: Double = 0.0
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
x = e.x
_barShadowRectBuffer.origin.x = CGFloat(x - barWidthHalf)
_barShadowRectBuffer.size.width = CGFloat(barWidth)
trans.rectValueToPixel(&_barShadowRectBuffer)
if !viewPortHandler.isInBoundsLeft(_barShadowRectBuffer.origin.x + _barShadowRectBuffer.size.width)
{
continue
}
if !viewPortHandler.isInBoundsRight(_barShadowRectBuffer.origin.x)
{
break
}
_barShadowRectBuffer.origin.y = viewPortHandler.contentTop
_barShadowRectBuffer.size.height = viewPortHandler.contentHeight
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(_barShadowRectBuffer)
}
}
let buffer = _buffers[index]
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(barRect)
}
}
let isSingleColor = dataSet.colors.count == 1
if isSingleColor
{
context.setFillColor(dataSet.color(atIndex: 0).cgColor)
}
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
if !isSingleColor
{
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
context.setFillColor(dataSet.color(atIndex: j).cgColor)
}
context.fill(barRect)
if drawBorder
{
context.setStrokeColor(borderColor.cgColor)
context.setLineWidth(borderWidth)
context.stroke(barRect)
}
}
context.restoreGState()
}
open func prepareBarHighlight(
x: Double,
y1: Double,
y2: Double,
barWidthHalf: Double,
trans: Transformer,
rect: inout CGRect)
{
let left = x - barWidthHalf
let right = x + barWidthHalf
let top = y1
let bottom = y2
rect.origin.x = CGFloat(left)
rect.origin.y = CGFloat(top)
rect.size.width = CGFloat(right - left)
rect.size.height = CGFloat(bottom - top)
trans.rectValueToPixel(&rect, phaseY: animator?.phaseY ?? 1.0)
}
open override func drawValues(context: CGContext)
{
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
guard
let dataProvider = dataProvider,
let viewPortHandler = self.viewPortHandler,
let barData = dataProvider.barData,
let animator = animator
else { return }
var dataSets = barData.dataSets
let valueOffsetPlus: CGFloat = 4.5
var posOffset: CGFloat
var negOffset: CGFloat
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
for dataSetIndex in 0 ..< barData.dataSetCount
{
guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue }
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
// calculate the correct offset depending on the draw position of the value
let valueFont = dataSet.valueFont
let valueTextHeight = valueFont.lineHeight
posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus)
negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus))
if isInverted
{
posOffset = -posOffset - valueTextHeight
negOffset = -negOffset - valueTextHeight
}
let buffer = _buffers[dataSetIndex]
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
// if only single values are drawn (sum)
if !dataSet.isStacked
{
for j in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let rect = buffer.rects[j]
let x = rect.origin.x + rect.size.width / 2.0
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(rect.origin.y)
|| !viewPortHandler.isInBoundsLeft(x)
{
continue
}
let val = e.y
drawValue(
context: context,
value: formatter.stringForValue(
val,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: val >= 0.0
? (rect.origin.y + posOffset)
: (rect.origin.y + rect.size.height + negOffset),
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(j))
}
}
else
{
// if we have stacks
var bufferIndex = 0
for index in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(index) as? BarChartDataEntry else { continue }
let vals = e.yValues
let rect = buffer.rects[bufferIndex]
let x = rect.origin.x + rect.size.width / 2.0
// we still draw stacked bars, but there is one non-stacked in between
if vals == nil
{
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(rect.origin.y)
|| !viewPortHandler.isInBoundsLeft(x)
{
continue
}
drawValue(
context: context,
value: formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: rect.origin.y +
(e.y >= 0 ? posOffset : negOffset),
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(index))
}
else
{
// draw stack values
let vals = vals!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for k in 0 ..< vals.count
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: 0.0, y: CGFloat(y * phaseY)))
}
trans.pointValuesToPixel(&transformed)
for k in 0 ..< transformed.count
{
let y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset)
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x)
{
continue
}
drawValue(
context: context,
value: formatter.stringForValue(
vals[k],
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: y,
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(index))
}
}
bufferIndex = vals == nil ? (bufferIndex + 1) : (bufferIndex + vals!.count)
}
}
}
}
}
/// Draws a value at the specified x and y position.
open func drawValue(context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: NSUIFont, align: NSTextAlignment, color: NSUIColor)
{
ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
context.saveGState()
var barRect = CGRect()
for high in indices
{
guard
let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet,
set.isHighlightEnabled
else { continue }
if let e = set.entryForXValue(high.x, closestToY: high.y) as? BarChartDataEntry
{
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
context.setFillColor(set.highlightColor.cgColor)
context.setAlpha(set.highlightAlpha)
let isStack = high.stackIndex >= 0 && e.isStacked
let y1: Double
let y2: Double
if isStack
{
if dataProvider.isHighlightFullBarEnabled
{
y1 = e.positiveSum
y2 = -e.negativeSum
}
else
{
let range = e.ranges?[high.stackIndex]
y1 = range?.from ?? 0.0
y2 = range?.to ?? 0.0
}
}
else
{
y1 = e.y
y2 = 0.0
}
prepareBarHighlight(x: e.x, y1: y1, y2: y2, barWidthHalf: barData.barWidth / 2.0, trans: trans, rect: &barRect)
setHighlightDrawPos(highlight: high, barRect: barRect)
context.fill(barRect)
}
}
context.restoreGState()
}
/// Sets the drawing position of the highlight object based on the riven bar-rect.
internal func setHighlightDrawPos(highlight high: Highlight, barRect: CGRect)
{
high.setDraw(x: barRect.midX, y: barRect.origin.y)
}
}
| mit | 8a19e5e37825278abfd31db47e61f79f | 35.242089 | 186 | 0.417682 | 6.514505 | false | false | false | false |
wenluma/swift | test/SILGen/default_arguments_generic.swift | 1 | 3026 | // RUN: %target-swift-frontend -emit-silgen -swift-version 3 %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -swift-version 4 %s | %FileCheck %s
func foo<T: ExpressibleByIntegerLiteral>(_: T.Type, x: T = 0) { }
struct Zim<T: ExpressibleByIntegerLiteral> {
init(x: T = 0) { }
init<U: ExpressibleByFloatLiteral>(_ x: T = 0, y: U = 0.5) { }
static func zim(x: T = 0) { }
static func zang<U: ExpressibleByFloatLiteral>(_: U.Type, _ x: T = 0, y: U = 0.5) { }
}
// CHECK-LABEL: sil hidden @_T025default_arguments_generic3baryyF : $@convention(thin) () -> () {
func bar() {
// CHECK: [[FOO_DFLT:%.*]] = function_ref @_T025default_arguments_generic3foo
// CHECK: apply [[FOO_DFLT]]<Int>
foo(Int.self)
// CHECK: [[ZIM_DFLT:%.*]] = function_ref @_T025default_arguments_generic3ZimV3zim
// CHECK: apply [[ZIM_DFLT]]<Int>
Zim<Int>.zim()
// CHECK: [[ZANG_DFLT_0:%.*]] = function_ref @_T025default_arguments_generic3ZimV4zang{{.*}}A0_
// CHECK: apply [[ZANG_DFLT_0]]<Int, Double>
// CHECK: [[ZANG_DFLT_1:%.*]] = function_ref @_T025default_arguments_generic3ZimV4zang{{.*}}A1_
// CHECK: apply [[ZANG_DFLT_1]]<Int, Double>
Zim<Int>.zang(Double.self)
// CHECK: [[ZANG_DFLT_1:%.*]] = function_ref @_T025default_arguments_generic3ZimV4zang{{.*}}A1_
// CHECK: apply [[ZANG_DFLT_1]]<Int, Double>
Zim<Int>.zang(Double.self, 22)
}
protocol Initializable {
init()
}
struct Generic<T: Initializable> {
init(_ value: T = T()) {}
}
struct InitializableImpl: Initializable {
init() {}
}
// CHECK-LABEL: sil hidden @_T025default_arguments_generic17testInitializableyyF
func testInitializable() {
// The ".init" is required to trigger the crash that used to happen.
_ = Generic<InitializableImpl>.init()
// CHECK: [[INIT:%.+]] = function_ref @_T025default_arguments_generic7GenericVACyxGxcfC
// CHECK: function_ref @_T025default_arguments_generic7GenericVACyxGxcfcfA_ : $@convention(thin) <τ_0_0 where τ_0_0 : Initializable> () -> @out τ_0_0
// CHECK: apply [[INIT]]<InitializableImpl>({{%.+}}, {{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : Initializable> (@in τ_0_0, @thin Generic<τ_0_0>.Type) -> Generic<τ_0_0>
} // CHECK: end sil function '_T025default_arguments_generic17testInitializableyyF'
// Local generic functions with default arguments
// CHECK-LABEL: sil hidden @_T025default_arguments_generic5outeryx1t_tlF : $@convention(thin) <T> (@in T) -> ()
func outer<T>(t: T) {
func inner1(x: Int = 0) {}
// CHECK: [[ARG_GENERATOR:%.*]] = function_ref @_T025default_arguments_generic5outeryx1t_tlF6inner1L_ySi1x_tlFfA_ : $@convention(thin) () -> Int
// CHECK: [[ARG:%.*]] = apply [[ARG_GENERATOR]]() : $@convention(thin) () -> Int
_ = inner1()
func inner2(x: Int = 0) { _ = T.self }
// CHECK: [[ARG_GENERATOR:%.*]] = function_ref @_T025default_arguments_generic5outeryx1t_tlF6inner2L_ySi1x_tlFfA_ : $@convention(thin) <τ_0_0> () -> Int
// CHECK: [[ARG:%.*]] = apply [[ARG_GENERATOR]]<T>() : $@convention(thin) <τ_0_0> () -> Int
_ = inner2()
}
| mit | 6d670bda02dee8c3c34081920e28e477 | 45.4 | 179 | 0.648541 | 3.106076 | false | false | false | false |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleApp/Services/AccessTokenProvider.swift | 1 | 7150 | /*
* Copyright 2022 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.
*/
import Combine
import Foundation
import GoogleRidesharingDriver
import UIKit
/// A service that can fetch tokens from the backend and test their validity.
///
/// Note that this class needs to inherit from NSObject in order to be able to adopt an Objective-C
/// protocol.
class AccessTokenProvider: NSObject, GMTDAuthorization, ObservableObject {
/// The data for a token as received from the Backend.
struct Token: Hashable, Codable {
let token: String
let creationTimestampMs: Date
let expirationTimestampMs: Date
static func loadFrom(from data: Data) throws -> Token {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.keyDecodingStrategy = .convertFromSnakeCase
return try decoder.decode(self, from: data)
}
}
/// Special-purpose error to indicate an uninitialized enum.
enum Errors: Error {
case uninitialized
}
/// Type for the most recent result.
typealias TokenOrError = Result<Token, Error>
/// Type for the callback from fetch().
typealias TokenCompletion = (TokenOrError) -> Void
/// The vehicleId for which we fetch tokens.
var vehicleId: String? {
didSet {
synchronize {
result = TokenOrError.failure(Errors.uninitialized)
fetch(nil)
}
}
}
/// This Error indicates that the vehicleId property was not set before fetch() was called.
enum TokenServiceError: Error {
case vehicleIdUninitialized
}
/// The most recent result.
///
/// Any token in this result may not be valid, so this shouldn't be
/// used for transactions; those should always call fetchToken().
/// This property is intended for debugging UIs that display the last result.
@Published public private(set) var result = TokenOrError.failure(Errors.uninitialized)
/// The cancelable for any token request in-flight.
private var inFlightFetch: AnyCancellable?
/// The set of completions to notify when a fetch completes.
private var completions: [TokenCompletion] = [TokenCompletion]()
/// Fetches an up-to-date token or reports an error.
///
/// This fetches a token, taking advantage of an internally cached token if it is still valid.
/// An error will be passed to the callback if a token cannot be fetched or if the vehicleId
/// property has not been initialized.
///
/// Since this is called by the GMTDAuthorization entry point below, this method
/// may be invoked on an arbitrary queue.
func fetch(_ callback: TokenCompletion?) {
synchronize {
switch result {
case .success(let token):
if token.expirationTimestampMs >= Date() {
callback?(result)
return
}
fallthrough
case .failure:
if let vehicleId = vehicleId {
if let callback = callback {
completions.append(callback)
}
if inFlightFetch != nil {
return
}
let backendBaseURL = URL(string: ApplicationDefaults.backendBaseURLString.value)!
var components = URLComponents(url: backendBaseURL, resolvingAgainstBaseURL: false)!
components.path = "/token/delivery_driver/\(vehicleId)"
let request = URLRequest(url: components.url!)
inFlightFetch =
URLSession
.DataTaskPublisher(request: request, session: .shared)
.receive(on: RunLoop.main)
.sink(
receiveCompletion: { [weak self] completion in
self?.handleReceiveCompletion(completion: completion)
},
receiveValue: { [weak self] output in
self?.handleReceiveData(data: output.data)
}
)
result = TokenOrError.failure(Errors.uninitialized)
} else {
/// vehicleId == nil
if let callback = callback {
callback(TokenOrError.failure(TokenServiceError.vehicleIdUninitialized))
}
return
}
}
}
}
/// Handler for the completion of the URLSession DataTask.
private func handleReceiveCompletion(
completion: Subscribers.Completion<URLSession.DataTaskPublisher.Failure>
) {
self.synchronize {
switch completion {
case .finished:
break
case .failure(let error):
self.result = TokenOrError.failure(error)
self.invokeCallbacks()
}
/// switch(completion)
self.inFlightFetch = nil
}
}
/// Handler for the data callback of the URLSession DataTask.
private func handleReceiveData(data: Data) {
var newResult = TokenOrError.failure(Errors.uninitialized)
do {
try newResult = TokenOrError.success(Token.loadFrom(from: data))
} catch {
newResult = TokenOrError.failure(error)
}
self.synchronize {
self.result = newResult
self.invokeCallbacks()
}
}
/// Entry point for GMTDAuthorization protocol called by DriverSDK.
///
/// The GMTDAuthorization header file notes that this method may be invoked on an arbitrary
/// queue.
func fetchToken(
with authorizationContext: GMTDAuthorizationContext?,
completion: @escaping GMTDAuthTokenFetchCompletionHandler
) {
/// Enforce the function signature.
assert(authorizationContext?.vehicleID != nil)
/// We expect DriverSDK to only be invoked on the single manifest supported by this app.
assert(authorizationContext?.vehicleID == vehicleId)
/// Fetch the token from the token service, which already handles caching.
fetch { tokenOrError in
switch tokenOrError {
case .failure(let error):
completion(nil, error)
case .success(let token):
completion(token.token, nil)
}
}
}
/// Re-entrant, lock-based synchronization primitive.
///
/// Equivalent to Objective-C @synchronized. See
/// https://www.cocoawithlove.com/blog/2016/06/02/threads-and-mutexes.html for more commentary
/// on synchronization in Swift. That also explains why this is in the individual class and not
/// placed in a helper function.
private func synchronize<T>(execute: () throws -> T) rethrows -> T {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
return try execute()
}
/// Invoke all pending callbacks with the current result and clear the completions array.
///
/// This must be called from inside a synchronize block.
private func invokeCallbacks() {
for completion in completions {
completion(self.result)
}
completions.removeAll()
}
}
| apache-2.0 | ead98b9114c1ba032571169228261468 | 33.375 | 99 | 0.675524 | 4.824561 | false | false | false | false |
DarielChen/DemoCode | iOS动画指南/iOS动画指南 - 6.可以很酷的转场动画/1.cook/2.Cook/Cook/PopAnimator.swift | 1 | 2913 | //
// PopAnimator.swift
// Cook
//
// Created by Dariel on 16/7/25.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
// 转场动画的原理:
/**
当两个控制器发生push或dismiss的时候,系统会把原始的view放到负责转场的控制器容器中,也会把目的的view也放进去,但是是不可见的,因此我们要做的就是把新的view显现出来,把老的view移除掉
*/
// 遵守协议
class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let duration = 1.0
var presenting = true
var originFrame = CGRect.zero
// 动画持续时间
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
//
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// 获得容器
let containerView = transitionContext.containerView()!
// 获得目标view
// viewForKey 获取新的和老的控制器的view
// viewControllerForKey 获取新的和老的控制器
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
// 拿到需要做动画的view
let herbView = presenting ? toView : fromView
// 获取初始和最终的frame
let initialFrame = presenting ? originFrame : herbView.frame
let finalFrame = presenting ? herbView.frame : originFrame
// 设置收缩比率
let xScaleFactor = presenting ? initialFrame.width / finalFrame.width : finalFrame.width / initialFrame.width
let yScaleFactor = presenting ? initialFrame.height / finalFrame.height : finalFrame.height / initialFrame.height
let scaleTransform = CGAffineTransformMakeScale(xScaleFactor, yScaleFactor)
// 当presenting的时候,设置herbView的初始位置
if presenting {
herbView.transform = scaleTransform
herbView.center = CGPoint(x: CGRectGetMidX(initialFrame), y: CGRectGetMidY(initialFrame))
herbView.clipsToBounds = true
}
containerView.addSubview(toView)
// 保证在最前,不然添加的东西看不到哦
containerView.bringSubviewToFront(herbView)
// 加了个弹性效果
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: [], animations: { () -> Void in
herbView.transform = self.presenting ? CGAffineTransformIdentity : scaleTransform
herbView.center = CGPoint(x: CGRectGetMidX(finalFrame), y: CGRectGetMidY(finalFrame))
}) { (_) -> Void in
transitionContext.completeTransition(true)
}
}
}
| mit | 82922945a672a3b8705a0ab251a475b2 | 33.648649 | 154 | 0.666537 | 4.978641 | false | false | false | false |
davejlin/treehouse | swift/swift3/RestaurantReviews/RestaurantReviews/YelpReviewsDataSource.swift | 1 | 1518 | //
// YelpReviewsDataSource.swift
// RestaurantReviews
//
// Created by Pasan Premaratne on 5/9/17.
// Copyright © 2017 Treehouse. All rights reserved.
//
import Foundation
import UIKit
class YelpReviewsDataSource: NSObject, UITableViewDataSource {
private var data: [YelpReview]
init(data: [YelpReview]) {
self.data = data
super.init()
}
// MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ReviewCell.reuseIdentifier, for: indexPath) as! ReviewCell
let review = object(at: indexPath)
let viewModel = ReviewCellViewModel(review: review)
cell.configure(with: viewModel)
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Reviews"
}
// MARK: Helpers
func update(_ object: YelpReview, at indexPath: IndexPath) {
data[indexPath.row] = object
}
func updateData(_ data: [YelpReview]) {
self.data = data
}
func object(at indexPath: IndexPath) -> YelpReview {
return data[indexPath.row]
}
}
| unlicense | f510fa487ec1c09ae6d27de7823dc7d9 | 25.155172 | 123 | 0.634806 | 4.785489 | false | false | false | false |
railsware/Sleipnir | Sleipnir/Spec/Matchers/Container/ContainSpec.swift | 1 | 5837 | //
// ContainSpec.swift
// Sleipnir
//
// Created by Artur Termenji on 7/22/14.
// Copyright (c) 2014 railsware. All rights reserved.
//
import Foundation
class ContainSpec : SleipnirSpec {
var containSpec : () = describe("Contain matcher") {
describe("when the container is an Array") {
var container: [Int]?
context("and it is is nil") {
beforeEach {
container = nil
}
it("should fail") {
let failureMessage = "Expected <nil> to contain <1>"
expectFailureWithMessage(failureMessage) {
expect(container).to(contain(1))
}
}
}
context("and it is empty") {
beforeEach {
container = [Int]()
}
it("should fail with a sensible failure message") {
let failureMessage = "Expected <[]> to contain <1>"
expectFailureWithMessage(failureMessage) {
expect(container).to(contain(1))
}
}
}
context("and it contains elements") {
beforeEach {
container = [1, 2, 3, 4, 5]
}
describe("positive match") {
let element = 1
it("should pass") {
expect(container).to(contain(element))
}
}
describe("negative match") {
let element = 1
it("should fail with a sensible failure message") {
let failureMessage = "Expected <[1, 2, 3, 4, 5]> to not contain <1>"
expectFailureWithMessage(failureMessage) {
expect(container).toNot(contain(element))
}
}
}
}
}
describe("when the container is a String") {
let container = "Test String"
var nested: String?
context("and it contains nested String") {
beforeEach {
nested = "Test"
}
describe("positive match") {
it("should pass") {
// expect(container).to(contain(nested!))
}
}
}
context("and it does not contain nested String") {
beforeEach {
nested = "Testt"
}
it("should fail with a sensible failure message") {
let failureMessage = "Expected <Test String> to contain <Testt>"
expectFailureWithMessage(failureMessage) {
// expect(container).to(contain(nested!))
}
}
}
}
describe("when the container is an NSArray") {
var container: NSArray?
context("and it is empty") {
beforeEach {
container = NSArray(array: [])
}
it("should fail with a sensible failure message") {
let failureMessage = "Expected <()> to contain <1>"
expectFailureWithMessage(failureMessage) {
expect(container).to(contain(1))
}
}
}
context("and it contains elements") {
beforeEach {
container = NSArray(array: [1, 2, 3, 4, 5])
}
describe("positive match") {
let element = 1
it("should pass") {
expect(container).to(contain(element))
}
}
context("when elements are Strings") {
beforeEach {
container = NSArray(array: ["test", "string"])
}
describe("positive match") {
let element = "test"
it("should pass") {
expect(container).to(contain(element))
}
}
}
}
}
describe("when the container is an NSSet") {
var container: NSSet?
context("and it is empty") {
beforeEach {
container = NSSet(array: [])
}
it("should fail with a sensible failure message") {
let failureMessage = "Expected <{()}> to contain <1>"
expectFailureWithMessage(failureMessage) {
expect(container).to(contain(1))
}
}
}
context("and it contains elements") {
beforeEach {
container = NSSet(array: [1, 2, 3, 4, 5])
}
describe("positive match") {
let element = 1
it("should pass") {
expect(container).to(contain(element))
}
}
}
}
}
} | mit | 78874a2072c2dc828663f5a9325d9d97 | 31.797753 | 92 | 0.371081 | 6.435502 | false | false | false | false |
0xcodezero/Vatrena | Vatrena/Vatrena/view/NLSegmentControl/UIView+Layout.swift | 3 | 6027 | //
// UIView+Layout.swift
// NLSegmentControl
//
// Created by songhailiang on 27/05/2017.
// Copyright © 2017 hailiang.song. All rights reserved.
//
import UIKit
// MARK: - Autolayout
public extension UIView {
@discardableResult
func nl_equalTop(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toView, attribute: .top, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalLeft(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalBottom(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toView, attribute: .bottom, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalRight(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: toView, attribute: .trailing, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalWidth(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: toView, attribute: .width, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalHeight(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: toView, attribute: .height, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalCenterX(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: toView, attribute: .centerX, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_equalCenterY(toView: UIView, offset: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: toView, attribute: .centerY, multiplier: 1.0, constant: offset)
layout.isActive = true
return layout
}
@discardableResult
func nl_marginTop(toView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toView, attribute: .bottom, multiplier: 1.0, constant: margin)
layout.isActive = true
return layout
}
@discardableResult
func nl_marginLeft(toView: UIView, margin: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: toView, attribute: .trailing, multiplier: 1.0, constant: margin)
layout.isActive = true
return layout
}
@discardableResult
func nl_marginBottom(toView: UIView, margin: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toView, attribute: .top, multiplier: 1.0, constant: margin)
layout.isActive = true
return layout
}
@discardableResult
func nl_marginRight(toView: UIView, margin: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: toView, attribute: .leading, multiplier: 1.0, constant: margin)
layout.isActive = true
return layout
}
@discardableResult
func nl_widthIs(_ width: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: width)
layout.isActive = true
return layout
}
@discardableResult
func nl_heightIs(_ height: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: height)
layout.isActive = true
return layout
}
@discardableResult
func nl_ratioIs(_ ratio: CGFloat) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let layout = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: self, attribute: .height, multiplier: ratio, constant: 0)
layout.isActive = true
return layout
}
}
| mit | 7d0a450b728dba73f2719c496608ed68 | 43.970149 | 166 | 0.690342 | 5.063866 | false | false | false | false |
finngaida/healthpad | Shared/ChartViews/WeightView.swift | 1 | 733 | //
// WeightView.swift
// HealthPad
//
// Created by Finn Gaida on 17.03.16.
// Copyright © 2016 Finn Gaida. All rights reserved.
//
import UIKit
public class WeightView: LineView {
override init(frame: CGRect) {
super.init(frame: frame)
self.color = .Yellow
self.titleText = "Weight"
self.averageText = "79 kg"
self.todayText = "78.5 kg"
self.dateText = "Today, 3:14 PM"
}
public override func majorValueFromHealthObject(obj:HealthObject) -> String {
if let o = obj as? Weight {
return "\(o.value)"
} else {return ""}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| apache-2.0 | a26a3fe878bbd3dfc0449aeb57694f7b | 21.875 | 81 | 0.584699 | 3.641791 | false | false | false | false |
stormpath/stormpath-sdk-swift | Stormpath/Networking/ResetPasswordAPIRequestManager.swift | 1 | 1029 | //
// ResetPasswordAPIRequestManager.swift
// Stormpath
//
// Created by Edward Jiang on 2/8/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import Foundation
typealias ResetPasswordAPIRequestCallback = ((NSError?) -> Void)
class ResetPasswordAPIRequestManager: APIRequestManager {
var email: String
var callback: ResetPasswordAPIRequestCallback
init(withURL url: URL, email: String, callback: @escaping ResetPasswordAPIRequestCallback) {
self.email = email
self.callback = callback
super.init(withURL: url)
}
override func prepareForRequest() {
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: ["email": email], options: [])
}
override func requestDidFinish(_ data: Data, response: HTTPURLResponse) {
performCallback(nil)
}
override func performCallback(_ error: NSError?) {
DispatchQueue.main.async {
self.callback(error)
}
}
}
| apache-2.0 | 9395fd46c774f0ad5cef723270614be9 | 26.052632 | 101 | 0.668288 | 4.715596 | false | false | false | false |
yikaraman/iOS8-day-by-day | 12-healthkit/BodyTemple/BodyTemple/TabBarViewController.swift | 1 | 2356 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import HealthKit
class TabBarViewController: UITabBarController {
var healthStore: HKHealthStore?
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
createAndPropagateHealthStore()
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
createAndPropagateHealthStore()
}
override func viewDidLoad() {
super.viewDidLoad()
requestAuthorisationForHealthStore()
}
private func createAndPropagateHealthStore() {
if self.healthStore == nil {
self.healthStore = HKHealthStore()
}
for vc in viewControllers {
if let healthStoreUser = vc as? HealthStoreUser {
healthStoreUser.healthStore = self.healthStore
}
}
}
private func requestAuthorisationForHealthStore() {
let dataTypesToWrite = [
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
]
let dataTypesToRead = [
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex),
HKCharacteristicType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)
]
self.healthStore?.requestAuthorizationToShareTypes(NSSet(array: dataTypesToWrite),
readTypes: NSSet(array: dataTypesToRead), completion: {
(success, error) in
if success {
println("User completed authorisation request.")
} else {
println("The user cancelled the authorisation request. \(error)")
}
})
}
}
| apache-2.0 | 4abe3160eb83e06f6551140031a506ff | 31.273973 | 101 | 0.729626 | 5.342404 | false | false | false | false |
taipingeric/RubyInSwift | RubyInSwiftExtension.swift | 1 | 6324 | import Foundation
extension Int {
/// Execute closure N times
func times(f: () -> ()) {
if self > 0 {
for _ in 0..<self { f() }
}
}
func times(@autoclosure f: () -> ()) {
if self > 0 {
for _ in 0..<self { f() }
}
}
}
extension CollectionType where Index.Distance == Int {
/// Return random element from collection, or nil if collection is empty or count out of range
public var sample: Generator.Element? {
if isEmpty { return nil }
let randomIndex = startIndex.advancedBy(Int(arc4random_uniform(UInt32(self.count))))
return self[randomIndex]
}
/// Return random elements from collection, or nil if collection is empty or count out of range
public func sample(count: Int = 1) -> [Generator.Element]? {
if isEmpty || count > self.count { return nil }
var count = count
var storedIndex: [Index] = []
while count > 0 {
let randomIndex = startIndex.advancedBy(Int(arc4random_uniform(UInt32(self.count))))
if storedIndex.contains(randomIndex) == false {
storedIndex.append(randomIndex)
count -= 1
}
}
var resultCollection: [Generator.Element] = []
storedIndex.forEach { resultCollection.append(self[$0]) }
return resultCollection
}
}
extension Array {
public func isIndexValid(index: Int) -> Bool { return self.indices.contains(index) }
public func isCountValid(count: Int) -> Bool { return count < self.count }
/// Unsigned Int index
private func uIndex(index: Int) -> Int {
return (index % count) + count
}
/// Return element at index, or nil if self is empty or out of range.
public func fetch(index: Int, defaultValue: Element? = nil) -> Generator.Element?{
guard self.count != 0 else {
return nil
}
if index < 0 {
return self[uIndex(index)]
}
if isIndexValid(index) {
return self[index]
} else {
return defaultValue ?? nil
}
}
/// Return element at index, or nil with exception closure executed if self is empty or out of range.
public func fetch(index: Int, exception: (Int -> ())?) -> Element? {
guard let element = fetch(index) else{
exception?(index)
return nil
}
return element
}
/// Returns the first N elements of self, or nil if self is empty or out of range.
public func first(count: Int) -> [Element]? {
return take(count)
}
/// Returns the last N elements of self, or nil if self is empty or out of range.
public func last(count: Int) -> [Element]? {
return drop(count)
}
/// Return first N elements in array, or nil if self is empty or out of range.
public func take(count: Int) -> [Element]? {
return isCountValid(count) ? Array(prefix(count)) : nil
}
/// Return last N elements in array, or nil if self is empty or out of range.
public func drop(count: Int) -> [Element]? {
return isCountValid(count) ? Array(suffix(count)) : nil
}
/// The number of elements the Array stores.
public var length: Int {
return count
}
public var size: Int {
return count
}
/// Returns `true` iff `self` is empty.
public var empty: Bool {
return isEmpty
}
/// Append the elements of `newElements` to `self`.
public mutating func push(newElements: Element...) {
self.appendContentsOf(newElements)
}
/// Insert the elements of `newElements` to the beginning of `self` .
public mutating func unshift(newElements: Element...) {
self.insertContentsOf(newElements, at: 0)
}
/// Insert the elements of `newElements` at the index of `self` .
public mutating func insert(index: Int, newElements: Element...) {
uIndex(index)
index < 0 ? self.insertContentsOf(newElements, at: uIndex(index) + 1) : self.insertContentsOf(newElements, at: index)
}
}
infix operator << { associativity left precedence 160 }
/// << operator: push elements to array
public func << <T>(inout left: [T], right: [T]) {
left.appendContentsOf(right)
}
extension SequenceType where Generator.Element : Equatable {
/// Returns `true` iff `element` is in `self`.
public func include(element: Generator.Element) -> Bool {
return contains(element)
}
}
extension Array {
/// If `!self.isEmpty`, remove the last element and return it, otherwise nil
public mutating func pop() -> Element? {
return popLast()
}
/// pop last N elements and return them, return nil count is no valid
public mutating func pop(count: Int) -> [Element]? {
guard isCountValid(count) else {
return nil
}
var arr: [Element] = []
count.times {
arr.append( self.popLast()! )
}
return arr.reverse()
}
/// Pop first element, otherwise return nil
public mutating func shift() -> Element? {
let first = self.first
removeAtIndex(0)
return first
}
/// Pop first N elements, nil if count is not available or array is empty
public mutating func shift(count: Int) -> [Element]? {
guard isCountValid(count) else {
return nil
}
var array: [Element] = []
count.times {
array.append( self.shift()! )
}
return array
}
/// Remove and return the element at index `i`, nil if index is not valid
public mutating func delete_at(index: Int) -> Element? {
guard isIndexValid(index) else {
return nil
}
return removeAtIndex(index)
}
}
extension Array where Element: Equatable {
/// Remove all elements equal to input item, nil if no matching element
public mutating func delete(item: Element, exception: (() -> Element)? = nil) -> Element? {
let isExist = contains(item)
self = self.filter { element -> Bool in
return element != item
}
if isExist {
return item
}
return exception?()
}
} | mit | 34677c9c90aa58bcaed763ec87c1a072 | 31.106599 | 125 | 0.585863 | 4.413119 | false | false | false | false |
lorentey/swift | test/attr/attr_availability_objc.swift | 36 | 9336 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
@objc
protocol OlfactoryProtocol {
@available(*, unavailable)
func bad() // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
func smelly() // expected-note {{here}}
@available(*, unavailable, renamed: "new")
func old() // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
func oldAndSmelly() // expected-note {{here}}
@available(*, unavailable)
var badProp: Int { get } // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
var smellyProp: Int { get } // expected-note {{here}}
@available(*, unavailable, renamed: "new")
var oldProp: Int { get } // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
var oldAndSmellyProp: Int { get } // expected-note {{here}}
@available(*, unavailable, renamed: "init")
func nowAnInitializer() // expected-note {{here}}
@available(*, unavailable, renamed: "init()")
func nowAnInitializer2() // expected-note {{here}}
@available(*, unavailable, renamed: "foo")
init(nowAFunction: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "foo(_:)")
init(nowAFunction2: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgNames(a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgRenamed(a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableNoArgs() // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableSame(a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableUnnamed(_ a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableUnnamedSame(_ a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableNewlyUnnamed(a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableMultiSame(a: Int, b: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)")
func unavailableMultiUnnamed(_ a: Int, _ b: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiNewlyUnnamed(a: Int, b: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "init(shinyNewName:)")
init(unavailableArgNames: Int) // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:)")
init(_ unavailableUnnamed: Int) // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:)")
init(unavailableNewlyUnnamed: Int) // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:b:)")
init(_ unavailableMultiUnnamed: Int, _ b: Int) // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:_:)")
init(unavailableMultiNewlyUnnamed a: Int, b: Int) // expected-note{{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableTooFew(a: Int, b: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:b:)")
func unavailableTooMany(a: Int) // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableNoArgsTooMany() // expected-note {{here}}
@available(*, unavailable, renamed: "Base.shinyLabeledArguments()")
func unavailableHasType() // expected-note {{here}}
}
final class SchnozType : OlfactoryProtocol {
@objc func bad() {} // expected-error {{cannot override 'bad' which has been marked unavailable}} {{none}}
@objc func smelly() {} // expected-error {{cannot override 'smelly' which has been marked unavailable: it was smelly}} {{none}}
@objc func old() {} // expected-error {{'old()' has been renamed to 'new'}} {{14-17=new}}
@objc func oldAndSmelly() {} // expected-error {{'oldAndSmelly()' has been renamed to 'new': it was smelly}} {{14-26=new}}
@objc var badProp: Int { return 0 } // expected-error {{cannot override 'badProp' which has been marked unavailable}} {{none}}
@objc var smellyProp: Int { return 0 } // expected-error {{cannot override 'smellyProp' which has been marked unavailable: it was smelly}} {{none}}
@objc var oldProp: Int { return 0 } // expected-error {{'oldProp' has been renamed to 'new'}} {{13-20=new}}
@objc var oldAndSmellyProp: Int { return 0 } // expected-error {{'oldAndSmellyProp' has been renamed to 'new': it was smelly}} {{13-29=new}}
@objc func nowAnInitializer() {} // expected-error {{'nowAnInitializer()' has been replaced by 'init'}} {{none}}
@objc func nowAnInitializer2() {} // expected-error {{'nowAnInitializer2()' has been replaced by 'init()'}} {{none}}
@objc init(nowAFunction: Int) {} // expected-error {{'init(nowAFunction:)' has been renamed to 'foo'}} {{none}}
@objc init(nowAFunction2: Int) {} // expected-error {{'init(nowAFunction2:)' has been renamed to 'foo(_:)'}} {{none}}
@objc func unavailableArgNames(a: Int) {} // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{14-33=shinyLabeledArguments}} {{34-34=example }}
@objc func unavailableArgRenamed(a param: Int) {} // expected-error {{'unavailableArgRenamed(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{14-35=shinyLabeledArguments}} {{36-37=example}}
@objc func unavailableNoArgs() {} // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{14-31=shinyLabeledArguments}}
@objc func unavailableSame(a: Int) {} // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{14-29=shinyLabeledArguments}}
@objc func unavailableUnnamed(_ a: Int) {} // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{14-32=shinyLabeledArguments}} {{33-34=example}}
@objc func unavailableUnnamedSame(_ a: Int) {} // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{14-36=shinyLabeledArguments}}
@objc func unavailableNewlyUnnamed(a: Int) {} // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{14-37=shinyLabeledArguments}} {{38-38=_ }}
@objc func unavailableMultiSame(a: Int, b: Int) {} // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{14-34=shinyLabeledArguments}}
@objc func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{14-37=shinyLabeledArguments}} {{38-39=example}} {{48-49=another}}
@objc func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{14-41=shinyLabeledArguments}}
@objc func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{14-42=shinyLabeledArguments}} {{43-43=_ }} {{51-51=_ }}
@objc init(unavailableArgNames: Int) {} // expected-error {{'init(unavailableArgNames:)' has been renamed to 'init(shinyNewName:)'}} {{14-14=shinyNewName }}
@objc init(_ unavailableUnnamed: Int) {} // expected-error {{'init(_:)' has been renamed to 'init(a:)'}} {{14-15=a}}
@objc init(unavailableNewlyUnnamed: Int) {} // expected-error {{'init(unavailableNewlyUnnamed:)' has been renamed to 'init(_:)'}} {{14-14=_ }}
@objc init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-error {{'init(_:_:)' has been renamed to 'init(a:b:)'}} {{14-15=a}} {{46-48=}}
@objc init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-error {{'init(unavailableMultiNewlyUnnamed:b:)' has been renamed to 'init(_:_:)'}} {{14-42=_}} {{51-51=_ }}
@objc func unavailableTooFew(a: Int, b: Int) {} // expected-error {{'unavailableTooFew(a:b:)' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}}
@objc func unavailableTooMany(a: Int) {} // expected-error {{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(x:b:)'}} {{none}}
@objc func unavailableNoArgsTooMany() {} // expected-error {{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}}
@objc func unavailableHasType() {} // expected-error {{'unavailableHasType()' has been replaced by 'Base.shinyLabeledArguments()'}} {{none}}
}
// Make sure we can still conform to a protocol with unavailable requirements,
// and check for some bogus diagnostics not being emitted.
@objc
protocol Snout {
@available(*, unavailable)
func sniff()
}
class Tapir : Snout {}
class Elephant : Snout {
@nonobjc func sniff() {}
}
class Puppy : Snout {}
extension Puppy {
func sniff() {}
}
class Kitten : Snout {}
extension Kitten {
@nonobjc func sniff() {}
}
| apache-2.0 | 8953f90ba86e9e20602256108b52e55d | 63.833333 | 237 | 0.69398 | 4.263014 | false | false | false | false |
joninsky/JVUtilities | JVUtilities/TUCell.swift | 1 | 2086 | //
// TUCell.swift
// JVUtilities
//
// Created by Jon Vogel on 4/7/16.
// Copyright © 2016 Jon Vogel. All rights reserved.
//
import UIKit
public class TUCell: UICollectionViewCell {
var cellImage: UIImageView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
cellImage.translatesAutoresizingMaskIntoConstraints = false
self.cellImage.contentMode = UIViewContentMode.ScaleAspectFit
self.addSubview(self.cellImage)
self.constrainImageView()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func constrainImageView() {
var constraints = [NSLayoutConstraint]()
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=0)-[image]-(>=0)-|", options: [], metrics: nil, views: ["image":self.cellImage])
for c in verticalConstraints {
constraints.append(c)
}
let centerHorizontal = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.cellImage, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)
constraints.append(centerHorizontal)
let centerVertical = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.cellImage, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)
constraints.append(centerVertical)
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=0)-[image]-(>=0)-|", options: [], metrics: nil, views: ["image":self.cellImage])
for c in horizontalConstraints {
constraints.append(c)
}
self.addConstraints(constraints)
}
}
| mit | b123246357fadc50868fd8e7808b20cc | 29.661765 | 226 | 0.633573 | 5.574866 | false | false | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/nested_arrays/main.swift | 2 | 914 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
class C {
private struct Nested { public static var g_counter = 1 }
let m_counter: Int
private init(_ val: Int) { m_counter = val }
class func Create() -> C {
Nested.g_counter += 1
return C(Nested.g_counter)
}
}
func main() {
var aInt = [[1,2,3,4,5],[1,2,3,4],[1,2,3],[1,2],[1],[]]
var aC = [[C.Create(),C.Create(),C.Create(),C.Create()],[C.Create(),C.Create()],[],[C.Create()],[C.Create(),C.Create()]]
print(0) // break here
}
main()
| apache-2.0 | c901cd8ed2707085b955248bae8411e1 | 30.517241 | 122 | 0.585339 | 3.39777 | false | false | false | false |
mshhmzh/firefox-ios | Utils/Extensions/HexExtensions.swift | 4 | 2389 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
extension String {
public var hexDecodedData: NSData {
// Convert to a CString and make sure it has an even number of characters (terminating 0 is included, so we
// check for uneven!)
guard let cString = self.cStringUsingEncoding(NSASCIIStringEncoding) where (cString.count % 2) == 1 else {
return NSData()
}
guard let result = NSMutableData(capacity: (cString.count - 1) / 2) else {
return NSData()
}
for i in 0.stride(to: (cString.count - 1), by: 2) {
guard let l = hexCharToByte(cString[i]), r = hexCharToByte(cString[i+1]) else {
return NSData()
}
var value: UInt8 = (l << 4) | r
result.appendBytes(&value, length: sizeofValue(value))
}
return result
}
private func hexCharToByte(c: CChar) -> UInt8? {
if c >= 48 && c <= 57 { // 0 - 9
return UInt8(c - 48)
}
if c >= 97 && c <= 102 { // a - f
return 10 + UInt8(c - 97)
}
if c >= 65 && c <= 70 { // A - F
return 10 + UInt8(c - 65)
}
return nil
}
}
private let HexDigits: [String] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
extension NSData {
public var hexEncodedString: String {
let result = NSMutableString(capacity: length * 2)
let p = UnsafePointer<UInt8>(bytes)
for i in 0..<length {
result.appendString(HexDigits[Int((p[i] & 0xf0) >> 4)])
result.appendString(HexDigits[Int(p[i] & 0x0f)])
}
return String(result)
}
public class func randomOfLength(length: UInt) -> NSData? {
let length = Int(length)
if let data = NSMutableData(length: length) {
_ = SecRandomCopyBytes(kSecRandomDefault, length, UnsafeMutablePointer<UInt8>(data.mutableBytes))
return NSData(data: data)
} else {
return nil
}
}
}
extension NSData {
public var base64EncodedString: String {
return base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
}
}
| mpl-2.0 | 42ffdbd4724b23e2c1f9716250206767 | 33.623188 | 115 | 0.55923 | 3.929276 | false | false | false | false |
kasketis/netfox | netfox_ios_demo/TextViewController.swift | 1 | 2603 | //
// TextViewController.swift
// netfox_ios_demo
//
// Created by Nathan Jangula on 10/12/17.
// Copyright © 2017 kasketis. All rights reserved.
//
import UIKit
class TextViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var session: URLSession!
var dataTask: URLSessionDataTask?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBAction func tappedLoad(_ sender: Any) {
dataTask?.cancel()
if session == nil {
session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
}
guard let url = URL(string: "https://api.chucknorris.io/jokes/random") else { return }
let request = URLRequest(url: url)
dataTask = session.dataTask(with: request) { (data, response, error) in
if let error = error {
self.handleCompletion(error: error.localizedDescription, data: data)
} else {
guard let data = data else { self.handleCompletion(error: "Invalid data", data: nil); return }
guard let response = response as? HTTPURLResponse else { self.handleCompletion(error: "Invalid response", data: data); return }
guard response.statusCode >= 200 && response.statusCode < 300 else { self.handleCompletion(error: "Invalid response code", data: data); return }
self.handleCompletion(error: error?.localizedDescription, data: data)
}
}
dataTask?.resume()
}
private func handleCompletion(error: String?, data: Data?) {
DispatchQueue.main.async {
if let error = error {
NSLog(error)
return
}
if let data = data {
do {
let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
if let message = dict?["value"] as? String {
self.textView.text = message
}
} catch {
}
}
}
}
}
extension TextViewController : URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
}
}
| mit | 658cd19d123f67998ba5792b99aecf26 | 34.643836 | 186 | 0.57648 | 5.214429 | false | false | false | false |
MAARK/Charts | Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift | 5 | 12730 | //
// XAxisRendererHorizontalBarChart.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class XAxisRendererHorizontalBarChart: XAxisRenderer
{
internal weak var chart: BarChartView?
@objc public init(viewPortHandler: ViewPortHandler, xAxis: XAxis?, transformer: Transformer?, chart: BarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer)
self.chart = chart
}
open override func computeAxis(min: Double, max: Double, inverted: Bool)
{
var min = min, max = max
if let transformer = self.transformer
{
// calculate the starting and entry point of the y-labels (depending on
// zoom / contentrect bounds)
if viewPortHandler.contentWidth > 10 && !viewPortHandler.isFullyZoomedOutY
{
let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
if inverted
{
min = Double(p2.y)
max = Double(p1.y)
}
else
{
min = Double(p1.y)
max = Double(p2.y)
}
}
}
computeAxisValues(min: min, max: max)
}
open override func computeSize()
{
guard let
xAxis = self.axis as? XAxis
else { return }
let longest = xAxis.getLongestLabel() as NSString
let labelSize = longest.size(withAttributes: [NSAttributedString.Key.font: xAxis.labelFont])
let labelWidth = floor(labelSize.width + xAxis.xOffset * 3.5)
let labelHeight = labelSize.height
let labelRotatedSize = CGSize(width: labelSize.width, height: labelHeight).rotatedBy(degrees: xAxis.labelRotationAngle)
xAxis.labelWidth = labelWidth
xAxis.labelHeight = labelHeight
xAxis.labelRotatedWidth = round(labelRotatedSize.width + xAxis.xOffset * 3.5)
xAxis.labelRotatedHeight = round(labelRotatedSize.height)
}
open override func renderAxisLabels(context: CGContext)
{
guard
let xAxis = self.axis as? XAxis
else { return }
if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled || chart?.data === nil
{
return
}
let xoffset = xAxis.xOffset
if xAxis.labelPosition == .top
{
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
}
else if xAxis.labelPosition == .topInside
{
drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
else if xAxis.labelPosition == .bottom
{
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
else if xAxis.labelPosition == .bottomInside
{
drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
}
/// draws the x-labels on the specified y-position
open override func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint)
{
guard
let xAxis = self.axis as? XAxis,
let transformer = self.transformer
else { return }
let labelFont = xAxis.labelFont
let labelTextColor = xAxis.labelTextColor
let labelRotationAngleRadians = xAxis.labelRotationAngle.DEG2RAD
let centeringEnabled = xAxis.isCenterAxisLabelsEnabled
// pre allocate to save performance (dont allocate in loop)
var position = CGPoint(x: 0.0, y: 0.0)
for i in stride(from: 0, to: xAxis.entryCount, by: 1)
{
// only fill x values
position.x = 0.0
if centeringEnabled
{
position.y = CGFloat(xAxis.centeredEntries[i])
}
else
{
position.y = CGFloat(xAxis.entries[i])
}
transformer.pointValueToPixel(&position)
if viewPortHandler.isInBoundsY(position.y)
{
if let label = xAxis.valueFormatter?.stringForValue(xAxis.entries[i], axis: xAxis)
{
drawLabel(
context: context,
formattedLabel: label,
x: pos,
y: position.y,
attributes: [NSAttributedString.Key.font: labelFont, NSAttributedString.Key.foregroundColor: labelTextColor],
anchor: anchor,
angleRadians: labelRotationAngleRadians)
}
}
}
}
@objc open func drawLabel(
context: CGContext,
formattedLabel: String,
x: CGFloat,
y: CGFloat,
attributes: [NSAttributedString.Key : Any],
anchor: CGPoint,
angleRadians: CGFloat)
{
ChartUtils.drawText(
context: context,
text: formattedLabel,
point: CGPoint(x: x, y: y),
attributes: attributes,
anchor: anchor,
angleRadians: angleRadians)
}
open override var gridClippingRect: CGRect
{
var contentRect = viewPortHandler.contentRect
let dy = self.axis?.gridLineWidth ?? 0.0
contentRect.origin.y -= dy / 2.0
contentRect.size.height += dy
return contentRect
}
private var _gridLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
open override func drawGridLine(context: CGContext, x: CGFloat, y: CGFloat)
{
if viewPortHandler.isInBoundsY(y)
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: y))
context.strokePath()
}
}
open override func renderAxisLine(context: CGContext)
{
guard let xAxis = self.axis as? XAxis else { return }
if !xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled
{
return
}
context.saveGState()
context.setStrokeColor(xAxis.axisLineColor.cgColor)
context.setLineWidth(xAxis.axisLineWidth)
if xAxis.axisLineDashLengths != nil
{
context.setLineDash(phase: xAxis.axisLineDashPhase, lengths: xAxis.axisLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
if xAxis.labelPosition == .top ||
xAxis.labelPosition == .topInside ||
xAxis.labelPosition == .bothSided
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
context.strokePath()
}
if xAxis.labelPosition == .bottom ||
xAxis.labelPosition == .bottomInside ||
xAxis.labelPosition == .bothSided
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
context.strokePath()
}
context.restoreGState()
}
open override func renderLimitLines(context: CGContext)
{
guard
let xAxis = self.axis as? XAxis,
let transformer = self.transformer
else { return }
var limitLines = xAxis.limitLines
if limitLines.count == 0
{
return
}
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= l.lineWidth / 2.0
clippingRect.size.height += l.lineWidth
context.clip(to: clippingRect)
position.x = 0.0
position.y = CGFloat(l.limit)
position = position.applying(trans)
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.setStrokeColor(l.lineColor.cgColor)
context.setLineWidth(l.lineWidth)
if l.lineDashLengths != nil
{
context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
let label = l.label
// if drawing the limit-value label is enabled
if l.drawLabelEnabled && label.count > 0
{
let labelLineHeight = l.valueFont.lineHeight
let xOffset: CGFloat = 4.0 + l.xOffset
let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset
if l.labelPosition == .topRight
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .right,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .bottomRight
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .right,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .topLeft
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .left,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .left,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
}
}
}
}
| apache-2.0 | 5c0b0cc1b88aa020c6a235da1d915299 | 34.758427 | 137 | 0.536449 | 5.482343 | false | false | false | false |
couchbase/couchbase-lite-ios | Swift/Tests/PredictiveQueryTest.swift | 1 | 44772 | //
// PredictiveQueryTest.swift
// CouchbaseLite
//
// Copyright (c) 2018 Couchbase, Inc. All rights reserved.
//
// Licensed under the Couchbase License Agreement (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://info.couchbase.com/rs/302-GJY-034/images/2017-10-30_License_Agreement.pdf
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
import CouchbaseLiteSwift
class PredictiveQueryTest: CBLTestCase {
override func setUp() {
super.setUp()
Database.prediction.unregisterModel(withName: AggregateModel.name)
Database.prediction.unregisterModel(withName: TextModel.name)
Database.prediction.unregisterModel(withName: EchoModel.name)
}
@discardableResult
func createDocument(withNumbers numbers: [Int]) -> MutableDocument {
let doc = MutableDocument()
doc.setValue(numbers, forKey: "numbers")
try! db.saveDocument(doc)
return doc
}
func testRegisterAndUnregisterModel() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction))
.from(DataSource.database(db))
// Query before registering the model:
expectError(domain: "CouchbaseLite.SQLite", code: 1) {
_ = try q.execute()
}
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let rows = try verifyQuery(q) { (n, r) in
let pred = r.dictionary(at: 0)!
XCTAssertEqual(pred.int(forKey: "sum"), 15)
}
XCTAssertEqual(rows, 1);
aggregateModel.unregisterModel()
// Query after unregistering the model:
expectError(domain: "CouchbaseLite.SQLite", code: 1) {
_ = try q.execute()
}
}
func testRegisterMultipleModelsWithSameName() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
let model = "TheModel"
let aggregateModel = AggregateModel()
Database.prediction.registerModel(aggregateModel, withName: model)
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction))
.from(DataSource.database(db))
var rows = try verifyQuery(q) { (n, r) in
let pred = r.dictionary(at: 0)!
XCTAssertEqual(pred.int(forKey: "sum"), 15)
}
XCTAssertEqual(rows, 1);
// Register a new model with the same name:
let echoModel = EchoModel()
Database.prediction.registerModel(echoModel, withName: model)
// Query again should use the new model:
rows = try verifyQuery(q) { (n, r) in
let pred = r.dictionary(at: 0)!
XCTAssertNil(pred.value(forKey: "sum"))
XCTAssert(pred.array(forKey: "numbers")!.toArray() == [1, 2, 3, 4, 5])
}
XCTAssertEqual(rows, 1);
Database.prediction.unregisterModel(withName: model)
}
func testPredictionInputOutput() throws {
// Register echo model:
let echoModel = EchoModel()
echoModel.registerModel()
// Create a doc:
let doc = self.createDocument()
doc.setString("Daniel", forKey: "name")
doc.setInt(2, forKey: "number")
try self.saveDocument(doc)
// Create prediction function input:
let date = Date()
let dateStr = jsonFromDate(date)
let power = Function.power(base: Expression.property("number"), exponent: Expression.value(2))
let dict: [String: Any] = [
// Literal:
"number1": 10,
"number2": 10.1,
"int_min": Int.min,
"int_max": Int.max,
"int64_min": Int64.min,
"int64_max": Int64.max,
"float_min": Float.leastNormalMagnitude,
"float_max": Float.greatestFiniteMagnitude,
"double_min": Double.leastNormalMagnitude,
// rounding error: https://issues.couchbase.com/browse/CBL-1363
// "double_max": Double.greatestFiniteMagnitude,
"boolean_true": true,
"boolean_false": false,
"string": "hello",
"date": date,
"null": NSNull(),
"dict": ["foo": "bar"],
"array": ["1", "2", "3"],
// Expression:
"expr_property": Expression.property("name"),
"expr_value_number1": Expression.value(20),
"expr_value_number2": Expression.value(20.1),
"expr_value_boolean": Expression.value(true),
"expr_value_string": Expression.value("hi"),
"expr_value_date": Expression.value(date),
"expr_value_null": Expression.value(nil),
"expr_value_dict": Expression.value(["ping": "pong"]),
"expr_value_array": Expression.value(["4", "5", "6"]),
"expr_power": power
]
// Execute query and validate output:
let input = Expression.value(dict)
let model = EchoModel.name
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
let pred = r.dictionary(at: 0)!
XCTAssertEqual(pred.count, dict.count)
// Literal:
XCTAssertEqual(pred.int(forKey: "number1"), 10)
XCTAssertEqual(pred.double(forKey: "number2"), 10.1)
XCTAssertEqual(pred.int(forKey: "int_min"), Int.min)
XCTAssertEqual(pred.int(forKey: "int_max"), Int.max)
XCTAssertEqual(pred.int64(forKey: "int64_min"), Int64.min)
XCTAssertEqual(pred.int64(forKey: "int64_max"), Int64.max)
XCTAssertEqual(pred.float(forKey: "float_min"), Float.leastNormalMagnitude)
XCTAssertEqual(pred.float(forKey: "float_max"), Float.greatestFiniteMagnitude)
XCTAssertEqual(pred.double(forKey: "double_min"), Double.leastNormalMagnitude)
XCTAssertEqual(pred.boolean(forKey: "boolean_true"), true)
XCTAssertEqual(pred.boolean(forKey: "boolean_false"), false)
XCTAssertEqual(pred.string(forKey: "string"), "hello")
XCTAssertEqual(jsonFromDate(pred.date(forKey: "date")!), dateStr)
XCTAssertEqual(pred.value(forKey: "null") as! NSNull, NSNull())
XCTAssert(pred.dictionary(forKey: "dict")!.toDictionary() == ["foo": "bar"] as [String: Any])
XCTAssert(pred.array(forKey: "array")!.toArray() == ["1", "2", "3"])
// Expression:
XCTAssertEqual(pred.string(forKey: "expr_property"), "Daniel")
XCTAssertEqual(pred.int(forKey: "expr_value_number1"), 20)
XCTAssertEqual(pred.double(forKey: "expr_value_number2"), 20.1)
XCTAssertEqual(pred.boolean(forKey: "expr_value_boolean"), true)
XCTAssertEqual(pred.string(forKey: "expr_value_string"), "hi")
XCTAssertEqual(jsonFromDate(pred.date(forKey: "expr_value_date")!), dateStr)
XCTAssertEqual(pred.value(forKey: "expr_value_null") as! NSNull, NSNull())
XCTAssert(pred.dictionary(forKey: "expr_value_dict")!.toDictionary() == ["ping": "pong"] as [String: Any])
XCTAssert(pred.array(forKey: "expr_value_array")!.toArray() == ["4", "5", "6"])
XCTAssertEqual(pred.int(forKey: "expr_power"), 4)
}
XCTAssertEqual(rows, 1);
echoModel.unregisterModel()
}
func testPredictionWithBlobPropertyInput() throws {
let texts = [
"Knox on fox in socks in box. Socks on Knox and Knox in box.",
"Clocks on fox tick. Clocks on Knox tock. Six sick bricks tick. Six sick chicks tock."
]
for text in texts {
let doc = MutableDocument()
doc.setBlob(blobForString(text), forKey: "text")
try db.saveDocument(doc)
}
let textModel = TextModel()
textModel.registerModel()
let model = TextModel.name
let input = Expression.dictionary(["text" : Expression.property("text")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.property("text"),
SelectResult.expression(prediction.property("wc")).as("wc"))
.from(DataSource.database(db))
.where(prediction.property("wc").greaterThan(Expression.value(15)))
let rows = try verifyQuery(q) { (n, r) in
let blob = r.blob(forKey: "text")!
let text = String(bytes: blob.content!, encoding: .utf8)!
XCTAssertEqual(text, texts[1])
XCTAssertEqual(r.int(forKey: "wc"), 16)
}
XCTAssertEqual(rows, 1);
textModel.unregisterModel()
}
func testPredictionWithBlobParameterInput() throws {
try db.saveDocument(MutableDocument())
let textModel = TextModel()
textModel.registerModel()
let model = TextModel.name
let input = Expression.dictionary(["text" : Expression.parameter("text")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("wc")).as("wc"))
.from(DataSource.database(db))
let params = Parameters()
params.setBlob(blobForString("Knox on fox in socks in box. Socks on Knox and Knox in box."),
forName: "text")
q.parameters = params
let rows = try verifyQuery(q) { (n, r) in
XCTAssertEqual(r.int(at: 0), 14)
}
XCTAssertEqual(rows, 1);
textModel.unregisterModel()
}
func testPredictionWithNonSupportedInputTypes() throws {
try db.saveDocument(MutableDocument())
let echoModel = EchoModel()
echoModel.registerModel()
// Query with non dictionary input:
let model = EchoModel.name
let input = Expression.value("string")
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction))
.from(DataSource.database(db))
expectError(domain: "CouchbaseLite.SQLite", code: 1) {
_ = try q.execute()
}
// Query with non-supported value type in dictionary input.
// Note: The code below will crash the test as Swift cannot handle exception thrown by
// Objective-C
//
// let input2 = Expression.value(["key": self])
// let prediction2 = Function.prediction(model: model, input: input2)
// let q2 = QueryBuilder
// .select(SelectResult.expression(prediction2))
// .from(DataSource.database(db))
// try q2.execute()
echoModel.unregisterModel()
}
func testQueryPredictionResultDictionary() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.property("numbers"), SelectResult.expression(prediction))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let pred = r.dictionary(at: 1)!
XCTAssertEqual(pred.int(forKey: "sum"), numbers.value(forKeyPath: "@sum.self") as! Int)
XCTAssertEqual(pred.int(forKey: "min"), numbers.value(forKeyPath: "@min.self") as! Int)
XCTAssertEqual(pred.int(forKey: "max"), numbers.value(forKeyPath: "@max.self") as! Int)
XCTAssertEqual(pred.int(forKey: "avg"), numbers.value(forKeyPath: "@avg.self") as! Int)
}
XCTAssertEqual(rows, 2);
aggregateModel.unregisterModel()
}
func testQueryPredictionValues() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.property("numbers"),
SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("min")).as("min"),
SelectResult.expression(prediction.property("max")).as("max"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let sum = r.int(at: 1)
let min = r.int(at: 2)
let max = r.int(at: 3)
let avg = r.int(at: 4)
XCTAssertEqual(sum, r.int(forKey: "sum"))
XCTAssertEqual(min, r.int(forKey: "min"))
XCTAssertEqual(max, r.int(forKey: "max"))
XCTAssertEqual(avg, r.int(forKey: "avg"))
XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int)
XCTAssertEqual(min, numbers.value(forKeyPath: "@min.self") as! Int)
XCTAssertEqual(max, numbers.value(forKeyPath: "@max.self") as! Int)
XCTAssertEqual(avg, numbers.value(forKeyPath: "@avg.self") as! Int)
}
XCTAssertEqual(rows, 2);
aggregateModel.unregisterModel()
}
func testWhereUsingPredictionValues() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.property("numbers"),
SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("min")).as("min"),
SelectResult.expression(prediction.property("max")).as("max"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let sum = r.int(at: 1)
XCTAssertEqual(sum, 15)
let min = r.int(at: 2)
let max = r.int(at: 3)
let avg = r.int(at: 4)
XCTAssertEqual(sum, r.int(forKey: "sum"))
XCTAssertEqual(min, r.int(forKey: "min"))
XCTAssertEqual(max, r.int(forKey: "max"))
XCTAssertEqual(avg, r.int(forKey: "avg"))
XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int)
XCTAssertEqual(min, numbers.value(forKeyPath: "@min.self") as! Int)
XCTAssertEqual(max, numbers.value(forKeyPath: "@max.self") as! Int)
XCTAssertEqual(avg, numbers.value(forKeyPath: "@avg.self") as! Int)
}
XCTAssertEqual(rows, 1);
aggregateModel.unregisterModel()
}
func testOrderByUsingPredictionValues() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
.where(prediction.property("sum").greaterThan(Expression.value(1)))
.orderBy(Ordering.expression(prediction.property("sum")).descending())
var sums: [Int] = []
let rows = try verifyQuery(q) { (n, r) in
sums.append(r.int(at: 0))
}
XCTAssertEqual(rows, 2);
XCTAssertEqual(sums, [40, 15])
aggregateModel.unregisterModel()
}
func testPredictiveModelReturningNull() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
let doc = createDocument()
doc.setString("Knox on fox in socks in box. Socks on Knox and Knox in box.", forKey: "text")
try saveDocument(doc)
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
var q: Query = QueryBuilder
.select(SelectResult.expression(prediction),
SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
var rows = try verifyQuery(q) { (n, r) in
if n == 1 {
XCTAssertNotNil(r.dictionary(at: 0))
XCTAssertEqual(r.int(at: 1), 15)
} else {
XCTAssertNil(r.value(at: 0))
XCTAssertNil(r.value(at: 1))
}
}
XCTAssertEqual(rows, 2);
// Evaluate with nullOrMissing:
q = QueryBuilder
.select(SelectResult.expression(prediction),
SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
.where(prediction.notNullOrMissing())
rows = try verifyQuery(q) { (n, r) in
XCTAssertNotNil(r.dictionary(at: 0))
XCTAssertEqual(r.int(at: 1), 15)
}
XCTAssertEqual(rows, 1);
}
func testIndexPredictionValueUsingValueIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let index = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("sum")))
try db.createIndex(index, withName: "SumIndex")
let q = QueryBuilder
.select(SelectResult.property("numbers"), SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let sum = r.int(at: 1)
XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
}
func testIndexMultiplePredictionValuesUsingValueIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let sumIndex = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("sum")))
try db.createIndex(sumIndex, withName: "SumIndex")
let avgIndex = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("avg")))
try db.createIndex(avgIndex, withName: "AvgIndex")
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
.where(prediction.property("sum").lessThanOrEqualTo(Expression.value(15)).or(
prediction.property("avg").equalTo(Expression.value(8))))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
XCTAssertNotEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
XCTAssert(r.int(at: 0) == 15 || r.int(at: 1) == 8)
}
XCTAssertEqual(rows, 2);
}
func testIndexCompoundPredictiveValuesUsingValueIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let index = IndexBuilder.valueIndex(items: ValueIndexItem.expression(prediction.property("sum")),
ValueIndexItem.expression(prediction.property("avg")))
try db.createIndex(index, withName: "SumAvgIndex")
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)).and(
prediction.property("avg").equalTo(Expression.value(3))))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumAvgIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
XCTAssertEqual(r.int(at: 0), 15)
XCTAssertEqual(r.int(at: 1), 3)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 4);
}
func testIndexPredictionResultUsingPredictiveIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let index = IndexBuilder.predictiveIndex(model: model, input: input)
try db.createIndex(index, withName: "AggIndex")
let q = QueryBuilder
.select(SelectResult.property("numbers"),
SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
let explain = try q.explain() as NSString
XCTAssertEqual(explain.range(of: "USING INDEX AggIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let sum = r.int(at: 1)
XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
aggregateModel.unregisterModel()
}
func testIndexPredictionValueUsingPredictiveIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let index = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["sum"])
try db.createIndex(index, withName: "SumIndex")
let q = QueryBuilder
.select(SelectResult.property("numbers"),
SelectResult.expression(prediction.property("sum")).as("sum"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
let sum = r.int(at: 1)
XCTAssertEqual(sum, numbers.value(forKeyPath: "@sum.self") as! Int)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
aggregateModel.unregisterModel()
}
func testIndexMultiplePredictionValuesUsingPredictiveIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let sumIndex = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["sum"])
try db.createIndex(sumIndex, withName: "SumIndex")
let avgIndex = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["avg"])
try db.createIndex(avgIndex, withName: "AvgIndex")
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
.where(prediction.property("sum").lessThanOrEqualTo(Expression.value(15)).or(
prediction.property("avg").equalTo(Expression.value(8))))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
XCTAssertNotEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
XCTAssert(r.int(at: 0) == 15 || r.int(at: 1) == 8)
}
XCTAssertEqual(rows, 2);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
aggregateModel.unregisterModel()
}
func testIndexCompoundPredictiveValuesUsingPredictiveIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
let index = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["sum", "avg"])
try db.createIndex(index, withName: "SumAvgIndex")
let q = QueryBuilder
.select(SelectResult.expression(prediction.property("sum")).as("sum"),
SelectResult.expression(prediction.property("avg")).as("avg"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)).and(
prediction.property("avg").equalTo(Expression.value(3))))
let explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumAvgIndex").location, NSNotFound)
let rows = try verifyQuery(q) { (n, r) in
XCTAssertEqual(r.int(at: 0), 15)
XCTAssertEqual(r.int(at: 1), 3)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
aggregateModel.unregisterModel()
}
func testDeletePredictiveIndex() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
// Index:
let index = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["sum"])
try db.createIndex(index, withName: "SumIndex")
// Query with index:
var q: Query = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
var explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
var rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
// Delete SumIndex:
try db.deleteIndex(forName: "SumIndex")
// Query again:
aggregateModel.reset()
q = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
explain = try q.explain() as NSString
XCTAssertEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
aggregateModel.unregisterModel()
}
func testDeletePredictiveIndexesSharingSameCacheTable() throws {
createDocument(withNumbers: [1, 2, 3, 4, 5])
createDocument(withNumbers: [6, 7, 8, 9, 10])
let aggregateModel = AggregateModel()
aggregateModel.registerModel()
let model = AggregateModel.name
let input = Expression.value(["numbers": Expression.property("numbers")])
let prediction = Function.prediction(model: model, input: input)
// Create agg index:
let aggIndex = IndexBuilder.predictiveIndex(model: model, input: input)
try db.createIndex(aggIndex, withName: "AggIndex")
// Create sum index:
let sumIndex = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["sum"])
try db.createIndex(sumIndex, withName: "SumIndex")
// Create avg index:
let avgIndex = IndexBuilder.predictiveIndex(model: model, input: input, properties: ["avg"])
try db.createIndex(avgIndex, withName: "AvgIndex")
// Query:
var q: Query = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("sum").lessThanOrEqualTo(Expression.value(15)).or(
prediction.property("avg").equalTo(Expression.value(8))))
var explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
XCTAssertNotEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
var rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 2);
XCTAssertEqual(aggregateModel.numberOfCalls, 2);
// Delete SumIndex:
try db.deleteIndex(forName: "SumIndex")
// Note: when having only one index, SQLite optimizer doesn't utilize the index
// when using OR expr. Hence explicity test each index with two queries:
aggregateModel.reset()
q = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("sum").equalTo(Expression.value(15)))
explain = try q.explain() as NSString
XCTAssertEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 0);
aggregateModel.reset()
q = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("avg").equalTo(Expression.value(8)))
explain = try q.explain() as NSString
XCTAssertNotEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 0);
// Delete AvgIndex
try db.deleteIndex(forName: "AvgIndex")
aggregateModel.reset()
q = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("avg").equalTo(Expression.value(8)))
explain = try q.explain() as NSString
XCTAssertEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 1);
XCTAssertEqual(aggregateModel.numberOfCalls, 0);
// Delete AggIndex
try db.deleteIndex(forName: "AggIndex")
aggregateModel.reset()
q = QueryBuilder
.select(SelectResult.property("numbers"))
.from(DataSource.database(db))
.where(prediction.property("sum").lessThanOrEqualTo(Expression.value(15)).or(
prediction.property("avg").equalTo(Expression.value(8))))
explain = try q.explain() as NSString
XCTAssertEqual(explain.range(of: "USING INDEX SumIndex").location, NSNotFound)
XCTAssertEqual(explain.range(of: "USING INDEX AvgIndex").location, NSNotFound)
rows = try verifyQuery(q) { (n, r) in
let numbers = r.array(at: 0)!.toArray() as NSArray
XCTAssert(numbers.count > 0)
}
XCTAssertEqual(rows, 2);
XCTAssert(aggregateModel.numberOfCalls > 0);
aggregateModel.unregisterModel()
}
func testEuclideanDistance() throws {
let tests: [[Any]] = [
[[10, 10], [13, 14], 5],
[[1, 2, 3], [1, 2, 3], 0],
[[], [], 0],
[[1, 2], [1, 2, 3], NSNull()],
[[1, 2], "foo", NSNull()]
]
for test in tests {
let doc = MutableDocument()
doc.setValue(test[0], forKey: "v1")
doc.setValue(test[1], forKey: "v2")
doc.setValue(test[2], forKey: "distance")
try db.saveDocument(doc)
}
let distance = Function.euclideanDistance(between: Expression.property("v1"),
and: Expression.property("v2"))
let q = QueryBuilder
.select(SelectResult.expression(distance), SelectResult.property("distance"))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
if r.value(at: 1) == nil {
XCTAssertNil(r.value(at: 0))
} else {
XCTAssertEqual(r.int(at: 0), r.int(at: 1))
}
}
XCTAssertEqual(Int(rows), tests.count);
}
func testSquaredEuclideanDistance() throws {
let tests: [[Any]] = [
[[10, 10], [13, 14], 25],
[[1, 2, 3], [1, 2, 3], 0],
[[], [], 0],
[[1, 2], [1, 2, 3], NSNull()],
[[1, 2], "foo", NSNull()]
]
for test in tests {
let doc = MutableDocument()
doc.setValue(test[0], forKey: "v1")
doc.setValue(test[1], forKey: "v2")
doc.setValue(test[2], forKey: "distance")
try db.saveDocument(doc)
}
let distance = Function.squaredEuclideanDistance(between: Expression.property("v1"),
and: Expression.property("v2"))
let q = QueryBuilder
.select(SelectResult.expression(distance), SelectResult.property("distance"))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
if r.value(at: 1) == nil {
XCTAssertNil(r.value(at: 0))
} else {
XCTAssertEqual(r.int(at: 0), r.int(at: 1))
}
}
XCTAssertEqual(Int(rows), tests.count);
}
func testCosineDistance() throws {
let tests: [[Any]] = [
[[10, 0], [0, 99], 1.0],
[[1, 2, 3], [1, 2, 3], 0.0],
[[1, 0, -1], [-1, -1, 0], 1.5],
[[], [], NSNull()],
[[1, 2], [1, 2, 3], NSNull()],
[[1, 2], "foo", NSNull()]
]
for test in tests {
let doc = MutableDocument()
doc.setValue(test[0], forKey: "v1")
doc.setValue(test[1], forKey: "v2")
doc.setValue(test[2], forKey: "distance")
try db.saveDocument(doc)
}
let distance = Function.cosineDistance(between: Expression.property("v1"),
and: Expression.property("v2"))
let q = QueryBuilder
.select(SelectResult.expression(distance), SelectResult.property("distance"))
.from(DataSource.database(db))
let rows = try verifyQuery(q) { (n, r) in
if r.value(at: 1) == nil {
XCTAssertNil(r.value(at: 0))
} else {
XCTAssertEqual(r.double(at: 0), r.double(at: 1))
}
}
XCTAssertEqual(Int(rows), tests.count);
}
}
// MARK: Models
class TestPredictiveModel: PredictiveModel {
class var name: String {
return "Untitled"
}
var numberOfCalls = 0
func predict(input: DictionaryObject) -> DictionaryObject? {
numberOfCalls = numberOfCalls + 1
return self.doPredict(input: input)
}
func doPredict(input: DictionaryObject) -> DictionaryObject? {
return nil
}
func registerModel() {
Database.prediction.registerModel(self, withName: type(of: self).name)
}
func unregisterModel() {
Database.prediction.unregisterModel(withName: type(of: self).name)
}
func reset() {
numberOfCalls = 0
}
}
class EchoModel: TestPredictiveModel {
override class var name: String {
return "EchoModel"
}
override func doPredict(input: DictionaryObject) -> DictionaryObject? {
return input;
}
}
class AggregateModel: TestPredictiveModel {
override class var name: String {
return "AggregateModel"
}
override func doPredict(input: DictionaryObject) -> DictionaryObject? {
guard let numbers = input.array(forKey: "numbers")?.toArray() as NSArray? else {
return nil
}
let output = MutableDictionaryObject()
output.setValue(numbers.value(forKeyPath: "@sum.self"), forKey: "sum")
output.setValue(numbers.value(forKeyPath: "@min.self"), forKey: "min")
output.setValue(numbers.value(forKeyPath: "@max.self"), forKey: "max")
output.setValue(numbers.value(forKeyPath: "@avg.self"), forKey: "avg")
return output
}
}
class TextModel: TestPredictiveModel {
override class var name: String {
return "TextModel"
}
override func doPredict(input: DictionaryObject) -> DictionaryObject? {
guard let blob = input.blob(forKey: "text") else {
return nil
}
guard let contentType = blob.contentType, contentType == "text/plain" else {
NSLog("WARN: Invalid blob content type; not text/plain.")
return nil
}
let text = String(bytes: blob.content!, encoding: .utf8)! as NSString
var wc = 0
var sc = 0
var curSentLoc = NSNotFound
text.enumerateLinguisticTags(in: NSRange(location: 0, length: text.length),
scheme: NSLinguisticTagScheme(rawValue: NSLinguisticTagScheme.tokenType.rawValue),
options: [], orthography: nil)
{ (tag, token, sent, stop) in
if tag!.rawValue == NSLinguisticTag.word.rawValue {
wc = wc + 1
}
if sent.location != NSNotFound && curSentLoc != sent.location {
curSentLoc = sent.location
sc = sc + 1
}
}
let output = MutableDictionaryObject()
output.setInt(wc, forKey: "wc")
output.setInt(sc, forKey: "sc")
return output
}
}
| apache-2.0 | 89435dec5c49bf6fb8f1d9b08deac6d8 | 39.813127 | 119 | 0.580541 | 4.633823 | false | true | false | false |
akiramur/PeerClient | PeerClient/PeerConnection.swift | 1 | 5617 | //
// PeerConnection.swift
// PeerClient
//
// Created by Akira Murao on 10/16/15.
// Copyright © 2017 Akira Murao. All rights reserved.
//
import Foundation
import libjingle_peerconnection
public protocol PeerConnectionDelegate {
func connection(connection: PeerConnection, shouldSendMessage message: [String: Any]) // TODO: replace this with block?
func connection(connection: PeerConnection, didReceiveRemoteStream stream: RTCMediaStream?)
func connection(connection: PeerConnection, didClose error: Error?)
func connection(connection: PeerConnection, didReceiveData data: Data)
}
enum PeerConnectionError: Error {
case invalidState
case creatingDataChannel
}
public class PeerConnection: NSObject {
public enum ConnectionType {
case media
case data
public var string: String {
switch self {
case .media:
return "media"
case .data:
return "data"
}
}
var prefix: String {
switch self {
case .media:
return "mc_"
case .data:
return "dc_"
}
}
}
var delegate: PeerConnectionDelegate?
var closeCompletionBlock: ((Error?) -> Void)?
public private(set) var peerId: String
public var connectionId: String {
get {
return self.options.connectionId
}
}
public var connectionType: PeerConnection.ConnectionType {
get {
return self.options.connectionType
}
}
var pc: RTCPeerConnection? {
didSet {
print("PeerConnection pc: \(String(describing: self.pc))")
}
}
var isOpen: Bool
var options: PeerConnectionOptions
var lostMessages: [[String: Any]]
var negotiator: Negotiator
/*
options = @{
@"connectionId": connectionId,
@"payload": payload,
@"metadata": metadata}
*/
init(peerId: String?, delegate: PeerConnectionDelegate?, options: PeerConnectionOptions) {
//EventEmitter.call(this); // lets move this to public method call
self.delegate = delegate
self.peerId = peerId ?? ""
self.pc = nil
self.isOpen = false
self.options = options
self.lostMessages = [[String: Any]]()
self.negotiator = Negotiator()
super.init()
// lets call this in subclasses
//self.startConnection(options)
}
func close(_ completion: @escaping (Error?) -> Void) {
print("PeerConnection close() \(self.options.connectionId)")
guard self.closeCompletionBlock == nil else {
print("ERROR: closeCompletionBlock already exists. something went wrong.")
return
}
if !self.isOpen {
completion(PeerConnectionError.invalidState)
return
}
self.closeCompletionBlock = completion
self.isOpen = false
if let pc = self.pc {
self.negotiator.stopConnection(pc: pc)
}
self.pc = nil
//this.emit('close')
// MEMO: let's call this in iceConnectionChanged: RTCICEConnectionClosed
//DispatchQueue.main.async {
// self.delegate?.connectionDidClose(connection: self)
//}
}
// from Negotiator
func handleLostMessages() {
// Find messages.
let messages = self.getMessages()
for message in messages {
self.handleMessage(message: message)
}
}
func storeMessage(message: [String: Any]) {
self.lostMessages.append(message)
}
func getMessages() -> [[String: Any]] {
let messages = self.lostMessages
self.lostMessages.removeAll()
return messages
}
func handleMessage(message: [String: Any]) {
print("handleMessage")
guard let pc = self.pc else {
print("ERROR: pc does't exist")
return
}
guard let payload = message["payload"] as? [String: Any] else {
print("ERROR: payload doesn't exist")
return
}
guard let type = message["type"] as? String else {
print("ERROR: type doesn't exist")
return
}
print("TYPE: \(type)")
switch type {
case "ANSWER":
if let browser = payload["browser"] as? String {
self.options.browser = browser
}
if let sdp = payload["sdp"] as? [String: Any] {
self.negotiator.handleSDP(pc, peerId: self.peerId, type: "answer", message: sdp, options: self.options, completion: { [weak self] (result) in
switch result {
case let .success(message):
if let sself = self {
sself.delegate?.connection(connection: sself, shouldSendMessage: message)
}
case let .failure(error):
print("Error: something went wrong in handleSDP \(error)")
return
}
})
self.isOpen = true
}
case "CANDIDATE":
if let candidate = payload["candidate"] as? [String: Any] {
self.negotiator.handleCandidate(pc, message: candidate)
}
default:
print("WARNING: Unrecognized message type: \(type) from peerId: \(self.peerId)")
break
}
}
}
| mit | f09a5fd307ed2f1d0c643edc6cadc835 | 25.870813 | 157 | 0.552885 | 4.956752 | false | false | false | false |
LeeroyDing/Bond | Bond/iOS/Bond+UISegmentedControl.swift | 8 | 3351 | //
// Bond+UISegmentedControl.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Austin Cooley (@adcooley)
//
// 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 class SegmentedControlDynamicHelper
{
weak var control: UISegmentedControl?
var listener: (UIControlEvents -> Void)?
init(control: UISegmentedControl) {
self.control = control
control.addTarget(self, action: Selector("valueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}
func valueChanged(control: UISegmentedControl) {
self.listener?(.ValueChanged)
}
deinit {
control?.removeTarget(self, action: nil, forControlEvents: .AllEvents)
}
}
class SegmentedControlDynamic<T>: InternalDynamic<UIControlEvents>
{
let helper: SegmentedControlDynamicHelper
init(control: UISegmentedControl) {
self.helper = SegmentedControlDynamicHelper(control: control)
super.init()
self.helper.listener = { [unowned self] in
self.value = $0
}
}
}
private var eventDynamicHandleUISegmentedControl: UInt8 = 0;
extension UISegmentedControl /*: Dynamical, Bondable */ {
public var dynEvent: Dynamic<UIControlEvents> {
if let d: AnyObject = objc_getAssociatedObject(self, &eventDynamicHandleUISegmentedControl) {
return (d as? Dynamic<UIControlEvents>)!
} else {
let d = SegmentedControlDynamic<UIControlEvents>(control: self)
objc_setAssociatedObject(self, &eventDynamicHandleUISegmentedControl, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedDynamic: Dynamic<UIControlEvents> {
return self.dynEvent
}
public var designatedBond: Bond<UIControlEvents> {
return self.dynEvent.valueBond
}
}
public func ->> (left: UISegmentedControl, right: Bond<UIControlEvents>) {
left.designatedDynamic ->> right
}
public func ->> <U: Bondable where U.BondType == UIControlEvents>(left: UISegmentedControl, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> <T: Dynamical where T.DynamicType == UIControlEvents>(left: T, right: UISegmentedControl) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: Dynamic<UIControlEvents>, right: UISegmentedControl) {
left ->> right.designatedBond
}
| mit | 0ae3d1e7eaff5bab912ff42aeb694495 | 32.178218 | 137 | 0.736795 | 4.516173 | false | false | false | false |
massaentertainment/MECarouselView | CarouselScrollView/MECarouselView+ScrollViewDelegate.swift | 1 | 1814 |
//
// CarouselScrollView+ScrollViewDelegate.swift
// CarouselScrollView
//
// Created by Gabriel Bezerra Valério on 12/06/17.
// Copyright © 2017 bepiducb. All rights reserved.
//
import UIKit
extension MECarouselView : UIScrollViewDelegate {
private func visibleViews() -> [UIView] {
var visibleRect = CGRect(origin: scrollView.contentOffset, size: scrollView.bounds.size)
let scale = 1.0 / scrollView.zoomScale
visibleRect.origin.x *= scale
visibleRect.origin.y *= scale
visibleRect.size.width *= scale
visibleRect.size.height *= scale
var visibleViews:[UIView] = []
for view in stackView.subviews where view.frame.intersects(visibleRect) {
visibleViews.append(view)
}
return visibleViews
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let scrollCenter = scrollView.frame.size.width / 2
let offset = scrollView.contentOffset.x
let visibleViews = self.visibleViews()
for view in visibleViews {
let normalizedCenter = view.center.x - offset
let maxDistance = view.frame.size.width + stackView.spacing
let distance = min(abs(scrollCenter - normalizedCenter), maxDistance)
let ratio = (maxDistance - distance) / maxDistance
let scale = ratio * (1 - self.standardItemScale) + self.standardItemScale
view.layer.transform = CATransform3DScale(CATransform3DIdentity, scale, scale, 1.0)
view.layer.zPosition = 10 * scale
}
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
self.delegate?.carouselView?(self, DidSnapTo: actualIndex)
}
}
| mit | 43d2de3ab7b5fc2934539d8fe933df1c | 33.188679 | 96 | 0.638521 | 4.897297 | false | false | false | false |
TwoRingSoft/shared-utils | Sources/PippinLibrary/Foundation/String/String+CSV.swift | 1 | 835 | //
// String+CSV.swift
// Pippin
//
// Created by Andrew McKnight on 1/8/19.
//
import Foundation
public typealias CSVRow = [String]
public typealias CSV = [CSVRow]
public extension String {
/// Split a String containing a CSV file's contents and split it into a 2-dimensional array of Strings, representing each row and its column fields.
var csv: CSV {
let rowComponents = split(separator: "\r\n").map({ (substring) -> String in
return String(substring)
})
let valueRows = Array(rowComponents[1..<rowComponents.count]) // return all but header row
let valueRowComponents: [CSVRow] = valueRows.map({ (row) -> [String] in
let result = Array(row.split(separator: ",")).map({String($0)})
return result
})
return valueRowComponents
}
}
| mit | 73eb6b908e74b5599ea2e4536cde881b | 31.115385 | 152 | 0.638323 | 3.995215 | false | false | false | false |
natecook1000/swift | test/SILGen/witnesses_class.swift | 1 | 5353 |
// RUN: %target-swift-emit-silgen -module-name witnesses_class -enable-sil-ownership %s | %FileCheck %s
protocol Fooable: class {
func foo()
static func bar()
init()
}
class Foo: Fooable {
func foo() { }
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class3FooCAA7FooableA2aDP3foo{{[_0-9a-zA-Z]*}}FTW
// CHECK-NOT: function_ref
// CHECK: class_method
class func bar() {}
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class3FooCAA7FooableA2aDP3bar{{[_0-9a-zA-Z]*}}FZTW
// CHECK-NOT: function_ref
// CHECK: class_method
required init() {}
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class3FooCAA7FooableA2aDP{{[_0-9a-zA-Z]*}}fCTW
// CHECK-NOT: function_ref
// CHECK: class_method
}
// CHECK-LABEL: sil hidden @$S15witnesses_class3genyyxAA7FooableRzlF
// CHECK: bb0([[SELF:%.*]] : @guaranteed $T)
// CHECK-NOT: copy_value [[SELF]]
// CHECK: [[METHOD:%.*]] = witness_method $T
// CHECK: apply [[METHOD]]<T>([[SELF]])
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: return
func gen<T: Fooable>(_ foo: T) {
foo.foo()
}
// CHECK-LABEL: sil hidden @$S15witnesses_class2exyyAA7Fooable_pF
// CHECK: bb0([[SELF:%[0-0]+]] : @guaranteed $Fooable):
// CHECK: [[SELF_PROJ:%.*]] = open_existential_ref [[SELF]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Fooable]],
// CHECK-NOT: copy_value [[SELF_PROJ]] : $
// CHECK: apply [[METHOD]]<[[OPENED]]>([[SELF_PROJ]])
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: return
func ex(_ foo: Fooable) {
foo.foo()
}
// Default implementations in a protocol extension
protocol HasDefaults {
associatedtype T = Self
func hasDefault()
func hasDefaultTakesT(_: T)
func hasDefaultGeneric<U : Fooable>(_: U)
func hasDefaultGenericTakesT<U : Fooable>(_: T, _: U)
}
extension HasDefaults {
func hasDefault() {}
func hasDefaultTakesT(_: T) {}
func hasDefaultGeneric<U : Fooable>(_: U) {}
func hasDefaultGenericTakesT<U : Fooable>(_: T, _: U) {}
}
protocol Barable {}
class UsesDefaults<X : Barable> : HasDefaults {}
// Covariant Self:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyqd__GAA03HasD0A2aEP10hasDefaultyyFTW : $@convention(witness_method: HasDefaults) <τ_0_0><τ_1_0 where τ_0_0 : UsesDefaults<τ_1_0>, τ_1_0 : Barable> (@in_guaranteed τ_0_0) -> () {
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE10hasDefaultyyF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults> (@in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<τ_0_0>(
// CHECK: return
// Invariant Self, since type signature contains an associated type:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP16hasDefaultTakesTyy1TQzFTW : $@convention(witness_method: HasDefaults) <τ_0_0 where τ_0_0 : Barable> (@in_guaranteed UsesDefaults<τ_0_0>, @in_guaranteed UsesDefaults<τ_0_0>) -> ()
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE16hasDefaultTakesTyy1TQzF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults> (@in_guaranteed τ_0_0.T, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<UsesDefaults<τ_0_0>>(
// CHECK: return
// Covariant Self:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyqd__GAA03HasD0A2aEP17hasDefaultGenericyyqd__AA7FooableRd__lFTW : $@convention(witness_method: HasDefaults) <τ_0_0><τ_1_0 where τ_0_0 : UsesDefaults<τ_1_0>, τ_1_0 : Barable><τ_2_0 where τ_2_0 : Fooable> (@guaranteed τ_2_0, @in_guaranteed τ_0_0) -> () {
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE17hasDefaultGenericyyqd__AA7FooableRd__lF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults><τ_1_0 where τ_1_0 : Fooable> (@guaranteed τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<τ_0_0, τ_2_0>(
// CHECK: return
// Invariant Self, since type signature contains an associated type:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP23hasDefaultGenericTakesTyy1TQz_qd__tAA7FooableRd__lFTW : $@convention(witness_method: HasDefaults) <τ_0_0 where τ_0_0 : Barable><τ_1_0 where τ_1_0 : Fooable> (@in_guaranteed UsesDefaults<τ_0_0>, @guaranteed τ_1_0, @in_guaranteed UsesDefaults<τ_0_0>) -> ()
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE23hasDefaultGenericTakesTyy1TQz_qd__tAA7FooableRd__lF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults><τ_1_0 where τ_1_0 : Fooable> (@in_guaranteed τ_0_0.T, @guaranteed τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<UsesDefaults<τ_0_0>, τ_1_0>(
// CHECK: return
protocol ReturnsCovariantSelf {
func returnsCovariantSelf() -> Self
}
extension ReturnsCovariantSelf {
func returnsCovariantSelf() -> Self { return self }
}
class NonMatchingMember: ReturnsCovariantSelf {
func returnsCovariantSelf() {}
}
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class17NonMatchingMemberCAA20ReturnsCovariantSelfA2aDP07returnsgH0xyFTW : $@convention(witness_method: ReturnsCovariantSelf) <τ_0_0 where τ_0_0 : NonMatchingMember> (@in_guaranteed τ_0_0) -> @out τ_0_0 {
| apache-2.0 | 158e3eb1f892d557073d233ba9ce5683 | 43.889831 | 358 | 0.679252 | 3.179472 | false | false | false | false |
anilkumarbp/ringcentral-swift-v2 | RingCentral/Platform/Platform.swift | 1 | 11149 | //
// Platform.swift
// RingCentral.
//
// Created by Anil Kumar BP on 2/10/16
// Copyright © 2016 Anil Kumar BP. All rights reserved..
//
import Foundation
/// Platform used to call HTTP request methods.
public class Platform {
// platform Constants
public let ACCESS_TOKEN_TTL = "3600"; // 60 minutes
public let REFRESH_TOKEN_TTL = "604800"; // 1 week
public let TOKEN_ENDPOINT = "/restapi/oauth/token";
public let REVOKE_ENDPOINT = "/restapi/oauth/revoke";
public let API_VERSION = "v1.0";
public let URL_PREFIX = "/restapi";
// Platform credentials
internal var auth: Auth
internal var client: Client
internal let server: String
internal let appKey: String
internal let appSecret: String
internal var appName: String
internal var appVersion: String
internal var USER_AGENT: String
// Creating an enum
/// Constructor for the platform of the SDK
///
/// - parameter appKey: The appKey of your app
/// - parameter appSecet: The appSecret of your app
/// - parameter server: Choice of PRODUCTION or SANDBOX
public init(client: Client, appKey: String, appSecret: String, server: String, appName: String = "", appVersion: String = "") {
self.appKey = appKey
self.appName = appName != "" ? appName : "Unnamed"
self.appVersion = appVersion != "" ? appVersion : "0.0.0"
self.appSecret = appSecret
self.server = server
self.auth = Auth()
self.client = client
self.USER_AGENT = "Swift :" + "/App Name : " + appName + "/App Version :" + appVersion + "/Current iOS Version :" + "/RCSwiftSDK";
}
// Returns the auth object
///
public func returnAuth() -> Auth {
return self.auth
}
/// func createUrl
///
/// @param: path The username of the RingCentral account
/// @param: options The password of the RingCentral account
/// @response: ApiResponse The password of the RingCentral account
public func createUrl(path: String, options: [String: AnyObject]) -> String {
var builtUrl = ""
if(options["skipAuthCheck"] === true){
builtUrl = builtUrl + self.server + path
return builtUrl
}
builtUrl = builtUrl + self.server + self.URL_PREFIX + "/" + self.API_VERSION + path
return builtUrl
}
/// Authenticates the user with the correct credentials
///
/// - parameter username: The username of the RingCentral account
/// - parameter password: The password of the RingCentral account
public func login(username: String, ext: String, password: String, completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) {
requestToken(self.TOKEN_ENDPOINT,body: [
"grant_type": "password",
"username": username,
"extension": ext,
"password": password,
"access_token_ttl": self.ACCESS_TOKEN_TTL,
"refresh_token_ttl": self.REFRESH_TOKEN_TTL
]) {
(t,e) in
self.auth.setData(t!.getDict())
completion(apiresponse: t, apiexception: e)
}
}
/// Refreshes the Auth object so that the accessToken and refreshToken are updated.
///
/// **Caution**: Refreshing an accessToken will deplete it's current time, and will
/// not be appended to following accessToken.
public func refresh(completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) throws {
if(!self.auth.refreshTokenValid()){
throw ApiException(apiresponse: nil, error: NSException(name: "Refresh token has expired", reason: "reason", userInfo: nil))
// apiexception
// throw ApiException(apiresponse: nil, error: NSException(name: "Refresh token has expired", reason: "reason", userInfo: nil))
}
requestToken(self.TOKEN_ENDPOINT,body: [
"refresh_token": self.auth.refreshToken(),
"grant_type": "refresh_token",
"access_token_ttl": self.ACCESS_TOKEN_TTL,
"refresh_token_ttl": self.REFRESH_TOKEN_TTL
]) {
(t,e) in
self.auth.setData(t!.getDict())
completion(apiresponse: t, apiexception: e)
}
}
/// func inflateRequest ()
///
/// @param: request NSMutableURLRequest
/// @param: options list of options
/// @response: NSMutableURLRequest
public func inflateRequest(request: NSMutableURLRequest, options: [String: AnyObject], completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) -> NSMutableURLRequest {
if options["skipAuthCheck"] == nil {
ensureAuthentication() {
(t,e) in
completion(apiresponse: t, apiexception: e)
}
let authHeader = self.auth.tokenType() + " " + self.auth.accessToken()
request.setValue(authHeader, forHTTPHeaderField: "Authorization")
request.setValue(self.USER_AGENT, forHTTPHeaderField: "User-Agent")
}
return request
}
/// func sendRequest ()
///
/// @param: request NSMutableURLRequest
/// @param: options list of options
/// @response: ApiResponse Callback
public func sendRequest(request: NSMutableURLRequest, options: [String: AnyObject]!, completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) {
do{
try client.send(inflateRequest(request, options: options){
(t,e) in
completion(apiresponse: t, apiexception: e)
}) {
(t,e) in
completion(apiresponse: t, apiexception: e)
}
} catch {
print("error")
}
}
/// func requestToken ()
///
/// @param: path The token endpoint
/// @param: array The body
/// @return ApiResponse
func requestToken(path: String, body: [String:AnyObject], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
let authHeader = "Basic" + " " + self.apiKey()
var headers: [String: String] = [:]
headers["Authorization"] = authHeader
headers["Content-type"] = "application/x-www-form-urlencoded;charset=UTF-8"
headers["User-Agent"] = self.USER_AGENT
var options: [String: AnyObject] = [:]
options["skipAuthCheck"] = true
let urlCreated = createUrl(path,options: options)
sendRequest(self.client.createRequest("POST", url: urlCreated, query: nil, body: body, headers: headers), options: options){
(r,e) in
completion(apiresponse: r,exception: e)
}
}
/// Base 64 encoding
func apiKey() -> String {
let plainData = (self.appKey + ":" + self.appSecret as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return base64String
}
/// Logs the user out of the current account.
///
/// Kills the current accessToken and refreshToken.
public func logout(completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) {
requestToken(self.TOKEN_ENDPOINT,body: [
"token": self.auth.accessToken()
]) {
(t,e) in
self.auth.reset()
completion(apiresponse: t, apiexception: e)
}
}
/// Check if the accessToken is valid
func ensureAuthentication(completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
if (!self.auth.accessTokenValid()) {
do{
try refresh() {
(r,e) in
completion(apiresponse: r,exception: e)
}
} catch {
print("error")
}
}
}
// Generic Method calls ( HTTP ) GET
///
/// @param: url token endpoint
/// @param: query body
/// @return ApiResponse Callback
public func get(url: String, query: [String: String]?=["":""], body: [String: AnyObject]?=nil, headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
let urlCreated = createUrl(url,options: options!)
sendRequest(self.client.createRequest("GET", url: urlCreated, query: query, body: body, headers: headers!), options: options) {
(r,e) in
completion(apiresponse: r,exception: e)
}
}
// Generic Method calls ( HTTP ) POST
///
/// @param: url token endpoint
/// @param: body body
/// @return ApiResponse Callback
public func post(url: String, query: [String: String]?=["":""], body: [String: AnyObject] = ["":""], headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
let urlCreated = createUrl(url,options: options!)
sendRequest(self.client.createRequest("POST", url: urlCreated, query: query, body: body, headers: headers!), options: options) {
(r,e) in
completion(apiresponse: r,exception: e)
}
}
// Generic Method calls ( HTTP ) PUT
///
/// @param: url token endpoint
/// @param: body body
/// @return ApiResponse Callback
public func put(url: String, query: [String: String]?=["":""], body: [String: AnyObject] = ["":""], headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
let urlCreated = createUrl(url,options: options!)
sendRequest(self.client.createRequest("PUT", url: urlCreated, query: query, body: body, headers: headers!), options: options) {
(r,e) in
completion(apiresponse: r,exception: e)
}
}
// Generic Method calls ( HTTP ) DELETE
///
/// @param: url token endpoint
/// @param: query body
/// @return ApiResponse Callback
public func delete(url: String, query: [String: String] = ["":""], body: [String: AnyObject]?=nil, headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
let urlCreated = createUrl(url,options: options!)
sendRequest(self.client.createRequest("DELETE", url: urlCreated, query: query, body: body, headers: headers!), options: options) {
(r,e) in
completion(apiresponse: r,exception: e)
}
}
}
| mit | c1b5c62fc22e94cfdda11f0d6e05b066 | 39.100719 | 254 | 0.577323 | 4.762067 | false | false | false | false |
natecook1000/swift | test/Migrator/post_fixit_pass.swift | 2 | 633 | // RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/post_fixit_pass.swift.result -o /dev/null -F %S/mock-sdk -swift-version 3
// RUN: diff -u %S/post_fixit_pass.swift.expected %t/post_fixit_pass.swift.result
#if swift(>=4)
public struct SomeAttribute: RawRepresentable {
public init(rawValue: Int) { self.rawValue = rawValue }
public init(_ rawValue: Int) { self.rawValue = rawValue }
public var rawValue: Int
public typealias RawValue = Int
}
#else
public typealias SomeAttribute = Int
#endif
func foo(_ d: SomeAttribute) {
let i: Int = d
}
| apache-2.0 | c614afacf85dc41427bbfa9a67342f1a | 34.166667 | 189 | 0.696682 | 3.279793 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.