repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
FirasAKAK/FInAppNotifications | refs/heads/master | FNotificationVoicePlayerExtensionView.swift | mit | 1 | //
// FNotificationVoicePlayerExtensionView.swift
// FInAppNotification
//
// Created by Firas Al Khatib Al Khalidi on 7/5/17.
// Copyright © 2017 Firas Al Khatib Al Khalidi. All rights reserved.
//
import UIKit
import AVFoundation
class FNotificationVoicePlayerExtensionView: FNotificationExtensionView {
var audioPlayer : AVPlayer!
var timeObserver : Any?
var didPlayRecording : (()-> Void)?
override var height : CGFloat{
return 100
}
var dataUrl: String!{
didSet{
guard dataUrl != nil else {
return
}
audioPlayer = AVPlayer(playerItem: AVPlayerItem(asset: AVAsset(url: URL(fileURLWithPath: dataUrl))))
NotificationCenter.default.addObserver(self, selector: #selector(itemDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: audioPlayer.currentItem!)
timeSlider.minimumValue = 0
timeSlider.maximumValue = Float(audioPlayer.currentItem!.asset.duration.seconds)
timeSlider.value = Float(audioPlayer.currentTime().seconds)
timeSlider.isEnabled = true
playPauseButton.isEnabled = true
addTimeObserver()
timeLabel.text = initialTimeString
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
addGestureRecognizer(tapGestureRecognizer)
tapGestureRecognizer.delegate = self
}
}
func viewTapped(){
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@IBOutlet weak var timeSlider : UISlider!
@IBOutlet weak var playPauseButton: UIButton!
@IBOutlet weak var timeLabel: UILabel!
var didFinishPlaying = false
@objc private func itemDidFinishPlaying(){
timeSlider.setValue(0, animated: true)
playPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal)
audioPlayer.currentItem?.seek(to: CMTime(seconds: 0, preferredTimescale: 1), completionHandler: { (completed) in
self.didFinishPlaying = true
self.timeLabel.text = self.initialTimeString
})
}
private var initialTimeString: String{
let time = Int(audioPlayer.currentItem!.asset.duration.seconds)
let minutes = time/60
let seconds = time-(minutes*60)
var timeString = ""
if minutes < 10{
timeString = "0\(minutes)"
}
else{
timeString = "\(minutes)"
}
if seconds < 10{
timeString = timeString + ":0\(seconds)"
}
else{
timeString = timeString + ":\(seconds)"
}
return timeString
}
private var currentTimeString: String{
let time = Int(audioPlayer.currentItem!.currentTime().seconds)
let minutes = time/60
let seconds = time-(minutes*60)
var timeString = ""
if minutes < 10{
timeString = "0\(minutes)"
}
else{
timeString = "\(minutes)"
}
if seconds < 10{
timeString = timeString + ":0\(seconds)"
}
else{
timeString = timeString + ":\(seconds)"
}
if audioPlayer.rate == 0 && seconds == 0{
return initialTimeString
}
return timeString
}
override func awakeFromNib() {
super.awakeFromNib()
addPlayPauseButtonBorder()
}
private func addPlayPauseButtonBorder(){
playPauseButton.layer.cornerRadius = 5
playPauseButton.layer.masksToBounds = true
playPauseButton.layer.borderColor = UIColor.white.cgColor
playPauseButton.layer.borderWidth = 1
}
private func addTimeObserver(){
timeObserver = audioPlayer.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 1), queue: DispatchQueue.main) { (time) in
if !self.timeSlider.isHighlighted{
DispatchQueue.main.async {
guard self.audioPlayer != nil else{
return
}
self.timeSlider.value = Float(self.audioPlayer.currentTime().seconds)
self.timeLabel.text = self.currentTimeString
}
}
}
}
@IBAction func timeSliderValueChanged(_ sender: UISlider) {
guard audioPlayer != nil else{
return
}
var wasPlaying = false
if audioPlayer.rate != 0{
audioPlayer.pause()
wasPlaying = true
}
if timeObserver != nil{
audioPlayer.removeTimeObserver(timeObserver!)
}
audioPlayer.currentItem?.seek(to: CMTime(seconds: Double(sender.value)+0.5, preferredTimescale: 1), completionHandler: { (Bool) in
guard self.audioPlayer != nil else{
return
}
self.addTimeObserver()
self.timeLabel.text = self.currentTimeString
if wasPlaying{
self.audioPlayer.play()
self.playPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal)
}
})
}
@IBAction func playPauseButtonPressed(_ sender: UIButton) {
didPlayRecording?()
didPlayRecording = nil
if audioPlayer.rate != 0{
audioPlayer.pause()
playPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal)
}
else{
audioPlayer.play()
playPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal)
}
}
}
extension FNotificationVoicePlayerExtensionView: UIGestureRecognizerDelegate{
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
}
| a3e0d4b5706c8020a01becc518d4ca64 | 36 | 189 | 0.602436 | false | false | false | false |
jiamao130/DouYuSwift | refs/heads/master | DouYuBroad/DouYuBroad/Main/CustomNavigationController.swift | mit | 1 | //
// CustomNavigationController.swift
// DouYuBroad
//
// Created by 贾卯 on 2017/8/14.
// Copyright © 2017年 贾卯. All rights reserved.
//
import UIKit
class CustomNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
guard let systemGes = interactivePopGestureRecognizer else {return}
guard let gesView = systemGes.view else {return}
/*
var count: UInt32 = 0
let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)!
for i in 0..<count{
let ivar = ivars[Int(i)]
let name = ivar_getName(ivar)
print(String(cString:name!))
}
let targets = systemGes.value(forKey: "_targets") as? [NSObject]
guard let targeObjc = targets?.first else {return}
guard let target = targeObjc.value(forKey: "target") else { return }
let action = Selector(("handleNavigationTransition:"))
let panGesure = UIPanGestureRecognizer()
gesView.addGestureRecognizer(panGesure)
panGesure.addTarget(target as Any, action: action)
*/
let targets = systemGes.value(forKey: "_targets") as? [NSObject]
guard let targetObjc = targets?.first else { return }
print(targetObjc)
// 3.2.取出target
guard let target = targetObjc.value(forKey: "target") else { return }
// 3.3.取出Action
let action = Selector(("handleNavigationTransition:"))
// 4.创建自己的Pan手势
let panGes = UIPanGestureRecognizer()
gesView.addGestureRecognizer(panGes)
panGes.addTarget(target, action: action)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
viewController.hidesBottomBarWhenPushed = true
super.pushViewController(viewController, animated: animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 9ed6f641bd7a3e1fea4764dcccf0c6ec | 31.292308 | 90 | 0.626965 | false | false | false | false |
TrustWallet/trust-wallet-ios | refs/heads/master | Trust/Browser/Types/DappCommand.swift | gpl-3.0 | 1 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
struct DappCommand: Decodable {
let name: Method
let id: Int
let object: [String: DappCommandObjectValue]
}
struct DappCallback {
let id: Int
let value: DappCallbackValue
}
enum DappCallbackValue {
case signTransaction(Data)
case sentTransaction(Data)
case signMessage(Data)
case signPersonalMessage(Data)
case signTypedMessage(Data)
var object: String {
switch self {
case .signTransaction(let data):
return data.hexEncoded
case .sentTransaction(let data):
return data.hexEncoded
case .signMessage(let data):
return data.hexEncoded
case .signPersonalMessage(let data):
return data.hexEncoded
case .signTypedMessage(let data):
return data.hexEncoded
}
}
}
struct DappCommandObjectValue: Decodable {
public var value: String = ""
public var array: [EthTypedData] = []
public init(from coder: Decoder) throws {
let container = try coder.singleValueContainer()
if let intValue = try? container.decode(Int.self) {
self.value = String(intValue)
} else if let stringValue = try? container.decode(String.self) {
self.value = stringValue
} else {
var arrayContainer = try coder.unkeyedContainer()
while !arrayContainer.isAtEnd {
self.array.append(try arrayContainer.decode(EthTypedData.self))
}
}
}
}
| d391008ec20f50ce2a3cdb768bfdf90f | 27.490909 | 79 | 0.634971 | false | false | false | false |
ghysrc/EasyMap | refs/heads/master | EasyMap/BMapManager.swift | mit | 1 | //
// Created by ghysrc on 2016/12/30.
// Copyright © 2016年 ghysrc. All rights reserved.
//
typealias BMapLocateSuccessHandler = ((CLLocation) -> Void)
typealias BMapLocateFailHandler = ((Error) -> Void)
typealias BMapReGeocoderSuccessHandler = ((BMKReverseGeoCodeResult) -> Void)
typealias BMapGeocoderSuccessHandler = ((BMKGeoCodeResult) -> Void)
typealias BMapSearchFailHandler = ((BMKSearchErrorCode) -> Void)
typealias BMapPoiSearchSuccessHandler = ((BMKPoiResult) -> Void)
typealias BMapSuggestionSearchSuccessHandler = ((BMKSuggestionResult) -> Void)
let BMap:BMapManager = BMapManager.instance
class BMapManager: NSObject, BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate, BMKPoiSearchDelegate, BMKSuggestionSearchDelegate {
static let instance = BMapManager()
private let locationService: BMKLocationService
private lazy var searchService = BMKGeoCodeSearch()
private lazy var poiSearch = BMKPoiSearch()
private lazy var suggestionSearch = BMKSuggestionSearch()
private var locateSuccess: BMapLocateSuccessHandler?
private var locateFail: BMapLocateFailHandler?
private var regeocoderSuccess: BMapReGeocoderSuccessHandler?
private var geoCoderSuccess: BMapGeocoderSuccessHandler?
private var poiSearchSuccess: BMapPoiSearchSuccessHandler?
private var suggestionSearchSuccess: BMapSuggestionSearchSuccessHandler?
private var searchFail: BMapSearchFailHandler?
override init() {
self.locationService = BMKLocationService()
super.init()
self.locationService.delegate = self
}
func requestAuthorization(whenInUse:Bool = true) {
if !CLLocationManager.locationServicesEnabled() || CLLocationManager.authorizationStatus() == .denied {
print("Location Service disabled or authorization denied.")
return
}
let clManager = CLLocationManager()
if whenInUse {
clManager.requestWhenInUseAuthorization()
} else {
clManager.requestAlwaysAuthorization()
}
}
/**
* Start continuouts locating
* Default desiredAccuracy is kCLLocationAccuracyHundredMeters
* Default distanceFilter is 200 meters
*/
func getLocation(withAccuracy: CLLocationAccuracy = kCLLocationAccuracyHundredMeters, distanceFilter: CLLocationDistance = 200, onSuccess: @escaping BMapLocateSuccessHandler, onFail: @escaping BMapLocateFailHandler) {
requestAuthorization()
locateSuccess = onSuccess
locateFail = onFail
locationService.desiredAccuracy = withAccuracy
locationService.distanceFilter = distanceFilter
locationService.startUserLocationService()
}
func didUpdate(_ userLocation: BMKUserLocation!) {
locateSuccess?(userLocation.location)
}
func didFailToLocateUserWithError(_ error: Error!) {
locateFail?(error)
}
/// coordinate to address
func reverseGeocoder(coordinate:CLLocationCoordinate2D, onSuccess:@escaping BMapReGeocoderSuccessHandler, onFail: @escaping BMapSearchFailHandler) {
regeocoderSuccess = onSuccess
searchFail = onFail
searchService.delegate = self
let regeo = BMKReverseGeoCodeOption()
regeo.reverseGeoPoint = coordinate
searchService.reverseGeoCode(regeo)
}
func onGetReverseGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
if error == BMK_SEARCH_NO_ERROR {
regeocoderSuccess?(result)
} else {
searchFail?(error)
}
}
/// address to coordinate, city can be empty
func geocoder(address:String, city:String, onSuccess: @escaping BMapGeocoderSuccessHandler, onFail: @escaping BMapSearchFailHandler) {
geoCoderSuccess = onSuccess
searchFail = onFail
searchService.delegate = self
let geo = BMKGeoCodeSearchOption()
geo.city = city
geo.address = address
searchService.geoCode(geo)
}
func onGetGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
if error == BMK_SEARCH_NO_ERROR {
geoCoderSuccess?(result)
} else {
searchFail?(error)
}
}
/**
* Search nearby pois
* Note: The keyword can NOT be nil or empty, it's required by SDK. If you want to get all kinds of pois, consider use reverseGeocoder instead.
*/
func searchPoi(near location:CLLocationCoordinate2D, radius:Int32, keyword:String, pageIndex:Int32 = 1, pageCapacity:Int32 = 20, onSuccess: @escaping BMapPoiSearchSuccessHandler, onFail: @escaping BMapSearchFailHandler) {
let option = BMKNearbySearchOption()
option.location = location
option.radius = radius
option.keyword = keyword
option.pageIndex = pageIndex
option.pageCapacity = pageCapacity
poiSearchSuccess = onSuccess
searchFail = onFail
poiSearch.delegate = self
poiSearch.poiSearchNear(by: option)
}
func onGetPoiResult(_ searcher: BMKPoiSearch!, result poiResult: BMKPoiResult!, errorCode: BMKSearchErrorCode) {
if errorCode == BMK_SEARCH_NO_ERROR {
poiSearchSuccess?(poiResult)
} else {
searchFail?(errorCode)
}
}
/// Get suggestions by keyword
func searchInputTips(keyword:String, city:String?, onSuccess: @escaping BMapSuggestionSearchSuccessHandler, onFail: @escaping BMapSearchFailHandler) {
let option = BMKSuggestionSearchOption()
option.cityname = city
option.keyword = keyword
suggestionSearchSuccess = onSuccess
searchFail = onFail
suggestionSearch.delegate = self
suggestionSearch.suggestionSearch(option)
}
func onGetSuggestionResult(_ searcher: BMKSuggestionSearch!, result: BMKSuggestionResult!, errorCode error: BMKSearchErrorCode) {
if error == BMK_SEARCH_NO_ERROR {
suggestionSearchSuccess?(result)
} else {
searchFail?(error)
}
}
/// Distance between two coordinates
func distanceBetween(coordinate1: CLLocationCoordinate2D, coordinate2: CLLocationCoordinate2D ) -> CLLocationDistance {
let point1 = BMKMapPointForCoordinate(coordinate1)
let point2 = BMKMapPointForCoordinate(coordinate2)
return BMKMetersBetweenMapPoints(point1, point2)
}
}
| 72403ea764f643907ca4f489edb60246 | 37.988166 | 225 | 0.695098 | false | false | false | false |
nickqiao/NKBill | refs/heads/master | Carthage/Checkouts/PagingMenuController/Pod/Classes/MenuItemView.swift | apache-2.0 | 1 | //
// MenuItemView.swift
// PagingMenuController
//
// Created by Yusuke Kita on 5/9/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import UIKit
public class MenuItemView: UIView {
lazy public var titleLabel: UILabel = {
let label = UILabel(frame: .zero)
label.numberOfLines = 1
label.textAlignment = .Center
label.userInteractionEnabled = true
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy public var menuImageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.userInteractionEnabled = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
public internal(set) var selected: Bool = false {
didSet {
if case .RoundRect = options.menuItemMode {
backgroundColor = UIColor.clearColor()
} else {
backgroundColor = selected ? options.selectedBackgroundColor : options.backgroundColor
}
switch options.menuItemViewContent {
case .Text:
titleLabel.textColor = selected ? options.selectedTextColor : options.textColor
titleLabel.font = selected ? options.selectedFont : options.font
// adjust label width if needed
let labelSize = calculateLabelSize()
widthConstraint.constant = labelSize.width
case .Image: break
}
}
}
lazy public private(set) var dividerImageView: UIImageView? = {
let imageView = UIImageView(image: self.options.menuItemDividerImage)
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
private var options: PagingMenuOptions!
private var widthConstraint: NSLayoutConstraint!
private var labelSize: CGSize {
guard let text = titleLabel.text else { return .zero }
return NSString(string: text).boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: titleLabel.font], context: nil).size
}
private let labelWidth: (CGSize, PagingMenuOptions.MenuItemWidthMode) -> CGFloat = { size, widthMode in
switch widthMode {
case .Flexible: return ceil(size.width)
case .Fixed(let width): return width
}
}
private var horizontalMargin: CGFloat {
switch options.menuDisplayMode {
case .SegmentedControl: return 0.0
default: return options.menuItemMargin
}
}
// MARK: - Lifecycle
internal init(title: String, options: PagingMenuOptions, addDivider: Bool) {
super.init(frame: .zero)
self.options = options
commonInit(addDivider) {
self.setupLabel(title)
self.layoutLabel()
}
}
internal init(image: UIImage, options: PagingMenuOptions, addDivider: Bool) {
super.init(frame: .zero)
self.options = options
commonInit(addDivider) {
self.setupImageView(image)
self.layoutImageView()
}
}
private func commonInit(addDivider: Bool, setup: () -> Void) {
setupView()
setup()
if let _ = options.menuItemDividerImage where addDivider {
setupDivider()
layoutDivider()
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
// MARK: - Cleanup
internal func cleanup() {
switch options.menuItemViewContent {
case .Text: titleLabel.removeFromSuperview()
case .Image: menuImageView.removeFromSuperview()
}
dividerImageView?.removeFromSuperview()
}
// MARK: - Constraints manager
internal func updateConstraints(size: CGSize) {
// set width manually to support ratotaion
switch (options.menuDisplayMode, options.menuItemViewContent) {
case (.SegmentedControl, .Text):
let labelSize = calculateLabelSize(size)
widthConstraint.constant = labelSize.width
case (.SegmentedControl, .Image):
widthConstraint.constant = size.width / CGFloat(options.menuItemCount)
default: break
}
}
// MARK: - Constructor
private func setupView() {
if case .RoundRect = options.menuItemMode {
backgroundColor = UIColor.clearColor()
} else {
backgroundColor = options.backgroundColor
}
translatesAutoresizingMaskIntoConstraints = false
}
private func setupLabel(title: String) {
titleLabel.text = title
titleLabel.textColor = options.textColor
titleLabel.font = options.font
addSubview(titleLabel)
}
private func setupImageView(image: UIImage) {
menuImageView.image = image
addSubview(menuImageView)
}
private func setupDivider() {
guard let dividerImageView = dividerImageView else { return }
addSubview(dividerImageView)
}
private func layoutLabel() {
let viewsDictionary = ["label": titleLabel]
let labelSize = calculateLabelSize()
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[label]|", options: [], metrics: nil, views: viewsDictionary)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|", options: [], metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
widthConstraint = NSLayoutConstraint(item: titleLabel, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: labelSize.width)
widthConstraint.active = true
}
private func layoutImageView() {
guard let image = menuImageView.image else { return }
let width: CGFloat
switch options.menuDisplayMode {
case .SegmentedControl:
width = UIApplication.sharedApplication().keyWindow!.bounds.size.width / CGFloat(options.menuItemCount)
default:
width = image.size.width + horizontalMargin * 2
}
widthConstraint = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: width)
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: menuImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: menuImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: menuImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: image.size.width),
NSLayoutConstraint(item: menuImageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: image.size.height),
widthConstraint
])
}
private func layoutDivider() {
guard let dividerImageView = dividerImageView else { return }
let centerYConstraint = NSLayoutConstraint(item: dividerImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 1.0)
let rightConstraint = NSLayoutConstraint(item: dividerImageView, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1.0, constant: 0.0)
NSLayoutConstraint.activateConstraints([centerYConstraint, rightConstraint])
}
// MARK: - Size calculator
private func calculateLabelSize(size: CGSize = UIApplication.sharedApplication().keyWindow!.bounds.size) -> CGSize {
guard let _ = titleLabel.text else { return .zero }
let itemWidth: CGFloat
switch options.menuDisplayMode {
case let .Standard(widthMode, _, _):
itemWidth = labelWidth(labelSize, widthMode)
case .SegmentedControl:
itemWidth = size.width / CGFloat(options.menuItemCount)
case let .Infinite(widthMode, _):
itemWidth = labelWidth(labelSize, widthMode)
}
let itemHeight = floor(labelSize.height)
return CGSizeMake(itemWidth + horizontalMargin * 2, itemHeight)
}
}
| dfe240d2baf88b44c1f980097b201104 | 37.421053 | 201 | 0.639612 | false | false | false | false |
shahmishal/swift | refs/heads/master | test/ParseableInterface/option-preservation.swift | apache-2.0 | 3 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -enable-library-evolution -emit-parseable-module-interface-path %t.swiftinterface -module-name t %s -emit-module -o /dev/null -Onone -enforce-exclusivity=unchecked -autolink-force-load
// RUN: %FileCheck %s < %t.swiftinterface -check-prefix=CHECK-SWIFTINTERFACE
//
// CHECK-SWIFTINTERFACE: swift-module-flags:
// CHECK-SWIFTINTERFACE-SAME: -enable-library-evolution
// CHECK-SWIFTINTERFACE-SAME: -Onone
// CHECK-SWIFTINTERFACE-SAME: -enforce-exclusivity=unchecked
// CHECK-SWIFTINTERFACE-SAME: -autolink-force-load
// Make sure flags show up when filelists are enabled
// RUN: %target-build-swift %s -driver-filelist-threshold=0 -emit-parseable-module-interface -o %t/foo -module-name foo -module-link-name fooCore -force-single-frontend-invocation -Ounchecked -enforce-exclusivity=unchecked -autolink-force-load 2>&1
// RUN: %FileCheck %s < %t/foo.swiftinterface --check-prefix CHECK-FILELIST-INTERFACE
// CHECK-FILELIST-INTERFACE: swift-module-flags:
// CHECK-FILELIST-INTERFACE-SAME: -target
// CHECK-FILELIST-INTERFACE-SAME: -autolink-force-load
// CHECK-FILELIST-INTERFACE-SAME: -module-link-name fooCore
// CHECK-FILELIST-INTERFACE-SAME: -enforce-exclusivity=unchecked
// CHECK-FILELIST-INTERFACE-SAME: -Ounchecked
// CHECK-FILELIST-INTERFACE-SAME: -module-name foo
public func foo() { }
| 403a375245e2d7c4a095c62d719d0090 | 53.36 | 248 | 0.770419 | false | false | false | false |
brokenhandsio/vapor-oauth | refs/heads/master | Sources/VaporOAuth/Models/OAuthClient.swift | mit | 1 | import Core
public final class OAuthClient: Extendable {
public let clientID: String
public let redirectURIs: [String]?
public let clientSecret: String?
public let validScopes: [String]?
public let confidentialClient: Bool?
public let firstParty: Bool
public let allowedGrantType: OAuthFlowType
public var extend: [String: Any] = [:]
public init(clientID: String, redirectURIs: [String]?, clientSecret: String? = nil, validScopes: [String]? = nil,
confidential: Bool? = nil, firstParty: Bool = false, allowedGrantType: OAuthFlowType) {
self.clientID = clientID
self.redirectURIs = redirectURIs
self.clientSecret = clientSecret
self.validScopes = validScopes
self.confidentialClient = confidential
self.firstParty = firstParty
self.allowedGrantType = allowedGrantType
}
func validateRedirectURI(_ redirectURI: String) -> Bool {
guard let redirectURIs = redirectURIs else {
return false
}
if redirectURIs.contains(redirectURI) {
return true
}
return false
}
}
| 945e21867a1ffe5a2787ff36f2267a66 | 29.263158 | 117 | 0.658261 | false | false | false | false |
luanlzsn/pos | refs/heads/master | pos/Classes/Ant/AntSingleton.swift | mit | 1 | //
// LeomanSingleton.swift
// MoFan
//
// Created by luan on 2017/1/4.
// Copyright © 2017年 luan. All rights reserved.
//
import UIKit
import AFNetworking
import MBProgressHUD
let kRequestTimeOut = 20.0
let AntManage = AntSingleton.sharedInstance
class AntSingleton: NSObject {
static let sharedInstance = AntSingleton()
var manager = AFHTTPSessionManager()
var requestBaseUrl = (UIDevice.current.userInterfaceIdiom == .pad) ? "http://pos.auroraeducationonline.info/api/" : "http://posonline.auroraeducationonline.info/index.php?"
var progress : MBProgressHUD?
var progressCount = 0//转圈数量
var isLogin = false//是否登录
var userModel: UserModel?
var iphoneToken = ""
private override init () {
if UIDevice.current.userInterfaceIdiom == .phone {
manager.requestSerializer = AFJSONRequestSerializer()
manager.requestSerializer.httpMethodsEncodingParametersInURI = Set.init(arrayLiteral: "GET", "HEAD")
}
manager.responseSerializer.acceptableContentTypes = Set(arrayLiteral: "application/json","text/json","text/javascript","text/html")
manager.requestSerializer.timeoutInterval = kRequestTimeOut
}
//MARK: - post请求
func postRequest(path:String, params:[String : Any]?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) {
AntLog(message: "请求接口:\(path),请求参数:\(String(describing: params))")
showMessage(message: "")
weak var weakSelf = self
manager.post(requestBaseUrl + path, parameters: params, progress: nil, success: { (task, response) in
weakSelf?.requestSuccess(response: response, successResult: successResult, failureResult: failureResult)
}) { (task, error) in
weakSelf?.hideMessage()
weakSelf?.showDelayToast(message: "未知错误,请重试!")
failureResult()
}
}
//MARK: - get请求
func getRequest(path:String, params:[String : Any]?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) {
AntLog(message: "请求接口:\(path),请求参数:\(String(describing: params))")
showMessage(message: "")
weak var weakSelf = self
manager.get(requestBaseUrl + path, parameters: params, progress: nil, success: { (task, response) in
weakSelf?.requestSuccess(response: response, successResult: successResult, failureResult: failureResult)
}) { (task, error) in
weakSelf?.hideMessage()
weakSelf?.showDelayToast(message: "未知错误,请重试!")
failureResult()
}
}
//MARK: - 请求成功回调
func requestSuccess(response: Any?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) {
AntLog(message: "接口返回数据:\(String(describing: response))")
hideMessage()
if let data = response as? [String : Any] {
if let status = data["status"] {
if status as! String == "success" {
if let success = data["data"] as? [String : Any] {
successResult(success)
} else {
successResult(data)
}
} else {
if let error = data["data"] as? [String : Any] {
if let message = error["message"] as? String {
showDelayToast(message: message)
}
} else if let message = data["message"] as? String {
showDelayToast(message: message)
}
failureResult()
}
} else {
failureResult()
}
} else {
failureResult()
}
}
//MARK: - iphone post请求
func iphonePostRequest(path:String, params:[String : Any]?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) {
AntLog(message: "请求接口:\(path),请求参数:\(String(describing: params))")
if path != "route=feed/rest_api/gettoken&grant_type=client_credentials" {
showMessage(message: "")
}
weak var weakSelf = self
if iphoneToken.isEmpty {
manager.requestSerializer.setValue("Basic cG9zb25saW5lOlBvTCMxMjA5", forHTTPHeaderField: "Authorization")
} else {
manager.requestSerializer.setValue("BEARER \(iphoneToken)", forHTTPHeaderField: "Authorization")
}
manager.requestSerializer.setValue((LanguageManager.currentLanguageString() == "en") ? "en" : "zh", forHTTPHeaderField: "Accept-Language")
manager.requestSerializer.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.httpShouldHandleCookies = false
manager.post(requestBaseUrl + path, parameters: params, progress: nil, success: { (task, response) in
weakSelf?.iphoneRequestSuccess(response: response, successResult: successResult, failureResult: failureResult)
}) { (task, error) in
if path != "route=feed/rest_api/gettoken&grant_type=client_credentials" {
weakSelf?.iphoneRequestFail(error: error, failureResult: failureResult)
}
}
}
//MARK: - iphone get请求
func iphoneGetRequest(path:String, params:[String : Any]?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) {
AntLog(message: "请求接口:\(path),请求参数:\(String(describing: params))")
showMessage(message: "")
weak var weakSelf = self
if iphoneToken.isEmpty {
manager.requestSerializer.setValue("Basic cG9zb25saW5lOlBvTCMxMjA5", forHTTPHeaderField: "Authorization")
} else {
manager.requestSerializer.setValue("BEARER \(iphoneToken)", forHTTPHeaderField: "Authorization")
}
manager.requestSerializer.setValue((LanguageManager.currentLanguageString() == "en") ? "en" : "zh", forHTTPHeaderField: "Accept-Language")
manager.requestSerializer.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.httpShouldHandleCookies = false
manager.get(requestBaseUrl + path, parameters: params, progress: nil, success: { (task, response) in
weakSelf?.iphoneRequestSuccess(response: response, successResult: successResult, failureResult: failureResult)
}) { (task, error) in
weakSelf?.iphoneRequestFail(error: error, failureResult: failureResult)
}
}
//MARK: - iphone get请求
func iphoneDeleteRequest(path:String, params:[String : Any]?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) {
AntLog(message: "请求接口:\(path),请求参数:\(String(describing: params))")
showMessage(message: "")
weak var weakSelf = self
if iphoneToken.isEmpty {
manager.requestSerializer.setValue("Basic cG9zb25saW5lOlBvTCMxMjA5", forHTTPHeaderField: "Authorization")
} else {
manager.requestSerializer.setValue("BEARER \(iphoneToken)", forHTTPHeaderField: "Authorization")
}
manager.requestSerializer.setValue((LanguageManager.currentLanguageString() == "en") ? "en" : "zh", forHTTPHeaderField: "Accept-Language")
manager.requestSerializer.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.httpShouldHandleCookies = false
manager.delete(requestBaseUrl + path, parameters: params, success: { (task, response) in
weakSelf?.iphoneRequestSuccess(response: response, successResult: successResult, failureResult: failureResult)
}) { (task, error) in
weakSelf?.iphoneRequestFail(error: error, failureResult: failureResult)
}
}
//MARK: - 请求成功回调
func iphoneRequestSuccess(response: Any?, successResult:@escaping ([String : Any]) -> Void, failureResult:@escaping () -> Void) {
AntLog(message: "接口返回数据:\(String(describing: response))")
hideMessage()
if let data = response as? [String : Any] {
if let success = data["success"] as? Bool {
if success {
successResult(data)
} else {
failureResult()
if let error = data["error"] as? [String : Any] {
for value in error.values {
if let message = value as? String {
showDelayToast(message: message)
}
}
} else if let error = data["error"] as? String {
showDelayToast(message: error)
}
}
} else {
successResult(data)
}
} else {
failureResult()
}
}
// MARK: - iPhone请求错误回调
func iphoneRequestFail(error: Error, failureResult:@escaping () -> Void) {
hideMessage()
failureResult()
if let responseData = (error as NSError).userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? Data {
if let responseDict = try! JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as? [String : Any] {
if let errorArray = responseDict["error"] as? [String] {
if let errorStr = errorArray.first {
showDelayToast(message: errorStr)
return
}
}
}
}
AntManage.showDelayToast(message: NSLocalizedString("未知错误,请重试!", comment: ""))
}
// MARK: - 显示提示
func showMessage(message : String) {
if progress == nil {
progressCount = 0
progress = MBProgressHUD.showAdded(to: kWindow!, animated: true)
progress?.label.text = message
}
progressCount += 1
}
// MARK: - 隐藏提示
func hideMessage() {
progressCount -= 1
if progressCount < 0 {
progressCount = 0
}
if (progress != nil) && progressCount == 0 {
progress?.hide(animated: true)
progress?.removeFromSuperview()
progress = nil
}
}
// MARK: - 显示固定时间的提示
func showDelayToast(message : String) {
let hud = MBProgressHUD.showAdded(to: kWindow!, animated: true)
hud.detailsLabel.text = message
hud.mode = .text
hud.hide(animated: true, afterDelay: 2)
}
// MARK: - 校验默认请求地址
func checkBaseRequestAddress(isStartUp: Bool) {
let baseRequestAddress = UserDefaults.standard.object(forKey: "BaseRequestAddress")
AntLog(message: baseRequestAddress)
let beforeUrl = requestBaseUrl
if let address = baseRequestAddress as? String {
if Common.isValidateURL(urlStr: address) {
if address.hasSuffix("/") {
requestBaseUrl = address + "api/"
} else {
requestBaseUrl = address + "/api/"
}
}
}
if beforeUrl != requestBaseUrl, !isStartUp {
NotificationCenter.default.post(name: NSNotification.Name("RequestAddressUpdate"), object: nil)
}
}
}
| 7d322b7d8a86aa6182b118f40f950182 | 43.34749 | 176 | 0.59394 | false | false | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Services/MediaStoreData/MediaStoreData_Error.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for MediaStoreData
public struct MediaStoreDataErrorType: AWSErrorType {
enum Code: String {
case containerNotFoundException = "ContainerNotFoundException"
case internalServerError = "InternalServerError"
case objectNotFoundException = "ObjectNotFoundException"
case requestedRangeNotSatisfiableException = "RequestedRangeNotSatisfiableException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize MediaStoreData
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The specified container was not found for the specified account.
public static var containerNotFoundException: Self { .init(.containerNotFoundException) }
/// The service is temporarily unavailable.
public static var internalServerError: Self { .init(.internalServerError) }
/// Could not perform an operation on an object that does not exist.
public static var objectNotFoundException: Self { .init(.objectNotFoundException) }
/// The requested content range is not valid.
public static var requestedRangeNotSatisfiableException: Self { .init(.requestedRangeNotSatisfiableException) }
}
extension MediaStoreDataErrorType: Equatable {
public static func == (lhs: MediaStoreDataErrorType, rhs: MediaStoreDataErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension MediaStoreDataErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| aeb94a7edf7196c560d4da2bf73ac0c5 | 36.727273 | 117 | 0.675502 | false | false | false | false |
D8Ge/Jchat | refs/heads/master | Jchat/Pods/SwiftProtobuf/Sources/SwiftProtobuf/ProtobufRawMessage.swift | mit | 1 | // ProtobufRuntime/Sources/Protobuf/ProtobufRawMessage.swift - Raw message decoding
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// A "RawMessage" is a tool for parsing proto binary messages without
/// using a schema of any sort. This is slow, inconvenient, and unsafe.
/// Despite these drawbacks, it is occasionally quite useful...
///
// -----------------------------------------------------------------------------
import Swift
// TODO: This is a tentative sketch; needs tests and plenty of more stuff filled in.
public struct ProtobufRawMessage {
public private(set) var fieldWireType = [Int: Int]()
public private(set) var fieldData = [Int: Any]()
public init(protobuf: [UInt8]) throws {
try protobuf.withUnsafeBufferPointer { (bp) throws in
var protobufDecoder = ProtobufBinaryDecoder(protobufPointer: bp)
while let tagType = try protobufDecoder.getTagType() {
let protoFieldNumber = tagType / 8
let wireType = tagType % 8
fieldWireType[protoFieldNumber] = wireType
switch wireType {
case 0:
if let v = try protobufDecoder.decodeUInt64() {
fieldData[protoFieldNumber] = v
} else {
throw ProtobufDecodingError.malformedProtobuf
}
case 1:
if let v = try protobufDecoder.decodeFixed64() {
fieldData[protoFieldNumber] = v
} else {
throw ProtobufDecodingError.malformedProtobuf
}
case 2:
if let v = try protobufDecoder.decodeBytes() {
fieldData[protoFieldNumber] = v
} else {
throw ProtobufDecodingError.malformedProtobuf
}
case 3:
// TODO: Find a useful way to deal with groups
try protobufDecoder.skip()
case 5:
if let v = try protobufDecoder.decodeFixed32() {
fieldData[protoFieldNumber] = v
} else {
throw ProtobufDecodingError.malformedProtobuf
}
default:
throw ProtobufDecodingError.malformedProtobuf
}
}
}
}
// TODO: serializeProtobuf(), serializeProtobufBytes()
/// Get the contents of this field as a UInt64
/// Returns nil if the field doesn't exist or it's contents cannot be expressed as a UInt64
public func getUInt64(protoFieldNumber: Int) -> UInt64? {
return fieldData[protoFieldNumber] as? UInt64
}
public func getString(protoFieldNumber: Int) -> String? {
if let bytes = fieldData[protoFieldNumber] as? [UInt8] {
return bytes.withUnsafeBufferPointer {(buffer) -> String? in
buffer.baseAddress?.withMemoryRebound(to: CChar.self, capacity: buffer.count) { (cp) -> String? in
// cp is not null-terminated!
var chars = [CChar](UnsafeBufferPointer<CChar>(start: cp, count: buffer.count))
chars.append(0)
return String(validatingUTF8: chars)
}
}
} else {
return nil
}
}
// TODO: More getters...
// TODO: Setters...
}
| 3fd9f0cb0150b7e315118b4ad08eedfc | 39.936842 | 114 | 0.541013 | false | false | false | false |
leasual/PDChart | refs/heads/master | PDChartDemo/PDChartDemo/PDChartDemo/PDChart/PDBarChart/PDBarChart.swift | mit | 2 | //
// PDBarChart.swift
// PDChart
//
// Created by Pandara on 14-7-11.
// Copyright (c) 2014年 Pandara. All rights reserved.
//
import UIKit
import QuartzCore
class PDBarChartDataItem {
//optional
var axesColor: UIColor = UIColor(red: 80.0 / 255, green: 80.0 / 255, blue: 80.0 / 255, alpha: 1.0) //坐标轴颜色
var axesTipColor: UIColor = UIColor(red: 80.0 / 255, green: 80.0 / 255, blue: 80.0 / 255, alpha: 1.0) //坐标轴刻度值颜色
var chartLayerColor: UIColor = UIColor(red: 61.0 / 255, green: 189.0 / 255, blue: 100.0 / 255, alpha: 1.0) //折线的颜色
var barBgColor: UIColor = UIColor(red: 234.0 / 255, green: 234.0 / 255, blue: 234.0 / 255, alpha: 1.0)
var barColor: UIColor = UIColor(red: 69.0 / 255, green: 189.0 / 255, blue: 100.0 / 255, alpha: 1.0)//69 189 100
var showAxes: Bool = true
var axesWidth: CGFloat = 1.0
var barMargin: CGFloat = 4.0
var barWidth: CGFloat!
var barCornerRadius: CGFloat = 0
//require
var xMax: CGFloat!
var xInterval: CGFloat!
var yMax: CGFloat!
var yInterval: CGFloat!
var xAxesDegreeTexts: [String]?
var yAxesDegreeTexts: [String]?
var barPointArray: [CGPoint]?
init() {
}
}
class PDBarChart: PDChart {
var axesComponent: PDChartAxesComponent!
var dataItem: PDBarChartDataItem!
//property
var barBgArray: [UIView] = []
var barLayerArray: [CAShapeLayer] = []
init(frame: CGRect, dataItem: PDBarChartDataItem) {
super.init(frame: frame)
self.dataItem = dataItem
var axesDataItem: PDChartAxesComponentDataItem = PDChartAxesComponentDataItem()
axesDataItem.arrowBodyLength += 10
axesDataItem.targetView = self
axesDataItem.featureH = getFeatureHeight()
axesDataItem.featureW = getFeatureWidth()
axesDataItem.xMax = dataItem.xMax
axesDataItem.xInterval = dataItem.xInterval
axesDataItem.yMax = dataItem.yMax
axesDataItem.yInterval = dataItem.yInterval
axesDataItem.xAxesDegreeTexts = dataItem.xAxesDegreeTexts
axesDataItem.showXDegree = false
axesDataItem.axesWidth = dataItem.axesWidth
self.axesComponent = PDChartAxesComponent(dataItem: axesDataItem)
//bar width
var xDegreeInterval = self.axesComponent.getXDegreeInterval()
self.dataItem.barWidth = xDegreeInterval - dataItem.barMargin * 2
self.addBarBackgroundView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func getFeatureWidth() -> CGFloat {
return CGFloat(self.frame.size.width)
}
func getFeatureHeight() -> CGFloat {
return CGFloat(self.frame.size.height)
}
func getBarView(frame: CGRect) -> UIView {
var barView: UIView = UIView(frame: frame)
barView.backgroundColor = self.dataItem.barBgColor
barView.clipsToBounds = true
barView.layer.cornerRadius = self.dataItem.barCornerRadius
return barView
}
func getBarShapeLayer(layerFrame: CGRect, barHeight: CGFloat) -> CAShapeLayer {
var shapeLayer: CAShapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor.whiteColor().CGColor
shapeLayer.strokeColor = self.dataItem.barColor.CGColor
shapeLayer.lineWidth = self.dataItem.barWidth
shapeLayer.strokeStart = 0.0
shapeLayer.strokeEnd = 1.0
shapeLayer.frame = layerFrame
var barPath: UIBezierPath = UIBezierPath()
barPath.moveToPoint(CGPointMake(self.dataItem.barWidth / 2, layerFrame.size.height))
barPath.addLineToPoint(CGPointMake(self.dataItem.barWidth / 2, layerFrame.size.height - barHeight))
barPath.stroke()
shapeLayer.path = barPath.CGPath
return shapeLayer
}
func getBarAnimation() -> CABasicAnimation {
CATransaction.begin()
var pathAnimation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = 1.0
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
pathAnimation.fromValue = 0.0
pathAnimation.toValue = 1.0
CATransaction.setCompletionBlock({
() -> Void in
return
})
CATransaction.commit()
return pathAnimation
}
func addBarBackgroundView() {
var xDegreeInterval: CGFloat = self.axesComponent.getXDegreeInterval()
var basePoint: CGPoint = self.axesComponent.getBasePoint()
var xAxesWidth: CGFloat = self.axesComponent.getXAxesWidth()
var yAxesHeight: CGFloat = self.axesComponent.getYAxesHeight()
for var i = 0; i < self.dataItem.barPointArray!.count; i++ {
var point: CGPoint = self.dataItem.barPointArray![i]
var bvw: CGFloat = self.dataItem.barWidth
var bvh: CGFloat = yAxesHeight
var bvx: CGFloat = basePoint.x + xDegreeInterval / 2 + self.dataItem.barMargin + (self.dataItem.barWidth + self.dataItem.barMargin * 2) * CGFloat(i)
var bvy: CGFloat = basePoint.y - bvh - self.dataItem.axesWidth / 2
var barView: UIView = self.getBarView(CGRectMake(bvx, bvy, bvw, bvh))
self.barBgArray.append(barView)
self.addSubview(barView)
}
}
override func strokeChart() {
if !(self.dataItem.barPointArray != nil) {
return
}
UIGraphicsBeginImageContext(self.frame.size)
var yAxesHeight: CGFloat = self.axesComponent.getYAxesHeight()
for var i = 0; i < self.dataItem.barPointArray!.count; i++ {
var point: CGPoint = self.dataItem.barPointArray![i]
var barView: UIView = self.barBgArray[i]
//barShape
var barShapeLayer: CAShapeLayer = self.getBarShapeLayer(CGRectMake(0, 0, barView.frame.size.width, barView.frame.size.height), barHeight: point.y / self.dataItem.yMax * yAxesHeight)
barShapeLayer.addAnimation(self.getBarAnimation(), forKey: "barAnimation")
self.barLayerArray.append(barShapeLayer)
barView.layer.addSublayer(barShapeLayer)
}
UIGraphicsEndImageContext()
}
override func drawRect(rect: CGRect)
{
super.drawRect(rect)
var context: CGContextRef = UIGraphicsGetCurrentContext()
axesComponent.strokeAxes(context)
}
}
| 1f55e52b4af451f80991ac741f745c28 | 28.733624 | 219 | 0.620943 | false | false | false | false |
antlr/grammars-v4 | refs/heads/master | swift/swift5/examples/Objects and Classes/Contents.swift | mit | 1 | //: ## Objects and Classes
//:
//: Use `class` followed by the class’s name to create a class. A property declaration in a class is written the same way as a constant or variable declaration, except that it’s in the context of a class. Likewise, method and function declarations are written the same way.
//:
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
//: - Experiment:
//: Add a constant property with `let`, and add another method that takes an argument.
//:
//: Create an instance of a class by putting parentheses after the class name. Use dot syntax to access the properties and methods of the instance.
//:
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
//: This version of the `Shape` class is missing something important: an initializer to set up the class when an instance is created. Use `init` to create one.
//:
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
//: Notice how `self` is used to distinguish the `name` property from the `name` argument to the initializer. The arguments to the initializer are passed like a function call when you create an instance of the class. Every property needs a value assigned—either in its declaration (as with `numberOfSides`) or in the initializer (as with `name`).
//:
//: Use `deinit` to create a deinitializer if you need to perform some cleanup before the object is deallocated.
//:
//: Subclasses include their superclass name after their class name, separated by a colon. There’s no requirement for classes to subclass any standard root class, so you can include or omit a superclass as needed.
//:
//: Methods on a subclass that override the superclass’s implementation are marked with `override`—overriding a method by accident, without `override`, is detected by the compiler as an error. The compiler also detects methods with `override` that don’t actually override any method in the superclass.
//:
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
var diameter: Double { sideLength * sqrt(2) }
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()
//: - Experiment:
//: Make another subclass of `NamedShape` called `Circle` that takes a radius and a name as arguments to its initializer. Implement an `area()` and a `simpleDescription()` method on the `Circle` class.
//:
//: In addition to simple properties that are stored, properties can have a getter and a setter.
//:
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)
//: In the setter for `perimeter`, the new value has the implicit name `newValue`. You can provide an explicit name in parentheses after `set`.
//:
//: Notice that the initializer for the `EquilateralTriangle` class has three different steps:
//:
//: 1. Setting the value of properties that the subclass declares.
//:
//: 1. Calling the superclass’s initializer.
//:
//: 1. Changing the value of properties defined by the superclass. Any additional setup work that uses methods, getters, or setters can also be done at this point.
//:
//: If you don’t need to compute the property but still need to provide code that’s run before and after setting a new value, use `willSet` and `didSet`. The code you provide is run any time the value changes outside of an initializer. For example, the class below ensures that the side length of its triangle is always the same as the side length of its square.
//:
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
didSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)
//: When working with optional values, you can write `?` before operations like methods, properties, and subscripting. If the value before the `?` is `nil`, everything after the `?` is ignored and the value of the whole expression is `nil`. Otherwise, the optional value is unwrapped, and everything after the `?` acts on the unwrapped value. In both cases, the value of the whole expression is an optional value.
//:
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength
//: [Previous](@previous) | [Next](@next)
| e34d7d9d4874841dc261215c1aa8915a | 41.442857 | 413 | 0.708347 | false | false | false | false |
jeanpimentel/HonourBridge | refs/heads/master | HonourBridge/HonourBridge/Honour/Library/Rules/Locale/BR/CPF.swift | mit | 1 | //
// CPF.swift
// Honour
//
// Created by Jean Pimentel on 5/18/15.
// Copyright (c) 2015 Honour. All rights reserved.
//
import Foundation
public class BR_CPF : Rule {
private var strict: Bool
public init(strict: Bool = false) {
self.strict = strict;
}
public init(_ strict: Bool = false) {
self.strict = strict;
}
public override func validate(value: String) -> Bool {
let numbers = filter(value, {contains("0123456789", $0)})
if numbers.count != 11 {
return false
}
if self.strict && count(value) != 11 {
return false
}
var allEquals = true
for char in numbers {
if char != numbers[0] {
allEquals = false
}
}
if allEquals {
return false
}
var s, n, i : Int
// First digit
for s = 10, n = 0, i = 0; s >= 2; n += String(numbers[i++]).toInt()! * s-- {}
n %= 11
if String(numbers[9]).toInt()! != (n < 2 ? 0 : 11 - n) {
return false
}
// Second digit
for s = 11, n = 0, i = 0; s >= 2; n += String(numbers[i++]).toInt()! * s-- {}
n %= 11
if String(numbers[10]).toInt()! != (n < 2 ? 0 : 11 - n) {
return false
}
return true
}
} | d46c9560591ded03a29eb37fe20e5a19 | 19.522388 | 85 | 0.459243 | false | false | false | false |
uShip/iOSIdeaFlow | refs/heads/master | IdeaFlow/ChartViewController.swift | gpl-3.0 | 1 | //
// ChartViewController.swift
// IdeaFlow
//
// Created by Matt Hayes on 8/14/15.
// Copyright (c) 2015 uShip. All rights reserved.
//
import UIKit
class ChartViewController: UIViewController
{
@IBOutlet weak var previousDate: UIButton!
@IBOutlet weak var currentDate: UILabel!
@IBOutlet weak var nextDate: UIButton!
override func viewDidLoad()
{
super.viewDidLoad()
refreshDateLabel()
let longPresser = UILongPressGestureRecognizer(target: self, action: Selector("onLongPress:"))
self.view.addGestureRecognizer(longPresser)
let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("onLeftSwipe:"))
leftSwipe.direction = .Left
self.view.addGestureRecognizer(leftSwipe)
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("onRightSwipe:"))
rightSwipe.direction = .Right
self.view.addGestureRecognizer(rightSwipe)
}
func onLeftSwipe(gestureRecognizer: UISwipeGestureRecognizer)
{
goToNextDay(gestureRecognizer)
}
func onRightSwipe(gestureRecognizer: UISwipeGestureRecognizer)
{
goToPreviousDay(gestureRecognizer)
}
func onLongPress(gestureRecognizer: UILongPressGestureRecognizer)
{
print("\(__FUNCTION__)")
}
@IBAction func goToNextDay(sender: AnyObject)
{
IdeaFlowEvent.setSelectedDayWithOffset(1)
refreshDateLabel()
}
@IBAction func goToPreviousDay(sender: AnyObject)
{
IdeaFlowEvent.setSelectedDayWithOffset(-1)
refreshDateLabel()
}
func refreshDateLabel()
{
let selectedDate = IdeaFlowEvent.getSelectedDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .NoStyle
currentDate.text = dateFormatter.stringFromDate(selectedDate)
}
} | 09ed8540c39bb38cb1448554874cc4d3 | 26.638889 | 102 | 0.664656 | false | false | false | false |
onevcat/CotEditor | refs/heads/develop | CotEditor/Sources/FilePermissions.swift | apache-2.0 | 1 | //
// FilePermissions.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2018-02-16.
//
// ---------------------------------------------------------------------------
//
// © 2018 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
struct FilePermissions {
var user: Permission
var group: Permission
var others: Permission
struct Permission: OptionSet {
let rawValue: UInt16
static let read = Permission(rawValue: 0b100)
static let write = Permission(rawValue: 0b010)
static let execute = Permission(rawValue: 0b001)
var humanReadable: String {
return (self.contains(.read) ? "r" : "-") +
(self.contains(.write) ? "w" : "-") +
(self.contains(.execute) ? "x" : "-")
}
}
init(mask: UInt16) {
self.user = Permission(rawValue: (mask & 0b111 << 6) >> 6)
self.group = Permission(rawValue: (mask & 0b111 << 3) >> 3)
self.others = Permission(rawValue: (mask & 0b111))
}
var mask: UInt16 {
let userMask = self.user.rawValue << 6
let groupMask = self.group.rawValue << 3
let othersMask = self.others.rawValue
return userMask + groupMask + othersMask
}
/// human-readable permission expression like "rwxr--r--"
var humanReadable: String {
return self.user.humanReadable + self.group.humanReadable + self.others.humanReadable
}
}
extension FilePermissions: CustomStringConvertible {
var description: String {
return self.humanReadable
}
}
| 253767a7793899224edf1218574095f7 | 25.395349 | 93 | 0.571366 | false | false | false | false |
leo150/Pelican | refs/heads/develop | Sources/Pelican/API/Types/Game/GameHighScore.swift | mit | 1 | //
// GameHighScore.swift
// Pelican
//
// Created by Ido Constantine on 31/08/2017.
//
import Foundation
import Vapor
import FluentProvider
/** This object represents one row of the high scores table for a game.
*/
final public class GameHighScore: Model {
public var storage = Storage()
var position: Int // Position in the high score table for the game
var user: User // User who made the score entry
var score: Int // The score the user set
// NodeRepresentable conforming methods
required public init(row: Row) throws {
position = try row.get("position")
user = try row.get("user")
score = try row.get("score")
}
public func makeRow() throws -> Row {
var row = Row()
try row.set("position", position)
try row.set("user", user)
try row.set("score", score)
return row
}
}
| fa7a0924e5ada69ac34fd54a464c60cc | 21.540541 | 71 | 0.672662 | false | false | false | false |
neonichu/emoji-search-keyboard | refs/heads/master | Keyboard/DefaultKeyboard.swift | bsd-3-clause | 1 | //
// DefaultKeyboard.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/10/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
func defaultKeyboard() -> Keyboard {
let defaultKeyboard = Keyboard()
for key in ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"] {
let keyModel = Key(.Character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 0)
}
for key in ["A", "S", "D", "F", "G", "H", "J", "K", "L"] {
let keyModel = Key(.Character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 0)
}
let keyModel = Key(.Shift)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
for key in ["Z", "X", "C", "V", "B", "N", "M"] {
let keyModel = Key(.Character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
}
let backspace = Key(.Backspace)
defaultKeyboard.addKey(backspace, row: 2, page: 0)
let keyModeChangeNumbers = Key(.ModeChange)
keyModeChangeNumbers.uppercaseKeyCap = "123"
keyModeChangeNumbers.toMode = 1
defaultKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 0)
let keyboardChange = Key(.KeyboardChange)
defaultKeyboard.addKey(keyboardChange, row: 3, page: 0)
let settings = Key(.Settings)
defaultKeyboard.addKey(settings, row: 3, page: 0)
let space = Key(.Space)
space.uppercaseKeyCap = "space"
space.uppercaseOutput = " "
space.lowercaseOutput = " "
defaultKeyboard.addKey(space, row: 3, page: 0)
let returnKey = Key(.Return)
returnKey.uppercaseKeyCap = "return"
returnKey.uppercaseOutput = "\n"
returnKey.lowercaseOutput = "\n"
defaultKeyboard.addKey(returnKey, row: 3, page: 0)
for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] {
let keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 1)
}
for key in ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""] {
let keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 1)
}
let keyModeChangeSpecialCharacters = Key(.ModeChange)
keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+="
keyModeChangeSpecialCharacters.toMode = 2
defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 2, page: 1)
for key in [".", ",", "?", "!", "'"] {
let keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 1)
}
defaultKeyboard.addKey(Key(backspace), row: 2, page: 1)
let keyModeChangeLetters = Key(.ModeChange)
keyModeChangeLetters.uppercaseKeyCap = "ABC"
keyModeChangeLetters.toMode = 0
defaultKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1)
defaultKeyboard.addKey(Key(keyboardChange), row: 3, page: 1)
defaultKeyboard.addKey(Key(settings), row: 3, page: 1)
defaultKeyboard.addKey(Key(space), row: 3, page: 1)
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 1)
for key in ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="] {
let keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 2)
}
for key in ["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"] {
let keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 2)
}
defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2)
for key in [".", ",", "?", "!", "'"] {
let keyModel = Key(.SpecialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 2)
}
defaultKeyboard.addKey(Key(backspace), row: 2, page: 2)
defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2)
defaultKeyboard.addKey(Key(keyboardChange), row: 3, page: 2)
defaultKeyboard.addKey(Key(settings), row: 3, page: 2)
defaultKeyboard.addKey(Key(space), row: 3, page: 2)
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 2)
return defaultKeyboard
}
| 94db6a05d45bb3247e97eeb29b789735 | 32.476923 | 75 | 0.596507 | false | false | false | false |
CCRogerWang/ReactiveWeatherExample | refs/heads/master | 10-combining-operators-in-practice/final/OurPlanet/Pods/RxSwift/RxSwift/Observables/Implementations/Take.swift | apache-2.0 | 11 | //
// Take.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/12/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// count version
class TakeCountSink<O: ObserverType> : Sink<O>, ObserverType {
typealias E = O.E
typealias Parent = TakeCount<E>
private let _parent: Parent
private var _remaining: Int
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_remaining = parent._count
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
switch event {
case .next(let value):
if _remaining > 0 {
_remaining -= 1
forwardOn(.next(value))
if _remaining == 0 {
forwardOn(.completed)
dispose()
}
}
case .error:
forwardOn(event)
dispose()
case .completed:
forwardOn(event)
dispose()
}
}
}
class TakeCount<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _count: Int
init(source: Observable<Element>, count: Int) {
if count < 0 {
rxFatalError("count can't be negative")
}
_source = source
_count = count
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
// time version
class TakeTimeSink<ElementType, O: ObserverType>
: Sink<O>
, LockOwnerType
, ObserverType
, SynchronizedOnType where O.E == ElementType {
typealias Parent = TakeTime<ElementType>
typealias E = ElementType
fileprivate let _parent: Parent
let _lock = NSRecursiveLock()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case .next(let value):
forwardOn(.next(value))
case .error:
forwardOn(event)
dispose()
case .completed:
forwardOn(event)
dispose()
}
}
func tick() {
_lock.lock(); defer { _lock.unlock() }
forwardOn(.completed)
dispose()
}
func run() -> Disposable {
let disposeTimer = _parent._scheduler.scheduleRelative((), dueTime: _parent._duration) {
self.tick()
return Disposables.create()
}
let disposeSubscription = _parent._source.subscribe(self)
return Disposables.create(disposeTimer, disposeSubscription)
}
}
class TakeTime<Element> : Producer<Element> {
typealias TimeInterval = RxTimeInterval
fileprivate let _source: Observable<Element>
fileprivate let _duration: TimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, duration: TimeInterval, scheduler: SchedulerType) {
_source = source
_scheduler = scheduler
_duration = duration
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| df982f4669201a4ea207bcd281fd8a54 | 25.944444 | 145 | 0.576031 | false | false | false | false |
DrabWeb/Keijiban | refs/heads/master | Keijiban/Keijiban/KJPostViewerViewController.swift | gpl-3.0 | 1 | //
// KJBrowserWindowPostViewerViewController.swift
// Keijiban
//
// Created by Seth on 2016-05-27.
//
import Cocoa
import Alamofire
/// The view controller for the posts viewer view(Can show catalog, index or a thread)
class KJPostViewerViewController: NSViewController {
/// The collection view for this post viewer for if it is in the catalog
@IBOutlet var catalogCollectionView: NSCollectionView!
/// The scroll view for catalogCollectionView
@IBOutlet var catalogCollectionViewScrollView: NSScrollView!
/// The NSArrayController for catalogCollectionView
@IBOutlet weak var catalogCollectionViewArrayController: NSArrayController!
/// The array of items in catalogCollectionViewArrayController
var catalogCollectionViewItems : NSMutableArray = NSMutableArray();
/// The stack view for showing the posts in the posts viewer stack view
@IBOutlet var postsViewerStackView: NSStackView!
/// The scroll view for postsViewerStackView
@IBOutlet var postsViewerStackViewScrollView: NSScrollView!
/// The current mode that this post viewer is in
var currentMode : KJPostViewerMode = KJPostViewerMode.None;
/// The current board this post viewer is showing something for
var currentBoard : KJ4CBoard? = nil;
/// The current thread we are displaying(If any)
var currentThread : KJ4CThread? = nil;
/// The last requests for downloading thumbnails in this view
var lastThumbnailDownloadRequests : [Request] = [];
/// Displays the given thread in the posts stack view. Returns the title that should be used in tabs
func displayThread(thread : KJ4CThread, completionHandler: (() -> ())?) -> String {
// Set the current mode, board and thread
currentMode = .Thread;
currentBoard = thread.board!;
currentThread = thread;
// Print what thread we are displaying
print("KJPostViewerViewController: Displaying thread /\(currentBoard!.code)/\(currentThread!.opPost!.postNumber) - \(currentThread!.displayTitle!)");
// Remove all the current post items
clearPostsViewerStackView();
// For every post in the given thread...
for(_, currentThreadPost) in currentThread!.allPosts.enumerate() {
// Add the current post to postsViewerStackView
addPostToPostsViewerStackView(currentThreadPost, displayImage: true);
}
// Scroll to the top of postsViewerStackViewScrollView
scrollToTopOfPostsViewerStackViewScrollView();
// Hide all the other views
catalogCollectionViewScrollView.hidden = true;
// Show the posts view
postsViewerStackViewScrollView.hidden = false;
// Return the title
return "/\(currentBoard!.code)/ - \(currentThread!.displayTitle!)";
}
/// Displays the catalog for the given board. Only shows the amount of pages given(Minimum 0, maximum 9). Calls the given completion handler when done(If any). Returns the title that should be used in tabs
func displayCatalog(forBoard : KJ4CBoard, maxPages : Int, completionHandler: (() -> ())?) -> String {
// Set the current mode, board and thread
currentMode = .Catalog;
currentBoard = forBoard;
currentThread = nil;
// Print what catalog we are displaying
print("KJPostViewerViewController: Displaying \(maxPages + 1) catalog pages for /\(currentBoard!.code)/");
// Clear all the current items
catalogCollectionViewArrayController.removeObjects(catalogCollectionViewArrayController.arrangedObjects as! [AnyObject]);
// Make the request to get the catalog
Alamofire.request(.GET, "https://a.4cdn.org/\(currentBoard!.code)/catalog.json", encoding: .JSON).responseJSON { (responseData) -> Void in
/// The string of JSON that will be returned when the GET request finishes
let responseJsonString : NSString = NSString(data: responseData.data!, encoding: NSUTF8StringEncoding)!;
// If the the response data isnt nil...
if let dataFromResponseJsonString = responseJsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
/// The JSON from the response string
let responseJson = JSON(data: dataFromResponseJsonString);
// For every page up till the given page limit...
for currentPageIndex in 0...maxPages {
// For every thread in the current page...
for(_, currentThread) in responseJson[currentPageIndex]["threads"].enumerate() {
/// The new OP post to add to the catalog collection view
let newOpPost : KJ4COPPost = KJ4COPPost(json: currentThread.1, board: self.currentBoard!);
// Load the thumbnail image
self.lastThumbnailDownloadRequests.append(Alamofire.request(.GET, newOpPost.fileThumbnailUrl).response { (request, response, data, error) in
// If data isnt nil...
if(data != nil) {
/// The downloaded image
let image : NSImage? = NSImage(data: data!);
// If image isnt nil...
if(image != nil) {
// If there are any items in catalogCollectionViewArrayController...
if((self.catalogCollectionViewArrayController.arrangedObjects as! [AnyObject]).count > 0) {
// For ever item in the catalog collection view...
for currentIndex in 0...(self.catalogCollectionViewArrayController.arrangedObjects as! [AnyObject]).count - 1 {
// If the current item's represented object is equal to the item we downloaded the thumbnail for...
if(((self.catalogCollectionView.itemAtIndex(currentIndex)! as! KJPostViewerCatalogCollectionViewItem).representedObject as! KJ4COPPost) == newOpPost) {
// Update the image view of the item
self.catalogCollectionView.itemAtIndex(currentIndex)!.imageView?.image = image!;
// Set the item's model's thumbnail image
((self.catalogCollectionView.itemAtIndex(currentIndex)! as! KJPostViewerCatalogCollectionViewItem).representedObject as! KJ4COPPost).thumbnailImage = image!;
}
}
}
}
}
});
// Add the OP post to the catalog collection view
self.catalogCollectionViewArrayController.addObject(newOpPost);
}
}
// Call the completion handler
completionHandler?();
}
}
// Hide all the other views
postsViewerStackViewScrollView.hidden = true;
// Show the catalog collection view
catalogCollectionViewScrollView.hidden = false;
// Return the title
return "/\(currentBoard!.code)/ - Catalog";
}
/// Displays the index for the given board. Only shows the amount of pages given(Minimum 0, maximum 9). Calls the given completion handler when done(If any). Returns the title that should be used in tabs
func displayIndex(forBoard : KJ4CBoard, maxPages : Int, completionHandler: (() -> ())?) -> String {
// Set the current mode, board and thread
currentMode = .Index;
currentBoard = forBoard;
currentThread = nil;
// Print what catalog we are displayinga
print("KJPostViewerViewController: Displaying \(maxPages + 1) index pages for /\(currentBoard!.code)/");
// Clear all the current items
clearPostsViewerStackView();
// Make the request to get the catalog
Alamofire.request(.GET, "https://a.4cdn.org/\(currentBoard!.code)/catalog.json", encoding: .JSON).responseJSON { (responseData) -> Void in
/// The string of JSON that will be returned when the GET request finishes
let responseJsonString : NSString = NSString(data: responseData.data!, encoding: NSUTF8StringEncoding)!;
// If the the response data isnt nil...
if let dataFromResponseJsonString = responseJsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
/// The JSON from the response string
let responseJson = JSON(data: dataFromResponseJsonString);
// For every page up till the given page limit...
for currentPageIndex in 0...maxPages {
// For every thread in the current page...
for(_, currentThread) in responseJson[currentPageIndex]["threads"].enumerate() {
/// The new OP post to add to the catalog collection view
let newOpPost : KJ4COPPost = KJ4COPPost(json: currentThread.1, board: self.currentBoard!);
// Load the thumbnail image
newOpPost.thumbnailImage = NSImage(contentsOfURL: NSURL(string: newOpPost.fileThumbnailUrl)!);
// Add the OP post to the posts view
self.addPostToPostsViewerStackView(newOpPost, displayImage: true);
// For every reply in the OP post's recent replies...
for(_, currentRecentReply) in newOpPost.recentReplies.enumerate() {
// Add the current post to the posts view
self.addPostToPostsViewerStackView(currentRecentReply, displayImage: false);
}
}
}
// Call the completion handler
completionHandler?();
}
}
// Scroll to the top of postsViewerStackViewScrollView
scrollToTopOfPostsViewerStackViewScrollView();
// Hide all the other views
catalogCollectionViewScrollView.hidden = true;
// Show the posts view
postsViewerStackViewScrollView.hidden = false;
// Return the title
return "/\(currentBoard!.code)/ - Index";
}
/// Scrolls to the top of postsViewerStackViewScrollView
func scrollToTopOfPostsViewerStackViewScrollView() {
// Scroll to the top of postsViewerStackViewScrollView
postsViewerStackViewScrollView.contentView.scrollToPoint(NSPoint(x: 0, y: postsViewerStackView.subviews.count * 100000));
}
/// Clears all the items in postsViewerStackView
func clearPostsViewerStackView() {
// Remove all the subviews from postsViewerStackView
postsViewerStackView.subviews.removeAll();
}
/// Adds the given post to postsViewerStackView. ALso only shows the thumbnail if displayImage is true
func addPostToPostsViewerStackView(post : KJ4CPost, displayImage : Bool) {
/// The new post view item for the stack view
let newPostView : KJPostView = KJPostView();
// Display the post's info in the new post view
newPostView.displayPost(post, displayImage: displayImage);
// Set newPostView's repliesViewerViewContainer
newPostView.repliesViewerViewContainer = self.view;
// Set newPostView's thumbnail clicked target and action
newPostView.thumbnailClickedTarget = self;
newPostView.thumbnailClickedAction = Selector("postThumbnailImageClicked:");
// Add the post view to postsViewerStackView
postsViewerStackView.addView(newPostView, inGravity: NSStackViewGravity.Top);
// Add the leading and trailing constraints
/// The constraint for the trailing edge of newPostView
let newPostViewTrailingConstraint = NSLayoutConstraint(item: newPostView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: postsViewerStackViewScrollView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -50);
// Add the constraint
postsViewerStackViewScrollView.addConstraint(newPostViewTrailingConstraint);
/// The constraint for the leading edge of newPostView
let newPostViewLeadingConstraint = NSLayoutConstraint(item: newPostView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: postsViewerStackViewScrollView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: -50);
// Add the constraint
postsViewerStackViewScrollView.addConstraint(newPostViewLeadingConstraint);
}
/// The current image browser for this posts viewer
var currentImageBrowser : KJPostsImageViewer? = nil;
/// Called when the user presses a post's thumbnail image
func postThumbnailImageClicked(post : KJ4CPost) {
// Print what post we are displaying the file of
print("KJPostViewerViewController: Displaying the file for \(post)");
// If the current image browser is nil...
if(currentImageBrowser?.superview == nil) {
// Create a new KJPostsImageViewer
currentImageBrowser = KJPostsImageViewer();
// Move it into this view
self.view.addSubview(currentImageBrowser!);
// Disable translating autoresizing masks into constraints
currentImageBrowser!.translatesAutoresizingMaskIntoConstraints = false;
// Add the outer constraints
currentImageBrowser!.addOuterConstraints(0);
// Load in the current posts
currentImageBrowser!.showImagesForPosts(self.currentThread!.allPosts, displayFirstPost: false);
}
// Jump to the clicked image in the current image browser
currentImageBrowser!.displayPostAtIndex(NSMutableArray(array: currentImageBrowser!.currentBrowsingPosts).indexOfObject(post));
}
override func viewWillAppear() {
// Theme the view
self.view.layer?.backgroundColor = KJThemingEngine().defaultEngine().backgroundColor.CGColor;
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
// Set postsViewerStackViewScrollView's document view
postsViewerStackViewScrollView.documentView = postsViewerStackView;
// Set the catalog collection view's item prototype
catalogCollectionView.itemPrototype = storyboard!.instantiateControllerWithIdentifier("catalogCollectionViewItem") as? NSCollectionViewItem;
// Set the minimum and maximum item sizes
catalogCollectionView.minItemSize = NSSize(width: 150, height: 200);
catalogCollectionView.maxItemSize = NSSize(width: 250, height: 250);
}
}
/// The different modes KJPostViewerViewController can be in
enum KJPostViewerMode {
/// Not set
case None
/// The catalog collection view
case Catalog
/// The index where you see the most recent posts
case Index
/// A thread
case Thread
}
| f7e4411065a4fd7533466fbc8115899e | 48.77709 | 265 | 0.614877 | false | false | false | false |
cfilipov/MuscleBook | refs/heads/master | MuscleBook/DB+Exercises.swift | gpl-3.0 | 1 | /*
Muscle Book
Copyright (C) 2016 Cristian Filipov
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import SQLite
extension Exercise {
enum SortType: Int {
case Alphabetical = 0
case Count
private func column(scope scope: SchemaType) -> Expressible {
typealias E = Exercise.Schema
typealias W = Workset.Schema
switch self {
case .Alphabetical: return scope[E.name]
case .Count: return W.workoutID.distinct.count.desc
}
}
}
}
extension DB {
func all(type: Exercise.Type) throws -> AnySequence<Exercise> {
return try db.prepare(Exercise.Schema.table)
}
func all(type: Exercise.Type, sort: Exercise.SortType) throws -> [ExerciseReference] {
typealias R = ExerciseReference.Schema
typealias E = Exercise.Schema
typealias W = Workset.Schema
let rows = try db.prepare(E.table
.select(E.table[E.exerciseID], E.table[E.name], W.workoutID.distinct.count)
.join(.LeftOuter, W.table, on: W.table[W.exerciseID] == E.table[E.exerciseID])
.group(E.table[E.exerciseID])
.order(sort.column(scope: E.table)))
return rows.map {
return ExerciseReference(
exerciseID: $0[R.exerciseID],
name: $0[R.name],
count: $0[W.workoutID.distinct.count])
}.filter {
guard sort == .Count else { return true }
return $0.count > 0
}
}
func count(type: Exercise.Type) -> Int {
return db.scalar(Exercise.Schema.table.count)
}
func count(type: Exercise.Type, exerciseID: Int64) -> Int {
typealias WS = Workset.Schema
return db.scalar(WS.table.select(WS.exerciseID.count).filter(WS.exerciseID == exerciseID))
}
func dereference(ref: ExerciseReference) -> Exercise? {
guard let exerciseID = ref.exerciseID else { return nil }
typealias S = Exercise.Schema
let query = S.table.filter(S.exerciseID == exerciseID)
return db.pluck(query)
}
func find(exactName name: String) -> ExerciseReference? {
typealias E = Exercise.Schema
return db.pluck(E.search
.select(E.exerciseID, E.name)
.filter(E.name == name))
}
func find(exerciseID exerciseID: Int64) throws -> AnySequence<MuscleMovement> {
return try db.prepare(
MuscleMovement.Schema.table.filter(
MuscleMovement.Schema.exerciseID == exerciseID))
}
func findUnknownExercises() throws -> AnySequence<ExerciseReference> {
let query = Workset.Schema.table
.select(Workset.Schema.exerciseName)
.filter(Workset.Schema.exerciseID == nil)
.group(Workset.Schema.exerciseName)
return try db.prepare(query)
}
func get(type: ExerciseReference.Type, date: NSDate) throws -> AnySequence<ExerciseReference> {
typealias WS = Workset.Schema
return try db.prepare(WS.table
.select(WS.exerciseID, WS.exerciseName)
.filter(WS.startTime.localDay == date.localDay)
.group(WS.exerciseID))
}
func match(name name: String, sort: Exercise.SortType) throws -> [ExerciseReference] {
typealias E = Exercise.Schema
typealias W = Workset.Schema
let rows = try db.prepare(E.search
.select(E.search[E.exerciseID], E.search[E.name], W.workoutID.distinct.count)
.join(.LeftOuter, W.table, on:
W.table[W.exerciseID] == E.search[E.exerciseID])
.group(E.search[E.exerciseID])
.match("*"+name+"*")
.order(sort.column(scope: E.search)))
return rows.map {
return ExerciseReference(
exerciseID: $0[E.search[E.exerciseID]],
name: $0[E.name],
count: $0[W.workoutID.distinct.count])
}.filter {
guard sort == .Count else { return true }
return $0.count > 0
}
}
func save(exercise: Exercise) throws {
try db.transaction { [unowned self] in
try self.db.run(Exercise.Schema.table.insert(or: .Replace, exercise))
for movement in exercise.muscles! {
try self.db.run(MuscleMovement.Schema.table.insert(movement))
}
try self.db.run(Exercise.Schema.search.insert(or: .Replace, exercise.exerciseReference))
}
}
func totalExercisesPerformed(sinceDate date: NSDate) -> Int {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.exerciseID.distinct.count)
.filter(W.startTime.localDay >= date))
}
} | cbee248f082b05bb3ce214552ab36006 | 35.380952 | 100 | 0.61773 | false | false | false | false |
AlexRamey/mbird-iOS | refs/heads/master | Pods/CVCalendar/CVCalendar/CVCalendarContentViewController.swift | mit | 1 | //
// CVCalendarContentViewController.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 12/04/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
public typealias Identifier = String
open class CVCalendarContentViewController: UIViewController {
// MARK: - Constants
open let previous = "Previous"
open let presented = "Presented"
open let following = "Following"
// MARK: - Public Properties
open unowned let calendarView: CalendarView
open let scrollView: UIScrollView
open var presentedMonthView: MonthView
open var bounds: CGRect {
return scrollView.bounds
}
open var currentPage = 1
open var pageChanged: Bool {
return currentPage == 1 ? false : true
}
open var pageLoadingEnabled = true
open var presentationEnabled = true
open var lastContentOffset: CGFloat = 0
open var direction: CVScrollDirection = .none
open var toggleDateAnimationDuration: Double {
return calendarView.delegate?.toggleDateAnimationDuration?() ?? 0.8
}
public init(calendarView: CalendarView, frame: CGRect) {
self.calendarView = calendarView
scrollView = UIScrollView(frame: frame)
presentedMonthView = MonthView(calendarView: calendarView, date: calendarView.presentedDate?.convertedDate() ?? Foundation.Date())
presentedMonthView.updateAppearance(frame)
super.init(nibName: nil, bundle: nil)
scrollView.contentSize = CGSize(width: frame.width * 3, height: frame.height)
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.layer.masksToBounds = true
scrollView.isPagingEnabled = true
scrollView.delegate = self
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI Refresh
extension CVCalendarContentViewController {
@objc public func updateFrames(_ frame: CGRect) {
if frame != CGRect.zero {
scrollView.frame = frame
scrollView.removeAllSubviews()
scrollView.contentSize = CGSize(width: frame.size.width * 3, height: frame.size.height)
}
calendarView.isHidden = false
}
}
//MARK: - Month Refresh
extension CVCalendarContentViewController {
public func refreshPresentedMonth() {
for weekV in presentedMonthView.weekViews {
for dayView in weekV.dayViews {
removeCircleLabel(dayView)
dayView.setupDotMarker()
dayView.preliminarySetup()
dayView.supplementarySetup()
dayView.topMarkerSetup()
dayView.interactionSetup()
dayView.labelSetup()
}
}
}
}
// MARK: Delete circle views (in effect refreshing the dayView circle)
extension CVCalendarContentViewController {
func removeCircleLabel(_ dayView: CVCalendarDayView) {
for each in dayView.subviews {
if each is UILabel {
continue
} else if each is CVAuxiliaryView {
continue
} else {
each.removeFromSuperview()
}
}
}
}
//MARK: Delete dot views (in effect refreshing the dayView dots)
extension CVCalendarContentViewController {
func removeDotViews(_ dayView: CVCalendarDayView) {
for each in dayView.subviews {
if each is CVAuxiliaryView && each.frame.height == 13 {
each.removeFromSuperview()
}
}
}
}
// MARK: - Abstract methods
/// UIScrollViewDelegate
extension CVCalendarContentViewController: UIScrollViewDelegate { }
// Convenience API.
extension CVCalendarContentViewController {
@objc public func performedDayViewSelection(_ dayView: DayView) { }
@objc public func togglePresentedDate(_ date: Foundation.Date) { }
@objc public func presentNextView(_ view: UIView?) { }
@objc public func presentPreviousView(_ view: UIView?) { }
@objc public func updateDayViews(shouldShow: Bool) { }
}
// MARK: - Contsant conversion
extension CVCalendarContentViewController {
public func indexOfIdentifier(_ identifier: Identifier) -> Int {
let index: Int
switch identifier {
case previous: index = 0
case presented: index = 1
case following: index = 2
default: index = -1
}
return index
}
}
// MARK: - Date management
extension CVCalendarContentViewController {
public func dateBeforeDate(_ date: Foundation.Date) -> Foundation.Date {
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
var components = Manager.componentsForDate(date, calendar: calendar)
components.month! -= 1
let dateBefore = calendar.date(from: components)!
return dateBefore
}
public func dateAfterDate(_ date: Foundation.Date) -> Foundation.Date {
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
var components = Manager.componentsForDate(date, calendar: calendar)
components.month! += 1
let dateAfter = calendar.date(from: components)!
return dateAfter
}
public func matchedMonths(_ lhs: CVDate, _ rhs: CVDate) -> Bool {
return lhs.year == rhs.year && lhs.month == rhs.month
}
public func matchedWeeks(_ lhs: CVDate, _ rhs: CVDate) -> Bool {
return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.week == rhs.week)
}
public func matchedDays(_ lhs: CVDate, _ rhs: CVDate) -> Bool {
return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day)
}
}
// MARK: - AutoLayout Management
extension CVCalendarContentViewController {
fileprivate func layoutViews(_ views: [UIView], toHeight height: CGFloat) {
scrollView.frame.size.height = height
var superStack = [UIView]()
var currentView: UIView = calendarView
while let currentSuperview = currentView.superview , !(currentSuperview is UIWindow) {
superStack += [currentSuperview]
currentView = currentSuperview
}
for view in views + superStack {
view.layoutIfNeeded()
}
}
public func updateHeight(_ height: CGFloat, animated: Bool) {
if calendarView.shouldAnimateResizing {
var viewsToLayout = [UIView]()
if let calendarSuperview = calendarView.superview {
for constraintIn in calendarSuperview.constraints {
if let firstItem = constraintIn.firstItem as? UIView,
let _ = constraintIn.secondItem as? CalendarView {
viewsToLayout.append(firstItem)
}
}
}
for constraintIn in calendarView.constraints where
constraintIn.firstAttribute == NSLayoutAttribute.height {
constraintIn.constant = height
if animated {
UIView.animate(withDuration: 0.2, delay: 0,
options: UIViewAnimationOptions.curveLinear,
animations: { [weak self] in
self?.layoutViews(viewsToLayout, toHeight: height)
}) { [weak self] _ in
guard let strongSelf = self else {
return
}
strongSelf.presentedMonthView.frame.size = strongSelf.presentedMonthView.potentialSize
strongSelf.presentedMonthView.updateInteractiveView()
}
} else {
layoutViews(viewsToLayout, toHeight: height)
presentedMonthView.updateInteractiveView()
presentedMonthView.frame.size = presentedMonthView.potentialSize
presentedMonthView.updateInteractiveView()
}
break
}
}
}
public func updateLayoutIfNeeded() {
if presentedMonthView.potentialSize.height != scrollView.bounds.height {
updateHeight(presentedMonthView.potentialSize.height, animated: true)
} else if presentedMonthView.frame.size != scrollView.frame.size {
presentedMonthView.frame.size = presentedMonthView.potentialSize
presentedMonthView.updateInteractiveView()
}
}
}
extension UIView {
public func removeAllSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
}
| f88eae5fae85a0b9500c6313c3f8788b | 31.492647 | 138 | 0.616316 | false | false | false | false |
alexwinston/UIViewprint | refs/heads/master | UIViewprint/Examples/Padding/PaddingExamplesController.swift | mit | 1 | //
// UILabelExamples.swift
// Blueprint
//
// Created by Alex Winston on 3/9/16.
// Copyright © 2016 Alex Winston. All rights reserved.
//
import Foundation
import UIKit
// TODO? Create UITableViewableStyleController that only requires a cell style and a datasource
class PaddingExamplesController: UITableViewableController {
let examples: [ExampleControllerDetails] = [
ExampleControllerDetails(name:"UIView basic padding example", controller:UIViewPaddingController.self),
]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "UIView padding examples"
self.edgesForExtendedLayout = UIRectEdge.None;
self.table(
sections: [
section(selectExample, foreach:examples) { (example:AnyObject) in
let example = example as! ExampleControllerDetails
return self.defaultTableViewCell(example.name)
}
]
)
}
func selectExample(indexPath:NSIndexPath) {
let controller:UIViewController = self.examples[indexPath.row].controller.init()
controller.view.frame = view.bounds
controller.view.backgroundColor = .whiteColor()
controller.view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
self.navigationController?.pushViewController(controller, animated: true)
}
} | 9e25694d004a99a720a2e083f2e58dc1 | 32.363636 | 112 | 0.664622 | false | false | false | false |
ReactiveCocoa/ReactiveSwift | refs/heads/master | Sources/Observers/CollectEvery.swift | mit | 1 | import Dispatch
extension Operators {
internal final class CollectEvery<Value, Error: Swift.Error>: UnaryAsyncOperator<Value, [Value], Error> {
let interval: DispatchTimeInterval
let discardWhenCompleted: Bool
let targetWithClock: DateScheduler
private let state: Atomic<CollectEveryState<Value>>
private let timerDisposable = SerialDisposable()
init(
downstream: Observer<[Value], Error>,
downstreamLifetime: Lifetime,
target: DateScheduler,
interval: DispatchTimeInterval,
skipEmpty: Bool,
discardWhenCompleted: Bool
) {
self.interval = interval
self.discardWhenCompleted = discardWhenCompleted
self.targetWithClock = target
self.state = Atomic(CollectEveryState(skipEmpty: skipEmpty))
super.init(downstream: downstream, downstreamLifetime: downstreamLifetime, target: target)
downstreamLifetime += timerDisposable
let initialDate = targetWithClock.currentDate.addingTimeInterval(interval)
timerDisposable.inner = targetWithClock.schedule(after: initialDate, interval: interval, leeway: interval * 0.1) {
let (currentValues, isCompleted) = self.state.modify { ($0.collect(), $0.isCompleted) }
if let currentValues = currentValues {
self.unscheduledSend(currentValues)
}
if isCompleted {
self.unscheduledTerminate(.completed)
}
}
}
override func receive(_ value: Value) {
state.modify { $0.values.append(value) }
}
override func terminate(_ termination: Termination<Error>) {
guard isActive else { return }
if case .completed = termination, !discardWhenCompleted {
state.modify { $0.isCompleted = true }
} else {
timerDisposable.dispose()
super.terminate(termination)
}
}
}
}
private struct CollectEveryState<Value> {
let skipEmpty: Bool
var values: [Value] = []
var isCompleted: Bool = false
init(skipEmpty: Bool) {
self.skipEmpty = skipEmpty
}
var hasValues: Bool {
return !values.isEmpty || !skipEmpty
}
mutating func collect() -> [Value]? {
guard hasValues else { return nil }
defer { values.removeAll() }
return values
}
}
| 16fc4f03637dc3f9d2b2cfda83cd2d47 | 25.807692 | 117 | 0.724055 | false | false | false | false |
tinypass/piano-sdk-for-ios | refs/heads/master | PianoAPI/API/SubscriptionAPI.swift | apache-2.0 | 1 | import Foundation
@objc(PianoAPISubscriptionAPI)
public class SubscriptionAPI: NSObject {
/// Lists a user's subscription
/// - Parameters:
/// - aid: Application aid
/// - userToken: User token
/// - userProvider: User token provider
/// - userRef: Encrypted user reference
/// - callback: Operation callback
@objc public func list(
aid: String,
userToken: String? = nil,
userProvider: String? = nil,
userRef: String? = nil,
completion: @escaping ([UserSubscription]?, Error?) -> Void) {
guard let client = PianoAPI.shared.client else {
completion(nil, PianoAPIError("PianoAPI not initialized"))
return
}
var params = [String:String]()
params["aid"] = aid
if let v = userToken { params["user_token"] = v }
if let v = userProvider { params["user_provider"] = v }
if let v = userRef { params["user_ref"] = v }
client.request(
path: "/api/v3/subscription/list",
method: PianoAPI.HttpMethod.from("POST"),
params: params,
completion: completion
)
}
}
| c498dd63e1fc044f89807c680dfa94db | 31.888889 | 70 | 0.571791 | false | false | false | false |
R3dTeam/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Rules/TypeNameRule.swift | mit | 5 | //
// TypeNameRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
import SwiftXPC
public struct TypeNameRule: ASTRule {
public init() {}
public let identifier = "type_name"
public func validateFile(file: File) -> [StyleViolation] {
return validateFile(file, dictionary: file.structure.dictionary)
}
public func validateFile(file: File, dictionary: XPCDictionary) -> [StyleViolation] {
return (dictionary["key.substructure"] as? XPCArray ?? []).flatMap { subItem in
var violations = [StyleViolation]()
if let subDict = subItem as? XPCDictionary,
let kindString = subDict["key.kind"] as? String,
let kind = flatMap(kindString, { SwiftDeclarationKind(rawValue: $0) }) {
violations.extend(validateFile(file, dictionary: subDict))
violations.extend(validateFile(file, kind: kind, dictionary: subDict))
}
return violations
}
}
public func validateFile(file: File,
kind: SwiftDeclarationKind,
dictionary: XPCDictionary) -> [StyleViolation] {
let typeKinds: [SwiftDeclarationKind] = [
.Class,
.Struct,
.Typealias,
.Enum,
.Enumelement
]
if !contains(typeKinds, kind) {
return []
}
var violations = [StyleViolation]()
if let name = dictionary["key.name"] as? String,
let offset = flatMap(dictionary["key.offset"] as? Int64, { Int($0) }) {
let location = Location(file: file, offset: offset)
let nameCharacterSet = NSCharacterSet(charactersInString: name)
if !NSCharacterSet.alphanumericCharacterSet().isSupersetOfSet(nameCharacterSet) {
violations.append(StyleViolation(type: .NameFormat,
location: location,
severity: .High,
reason: "Type name should only contain alphanumeric characters: '\(name)'"))
} else if !name.substringToIndex(name.startIndex.successor()).isUppercase() {
violations.append(StyleViolation(type: .NameFormat,
location: location,
severity: .High,
reason: "Type name should start with an uppercase character: '\(name)'"))
} else if count(name) < 3 || count(name) > 40 {
violations.append(StyleViolation(type: .NameFormat,
location: location,
severity: .Medium,
reason: "Type name should be between 3 and 40 characters in length: " +
"'\(name)'"))
}
}
return violations
}
public let example = RuleExample(
ruleName: "Type Name Rule",
ruleDescription: "Type name should only contain alphanumeric characters, " +
"start with an uppercase character and between 3 and 40 characters in length.",
nonTriggeringExamples: [],
triggeringExamples: [],
showExamples: false
)
}
| bcddeeb8a9ff8bea0d19511cc425ae28 | 38.407407 | 96 | 0.5849 | false | false | false | false |
sudeepunnikrishnan/ios-sdk | refs/heads/master | Instamojo/Spinner.swift | lgpl-3.0 | 1 | //
// Spinner.swift
// Instamojo
//
// Created by Sukanya Raj on 07/03/17.
// Copyright © 2017 Sukanya Raj. All rights reserved.
//
import UIKit
public class Spinner: UIVisualEffectView {
var text: String? {
didSet {
label.text = text
}
}
let background: UIView = UIView()
let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
let label: UILabel = UILabel()
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
let vibrancyView: UIVisualEffectView
public init(text: String) {
self.text = text
self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
super.init(effect: blurEffect)
self.setup()
}
public func setText(text: String) {
self.text = text
}
required public init?(coder aDecoder: NSCoder) {
self.text = ""
self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
super.init(coder: aDecoder)
self.setup()
}
func setup() {
contentView.addSubview(background)
contentView.addSubview(vibrancyView)
contentView.addSubview(activityIndictor)
contentView.addSubview(label)
activityIndictor.startAnimating()
}
override public func didMoveToSuperview() {
super.didMoveToSuperview()
if let superview = self.superview {
let width = superview.frame.size.width / 1.7
let height: CGFloat = 50.0
self.frame = CGRect(x: superview.frame.size.width / 2 - width / 2,
y: superview.frame.height / 2 - height / 2,
width: width,
height: height)
vibrancyView.frame = self.bounds
background.frame = self.bounds
background.backgroundColor = UIColor.lightGray
let activityIndicatorSize: CGFloat = 40
activityIndictor.frame = CGRect(x: 5,
y: height / 2 - activityIndicatorSize / 2,
width: activityIndicatorSize,
height: activityIndicatorSize)
layer.cornerRadius = 8.0
layer.masksToBounds = true
label.text = text
label.textAlignment = NSTextAlignment.center
label.frame = CGRect(x: activityIndicatorSize + 1,
y: 0,
width: width - activityIndicatorSize - 10,
height: height)
label.textColor = UIColor.white
label.font = UIFont.boldSystemFont(ofSize: 14)
}
}
public func show() {
self.isHidden = false
label.text = text
}
public func hide() {
self.isHidden = true
}
}
| 156e8a0c567111a24a685ea9917491d9 | 31.586957 | 140 | 0.571381 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Banking | refs/heads/master | HatchReadyApp/apps/Hatch/iphone/native/Hatch/Controllers/HybridViewController.swift | epl-1.0 | 1 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/**
* Contains the webview that holds the hybrid view components in the app.
*/
class HybridViewController: CDVViewController {
/// determines whether the HybridViewController is rendering the initial hybrid view screen
var isFirstInstance = true
/// determines whether the HybridViewController was instantiated for showing the goals screens
var fromGoals: Bool = false
/// determines whether the HybridViewController was instantiated for showing the dashboard screens
var fromDash: Bool = false
/// saves a screenshot of the hybrid view which is helpful for reducing flickering between screen transitions
var image : UIImage!
/**
This init method is called when the hybridViewController is first initialized in the app delegate
- parameter aDecoder: <#aDecoder description#>
- returns: <#return value description#>
*/
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.startPage = WL.sharedInstance().mainHtmlFilePath()
print("Start Page: \(self.startPage)")
}
/**
When the hybridViewController is first loaded, it sets the start page and sends a message to the javascript passing the person data to prepopulate the fields
*/
override func viewDidLoad() {
super.viewDidLoad()
self.webView.scrollView.bounces = false
addTapRecognizer()
}
/**
Adds a UITapGestureRecognizer to the view that will be used to know when to update the screenshot of the view for transitioning
*/
func addTapRecognizer(){
let tapRecognizer = UITapGestureRecognizer(target: self, action: "updateImage")
tapRecognizer.cancelsTouchesInView = false
tapRecognizer.delegate = self
self.view.addGestureRecognizer(tapRecognizer)
}
/**
Takes a screenshot of the current state of the view. This is used to make the transitions smoother
*/
func updateImage(){
image = Utils.imageWithView(self.view)
}
}
extension HybridViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| 843913c636af882535a41ee845410001 | 35.606061 | 172 | 0.714404 | false | false | false | false |
DianQK/Flix | refs/heads/master | Example/Example/Tutorial/SettingsViewController.swift | mit | 1 | //
// SettingsViewController.swift
// Example
//
// Created by DianQK on 02/11/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Flix
class SettingsViewController: TableViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.largeTitleDisplayMode = .automatic
title = "Settings"
let profileProvider = ProfileProvider(avatar: #imageLiteral(resourceName: "Flix Icon"), name: "Flix")
let profileSectionProvider = SpacingSectionProvider(providers: [profileProvider], headerHeight: 35, footerHeight: 0)
let airplaneModeProvider = SwitchTableViewCellProvider(title: "Airplane Mode", icon: #imageLiteral(resourceName: "Airplane Icon"), isOn: false)
let wifiProvider = DescriptionTableViewCellProvider(title: "Wi-Fi", icon: #imageLiteral(resourceName: "Wifi Icon"), description: "Flix_5G")
let bluetoothProvider = DescriptionTableViewCellProvider(title: "Bluetooth", icon: #imageLiteral(resourceName: "Bluetooth Icon"), description: "On")
let cellularProvider = DescriptionTableViewCellProvider(title: "Cellular", icon: #imageLiteral(resourceName: "Cellular Icon"))
let personalHotspotProvider = DescriptionTableViewCellProvider(title: "Personal Hotspot", icon: #imageLiteral(resourceName: "Personal Hotspot Icon"), description: "Off")
let carrierProvider = DescriptionTableViewCellProvider(title: "Carrier", icon: #imageLiteral(resourceName: "Carrier Icon"), description: "AT&T")
let networkSectionProvider = SpacingSectionProvider(
providers: [
airplaneModeProvider,
wifiProvider,
bluetoothProvider,
cellularProvider,
personalHotspotProvider,
carrierProvider
],
headerHeight: 35,
footerHeight: 0
)
let appSectionProvider = SpacingSectionProvider(
providers: [AppsProvider(apps: [
App(icon: #imageLiteral(resourceName: "Wallet App Icon"), title: "Wallet"),
App(icon: #imageLiteral(resourceName: "Music App Icon"), title: "Music"),
App(icon: #imageLiteral(resourceName: "Safari App Icon"), title: "Safari"),
App(icon: #imageLiteral(resourceName: "News App Icon"), title: "News"),
App(icon: #imageLiteral(resourceName: "Camera App Icon"), title: "Camera"),
App(icon: #imageLiteral(resourceName: "Photos App Icon"), title: "Photo")
])],
headerHeight: 35,
footerHeight: 35
)
self.tableView.flix.build([profileSectionProvider, networkSectionProvider, appSectionProvider])
}
}
| b218d04bf01550372c5cefcc7e2503a7 | 43.31746 | 177 | 0.663682 | false | false | false | false |
d4rkl0rd3r3b05/Data_Structure_And_Algorithm | refs/heads/master | LeetCode_LongestPalindromicSubString.swift | mit | 1 | /*
* Given a string s, find the longest palindromic substring in s.
*/
func checkPalindromicString(input : String) -> Bool{
guard input.characters.count > 0 else {
return false
}
if input.characters.count == 1 {
return true
}
for index in 0 ..< input.characters.count/2 {
if input[index] != input[input.characters.count - index - 1] {
return false
}
}
return true
}
public func getLongestPalindromicSubString(input : String) -> String?{
var maxLength = 0
var palindromicSubString = ""
for index in 0 ..< input.characters.count {
for innerIndex in ((index + 1) ..< input.characters.count).reversed() {
if input[index] == input[innerIndex] {
if checkPalindromicString(input: input[(index + 1) ..< innerIndex]) && maxLength < input[(index + 1) ..< innerIndex].characters.count{
maxLength = input[(index + 1) ..< innerIndex].characters.count
palindromicSubString = input[index ..< innerIndex + 1]
}
}
}
}
return maxLength != 0 ? palindromicSubString : nil
}
| 2182b9c254cd1cdfa4cc940d2125b232 | 30.105263 | 150 | 0.576142 | false | false | false | false |
tjw/swift | refs/heads/master | test/SILGen/downgrade_exhaustivity_swift3.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -swift-version 3 -enable-sil-ownership -emit-silgen %s | %FileCheck %s
enum Downgradable {
case spoon
case hat
@_downgrade_exhaustivity_check
case fork
}
// CHECK-LABEL: sil hidden @$S29downgrade_exhaustivity_swift343testDowngradableOmittedPatternIsUnreachable3patyAA0E0OSg_tF
func testDowngradableOmittedPatternIsUnreachable(pat : Downgradable?) {
// CHECK: switch_enum {{%.*}} : $Downgradable, case #Downgradable.spoon!enumelt: [[CASE1:bb[0-9]+]], case #Downgradable.hat!enumelt: [[CASE2:bb[0-9]+]], default [[DEFAULT_CASE:bb[0-9]+]]
switch pat! {
// CHECK: [[CASE1]]:
case .spoon:
break
// CHECK: [[CASE2]]:
case .hat:
break
// CHECK: [[DEFAULT_CASE]]({{%.*}} : @trivial $Downgradable):
// CHECK-NEXT: [[METATYPE:%.+]] = value_metatype $@thick Downgradable.Type, {{%.*}} : $Downgradable
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[DIAGNOSE:%.+]] = function_ref @$Ss27_diagnoseUnexpectedEnumCase
// CHECK-NEXT: = apply [[DIAGNOSE]]<Downgradable>([[METATYPE]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Never
// CHECK-NEXT: unreachable
}
// CHECK: switch_enum {{%[0-9]+}} : $Downgradable, case #Downgradable.spoon!enumelt: {{bb[0-9]+}}, case #Downgradable.hat!enumelt: {{bb[0-9]+}}, default [[TUPLE_DEFAULT_CASE_1:bb[0-9]+]]
// CHECK: switch_enum [[Y:%[0-9]+]] : $Downgradable, case #Downgradable.spoon!enumelt: {{bb[0-9]+}}, case #Downgradable.hat!enumelt: {{bb[0-9]+}}, default [[TUPLE_DEFAULT_CASE_2:bb[0-9]+]]
switch (pat!, pat!) {
case (.spoon, .spoon):
break
case (.spoon, .hat):
break
case (.hat, .spoon):
break
case (.hat, .hat):
break
// CHECK: [[TUPLE_DEFAULT_CASE_2]]({{%.*}} : @trivial $Downgradable):
// CHECK-NEXT: [[METATYPE:%.+]] = value_metatype $@thick (Downgradable, Downgradable).Type, {{%.*}} : $(Downgradable, Downgradable)
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[DIAGNOSE:%.+]] = function_ref @$Ss27_diagnoseUnexpectedEnumCase
// CHECK-NEXT: = apply [[DIAGNOSE]]<(Downgradable, Downgradable)>([[METATYPE]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Never
// CHECK-NEXT: unreachable
// CHECK: switch_enum [[Y]] : $Downgradable, case #Downgradable.spoon!enumelt: {{bb[0-9]+}}, case #Downgradable.hat!enumelt: {{bb[0-9]+}}, default [[TUPLE_DEFAULT_CASE_3:bb[0-9]+]]
// CHECK: [[TUPLE_DEFAULT_CASE_3]]({{%.*}} : @trivial $Downgradable):
// CHECK-NEXT: [[METATYPE:%.+]] = value_metatype $@thick (Downgradable, Downgradable).Type, {{%.*}} : $(Downgradable, Downgradable)
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[DIAGNOSE:%.+]] = function_ref @$Ss27_diagnoseUnexpectedEnumCase
// CHECK-NEXT: = apply [[DIAGNOSE]]<(Downgradable, Downgradable)>([[METATYPE]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Never
// CHECK-NEXT: unreachable
// CHECK: [[TUPLE_DEFAULT_CASE_1]]({{%.*}} : @trivial $Downgradable):
// CHECK-NEXT: [[METATYPE:%.+]] = value_metatype $@thick (Downgradable, Downgradable).Type, {{%.*}} : $(Downgradable, Downgradable)
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[DIAGNOSE:%.+]] = function_ref @$Ss27_diagnoseUnexpectedEnumCase
// CHECK-NEXT: = apply [[DIAGNOSE]]<(Downgradable, Downgradable)>([[METATYPE]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Never
// CHECK-NEXT: unreachable
}
}
| 11dfbb0c1405f47b277f46ff6f976181 | 52.1875 | 190 | 0.628085 | false | false | false | false |
Yummypets/YPImagePicker | refs/heads/master | Source/Filters/Video/YPVideoFiltersVC.swift | mit | 1 | //
// VideoFiltersVC.swift
// YPImagePicker
//
// Created by Nik Kov || nik-kov.com on 18.04.2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
import Photos
import PryntTrimmerView
import Stevia
public final class YPVideoFiltersVC: UIViewController, IsMediaFilterVC {
/// Designated initializer
public class func initWith(video: YPMediaVideo,
isFromSelectionVC: Bool) -> YPVideoFiltersVC {
let vc = YPVideoFiltersVC()
vc.inputVideo = video
vc.isFromSelectionVC = isFromSelectionVC
return vc
}
// MARK: - Public vars
public var inputVideo: YPMediaVideo!
public var inputAsset: AVAsset { return AVAsset(url: inputVideo.url) }
public var didSave: ((YPMediaItem) -> Void)?
public var didCancel: (() -> Void)?
// MARK: - Private vars
private var playbackTimeCheckerTimer: Timer?
private var imageGenerator: AVAssetImageGenerator?
private var isFromSelectionVC = false
private let trimmerContainerView: UIView = {
let v = UIView()
return v
}()
private let trimmerView: TrimmerView = {
let v = TrimmerView()
v.mainColor = YPConfig.colors.trimmerMainColor
v.handleColor = YPConfig.colors.trimmerHandleColor
v.positionBarColor = YPConfig.colors.positionLineColor
v.maxDuration = YPConfig.video.trimmerMaxDuration
v.minDuration = YPConfig.video.trimmerMinDuration
return v
}()
private let coverThumbSelectorView: ThumbSelectorView = {
let v = ThumbSelectorView()
v.thumbBorderColor = YPConfig.colors.coverSelectorBorderColor
v.isHidden = true
return v
}()
private lazy var trimBottomItem: YPMenuItem = {
let v = YPMenuItem()
v.textLabel.text = YPConfig.wordings.trim
v.button.addTarget(self, action: #selector(selectTrim), for: .touchUpInside)
return v
}()
private lazy var coverBottomItem: YPMenuItem = {
let v = YPMenuItem()
v.textLabel.text = YPConfig.wordings.cover
v.button.addTarget(self, action: #selector(selectCover), for: .touchUpInside)
return v
}()
private let videoView: YPVideoView = {
let v = YPVideoView()
return v
}()
private let coverImageView: UIImageView = {
let v = UIImageView()
v.contentMode = .scaleAspectFit
v.isHidden = true
return v
}()
// MARK: - Live cycle
override public func viewDidLoad() {
super.viewDidLoad()
setupLayout()
title = YPConfig.wordings.trim
view.backgroundColor = YPConfig.colors.filterBackgroundColor
setupNavigationBar(isFromSelectionVC: self.isFromSelectionVC)
// Remove the default and add a notification to repeat playback from the start
videoView.removeReachEndObserver()
NotificationCenter.default
.addObserver(self,
selector: #selector(itemDidFinishPlaying(_:)),
name: .AVPlayerItemDidPlayToEndTime,
object: videoView.player.currentItem)
// Set initial video cover
imageGenerator = AVAssetImageGenerator(asset: self.inputAsset)
imageGenerator?.appliesPreferredTrackTransform = true
didChangeThumbPosition(CMTime(seconds: 1, preferredTimescale: 1))
}
override public func viewDidAppear(_ animated: Bool) {
trimmerView.asset = inputAsset
trimmerView.delegate = self
coverThumbSelectorView.asset = inputAsset
coverThumbSelectorView.delegate = self
selectTrim()
videoView.loadVideo(inputVideo)
videoView.showPlayImage(show: true)
startPlaybackTimeChecker()
super.viewDidAppear(animated)
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopPlaybackTimeChecker()
videoView.stop()
}
// MARK: - Setup
private func setupNavigationBar(isFromSelectionVC: Bool) {
if isFromSelectionVC {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: YPConfig.wordings.cancel,
style: .plain,
target: self,
action: #selector(cancel))
navigationItem.leftBarButtonItem?.setFont(font: YPConfig.fonts.leftBarButtonFont, forState: .normal)
}
setupRightBarButtonItem()
}
private func setupRightBarButtonItem() {
let rightBarButtonTitle = isFromSelectionVC ? YPConfig.wordings.done : YPConfig.wordings.next
navigationItem.rightBarButtonItem = UIBarButtonItem(title: rightBarButtonTitle,
style: .done,
target: self,
action: #selector(save))
navigationItem.rightBarButtonItem?.tintColor = YPConfig.colors.tintColor
navigationItem.rightBarButtonItem?.setFont(font: YPConfig.fonts.rightBarButtonFont, forState: .normal)
}
private func setupLayout() {
view.subviews(
trimBottomItem,
coverBottomItem,
videoView,
coverImageView,
trimmerContainerView.subviews(
trimmerView,
coverThumbSelectorView
)
)
trimBottomItem.leading(0).height(40)
trimBottomItem.Bottom == view.safeAreaLayoutGuide.Bottom
trimBottomItem.Trailing == coverBottomItem.Leading
coverBottomItem.Bottom == view.safeAreaLayoutGuide.Bottom
coverBottomItem.trailing(0)
equal(sizes: trimBottomItem, coverBottomItem)
videoView.heightEqualsWidth().fillHorizontally().top(0)
videoView.Bottom == trimmerContainerView.Top
coverImageView.followEdges(videoView)
trimmerContainerView.fillHorizontally()
trimmerContainerView.Top == videoView.Bottom
trimmerContainerView.Bottom == trimBottomItem.Top
trimmerView.fillHorizontally(padding: 30).centerVertically()
trimmerView.Height == trimmerContainerView.Height / 3
coverThumbSelectorView.followEdges(trimmerView)
}
// MARK: - Actions
@objc private func save() {
guard let didSave = didSave else {
return ypLog("Don't have saveCallback")
}
navigationItem.rightBarButtonItem = YPLoaders.defaultLoader
do {
let asset = AVURLAsset(url: inputVideo.url)
let trimmedAsset = try asset
.assetByTrimming(startTime: trimmerView.startTime ?? CMTime.zero,
endTime: trimmerView.endTime ?? inputAsset.duration)
// Looks like file:///private/var/mobile/Containers/Data/Application
// /FAD486B4-784D-4397-B00C-AD0EFFB45F52/tmp/8A2B410A-BD34-4E3F-8CB5-A548A946C1F1.mov
let destinationURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingUniquePathComponent(pathExtension: YPConfig.video.fileType.fileExtension)
_ = trimmedAsset.export(to: destinationURL) { [weak self] session in
switch session.status {
case .completed:
DispatchQueue.main.async {
if let coverImage = self?.coverImageView.image {
let resultVideo = YPMediaVideo(thumbnail: coverImage,
videoURL: destinationURL,
asset: self?.inputVideo.asset)
didSave(YPMediaItem.video(v: resultVideo))
self?.setupRightBarButtonItem()
} else {
ypLog("Don't have coverImage.")
}
}
case .failed:
ypLog("Export of the video failed. Reason: \(String(describing: session.error))")
default:
ypLog("Export session completed with \(session.status) status. Not handled")
}
}
} catch let error {
ypLog("Error: \(error)")
}
}
@objc private func cancel() {
didCancel?()
}
// MARK: - Bottom buttons
@objc private func selectTrim() {
title = YPConfig.wordings.trim
trimBottomItem.select()
coverBottomItem.deselect()
trimmerView.isHidden = false
videoView.isHidden = false
coverImageView.isHidden = true
coverThumbSelectorView.isHidden = true
}
@objc private func selectCover() {
title = YPConfig.wordings.cover
trimBottomItem.deselect()
coverBottomItem.select()
trimmerView.isHidden = true
videoView.isHidden = true
coverImageView.isHidden = false
coverThumbSelectorView.isHidden = false
stopPlaybackTimeChecker()
videoView.stop()
}
// MARK: - Various Methods
// Updates the bounds of the cover picker if the video is trimmed
// TODO: Now the trimmer framework doesn't support an easy way to do this.
// Need to rethink a flow or search other ways.
private func updateCoverPickerBounds() {
if let startTime = trimmerView.startTime,
let endTime = trimmerView.endTime {
if let selectedCoverTime = coverThumbSelectorView.selectedTime {
let range = CMTimeRange(start: startTime, end: endTime)
if !range.containsTime(selectedCoverTime) {
// If the selected before cover range is not in new trimeed range,
// than reset the cover to start time of the trimmed video
}
} else {
// If none cover time selected yet, than set the cover to the start time of the trimmed video
}
}
}
// MARK: - Trimmer playback
@objc private func itemDidFinishPlaying(_ notification: Notification) {
if let startTime = trimmerView.startTime {
videoView.player.seek(to: startTime)
}
}
private func startPlaybackTimeChecker() {
stopPlaybackTimeChecker()
playbackTimeCheckerTimer = Timer
.scheduledTimer(timeInterval: 0.05, target: self,
selector: #selector(onPlaybackTimeChecker),
userInfo: nil,
repeats: true)
}
private func stopPlaybackTimeChecker() {
playbackTimeCheckerTimer?.invalidate()
playbackTimeCheckerTimer = nil
}
@objc private func onPlaybackTimeChecker() {
guard let startTime = trimmerView.startTime,
let endTime = trimmerView.endTime else {
return
}
let playBackTime = videoView.player.currentTime()
trimmerView.seek(to: playBackTime)
if playBackTime >= endTime {
videoView.player.seek(to: startTime,
toleranceBefore: CMTime.zero,
toleranceAfter: CMTime.zero)
trimmerView.seek(to: startTime)
}
}
}
// MARK: - TrimmerViewDelegate
extension YPVideoFiltersVC: TrimmerViewDelegate {
public func positionBarStoppedMoving(_ playerTime: CMTime) {
videoView.player.seek(to: playerTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
videoView.play()
startPlaybackTimeChecker()
updateCoverPickerBounds()
}
public func didChangePositionBar(_ playerTime: CMTime) {
stopPlaybackTimeChecker()
videoView.pause()
videoView.player.seek(to: playerTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
}
}
// MARK: - ThumbSelectorViewDelegate
extension YPVideoFiltersVC: ThumbSelectorViewDelegate {
public func didChangeThumbPosition(_ imageTime: CMTime) {
if let imageGenerator = imageGenerator,
let imageRef = try? imageGenerator.copyCGImage(at: imageTime, actualTime: nil) {
coverImageView.image = UIImage(cgImage: imageRef)
}
}
}
| 4a28f96c2aaa990570c2838be1155f9f | 35.188406 | 112 | 0.605046 | false | true | false | false |
giangbvnbgit128/AnViet | refs/heads/master | AnViet/Class/Models/NewsItem.swift | apache-2.0 | 1 | //
// NewsItem.swift
// AnViet
//
// Created by Bui Giang on 6/6/17.
// Copyright © 2017 Bui Giang. All rights reserved.
//
import Foundation
import ObjectMapper
class NewsItem: Mappable {
var error:String = "FALSE"
var host:String = ""
var message:String = ""
var data:[DataForItem] = []
init() {}
required init(map: Map) {
}
func mapping(map: Map) {
error <- map["error"]
host <- map["host"]
message <- map["mess"]
data <- map["data"]
}
}
class DataForItem: Mappable {
var post:PostOfData = PostOfData()
var user:UserNewsPost = UserNewsPost()
init() {}
required init(map: Map) {
}
func mapping(map: Map) {
post <- map["Post"]
user <- map["User"]
}
}
class PostOfData: Mappable {
var id:String = ""
var title:String = ""
var avatar:String = ""
var userId:String = ""
var content:String = ""
private var strImage:String = ""
var image:[ImageItem] = []
var userLike:String = ""
var userView:String = ""
var activate:String = "0"
var status:String = "0"
var createdDate:String = "2017"
init() {}
required init(map: Map) {
}
func mapping(map: Map) {
id <- map["id"]
title <- map["title"]
avatar <- map["avatar"]
userId <- map["user_id"]
content <- map["content"]
strImage <- map["image"]
userLike <- map["user_like"]
userView <- map["user_view"]
activate <- map["active"]
status <- map["status"]
createdDate <- map["created_date"]
image = self.getArrayLinkImage(strListImage: strImage)
}
func getArrayLinkImage(strListImage: String) -> [ImageItem] {
var arrayImage:[ImageItem] = []
let data: Data? = strListImage.data(using: String.Encoding.utf8)
guard data != nil else {
return []
}
let json = try? JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? [String : AnyObject]
guard json != nil else {
return []
}
for item in json!! {
print(item.value)
print(item.key)
let itemImage:ImageItem = ImageItem(id: item.key, urlImage: item.value as! String)
arrayImage.append(itemImage)
}
return arrayImage
}
}
class UserNewsPost: Mappable {
var id:String = ""
var username:String = ""
var avartar:String = ""
init() {}
required init(map: Map) {
}
func mapping(map: Map) {
id <- map["id"]
username <- map["username"]
avartar <- map["avatar"]
}
}
class ImageItem: AnyObject {
var id:String = ""
var urlImage = ""
init() {
}
init(id:String , urlImage:String) {
self.id = id
self.urlImage = urlImage
}
}
| b0de7c539771145b7268b49b5816b64f | 20.232394 | 115 | 0.519403 | false | false | false | false |
grandiere/box | refs/heads/master | box/View/GridHarvest/VGridHarvestBarCollect.swift | mit | 1 | import UIKit
class VGridHarvestBarCollect:UIButton
{
private weak var controller:CGridHarvest!
private weak var labelScore:UILabel!
private weak var labelKills:UILabel!
private weak var labelGet:UILabel!
private weak var viewGet:UIView!
private let kLabelsHeight:CGFloat = 26
private let kTitlesHeigth:CGFloat = 18
private let KBorderWidth:CGFloat = 1
private let kCornerRadius:CGFloat = 6
private let kGetWidth:CGFloat = 50
private let kScoreMultiplier:CGFloat = 0.6
private let kKillsMultiplier:CGFloat = 0.4
init(controller:CGridHarvest)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
layer.cornerRadius = kCornerRadius
layer.borderWidth = KBorderWidth
isUserInteractionEnabled = false
addTarget(
self,
action:#selector(actionCollect(sender:)),
for:UIControlEvents.touchUpInside)
self.controller = controller
let viewGet:UIView = UIView()
viewGet.translatesAutoresizingMaskIntoConstraints = false
viewGet.isUserInteractionEnabled = false
viewGet.clipsToBounds = true
self.viewGet = viewGet
let viewLabels:UIView = UIView()
viewLabels.isUserInteractionEnabled = false
viewLabels.translatesAutoresizingMaskIntoConstraints = false
viewLabels.clipsToBounds = true
viewLabels.backgroundColor = UIColor.clear
let labelGet:UILabel = UILabel()
labelGet.isUserInteractionEnabled = false
labelGet.backgroundColor = UIColor.clear
labelGet.translatesAutoresizingMaskIntoConstraints = false
labelGet.textAlignment = NSTextAlignment.center
labelGet.font = UIFont.bold(size:14)
labelGet.text = NSLocalizedString("VGridHarvestBarCollect_labelGet", comment:"")
self.labelGet = labelGet
let labelScore:UILabel = UILabel()
labelScore.translatesAutoresizingMaskIntoConstraints = false
labelScore.isUserInteractionEnabled = false
labelScore.backgroundColor = UIColor.clear
labelScore.textAlignment = NSTextAlignment.center
labelScore.font = UIFont.numeric(size:15)
self.labelScore = labelScore
let labelKills:UILabel = UILabel()
labelKills.translatesAutoresizingMaskIntoConstraints = false
labelKills.isUserInteractionEnabled = false
labelKills.backgroundColor = UIColor.clear
labelKills.textAlignment = NSTextAlignment.center
labelKills.font = UIFont.numeric(size:15)
self.labelKills = labelKills
let labelScoreTitle:UILabel = UILabel()
labelScoreTitle.isUserInteractionEnabled = false
labelScoreTitle.translatesAutoresizingMaskIntoConstraints = false
labelScoreTitle.backgroundColor = UIColor.clear
labelScoreTitle.textAlignment = NSTextAlignment.center
labelScoreTitle.font = UIFont.regular(size:10)
labelScoreTitle.textColor = UIColor.white
labelScoreTitle.text = NSLocalizedString("VGridHarvestBarCollect_labelScoreTitle", comment:"")
let labelKillsTitle:UILabel = UILabel()
labelKillsTitle.isUserInteractionEnabled = false
labelKillsTitle.translatesAutoresizingMaskIntoConstraints = false
labelKillsTitle.backgroundColor = UIColor.clear
labelKillsTitle.textAlignment = NSTextAlignment.center
labelKillsTitle.font = UIFont.regular(size:10)
labelKillsTitle.textColor = UIColor.white
labelKillsTitle.text = NSLocalizedString("VGridHarvestBarCollect_labelKillsTitle", comment:"")
viewGet.addSubview(labelGet)
viewLabels.addSubview(labelScore)
viewLabels.addSubview(labelKills)
viewLabels.addSubview(labelScoreTitle)
viewLabels.addSubview(labelKillsTitle)
addSubview(viewLabels)
addSubview(viewGet)
NSLayoutConstraint.equals(
view:labelGet,
toView:viewGet)
NSLayoutConstraint.equalsVertical(
view:viewLabels,
toView:self)
NSLayoutConstraint.rightToLeft(
view:viewLabels,
toView:viewGet)
NSLayoutConstraint.leftToLeft(
view:viewLabels,
toView:self)
NSLayoutConstraint.equalsVertical(
view:viewGet,
toView:self)
NSLayoutConstraint.rightToRight(
view:viewGet,
toView:self)
NSLayoutConstraint.width(
view:viewGet,
constant:kGetWidth)
NSLayoutConstraint.topToTop(
view:labelScore,
toView:viewLabels)
NSLayoutConstraint.height(
view:labelScore,
constant:kLabelsHeight)
NSLayoutConstraint.width(
view:labelScore,
toView:viewLabels,
multiplier:kScoreMultiplier)
NSLayoutConstraint.rightToRight(
view:labelScore,
toView:viewLabels)
NSLayoutConstraint.topToTop(
view:labelKills,
toView:viewLabels)
NSLayoutConstraint.height(
view:labelKills,
constant:kLabelsHeight)
NSLayoutConstraint.leftToLeft(
view:labelKills,
toView:viewLabels)
NSLayoutConstraint.width(
view:labelKills,
toView:viewLabels,
multiplier:kKillsMultiplier)
NSLayoutConstraint.bottomToBottom(
view:labelScoreTitle,
toView:viewLabels)
NSLayoutConstraint.height(
view:labelScoreTitle,
constant:kTitlesHeigth)
NSLayoutConstraint.equalsHorizontal(
view:labelScore,
toView:labelScoreTitle)
NSLayoutConstraint.bottomToBottom(
view:labelKillsTitle,
toView:viewLabels)
NSLayoutConstraint.height(
view:labelKillsTitle,
constant:kTitlesHeigth)
NSLayoutConstraint.equalsHorizontal(
view:labelKillsTitle,
toView:labelKills)
hover()
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: actions
func actionCollect(sender button:UIButton)
{
button.isUserInteractionEnabled = false
controller.collect()
}
//MARK: private
private func hover()
{
if isUserInteractionEnabled
{
if isSelected || isHighlighted
{
layer.borderColor = UIColor.gridOrange.cgColor
viewGet.backgroundColor = UIColor.gridOrange
labelGet.textColor = UIColor.white
labelScore.textColor = UIColor.gridOrange
labelKills.textColor = UIColor.gridOrange
}
else
{
layer.borderColor = UIColor.gridBlue.cgColor
viewGet.backgroundColor = UIColor.gridBlue
labelGet.textColor = UIColor.black
labelScore.textColor = UIColor.white
labelKills.textColor = UIColor.white
}
}
else
{
layer.borderColor = UIColor(white:1, alpha:0.2).cgColor
viewGet.backgroundColor = UIColor(white:1, alpha:0.2)
labelGet.textColor = UIColor(white:1, alpha:0.4)
labelScore.textColor = UIColor(white:1, alpha:0.4)
labelKills.textColor = UIColor(white:1, alpha:0.4)
}
}
//MARK: public
func displayHarvest()
{
labelScore.text = "\(controller.model.harvestScore)"
labelKills.text = "\(controller.model.harvestKills)"
if controller.model.harvestScore > 0
{
isUserInteractionEnabled = true
}
else
{
isUserInteractionEnabled = false
}
hover()
}
}
| 74225d66144996e41215be54b1feb69a | 32.167331 | 102 | 0.624144 | false | false | false | false |
netyouli/SexyJson | refs/heads/master | SexyJsonKit/SexyJsonOperation.swift | mit | 1 | //
// SexyJsonOperation.swift
// SexyJson
//
// Created by WHC on 17/5/14.
// Copyright © 2017年 WHC. All rights reserved.
//
// Github <https://github.com/netyouli/SexyJson>
// 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
infix operator <<<
//MARK: - SexyJsonBasicType -
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
public func <<< <T: _SexyJsonBasicType>(left: inout T!, right: Any?) -> Void {
left = T.sexyTransform(right)
}
#endif
public func <<< <T: _SexyJsonBasicType>(left: inout T?, right: Any?) -> Void {
left = T.sexyTransform(right)
}
public func <<< <T: _SexyJsonBasicType>(left: inout T, right: Any?) -> Void {
if let value = T.sexyTransform(right) {
left = value
}
}
//MARK: - SexyJsonEnumType -
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
public func <<< <T: SexyJsonEnumType> (left: inout T!, right: Any?) -> Void {
left = T.sexyTransform(right)
}
#endif
public func <<< <T: SexyJsonEnumType>(left: inout T?, right: Any?) -> Void {
left = T.sexyTransform(right)
}
public func <<< <T: SexyJsonEnumType>(left: inout T, right: Any?) -> Void {
if let value = T.sexyTransform(right) {
left = value
}
}
//MARK: - SexyJsonObjectType -
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
public func <<< <T: SexyJsonObjectType>(left: inout T!, right: Any?) -> Void {
left = T._sexyTransform(right) as? T
}
#endif
public func <<< <T: SexyJsonObjectType>(left: inout T?, right: Any?) -> Void {
left = T._sexyTransform(right) as? T
}
public func <<< <T: SexyJsonObjectType>(left: inout T, right: Any?) -> Void {
if let value = T._sexyTransform(right) as? T {
left = value
}
}
//MARK: - SexyJson -
public func <<< <T: SexyJson>(left: inout T?, right: Any?) -> Void {
if let rightMap = right as? [String: Any] {
left = T.init()
left!.sexyMap(rightMap)
}
}
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
public func <<< <T: SexyJson>(left: inout T!, right: Any?) -> Void {
if let rightMap = right as? [String: Any] {
left = T.init()
left.sexyMap(rightMap)
}
}
#endif
public func <<< <T: SexyJson>(left: inout T, right: Any?) -> Void {
if let rightMap = right as? [String: Any] {
left.sexyMap(rightMap)
}
}
//MARK: - [SexyJsonBasicType] -
public func <<< <T: _SexyJsonBasicType>(left: inout [T]?, right: Any?) -> Void {
if right != nil {
left = [T].init()
left! <<< right
}
}
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
public func <<< <T: _SexyJsonBasicType>(left: inout [T]!, right: Any?) -> Void {
if right != nil {
left = [T].init()
left! <<< right
}
}
#endif
public func <<< <T: _SexyJsonBasicType>(left: inout [T], right: Any?) -> Void {
if let rightMap = right as? [Any] {
rightMap.forEach({ (map) in
left.append(T.sexyTransform(map)!)
})
}
}
//MARK: - [SexyJsonEnumType] -
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
public func <<< <T: SexyJsonEnumType> (left: inout [T]!, right: Any?) -> Void {
if right != nil {
left = [T].init()
left! <<< right
}
}
#endif
public func <<< <T: SexyJsonEnumType>(left: inout [T]?, right: Any?) -> Void {
if right != nil {
left = [T].init()
left! <<< right
}
}
public func <<< <T: SexyJsonEnumType>(left: inout [T], right: Any?) -> Void {
if let rightMap = right as? [Any] {
rightMap.forEach({ (map) in
left.append(T.sexyTransform(map)!)
})
}
}
//MARK: - [SexyJsonObjectType] -
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
public func <<< <T: SexyJsonObjectType>(left: inout [T]!, right: Any?) -> Void {
if right != nil {
left = [T].init()
left! <<< right
}
}
#endif
public func <<< <T: SexyJsonObjectType>(left: inout [T]?, right: Any?) -> Void {
if right != nil {
left = [T].init()
left! <<< right
}
}
public func <<< <T: SexyJsonObjectType>(left: inout [T], right: Any?) -> Void {
if let rightMap = right as? [Any] {
rightMap.forEach({ (map) in
if let value = T._sexyTransform(map) as? T {
left.append(value)
}
})
}
}
//MARK: - [SexyJson] -
public func <<< <T: SexyJson>(left: inout [T]?, right: Any?) -> Void {
if right != nil {
left = [T].init()
left! <<< right
}
}
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
public func <<< <T: SexyJson>(left: inout [T]!, right: Any?) -> Void {
if right != nil {
left = [T].init()
left! <<< right
}
}
#endif
public func <<< <T: SexyJson>(left: inout [T], right: Any?) -> Void {
if let rightMap = right as? [Any] {
rightMap.forEach({ (map) in
if let elementMap = map as? [String : Any] {
var element = T.init()
element.sexyMap(elementMap)
left.append(element)
}
})
}
}
| 720780e941a0fb48064985ed0687f692 | 26.7 | 80 | 0.576469 | false | false | false | false |
CODE4APPLE/PKHUD | refs/heads/master | Demo/DemoViewController.swift | mit | 2 | //
// DemoViewController.swift
// PKHUD Demo
//
// Created by Philip Kluz on 6/18/14.
// Copyright (c) 2014 NSExceptional. All rights reserved.
//
import UIKit
import PKHUD
class DemoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
PKHUD.sharedHUD.dimsBackground = false
PKHUD.sharedHUD.userInteractionOnUnderlyingViewsEnabled = false
}
@IBAction func showAnimatedSuccessHUD(sender: AnyObject) {
PKHUD.sharedHUD.contentView = PKHUDSuccessView()
PKHUD.sharedHUD.show()
PKHUD.sharedHUD.hide(afterDelay: 2.0);
}
@IBAction func showAnimatedErrorHUD(sender: AnyObject) {
PKHUD.sharedHUD.contentView = PKHUDErrorView()
PKHUD.sharedHUD.show()
PKHUD.sharedHUD.hide(afterDelay: 2.0);
}
@IBAction func showAnimatedProgressHUD(sender: AnyObject) {
PKHUD.sharedHUD.contentView = PKHUDProgressView()
PKHUD.sharedHUD.show()
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
PKHUD.sharedHUD.contentView = PKHUDSuccessView()
PKHUD.sharedHUD.hide(afterDelay: 2.0)
}
}
@IBAction func showTextHUD(sender: AnyObject) {
PKHUD.sharedHUD.contentView = PKHUDTextView(text: "Requesting Licence…")
PKHUD.sharedHUD.show()
PKHUD.sharedHUD.hide(afterDelay: 2.0)
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.AllButUpsideDown;
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
| fd0b5302a69451e8b84080dc9d26d41d | 30.392857 | 91 | 0.671217 | false | false | false | false |
vsubrahmanian/iRemind | refs/heads/master | iRemind/ReminderInfoModel.swift | apache-2.0 | 2 | //
// ReminderInfoModel.swift
// iRemind
//
// Created by Vijay Subrahmanian on 03/06/15.
// Copyright (c) 2015 Vijay Subrahmanian. All rights reserved.
//
import Foundation
class ReminderInfoModel: NSObject, NSCoding {
var name = ""
var details = ""
var time: NSDate?
override init() {
super.init()
}
required convenience init(coder aDecoder: NSCoder) {
self.init()
self.name = aDecoder.decodeObjectForKey("nameKey") as! String
self.details = aDecoder.decodeObjectForKey("detailsKey") as! String
self.time = aDecoder.decodeObjectForKey("timeKey") as? NSDate
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.name, forKey: "nameKey")
aCoder.encodeObject(self.details, forKey: "detailsKey")
aCoder.encodeObject(self.time, forKey: "timeKey")
}
} | 5ac761ab2e9415dbe21aa5b60bf9164d | 25.757576 | 75 | 0.651927 | false | false | false | false |
wireapp/wire-ios-sync-engine | refs/heads/develop | Tests/Source/Synchronization/Strategies/UserImageAssetUpdateStrategyTests.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import XCTest
@testable import WireSyncEngine
typealias ProfileImageSize = WireSyncEngine.ProfileImageSize
class MockImageUpdateStatus: WireSyncEngine.UserProfileImageUploadStatusProtocol {
var allSizes: [ProfileImageSize] { return [.preview, .complete] }
var assetIdsToDelete = Set<String>()
func hasAssetToDelete() -> Bool {
return !assetIdsToDelete.isEmpty
}
func consumeAssetToDelete() -> String? {
return assetIdsToDelete.removeFirst()
}
var dataToConsume = [ProfileImageSize: Data]()
func consumeImage(for size: ProfileImageSize) -> Data? {
return dataToConsume[size]
}
func hasImageToUpload(for size: ProfileImageSize) -> Bool {
return dataToConsume[size] != nil
}
var uploadDoneForSize: ProfileImageSize?
var uploadDoneWithAssetId: String?
func uploadingDone(imageSize: ProfileImageSize, assetId: String) {
uploadDoneForSize = imageSize
uploadDoneWithAssetId = assetId
}
var uploadFailedForSize: ProfileImageSize?
var uploadFailedWithError: Error?
func uploadingFailed(imageSize: ProfileImageSize, error: Error) {
uploadFailedForSize = imageSize
uploadFailedWithError = error
}
}
class UserImageAssetUpdateStrategyTests: MessagingTest {
var sut: WireSyncEngine.UserImageAssetUpdateStrategy!
var mockApplicationStatus: MockApplicationStatus!
var updateStatus: MockImageUpdateStatus!
override func setUp() {
super.setUp()
self.mockApplicationStatus = MockApplicationStatus()
self.mockApplicationStatus.mockSynchronizationState = .online
self.updateStatus = MockImageUpdateStatus()
sut = UserImageAssetUpdateStrategy(managedObjectContext: syncMOC,
applicationStatus: mockApplicationStatus,
imageUploadStatus: updateStatus)
self.syncMOC.zm_userImageCache = UserImageLocalCache(location: nil)
self.uiMOC.zm_userImageCache = self.syncMOC.zm_userImageCache
}
override func tearDown() {
self.mockApplicationStatus = nil
self.updateStatus = nil
self.sut = nil
self.syncMOC.zm_userImageCache = nil
BackendInfo.domain = nil
super.tearDown()
}
}
// MARK: - Profile image upload
extension UserImageAssetUpdateStrategyTests {
func testThatItDoesNotReturnARequestWhenThereIsNoImageToUpload() {
// WHEN
updateStatus.dataToConsume.removeAll()
// THEN
XCTAssertNil(sut.nextRequest(for: .v0))
}
func testThatItDoesNotReturnARequestWhenUserIsNotLoggedIn() {
// WHEN
updateStatus.dataToConsume[.preview] = Data()
updateStatus.dataToConsume[.complete] = Data()
mockApplicationStatus.mockSynchronizationState = .unauthenticated
// THEN
XCTAssertNil(sut.nextRequest(for: .v0))
}
func testThatItCreatesRequestSyncs() {
XCTAssertNotNil(sut.upstreamRequestSyncs[.preview])
XCTAssertNotNil(sut.upstreamRequestSyncs[.complete])
}
func testThatItReturnsCorrectSizeFromRequestSync() {
// WHEN
let previewSync = sut.upstreamRequestSyncs[.preview]!
let completeSync = sut.upstreamRequestSyncs[.complete]!
// THEN
XCTAssertEqual(sut.size(for: previewSync), .preview)
XCTAssertEqual(sut.size(for: completeSync), .complete)
}
func testThatItCreatesRequestWhenThereIsData() {
// WHEN
updateStatus.dataToConsume.removeAll()
updateStatus.dataToConsume[.preview] = "Some".data(using: .utf8)
// THEN
let previewRequest = sut.nextRequest(for: .v0)
XCTAssertNotNil(previewRequest)
XCTAssertEqual(previewRequest?.path, "/assets/v3")
XCTAssertEqual(previewRequest?.method, .methodPOST)
// WHEN
updateStatus.dataToConsume.removeAll()
updateStatus.dataToConsume[.complete] = "Other".data(using: .utf8)
// THEN
let completeRequest = sut.nextRequest(for: .v0)
XCTAssertNotNil(completeRequest)
XCTAssertEqual(completeRequest?.path, "/assets/v3")
XCTAssertEqual(completeRequest?.method, .methodPOST)
}
func testThatItCreatesRequestWithExpectedData() {
// GIVEN
let previewData = "--1--".data(using: .utf8)
let previewRequest = sut.requestFactory.upstreamRequestForAsset(withData: previewData!, shareable: true, retention: .eternal, apiVersion: .v0)
let completeData = "1111111".data(using: .utf8)
let completeRequest = sut.requestFactory.upstreamRequestForAsset(withData: completeData!, shareable: true, retention: .eternal, apiVersion: .v0)
// WHEN
updateStatus.dataToConsume.removeAll()
updateStatus.dataToConsume[.preview] = previewData
// THEN
XCTAssertEqual(sut.nextRequest(for: .v0)?.binaryData, previewRequest?.binaryData)
// WHEN
updateStatus.dataToConsume.removeAll()
updateStatus.dataToConsume[.complete] = completeData
// THEN
XCTAssertEqual(sut.nextRequest(for: .v0)?.binaryData, completeRequest?.binaryData)
}
func testThatItCreatesDeleteRequestIfThereAreAssetsToDelete() {
// GIVEN
let assetId = "12344"
let deleteRequest = ZMTransportRequest(path: "/assets/v3/\(assetId)", method: .methodDELETE, payload: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
updateStatus.assetIdsToDelete = [assetId]
// THEN
XCTAssertEqual(sut.nextRequest(for: .v0), deleteRequest)
XCTAssert(updateStatus.assetIdsToDelete.isEmpty)
}
func testThatUploadMarkedAsFailedOnUnsuccessfulResponse() {
// GIVEN
let size = ProfileImageSize.preview
let sync = sut.upstreamRequestSyncs[size]
let failedResponse = ZMTransportResponse(payload: nil, httpStatus: 500, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
sut.didReceive(failedResponse, forSingleRequest: sync!)
// THEN
XCTAssertEqual(updateStatus.uploadFailedForSize, size)
}
func testThatUploadIsMarkedAsDoneAfterSuccessfulResponse() {
// GIVEN
let size = ProfileImageSize.preview
let sync = sut.upstreamRequestSyncs[size]
let assetId = "123123"
let payload: [String: String] = ["key": assetId]
let successResponse = ZMTransportResponse(payload: payload as NSDictionary, httpStatus: 200, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
sut.didReceive(successResponse, forSingleRequest: sync!)
// THEN
XCTAssertEqual(updateStatus.uploadDoneForSize, size)
XCTAssertEqual(updateStatus.uploadDoneWithAssetId, assetId)
}
}
// MARK: - Profile image download
extension UserImageAssetUpdateStrategyTests {
func testThatItCreatesDownstreamRequestSyncs() {
XCTAssertNotNil(sut.downstreamRequestSyncs[.preview])
XCTAssertNotNil(sut.downstreamRequestSyncs[.complete])
}
func testThatItReturnsCorrectSizeFromDownstreamRequestSync() {
// WHEN
let previewSync = sut.downstreamRequestSyncs[.preview]!
let completeSync = sut.downstreamRequestSyncs[.complete]!
// THEN
XCTAssertEqual(sut.size(for: previewSync), .preview)
XCTAssertEqual(sut.size(for: completeSync), .complete)
}
func testThatItWhitelistsUserOnPreviewSyncForPreviewImageNotification() {
// GIVEN
let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC)
user.previewProfileAssetIdentifier = "fooo"
let sync = self.sut.downstreamRequestSyncs[.preview]!
XCTAssertFalse(sync.hasOutstandingItems)
syncMOC.saveOrRollback()
// WHEN
uiMOC.performGroupedBlock {
(self.uiMOC.object(with: user.objectID) as? ZMUser)?.requestPreviewProfileImage()
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
XCTAssertTrue(sync.hasOutstandingItems)
}
func testThatItWhitelistsUserOnPreviewSyncForCompleteImageNotification() {
// GIVEN
let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC)
user.completeProfileAssetIdentifier = "fooo"
let sync = self.sut.downstreamRequestSyncs[.complete]!
XCTAssertFalse(sync.hasOutstandingItems)
syncMOC.saveOrRollback()
// WHEN
uiMOC.performGroupedBlock {
(self.uiMOC.object(with: user.objectID) as? ZMUser)?.requestCompleteProfileImage()
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
XCTAssertTrue(sync.hasOutstandingItems)
}
func testThatItCreatesRequestForCorrectAssetIdentifier(for size: ProfileImageSize, apiVersion: APIVersion) {
// GIVEN
let domain = "example.domain.com"
BackendInfo.domain = domain
let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC)
let assetId = "foo-bar"
switch size {
case .preview:
user.previewProfileAssetIdentifier = assetId
case .complete:
user.completeProfileAssetIdentifier = assetId
}
syncMOC.saveOrRollback()
// WHEN
uiMOC.performGroupedBlock {
let user = self.uiMOC.object(with: user.objectID) as? ZMUser
switch size {
case .preview:
user?.requestPreviewProfileImage()
case .complete:
user?.requestCompleteProfileImage()
}
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
let expectedPath: String
switch apiVersion {
case .v0:
expectedPath = "/assets/v3/\(assetId)"
case .v1:
expectedPath = "/v1/assets/v4/\(domain)/\(assetId)"
case .v2:
expectedPath = "/v2/assets/\(domain)/\(assetId)"
}
let request = self.sut.downstreamRequestSyncs[size]?.nextRequest(for: apiVersion)
XCTAssertNotNil(request)
XCTAssertEqual(request?.path, expectedPath)
XCTAssertEqual(request?.method, .methodGET)
}
func testThatItCreatesRequestForCorrectAssetIdentifierForPreviewImage() {
testThatItCreatesRequestForCorrectAssetIdentifier(for: .preview, apiVersion: .v0)
testThatItCreatesRequestForCorrectAssetIdentifier(for: .preview, apiVersion: .v1)
testThatItCreatesRequestForCorrectAssetIdentifier(for: .preview, apiVersion: .v2)
}
func testThatItCreatesRequestForCorrectAssetIdentifierForCompleteImage() {
testThatItCreatesRequestForCorrectAssetIdentifier(for: .complete, apiVersion: .v0)
testThatItCreatesRequestForCorrectAssetIdentifier(for: .complete, apiVersion: .v1)
testThatItCreatesRequestForCorrectAssetIdentifier(for: .complete, apiVersion: .v2)
}
func testThatItUpdatesCorrectUserImageDataForPreviewImage() {
// GIVEN
let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC)
let imageData = "image".data(using: .utf8)!
let sync = self.sut.downstreamRequestSyncs[.preview]!
user.previewProfileAssetIdentifier = "foo"
let response = ZMTransportResponse(imageData: imageData, httpStatus: 200, transportSessionError: nil, headers: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
self.sut.update(user, with: response, downstreamSync: sync)
// THEN
XCTAssertEqual(user.imageSmallProfileData, imageData)
}
func testThatItUpdatesCorrectUserImageDataForCompleteImage() {
// GIVEN
let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC)
let imageData = "image".data(using: .utf8)!
let sync = self.sut.downstreamRequestSyncs[.complete]!
user.completeProfileAssetIdentifier = "foo"
let response = ZMTransportResponse(imageData: imageData, httpStatus: 200, transportSessionError: nil, headers: nil, apiVersion: APIVersion.v0.rawValue)
// WHEN
self.sut.update(user, with: response, downstreamSync: sync)
// THEN
XCTAssertEqual(user.imageMediumData, imageData)
}
func testThatItDeletesPreviewProfileAssetIdentifierWhenReceivingAPermanentErrorForPreviewImage() {
// Given
let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC)
let assetId = UUID.create().transportString()
user.previewProfileAssetIdentifier = assetId
syncMOC.saveOrRollback()
// When
uiMOC.performGroupedBlock {
(self.uiMOC.object(with: user.objectID) as? ZMUser)?.requestPreviewProfileImage()
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
guard let request = sut.nextRequestIfAllowed(for: .v0) else { return XCTFail("nil request generated") }
XCTAssertEqual(request.path, "/assets/v3/\(assetId)")
XCTAssertEqual(request.method, .methodGET)
// Given
let response = ZMTransportResponse(payload: nil, httpStatus: 404, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
request.complete(with: response)
// THEN
user.requestPreviewProfileImage()
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
XCTAssertNil(user.previewProfileAssetIdentifier)
XCTAssertNil(sut.nextRequestIfAllowed(for: .v0))
}
func testThatItDeletesCompleteProfileAssetIdentifierWhenReceivingAPermanentErrorForCompleteImage() {
// Given
let user = ZMUser.fetchOrCreate(with: UUID.create(), domain: nil, in: self.syncMOC)
let assetId = UUID.create().transportString()
user.completeProfileAssetIdentifier = assetId
syncMOC.saveOrRollback()
// When
uiMOC.performGroupedBlock {
(self.uiMOC.object(with: user.objectID) as? ZMUser)?.requestCompleteProfileImage()
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
guard let request = sut.nextRequestIfAllowed(for: .v0) else { return XCTFail("nil request generated") }
XCTAssertEqual(request.path, "/assets/v3/\(assetId)")
XCTAssertEqual(request.method, .methodGET)
// Given
let response = ZMTransportResponse(payload: nil, httpStatus: 404, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
request.complete(with: response)
// THEN
user.requestCompleteProfileImage()
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
XCTAssertNil(user.completeProfileAssetIdentifier)
XCTAssertNil(sut.nextRequestIfAllowed(for: .v0))
}
}
| cc172d8f9f93e5e88c1a5d33c6fa5c3e | 36.924574 | 164 | 0.685251 | false | true | false | false |
NickEntin/SimPermissions | refs/heads/master | Pods/SwiftFSWatcher/src/SwiftFSWatcher/SwiftFSWatcher/SwiftFSWatcher.swift | mit | 1 | //
// SwiftFSWatcher.swift
// SwiftFSWatcher
//
// Created by Gurinder Hans on 4/9/16.
// Copyright © 2016 Gurinder Hans. All rights reserved.
//
@objc public class SwiftFSWatcher : NSObject {
var isRunning = false
var stream: FSEventStreamRef?
var onChangeCallback: ([FileEvent] -> Void)?
public var watchingPaths: [String]?
// MARK: - Init methods
public override init() {
// Default init
super.init()
}
public convenience init(_ paths: [String]) {
self.init()
self.watchingPaths = paths
}
// MARK: - API public methods
public func watch(changeCb: ([FileEvent] -> Void)?) {
guard let paths = watchingPaths else {
return
}
guard stream == nil else {
return
}
onChangeCallback = changeCb
var context = FSEventStreamContext(version: 0, info: UnsafeMutablePointer<Void>(unsafeAddressOf(self)), retain: nil, release: nil, copyDescription: nil)
stream = FSEventStreamCreate(kCFAllocatorDefault, innerEventCallback, &context, paths, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 0, UInt32(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents))
FSEventStreamScheduleWithRunLoop(stream!, NSRunLoop.currentRunLoop().getCFRunLoop(), kCFRunLoopDefaultMode)
FSEventStreamStart(stream!)
isRunning = true
}
public func resume() {
guard stream != nil else {
return
}
FSEventStreamStart(stream!)
}
public func pause() {
guard stream != nil else {
return
}
FSEventStreamStop(stream!)
}
// MARK: - [Private] Closure passed into `FSEventStream` and is called on new file event
private let innerEventCallback: FSEventStreamCallback = { (stream: ConstFSEventStreamRef, contextInfo: UnsafeMutablePointer<Void>, numEvents: Int, eventPaths: UnsafeMutablePointer<Void>, eventFlags: UnsafePointer<FSEventStreamEventFlags>, eventIds: UnsafePointer<FSEventStreamEventId>) in
let fsWatcher: SwiftFSWatcher = unsafeBitCast(contextInfo, SwiftFSWatcher.self)
let paths = unsafeBitCast(eventPaths, NSArray.self) as! [String]
var fileEvents = [FileEvent]()
for i in 0..<numEvents {
let event = FileEvent(path: paths[i], flag: eventFlags[i], id: eventIds[i])
fileEvents.append(event)
}
fsWatcher.onChangeCallback?(fileEvents)
}
}
@objc public class FileEvent : NSObject {
public var eventPath: String!
public var eventFlag: NSNumber!
public var eventId: NSNumber!
public init(path: String!, flag: UInt32!, id: UInt64!) {
eventPath = path
eventFlag = NSNumber(unsignedInt: flag)
eventId = NSNumber(unsignedLongLong: id)
}
} | cff30cde8e86824e372c0ca4675d0468 | 28.317308 | 292 | 0.614173 | false | false | false | false |
henriquecfreitas/diretop | refs/heads/master | Diretop/SimpleDataSource.swift | gpl-3.0 | 1 | //
// SimpleDataSource.swift
// Diretop
//
// Created by Henrique on 22/04/17.
// Copyright © 2017 Henrique. All rights reserved.
//
import UIKit
class SimpleDataSource: NSObject {
var data = Array<String>()
public func addItenToDts(iten: String){
data.append(iten)
}
public func removeItenFromDts(index: Int){
data.remove(at: index)
}
public func setData(dataToSet: Array<String>){
data = dataToSet
}
}
class SimpleTableViewDataSource: SimpleDataSource, UITableViewDataSource {
var tableKey: String!
init(tableKey: String) {
super.init()
self.tableKey = tableKey
self.setData(dataToSet: getPersistedData())
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let index = indexPath.item
cell.textLabel?.text = data[index]
return cell
}
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCellEditingStyle.delete) {
let index = indexPath.item
self.removeItenFromDts(index: index)
tableView.reloadData()
}
}
override func addItenToDts(iten: String) {
super.addItenToDts(iten: iten)
persistData()
}
override func removeItenFromDts(index: Int) {
super.removeItenFromDts(index: index)
persistData()
}
public func persistData() {
UserDefaults.standard.set(data, forKey: tableKey)
}
public func getPersistedData() -> Array<String> {
let data = UserDefaults.standard.array(forKey: tableKey) as! Array<String>
return data
}
}
class SimplePickerViewDataSource: SimpleDataSource, UIPickerViewDataSource, UIPickerViewDelegate {
func onRowSelected() {/*
override this method if you need to execute any actions after selecting another row
ps: 9x2 eterno
*/}
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return data.count
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return data.count > 0 && data.count > row ? data[row] : ""
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
onRowSelected()
}
}
| 1819af8c0ec497a90e4875eed787f6a3 | 28.43 | 134 | 0.648318 | false | false | false | false |
yanif/circator | refs/heads/master | MetabolicCompass/View Controller/Charts/ChartsViewController.swift | apache-2.0 | 1 | //
// ChartsViewController.swift
// MetabolicCompass
//
// Created by Artem Usachov on 6/9/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import UIKit
import Charts
import HealthKit
import MetabolicCompassKit
import MCCircadianQueries
import SwiftDate
import Crashlytics
enum DataRangeType : Int {
case Week = 0
case Month
case Year
}
class ChartsViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
private var rangeType = DataRangeType.Week
private let barChartCellIdentifier = "BarChartCollectionCell"
private let lineChartCellIdentifier = "LineChartCollectionCell"
private let scatterChartCellIdentifier = "ScatterChartCollectionCell"
private let chartCollectionDataSource = ChartCollectionDataSource()
private let chartCollectionDelegate = ChartCollectionDelegate()
private let chartsModel = BarChartModel()
private var segmentControl: UISegmentedControl? = nil
// MARK :- View life cycle
override func viewDidLoad() {
super.viewDidLoad()
updateNavigationBar()
registerCells()
chartCollectionDataSource.model = chartsModel
collectionView.delegate = chartCollectionDelegate
collectionView.dataSource = chartCollectionDataSource
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateChartDataWithClean), name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateChartsData), name: HMDidUpdatedChartsData, object: nil)
chartCollectionDataSource.updateData()
updateChartsData()
logContentView()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
logContentView(false)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func logContentView(asAppear: Bool = true) {
Answers.logContentViewWithName("Charts",
contentType: asAppear ? "Appear" : "Disappear",
contentId: NSDate().toString(DateFormat.Custom("YYYY-MM-dd:HH")),
customAttributes: ["range": rangeType.rawValue])
}
// MARK :- Base preparation
func updateChartDataWithClean() {
chartsModel.typesChartData = [:]
IOSHealthManager.sharedManager.cleanCache()
IOSHealthManager.sharedManager.collectDataForCharts()
activityIndicator.startAnimating()
}
func updateChartsData () {
if !activityIndicator.isAnimating() {
activityIndicator.startAnimating()
}
chartsModel.getAllDataForCurrentPeriod({
self.activityIndicator.stopAnimating()
self.collectionView.reloadData()
})
}
func registerCells () {
let barChartCellNib = UINib(nibName: "BarChartCollectionCell", bundle: nil)
collectionView?.registerNib(barChartCellNib, forCellWithReuseIdentifier: barChartCellIdentifier)
let lineChartCellNib = UINib(nibName: "LineChartCollectionCell", bundle: nil)
collectionView?.registerNib(lineChartCellNib, forCellWithReuseIdentifier: lineChartCellIdentifier)
let scatterChartCellNib = UINib(nibName: "ScatterChartCollectionCell", bundle: nil)
collectionView.registerNib(scatterChartCellNib, forCellWithReuseIdentifier: scatterChartCellIdentifier)
}
func updateNavigationBar () {
let manageButton = ScreenManager.sharedInstance.appNavButtonWithTitle("Manage")
manageButton.addTarget(self, action: #selector(manageCharts), forControlEvents: .TouchUpInside)
let manageBarButton = UIBarButtonItem(customView: manageButton)
self.navigationItem.leftBarButtonItem = manageBarButton
self.navigationItem.title = NSLocalizedString("CHART", comment: "chart screen title")
// let correlateButton = ScreenManager.sharedInstance.appNavButtonWithTitle("Correlate")
// correlateButton.addTarget(self, action: #selector(correlateChart), forControlEvents: .TouchUpInside)
// let corrButton = UIBarButtonItem(customView: correlateButton)
// self.navigationItem.rightBarButtonItem = corrButton
}
@IBAction func rangeChanged(sender: UISegmentedControl) {
self.segmentControl = sender
// var showCorrelate = false
// let correlateSegment = sender.numberOfSegments-1
switch sender.selectedSegmentIndex {
case HealthManagerStatisticsRangeType.Month.rawValue:
chartsModel.rangeType = .Month
case HealthManagerStatisticsRangeType.Year.rawValue:
chartsModel.rangeType = .Year
break
default:
chartsModel.rangeType = .Week
}
logContentView()
updateChartsData()
}
func manageCharts () {
let manageController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("manageCharts")
self.presentViewController(manageController, animated: true) {}
}
// func correlateChart () {
// if let correlateController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("correlatePlaceholder") as? UIViewController {
// let leftButton = UIBarButtonItem(image: UIImage(named: "close-button"), style: .Plain, target: self, action: #selector(dismissCorrelateChart))
//
// self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
// self.navigationController?.pushViewController(correlateController, animated: true)
//
// }
// }
//
// func dismissCorrelateChart() {
// dismissViewControllerAnimated(true) { _ in
// if let sc = self.segmentControl {
// sc.selectedSegmentIndex = 0
// self.rangeChanged(sc)
// }
// }
// }
}
| 3118ec787f7fd0101e5101579bff37b3 | 39.877419 | 174 | 0.693971 | false | false | false | false |
GuiBayma/PasswordVault | refs/heads/develop | PasswordVault/Scenes/Groups/GroupsTableViewDataSource.swift | mit | 1 | //
// GroupsTableViewDataSource.swift
// PasswordVault
//
// Created by Guilherme Bayma on 7/26/17.
// Copyright © 2017 Bayma. All rights reserved.
//
import UIKit
import CoreData
class GroupsTableViewDataSource: NSObject, UITableViewDataSource {
// MARK: - Variables
fileprivate var data: [NSManagedObject] = []
weak var tableView: UITableView?
// MARK: - Set Data
func setData(_ data: [NSManagedObject]) {
self.data = data
tableView?.reloadData()
}
// MARK: - Return data
func getData(at index: Int) -> Group? {
if let group = data[index] as? Group {
return group
}
return nil
}
// MARK: - Add data
func addData(_ group: Group) {
data.append(group)
tableView?.reloadData()
}
// MARK: - Delete data
fileprivate func removeDataAt(_ indexPath: IndexPath) {
if let group = data[indexPath.item] as? Group {
if GroupManager.sharedInstance.delete(object: group) {
data.remove(at: indexPath.item)
tableView?.deleteRows(at: [indexPath], with: .automatic)
}
}
}
// MARK: - Data Source
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(for:indexPath) as GroupTableViewCell
if let group = data[indexPath.item] as? Group {
cell.configure(group)
}
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
removeDataAt(indexPath)
}
}
}
| 62dedde0729c8071e4537b43bea2eeda | 24.419753 | 127 | 0.617776 | false | false | false | false |
akupara/Vishnu | refs/heads/master | Vishnu/Matsya/MatsyaContainerViewController.swift | mit | 1 | //
// MatsyaContainerViewController.swift
// Vishnu
//
// Created by Daniel Lu on 3/9/16.
// Copyright © 2016 Daniel Lu. All rights reserved.
//
import UIKit
public class MatsyaContainerViewController: UIViewController {
enum PanelStatus {
case RightExpaned
case LeftExpanded
case BothCollapsed
}
private var mainNavigationController:UINavigationController!
private var rightPanel:UIViewController?
private var leftPanel:UIViewController?
private var mainViewGestures:[UISwipeGestureRecognizer] = []
private var leftViewGesture:UISwipeGestureRecognizer?
private var rightViewGesture:UISwipeGestureRecognizer?
private var currentPanelStatus:PanelStatus = .BothCollapsed
internal var targetPosRate:CGFloat = 0.7
internal var targetSizeScaleRate:CGFloat = 1
public var positionRate:CGFloat {
get {
return targetPosRate
}
set {
if newValue > 1 || newValue < 0 {
targetPosRate = 0.7
} else {
targetPosRate = newValue
}
}
}
public var mainViewScaleRate:CGFloat {
get {
return targetSizeScaleRate
}
set {
if newValue > 1 || newValue < 0 {
targetSizeScaleRate = 1
} else {
targetSizeScaleRate = newValue
}
}
}
public var backgroundImage:UIImage! = nil
public var backgroundView:UIView! = nil
static let animationDuration:NSTimeInterval = 0.5
static let springWithDamping:CGFloat = 0.8
override public func viewDidLoad() {
super.viewDidLoad()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MAKR: - MainViewController
public func setMainViewController(viewController:UIViewController) {
if mainNavigationController != nil {
if mainViewGestures.count > 0 {
for gesture in mainViewGestures {
mainNavigationController.view.removeGestureRecognizer(gesture)
}
}
mainNavigationController.view.removeFromSuperview()
mainNavigationController.removeFromParentViewController()
mainNavigationController = nil
}
if let navigation = viewController as? UINavigationController {
mainNavigationController = navigation
if let viewController = navigation.topViewController as? MatsyaContainerContent {
viewController.delegate = self
}
} else {
let navigation = UINavigationController(rootViewController: viewController)
mainNavigationController = navigation
if let mainController = viewController as? MatsyaContainerContent {
mainController.delegate = self
}
}
let index = view.subviews.count
let leftGesture = setupSwipeGestureRecognizerViewController(viewController, direction: .Left)
let rightGesture = setupSwipeGestureRecognizerViewController(viewController, direction: .Right)
mainViewGestures.append(leftGesture)
mainViewGestures.append(rightGesture)
view.insertSubview(viewController.view, atIndex: index)
addChildViewController(viewController)
viewController.didMoveToParentViewController(self)
}
public func setMainViewControllerInStoryboard(storyboard:UIStoryboard, withIdentifier identifier:String, params: [String:AnyObject]! = nil) {
let viewController = storyboard.instantiateViewControllerWithIdentifier(identifier)
setupParams(viewController, params: params)
setMainViewController(viewController)
}
public func setMainViewControllerWithStoryboardInitialController(storyboard: UIStoryboard, params:[String:AnyObject]! = nil) {
if let viewController = storyboard.instantiateInitialViewController() {
setupParams(viewController, params: params)
setMainViewController(viewController)
}
}
// MARK: - Panel update
public func setLeftPanel<T: UIViewController where T:MatsyaContainerContent> (panel: T) {
if currentPanelStatus == .LeftExpanded {
hidePanel(leftPanel)
if let gesture = leftViewGesture {
leftPanel?.view.removeGestureRecognizer(gesture)
leftViewGesture = nil
}
leftPanel = nil
}
leftPanel = panel
leftViewGesture = setupSwipeGestureRecognizerViewController(panel, direction: .Left)
panel.delegate = self
}
public func setRightPanen<T: UIViewController where T:MatsyaContainerContent> (panel: T) {
if currentPanelStatus == .RightExpaned {
hidePanel(rightPanel)
if let gesture = rightViewGesture {
rightPanel?.view.removeGestureRecognizer(gesture)
}
rightPanel = nil
}
rightPanel = panel
rightViewGesture = setupSwipeGestureRecognizerViewController(panel, direction: .Right)
panel.delegate = self
}
//MARK: - panel toggle and main view navigation
public func toggleRightPanel() {
if currentPanelStatus == .RightExpaned {
hidePanel(rightPanel)
} else if let _ = rightPanel {
currentPanelStatus = .RightExpaned
let targetPosition = (0 - (view.frame.size.width * targetPosRate))
showPanel(rightPanel, mainViewPosition: targetPosition)
}
}
public func toggleLeftPanel() {
if currentPanelStatus == .LeftExpanded {
hidePanel(leftPanel)
} else if let _ = leftPanel {
let targetPosition = view.frame.size.width * targetPosRate
showPanel(leftPanel, mainViewPosition: targetPosition)
}
}
public func collapsePanels(completion:((Bool) -> Void)! = nil) {
if currentPanelStatus == .LeftExpanded {
hidePanel(leftPanel, completion: completion)
} else if currentPanelStatus == .RightExpaned {
hidePanel(rightPanel, completion: completion)
}
}
public func presentViewController(viewController: UIViewController, animated:Bool, params:[String:AnyObject]! = nil) {
super.presentViewController(viewController, animated: animated, withParams: params, inViewController: mainNavigationController)
}
public func presentViewControllerInStoryboard(storyboard:UIStoryboard, withIdentifier identifier:String, animated:Bool, params: [String: AnyObject]! = nil) {
let viewController = storyboard.instantiateViewControllerWithIdentifier(identifier)
presentViewController(viewController, animated: animated, params: params)
}
public func presentInitialViewControllerInStoryboard(storyboard:UIStoryboard, animated:Bool, params:[String:AnyObject]! = nil) {
if let viewController = storyboard.instantiateInitialViewController() {
presentViewController(viewController, animated: animated, params: params)
}
}
// MARK: - internal messages
internal func animateMainView(targetPosition:CGFloat, newSize: CGSize! = nil, completion: ((Bool) -> Void)! = nil) {
UIView.animateWithDuration(MatsyaContainerViewController.animationDuration, delay: 0.0,
usingSpringWithDamping: MatsyaContainerViewController.springWithDamping,
initialSpringVelocity: 0, options: .CurveEaseInOut, animations: {
[unowned self] in
self.mainNavigationController.view.frame.origin.x = targetPosition
if newSize != nil {
self.mainNavigationController.view.frame.size = newSize
self.mainNavigationController.view.layoutIfNeeded()
}
}, completion: completion)
}
internal func hidePanel(panel:UIViewController?, completion: ((Bool) -> Void)! = nil) {
currentPanelStatus = .BothCollapsed
if let viewController = panel {
animateMainView(0.0, newSize: view.frame.size) {
[unowned self] (finished:Bool) in
self.showShadowForMainViewController(false)
viewController.view.removeFromSuperview()
viewController.removeFromParentViewController()
if completion != nil {
completion(finished)
}
}
}
}
internal func showPanel(panel:UIViewController?, mainViewPosition position:CGFloat) {
if let viewController = panel {
view.insertSubview(viewController.view, belowSubview: mainNavigationController.view)
addChildViewController(viewController)
viewController.didMoveToParentViewController(self)
let newSize:CGSize!
if targetSizeScaleRate < 1 {
let newWidth = mainNavigationController.view.frame.width * targetSizeScaleRate
let newHeight = mainNavigationController.view.frame.height * targetSizeScaleRate
newSize = CGSizeMake(newWidth, newHeight)
} else {
newSize = nil
}
showShadowForMainViewController(true)
layoutPanelForPosition(position, panel: panel)
animateMainView(position, newSize: newSize)
}
}
internal func showShadowForMainViewController(showShadow:Bool = true) {
if (showShadow) {
mainNavigationController.view.layer.shadowOpacity = 0.8
} else {
mainNavigationController.view.layer.shadowOpacity = 0.0
}
}
internal func layoutPanelForPosition(position:CGFloat, panel:UIViewController?) {
if position == 0.0 {
return
}
if let viewController = panel {
let maxWidth = view.frame.width
let height = view.frame.height
let width = abs(position)
let xPos:CGFloat!
if position > 0 {
xPos = 0.0
} else {
xPos = maxWidth - width
}
let targetFrame = CGRectMake(xPos, 0.0, width, height)
viewController.view.frame = targetFrame
viewController.view.layoutIfNeeded()
}
}
internal func setupSwipeGestureRecognizerViewController(viewController:UIViewController, direction:UISwipeGestureRecognizerDirection) -> UISwipeGestureRecognizer {
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(MatsyaContainerViewController.gestureSwipeHandler(_:)))
gesture.numberOfTouchesRequired = 1
gesture.direction = direction
viewController.view.addGestureRecognizer(gesture)
return gesture
}
// MARK: - Gesture Recogniser Handlers
public func gestureSwipeHandler(sender:UISwipeGestureRecognizer) {
if sender.view == leftPanel?.view {
leftPanelSwiped(sender)
} else if sender.view == rightPanel?.view {
rightPanelSwiped(sender)
} else if sender.view == mainNavigationController.view {
mainViewSwiped(sender)
}
}
internal func leftPanelSwiped(gesture:UISwipeGestureRecognizer) {
if currentPanelStatus == .LeftExpanded && gesture.direction == .Left {
hidePanel(leftPanel)
}
}
internal func rightPanelSwiped(gesture:UISwipeGestureRecognizer) {
if currentPanelStatus == .RightExpaned && gesture.direction == .Right {
hidePanel(rightPanel)
}
}
internal func mainViewSwiped(gesture:UISwipeGestureRecognizer) {
if gesture.direction == .Right {
if currentPanelStatus == .BothCollapsed {
toggleLeftPanel()
} else if currentPanelStatus == .RightExpaned {
hidePanel(rightPanel)
}
} else if gesture.direction == .Left {
if currentPanelStatus == .BothCollapsed {
toggleRightPanel()
} else if currentPanelStatus == .LeftExpanded {
hidePanel(leftPanel)
}
}
}
//MARK: - Background
private func setupBackgroundImage() {
if backgroundImage != nil {
//Remove previous background view
if backgroundView != nil {
backgroundView.removeFromSuperview()
backgroundView = nil
}
let imageView = UIImageView(image: backgroundImage)
imageView.translatesAutoresizingMaskIntoConstraints = false
view.insertSubview(imageView, atIndex: 0)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[imageView]|", options: [NSLayoutFormatOptions.AlignAllCenterX, NSLayoutFormatOptions.AlignAllCenterY], metrics: nil, views: ["imageView": imageView]))
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: imageView, attribute: .Width, multiplier: backgroundImage.size.height/backgroundImage.size.width, constant: 0))
// let rate = backgroundImage.size.width
}
}
}
@objc public protocol MatsyaContainerContent {
weak var delegate:MatsyaContainerViewController? { get set }
} | 656dc24d398a8498ac217135c4d5641b | 38.64723 | 232 | 0.640462 | false | false | false | false |
adobe-behancemobile/PeekPan | refs/heads/master | PeekPan/Demo/DemoViewController.swift | apache-2.0 | 1 | /******************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
* Copyright 2016 Adobe Systems Incorporated
* All Rights Reserved.
*
* This file is licensed 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 REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
******************************************************************************/
import UIKit
import Foundation
class DemoViewController : UIViewController, UIViewControllerPreviewingDelegate, PeekPanCoordinatorDelegate, PeekPanCoordinatorDataSource {
var peekPanCoordinator: PeekPanCoordinator!
@IBOutlet var percentageLabel: UILabel!
@IBOutlet var redView: UIView!
@IBOutlet var greenView: UIView!
@IBOutlet var yellowView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
redView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: view.bounds.width, height: view.bounds.height))
greenView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: view.bounds.height))
yellowView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: view.bounds.height))
redView.backgroundColor = .red
greenView.backgroundColor = .green
yellowView.backgroundColor = .yellow
view.addSubview(redView)
view.addSubview(greenView)
view.addSubview(yellowView)
yellowView.addSubview(percentageLabel)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 9.0, *) {
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: view)
peekPanCoordinator = PeekPanCoordinator(sourceView: view)
peekPanCoordinator.delegate = self
peekPanCoordinator.dataSource = self
}
}
}
// MARK: PeekPanCoordinatorDataSource
func maximumIndex(for peekPanCoordinator: PeekPanCoordinator) -> Int {
return 0
}
func shouldStartFromMinimumIndex(for peekPanCoordinator: PeekPanCoordinator) -> Bool {
return true
}
// MARK: PeekPanCoordinatorDelegate
func peekPanCoordinatorBegan(_ peekPanCoordinator: PeekPanCoordinator) {
greenView.frame.origin.x = peekPanCoordinator.startingPoint.x
greenView.frame.size.width = peekPanCoordinator.sourceView.bounds.width - peekPanCoordinator.startingPoint.x
yellowView.frame.origin.x = peekPanCoordinator.startingPoint.x
}
func peekPanCoordinatorEnded(_ peekPanCoordinator: PeekPanCoordinator) {
greenView.frame.size.width = 0.0
yellowView.frame.size.width = 0.0
percentageLabel.text = ""
}
func peekPanCoordinatorUpdated(_ peekPanCoordinator: PeekPanCoordinator) {
greenView.frame.origin.x = peekPanCoordinator.minimumPoint.x
greenView.frame.size.width = peekPanCoordinator.maximumPoint.x - peekPanCoordinator.minimumPoint.x
yellowView.frame.origin.x = peekPanCoordinator.minimumPoint.x
yellowView.frame.size.width = peekPanCoordinator.percentage * (peekPanCoordinator.maximumPoint.x - peekPanCoordinator.minimumPoint.x);
percentageLabel.text = String(format: "%.2f", Double(peekPanCoordinator.percentage))
percentageLabel.sizeToFit()
percentageLabel.frame.origin = CGPoint(x: 0.0, y: yellowView.bounds.height/2)
}
// MARK: UIViewControllerPreviewingDelegate
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
peekPanCoordinator.setup()
return nil
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
peekPanCoordinator.end(true)
}
}
| ef62c5f2f2e0f963ca06c019654f09da | 41.913462 | 143 | 0.678467 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | Objects/struct tables/ItemsTable.swift | gpl-2.0 | 1 | //
// ItemsTable.swift
// GoD Tool
//
// Created by Stars Momodu on 24/03/2021.
//
import Foundation
let itemsStruct = GoDStruct(name: "Item", format: [
.byte(name: "Pocket", description: "Which pocket in the bag the item goes in", type: .itemPocket),
.byte(name: "Is Locked", description: "Can't be held or tossed", type: .bool),
.byte(name: "Padding", description: "", type: .null),
.byte(name: "Unknown Flag", description: "", type: .bool),
.byte(name: "Battle Item ID", description: "Referred to by the ASM to determine item effect when used in battle", type: .uintHex),
.short(name: "Price", description: "", type: .uint),
.short(name: "Coupon Price", description: "", type: .uint),
.short(name: "Hold Item ID", description: "Referred to by the ASM to determine item effect when held in battle", type: .uint),
.word(name: "Padding 2", description: "", type: .null),
.word(name: "Name ID", description: "", type: .msgID(file: .common_rel)),
.word(name: "Description ID", description: "", type: .msgID(file: .typeAndFsysName(.msg, "pocket_menu"))),
.word(name: "Parameter", description: "Determines effectiveness of item", type: .uint),
.word(name: "Function Pointer", description: "Offset of ASM function the item triggers. This is set at run time but if you set it in the game file for an item that doesn't normally get set then it will keep that value.", type: .uintHex),
.word(name: "Function Pointer 2", description: "Offset of ASM function the item triggers. This is set at run time but if you set it in the game file for an item that doesn't normally get set then it will keep that value.", type: .uintHex),
.array(name: "Happiness effects", description: "Determines how much a pokemon's happiness changes when consuming this item. The amount varies based on the current happiness in 2 tiers.", property: .byte(name: "Happiness Effect", description: "", type: .int), count: 3)
])
let validItemStruct = GoDStruct(name: "Valid Item", format: [
.short(name: "Item ID", description: "", type: .itemID)
])
#if GAME_XD
let itemsTable = CommonStructTable(index: .Items, properties: itemsStruct, documentByIndex: false)
let validItemsTable = CommonStructTable(index: .ValidItems, properties: validItemStruct)
#else
let itemsTable = GoDStructTable(file: .dol, properties: itemsStruct, documentByIndex: false) { (file) -> Int in
kFirstItemOffset
} numberOfEntriesInFile: { (file) -> Int in
kNumberOfItems
}
let validItemsTable = GoDStructTable(file: .dol, properties: validItemStruct) { (file) -> Int in
return kFirstValidItemOffset
} numberOfEntriesInFile: { (file) -> Int in
return 1220
}
let validItemStruct2 = GoDStruct(name: "Valid Item 2", format: [
.short(name: "Item ID", description: "", type: .itemID)
])
let validItemsTable2 = GoDStructTable(file: .dol, properties: validItemStruct2) { (file) -> Int in
return kFirstValidItem2Offset
} numberOfEntriesInFile: { (file) -> Int in
return 1220
}
#endif
| cf84c9198391ed54021dc49283a1f501 | 50.614035 | 269 | 0.717539 | false | false | false | false |
eneko/SourceDocs | refs/heads/main | Sources/SourceDocsLib/PackageProcessor/PackageProcessor.swift | mit | 1 | //
// PackageProcessor.swift
//
//
// Created by Eneko Alonso on 5/1/20.
//
import Foundation
import Rainbow
import ProcessRunner
import MarkdownGenerator
public final class PackageProcessor {
public let inputPath: URL
public let outputPath: URL
public let reproducibleDocs: Bool
public var clustersEnabled: Bool = true
let canRenderDOT: Bool
let packageDump: PackageDump
let packageDependencyTree: PackageDependency
public enum Error: Swift.Error {
case invalidInput
}
static var canRenderDOT: Bool {
let result = try? system(command: "which dot", captureOutput: true)
return result?.standardOutput.isEmpty == false
}
public init(inputPath: String, outputPath: String, reproducibleDocs: Bool) throws {
self.inputPath = URL(fileURLWithPath: inputPath)
self.outputPath = URL(fileURLWithPath: outputPath)
self.reproducibleDocs = reproducibleDocs
canRenderDOT = Self.canRenderDOT
let path = self.inputPath.appendingPathComponent("Package.swift").path
guard FileManager.default.fileExists(atPath: path) else {
throw Error.invalidInput
}
try PackageLoader.resolveDependencies(at: inputPath)
packageDump = try PackageLoader.loadPackageDump(from: inputPath)
packageDependencyTree = try PackageLoader.loadPackageDependencies(from: inputPath)
}
public func run() throws {
fputs("Processing package...\n".green, stdout)
try createOutputFolderIfNeeded()
try generateGraphs()
let content: [MarkdownConvertible] = [
MarkdownHeader(title: "Package: **\(packageDump.name)**"),
renderProductsSection(),
renderModulesSection(),
renderExternalDependenciesSection(),
renderRequirementsSection(),
DocumentationGenerator.generateFooter(reproducibleDocs: reproducibleDocs)
]
let file = MarkdownFile(filename: "Package", basePath: outputPath.path, content: content)
fputs(" Writing \(file.filePath)", stdout)
try file.write()
fputs(" ✔\n".green, stdout)
fputs("Done 🎉\n".green, stdout)
}
func generateGraphs() throws {
let modules = ModuleGraphGenerator(basePath: outputPath, packageDump: packageDump)
modules.canRenderDOT = canRenderDOT
modules.clustersEnabled = clustersEnabled
try modules.run()
let dependencies = DependencyGraphGenerator(basePath: outputPath, dependencyTree: packageDependencyTree)
dependencies.canRenderDOT = canRenderDOT
dependencies.clustersEnabled = clustersEnabled
try dependencies.run()
}
func createOutputFolderIfNeeded() throws {
if FileManager.default.fileExists(atPath: outputPath.path) {
return
}
try FileManager.default.createDirectory(at: outputPath,
withIntermediateDirectories: true,
attributes: nil)
}
func renderProductsSection() -> MarkdownConvertible {
if packageDump.products.isEmpty {
return ""
}
let rows = packageDump.products.map { productDescription -> [String] in
let name = productDescription.name
let type = productDescription.type.label
let targets = productDescription.targets
return [name, type, targets.joined(separator: ", ")]
}
return [
MarkdownHeader(title: "Products", level: .h2),
"List of products in this package:",
MarkdownTable(headers: ["Product", "Type", "Targets"], data: rows),
"_Libraries denoted 'automatic' can be both static or dynamic._"
]
}
func renderModulesSection() -> MarkdownConvertible {
return [
MarkdownHeader(title: "Modules", level: .h2),
renderTargets(),
renderModuleGraph()
]
}
func renderModuleGraph() -> MarkdownConvertible {
let url = outputPath.appendingPathComponent("PackageModules.png")
guard FileManager.default.fileExists(atPath: url.path) else {
return ""
}
return [
MarkdownHeader(title: "Module Dependency Graph", level: .h3),
"[](PackageModules.png)"
]
}
func renderTargets() -> MarkdownConvertible {
let rows = packageDump.targets.map { targetDescription -> [String] in
let name = targetDescription.name
let type = targetDescription.type.rawValue.capitalized
let dependencies = targetDescription.dependencies.map { $0.label }.sorted()
return [name, type, dependencies.joined(separator: ", ")]
}
let regularRows = rows.filter { $0[1] != "Test" }
let testRows = rows.filter { $0[1] == "Test" }
return [
MarkdownHeader(title: "Program Modules", level: .h3),
MarkdownTable(headers: ["Module", "Type", "Dependencies"], data: regularRows),
MarkdownHeader(title: "Test Modules", level: .h3),
MarkdownTable(headers: ["Module", "Type", "Dependencies"], data: testRows)
]
}
func renderExternalDependenciesSection() -> MarkdownConvertible {
let title = MarkdownHeader(title: "External Dependencies", level: .h2)
if packageDump.dependencies.isEmpty {
return [
title,
"This package has zero dependencies 🎉"
]
}
return [
title,
MarkdownHeader(title: "Direct Dependencies", level: .h3),
renderDependenciesTable(),
MarkdownHeader(title: "Resolved Dependencies", level: .h3),
renderDependencyTree(dependency: packageDependencyTree),
renderExternalDependenciesGraph()
]
}
func renderDependenciesTable() -> MarkdownConvertible {
let sortedDependencies = packageDump.dependencies.sorted { $0.label < $1.label }
let rows = sortedDependencies.map { dependency -> [String] in
let name = MarkdownLink(text: dependency.label, url: dependency.url).markdown
let versions = dependency.requirementDescription
return [name, versions]
}
return MarkdownTable(headers: ["Package", "Versions"], data: rows)
}
func renderDependencyTree(dependency: PackageDependency) -> MarkdownConvertible {
let versionedName = "\(dependency.name) (\(dependency.version))"
let link: MarkdownConvertible = dependency.url.hasPrefix("http")
? MarkdownLink(text: versionedName, url: dependency.url)
: versionedName
let items = [link] + dependency.dependencies.map(renderDependencyTree)
return MarkdownList(items: items)
}
func renderExternalDependenciesGraph() -> MarkdownConvertible {
guard canRenderDOT else {
return ""
}
return [
MarkdownHeader(title: "Package Dependency Graph", level: .h3),
"[](PackageDependencies.png)"
]
}
func renderRequirementsSection() -> MarkdownConvertible {
return [
MarkdownHeader(title: "Requirements", level: .h2),
renderPlatforms()
]
}
func renderPlatforms() -> MarkdownConvertible {
if packageDump.platforms.isEmpty {
return ""
}
let rows = packageDump.platforms.map { platform -> [String] in
let name = platform.platformName.replacingOccurrences(of: "os", with: "OS")
let version = platform.version ?? ""
return [name, version]
}
return [
MarkdownHeader(title: "Minimum Required Versions", level: .h3),
MarkdownTable(headers: ["Platform", "Version"], data: rows)
]
}
}
| 147c0a5e44d22ada19c9e4b65ec8f946 | 36.820755 | 112 | 0.624345 | false | false | false | false |
TableBooking/ios-client | refs/heads/master | TableBooking/HistoryViewController.swift | mit | 1 | //
// HistoryViewController.swift
// TableBooking
//
// Created by Nikita Kirichek on 11/30/16.
// Copyright © 2016 Nikita Kirichek. All rights reserved.
//
import UIKit
class HistoryViewController: UIViewController {
let numberOfSectionsForTable = 2
let heightForCell = 130
@IBOutlet weak var orderHistory: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
orderHistory.backgroundColor = Color.TBBackground
navigationController?.navigationBar.barTintColor = Color.TBGreen
navigationController?.navigationBar.barStyle = .black;
navigationItem.title = "History"
// Do any additional setup after loading the view.
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension HistoryViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(heightForCell)
}
func numberOfSections(in tableView: UITableView) -> Int {
return numberOfSectionsForTable
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "historyItemCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! HistoryItemTableViewCell
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "Active"
case 1:
return "Previous"
default:
return ""
}
}
}
| b39111edd492d51cbfb0bfbb2aaa5fc4 | 25.05618 | 125 | 0.658473 | false | false | false | false |
DuckDeck/ViewChaos | refs/heads/master | Sources/DrawView.swift | mit | 1 | //
// DrawView.swift
// ViewChaosDemo
//
// Created by HuStan on 3/26/16.
// Copyright © 2016 Qfq. All rights reserved.
//
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
enum DrawMode {
case draw,capture
}
class DrawView: UIView {
var btnCaptureScreen = UIButton()
var btnCleanTrace = UIButton()
var drawMode = DrawMode.draw
var pointOrigin = CGPoint.zero
var pointLast = CGPoint.zero
fileprivate var arrTraces:Array<Trace>?
override init(frame: CGRect) {
super.init(frame: frame)
arrTraces = [Trace]()
self.frame = UIScreen.main.bounds
self.backgroundColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 0.2)
btnCaptureScreen.frame = CGRect(x: UIScreen.main.bounds.size.width - 90, y: UIScreen.main.bounds.size.height - 25, width: 90, height: 25)
btnCaptureScreen.backgroundColor = UIColor(red: 0.0, green: 0.898, blue: 0.836, alpha: 0.5)
btnCaptureScreen.setTitle("启用截屏", for: UIControl.State())
btnCaptureScreen.addTarget(self, action: #selector(DrawView.captureScreenClick(_:)), for: UIControl.Event.touchUpInside)
addSubview(btnCaptureScreen)
btnCleanTrace.frame = CGRect(x: UIScreen.main.bounds.size.width - 150, y: UIScreen.main.bounds.size.height - 25, width: 50, height: 25)
btnCleanTrace.backgroundColor = UIColor(red: 0.0, green: 0.898, blue: 0.836, alpha: 0.5)
btnCleanTrace.setTitle("清理", for: UIControl.State())
btnCleanTrace.addTarget(self, action: #selector(DrawView.clearTraceClick(_:)), for: UIControl.Event.touchUpInside)
addSubview(btnCleanTrace)
btnCleanTrace.isHidden = true
}
@objc func captureScreenClick(_ sender:UIButton) {
//这里用截图功能
if let title = sender.title(for: UIControl.State())
{
if title == "启用截屏"{
Chaos.toast("现在开始截图")
drawMode = .capture
self.backgroundColor = UIColor.clear
btnCaptureScreen.setTitle("保存", for: UIControl.State())
}
else{
UIGraphicsBeginImageContextWithOptions(UIScreen.main.bounds.size, true, 0)//这个应该是设定一个区域
UIApplication.shared.keyWindow!.layer.render(in: UIGraphicsGetCurrentContext()!)//将整个View渲染到Context里
let imgCapture = UIGraphicsGetImageFromCurrentImageContext()
UIImageWriteToSavedPhotosAlbum(imgCapture!, self, nil, nil)
self.backgroundColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 0.2)
Chaos.toast("保存截图成功")
btnCaptureScreen.setTitle("启用截屏", for: UIControl.State())
clearTrace()
drawMode = .draw
}
}
}
@objc func clearTraceClick(_ sender:UIButton){
clearTrace()
btnCaptureScreen.setTitle("启用截屏", for: UIControl.State())
drawMode = .draw
}
func clearTrace() {
arrTraces?.removeAll()
btnCleanTrace.isHidden = true
pointOrigin = CGPoint.zero
pointLast = CGPoint.zero
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let ctg = UIGraphicsGetCurrentContext()
ctg?.clear(rect)
ctg?.setLineWidth(1)
ctg?.setLineJoin(CGLineJoin.round)
ctg?.setLineCap(CGLineCap.round)
//画当前的线
if arrTraces?.count > 0
{
ctg?.beginPath()
var i = 0
while i < arrTraces?.count {
var tempTrace = arrTraces![i]
if tempTrace.arrPoints.count > 0
{
ctg?.beginPath()
var point = tempTrace.arrPoints[0]
ctg?.move(to: CGPoint(x: point.x, y: point.y))
let count:Int! = tempTrace.arrPoints.count
for j in 0 ..< count-1
{
point = tempTrace.arrPoints[j+1]
ctg?.addLine(to: CGPoint(x: point.x, y: point.y))
}
ctg?.setStrokeColor(tempTrace.color.cgColor)
let width:CGFloat! = tempTrace.thickness
ctg?.setLineWidth(width)
ctg?.strokePath()
}
i += 1
}
}
if drawMode == .capture{
ctg?.setFillColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.3).cgColor)
ctg?.setStrokeColor(UIColor.red.cgColor)
// let dash:UnsafeMutablePointer<CGFloat> = UnsafeMutablePointer<CGFloat>.alloc(2)
// dash.initialize(1)
// dash.successor().initialize(1)
//
// CGContextSetLineDash(ctg, 0, dash, 2)
ctg?.stroke(CGRect(x: pointOrigin.x, y: pointOrigin.y, width: pointLast.x - pointOrigin.x, height: pointLast.y - pointOrigin.y))
ctg?.fill(CGRect(x: pointOrigin.x, y: pointOrigin.y, width: pointLast.x - pointOrigin.x, height: pointLast.y - pointOrigin.y))
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if drawMode == .draw{
for touch in touches
{
let touchPoint:UITouch = touch
let point = touchPoint.location(in: self)
var trace = Trace()
trace.arrPoints = Array<CGPoint>()
trace.arrPoints.append(point)
trace.color = UIColor.red
trace.thickness = 1
arrTraces?.append(trace)
self.setNeedsDisplay()
}
}
else{
if let touch = touches.first{
pointOrigin = touch.location(in: self)
}
}
btnCleanTrace.isHidden = false
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
if drawMode == .draw{
for touch in touches
{
let touchPoint:UITouch = touch
let point = touchPoint.location(in: self)
//怎么找到上一个Point
let previousPoint = touchPoint.previousLocation(in: self)
var i = 0
while i < arrTraces?.count {
var tempTraces = arrTraces![i]
let lastPoint = tempTraces.arrPoints.last
if lastPoint == previousPoint
{
arrTraces![i].arrPoints.append(point)
break
}
i += 1
}
self .setNeedsDisplay()
}
}
else{
if let touch = touches.first{
pointLast = touch.location(in: self)
setNeedsDisplay()
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
struct Trace {
fileprivate var _arrPoints:Array<CGPoint>?
fileprivate var _color:UIColor = UIColor.white
fileprivate var _thickness:CGFloat = 1
var arrPoints:Array<CGPoint>{
mutating get{
if _arrPoints == nil
{
_arrPoints = Array<CGPoint>()
}
return _arrPoints!
}
set{
_arrPoints = newValue
}
}
var color:UIColor{
get{
return _color
}
set{
_color = newValue
}
}
var thickness:CGFloat{
get{
return _thickness
}
set{
_thickness = newValue
}
}
}
| c9bd53be745f81c139f2fd8b6ce78c1b | 31.835341 | 145 | 0.533146 | false | false | false | false |
kyleYang/KYNavigationFadeManager | refs/heads/master | KYNavigationFadeManager/TableViewController.swift | mit | 1 | //
// TableViewController.swift
// KYNavigationFadeManager
//
// Created by Kyle on 2017/5/8.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
open class TableViewController: UIViewController {
let tableView = UITableView(frame: .zero, style: .plain)
var fadeManager : KYNavigationFadeManager!
var shareButton : UIButton!
var backButton : UIButton!
var backBarItem : UIBarButtonItem!
public var shouldeHiddenTitle : Bool = true
override open func viewDidLoad() {
super.viewDidLoad()
self.extendedLayoutIncludesOpaqueBars = true;
self.automaticallyAdjustsScrollViewInsets = false
if #available(iOS 11.0, *) {
self.tableView.contentInsetAdjustmentBehavior = .never
} else {
// Fallback on earlier versions
}
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "tablecell")
self.view.addSubview(self.tableView);
self.tableView.translatesAutoresizingMaskIntoConstraints = false
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[table]|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["table":self.tableView]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[table]|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["table":self.tableView]))
let headerView = UIImageView(frame: CGRect(x:0,y:0,width:0,height:200))
headerView.image = UIImage(named:"header")
headerView.contentMode = .scaleAspectFill
self.tableView.tableHeaderView = headerView
self.backButton = UIButton()
self.backButton.setImage(UIImage(named:"navigationBar_back"), for: .normal)
self.backButton.frame = CGRect(x: 0, y: 0, width: 64, height: 64)
self.backButton.addTarget(self, action: #selector(TableViewController.buttonTapped(sender:)), for: .touchUpInside)
self.backBarItem = UIBarButtonItem(customView: self.backButton);
self.navigationItem.leftBarButtonItem = self.backBarItem
self.shareButton = UIButton()
self.shareButton.setImage(UIImage(named:"navi_collect"), for: .normal)
self.shareButton.frame = CGRect(x: 0, y: 0, width: 64, height: 64)
let shareBarItem = UIBarButtonItem(customView: self.shareButton);
self.navigationItem.rightBarButtonItems = [shareBarItem]
self.fadeManager = KYNavigationFadeManager(viewController: self, scollView: self.tableView)
self.fadeManager.allowTitleHidden = shouldeHiddenTitle
self.fadeManager.zeroAlphaOffset = 0;
self.fadeManager.fullAlphaOffset = 200;
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.fadeManager.viewWillAppear(animated)
}
open override func viewWillDisappear(_ animated: Bool) {
self.fadeManager.viewWillDisappear(animated)
super .viewWillDisappear(animated)
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func buttonTapped(sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
deinit {
print("TableViewController deinit")
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
if (self.fadeManager != nil && self.fadeManager.state == .faded) {
return .lightContent;
}
return .default;
}
}
extension TableViewController : UITableViewDelegate,UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell")
cell?.textLabel?.text = String(format: "%ld", arguments: [indexPath.row])
return cell!
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = AfterTableViewController(nibName: nil, bundle: nil);
vc.title = "下一个"
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension TableViewController : KYNavigationFadeManagerDelegate {
public func fadeManagerBarItemColorChange(_ manager: KYNavigationFadeManager, barItem: UIBarButtonItem, alpha: CGFloat) -> Bool {
if (barItem == self.backBarItem) {
return false
}
if (alpha > 0.3) {
self.shareButton.setImage(UIImage(named:"navi_collect"), for: .normal)
}else {
self.shareButton.setImage(UIImage(named:"navi_collect_fade"), for: .normal)
}
return true
}
public func fadeManager(_ manager: KYNavigationFadeManager, changeState: KYNavigationFadeState) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
| 78b01c3eb100221f552866bd8d780414 | 34.360544 | 189 | 0.683147 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | refs/heads/master | 45--Single-File-Please/IronSkies/IronSkies/AppDelegate.swift | cc0-1.0 | 1 | //
// AppDelegate.swift
// IronSkies
//
// Created by Pedro Trujillo on 12/7/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 throttle down OpenGL ES frame rates. 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 inactive 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 applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.tiy.IronSkies" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("IronSkies", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 4b4bed1011c654892ebbf5bc134acb5b | 53.90991 | 291 | 0.719606 | false | false | false | false |
gkaimakas/ReactiveBluetooth | refs/heads/master | Example/ReactiveBluetooth/Views/ActionButton.swift | mit | 1 | //
// ActionButton.swift
// ReactiveBluetooth_Example
//
// Created by George Kaimakas on 06/03/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
import ReactiveCocoa
import ReactiveSwift
import Result
import UIKit
public class ActionButton: UIButton {
fileprivate let activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
override public init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
addSubview(activityIndicator)
activityIndicator.activityIndicatorViewStyle = .gray
activityIndicator.hidesWhenStopped = true
activityIndicator.color = tintColor
bringSubview(toFront: activityIndicator)
layer.borderColor = tintColor.cgColor
layer.borderWidth = 0.5
contentEdgeInsets = UIEdgeInsets(top: 8, left: 32, bottom: 8, right: 32)
}
override public func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = self.frame.height/2
activityIndicator.frame = CGRect(x: frame.width-28, y: (frame.height - 24)/2, width: 24, height: 24)
}
}
extension Reactive where Base: ActionButton {
public var action: CocoaAction<Base>? {
get {
return self.pressed
}
nonmutating set {
self.pressed = newValue
if let _action = newValue {
base.activityIndicator.reactive.isAnimating <~ _action.isExecuting.producer
}
}
}
}
| d1f66a9b4f4de941f5cec265d776267c | 24.984615 | 113 | 0.646536 | false | false | false | false |
ksco/swift-algorithm-club-cn | refs/heads/master | Quicksort/Quicksort.playground/Contents.swift | mit | 2 | //: Playground - noun: a place where people can play
import Foundation
// *** Simple but inefficient version of quicksort ***
func quicksort<T: Comparable>(a: [T]) -> [T] {
if a.count <= 1 {
return a
} else {
let pivot = a[a.count/2]
let less = a.filter { $0 < pivot }
let equal = a.filter { $0 == pivot }
let greater = a.filter { $0 > pivot }
// Uncomment this following line to see in detail what the
// pivot is in each step and how the subarrays are partitioned.
//print(pivot, less, equal, greater)
return quicksort(less) + equal + quicksort(greater)
}
}
let list1 = [ 10, 0, 3, 9, 2, 14, 8, 27, 1, 5, 8, -1, 26 ]
quicksort(list1)
// *** Using Lomuto partitioning ***
/*
Lomuto's partitioning algorithm.
The return value is the index of the pivot element in the new array. The left
partition is [low...p-1]; the right partition is [p+1...high], where p is the
return value.
*/
func partitionLomuto<T: Comparable>(inout a: [T], low: Int, high: Int) -> Int {
let pivot = a[high]
var i = low
for j in low..<high {
if a[j] <= pivot {
(a[i], a[j]) = (a[j], a[i])
i += 1
}
}
(a[i], a[high]) = (a[high], a[i])
return i
}
var list2 = [ 10, 0, 3, 9, 2, 14, 26, 27, 1, 5, 8, -1, 8 ]
partitionLomuto(&list2, low: 0, high: list2.count - 1)
list2
func quicksortLomuto<T: Comparable>(inout a: [T], low: Int, high: Int) {
if low < high {
let p = partitionLomuto(&a, low: low, high: high)
quicksortLomuto(&a, low: low, high: p - 1)
quicksortLomuto(&a, low: p + 1, high: high)
}
}
quicksortLomuto(&list2, low: 0, high: list2.count - 1)
// *** Hoare partitioning ***
/*
Hoare's partitioning scheme.
The return value is NOT necessarily the index of the pivot element in the
new array. Instead, the array is partitioned into [low...p] and [p+1...high],
where p is the return value. The pivot value is placed somewhere inside one
of the two partitions, but the algorithm doesn't tell you which one or where.
*/
func partitionHoare<T: Comparable>(inout a: [T], low: Int, high: Int) -> Int {
let pivot = a[low]
var i = low - 1
var j = high + 1
while true {
repeat { j -= 1 } while a[j] > pivot
repeat { i += 1 } while a[i] < pivot
if i < j {
swap(&a[i], &a[j])
} else {
return j
}
}
}
var list3 = [ 8, 0, 3, 9, 2, 14, 10, 27, 1, 5, 8, -1, 26 ]
partitionHoare(&list3, low: 0, high: list3.count - 1)
list3
func quicksortHoare<T: Comparable>(inout a: [T], low: Int, high: Int) {
if low < high {
let p = partitionHoare(&a, low: low, high: high)
quicksortHoare(&a, low: low, high: p)
quicksortHoare(&a, low: p + 1, high: high)
}
}
quicksortHoare(&list3, low: 0, high: list3.count - 1)
// *** Randomized sorting ***
/* Returns a random integer in the range min...max, inclusive. */
public func random(min min: Int, max: Int) -> Int {
assert(min < max)
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
func quicksortRandom<T: Comparable>(inout a: [T], low: Int, high: Int) {
if low < high {
let pivotIndex = random(min: low, max: high)
(a[pivotIndex], a[high]) = (a[high], a[pivotIndex])
let p = partitionLomuto(&a, low: low, high: high)
quicksortRandom(&a, low: low, high: p - 1)
quicksortRandom(&a, low: p + 1, high: high)
}
}
var list4 = [ 10, 0, 3, 9, 2, 14, 8, 27, 1, 5, 8, -1, 26 ]
quicksortRandom(&list4, low: 0, high: list4.count - 1)
list4
// *** Dutch national flag partioning ***
/*
Swift's swap() doesn't like it if the items you're trying to swap refer to
the same memory location. This little wrapper simply ignores such swaps.
*/
public func swap<T>(inout a: [T], _ i: Int, _ j: Int) {
if i != j {
swap(&a[i], &a[j])
}
}
/*
Dutch national flag partitioning.
Returns a tuple with the start and end index of the middle area.
*/
func partitionDutchFlag<T: Comparable>(inout a: [T], low: Int, high: Int, pivotIndex: Int) -> (Int, Int) {
let pivot = a[pivotIndex]
var smaller = low
var equal = low
var larger = high
while equal <= larger {
if a[equal] < pivot {
swap(&a, smaller, equal)
smaller += 1
equal += 1
} else if a[equal] == pivot {
equal += 1
} else {
swap(&a, equal, larger)
larger -= 1
}
}
return (smaller, larger)
}
var list5 = [ 10, 0, 3, 9, 2, 14, 8, 27, 1, 5, 8, -1, 26 ]
partitionDutchFlag(&list5, low: 0, high: list5.count - 1, pivotIndex: 10)
list5
func quicksortDutchFlag<T: Comparable>(inout a: [T], low: Int, high: Int) {
if low < high {
let pivotIndex = random(min: low, max: high)
let (p, q) = partitionDutchFlag(&a, low: low, high: high, pivotIndex: pivotIndex)
quicksortDutchFlag(&a, low: low, high: p - 1)
quicksortDutchFlag(&a, low: q + 1, high: high)
}
}
quicksortDutchFlag(&list5, low: 0, high: list5.count - 1)
| d6fc82a7c5281e7dc183519c2793908c | 24.957672 | 106 | 0.602324 | false | false | false | false |
rringham/webviewqueue | refs/heads/master | src/WebViewQueue/WebViewQueue/ViewController.swift | mit | 1 | //
// ViewController.swift
// WebViewQueue
//
// Created by Robert Ringham on 10/10/16.
//
import Foundation
import UIKit
import WebKit
import JavaScriptCore
class RequestOperation {
var operationId: Int
init(_ operationId: Int) {
self.operationId = operationId
}
}
class ViewController: UIViewController, WKScriptMessageHandler, WKUIDelegate {
var webView: WKWebView?
var contentController: WKUserContentController?
var requestQueue: [RequestOperation] = [RequestOperation]()
var operationsQueued = 0
var operationsStarted = 0
var operationsCompleted = 0
override func viewDidLoad() {
super.viewDidLoad()
contentController = WKUserContentController()
contentController?.addScriptMessageHandler(self, name: "continueHandler")
let config = WKWebViewConfiguration()
config.userContentController = contentController!
webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), configuration: config)
webView?.UIDelegate = self
webView?.loadHTMLString(getHtml(), baseURL: nil)
// view.addSubview(webView!)
}
func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void)
{
let alert = UIAlertController(title: message, message: nil, preferredStyle: UIAlertControllerStyle.Alert);
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel) { _ in completionHandler()});
self.presentViewController(alert, animated: true, completion: {});
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
var queued = false
if let queuedParam = message.body["queued"] as? Bool {
queued = queuedParam
}
if let dataRequestProcessId = message.body["dataRequestProcessId"] as? Int {
print("requested data for process id \(dataRequestProcessId)")
self.webView?.evaluateJavaScript("continueLongRunningProcess(\(dataRequestProcessId), \(queued));", completionHandler: { (result, error) in
print("evaluateJavaScript completion handler for \(queued ? "queued" : "unqueued") DATA REQUEST for js operation \(dataRequestProcessId) done")
})
}
if let networkRequestProcessId = message.body["networkRequestProcessId"] as? Int {
print("requested data for process id \(networkRequestProcessId)")
self.webView?.evaluateJavaScript("finishLongRunningProcess(\(networkRequestProcessId), \(queued));", completionHandler: { (result, error) in
print("evaluateJavaScript completion handler for \(queued ? "queued" : "unqueued") NETWORK REQUEST for js operation \(networkRequestProcessId) done")
})
}
if let completedProcessId = message.body["completedProcessId"] as? Int {
print("completed process id \(completedProcessId)")
self.operationsCompleted += 1
if queued {
dequeueAndSubmitNextRequest()
}
}
if let pongId = message.body["pongId"] as? Int {
print("pong <- JS \(pongId)")
}
}
@IBAction func startWithNoProcessQueuing(sender: AnyObject) {
operationsQueued = 0
operationsStarted = 0
operationsCompleted = 0
for operationId in 1...10 {
print("started process \(operationId)")
self.operationsQueued += 1
self.operationsStarted += 1
self.webView?.evaluateJavaScript("someLongRunningProcess(\(operationId), false);", completionHandler: { (result, error) in
print("evaluateJavaScript completion handler for unqueued START js operation \(operationId) done")
})
}
// startPings()
}
@IBAction func startWithProcessQueuing(sender: AnyObject) {
operationsStarted = 0
operationsCompleted = 0
for operationId in 1...10 {
self.operationsQueued += 1
requestQueue.append(RequestOperation(operationId))
}
dequeueAndSubmitNextRequest()
// startPings()
}
@IBAction func printStats(sender: AnyObject) {
print("")
print("operations queued: \(operationsQueued)")
print("operations started: \(operationsStarted)")
print("operations completed: \(operationsCompleted)")
print("")
}
func dequeueAndSubmitNextRequest() {
if let requestOperation = self.requestQueue.first {
self.requestQueue.removeFirst()
print("started process \(requestOperation.operationId)")
self.operationsStarted += 1
self.webView?.evaluateJavaScript("someLongRunningProcess(\(requestOperation.operationId), true);", completionHandler: { (result, error) in
print("evaluateJavaScript completion handler for queued START js operation \(requestOperation.operationId) done")
})
}
}
func startPings() {
dispatch_async(dispatch_get_main_queue()) {
for pingId in 1...100 {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(pingId * 1000) * NSEC_PER_MSEC)), dispatch_get_main_queue(), { () -> Void in
print("ping -> JS \(pingId)")
self.webView?.evaluateJavaScript("ping(\(pingId));", completionHandler: nil)
})
}
}
}
func getHtml() -> String {
let fileLocation = NSBundle.mainBundle().pathForResource("poc", ofType: "html")!
do {
return try String(contentsOfFile: fileLocation)
}
catch {
return ""
}
}
}
| be76cf749bcb5aa4623c1ef22aec1136 | 37.371795 | 165 | 0.624123 | false | false | false | false |
Rapid-SDK/ios | refs/heads/master | Examples/RapiDO - ToDo list/RapiDO macOS/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// ExampleMacOSApp
//
// Created by Jan on 15/05/2017.
// Copyright © 2017 Rapid. All rights reserved.
//
import Cocoa
import Rapid
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var newTaskWindows: [NSWindow] = []
func applicationDidFinishLaunching(_ aNotification: Notification) {
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
@IBAction func newDocument(_ sender: Any) {
let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
let window = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "AddTaskWindow")) as! NSWindowController
window.showWindow(self)
if let window = window.window {
newTaskWindows.append(window)
}
}
func updateTask(_ task: Task) {
let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
let window = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "AddTaskWindow")) as! NSWindowController
(window.contentViewController as? TaskViewController)?.task = task
window.showWindow(self)
if let window = window.window {
newTaskWindows.append(window)
}
}
class func closeWindow(_ window: NSWindow) {
window.close()
windowClosed(window)
}
class func windowClosed(_ window: NSWindow) {
let delegate = NSApplication.shared.delegate as? AppDelegate
if let index = delegate?.newTaskWindows.index(of: window) {
delegate?.newTaskWindows.remove(at: index)
}
}
}
| 23e361915f72c6288f59df415fd87aca | 30.964286 | 149 | 0.669832 | false | false | false | false |
CodaFi/swift | refs/heads/master | stdlib/public/Darwin/Foundation/Publishers+KeyValueObserving.swift | apache-2.0 | 9 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
// Only support 64bit
#if !(os(iOS) && (arch(i386) || arch(arm)))
@_exported import Foundation // Clang module
import Combine
// The following protocol is so that we can reference `Self` in the Publisher
// below. This is based on a trick used in the the standard library's
// implementation of `NSObject.observe(key path)`
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public protocol _KeyValueCodingAndObservingPublishing {}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NSObject: _KeyValueCodingAndObservingPublishing {}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension _KeyValueCodingAndObservingPublishing where Self: NSObject {
/// Publish values when the value identified by a KVO-compliant keypath changes.
///
/// - Parameters:
/// - keyPath: The keypath of the property to publish.
/// - options: Key-value observing options.
/// - Returns: A publisher that emits elements each time the property’s value changes.
public func publisher<Value>(for keyPath: KeyPath<Self, Value>,
options: NSKeyValueObservingOptions = [.initial, .new])
-> NSObject.KeyValueObservingPublisher<Self, Value> {
return NSObject.KeyValueObservingPublisher(object: self, keyPath: keyPath, options: options)
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NSObject.KeyValueObservingPublisher {
/// Returns a publisher that emits values when a KVO-compliant property changes.
///
/// - Returns: A key-value observing publisher.
public func didChange()
-> Publishers.Map<NSObject.KeyValueObservingPublisher<Subject, Value>, Void> {
return map { _ in () }
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NSObject {
/// A publisher that emits events when the value of a KVO-compliant property changes.
public struct KeyValueObservingPublisher<Subject: NSObject, Value> : Equatable {
public let object: Subject
public let keyPath: KeyPath<Subject, Value>
public let options: NSKeyValueObservingOptions
public init(
object: Subject,
keyPath: KeyPath<Subject, Value>,
options: NSKeyValueObservingOptions
) {
self.object = object
self.keyPath = keyPath
self.options = options
}
public static func == (
lhs: KeyValueObservingPublisher,
rhs: KeyValueObservingPublisher
) -> Bool {
return lhs.object === rhs.object
&& lhs.keyPath == rhs.keyPath
&& lhs.options == rhs.options
}
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NSObject.KeyValueObservingPublisher: Publisher {
public typealias Output = Value
public typealias Failure = Never
public func receive<S: Subscriber>(subscriber: S) where S.Input == Output, S.Failure == Failure {
let s = NSObject.KVOSubscription(object, keyPath, options, subscriber)
subscriber.receive(subscription: s)
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NSObject {
private final class KVOSubscription<Subject: NSObject, Value>: Subscription, CustomStringConvertible, CustomReflectable, CustomPlaygroundDisplayConvertible {
private var observation: NSKeyValueObservation? // GuardedBy(lock)
private var demand: Subscribers.Demand // GuardedBy(lock)
// for configurations that care about '.initial' we need to 'cache' the value to account for backpressure, along with whom to send it to
//
// TODO: in the future we might want to consider interjecting a temporary publisher that does this, so that all KVO subscriptions don't incur the cost.
private var receivedInitial: Bool // GuardedBy(lock)
private var last: Value? // GuardedBy(lock)
private var subscriber: AnySubscriber<Value, Never>? // GuardedBy(lock)
private let lock = Lock()
// This lock can only be held for the duration of downstream callouts
private let downstreamLock = RecursiveLock()
var description: String { return "KVOSubscription" }
var customMirror: Mirror {
lock.lock()
defer { lock.unlock() }
return Mirror(self, children: [
"observation": observation as Any,
"demand": demand
])
}
var playgroundDescription: Any { return description }
init<S: Subscriber>(
_ object: Subject,
_ keyPath: KeyPath<Subject, Value>,
_ options: NSKeyValueObservingOptions,
_ subscriber: S)
where
S.Input == Value,
S.Failure == Never
{
demand = .max(0)
receivedInitial = false
self.subscriber = AnySubscriber(subscriber)
observation = object.observe(
keyPath,
options: options
) { [weak self] obj, _ in
guard let self = self else {
return
}
let value = obj[keyPath: keyPath]
self.lock.lock()
if self.demand > 0, let sub = self.subscriber {
self.demand -= 1
self.lock.unlock()
self.downstreamLock.lock()
let additional = sub.receive(value)
self.downstreamLock.unlock()
self.lock.lock()
self.demand += additional
self.lock.unlock()
} else {
// Drop the value, unless we've asked for .initial, and this
// is the first value.
if self.receivedInitial == false && options.contains(.initial) {
self.last = value
self.receivedInitial = true
}
self.lock.unlock()
}
}
}
deinit {
lock.cleanupLock()
downstreamLock.cleanupLock()
}
func request(_ d: Subscribers.Demand) {
lock.lock()
demand += d
if demand > 0, let v = last, let sub = subscriber {
demand -= 1
last = nil
lock.unlock()
downstreamLock.lock()
let additional = sub.receive(v)
downstreamLock.unlock()
lock.lock()
demand += additional
} else {
demand -= 1
last = nil
}
lock.unlock()
}
func cancel() {
lock.lock()
guard let o = observation else {
lock.unlock()
return
}
lock.unlock()
observation = nil
subscriber = nil
last = nil
o.invalidate()
}
}
}
#endif /* !(os(iOS) && (arch(i386) || arch(arm))) */
| 1f484211dcc54e323f0f859236708202 | 36.071429 | 161 | 0.560051 | false | false | false | false |
radvansky-tomas/NutriFacts | refs/heads/master | Example/Pods/RealmSwift/RealmSwift/Realm.swift | gpl-2.0 | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
A Realm instance (also referred to as "a realm") represents a Realm
database.
Realms can either be stored on disk (see `init(path:)`) or in
memory (see `init(inMemoryIdentifier:)`).
Realm instances are cached internally, and constructing equivalent Realm
objects (with the same path or identifier) produces limited overhead.
If you specifically want to ensure a Realm object is
destroyed (for example, if you wish to open a realm, check some property, and
then possibly delete the realm file and re-open it), place the code which uses
the realm within an `autoreleasepool {}` and ensure you have no other
strong references to it.
:warning: Realm instances are not thread safe and can not be shared across
threads or dispatch queues. You must construct a new instance on each thread you want
to interact with the realm on. For dispatch queues, this means that you must
call it in each block which is dispatched, as a queue is not guaranteed to run
on a consistent thread.
*/
public final class Realm {
// MARK: Properties
/// Path to the file where this Realm is persisted.
public var path: String { return rlmRealm.path }
/// Indicates if this Realm was opened in read-only mode.
public var readOnly: Bool { return rlmRealm.readOnly }
/// The Schema used by this realm.
public var schema: Schema { return Schema(rlmRealm.schema) }
/**
The location of the default Realm as a string. Can be overridden.
`~/Application Support/{bundle ID}/default.realm` on OS X.
`default.realm` in your application's documents directory on iOS.
:returns: Location of the default Realm.
*/
public class var defaultPath: String {
get {
return RLMRealm.defaultRealmPath()
}
set {
RLMRealm.setDefaultRealmPath(newValue)
}
}
// MARK: Initializers
/**
Obtains a Realm instance persisted at the specified file path. Defaults to
`Realm.defaultPath`
:param: path Path to the realm file.
*/
public convenience init(path: String = Realm.defaultPath) {
self.init(RLMRealm(path: path, readOnly: false, error: nil))
}
/**
Obtains a `Realm` instance with persistence to a specific file path with
options.
Like `init(path:)`, but with the ability to open read-only realms and get
errors as an `NSError` inout parameter rather than exceptions.
:warning: Read-only Realms do not support changes made to the file while the
`Realm` exists. This means that you cannot open a Realm as both read-only
and read-write at the same time. Read-only Realms should normally only be used
on files which cannot be opened in read-write mode, and not just for enforcing
correctness in code that should not need to write to the Realm.
:param: path Path to the file you want the data saved in.
:param: readOnly Bool indicating if this Realm is read-only (must use for read-only files).
:param: encryptionKey 64-byte key to use to encrypt the data.
:param: error If an error occurs, upon return contains an `NSError` object
that describes the problem. If you are not interested in
possible errors, omit the argument, or pass in `nil`.
*/
public convenience init?(path: String, readOnly: Bool, encryptionKey: NSData? = nil, error: NSErrorPointer = nil) {
if let rlmRealm = RLMRealm(path: path, key: encryptionKey, readOnly: readOnly, inMemory: false, dynamic: false, schema: nil, error: error) as RLMRealm? {
self.init(rlmRealm)
} else {
self.init(RLMRealm())
return nil
}
}
/**
Obtains a Realm instance for an un-persisted in-memory Realm. The identifier
used to create this instance can be used to access the same in-memory Realm from
multiple threads.
Because in-memory Realms are not persisted, you must be sure to hold on to a
reference to the `Realm` object returned from this for as long as you want
the data to last. Realm's internal cache of `Realm`s will not keep the
in-memory Realm alive across cycles of the run loop, so without a strong
reference to the `Realm` a new Realm will be created each time. Note that
`Object`s, `List`s, and `Results` that refer to objects persisted in a Realm have a
strong reference to the relevant `Realm`, as do `NotifcationToken`s.
:param: identifier A string used to identify a particular in-memory Realm.
*/
public convenience init(inMemoryIdentifier: String) {
self.init(RLMRealm.inMemoryRealmWithIdentifier(inMemoryIdentifier))
}
// MARK: Transactions
/**
Helper to perform actions contained within the given block inside a write transation.
:param: block The block to be executed inside a write transaction.
*/
public func write(block: (() -> Void)) {
rlmRealm.transactionWithBlock(block)
}
/**
Begins a write transaction in a `Realm`.
Only one write transaction can be open at a time. Write transactions cannot be
nested, and trying to begin a write transaction on a `Realm` which is
already in a write transaction with throw an exception. Calls to
`beginWrite` from `Realm` instances in other threads will block
until the current write transaction completes.
Before beginning the write transaction, `beginWrite` updates the
`Realm` to the latest Realm version, as if `refresh()` was called, and
generates notifications if applicable. This has no effect if the `Realm`
was already up to date.
It is rarely a good idea to have write transactions span multiple cycles of
the run loop, but if you do wish to do so you will need to ensure that the
`Realm` in the write transaction is kept alive until the write transaction
is committed.
*/
public func beginWrite() {
rlmRealm.beginWriteTransaction()
}
/**
Commits all writes operations in the current write transaction.
After this is called, the `Realm` reverts back to being read-only.
Calling this when not in a write transaction will throw an exception.
*/
public func commitWrite() {
rlmRealm.commitWriteTransaction()
}
/**
Revert all writes made in the current write transaction and end the transaction.
This rolls back all objects in the Realm to the state they were in at the
beginning of the write transaction, and then ends the transaction.
This restores the data for deleted objects, but does not reinstate deleted
accessor objects. Any `Object`s which were added to the Realm will be
invalidated rather than switching back to standalone objects.
Given the following code:
```swift
let oldObject = objects(ObjectType).first!
let newObject = ObjectType()
realm.beginWrite()
realm.add(newObject)
realm.delete(oldObject)
realm.cancelWrite()
```
Both `oldObject` and `newObject` will return `true` for `invalidated`,
but re-running the query which provided `oldObject` will once again return
the valid object.
Calling this when not in a write transaction will throw an exception.
*/
public func cancelWrite() {
rlmRealm.cancelWriteTransaction()
}
/**
Indicates if this Realm is currently in a write transaction.
:warning: Wrapping mutating operations in a write transaction if this property returns `false`
may cause a large number of write transactions to be created, which could negatively
impact Realm's performance. Always prefer performing multiple mutations in a single
transaction when possible.
*/
public var inWriteTransaction: Bool {
return rlmRealm.inWriteTransaction
}
// MARK: Adding and Creating objects
/**
Adds or updates an object to be persisted it in this Realm.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
When added, all linked (child) objects referenced by this object will also be
added to the Realm if they are not already in it. If the object or any linked
objects already belong to a different Realm an exception will be thrown. Use one
of the `create` functions to insert a copy of a persisted object into a different
Realm.
The object to be added must be valid and cannot have been previously deleted
from a Realm (i.e. `invalidated` must be false).
:param: object Object to be added to this Realm.
:param: update If true will try to update existing objects with the same primary key.
*/
public func add(object: Object, update: Bool = false) {
if update && object.objectSchema.primaryKeyProperty == nil {
throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
}
RLMAddObjectToRealm(object, rlmRealm, update ? .UpdateOrCreate : .allZeros)
}
/**
Adds or updates objects in the given sequence to be persisted it in this Realm.
:see: add(object:update:)
:param: objects A sequence which contains objects to be added to this Realm.
:param: update If true will try to update existing objects with the same primary key.
*/
public func add<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false) {
for obj in objects {
add(obj, update: update)
}
}
/**
Create an `Object` with the given object.
Creates or updates an instance of this object and adds it to the `Realm` populating
the object represented by value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
:param: type The object type to create.
:param: value The value used to populate the object. This can be any key/value coding compliant
object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
:param: update If true will try to update existing objects with the same primary key.
:returns: The created object.
*/
public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> T {
if update && schema[T.className()]?.primaryKeyProperty == nil {
throwRealmException("'\(T.className())' does not have a primary key and can not be updated")
}
let creationOptions: RLMCreationOptions = (update ? .UpdateOrCreate : .allZeros) | .AllowCopy
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, T.className(), value, creationOptions), T.self)
}
// MARK: Deleting objects
/**
Deletes the given object from this Realm.
:param: object The object to be deleted.
*/
public func delete(object: Object) {
RLMDeleteObjectFromRealm(object, rlmRealm)
}
/**
Deletes the given objects from this Realm.
:param: object The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
*/
public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S) {
for obj in objects {
delete(obj)
}
}
/**
Deletes the given objects from this Realm.
:param: object The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
:nodoc:
*/
public func delete<T: Object>(objects: List<T>) {
rlmRealm.deleteObjects(objects._rlmArray)
}
/**
Deletes the given objects from this Realm.
:param: object The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
:nodoc:
*/
public func delete<T: Object>(objects: Results<T>) {
rlmRealm.deleteObjects(objects.rlmResults)
}
/**
Deletes all objects from this Realm.
*/
public func deleteAll() {
RLMDeleteAllObjectsFromRealm(rlmRealm)
}
// MARK: Object Retrieval
/**
Returns all objects of the given type in the Realm.
:param: type The type of the objects to be returned.
:returns: All objects of the given type in Realm.
*/
public func objects<T: Object>(type: T.Type) -> Results<T> {
return Results<T>(RLMGetObjects(rlmRealm, T.className(), nil))
}
/**
Get an object with the given primary key.
Returns `nil` if no object exists with the given primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
:see: Object.primaryKey()
:param: type The type of the objects to be returned.
:param: key The primary key of the desired object.
:returns: An object of type `type` or `nil` if an object with the given primary key does not exist.
*/
public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T? {
return unsafeBitCast(RLMGetObject(rlmRealm, type.className(), key), Optional<T>.self)
}
// MARK: Notifications
/**
Add a notification handler for changes in this Realm.
:param: block A block which is called to process Realm notifications.
It receives the following parameters:
- `Notification`: The incoming notification.
- `Realm`: The realm for which this notification occurred.
:returns: A notification token which can later be passed to `removeNotification(_:)`
to remove this notification.
*/
public func addNotificationBlock(block: NotificationBlock) -> NotificationToken {
return rlmRealm.addNotificationBlock(rlmNotificationBlockFromNotificationBlock(block))
}
/**
Remove a previously registered notification handler using the token returned
from `addNotificationBlock(_:)`
:param: notificationToken The token returned from `addNotificationBlock(_:)`
corresponding to the notification block to remove.
*/
public func removeNotification(notificationToken: NotificationToken) {
rlmRealm.removeNotification(notificationToken)
}
// MARK: Autorefresh and Refresh
/**
Whether this Realm automatically updates when changes happen in other threads.
If set to `true` (the default), changes made on other threads will be reflected
in this Realm on the next cycle of the run loop after the changes are
committed. If set to `false`, you must manually call -refresh on the Realm to
update it to get the latest version.
Even with this enabled, you can still call `refresh()` at any time to update the
Realm before the automatic refresh would occur.
Notifications are sent when a write transaction is committed whether or not
this is enabled.
Disabling this on a `Realm` without any strong references to it will not
have any effect, and it will switch back to YES the next time the `Realm`
object is created. This is normally irrelevant as it means that there is
nothing to refresh (as persisted `Object`s, `List`s, and `Results` have strong
references to the containing `Realm`), but it means that setting
`Realm().autorefresh = false` in
`application(_:didFinishLaunchingWithOptions:)` and only later storing Realm
objects will not work.
Defaults to true.
*/
public var autorefresh: Bool {
get {
return rlmRealm.autorefresh
}
set {
rlmRealm.autorefresh = newValue
}
}
/**
Update a `Realm` and outstanding objects to point to the most recent
data for this `Realm`.
:returns: Whether the realm had any updates.
Note that this may return true even if no data has actually changed.
*/
public func refresh() -> Bool {
return rlmRealm.refresh()
}
// MARK: Invalidation
/**
Invalidate all `Object`s and `Results` read from this Realm.
A Realm holds a read lock on the version of the data accessed by it, so
that changes made to the Realm on different threads do not modify or delete the
data seen by this Realm. Calling this method releases the read lock,
allowing the space used on disk to be reused by later write transactions rather
than growing the file. This method should be called before performing long
blocking operations on a background thread on which you previously read data
from the Realm which you no longer need.
All `Object`, `Results` and `List` instances obtained from this
`Realm` on the current thread are invalidated, and can not longer be used.
The `Realm` itself remains valid, and a new read transaction is implicitly
begun the next time data is read from the Realm.
Calling this method multiple times in a row without reading any data from the
Realm, or before ever reading any data from the Realm is a no-op. This method
cannot be called on a read-only Realm.
*/
public func invalidate() {
rlmRealm.invalidate()
}
// MARK: Writing a Copy
/**
Write an encrypted and compacted copy of the Realm to the given path.
The destination file cannot already exist.
Note that if this is called from within a write transaction it writes the
*current* data, and not data when the last write transaction was committed.
:param: path Path to save the Realm to.
:param: encryptionKey Optional 64-byte encryption key to encrypt the new file with.
:returns: If an error occurs, returns an `NSError` object, otherwise `nil`.
:returns: Whether the realm was copied successfully.
*/
public func writeCopyToPath(path: String, encryptionKey: NSData? = nil) -> NSError? {
var error: NSError?
if let encryptionKey = encryptionKey {
rlmRealm.writeCopyToPath(path, encryptionKey: encryptionKey, error: &error)
} else {
rlmRealm.writeCopyToPath(path, error: &error)
}
return error
}
// MARK: Encryption
/**
Set the encryption key to use when opening Realms at a certain path.
This can be used as an alternative to explicitly passing the key to
`Realm(path:, encryptionKey:, readOnly:, error:)` each time a Realm instance is
needed. The encryption key will be used any time a Realm is opened with
`Realm(path:)` or `Realm()`.
If you do not want Realm to hold on to your encryption keys any longer than
needed, then use `Realm(path:, encryptionKey:, readOnly:, error:)` rather than this
method.
:param: encryptionKey 64-byte encryption key to use, or `nil` to unset.
:param: path Realm path to set the encryption key for.
+*/
public class func setEncryptionKey(encryptionKey: NSData?, forPath: String = Realm.defaultPath) {
RLMRealm.setEncryptionKey(encryptionKey, forRealmsAtPath: forPath)
}
// MARK: Internal
internal var rlmRealm: RLMRealm
internal init(_ rlmRealm: RLMRealm) {
self.rlmRealm = rlmRealm
}
}
// MARK: Equatable
extension Realm: Equatable { }
/// Returns whether the two realms are equal.
public func ==(lhs: Realm, rhs: Realm) -> Bool {
return lhs.rlmRealm == rhs.rlmRealm
}
// MARK: Notifications
/// A notification due to changes to a realm.
public enum Notification: String {
/**
Posted when the data in a realm has changed.
DidChange are posted after a realm has been refreshed to reflect a write transaction, i.e. when
an autorefresh occurs, `refresh()` is called, after an implicit refresh from
`beginWriteTransaction()`, and after a local write transaction is committed.
*/
case DidChange = "RLMRealmDidChangeNotification"
/**
Posted when a write transaction has been committed to a realm on a different thread for the same
file. This is not posted if `autorefresh` is enabled or if the Realm is refreshed before the
notifcation has a chance to run.
Realms with autorefresh disabled should normally have a handler for this notification which
calls `refresh()` after doing some work.
While not refreshing is allowed, it may lead to large Realm files as Realm has to keep an extra
copy of the data for the un-refreshed Realm.
*/
case RefreshRequired = "RLMRealmRefreshRequiredNotification"
}
/// Closure to run when the data in a Realm was modified.
public typealias NotificationBlock = (notification: Notification, realm: Realm) -> Void
internal func rlmNotificationBlockFromNotificationBlock(notificationBlock: NotificationBlock) -> RLMNotificationBlock {
return { rlmNotification, rlmRealm in
return notificationBlock(notification: Notification(rawValue: rlmNotification)!, realm: Realm(rlmRealm))
}
}
| 6bc8456f239305bc221707d0c75381dc | 37.650086 | 161 | 0.682954 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | iOS/Inspector/AccountInspectorViewController.swift | mit | 1 | //
// AccountInspectorViewController.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 5/17/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
import Account
class AccountInspectorViewController: UITableViewController {
static let preferredContentSizeForFormSheetDisplay = CGSize(width: 460.0, height: 400.0)
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var activeSwitch: UISwitch!
@IBOutlet weak var deleteAccountButton: VibrantButton!
var isModal = false
weak var account: Account?
override func viewDidLoad() {
super.viewDidLoad()
guard let account = account else { return }
nameTextField.placeholder = account.defaultName
nameTextField.text = account.name
nameTextField.delegate = self
activeSwitch.isOn = account.isActive
navigationItem.title = account.nameForDisplay
if account.type != .onMyMac {
deleteAccountButton.setTitle(NSLocalizedString("Remove Account", comment: "Remove Account"), for: .normal)
}
if isModal {
let doneBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done))
navigationItem.leftBarButtonItem = doneBarButtonItem
}
tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader")
}
override func viewWillDisappear(_ animated: Bool) {
account?.name = nameTextField.text
account?.isActive = activeSwitch.isOn
}
@objc func done() {
dismiss(animated: true)
}
@IBAction func credentials(_ sender: Any) {
guard let account = account else { return }
switch account.type {
case .feedbin:
let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "FeedbinAccountNavigationViewController") as! UINavigationController
let addViewController = navController.topViewController as! FeedbinAccountViewController
addViewController.account = account
navController.modalPresentationStyle = .currentContext
present(navController, animated: true)
case .feedWrangler:
let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "FeedWranglerAccountNavigationViewController") as! UINavigationController
let addViewController = navController.topViewController as! FeedWranglerAccountViewController
addViewController.account = account
navController.modalPresentationStyle = .currentContext
present(navController, animated: true)
case .newsBlur:
let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "NewsBlurAccountNavigationViewController") as! UINavigationController
let addViewController = navController.topViewController as! NewsBlurAccountViewController
addViewController.account = account
navController.modalPresentationStyle = .currentContext
present(navController, animated: true)
case .inoreader, .bazQux, .theOldReader, .freshRSS:
let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "ReaderAPIAccountNavigationViewController") as! UINavigationController
let addViewController = navController.topViewController as! ReaderAPIAccountViewController
addViewController.accountType = account.type
addViewController.account = account
navController.modalPresentationStyle = .currentContext
present(navController, animated: true)
default:
break
}
}
@IBAction func deleteAccount(_ sender: Any) {
guard let account = account else {
return
}
let title = NSLocalizedString("Remove Account", comment: "Remove Account")
let message: String = {
switch account.type {
case .feedly:
return NSLocalizedString("Are you sure you want to remove this account? NetNewsWire will no longer be able to access articles and feeds unless the account is added again.", comment: "Log Out and Remove Account")
default:
return NSLocalizedString("Are you sure you want to remove this account? This cannot be undone.", comment: "Remove Account")
}
}()
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel")
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel)
alertController.addAction(cancelAction)
let markTitle = NSLocalizedString("Remove", comment: "Remove")
let markAction = UIAlertAction(title: markTitle, style: .default) { [weak self] (action) in
guard let self = self, let account = self.account else { return }
AccountManager.shared.deleteAccount(account)
if self.isModal {
self.dismiss(animated: true)
} else {
self.navigationController?.popViewController(animated: true)
}
}
alertController.addAction(markAction)
alertController.preferredAction = markAction
present(alertController, animated: true)
}
}
// MARK: Table View
extension AccountInspectorViewController {
var hidesCredentialsSection: Bool {
guard let account = account else {
return true
}
switch account.type {
case .onMyMac, .cloudKit, .feedly:
return true
default:
return false
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
guard let account = account else { return 0 }
if account == AccountManager.shared.defaultAccount {
return 1
} else if hidesCredentialsSection {
return 2
} else {
return super.numberOfSections(in: tableView)
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let account = account else { return nil }
if section == 0 {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView
headerView.imageView.image = AppAssets.image(for: account.type)
return headerView
} else {
return super.tableView(tableView, viewForHeaderInSection: section)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
if indexPath.section == 1, hidesCredentialsSection {
cell = super.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 2))
} else {
cell = super.tableView(tableView, cellForRowAt: indexPath)
}
return cell
}
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
if indexPath.section > 0 {
return true
}
return false
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
}
}
// MARK: UITextFieldDelegate
extension AccountInspectorViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| 338d30d0d4a291c41ec2ebfc2b6df91b | 33.362745 | 215 | 0.763481 | false | false | false | false |
HPE-Haven-OnDemand/havenondemand-ios-swift | refs/heads/master | HODClient/lib/HODClient.swift | mit | 1 | //
// HODClient.swift
//
// Created by MAC_USER on 2/12/15.
// Copyright (c) 2015 Paco Vu. All rights reserved.
//
import Foundation
import MobileCoreServices
public protocol HODClientDelegate {
func requestCompletedWithContent(var response:String)
func requestCompletedWithJobID(response:String)
func onErrorOccurred(errorMessage:String)
}
public class HODClient : NSObject
{
public enum REQ_MODE { case SYNC, ASYNC }
public var delegate: HODClientDelegate?
private var apikey : String = ""
private let havenBase : String = "https://api.havenondemand.com/1/api/"
private let havenJobResult : String = "https://api.havenondemand.com/1/job/result/"
private let havenJobStatus : String = "https://api.havenondemand.com/1/job/status/"
private var getJobID = true
private var isBusy = false
private var version = "v1"
private var session = NSURLSession.sharedSession()
public init(apiKey:String, version:String = "v1") {
apikey = apiKey
self.version = version
session.configuration.timeoutIntervalForRequest = 600
}
public func GetJobResult(jobID:String)
{
if !isBusy {
let queryStr:String = String(format: "%@%@?apikey=%@", arguments: [havenJobResult,jobID,apikey])
getJobID = false
let uri = NSURL(string: queryStr)
let request = NSMutableURLRequest(URL: uri!)
request.HTTPMethod = "GET"
isBusy = true
sendRequest(request)
} else {
self.delegate?.onErrorOccurred("Busy. Previous operation is in progress.")
}
}
public func GetJobStatus(jobID:String)
{
if !isBusy {
let queryStr:String = String(format: "%@%@?apikey=%@", arguments: [havenJobStatus,jobID,apikey])
getJobID = false
let uri = NSURL(string: queryStr)
let request = NSMutableURLRequest(URL: uri!)
request.HTTPMethod = "GET"
isBusy = true
sendRequest(request)
} else {
self.delegate?.onErrorOccurred("Busy. Previous operation is in progress.")
}
}
public func GetRequest(inout params:Dictionary<String, AnyObject>, hodApp:String, requestMode:REQ_MODE = .ASYNC)
{
if !isBusy {
var endPoint:String = havenBase
if requestMode == .SYNC {
endPoint += String(format: "sync/%@/%@?apikey=%@", arguments: [hodApp,version,apikey])
getJobID = false
} else {
endPoint += String(format: "async/%@/%@?apikey=%@", arguments: [hodApp,version,apikey])
getJobID = true
}
var queryStr:String = ""
if params.count > 0 {
for (key, value) in params {
if (key == "file") {
self.delegate?.onErrorOccurred("Failed. File upload must be used with PostRequest function.")
return
}
if let arr = value as? Array<String> {
for item in arr {
queryStr += String(format: "&%@=%@", arguments: [key,item])
}
} else if let _ = value as? String {
queryStr += String(format: "&%@=%@", arguments: [key,value as! String])
}
}
}
let encodedUrl = queryStr.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
endPoint = endPoint.stringByAppendingString(encodedUrl!)
let uri = NSURL(string: endPoint)
let request = NSMutableURLRequest(URL: uri!)
request.HTTPMethod = "GET"
isBusy = true
sendRequest(request)
} else {
self.delegate?.onErrorOccurred("Busy. Previous operation is in progress.")
}
}
public func PostRequest(inout params : Dictionary<String, AnyObject>, hodApp:String, requestMode:REQ_MODE = .ASYNC)
{
if !isBusy {
var queryStr:String = havenBase
if requestMode == .SYNC {
queryStr += String(format: "sync/%@/%@", arguments: [hodApp,version])
getJobID = false
} else {
queryStr += String(format: "async/%@/%@", arguments: [hodApp,version])
getJobID = true
}
let appUrl = NSURL(string: queryStr)
let request = NSMutableURLRequest()
request.URL = appUrl!
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let postData = createBodyWithParameters(¶ms, boundary: boundary)
if postData != nil {
request.HTTPBody = postData
request.setValue("\(postData!.length)", forHTTPHeaderField: "Content-Length")
request.HTTPMethod = "POST"
isBusy = true
sendRequest(request)
}
} else {
self.delegate?.onErrorOccurred("Busy. Previous operation is in progress.")
}
}
/********
// private functions
********/
private func createBodyWithParameters(inout parameters: Dictionary<String, AnyObject>, boundary: String) -> NSData? {
let body = NSMutableData()
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"apikey\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("\(apikey)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
if parameters.count > 0 {
for (key, value) in parameters {
//let type:String = "array" //value.type
//if type == "array" {
if let arr = value as? Array<String> {
if (key == "file") {
for file in arr {
let fullFileNameWithPath = file
let fileUrl = NSURL(fileURLWithPath: fullFileNameWithPath)
do {
let data = try NSData(contentsOfURL: fileUrl,options: NSDataReadingOptions.DataReadingMappedIfSafe)
var index = fullFileNameWithPath.rangeOfString("/", options: .BackwardsSearch)?.endIndex
let fileName = fullFileNameWithPath.substringFromIndex(index!)
index = fileName.rangeOfString(".", options: .BackwardsSearch)?.endIndex
let fileExtension = fileName.substringFromIndex(index!)
let mimeType = DetermineMIMEType(fileExtension)!
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(fileName)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(data)
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
} catch let error as NSError {
self.delegate!.onErrorOccurred(error.localizedDescription as String)
return nil
}
}
} else {
for item in arr {
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("\(item )\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
}
}
} else if let _ = value as? String {
if (key == "file") {
let fullFileNameWithPath = value as! String
let fileUrl = NSURL(fileURLWithPath: fullFileNameWithPath)
do {
let data = try NSData(contentsOfURL: fileUrl,options: NSDataReadingOptions.DataReadingMappedIfSafe)
var index = fullFileNameWithPath.rangeOfString("/", options: .BackwardsSearch)?.endIndex
let fileName = fullFileNameWithPath.substringFromIndex(index!)
index = fileName.rangeOfString(".", options: .BackwardsSearch)?.endIndex
let fileExtension = fileName.substringFromIndex(index!)
let mimeType = DetermineMIMEType(fileExtension)!
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(fileName)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(data)
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
} catch let error as NSError {
self.delegate!.onErrorOccurred(error.localizedDescription as String)
return nil
}
} else {
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("\(value as! String)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
}
}
}
}
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
return body
}
// util funcs
private func generateBoundaryString() -> String {
return "Boundary--\(NSUUID().UUIDString)"
}
private func DetermineMIMEType(fileExtension: String) -> String? {
if !fileExtension.isEmpty {
let UTIRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, nil)
let UTI = UTIRef!.takeUnretainedValue()
UTIRef!.release()
let MIMETypeRef = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType)
if MIMETypeRef != nil
{
let MIMEType = MIMETypeRef!.takeUnretainedValue()
MIMETypeRef!.release()
return MIMEType as String
}
}
return "application/octet-stream"
}
private func sendRequest(request: NSMutableURLRequest)
{
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
self.isBusy = false
if (error != nil) {
dispatch_async(dispatch_get_main_queue(), {
let errorStr = error!.localizedDescription
self.delegate!.onErrorOccurred(errorStr)
})
} else {
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
dispatch_async(dispatch_get_main_queue(), {
if (self.getJobID) {
self.delegate!.requestCompletedWithJobID(strData! as String)
} else {
self.delegate!.requestCompletedWithContent(strData! as String)
}
})
}
})
task.resume()
}
}
extension String
{
func trim() -> String
{
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
}
public struct HODApps {
public static let RECOGNIZE_SPEECH = "recognizespeech"
public static let CANCEL_CONNECTOR_SCHEDULE = "cancelconnectorschedule"
public static let CONNECTOR_HISTORY = "connectorhistory"
public static let CONNECTOR_STATUS = "connectorstatus"
public static let CREATE_CONNECTOR = "createconnector"
public static let DELETE_CONNECTOR = "deleteconnector"
public static let RETRIEVE_CONFIG = "retrieveconfig"
public static let START_CONNECTOR = "startconnector"
public static let STOP_CONNECTOR = "stopconnector"
public static let UPDATE_CONNECTOR = "updateconnector"
public static let EXPAND_CONTAINER = "expandcontainer"
public static let STORE_OBJECT = "storeobject"
public static let EXTRACT_TEXT = "extracttext"
public static let VIEW_DOCUMENT = "viewdocument"
public static let OCR_DOCUMENT = "ocrdocument"
public static let RECOGNIZE_BARCODES = "recognizebarcodes"
public static let DETECT_FACES = "detectfaces"
public static let RECOGNIZE_IMAGES = "recognizeimages"
public static let GET_COMMON_NEIGHBORS = "getcommonneighbors"
public static let GET_NEIGHBORS = "getneighbors"
public static let GET_NODES = "getnodes"
public static let GET_SHORTEST_PATH = "getshortestpath"
public static let GET_SUB_GRAPH = "getsubgraph"
public static let SUGGEST_LINKS = "suggestlinks"
public static let SUMMARIZE_GRAPH = "summarizegraph"
public static let ANOMALY_DETECTION = "anomalydetection"
public static let TREND_ANALYSIS = "trendanalysis"
public static let CREATE_CLASSIFICATION_OBJECTS = "createclassificationobjects"
public static let CREATE_POLICY_OBJECTS = "createpolicyobjects"
public static let DELETE_CLASSIFICATION_OBJECTS = "deleteclassificationobjects"
public static let DELETE_POLICY_OBJECTS = "deletepolicyobjects"
public static let RETRIEVE_CLASSIFICATION_OBJECTS = "retrieveclassificationobjects"
public static let RETRIEVE_POLICY_OBJECTS = "retrievepolicyobjects"
public static let UPDATE_CLASSIFICATION_OBJECTS = "updateclassificationobjects"
public static let UPDATE_POLICY_OBJECTS = "updatepolicyobjects"
public static let PREDICT = "predict"
public static let RECOMMEND = "recommend"
public static let TRAIN_PREDICTOR = "trainpredictor"
public static let CREATE_QUERY_PROFILE = "createqueryprofile"
public static let DELETE_QUERY_PROFILE = "deletequeryprofile"
public static let RETRIEVE_QUERY_PROFILE = "retrievequeryprofile"
public static let UPDATE_QUERY_PROFILE = "updatequeryprofile"
public static let FIND_RELATED_CONCEPTS = "findrelatedconcepts"
public static let FIND_SIMILAR = "findsimilar"
public static let GET_CONTENT = "getcontent"
public static let GET_PARAMETRIC_VALUES = "getparametricvalues"
public static let QUERY_TEXT_INDEX = "querytextindex"
public static let RETRIEVE_INDEX_FIELDS = "retrieveindexfields"
public static let AUTO_COMPLETE = "autocomplete"
public static let CLASSIFY_DOCUMENT = "classifydocument"
public static let EXTRACT_CONCEPTS = "extractconcepts"
public static let CATEGORIZE_DOCUMENT = "categorizedocument"
public static let ENTITY_EXTRACTION = "extractentities"
public static let EXPAND_TERMS = "expandterms"
public static let HIGHLIGHT_TEXT = "highlighttext"
public static let IDENTIFY_LANGUAGE = "identifylanguage"
public static let ANALYZE_SENTIMENT = "analyzesentiment"
public static let TOKENIZE_TEXT = "tokenizetext"
public static let ADD_TO_TEXT_INDEX = "addtotextindex"
public static let CREATE_TEXT_INDEX = "createtextindex"
public static let DELETE_TEXT_INDEX = "deletetextindex"
public static let DELETE_FROM_TEXT_INDEX = "deletefromtextindex"
public static let INDEX_STATUS = "indexstatus"
//public static let LIST_INDEXES = "listindexes" REMOVED
public static let LIST_RESOURCES = "listresources"
public static let RESTORE_TEXT_INDEX = "restoretextindex"
}
| 066d99b7391876b6e57cf2f8db0ec63f | 46.965116 | 169 | 0.593152 | false | false | false | false |
ReactiveKit/ReactiveGitter | refs/heads/master | Carthage/Checkouts/Bond/Sources/Bond/UIKit/UITableView.swift | mit | 2 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// 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.
//
#if os(iOS) || os(tvOS)
import UIKit
import ReactiveKit
public extension ReactiveExtensions where Base: UITableView {
public var delegate: ProtocolProxy {
return base.protocolProxy(for: UITableViewDelegate.self, setter: NSSelectorFromString("setDelegate:"))
}
public var dataSource: ProtocolProxy {
return base.protocolProxy(for: UITableViewDataSource.self, setter: NSSelectorFromString("setDataSource:"))
}
}
public protocol TableViewBond {
associatedtype DataSource: DataSourceProtocol
func apply(event: DataSourceEvent<DataSource>, to tableView: UITableView)
func cellForRow(at indexPath: IndexPath, tableView: UITableView, dataSource: DataSource) -> UITableViewCell
func titleForHeader(in section: Int, dataSource: DataSource) -> String?
func titleForFooter(in section: Int, dataSource: DataSource) -> String?
}
extension TableViewBond {
public func apply(event: DataSourceEvent<DataSource>, to tableView: UITableView) {
switch event.kind {
case .reload:
tableView.reloadData()
case .insertItems(let indexPaths):
tableView.insertRows(at: indexPaths, with: .automatic)
case .deleteItems(let indexPaths):
tableView.deleteRows(at: indexPaths, with: .automatic)
case .reloadItems(let indexPaths):
tableView.reloadRows(at: indexPaths, with: .automatic)
case .moveItem(let indexPath, let newIndexPath):
tableView.moveRow(at: indexPath, to: newIndexPath)
case .insertSections(let indexSet):
tableView.insertSections(indexSet, with: .automatic)
case .deleteSections(let indexSet):
tableView.deleteSections(indexSet, with: .automatic)
case .reloadSections(let indexSet):
tableView.reloadSections(indexSet, with: .automatic)
case .moveSection(let index, let newIndex):
tableView.moveSection(index, toSection: newIndex)
case .beginUpdates:
tableView.beginUpdates()
case .endUpdates:
tableView.endUpdates()
}
}
public func titleForHeader(in section: Int, dataSource: DataSource) -> String? {
return nil
}
public func titleForFooter(in section: Int, dataSource: DataSource) -> String? {
return nil
}
}
private struct DefaultTableViewBond<DataSource: DataSourceProtocol>: TableViewBond {
let createCell: (DataSource, IndexPath, UITableView) -> UITableViewCell
func cellForRow(at indexPath: IndexPath, tableView: UITableView, dataSource: DataSource) -> UITableViewCell {
return createCell(dataSource, indexPath, tableView)
}
}
private struct ReloadingTableViewBond<DataSource: DataSourceProtocol>: TableViewBond {
let createCell: (DataSource, IndexPath, UITableView) -> UITableViewCell
func cellForRow(at indexPath: IndexPath, tableView: UITableView, dataSource: DataSource) -> UITableViewCell {
return createCell(dataSource, indexPath, tableView)
}
func apply(event: DataSourceEvent<DataSource>, to tableView: UITableView) {
tableView.reloadData()
}
}
public extension SignalProtocol where Element: DataSourceEventProtocol, Error == NoError {
public typealias DataSource = Element.DataSource
@discardableResult
public func bind(to tableView: UITableView, animated: Bool = true, createCell: @escaping (DataSource, IndexPath, UITableView) -> UITableViewCell) -> Disposable {
if animated {
return bind(to: tableView, using: DefaultTableViewBond<DataSource>(createCell: createCell))
} else {
return bind(to: tableView, using: ReloadingTableViewBond<DataSource>(createCell: createCell))
}
}
@discardableResult
public func bind<B: TableViewBond>(to tableView: UITableView, using bond: B) -> Disposable where B.DataSource == DataSource {
let dataSource = Property<DataSource?>(nil)
let disposable = CompositeDisposable()
disposable += tableView.reactive.dataSource.feed(
property: dataSource,
to: #selector(UITableViewDataSource.tableView(_:cellForRowAt:)),
map: { (dataSource: DataSource?, tableView: UITableView, indexPath: NSIndexPath) -> UITableViewCell in
return bond.cellForRow(at: indexPath as IndexPath, tableView: tableView, dataSource: dataSource!)
})
disposable += tableView.reactive.dataSource.feed(
property: dataSource,
to: #selector(UITableViewDataSource.tableView(_:titleForHeaderInSection:)),
map: { (dataSource: DataSource?, tableView: UITableView, index: Int) -> NSString? in
guard let dataSource = dataSource else { return nil }
return bond.titleForHeader(in: index, dataSource: dataSource) as NSString?
})
disposable += tableView.reactive.dataSource.feed(
property: dataSource,
to: #selector(UITableViewDataSource.tableView(_:titleForFooterInSection:)),
map: { (dataSource: DataSource?, tableView: UITableView, index: Int) -> NSString? in
guard let dataSource = dataSource else { return nil }
return bond.titleForFooter(in: index, dataSource: dataSource) as NSString?
})
disposable += tableView.reactive.dataSource.feed(
property: dataSource,
to: #selector(UITableViewDataSource.tableView(_:numberOfRowsInSection:)),
map: { (dataSource: DataSource?, _: UITableView, section: Int) -> Int in
dataSource?.numberOfItems(inSection: section) ?? 0
})
disposable += tableView.reactive.dataSource.feed(
property: dataSource,
to: #selector(UITableViewDataSource.numberOfSections(in:)),
map: { (dataSource: DataSource?, _: UITableView) -> Int in dataSource?.numberOfSections ?? 0 }
)
disposable += bind(to: tableView) { (tableView, event) in
let event = event._unbox
dataSource.value = event.dataSource
bond.apply(event: event, to: tableView)
}
return disposable
}
}
#endif
| 39e228295ad5808eec1447b2ddc6e4f1 | 38.3125 | 163 | 0.73103 | false | false | false | false |
ndevenish/KerbalHUD | refs/heads/master | KerbalHUD/RPMTextFile.swift | mit | 1 | //
// RPMTextFile.swift
// KerbalHUD
//
// Created by Nicholas Devenish on 03/09/2015.
// Copyright © 2015 Nicholas Devenish. All rights reserved.
//
import Foundation
class RPMTextFileWidget : Widget {
private(set) var bounds : Bounds
private(set) var variables : [String]
private let drawing : DrawingTools
private let rpm : RPMTextFile
private var data : [String : Any]? = nil
init(tools : DrawingTools, bounds : Bounds) {
self.bounds = bounds
self.drawing = tools
let url = NSBundle.mainBundle().URLForResource("RPMHUD", withExtension: "txt")
let rpm = RPMTextFile(file: url!)
rpm.prepareTextFor(1.0/20, screenHeight: 1, font: self.drawing.defaultTextRenderer, tools: tools)
self.rpm = rpm
self.variables = rpm.variables
}
func update(data : [String : JSON]) {
var c : [String : Any] = [:]
for (x, y) in data {
c[x] = y
}
self.data = c
}
func draw() {
if let data = self.data {
self.rpm.draw(data)
}
}
}
struct TextDrawInfo {
var position : Point2D
var color : Color4
var size : Float
var string : String
}
protocol PageEntry {
/// Is this entry dynamic, or can it's behaviour change?
var isDynamic : Bool { get }
/// Is this entry always the same length?
var isFixedLength : Bool { get }
/// Can, or does this entry, affect state?
var affectsState : Bool { get }
var affectsOffset : Bool { get }
var affectsTextScale : Bool { get }
var affectsColor : Bool { get }
var affectsFont : Bool { get }
/// What is the length, or at least, current length
var length : Int { get }
var state : FormatState? { get set }
// Position, in lines, where we would expect to start
var position : Point2D? { get set }
var variables : [String] { get }
func process(data : [String : Any]) -> TextDrawInfo
}
class FixedLengthEntry : PageEntry {
private(set) var length : Int
init(length : Int) {
self.length = length
}
var isDynamic : Bool { return false }
var isFixedLength : Bool { return true }
var affectsState : Bool { return false }
var affectsOffset : Bool { return false }
var affectsTextScale : Bool { return false }
var affectsColor : Bool { return false }
var affectsFont : Bool { return false }
var state : FormatState?
var position : Point2D? = nil
let variables : [String] = []
func process(data : [String : Any]) -> TextDrawInfo {
fatalError()
}
}
class EmptyString : FixedLengthEntry {
}
class FixedString : FixedLengthEntry {
private(set) var text : String
init(text: String) {
self.text = text
super.init(length: text.characters.count)
}
override func process(data : [String : Any]) -> TextDrawInfo {
return TextDrawInfo(position: position!+state!.offset, color: state!.color, size: 1, string: text)
}
}
class FormatEntry : PageEntry {
var variable : String
var alignment : Int
var format : String
var variables : [String] { return variable.isEmpty ? [] : [variable] }
private(set) var length : Int
var isDynamic : Bool { return true }
var isFixedLength : Bool { return stringFormatter.fixedLength }
var affectsState : Bool { return affectsOffset || affectsTextScale || affectsColor || affectsFont }
private(set) var affectsOffset : Bool
private(set) var affectsTextScale : Bool
private(set) var affectsColor : Bool
private(set) var affectsFont : Bool
var state : FormatState?
var position : Point2D? = nil
var stringFormatter : StringFormatter
init(variable: String, alignment: Int, format: String) {
self.variable = variable
self.alignment = alignment
self.format = format
self.length = 0
stringFormatter = getFormatterForString(format)
if (stringFormatter.fixedLength) {
self.length = stringFormatter.length
}
affectsColor = false
affectsTextScale = false
affectsFont = false
affectsOffset = false
}
func process(data : [String : Any]) -> TextDrawInfo {
let dataVar = "rpm." + variable
return TextDrawInfo(position: position!+state!.offset, color: state!.color, size: 1,
string: stringFormatter.format(data[dataVar]))
}
}
class Tag : FixedLengthEntry {
func changeState(from: FormatState) -> FormatState {
fatalError()
}
// var affectsOffset : Bool { return false }
// var affectsTextScale : Bool { return false }
// var affectsColor : Bool { return false }
// var affectsFont : Bool { return false }
//
override var affectsState : Bool { return true }
init() {
super.init(length: 0)
}
}
class ColorTag : Tag {
var text : String
override var affectsColor : Bool { return true }
init(value : String) {
text = value
}
override func changeState(from: FormatState) -> FormatState {
fatalError()
}
}
class NudgeTag : Tag {
var value : Float
var x : Bool
init(value : Float, x : Bool) {
self.value = value
self.x = x
}
override var affectsOffset : Bool { return true }
override func changeState(from: FormatState) -> FormatState {
if x {
return FormatState(prior: from, offset: Point2D(value, from.offset.y))
} else {
return FormatState(prior: from, offset: Point2D(from.offset.x, value))
}
}
}
class WidthTag : Tag {
enum WidthType {
case Normal
case Half
case Double
}
var type : WidthType = .Normal
init(type : WidthType) {
self.type = type
}
override var affectsTextScale : Bool { return true }
override func changeState(from: FormatState) -> FormatState {
return FormatState(prior: from, textSize: type)
}
}
struct FormatState {
var offset : Point2D
var textSize : WidthTag.WidthType
var color : Color4
var font : String
init(prior: FormatState) {
self.offset = prior.offset
self.textSize = prior.textSize
self.color = prior.color
self.font = prior.font
}
init(prior: FormatState, offset: Point2D) {
self.init(prior: prior)
self.offset = offset
}
init(prior: FormatState, textSize: WidthTag.WidthType) {
self.init(prior: prior)
self.textSize = textSize
}
init() {
self.offset = Point2D(0,0)
self.textSize = .Normal
self.color = Color4.White
self.font = ""
}
}
class RPMTextFile {
private(set) var lineHeight : Float = 0
private(set) var screenHeight : Float = 0
var fixedEntries : [PageEntry] = []
var dynamicEntries : [PageEntry] = []
var dynamicLines : [[PageEntry]] = []
let textFileData : String
var text : TextRenderer? = nil
var drawing : DrawingTools? = nil
private(set) var variables : [String] = []
convenience init(file : NSURL) {
let data = NSData(contentsOfURL: file)
let s = NSString(bytes: data!.bytes, length: data!.length, encoding: NSUTF8StringEncoding)! as String
self.init(data: s)
}
init(data : String) {
textFileData = data
}
func prepareTextFor(lineHeight : Float, screenHeight : Float, font : TextRenderer, tools: DrawingTools) {
self.lineHeight = lineHeight
self.screenHeight = screenHeight
let fW : Float = 16//lineHeight * font.aspect * 0.5
text = font
drawing = tools
let reSplit = try! NSRegularExpression(pattern: "^(.+?)(?:\\$&\\$\\s*(.+))?$", options: NSRegularExpressionOptions())
var allLines : [[PageEntry]] = []
// for line in data.s
let lines = textFileData.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
for (i, line) in lines.enumerate() {
var lineEntries : [PageEntry] = []
if let match = reSplit.firstMatchInString(line, options: NSMatchingOptions(), range: NSRange(location: 0, length: line.characters.count)) {
let nss = line as NSString
let formatString = nss.substringWithRange(match.rangeAtIndex(1))
let variables : [String]
if match.rangeAtIndex(2).location != NSNotFound {
variables = nss.substringWithRange(match.rangeAtIndex(2))
.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
} else {
variables = []
}
self.variables.appendContentsOf(variables)
print ("\(i) Vars: ", variables)
lineEntries.appendContentsOf(parseWholeFormattingLine(formatString, variables: variables))
// } else {
// // No formatting variables. pass the whole thing
// lineEntries.appendContentsOf(parseWholeFormattingLine(line, variables: []))
}
print ("Processed line: ", lineEntries)
allLines.append(lineEntries)
}
print("Done")
// Now, go over each line, and reduce down to dynamic entries only
var fixedEntries : [PageEntry] = []
// Lines with only dynamic entries remaining
var dynamicLines : [[PageEntry]] = []
// Dynamic entries that do not affect state
var dynamicEntries : [PageEntry] = []
// var dynamicEntries : [PageEntry] = []
for (lineNum, entries) in allLines.enumerate() {
var state : FormatState = FormatState()
var position : Point2D = Point2D(0,Float(lineNum))
var lineDynamics : [PageEntry] = []
for (j, var entry) in entries.enumerate() {
// Assign the current position and state
// entry.position = position
entry.state = state
entry.position = Point2D(x: position.x*fW, y: screenHeight-(0.5+Float(lineNum))*lineHeight) + state.offset
// If we have a text scale, calculate this now for width calculations
let scale : Float = state.textSize == .Normal ? 1 : (state.textSize == .Half ? 0.5 : 2.0)
position.x += Float(entry.length) * scale
if entry is EmptyString {
// position.x += Float(entry.length) * scale
} else if entry is Tag {
// We have something that can change state
state = (entry as! Tag).changeState(state)
} else if !entry.isDynamic && entry.isFixedLength {
fixedEntries.append(entry)
} else if entry.isFixedLength && !entry.affectsState {
// We are dynamic, but not in a way that affects other items.
dynamicEntries.append(entry)
// position.x += Float(entry.length) * scale
} else {
// We are dynamic, or not fixed length. Skip the rest
for iEntry in j..<entries.count {
lineDynamics.append(entries[iEntry])
}
break
}
}
if !lineDynamics.isEmpty {
// Strip any empty strings off of the end
while lineDynamics.last is EmptyString {
lineDynamics.removeLast()
}
// If a single entry, just shove onto the dynamic pile
if lineDynamics.count == 1 {
dynamicEntries.append(lineDynamics.first!)
} else {
dynamicLines.append(lineDynamics)
}
}
}
self.fixedEntries = fixedEntries
self.dynamicEntries = dynamicEntries
self.dynamicLines = dynamicLines
// Deduplicate the variables
self.variables = Array(Set(self.variables.map({"rpm."+$0})))
}
func parseWholeFormattingLine(line : String, variables : [String]) -> [PageEntry] {
let nss = line as NSString
var entries : [PageEntry] = []
let formatRE = try! NSRegularExpression(pattern: "\\{([^\\}]+)\\}", options: NSRegularExpressionOptions())
// Split all formatting out of this, iteratively
var position = 0
for match in
formatRE.matchesInString(line, options: NSMatchingOptions(), range: NSRange(location: 0, length: nss.length))
{
if match.range.location > position {
let s = nss.substringWithRange(NSRange(location: position, length: match.range.location-position))
// Process anything between the position and this match
entries.appendContentsOf(parsePotentiallyTaggedString(s as String))
position = match.range.location
}
// Append an entry for this variable
entries.append(parseFormatString(nss.substringWithRange(match.rangeAtIndex(1)), variables: variables))
position = match.range.location + match.range.length
}
if position != nss.length {
let remaining = nss.substringFromIndex(position)
entries.appendContentsOf(parsePotentiallyTaggedString(remaining))
}
return entries
}
func parseFormatString(fragment : String, variables : [String]) -> PageEntry {
let fmtRE = Regex(pattern: "(\\d+)(?:,(\\d+))?(?::(.+))?")
let info = fmtRE.firstMatchInString(fragment)!.groups
let variable = variables[Int(info[0])!]
let alignment = Int(info[1] ?? "0") ?? 0
let format = info[2] ?? ""
return FormatEntry(variable: variable, alignment: alignment, format: format)
}
/// Parse a string that contains no variables {} but may contain tags
func parsePotentiallyTaggedString(fragment : String) -> [PageEntry] {
var entries : [PageEntry] = []
// Handle square bracket escaping
let fragment = fragment.stringByReplacingOccurrencesOfString("[[", withString: "[")
let tagRE = try! NSRegularExpression(pattern: "\\[([@\\#hs\\/].+?)\\]", options: NSRegularExpressionOptions())
let matches = tagRE.matchesInString(fragment,
options: NSMatchingOptions(), range: NSRange(location: 0, length: fragment.characters.count))
var position = 0
for match in matches
{
// Handle any intermediate text
if match.range.location > position {
let subS = (fragment as NSString).substringWithRange(NSRange(location: position, length: match.range.location-position))
entries.appendContentsOf(processStringEntry(subS))
position = match.range.location
}
// Handle the tag type
entries.append(processTag((fragment as NSString).substringWithRange(match.rangeAtIndex(1))))
position += match.range.length
}
if position < fragment.characters.count {
let subS = (fragment as NSString).substringFromIndex(position)
entries.appendContentsOf(processStringEntry(subS))
}
return entries
}
func lengthOfSpacesAtFrontOf(string : String) -> UInt {
var charCount : UInt = 0
var idx = string.startIndex
while string[idx] == " " as Character {
charCount += 1
if idx == string.endIndex {
break
}
idx = idx.advancedBy(1)
}
return charCount
}
/// Takes a plain string entry, and splits into an array of potential
/// [Whitespace] [String] [Whitespace] entries
func processStringEntry(var fragment : String) -> [PageEntry] {
if fragment.isWhitespace() {
return [EmptyString(length: fragment.characters.count)]
}
var entries : [PageEntry] = []
let startWhite = lengthOfSpacesAtFrontOf(fragment)
if startWhite > 0 {
entries.append(EmptyString(length: Int(startWhite)))
fragment = fragment.substringFromIndex(fragment.startIndex.advancedBy(Int(startWhite)))
}
let reversed = fragment.characters.reverse().reduce("", combine: { (str : String, ch : Character) -> String in
var news = str
news.append(ch)
return news
})
let endWhite = lengthOfSpacesAtFrontOf(reversed)
if endWhite > 0 {
fragment = fragment.substringToIndex(fragment.endIndex.advancedBy(-Int(endWhite)))
}
entries.append(FixedString(text: fragment))
if endWhite > 0 {
entries.append(EmptyString(length: Int(endWhite)))
}
return entries
}
/// Processes the inner contents of a tag, and returns the page entry
func processTag(fragment : String) -> Tag {
let offsetRE = Regex(pattern: "@([xy])(-?\\d+)")
if let nudge = offsetRE.firstMatchInString(fragment) {
let res = nudge.groups
return NudgeTag(value: Float(res[1])!, x: res[0] == "x")
} else if fragment == "hw" {
return WidthTag(type: .Half)
} else if fragment == "/hw" || fragment == "/dw"{
return WidthTag(type: .Normal)
} else if fragment == "dw" {
return WidthTag(type: .Double)
}
fatalError()
}
func draw(data : [String : Any]) {
// Draw all the fixed positions
for entry in fixedEntries {
let txt = entry.process(data)
drawing!.program.setColor(txt.color)
text?.draw(txt.string, size: lineHeight*txt.size, position: txt.position)
}
}
}
extension String {
func isWhitespace() -> Bool {
let trim = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
return trim.characters.count == 0
}
}
//private let sipRE = Regex(pattern: "SIP(_?)(0?)(\\d+)(?:\\.(\\d+))?")
//
protocol StringFormatter {
func format<T>(item : T) -> String
var fixedLength : Bool { get }
var length : Int { get }
}
//
//class SIFormatter : StringFormatter {
// var spaced : Bool
// var zeroPadded : Bool
// var length : Int
// var precision : Int?
//
// var fixedLength : Bool { return true }
//
// init(format: String) {
// guard let match = sipRE.firstMatchInString(format) else {
// fatalError()
// }
// // We have an SI processing entry.
// var parts = match.groups
// spaced = parts[0] != ""
// zeroPadded = parts[1] == "0"
// length = Int(parts[2])!
// precision = parts[3] == "" ? nil : Int(parts[3])!
// }
//
//// var length : Int { return length }
//
// func format<T>(item : T) -> String {
// fatalError()
// }
//}
//
class DefaultStringFormatter : StringFormatter {
var fixedLength : Bool { return false }
var length : Int { return 0 }
func format<T>(item: T) -> String {
return String(item)
}
}
//
func getFormatterForString(format: String) -> StringFormatter {
// if let _ = sipRE.firstMatchInString(format) {
// return SIFormatter(format: format)
// }
return DefaultStringFormatter()
} | e16ef68a3b84a04c4e9f7b2e4bb976f1 | 30.154657 | 145 | 0.646339 | false | false | false | false |
YouareMylovelyGirl/Sina-Weibo | refs/heads/Develop | 新浪微博/新浪微博/Classes/Tools(工具)/NetManager/NetManager+Extension.swift | apache-2.0 | 1 | //
// NetManager+Extension.swift
// 新浪微博
//
// Created by 阳光 on 2017/6/7.
// Copyright © 2017年 YG. All rights reserved.
//
import Foundation
//封装新浪微博的网络请求方法
extension NetManager {
/// 加载微博字典数据
/// - since_id: 则返回ID比since_id大的微博(即比since_id时间晚的微博),默认为0。
/// - max_id: 则返回ID小于或等于max_id的微博,默认为0。
/// - Parameter completionHandler: 完成回调 [list: 微博字典数组/错误信息]
func stausList( since_id: Int64 = 0, max_id: Int64 = 0, completionHandler: @escaping (_ list: [[String: AnyObject]]?, _ error : NSError? ) -> ()) {
//用AFN加载网络数据
let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
// let params = ["access_token": "2.00UCb9cD0VJ8eC0a8a9bbdf5S6IHwC"]
//Swift 中 Int 可以转换成AnyObject / 但是Int64 不行, 但是可以将Int64 装换成字符串
let params = ["since_id": "\(since_id)",
"max_id": "\(max_id > 0 ?max_id - 1 : 0)"]
//提示: 服务器返回的字典, 就是按照时间倒序排序的
tokenRequest(url: urlString, params: params) { (json, error) in
let result = json?["statuses"] as? [[String: AnyObject]]
completionHandler(result, error as NSError?)
}
}
//定时刷新不需要提示失败
///返回微博的未读数量
func unreadCount(completionHandler:@escaping (_ count: Int)->()) {
guard let uid = userAccount.uid else { return }
let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
let params = ["uid": uid]
tokenRequest(url: urlString, params: params) { (data, error) in
let dic = data as [String: AnyObject]?
let count = dic?["status"] as? Int
completionHandler(count ?? 0)
}
}
}
//MARK: - OAuth相关方法
extension NetManager {
//加载accessToken
/// 加载AccessToken
///
/// - Parameters:
/// - code: 授权码
/// - completionHandler: 完成回调
func loadAccessToken(code: String, completionHandler:@escaping (_ isSuccess: Bool)->()) {
let urlString = "https://api.weibo.com/oauth2/access_token"
let params = ["client_id": APPKey,
"client_secret": APPSecret,
"grant_type": "authorization_code",
"code": code,
"redirect_uri": RedirectURI]
//发起网络请求
request(requestType: .POST, url: urlString, params: params) { (data, error) in
//直接用字典设置 userAccount属性
self.userAccount.yy_modelSet(with: (data as [String: AnyObject]?) ?? [:])
print(self.userAccount)
//加载用户信息
self.loadUserInfo(completionHandler: { (dict) in
//使用用户信息字典设置用户账户信息, 设置昵称和头像地址
self.userAccount.yy_modelSet(with: dict)
//保存模型
self.userAccount.saceAccount()
print(self.userAccount)
//等用户信息加载完成后再 完成回调
if error == nil {
completionHandler(true)
} else {
completionHandler(false)
}
})
}
}
}
extension NetManager {
///加载当前用户信息 - 用户登录后立即执行
func loadUserInfo(completionHandler:@escaping (_ dict: [String: AnyObject])->()) {
guard let uid = userAccount.uid else {
return
}
let urlString = "https://api.weibo.com/2/users/show.json"
let params = ["uid": uid]
//发起网络请求
tokenRequest(url: urlString, params: params) { (data, error) in
completionHandler(data as [String : AnyObject]? ?? [:])
}
}
}
| 3c1cdf4f9274ec4fe3a19b00aa1eee60 | 29.747967 | 151 | 0.513749 | false | false | false | false |
BeanstalkData/beanstalk-ios-sdk | refs/heads/master | Example/BeanstalkEngageiOSSDK/ProfileViewController.swift | mit | 1 | //
// ProfileViewController.swift
// BeanstalkEngageiOSSDK
//
// 2016 Heartland Commerce, Inc. All rights reserved.
//
import UIKit
import BeanstalkEngageiOSSDK
class ProfileViewController: BaseViewController, CoreProtocol, EditProfileProtocol {
var contact: ContactModel?
var updateContactRequest: UpdateContactRequest?
@IBOutlet var nameLabel: UILabel!
@IBOutlet var emailLabel: UILabel!
@IBOutlet var genderSegment: UISegmentedControl!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if self.contact == nil {
self.loadProfile()
}
else {
self.updateProfile()
}
}
//MARK: - Private
func loadProfile() {
self.coreService?.getContact(self, handler: { (contact) in
if contact != nil {
self.contact = contact as? ContactModel
self.updateProfile()
}
})
}
func updateProfile() {
let updateRequest = UpdateContactRequest(contact: self.contact)
self.updateContactRequest = updateRequest
self.nameLabel.text = self.contact?.getFullName()
self.emailLabel.text = updateRequest.email
if self.updateContactRequest?.gender == "Male" {
self.genderSegment.selectedSegmentIndex = 0
}
else if self.updateContactRequest?.gender == "Female" {
self.genderSegment.selectedSegmentIndex = 1
}
else {
self.genderSegment.selectedSegmentIndex = 2
}
}
//MARK: - Actions
@IBAction func genderAction() {
switch self.genderSegment.selectedSegmentIndex {
case 0:
self.updateContactRequest?.gender = "Male"
case 1:
self.updateContactRequest?.gender = "Female"
default:
self.updateContactRequest?.gender = "Unknown"
}
}
@IBAction func saveContactAction() {
if let cont = self.contact {
if let upd = self.updateContactRequest {
self.coreService?.updateContact(self, original: cont, request: upd, handler: { (success) in
if success {
self.loadProfile()
}
})
}
}
}
}
| a2ac0a19edebd382924492bf554913a4 | 22.75 | 99 | 0.653589 | false | false | false | false |
EGF2/ios-client | refs/heads/master | EGF2/EGF2/Graph/EGF2Graph+WebSocket.swift | mit | 1 | //
// EGF2Graph+WebSocket.swift
// EGF2
//
// Created by LuzanovRoman on 12.01.17.
// Copyright © 2017 EigenGraph. All rights reserved.
//
import Foundation
class EGF2Subscription {
var isSent = false
var observerPointers = [UnsafeRawPointer]()
var isNoObservers: Bool {
return observerPointers.isEmpty
}
static func pointer(forObserver observer: NSObject) -> UnsafeRawPointer {
return UnsafeRawPointer(Unmanaged.passUnretained(observer).toOpaque())
}
static func observer(fromPointer pointer: UnsafeRawPointer) -> NSObject {
return Unmanaged<NSObject>.fromOpaque(pointer).takeUnretainedValue()
}
init(isSent: Bool, observers: [NSObject]) {
self.isSent = isSent
self.observerPointers = observers.map( {EGF2Subscription.pointer(forObserver: $0)} )
}
func add(_ observer: NSObject) {
let pointer = EGF2Subscription.pointer(forObserver: observer)
if let _ = observerPointers.first(where: {$0 == pointer}) { return }
observerPointers.append(EGF2Subscription.pointer(forObserver: observer))
}
func remove(_ observer: NSObject) {
let pointer = EGF2Subscription.pointer(forObserver: observer)
guard let ptr = observerPointers.first(where: {$0 == pointer}) else { return }
observerPointers.remove(ptr)
}
func contains(_ observer: NSObject) -> Bool {
let pointer = EGF2Subscription.pointer(forObserver: observer)
return observerPointers.first(where: {$0 == pointer}) != nil
}
}
extension EGF2Graph: WebSocketDelegate {
// MARK: - Private methods
fileprivate func startPing() {
if let timer = webSocketPingTimer {
timer.invalidate()
}
webSocketPingTimer = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { [weak self] (timer) in
guard let socket = self?.webSocket else { return }
socket.write(ping: Data())
}
}
fileprivate func stopPing() {
webSocketPingTimer?.invalidate()
webSocketPingTimer = nil
}
// Send JSON for subscribe/unsubscribe a specific object
// Returns false if subscription wasn't sent
fileprivate func updateSubscription(subscribe: Bool, forObjecWithId id: String) -> Bool {
guard let socket = webSocket, socket.isConnected else { return false }
let action = subscribe ? "subscribe" : "unsubscribe"
guard let data = Data(jsonObject:[action:[["object_id":id]]]) else { return false }
guard let string = String(data: data, encoding: .utf8) else { return false }
socket.write(string: string)
if showLogs {
print("EGF2Graph. Sent json: \(string).")
}
return true
}
// Send JSON for subscribe/unsubscribe a specific edge
// Returns false if subscription wasn't sent
fileprivate func updateSubscription(subscribe: Bool, forSourceWithId id: String, andEdge edge: String) -> Bool {
guard let socket = webSocket, socket.isConnected else { return false}
let action = subscribe ? "subscribe" : "unsubscribe"
guard let data = Data(jsonObject:[action:[["edge":["source":id,"name":edge]]]]) else { return false }
guard let string = String(data: data, encoding: .utf8) else { return false }
socket.write(string: string)
if showLogs {
print("EGF2Graph. Sent json: \(string).")
}
return true
}
fileprivate func subscribe(observer: NSObject, key: String, subscribe: () -> Bool) {
guard let subscription = subscriptions[key] else {
subscriptions[key] = EGF2Subscription(isSent: subscribe(), observers: [observer])
return
}
// Add new observer (if needed)
subscription.add(observer)
}
fileprivate func unsubscribe(observer: NSObject, key: String, unsubscribe: () -> () ) {
guard let subscription = subscriptions[key] else { return }
subscription.remove(observer)
if subscription.isNoObservers {
if subscription.isSent {
unsubscribe()
}
subscriptions[key] = nil
}
}
// MARK: - Internal methods
func subscribe(observer: NSObject, forObjectWithId id: String) {
subscribe(observer: observer, key: id) { () -> Bool in
updateSubscription(subscribe: true, forObjecWithId: id)
}
}
func subscribe(observer: NSObject, forSourceWithId id: String, andEdge edge: String) {
subscribe(observer: observer, key: "\(id)|\(edge)") { () -> Bool in
updateSubscription(subscribe: true, forSourceWithId: id, andEdge: edge)
}
}
func unsubscribe(observer: NSObject, fromObjectWithId id: String) {
unsubscribe(observer: observer, key: id) {
_ = updateSubscription(subscribe: false, forObjecWithId: id)
}
}
func unsubscribe(observer: NSObject, fromSourceWithId id: String, andEdge edge: String) {
unsubscribe(observer: observer, key: "\(id)|\(edge)") {
_ = updateSubscription(subscribe: false, forSourceWithId: id, andEdge: edge)
}
}
func subscribe(observer: NSObject, forObjectsWithIds ids: [String]) {
var subscribe = [[String: Any]]()
let isConnected = webSocket?.isConnected ?? false
for id in ids {
// If there is a subscription just add new observer (if needed)
if let subscription = subscriptions[id] {
subscription.add(observer)
} else {
// Add a new subscription
subscriptions[id] = EGF2Subscription(isSent: isConnected, observers: [observer])
subscribe.append(["object_id":id])
}
}
// If we need to subscribe for the new objects
if subscribe.count > 0 && isConnected {
if let data = Data(jsonObject:["subscribe":subscribe]), let string = String(data: data, encoding: .utf8) {
webSocket?.write(string: string)
if showLogs {
print("EGF2Graph. Sent json: \(string).")
}
}
}
}
// Unsubscribe observer from all subscriptions
// Send unsubscribe message via websocket if needed
func unsubscribe(observer: NSObject) {
var unsubscribe = [[String: Any]]()
for (key, subscription) in subscriptions {
if !subscription.contains(observer) {
continue
}
subscription.remove(observer)
if !subscription.isNoObservers {
continue
}
if subscription.isSent {
let components = key.components(separatedBy: "|")
// Just object id
if components.count == 1 {
guard let id = components.first else { return }
unsubscribe.append(["object_id":id])
// Object id and edge
} else {
guard let id = components.first, let edge = components.last else { return }
unsubscribe.append(["edge":["source":id,"name":edge]])
}
}
subscriptions[key] = nil
}
if unsubscribe.count > 0 {
if let data = Data(jsonObject:["unsubscribe":unsubscribe]), let string = String(data: data, encoding: .utf8) {
webSocket?.write(string: string)
if showLogs {
print("EGF2Graph. Sent json: \(string).")
}
}
}
}
// MARK: -
func webSocketConnect() {
guard let url = webSocketURL, let token = account.userToken else { return }
// Is already have a connected socket?
if let socket = webSocket, socket.isConnected { return }
// Is already connecting?
if webSocketIsConnecting { return }
// Create a new socket and connect it
webSocketIsConnecting = true
webSocket = WebSocket(url: url)
webSocket?.headers["Authorization"] = token
webSocket?.delegate = self
webSocket?.connect()
}
func webSocketDisonnect() {
webSocket?.disconnect()
}
// MARK:- WebSocketDelegate
public func websocketDidConnect(socket: WebSocket) {
webSocketIsConnecting = false
var subscribe = [[String: Any]]()
for (key, subscription) in subscriptions {
if !subscription.isSent {
let components = key.components(separatedBy: "|")
// Just object id
if components.count == 1 {
guard let id = components.first else { return }
subscribe.append(["object_id":id])
// Object id and edge
} else {
guard let id = components.first, let edge = components.last else { return }
subscribe.append(["edge":["source":id,"name":edge]])
}
subscription.isSent = true
}
}
if subscribe.count > 0 {
if let data = Data(jsonObject:["subscribe":subscribe]), let string = String(data: data, encoding: .utf8) {
socket.write(string: string)
if showLogs {
print("EGF2Graph. Sent json: \(string).")
}
}
}
startPing()
if showLogs {
print("EGF2Graph. Websocket connected to \(socket.currentURL.absoluteString).")
}
}
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
webSocketIsConnecting = false
for (_, subscription) in subscriptions {
subscription.isSent = false
}
stopPing()
if showLogs {
print("EGF2Graph. Websocket disconnected from \(socket.currentURL.absoluteString).")
}
}
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
guard let json = text.data(using: .utf8)?.jsonObject() as? [String: Any] else { return }
guard let method = json["method"] as? String else { return }
if let objectId = json["object"] as? String {
if method == "PUT" {
guard let dictionary = json["current"] as? [String: Any] else { return }
self.internalUpdateObject(withId: objectId, dictionary: dictionary, completion: nil)
} else if method == "DELETE" {
self.internalDeleteObject(withId: objectId, completion: nil)
}
} else if let edge = json["edge"] as? [String: String], let src = edge["src"], let dst = edge["dst"], let name = edge["name"] {
if method == "POST" {
self.internalAddObject(withId: dst, forSource: src, toEdge: name, completion: nil)
} else if method == "DELETE" {
self.internalDeleteObject(withId: dst, forSource: src, fromEdge: name, completion: nil)
}
}
}
public func websocketDidReceiveData(socket: WebSocket, data: Data) {
// Nothing here
}
}
| 448b05c192f855b5e7d3e0c20c09b2e9 | 36.766447 | 135 | 0.570769 | false | false | false | false |
Ben-G/Argo | refs/heads/master | ArgoTests/Tests/SwiftDictionaryDecodingTests.swift | mit | 10 | import XCTest
import Argo
class SwiftDictionaryDecodingTests: XCTestCase {
func testDecodingAllTypesFromSwiftDictionary() {
let typesDict = [
"numerics": [
"int": 5,
"int64": 9007199254740992,
"double": 3.4,
"float": 1.1,
"int_opt": 4
],
"bool": false,
"string_array": ["hello", "world"],
"embedded": [
"string_array": ["hello", "world"],
"string_array_opt": []
],
"user_opt": [
"id": 6,
"name": "Cooler User"
]
]
let model: TestModel? = decode(typesDict)
XCTAssert(model != nil)
XCTAssert(model?.numerics.int == 5)
XCTAssert(model?.numerics.int64 == 9007199254740992)
XCTAssert(model?.numerics.double == 3.4)
XCTAssert(model?.numerics.float == 1.1)
XCTAssert(model?.numerics.intOpt != nil)
XCTAssert(model?.numerics.intOpt! == 4)
XCTAssert(model?.string == "Cooler User")
XCTAssert(model?.bool == false)
XCTAssert(model?.stringArray.count == 2)
XCTAssert(model?.stringArrayOpt == nil)
XCTAssert(model?.eStringArray.count == 2)
XCTAssert(model?.eStringArrayOpt != nil)
XCTAssert(model?.eStringArrayOpt?.count == 0)
XCTAssert(model?.userOpt != nil)
XCTAssert(model?.userOpt?.id == 6)
}
}
| dd3949cc2758324e12e1b577c7f4ef79 | 27.688889 | 56 | 0.597211 | false | true | false | false |
cubixlabs/GIST-Framework | refs/heads/master | GISTFramework/Classes/BaseClasses/BaseUINavigationItem.swift | agpl-3.0 | 1 | //
// BaseUINavigationItem.swift
// GISTFramework
//
// Created by Shoaib Abdul on 14/07/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
/// BaseUINavigationItem is a subclass of UINavigationItem and implements BaseView. It has some extra proporties and support for SyncEngine.
open class BaseUINavigationItem: UINavigationItem, BaseView {
//MARK: - Properties
/// Overriden title property to set title from SyncEngine (Hint '#' prefix).
override open var title: String? {
get {
return super.title;
}
set {
if let key:String = newValue , key.hasPrefix("#") == true {
super.title = SyncedText.text(forKey: key);
} else {
super.title = newValue;
}
}
} //P.E.
//MARK: - Constructors
/// Overridden constructor to setup/ initialize components.
///
/// - Parameter title: Title of Navigation Item
public override init(title: String) {
super.init(title: title);
} //F.E.
/// Required constructor implemented.
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
} //F.E.
//MARK: - Overridden Methods
/// Overridden method to setup/ initialize components.
open override func awakeFromNib() {
super.awakeFromNib();
self.commontInit();
} //F.E.
/// Common initazier for setting up items.
private func commontInit() {
if let txt:String = self.title , txt.hasPrefix("#") == true {
self.title = txt; // Assigning again to set value from synced data
}
} //F.E.
} //CLS END
| e935eb7870e9ed06e6ffddee9dd6bdeb | 27.377049 | 140 | 0.589832 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/MaxWidthSelectionTableViewCell.swift | apache-2.0 | 3 | //
// MaxWidthSelectionTableViewCell.swift
// SwiftEntryKit_Example
//
// Created by Daniel Huri on 4/26/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
class MaxWidthSelectionTableViewCell: SelectionTableViewCell {
override func configure(attributesWrapper: EntryAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "Max Width"
descriptionValue = "Describes the entry's maximum width limitation. It can stretch to the width of the screen, get screen edge less 40pts, or be 90% of the screen width"
insertSegments(by: ["Stretch", "Min Edge", "90% Screen"])
selectSegment()
}
private func selectSegment() {
switch attributesWrapper.attributes.positionConstraints.maxSize.width {
case .offset(value: _):
segmentedControl.selectedSegmentIndex = 0
case .constant(value: _):
segmentedControl.selectedSegmentIndex = 1
case .ratio(value: 0.9):
segmentedControl.selectedSegmentIndex = 2
default:
break
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
attributesWrapper.attributes.positionConstraints.maxSize.width = .offset(value: 0)
case 1:
attributesWrapper.attributes.positionConstraints.maxSize.width = .constant(value: UIScreen.main.minEdge - 40)
case 2:
attributesWrapper.attributes.positionConstraints.maxSize.width = .ratio(value: 0.9)
default:
break
}
}
}
| 8443c8a214cfb0f27dde4841fd31b899 | 35.577778 | 177 | 0.664642 | false | false | false | false |
josve05a/wikipedia-ios | refs/heads/develop | Wikipedia/Code/WelcomeContainerViewController.swift | mit | 4 | import UIKit
protocol WelcomeContainerViewControllerDataSource: AnyObject {
var animationView: WelcomeAnimationView { get }
var panelViewController: WelcomePanelViewController { get }
var isFirst: Bool { get }
}
extension WelcomeContainerViewControllerDataSource {
var isFirst: Bool {
return false
}
}
class WelcomeContainerViewController: UIViewController {
weak var dataSource: WelcomeContainerViewControllerDataSource?
@IBOutlet private weak var topContainerView: UIView!
@IBOutlet private weak var bottomContainerView: UIView!
private var theme = Theme.standard
init(dataSource: WelcomeContainerViewControllerDataSource) {
self.dataSource = dataSource
super.init(nibName: "WelcomeContainerViewController", bundle: Bundle.main)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
guard let dataSource = dataSource else {
assertionFailure("dataSource should be set by now")
apply(theme: theme)
return
}
addChild(WelcomeAnimationViewController(animationView: dataSource.animationView, waitsForAnimationTrigger: dataSource.isFirst), to: topContainerView)
addChild(dataSource.panelViewController, to: bottomContainerView)
apply(theme: theme)
}
private func addChild(_ viewController: UIViewController?, to view: UIView) {
guard
let viewController = viewController,
viewController.parent == nil,
viewIfLoaded != nil
else {
return
}
addChild(viewController)
viewController.view.translatesAutoresizingMaskIntoConstraints = false
view.wmf_addSubviewWithConstraintsToEdges(viewController.view)
viewController.didMove(toParent: self)
(viewController as? Themeable)?.apply(theme: theme)
}
}
extension WelcomeContainerViewController: Themeable {
func apply(theme: Theme) {
guard viewIfLoaded != nil else {
self.theme = theme
return
}
children.forEach { ($0 as? Themeable)?.apply(theme: theme) }
topContainerView.backgroundColor = theme.colors.midBackground
bottomContainerView.backgroundColor = theme.colors.midBackground
}
}
extension WelcomeContainerViewController: PageViewControllerViewLifecycleDelegate {
func pageViewControllerDidAppear(_ pageViewController: UIPageViewController) {
dataSource?.animationView.animate()
}
}
| f17b75cb175c6eb56180076b617a0a04 | 33.513158 | 157 | 0.698437 | false | false | false | false |
githubError/KaraNotes | refs/heads/master | KaraNotes/KaraNotes/WriteArticle/View/CPFPreviewHeaderView.swift | apache-2.0 | 1 | //
// CPFHeaderView.swift
// KaraNotes
//
// Created by 崔鹏飞 on 2017/4/16.
// Copyright © 2017年 崔鹏飞. All rights reserved.
//
import UIKit
protocol CPFPreviewHeaderViewDelegate {
func headerView(headerView: UIView, didClickDismissBtn dismissBtn: UIButton)
func headerView(headerView: UIView, didClickExportBtn dismissBtn: UIButton)
}
class CPFPreviewHeaderView: UIView {
fileprivate var titleLabel:UILabel!
fileprivate var dismissBtn:UIButton!
fileprivate var exportBtn:UIButton!
var delegate:CPFPreviewHeaderViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
extension CPFPreviewHeaderView {
fileprivate func setupSubviews(frame: CGRect) -> Void {
backgroundColor = CPFNavColor
dismissBtn = UIButton(type: .custom)
dismissBtn.setImage(UIImage.init(named: "dismissBtn"), for: .normal)
dismissBtn.addTarget(self, action: #selector(dismissBtnClick), for: .touchUpInside)
addSubview(dismissBtn)
dismissBtn.snp.makeConstraints { (mark) in
mark.width.height.equalTo(30)
mark.centerY.equalTo(self.snp.centerY).offset(10)
mark.left.equalTo(15)
}
titleLabel = UILabel()
addSubview(titleLabel)
titleLabel.text = CPFLocalizableTitle("previewArticle_title")
titleLabel.font = CPFPingFangSC(weight: .semibold, size: 18)
titleLabel.textColor = UIColor.white
titleLabel.textAlignment = .center
titleLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(dismissBtn.snp.centerY)
make.width.equalTo(60)
make.height.equalTo(35)
make.centerX.equalToSuperview()
}
exportBtn = UIButton(type: .custom)
addSubview(exportBtn)
exportBtn.titleLabel?.font = CPFPingFangSC(weight: .regular, size: 14)
exportBtn.setTitle(CPFLocalizableTitle("previewArticle_export"), for: .normal)
exportBtn.setTitleColor(UIColor.white, for: .normal)
exportBtn.addTarget(self, action: #selector(exportBtnClick), for: .touchUpInside)
exportBtn.snp.makeConstraints { (make) in
make.centerY.equalTo(dismissBtn.snp.centerY)
make.width.equalTo(40)
make.height.equalTo(25)
make.right.equalToSuperview().offset(-10)
}
}
}
extension CPFPreviewHeaderView {
@objc fileprivate func dismissBtnClick() -> Void {
delegate?.headerView(headerView: self, didClickDismissBtn: dismissBtn)
}
@objc fileprivate func exportBtnClick() -> Void {
delegate?.headerView(headerView: self, didClickExportBtn: exportBtn)
}
}
| 4fcb2efa398b7a48587fcf471b0fa57a | 31.908046 | 91 | 0.661893 | false | false | false | false |
antonio081014/LeetCode-CodeBase | refs/heads/main | Swift/baseball-game.swift | mit | 1 | /**
* https://leetcode.com/problems/baseball-game/
*
*
*/
// Date: Sat Apr 9 23:27:59 PDT 2022
class Solution {
func calPoints(_ ops: [String]) -> Int {
var result = [Int]()
for op in ops {
if op == "+" {
let n = result.count
let sum = result[n - 1] + result[n - 2]
result.append(sum)
} else if op == "D" {
let d = result[result.count - 1] * 2
result.append(d)
} else if op == "C" {
result.removeLast()
} else {
result.append(Int(op)!)
}
// print(result)
}
return result.reduce(0) { $0 + $1 }
}
} | e796149d157edd16aff34a037a166623 | 26 | 55 | 0.410714 | false | false | false | false |
hetefe/HTF_sina_swift | refs/heads/master | sina_htf/sina_htf/Classes/Module/Home/StatusCell/StatusCellBottomView.swift | mit | 1 | //
// StatusCellBottomView.swift
// sina_htf
//
// Created by 赫腾飞 on 15/12/18.
// Copyright © 2015年 hetefe. All rights reserved.
//
import UIKit
class StatusCellBottomView: UIView {
override init(frame:CGRect) {
super.init(frame: frame)
// backgroundColor = UIColor(white: 0.3, alpha: 1)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI(){
addSubview(retweetedBtn)
addSubview(composeBtn)
addSubview(likeBtn)
//MARK:- 设置约束
retweetedBtn.snp_makeConstraints { (make) -> Void in
make.top.left.bottom.equalTo(self)
}
composeBtn.snp_makeConstraints { (make) -> Void in
make.left.equalTo(retweetedBtn.snp_right)
make.top.bottom.equalTo(self)
make.width.equalTo(retweetedBtn.snp_width)
}
likeBtn.snp_makeConstraints { (make) -> Void in
make.left.equalTo(composeBtn.snp_right)
make.right.equalTo(self.snp_right)
make.top.bottom.equalTo(self)
make.width.equalTo(composeBtn.snp_width)
}
let sepView1 = sepView()
let sepView2 = sepView()
//添加
addSubview(sepView1)
addSubview(sepView2)
//设置约束
let w = 0.5
let scale = 0.4
sepView1.snp_makeConstraints { (make) -> Void in
make.left.equalTo(retweetedBtn.snp_right)
make.height.equalTo(self.snp_height).multipliedBy(scale)
make.centerY.equalTo(self.snp_centerY)
make.width.equalTo(w)
}
sepView2.snp_makeConstraints { (make) -> Void in
make.left.equalTo(composeBtn.snp_right)
make.height.equalTo(self.snp_height).multipliedBy(scale)
make.centerY.equalTo(self.snp_centerY)
make.width.equalTo(w)
}
}
//MARK:- 生成分割线的方法
private func sepView() -> UIView{
let v = UIView()
v.backgroundColor = UIColor.darkGrayColor()
return v
}
//MARK:- 懒加载视图
private lazy var retweetedBtn: UIButton = UIButton(backImageNameN: nil, backImageNameH: nil, color: UIColor.darkGrayColor(), title: "转发", fontOfSize: 10, imageName: "timeline_icon_retweet")
private lazy var composeBtn: UIButton = UIButton(backImageNameN: nil, backImageNameH: nil, color: UIColor.darkGrayColor(), title: "评论", fontOfSize: 10, imageName: "timeline_icon_comment")
private lazy var likeBtn: UIButton = UIButton(backImageNameN: nil, backImageNameH: nil, color: UIColor.darkGrayColor(), title: "赞", fontOfSize: 10, imageName: "timeline_icon_unlike")
}
| 0cebbfae992da3d5e582e61a060de0a0 | 29.630435 | 193 | 0.598297 | false | false | false | false |
istyle-inc/LoadMoreTableViewController | refs/heads/master | Pod/Classes/FooterCell.swift | mit | 1 | import UIKit
public class FooterCell: UITableViewCell {
@IBOutlet private weak var activityIndecator: UIActivityIndicatorView!
@IBOutlet weak var retryButton: UIButton!
var showsRetryButton = false {
didSet {
if showsRetryButton {
activityIndecator.isHidden = true
retryButton.isHidden = false
} else {
activityIndecator.isHidden = false
retryButton.isHidden = true
}
}
}
var retryButtonTapped: (() -> ())?
public override func awakeFromNib() {
super.awakeFromNib()
showsRetryButton = false
}
override public func layoutSubviews() {
super.layoutSubviews()
activityIndecator.startAnimating()
}
@IBAction func retryButtonTapped(_ sender: UIButton) {
retryButtonTapped?()
}
}
| 607b877cff49bdcfc5f7c5a6b0c13ddd | 22.837838 | 74 | 0.602041 | false | false | false | false |
amieka/FlickStream | refs/heads/master | FlickStream/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// FlickStream
//
// Created by Arunoday Sarkar on 6/4/16.
// Copyright © 2016 Sark Software LLC. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController(rootViewController: InterestingnessViewController())
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 throttle down OpenGL ES frame rates. 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 inactive 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 applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.arunoday.FlickStream" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("FlickStream", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 06a1e07498d882f622fe05f38a3ed4ab | 51.921053 | 288 | 0.755511 | false | false | false | false |
jcfausto/transit-app | refs/heads/master | TransitApp/TransitApp/RouteSegmentsDetailViewController.swift | mit | 1 | //
// RouteSegmentsDetailViewController.swift
// TransitApp
//
// Created by Julio Cesar Fausto on 26/02/16.
// Copyright © 2016 Julio Cesar Fausto. All rights reserved.
//
import UIKit
import GoogleMaps
import Polyline
import CoreLocation
class RouteSegmentsDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: Properties
var route: Route?
@IBOutlet weak var mapViewContainer: GMSMapView!
// MARK: properties
@IBOutlet weak var routeSegmentsView: RouteSegmentsView!
@IBOutlet weak var routeDurationLabel: UILabel!
@IBOutlet weak var routeSummaryLabel: UILabel!
@IBOutlet weak var segmentsTableView: UITableView!
// MARK: Initialization
override func viewDidLoad() {
super.viewDidLoad()
doFillRouteInformation(self)
initMapView(self)
// Observers
NSNotificationCenter.defaultCenter().addObserver(self, selector:"performSegmentSelection:", name: "RSVButtonTapped", object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Deinitialization
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: TableView protocols compliance
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let route = self.route {
return route.segments.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "RouteSegmentsDetailTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! RouteSegmentsDetailTableViewCell
doInitializeCell(cell, indexPath: indexPath)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
doPlotSegmentOnTheMap(indexPath)
}
}
// MARK: Custom functions
extension RouteSegmentsDetailViewController {
/**
Fill the view with the route information
*/
func doFillRouteInformation(rsViewController: RouteSegmentsDetailViewController) {
if let route = rsViewController.route {
rsViewController.navigationItem.title = route.provider
rsViewController.routeSegmentsView.segments = route.segments
rsViewController.routeSummaryLabel.text = route.summary
rsViewController.routeDurationLabel.text = route.duration.stringValueInMinutes
}
}
// MARK: Cell initialization
func doInitializeCell(cell: RouteSegmentsDetailTableViewCell, indexPath: NSIndexPath) {
if let route = self.route {
let segment = route.segments[indexPath.row]
let firstStop = route.segments[indexPath.row].stops.first
let lastStop = route.segments[indexPath.row].stops.last
//Segment vertical line color
cell.segmentDetailVerticalLineView.fillColor = segment.color
//Segment duration in minutes
if let firstStop = firstStop, lastStop = lastStop {
cell.segmentEstimatedDurationLabel.text = lastStop.time.timeIntervalSinceDate(firstStop.time).stringValueInMinutes
}
//Departure and arrival information
if let firstStop = firstStop {
cell.segmentTimeLabel.text = "Departure at \(firstStop.time.stringValueWithHourAndMinute)"
if let name = firstStop.name {
if (!name.isEmpty) {
cell.segmentNameLabel.text = "starting at \(name)"
}
}
var destinationSummary: String = ""
if (!segment.travelMode.isEmpty) {
destinationSummary = destinationSummary + "\(segment.travelMode)"
}
if let lastStop = lastStop {
if let name = lastStop.name {
if (!name.isEmpty) {
var prepString = "to"
if segment.isSetupStop() {
prepString = "at"
}
destinationSummary = destinationSummary + " \(prepString) \(name)"
}
}
}
cell.segmentTravelModeLabel.text = destinationSummary
}
//Last segment additional information
if indexPath.row == route.segments.count-1 {
if let lastStop = lastStop {
cell.segmentFinishTimeLabel.text = "Estimated arrival at \(lastStop.time.stringValueWithHourAndMinute)"
cell.segmentDetailVerticalLineView.lastSegment = true
}
}
}
}
// MARK: Map initialization, centered initially for the purpose of this application in Berlin
func initMapView(rsViewController: RouteSegmentsDetailViewController) {
//This initial center position could come from a .plist config file.
let camera = GMSCameraPosition.cameraWithLatitude(52.524370, longitude: 13.410530, zoom: 15)
rsViewController.mapViewContainer.camera = camera
rsViewController.mapViewContainer.myLocationEnabled = true
}
/**
Plot a segment on the map
*/
func doPlotSegmentOnTheMap(indexPath: NSIndexPath) {
if let route = self.route {
let selectedSegment: Segment = route.segments[indexPath.row]
//If the segment doesn't have a polyline, means that is a stop in the same place
//for some acton (bike or car returnin, car setup, etc)
if (!selectedSegment.polyline.isEmpty) {
let decodePolyline = Polyline(encodedPolyline: selectedSegment.polyline)
let decodedPath: [CLLocationCoordinate2D]? = decodePolyline.coordinates
let path = GMSMutablePath()
if let decodedPath = decodedPath {
for location in decodedPath {
path.addCoordinate(location)
}
}
let polyline = GMSPolyline(path: path)
polyline.strokeColor = selectedSegment.color
polyline.strokeWidth = 2.0
var locationPosition = path.coordinateAtIndex(0) //First location
switch indexPath.row {
case 0:
let marker = GMSMarker(position: locationPosition)
marker.icon = GMSMarker.markerImageWithColor(selectedSegment.color)
marker.title = selectedSegment.name
marker.map = self.mapViewContainer
//When there's only one segment, the index row 0 represents both the starting
//and stopping positions.
if route.segments.count == 1 {
let finalPosition = path.coordinateAtIndex(path.count()-1) //Last location
let finalMarker = GMSMarker(position: finalPosition)
finalMarker.icon = GMSMarker.markerImageWithColor(selectedSegment.color)
finalMarker.map = self.mapViewContainer
}
case route.segments.count-1:
locationPosition = path.coordinateAtIndex(path.count()-1) //Last location
let marker = GMSMarker(position: locationPosition)
marker.icon = GMSMarker.markerImageWithColor(selectedSegment.color)
marker.title = selectedSegment.name
marker.map = self.mapViewContainer
default: break
}
polyline.map = self.mapViewContainer
self.mapViewContainer.animateToLocation(locationPosition)
}
}
}
/**
This method will be invoked every time that the RouteSegmentsView notify for an
RSVButtonTapped event
*/
func performSegmentSelection(notification: NSNotification) {
let userInfo = notification.userInfo as! [String: AnyObject]
let button = userInfo["button"] as! RouteSegmentButton?
if let button = button {
let indexPath = NSIndexPath(forRow: button.index, inSection: 0)
self.segmentsTableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Middle)
self.tableView(self.segmentsTableView, didSelectRowAtIndexPath: indexPath)
}
}
}
| 036430c051fa715f0c9de8863c81baad | 35.393701 | 140 | 0.586651 | false | false | false | false |
JGiola/swift | refs/heads/main | validation-test/compiler_crashers_2_fixed/sr11639.swift | apache-2.0 | 4 | // RUN: %target-swift-frontend -emit-ir -primary-file %s -debug-generic-signatures 2>&1 | %FileCheck %s
public protocol FooProtocol {
associatedtype Bar
}
public struct Foo<Bar>: FooProtocol {
public var bar: Bar
}
public protocol BazProtocol: FooProtocol {
associatedtype Foo1: FooProtocol where Foo1.Bar == Foo2.Bar
associatedtype Foo2Bar
typealias Foo2 = Foo<Foo2Bar>
}
// CHECK-LABEL: sr11639.(file).BazProtocol@
// CHECK-NEXT: Requirement signature: <Self where Self : FooProtocol, Self.[BazProtocol]Foo1 : FooProtocol, Self.[BazProtocol]Foo2Bar == Self.[BazProtocol]Foo1.[FooProtocol]Bar>
| d95cb61722ea2a71109cf90ae1b8ed7e | 32.833333 | 177 | 0.752053 | false | false | false | false |
BluefinSolutions/ODataParser | refs/heads/master | ODataParser/ODataServiceManager.swift | apache-2.0 | 1 | //
// ODataServiceManager.swift
// Demo Jam
//
// Created by Brenton O'Callaghan on 09/10/2014.
// Completely open source without any warranty to do with what you like :-)
//
import Foundation
class ODataServiceManager: NSObject, ODataCollectionDelegate{
internal var _entitiesAvailable: NSMutableArray = NSMutableArray()
internal var _collectionListLoaded: Bool = false;
// The local oData requestor.
internal var _oDataRequester: ODataCollectionManager?
// Callsback to the passed in function with a list of the available collections in the oData service.
class func getCollectionList() -> NSMutableArray{
// This would be so much better as a class variable with async calls but Swift does not
// support class variables yet :-(
/*var serviceManager: ODataServiceManager = ODataServiceManager()
serviceManager._oDataRequester?.makeRequestToCollection(OdataFilter())
while (!serviceManager._collectionListLoaded){
sleep(1)
}
return serviceManager._entitiesAvailable*/
return NSMutableArray()
}
// Create a collection manager object used to make all the requests to a particular collection.
class func createCollectionManagerForCollection(collectionName:NSString, andDelegate:ODataCollectionDelegate) -> ODataCollectionManager{
// New instance of a collection.
var newCollectionManager: ODataCollectionManager = ODataCollectionManager();
// Set the delegate and the collection name.
newCollectionManager.setDelegate(andDelegate)
newCollectionManager.setCollectionName(collectionName)
// Return to the user :-)
return newCollectionManager
}
// ======================================================================
// MARK: - Internal Private instance methods.
// ======================================================================
override init() {
// Always do the super.
super.init()
// Create an odata request to the service with no specific collection.
self._oDataRequester = ODataServiceManager.createCollectionManagerForCollection("", andDelegate: self)
}
func didRecieveResponse(results: NSDictionary){
let queryDictionary = results.objectForKey("d") as NSMutableDictionary
let queryResults = queryDictionary.objectForKey("EntitySets") as NSMutableArray
for singleResult in queryResults{
// Create and initialise the new entity object.
self._entitiesAvailable.addObject(singleResult as NSString)
}
// Very important if we want to exit the infinite loop above!
// There has to be a better way to do this!!! :)
self._collectionListLoaded = true
}
func requestFailedWithError(error: NSString){
println("=== ERROR ERROR ERROR ===")
println("Unable to request entity listing from OData service - is it an odata server??")
println("Error: " + error)
}
} | 6077b41715c584f28e7266ca463a32ac | 35.505747 | 140 | 0.630866 | false | false | false | false |
cbaker6/qismartcity_netatmo | refs/heads/master | QiSmartCity/NetatmoModuleProvider.swift | apache-2.0 | 1 | //
// NetadmoModuleProvider.swift
// netatmoclient
//
// Created by Corey Baker on 5/10/16.
// Copyright © 2016 University of California San Diego. All rights reserved.
//
// Original code by: Thomas Kluge, https://github.com/thkl/NetatmoSwift
import Foundation
import CoreData
//Currently not using anything in this class
struct NetatmoModule: Equatable {
var id: String
var moduleName: String
var type: String //Might need to make an enum for types
var stationid : String
}
func ==(lhs: NetatmoModule, rhs: NetatmoModule) -> Bool {
return lhs.id == rhs.id
}
extension NetatmoModule {
init(managedObject : NSManagedObject) {
self.id = managedObject.valueForKey(kQSModuleId) as! String
self.moduleName = managedObject.valueForKey(kQSModuleName) as! String
self.type = managedObject.valueForKey(kQSModuleType) as! String
self.stationid = managedObject.valueForKey(kQSParentStationId) as! String
}
var measurementTypes : [NetatmoMeasureType] {
switch self.type {
case "NAMain":
return [.Temperature,.CO2,.Humidity,.Pressure,.Noise]
case "NAModule1","NAModule4":
return [.Temperature,.Humidity]
case "NAModule3":
return [.Rain]
case "NAModule2":
return [.WindStrength,.WindAngle]
default:
return []
}
}
}
class NetadmoModuleProvider {
private let coreDataStore: CoreDataStore!
init(coreDataStore : CoreDataStore?) {
if (coreDataStore != nil) {
self.coreDataStore = coreDataStore
} else {
self.coreDataStore = CoreDataStore()
}
}
func save() {
try! coreDataStore.managedObjectContext.save()
}
func modules()->Array<NetatmoModule> {
let fetchRequest = NSFetchRequest(entityName: kQSModule)
fetchRequest.fetchLimit = 1
let results = try! coreDataStore.managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
return results.map{NetatmoModule(managedObject: $0 )}
}
func createModule(id: String, name: String, type : String, stationId : String)->NSManagedObject {
let newModule = NSManagedObject(entity: coreDataStore.managedObjectContext.persistentStoreCoordinator!.managedObjectModel.entitiesByName[kQSModule]!, insertIntoManagedObjectContext: coreDataStore.managedObjectContext)
newModule.setValue(id, forKey: kQSModuleId)
newModule.setValue(name, forKey: kQSModuleName)
newModule.setValue(type, forKey: kQSModuleType)
newModule.setValue(stationId, forKey: kQSParentStationId)
try! coreDataStore.managedObjectContext.save()
return newModule
}
func getModuleWithId(id: String)->NSManagedObject? {
let fetchRequest = NSFetchRequest(entityName: kQSModule)
fetchRequest.predicate = NSPredicate(format: "\(kQSModuleId) == %@", argumentArray: [id])
fetchRequest.fetchLimit = 1
let results = try! coreDataStore.managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
return results.first
}
} | 602c7382a99e1a6e1a56604ee262a3ed | 29.670103 | 221 | 0.726967 | false | false | false | false |
acastano/swift-bootstrap | refs/heads/master | foundationkit/Sources/Classes/Extensions/Primitives/String+Crypto.swift | apache-2.0 | 1 |
import Foundation
import CommonCrypto
public extension String {
public func sha1() -> String? {
var output: NSMutableString?
if let data = dataUsingEncoding(NSUTF8StringEncoding) {
var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue:0)
CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
output = NSMutableString(capacity:Int(CC_SHA1_DIGEST_LENGTH))
for byte in digest {
output?.appendFormat("%02x", byte)
}
}
var string: String?
if let output = output {
string = String(output)
}
return string
}
public func applyHmac(key: String) -> String? {
return ""
}
public func hmac(key: String) -> String? {
var hmac: String?
if let cData = cStringUsingEncoding(NSUTF8StringEncoding), let cKey = key.cStringUsingEncoding(NSUTF8StringEncoding) {
let digestLenght = Int(CC_SHA1_DIGEST_LENGTH)
let cHMAC = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLenght)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), cKey, Int(strlen(cKey)), cData, Int(strlen(cData)), cHMAC)
let hash = NSMutableString()
for i in 0..<digestLenght {
hash.appendFormat("%02x", cHMAC[i])
}
hmac = String(hash)
}
return hmac
}
}
| 533b844de6ec5aa8fe4fcc98a9c43902 | 23.150685 | 126 | 0.470788 | false | false | false | false |
AndersHqst/SwiftRestFramework | refs/heads/master | SwiftServer/main.swift | mit | 1 | //
// main.swift
// SwiftServer
//
// Created by Anders Høst Kjærgaard on 15/08/2015.
// Copyright (c) 2015 hqst IT. All rights reserved.
//
import Foundation
let server = HttpServer()
// Custom endpoint
server["endpoint"] = {
request in
return HttpResponse(text: "Hello world")
}
// Custom endpoint
server["json"] = {
request in
switch request.method {
case .POST:
// Do something with the body
return Created(json: request.body)
case .GET:
return OK(json: ["foo": "bar"])
default: return MethodNotAllowed()
}
}
// POST and GET /users. No validation. Subject to a "users" collection
server["/users"] = Create(resource: "users").handler
// GET /readonly-users. Returns the "users" collection
server["/readonly-users"] = Read(resource: "users").handler
server.run()
| ec0c59dff6ddc0d8437af264a4a5dab5 | 19.023256 | 70 | 0.632985 | false | false | false | false |
MadAppGang/refresher | refs/heads/master | Refresher/ConnectionLostExtension.swift | mit | 1 | //
// ConnectionLostExtension.swift
// Pods
//
// Created by Ievgen Rudenko on 21/10/15.
//
//
import Foundation
import ReachabilitySwift
private let сonnectionLostTag = 1326
private let ConnectionLostViewDefaultHeight: CGFloat = 24
extension UIScrollView {
// View on top that shows "connection lost"
public var сonnectionLostView: ConnectionLostView? {
get {
let theView = viewWithTag(сonnectionLostTag) as? ConnectionLostView
return theView
}
}
// If you want to connection lost functionality to your UIScrollView just call this method and pass action closure you want to execute when Reachabikity changed. If you want to stop showing reachability view you must do that manually calling hideReachabilityView methods on your scroll view
public func addReachability(action:(newStatus: Reachability.NetworkStatus) -> ()) {
let frame = CGRectMake(0, -ConnectionLostViewDefaultHeight, self.frame.size.width, ConnectionLostViewDefaultHeight)
let defaultView = ConnectionLostDefaultSubview(frame: frame)
let reachabilityView = ConnectionLostView(view:defaultView, action:action)
reachabilityView.tag = сonnectionLostTag
reachabilityView.hidden = true
addSubview(reachabilityView)
}
public func addReachabilityView(view:UIView, action:(newStatus: Reachability.NetworkStatus) -> ()) {
let reachabilityView = ConnectionLostView(view:view, action:action)
reachabilityView.tag = сonnectionLostTag
reachabilityView.hidden = true
addSubview(reachabilityView)
}
// Manually start pull to refresh
public func showReachabilityView() {
сonnectionLostView?.becomeUnreachable()
}
// Manually stop pull to refresh
public func hideReachabilityView() {
сonnectionLostView?.becomeReachable()
}
} | 01f4bde6b5885308672feb18a20bbcb2 | 33.654545 | 294 | 0.717585 | false | false | false | false |
ainopara/Stage1st-Reader | refs/heads/master | Stage1st/Manager/DiscuzClient/Utilities/Transformers/StringDateTransformer.swift | bsd-3-clause | 1 | //
// StringDateTransformer.swift
// Stage1st
//
// Created by Zheng Li on 2018/11/3.
// Copyright © 2018 Renaissance. All rights reserved.
//
import CodableExtensions
struct StringDateTransformer: DecodingContainerTransformer {
typealias Input = String
typealias Output = Date
enum DateType {
case secondSince1970
}
let dateType: DateType
init(dateType: DateType) {
self.dateType = dateType
}
func transform(_ decoded: String) throws -> Date {
switch self.dateType {
case .secondSince1970:
guard let intValue = Int(decoded) else {
throw "Failed to transform \(decoded) to Int."
}
guard intValue >= 0 else {
throw "Invalid time interval \(intValue)."
}
return Date(timeIntervalSince1970: TimeInterval(intValue))
}
}
}
| a1cf8145cb96d556846829de334259be | 21.475 | 70 | 0.606229 | false | false | false | false |
biohazardlover/NintendoEverything | refs/heads/master | Pods/SwiftSoup/Sources/TreeBuilder.swift | mit | 5 | //
// TreeBuilder.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 24/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
public class TreeBuilder {
public var reader: CharacterReader
var tokeniser: Tokeniser
public var doc: Document // current doc we are building into
public var stack: Array<Element> // the stack of open elements
public var baseUri: String // current base uri, for creating new elements
public var currentToken: Token? // currentToken is used only for error tracking.
public var errors: ParseErrorList // null when not tracking errors
public var settings: ParseSettings
private let start: Token.StartTag = Token.StartTag() // start tag to process
private let end: Token.EndTag = Token.EndTag()
public func defaultSettings() -> ParseSettings {preconditionFailure("This method must be overridden")}
public init() {
doc = Document("")
reader = CharacterReader("")
tokeniser = Tokeniser(reader, nil)
stack = Array<Element>()
baseUri = ""
errors = ParseErrorList(0, 0)
settings = ParseSettings(false, false)
}
public func initialiseParse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings) {
doc = Document(baseUri)
self.settings = settings
reader = CharacterReader(input)
self.errors = errors
tokeniser = Tokeniser(reader, errors)
stack = Array<Element>()
self.baseUri = baseUri
}
func parse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Document {
initialiseParse(input, baseUri, errors, settings)
try runParser()
return doc
}
public func runParser()throws {
while (true) {
let token: Token = try tokeniser.read()
try process(token)
token.reset()
if (token.type == Token.TokenType.EOF) {
break
}
}
}
@discardableResult
public func process(_ token: Token)throws->Bool {preconditionFailure("This method must be overridden")}
@discardableResult
public func processStartTag(_ name: String)throws->Bool {
if (currentToken === start) { // don't recycle an in-use token
return try process(Token.StartTag().name(name))
}
return try process(start.reset().name(name))
}
@discardableResult
public func processStartTag(_ name: String, _ attrs: Attributes)throws->Bool {
if (currentToken === start) { // don't recycle an in-use token
return try process(Token.StartTag().nameAttr(name, attrs))
}
start.reset()
start.nameAttr(name, attrs)
return try process(start)
}
@discardableResult
public func processEndTag(_ name: String)throws->Bool {
if (currentToken === end) { // don't recycle an in-use token
return try process(Token.EndTag().name(name))
}
return try process(end.reset().name(name))
}
public func currentElement() -> Element? {
let size: Int = stack.count
return size > 0 ? stack[size-1] : nil
}
}
| a1ce8932645de45779972f5bfcd7cc1b | 31.897959 | 122 | 0.634615 | false | false | false | false |
firebase/FirebaseUI-iOS | refs/heads/master | samples/swift/FirebaseUI-demo-swift/Samples/Auth/FUIAuthViewController.swift | apache-2.0 | 1 | //
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebaseAuth
import FirebaseEmailAuthUI
import FirebaseFacebookAuthUI
import FirebaseAnonymousAuthUI
import FirebasePhoneAuthUI
import FirebaseOAuthUI
import FirebaseGoogleAuthUI
let kFirebaseTermsOfService = URL(string: "https://firebase.google.com/terms/")!
let kFirebasePrivacyPolicy = URL(string: "https://firebase.google.com/support/privacy/")!
enum UISections: Int, RawRepresentable {
case Settings = 0
case Providers
case AnonymousSignIn
case Name
case Email
case UID
case Phone
case AccessToken
case IDToken
}
enum Providers: Int, RawRepresentable {
case Email = 0
case Google
case Facebook
case Twitter
case Apple
case Phone
}
/// A view controller displaying a basic sign-in flow using FUIAuth.
class FUIAuthViewController: UITableViewController {
// Before running this sample, make sure you've correctly configured
// the appropriate authentication methods in Firebase console. For more
// info, see the Auth README at ../../FirebaseAuthUI/README.md
// and https://firebase.google.com/docs/auth/
fileprivate var authStateDidChangeHandle: AuthStateDidChangeListenerHandle?
fileprivate(set) var auth: Auth? = Auth.auth()
fileprivate(set) var authUI: FUIAuth? = FUIAuth.defaultAuthUI()
fileprivate(set) var customAuthUIDelegate: FUIAuthDelegate = FUICustomAuthDelegate()
@IBOutlet weak var cellSignedIn: UITableViewCell!
@IBOutlet weak var cellName: UITableViewCell!
@IBOutlet weak var cellEmail: UITableViewCell!
@IBOutlet weak var cellUid: UITableViewCell!
@IBOutlet weak var cellPhone: UITableViewCell!
@IBOutlet weak var cellAccessToken: UITableViewCell!
@IBOutlet weak var cellIdToken: UITableViewCell!
@IBOutlet weak var cellAnonymousSignIn: UITableViewCell!
@IBOutlet weak var authorizationButton: UIBarButtonItem!
@IBOutlet weak var customAuthorizationSwitch: UISwitch!
@IBOutlet weak var customScopesSwitch: UISwitch!
@IBOutlet weak var facebookSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
self.authUI?.tosurl = kFirebaseTermsOfService
self.authUI?.privacyPolicyURL = kFirebasePrivacyPolicy
self.tableView.selectRow(at: IndexPath(row: Providers.Email.rawValue, section: UISections.Providers.rawValue),
animated: false,
scrollPosition: .none)
self.tableView.selectRow(at: IndexPath(row: Providers.Google.rawValue, section: UISections.Providers.rawValue),
animated: false,
scrollPosition: .none)
self.tableView.selectRow(at: IndexPath(row: Providers.Facebook.rawValue, section: UISections.Providers.rawValue),
animated: false,
scrollPosition: .none)
self.tableView.selectRow(at: IndexPath(row: Providers.Twitter.rawValue, section: UISections.Providers.rawValue),
animated: false,
scrollPosition: .none)
self.tableView.selectRow(at: IndexPath(row: Providers.Apple.rawValue, section: UISections.Providers.rawValue),
animated: false,
scrollPosition: .none)
self.tableView.selectRow(at: IndexPath(row: Providers.Phone.rawValue, section: UISections.Providers.rawValue),
animated: false,
scrollPosition: .none)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.rowHeight = UITableView.automaticDimension;
self.tableView.estimatedRowHeight = 240;
self.authStateDidChangeHandle =
self.auth?.addStateDidChangeListener(self.updateUI(auth:user:))
self.navigationController?.isToolbarHidden = false;
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let handle = self.authStateDidChangeHandle {
self.auth?.removeStateDidChangeListener(handle)
}
self.navigationController?.isToolbarHidden = true;
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (indexPath.section == UISections.AnonymousSignIn.rawValue && indexPath.row == 0) {
if (auth?.currentUser?.isAnonymous ?? false) {
tableView.deselectRow(at: indexPath, animated: false)
return;
}
do {
try self.authUI?.signOut()
} catch let error {
self.ifNoError(error) {}
}
auth?.signInAnonymously() { authReuslt, error in
self.ifNoError(error) {
self.showAlert(title: "Signed In Anonymously")
}
}
tableView.deselectRow(at: indexPath, animated: false)
}
}
fileprivate func showAlert(title: String, message: String? = "") {
if #available(iOS 8.0, *) {
let alertController =
UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK",
style: .default,
handler: { (UIAlertAction) in
alertController.dismiss(animated: true, completion: nil)
}))
self.present(alertController, animated: true, completion: nil)
} else {
UIAlertView(title: title,
message: message ?? "",
delegate: nil,
cancelButtonTitle: nil,
otherButtonTitles: "OK").show()
}
}
private func ifNoError(_ error: Error?, execute: () -> Void) {
guard error == nil else {
showAlert(title: "Error", message: error!.localizedDescription)
return
}
execute()
}
@IBAction func onAuthorize(_ sender: AnyObject) {
if (self.auth?.currentUser) != nil {
if (auth?.currentUser?.isAnonymous != false) {
auth?.currentUser?.delete() { error in
self.ifNoError(error) {
self.showAlert(title: "", message:"The user was properly deleted.")
}
}
} else {
do {
try self.authUI?.signOut()
} catch let error {
self.ifNoError(error) {
self.showAlert(title: "Error", message:"The user was properly signed out.")
}
}
}
} else {
self.authUI?.delegate = self.customAuthorizationSwitch.isOn ? self.customAuthUIDelegate : nil;
// If you haven't set up your authentications correctly these buttons
// will still appear in the UI, but they'll crash the app when tapped.
self.authUI?.providers = self.getListOfIDPs()
let providerID = self.authUI?.providers.first?.providerID;
let isPhoneAuth = providerID == PhoneAuthProviderID;
let isEmailAuth = providerID == EmailAuthProviderID;
let shouldSkipAuthPicker = self.authUI?.providers.count == 1 && (isPhoneAuth || isEmailAuth);
if (shouldSkipAuthPicker) {
if (isPhoneAuth) {
let provider = self.authUI?.providers.first as! FUIPhoneAuth;
provider.signIn(withPresenting: self, phoneNumber: nil);
} else if (isEmailAuth) {
let provider = self.authUI?.providers.first as! FUIEmailAuth;
provider.signIn(withPresenting: self, email: nil);
}
} else {
let controller = self.authUI!.authViewController()
controller.navigationBar.isHidden = self.customAuthorizationSwitch.isOn
self.present(controller, animated: true, completion: nil)
}
}
}
// Boilerplate
func updateUI(auth: Auth, user: User?) {
if let user = self.auth?.currentUser {
self.cellSignedIn.textLabel?.text = "Signed in"
self.cellName.textLabel?.text = user.displayName ?? "(null)"
self.cellEmail.textLabel?.text = user.email ?? "(null)"
self.cellUid.textLabel?.text = user.uid
self.cellPhone.textLabel?.text = user.phoneNumber
if (auth.currentUser?.isAnonymous != false) {
self.authorizationButton.title = "Delete Anonymous User";
} else {
self.authorizationButton.title = "Sign Out";
}
} else {
self.cellSignedIn.textLabel?.text = "Not signed in"
self.cellName.textLabel?.text = "null"
self.cellEmail.textLabel?.text = "null"
self.cellUid.textLabel?.text = "null"
self.cellPhone.textLabel?.text = "null"
self.authorizationButton.title = "Sign In";
}
self.cellAccessToken.textLabel?.text = getAllAccessTokens()
self.cellIdToken.textLabel?.text = getAllIdTokens()
let selectedRows = self.tableView.indexPathsForSelectedRows
self.tableView.reloadData()
if let rows = selectedRows {
for path in rows {
self.tableView.selectRow(at: path, animated: false, scrollPosition: .none)
}
}
}
func getAllAccessTokens() -> String {
var result = ""
for provider in self.authUI!.providers {
result += (provider.shortName + ": " + (provider.accessToken ?? "null") + "\n")
}
return result
}
func getAllIdTokens() -> String {
var result = ""
for provider in self.authUI!.providers {
result += (provider.shortName + ": " + (provider.idToken! ?? "null") + "\n")
}
return result
}
func getListOfIDPs() -> [FUIAuthProvider] {
var providers = [FUIAuthProvider]()
if let selectedRows = self.tableView.indexPathsForSelectedRows {
for indexPath in selectedRows {
if indexPath.section == UISections.Providers.rawValue {
let provider:FUIAuthProvider?
switch indexPath.row {
case Providers.Email.rawValue:
provider = FUIEmailAuth()
case Providers.Google.rawValue:
provider = self.customScopesSwitch.isOn ? FUIGoogleAuth(authUI: self.authUI!,
scopes: [kGoogleGamesScope,
kGooglePlusMeScope,
kGoogleUserInfoEmailScope,
kGoogleUserInfoProfileScope])
: FUIGoogleAuth(authUI: self.authUI!)
case Providers.Twitter.rawValue:
let buttonColor =
UIColor(red: 71.0/255.0, green: 154.0/255.0, blue: 234.0/255.0, alpha: 1.0)
guard let iconPath = Bundle.main.path(forResource: "twtrsymbol", ofType: "png") else {
NSLog("Warning: Unable to find Twitter icon")
continue
}
provider = FUIOAuth(authUI: self.authUI!,
providerID: "twitter.com",
buttonLabelText: "Sign in with Twitter",
shortName: "Twitter",
buttonColor: buttonColor,
iconImage: UIImage(contentsOfFile: iconPath)!,
scopes: ["user.readwrite"],
customParameters: ["prompt" : "consent"],
loginHintKey: nil)
case Providers.Facebook.rawValue:
provider = self.customScopesSwitch.isOn ? FUIFacebookAuth(authUI: self.authUI!,
permissions: ["email",
"user_friends",
"ads_read"])
: FUIFacebookAuth(authUI: self.authUI!)
let facebookProvider = provider as! FUIFacebookAuth
facebookProvider.useLimitedLogin = self.facebookSwitch.isOn
case Providers.Apple.rawValue:
if #available(iOS 13.0, *) {
provider = FUIOAuth.appleAuthProvider()
} else {
provider = nil
}
case Providers.Phone.rawValue:
provider = FUIPhoneAuth(authUI: self.authUI!)
default: provider = nil
}
guard provider != nil else {
continue
}
providers.append(provider!)
}
}
}
return providers
}
}
| 94013ad8a266e6bed8e6e23ba74cdb4f | 37.114035 | 117 | 0.614653 | false | false | false | false |
Bartlebys/Bartleby | refs/heads/master | Bartleby.xOS/bsfs/BSFS.swift | apache-2.0 | 1 | //
// BSFS.swift
// BartlebyKit
//
// Created by Benoit Pereira da silva on 02/11/2016.
//
//
import Foundation
/// The BSFS is set per document.
/// File level operations are done on GCD global utility queue.
public final class BSFS:TriggerHook{
// MARK: -
// If set to false we use the sandBoxing Context
// else we use the `exportPath` (CLI context)
static var useExportPath = false
static var exportPath:String = Bartleby.getSearchPath(.desktopDirectory) ?? Default.NO_PATH
// Document
fileprivate var _document:BartlebyDocument
/// The File manager used to perform all the BSFS operation on GCD global utility queue.
/// Note that we also use specific FileHandle at chunk level
fileprivate let _fileManager:FileManager=FileManager()
/// Chunk level operations
fileprivate let _chunker:Chunker
// The box Delegate
fileprivate var _boxDelegate:BoxDelegate?
// The current accessors key:node.UID, value:Array of Accessors
fileprivate var _accessors=[String:[NodeAccessor]]()
/// Store the blocks UIDs that need to be uploaded
fileprivate var _toBeUploadedBlocksUIDS=[String]()
// Store the blocks UIDs that need to be downloaded
fileprivate var _toBeDownloadedBlocksUIDS=[String]()
/// The downloads operations in progrees
fileprivate var _downloadsInProgress=[DownloadBlock]()
/// The uploads operations in progrees
fileprivate var _uploadsInProgress=[UploadBlock]()
/// Max Simultaneous operations ( per operation type and per bsfs instance. )
fileprivate var _maxSimultaneousOperations=1
// MARK: - initialization
/// Each document has it own BSFS
///
/// - Parameter document: the document instance
required public init(in document:BartlebyDocument){
self._document=document
self._chunker=Chunker(fileManager: FileManager.default,
mode:.digestAndProcessing,
embeddedIn:document)
self._boxDelegate=document
}
// MARK: - Persistency
/// Serialize the local state of the BSFS
///
/// - Returns: the serialized data
public func saveState()->Data{
let state=["toBeUploaded":self._toBeUploadedBlocksUIDS,
"toBeDownloaded":self._toBeDownloadedBlocksUIDS]
if let data = try? JSONSerialization.data(withJSONObject: state){
return data
}
return Data()
}
/// Restore the state
///
/// - Parameter data: from the serialized state data
public func restoreStateFrom(data:Data)throws->(){
if let state = try? JSONSerialization.jsonObject(with: data) as? [String:[String]]{
self._toBeDownloadedBlocksUIDS=state?["toBeDownloaded"] ?? [String]()
self._toBeUploadedBlocksUIDS=state?["toBeUploaded"] ?? [String]()
}
}
// MARK: - Paths
/// The BSFS base folder path
/// ---
/// baseFolder/
/// - boxes/<boxUID>/[files]
/// - downloads/[files] tmp download files
public var baseFolderPath:String{
if BSFS.useExportPath{
return BSFS.exportPath
}
if self._document.metadata.appGroup != ""{
if let url=self._fileManager.containerURL(forSecurityApplicationGroupIdentifier: self._document.metadata.appGroup){
return url.path+"/\(_document.UID)"
}
}
return Bartleby.getSearchPath(.documentDirectory)!+"/\(_document.UID)"
}
/// Downloads folder
public var downloadFolderPath:String{
return baseFolderPath+"/downloads"
}
/// Boxes folder
public var boxesFolderPath:String{
return baseFolderPath+"/boxes"
}
//MARK: - Box Level
/// Mounts the current local box == Assemble all its assemblable nodes
/// There is no guarantee that the box is not fully up to date
///
/// - Parameters:
/// - boxUID: the Box UID
/// - progressed: a closure to relay the Progression State
/// - completed: a closure called on completion with Completion State.
/// the box UID is stored in the completion.getResultExternalReference()
public func mount( boxUID:String,
progressed:@escaping (Progression)->(),
completed:@escaping (Completion)->()){
do {
let box = try Bartleby.registredObjectByUID(boxUID) as Box
self._document.send(BoxStates.isMounting(box: box))
if box.assemblyInProgress || box.isMounted {
throw BSFSError.attemptToMountBoxMultipleTime(boxUID: boxUID)
}
var concernedNodes=[Node]()
let group=AsyncGroup()
group.utility{
try? self._fileManager.createDirectory(atPath: box.nodesFolderPath, withIntermediateDirectories: true, attributes: nil)
}
group.wait()
// Let's try to assemble as much nodes as we can.
let nodes=box.nodes
for node in nodes{
let isNotAssembled = !self.isAssembled(node)
let isAssemblable = node.isAssemblable
if node.isAssemblable && isNotAssembled{
concernedNodes.append(node)
}
}
box.quietChanges{
box.assemblyProgression.totalTaskCount=concernedNodes.count
box.assemblyProgression.currentTaskIndex=0
box.assemblyProgression.currentPercentProgress=0
}
// We want to assemble the node sequentially.
// So we will use a recursive pop method
func __popNode(){
if let node=concernedNodes.popLast(){
node.assemblyInProgress=true
do{
try self._assemble(node: node, progressed: { (progression) in
progressed(progression)
}, completed: { (completion) in
node.assemblyInProgress=false
box.assemblyProgression.currentTaskIndex += 1
box.assemblyProgression.currentPercentProgress=Double(box.assemblyProgression.currentTaskIndex)*Double(100)/Double(box.assemblyProgression.totalTaskCount)
__popNode()
})
}catch{
self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false)
completed(Completion.failureStateFromError(error))
}
}else{
box.assemblyInProgress=false
box.isMounted=true
let completionState=Completion.successState()
completionState.setExternalReferenceResult(from:box)
completed(completionState)
self._document.send(BoxStates.hasBeenMounted(box: box))
}
}
// Call the first pop.
__popNode()
} catch {
let resolvedBox:Box? = try? Bartleby.registredObjectByUID(boxUID)
resolvedBox?.assemblyInProgress = false
completed(Completion.failureStateFromError(error))
self._document.send(BoxStates.mountingHasFailed(boxUID:boxUID,message: "\(error)"))
}
}
public func unMountAllBoxes(){
self._document.boxes.forEach { (box) in
self.unMount(box: box)
}
let group=AsyncGroup()
group.utility{
try? self._fileManager.removeItem(atPath: self.boxesFolderPath)
}
group.wait()
}
/// Un mounts the Box == deletes all the assembled files
///
/// - Parameters:
/// - boxUID: the Box UID
/// - completed: a closure called on completion with Completion State.
public func unMount( boxUID:String,
completed:@escaping (Completion)->()){
do {
let box = try Bartleby.registredObjectByUID(boxUID) as Box
self.unMount(box: box)
completed(Completion.successState())
}catch{
completed(Completion.failureStateFromError(error))
}
}
public func unMount(box:Box)->(){
for node in box.nodes{
if let accessors=self._accessors[node.UID]{
for accessor in accessors{
accessor.willBecomeUnusable(node: node)
}
}
let assembledPath=self.assemblyPath(for:node)
let group=AsyncGroup()
group.utility{
try? self._fileManager.removeItem(atPath: assembledPath)
}
group.wait()
}
let group=AsyncGroup()
group.utility{
try? self._fileManager.removeItem(atPath: box.nodesFolderPath)
}
group.wait()
box.isMounted=false
box.assemblyInProgress=false
}
///
/// - Parameter node: the node
/// - Returns: the assembled path (created if there no
public func assemblyPath(for node:Node)->String{
if let box=node.box{
return self.assemblyPath(for: box)+node.relativePath
}
return Default.NO_PATH
}
public func assemblyPath(for box:Box)->String{
return box.nodesFolderPath
}
/// Return is the node file has been assembled
///
/// - Parameter node: the node
/// - Returns: true if the file is available and the node not marked assemblyInProgress
public func isAssembled(_ node:Node)->Bool{
if node.assemblyInProgress {
// Return false if the assembly is in progress
return false
}
let group=AsyncGroup()
var isAssembled=false
group.utility{
let path=self.assemblyPath(for: node)
isAssembled=self._fileManager.fileExists(atPath: path)
if isAssembled{
if let attributes = try? self._fileManager.attributesOfItem(atPath: path){
if let size:Int=attributes[FileAttributeKey.size] as? Int{
if size != node.size{
self._document.log("Divergent size node Size:\(node.size) fs.size: \(size) ", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false)
isAssembled=false
}
}
}
}
}
group.wait()
return isAssembled
}
/// Creates a file from the node blocks.
/// IMPORTANT: this method requires a response from the BoxDelegate
///
/// - Parameters:
/// - node: the node
/// - progressed: a closure to relay the Progression State
/// - completed: a closure called on completion with Completion State.
/// the node UID is stored in the completion.getResultExternalReference()
internal func _assemble(node:Node,
progressed:@escaping (Progression)->(),
completed:@escaping (Completion)->()) throws->(){
do {
if node.isAssemblable == false{
throw BSFSError.nodeIsNotAssemblable
}
if let delegate = self._boxDelegate{
delegate.nodeIsReady(node: node, proceed: {
let path=self.assemblyPath(for: node)
let blocks=node.blocks.sorted(by: { (rblock, lblock) -> Bool in
return rblock.rank < lblock.rank
})
if node.nature == .file || node.nature == .flock {
var blockPaths=[String]()
for block in blocks{
// The blocks are embedded in a document
// So we use the relative path
blockPaths.append(block.blockRelativePath())
}
self._chunker.joinChunksToFile(from: blockPaths,
to: path,
decompress: node.compressedBlocks,
decrypt: node.cryptedBlocks,
externalId:node.UID,
progression: { (progression) in
progressed(progression)
}, success: { path in
if node.nature == .flock{
//TODO
// FLOCK path == path
let completionState=Completion.successState()
completionState.setExternalReferenceResult(from:node)
completed(completionState)
}else{
// The file has been assembled
let completionState=Completion.successState()
completionState.setExternalReferenceResult(from:node)
completed(completionState)
}
}, failure: { (message) in
let completion=Completion()
completion.message=message
completion.success=false
completion.externalIdentifier=node.UID
completed(completion)
})
}else if node.nature == .alias{
Async.utility{
do{
if let rNodeUID=node.referentNodeUID{
if let rNode = try? Bartleby.registredObjectByUID(rNodeUID) as Node{
let destination=self.assemblyPath(for: rNode)
try self._fileManager.createSymbolicLink(atPath: path, withDestinationPath:destination)
let completionState=Completion.successState()
completionState.setExternalReferenceResult(from:node)
completed(completionState)
}else{
completed(Completion.failureState("Unable to find Alias referent node", statusCode:.expectation_Failed))
}
}else{
completed(Completion.failureState("Unable to find Alias destination", statusCode:.expectation_Failed))
}
}catch{
completed(Completion.failureStateFromError(error))
}
}
}else if node.nature == .folder{
Async.utility{
do{
try self._fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
let completionState=Completion.successState()
completionState.setExternalReferenceResult(from:node)
completed(completionState)
}catch{
completed(Completion.failureStateFromError(error))
}
}
}
})
}else{
throw BSFSError.boxDelegateIsNotAvailable
}
} catch{
completed(Completion.failureStateFromError(error))
}
}
//MARK: - File Level
/// Adds a file or all the file from o folder into the box
/// Flocks may be supported soon
///
/// + generate the blocks in background.
/// + adds the node(s)
/// + the first node UID is stored in the Completion (use completion.getResultExternalReference())
///
/// - Parameters:
/// - FileReference: the file reference (Nature == file or flock)
/// - box: the box
/// - relativePath: the relative Path of the Node in the box
/// - deleteOriginal: should we delete the original?
/// - progressed: a closure to relay the Progression State
/// - completed: a closure called on completion with Completion State
/// the node UID is stored in the completion.getResultExternalReference()
public func add( reference:FileReference,
in box:Box,
to relativePath:String,
deleteOriginal:Bool=false,
progressed:@escaping (Progression)->(),
completed:@escaping (Completion)->()){
var fileExistsAtPath = false
let group=AsyncGroup()
group.utility{
fileExistsAtPath = self._fileManager.fileExists(atPath: reference.absolutePath)
}
group.wait()
if fileExistsAtPath{
var firstNode:Node?
func __chunksHaveBeenCreated(chunks:[Chunk]){
// Successful operation
// Let's Upsert the distant models.
// AND the local nodes
let groupedChunks=Chunk.groupByNodePath(chunks: chunks)
for (nodeRelativePath,groupOfChunks) in groupedChunks{
// Create the new node.
// And add its blocks
let node=self._document.newManagedModel() as Node
if firstNode==nil{
firstNode=node
}
node.quietChanges{
node.nature=reference.nodeNature.forNode
node.relativePath=relativePath///
node.priority=reference.priority
// Set up the node relative path
node.relativePath=nodeRelativePath
var cumulatedDigests=""
var cumulatedSize=0
box.quietChanges {
box.declaresOwnership(of: node)
}
// Let's add the blocks
for chunk in groupOfChunks{
let block=self._document.newManagedModel() as Block
block.quietChanges{
block.rank=chunk.rank
block.digest=chunk.sha1
block.startsAt=chunk.startsAt
block.size=chunk.originalSize
block.priority=reference.priority
}
cumulatedSize += chunk.originalSize
cumulatedDigests += chunk.sha1
node.addBlock(block)
self._toBeUploadedBlocksUIDS.append(block.UID)
}
// Store the digest of the cumulated digests.
node.digest=cumulatedDigests.sha1
// And the node original size
node.size=cumulatedSize
}
// Add the file in the box if it is mounted.
if box.isMounted{
let nodeAssemblyPath = self.assemblyPath(for:node)
do {
try self._fileManager.copyItem(atPath: reference.absolutePath, toPath: nodeAssemblyPath)
}catch{
self._document.log("Original Copy has failed. \nReferencePath:\( reference.absolutePath) \nassemblyPath:\(nodeAssemblyPath)",category: Default.LOG_BSFS)
}
}
}
// Delete the original
if deleteOriginal{
// We consider deletion as non mandatory.
// So we produce only a log.
do {
try self._fileManager.removeItem(atPath: reference.absolutePath)
} catch {
self._document.log("Deletion has failed. Path:\( reference.absolutePath)",file: Default.LOG_BSFS)
}
}
let finalState=Completion.successState()
if let node=firstNode{
finalState.setExternalReferenceResult(from:node)
}
completed(finalState)
// Call the centralized upload mechanism
self._uploadNext()
}
Async.utility{
if reference.nodeNature == .file{
var isDirectory:ObjCBool=false
if self._fileManager.fileExists(atPath: reference.absolutePath, isDirectory: &isDirectory){
if isDirectory.boolValue{
self._chunker.breakFolderIntoChunk(filesIn: reference.absolutePath,
chunksFolderPath: box.nodesFolderPath,
progression: { (progression) in
progressed(progression)
}, success: { (chunks) in
__chunksHaveBeenCreated(chunks: chunks)
}, failure: { (chunks, message) in
completed(Completion.failureState(message, statusCode: .expectation_Failed))
})
}else{
/// Let's break the file into chunk.
self._chunker.breakIntoChunk( fileAt: reference.absolutePath,
relativePath:relativePath,
chunksFolderPath: box.nodesFolderPath,
chunkMaxSize:reference.chunkMaxSize,
compress: reference.compressed,
encrypt: reference.crypted,
progression: { (progression) in
progressed(progression)
}
, success: { (chunks) in
__chunksHaveBeenCreated(chunks: chunks)
}, failure: { (message) in
completed(Completion.failureState(message, statusCode: .expectation_Failed))
})
}
}else{
let message=NSLocalizedString("Unexisting path: ", tableName:"system", comment: "Unexisting path: ")+reference.absolutePath
completed(Completion.failureState(message, statusCode: .expectation_Failed))
}
}
if reference.nodeNature == .flock{
// @TODO
}
}
}else{
completed(Completion.failureState(NSLocalizedString("Reference Not Found!", tableName:"system", comment: "Reference Not Found!")+" \(reference.absolutePath)", statusCode: .not_Found))
}
}
/// Call to replace the content of a file node with a given file. (alias, flocks, folders are not supported)
/// This action may be refused by the BoxDelegate (check the completion state)
///
/// Delta Optimization:
/// We first compute the `deltaChunks` to determine if some Blocks can be preserved
/// Then we `breakIntoChunk` the chunks that need to be chunked.
///
///
/// - Parameters:
/// - node: the concerned node
/// - path: the file path
/// - deleteOriginal: should we destroy the original file
/// - accessor: the accessor that ask for replacement
/// - progressed: a closure to relay the Progression State
/// - completed: a closure called on completion with Completion State.
/// the node UID is stored in the completion.getResultExternalReference()
func replaceContent(of node:Node,
withContentAt path:String,
deleteOriginal:Bool,
accessor:NodeAccessor,
progressed:@escaping (Progression)->(),
completed:@escaping (Completion)->()){
if node.nature == .file{
if node.authorized.contains(self._document.currentUser.UID) ||
node.authorized.contains("*"){
var isDirectory:ObjCBool=false
var fileExistsAtPath = false
let group=AsyncGroup()
group.utility{
fileExistsAtPath = self._fileManager.fileExists(atPath:path, isDirectory: &isDirectory)
}
group.wait()
if fileExistsAtPath{
if isDirectory.boolValue{
completed(Completion.failureState(NSLocalizedString("Forbidden! Replacement is restricted to single files not folder", tableName:"system", comment: "Forbidden! Replacement is restricted to single files not folder"), statusCode: .forbidden))
}else{
if let box=node.box{
let analyzer=DeltaAnalyzer(embeddedIn: self._document)
//////////////////////////////
// #1 We first compute the `deltaChunks` to determine if some Blocks can be preserved
//////////////////////////////
analyzer.deltaChunks(fromFileAt: path, to: node, using: self._fileManager, completed: { (toBePreserved, toBeDeleted) in
/// delete the blocks to be deleted
for chunk in toBeDeleted{
if let block=self._findBlockMatching(chunk: chunk){
self.deleteBlockFile(block)
}
}
/////////////////////////////////
// #2 Then we `breakIntoChunk` the chunks that need to be chunked.
/////////////////////////////////
self._chunker.breakIntoChunk(fileAt: path,
relativePath: node.relativePath,
chunksFolderPath: box.nodesFolderPath,
compress: node.compressedBlocks,
encrypt: node.cryptedBlocks,
excludeChunks:toBePreserved,
progression: { (progression) in
progressed(progression)
}
, success: { (chunks) in
// Successful operation
// Let's Upsert the node.
// AND create the local node
node.quietChanges{
var cumulatedDigests=""
var cumulatedSize=0
// Let's add the blocks
for chunk in chunks{
var block:Block?
if let b=self._findBlockMatching(chunk: chunk){
block=b
block?.needsToBeCommitted()
}else{
block=self._document.newManagedModel() as Block
node.quietChanges {
block!.quietChanges {
node.addBlock(block!)
}
}
}
block!.quietChanges{
block!.rank=chunk.rank
block!.digest=chunk.sha1
block!.startsAt=chunk.startsAt
block!.size=chunk.originalSize
block!.priority=node.priority
}
cumulatedDigests += chunk.sha1
cumulatedSize += chunk.originalSize
}
// Store the digest of the cumulated digests.
node.digest=cumulatedDigests.sha1
// And the node original size
node.size=cumulatedSize
}
// Mark the node to be committed
node.needsToBeCommitted()
// Delete the original
Async.utility{
if deleteOriginal{
// We consider deletion as non mandatory.
// So we produce only a log.
do {
try self._fileManager.removeItem(atPath: path)
} catch {
self._document.log("Deletion has failed. Path:\( path)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false)
}
}
}
let finalState=Completion.successState()
finalState.setExternalReferenceResult(from:node)
completed(finalState)
// Call the centralized upload mechanism
self._uploadNext()
}, failure: { (message) in
completed(Completion.failureState(message, statusCode: .expectation_Failed))
})
}, failure: { (message) in
completed(Completion.failureState(message, statusCode: .expectation_Failed))
})
}else{
completed(Completion.failureState(NSLocalizedString("Forbidden! Box not found", tableName:"system", comment: "Forbidden! Box not found"), statusCode: .forbidden))
}
}
}
}else{
completed(Completion.failureState(NSLocalizedString("Forbidden! Replacement refused", tableName:"system", comment: "Forbidden! Replacement refused"), statusCode: .forbidden))
}
}else{
completed(Completion.failureState("\(node.nature)", statusCode: .precondition_Failed))
}
}
//MARK: - Node Level
//MARK: Access
/// Any accessor to obtain access to the resource (file) of a node need to call this method.
/// The nodeIsUsable() will be called when the file will be usable.
///
/// WHY?
/// Because there is no guarantee that the node is locally available.
/// The application may work with a file that is available or another computer, with pending synchro.
///
/// By registering as accessor, the caller will be notified as soon as possible.
///
///
/// - Parameters:
/// - node: the node
/// - accessor: the accessor
public func wantsAccess(to node:Node,accessor:NodeAccessor){
// The nodeIsUsable() will be called when the file will be usable.
if node.authorized.contains("*") || node.authorized.contains(self._document.currentUser.UID){
if self._accessors[node.UID] != nil {
self._accessors[node.UID]=[NodeAccessor]()
}
if !self._accessors[node.UID]!.contains(where: {$0.UID==accessor.UID}){
self._accessors[node.UID]!.append(accessor)
}
if self.isAssembled(node){
self._grantAccess(to: node, accessor: accessor)
}
}else{
accessor.accessRefused(to:node, explanations: NSLocalizedString("Authorization failed", tableName:"system", comment: "Authorization failed"))
}
}
/// Should be called when the accessor does not need any more the node resource.
///
/// - Parameters:
/// - node: the node
/// - accessor: the accessor
public func stopsAccessing(to node:Node,accessor:NodeAccessor){
if let idx=self._accessors[node.UID]?.index(where: {$0.UID==accessor.UID}){
self._accessors[node.UID]!.remove(at: idx)
}
}
/// Grants the access
///
/// - Parameters:
/// - node: to the node
/// - accessor: for an Accessor
fileprivate func _grantAccess(to node:Node,accessor:NodeAccessor){
accessor.fileIsAvailable(for:node, at: self.assemblyPath(for:node))
}
//MARK: Logical actions
/// Moves a node to another destination in the box.
/// IMPORTANT: this method requires a response from the BoxDelegate
/// The completion occurs when the BoxDelegate invokes `applyPendingChanges` on the concerned node
///
/// - Parameters:
/// - node: the node
/// - relativePath: the relative path
/// - completed: a closure called on completion with Completion State.
/// the copied node UID is stored in the completion.getResultExternalReference()
public func copy(node:Node,to relativePath:String,completed:@escaping (Completion)->())->(){
// The nodeIsUsable() will be called when the file will be usable.
if node.authorized.contains("*") || node.authorized.contains(self._document.currentUser.UID){
self._boxDelegate?.copyIsReady(node: node, to: relativePath, proceed: {
if let box=node.box{
Async.utility{
do{
try self._fileManager.copyItem(atPath: self.assemblyPath(for: node), toPath:box.nodesFolderPath+relativePath)
// Create the copiedNode
let copiedNode=self._document.newManagedModel() as Node
copiedNode.quietChanges{
box.declaresOwnership(of: copiedNode)
try? copiedNode.mergeWith(node)// merge
copiedNode.relativePath=relativePath // Thats it!
}
let finalState=Completion.successState()
finalState.setExternalReferenceResult(from:copiedNode)
completed(finalState)
}catch{
completed(Completion.failureStateFromError(error))
}
}
}else{
completed(Completion.failureState(NSLocalizedString("Forbidden! Box not found", tableName:"system", comment: "Forbidden! Box not found"), statusCode: .forbidden))
}
})
}else{
completed(Completion.failureState(NSLocalizedString("Authorization failed", tableName:"system", comment: "Authorization failed"), statusCode: .unauthorized))
}
}
/// Moves a node to another destination in the box.
/// IMPORTANT: this method requires a response from the BoxDelegate
/// The completion occurs when the BoxDelegate invokes `applyPendingChanges` on the concerned node
///
/// - Parameters:
/// - node: the node
/// - relativePath: the relative path
/// - completed: a closure called on completion with Completion State.
/// the copied node UID is stored in the completion.getResultExternalReference()
public func move(node:Node,to relativePath:String,completed:@escaping (Completion)->())->(){
// The nodeIsUsable() will be called when the file will be usable.
if node.authorized.contains("*") || node.authorized.contains(self._document.currentUser.UID){
self._boxDelegate?.moveIsReady(node: node, to: relativePath, proceed: {
node.relativePath=relativePath
let finalState=Completion.successState()
finalState.setExternalReferenceResult(from:node)
completed(finalState)
})
}else{
completed(Completion.failureState(NSLocalizedString("Authorization failed", tableName:"system", comment: "Authorization failed"), statusCode: .unauthorized))
}
}
/// Deletes a node
/// IMPORTANT: this method requires a response from the BoxDelegate
/// The completion occurs when the BoxDelegate invokes `applyPendingChanges` on the concerned node
///
/// - Parameters:
/// - node: the node
/// - completed: a closure called on completion with Completion State.
public func delete(node:Node,completed:@escaping (Completion)->())->(){
// The nodeIsUsable() will be called when the file will be usable.
if node.authorized.contains("*") || node.authorized.contains(self._document.currentUser.UID){
self._boxDelegate?.deletionIsReady(node: node, proceed: {
/// TODO implement the deletion
/// Delete the node
/// Delete the files if necessary
/// Refuse to delete folder containing nodes
completed(Completion.successState())
})
}else{
completed(Completion.failureState(NSLocalizedString("Authorization failed", tableName:"system", comment: "Authorization failed"), statusCode: .unauthorized))
}
}
/// Create Folders
/// - Parameters:
/// - relativePath: the relative Path
/// - completed: a closure called on completion with Completion State.
public func createFolder(in box:Box,at relativePath:String,completed:@escaping (Completion)->())->(){
/// TODO implement
/// TEST IF THERE IS A LOCAL FOLDER
/// Create the folder
/// Create the NODE
completed(Completion.successState())
}
/// Creates the Alias
/// - Parameters:
/// - node: the node to be aliased
/// - relativePath: the destination relativePath
/// - completed: a closure called on completion with Completion State.
public func createAlias(of node:Node,to relativePath:String, completed:@escaping (Completion)->())->(){
// The nodeIsUsable() will be called when the file will be usable.
if node.authorized.contains("*") || node.authorized.contains(self._document.currentUser.UID){
// TODO
/// Create the Alias
/// Create the NODE
}else{
completed(Completion.failureState(NSLocalizedString("Authorization failed", tableName:"system", comment: "Authorization failed"), statusCode: .unauthorized))
}
}
// MARK: - TriggerHook
/// Called by the Document before trigger integration
///
/// - Parameter trigger: the trigger
public func triggerWillBeIntegrated(trigger:Trigger){
// We have nothing to do.
}
/// Called by the Document after trigger integration
///
/// - Parameter trigger: the trigger
public func triggerHasBeenIntegrated(trigger:Trigger){
// CHECK if there are Blocks, Node actions.
// UploadBlock -> download if allowed triggered_download
// DeleteBlock, DeleteBlocks -> delete the block immediately
// UpsertBlock, UpsertBlocks -> nothing to do
// On Nodes or Blocks check if we are concerned / allowed.
}
//MARK: - Triggered Block Level Action
/// Downloads a Block.
/// This occurs before triggered_create on each successfull upload.
///
/// - Parameters:
/// - node: the node
internal func triggered_download(block:Block){
if let node=block.node{
if node.authorized.contains(self._document.currentUser.UID) ||
node.authorized.contains("*"){
self._toBeDownloadedBlocksUIDS.append(block.UID)
self._downloadNext()
}
}
}
//MARK: - Block Level
/// Will upload the next block if possible
/// Respecting the priorities
internal func _uploadNext()->(){
if self._uploadsInProgress.count<_maxSimultaneousOperations{
do{
let uploadableBlocks = try self._toBeUploadedBlocksUIDS.map({ (UID) -> Block in
return try Bartleby.registredObjectByUID(UID) as Block
})
let priorizedBlocks=uploadableBlocks.sorted { (l, r) -> Bool in
return l.priority>r.priority
}
var toBeUploaded:Block?
for candidate in priorizedBlocks{
if self._toBeUploadedBlocksUIDS.contains(candidate.UID) && candidate.uploadInProgress==false {
toBeUploaded=candidate
break
}
}
func __removeBlockFromList(_ block:Block){
block.uploadInProgress=false
if let idx=self._toBeUploadedBlocksUIDS.index(where:{ $0 == block.UID}){
self._toBeUploadedBlocksUIDS.remove(at: idx)
}
if let idx=self._uploadsInProgress.index(where:{ $0.blockUID == block.UID}){
self._uploadsInProgress.remove(at: idx)
}
}
if toBeUploaded != nil{
if let block = try? Bartleby.registredObjectByUID(toBeUploaded!.UID) as Block {
block.uploadInProgress=true
let uploadOperation=UploadBlock(block: block, documentUID: self._document.UID, sucessHandler: { (context) in
__removeBlockFromList(block)
self._uploadNext()
}, failureHandler: { (context) in
__removeBlockFromList(block)
}, cancelationHandler: {
__removeBlockFromList(block)
})
self._uploadsInProgress.append(uploadOperation)
}else{
self._document.log("Block not found \(toBeUploaded!.UID)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false)
}
}
} catch{
self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false)
}
}
}
/// Will download the next block if possible
/// Respecting the priorities
internal func _downloadNext()->(){
if self._downloadsInProgress.count<self._maxSimultaneousOperations{
do{
let downloadableBlocks = try self._toBeDownloadedBlocksUIDS.map({ (UID) -> Block in
return try Bartleby.registredObjectByUID(UID) as Block
})
let priorizedBlocks=downloadableBlocks.sorted { (l, r) -> Bool in
return l.priority>r.priority
}
var toBeDownloaded:Block?
for candidate in priorizedBlocks{
if self._toBeDownloadedBlocksUIDS.contains(candidate.UID) && candidate.downloadInProgress==false {
toBeDownloaded=candidate
break
}
}
func __removeBlockFromList(_ block:Block){
block.downloadInProgress=false
if let idx=self._toBeDownloadedBlocksUIDS.index(where:{ $0 == block.UID }){
self._toBeDownloadedBlocksUIDS.remove(at: idx)
}
if let idx=self._downloadsInProgress.index(where:{ $0.blockUID == block.UID }){
self._downloadsInProgress.remove(at: idx)
}
}
if toBeDownloaded != nil{
if let block = try? Bartleby.registredObjectByUID(toBeDownloaded!.UID) as Block {
block.downloadInProgress=true
let downLoadOperation=DownloadBlock(block: block, documentUID: self._document.UID, sucessHandler: { (tempURL) in
var data:Data?
var sha1=""
Async.utility{
do{
data=try Data(contentsOf:tempURL)
sha1=data!.sha1
}catch{
self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false)
}
}.main{
do{
if sha1==block.digest{
try self._document.put(data: data!, identifiedBy:sha1)
__removeBlockFromList(block)
self._uploadNext()
}else{
self._document.log("Digest of the block is not matching", file: #file, function: #function, line: #line, category: Default.LOG_SECURITY, decorative: false)
}
}catch{
self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false)
}
}
}, failureHandler: { (context) in
__removeBlockFromList(block)
}, cancelationHandler: {
__removeBlockFromList(block)
})
self._downloadsInProgress.append(downLoadOperation)
}else{
self._document.log("Block not found \(toBeDownloaded!.UID)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false)
}
}
}catch{
self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_WARNING, decorative: false)
}
}
}
/// Return the block matching the Chunk if found
///
/// - Parameter chunk: the chunk
/// - Returns: the block.
internal func _findBlockMatching(chunk:Chunk) -> Block? {
if let idx=self._document.blocks.index(where: { (block) -> Bool in
return block.digest==chunk.sha1
}){
return self._document.blocks[idx]
}
return nil
}
///
///
/// - Parameter block: the block or the Block reference
/// Delete a Block its Block, raw file
///
/// - Parameters:
/// - block: the block or the Block
open func deleteBlockFile(_ block:Block) {
if let node:Node = block.firstRelation(Relationship.ownedBy){
node.removeRelation(Relationship.owns, to: block)
node.numberOfBlocks -= 1
}else{
self._document.log("Block's node not found (block.UID:\(block.UID)", file: #file, function: #function, line: #line, category: Default.LOG_FAULT, decorative: false)
}
self._document.blocks.removeObject(block)
do{
try self._document.removeBlock(with: block.digest)
}catch{
self._document.log("\(error)", file: #file, function: #function, line: #line, category: Default.LOG_WARNING, decorative: false)
}
}
}
| f86f31dc2a2568d3a55662ddb64ceb14 | 41.687606 | 264 | 0.499781 | false | false | false | false |
lelandjansen/fatigue | refs/heads/master | ios/fatigue/Result.swift | apache-2.0 | 1 | import Foundation
class Result: QuestionnaireItem {
enum QualitativeRisk {
case low, medium, high, veryHigh
}
static func getQualitativeRisk(forRiskScore riskScore: Int32) -> QualitativeRisk {
if riskScore < 6 {
return .low
} else if riskScore < 15 {
return .medium
} else if riskScore < 18 {
return .high
} else {
return .veryHigh
}
}
static func getRemark(forRiskScore riskScore: Int32, role: Role) -> String {
let qualitativeRisk = getQualitativeRisk(forRiskScore: riskScore)
return getRemark(forQualitativeRisk: qualitativeRisk, role: role)
}
static func getRemark(forQualitativeRisk qualitativeRisk: QualitativeRisk, role: Role) -> String {
switch (role, qualitativeRisk) {
case (.none, _):
fatalError("Role cannot be none")
case (_, .low):
return "Continue as normal."
case (.pilot, .medium):
return "Reduce flight time and if possible reduce duty period."
case (.engineer, .medium):
return "Reduce duty day and defer all non-essential tasks."
case (.pilot, .high):
return "Proceed upon approval from your supervisor."
case (.engineer, .high):
return "Proceed upon approval from your supervisor."
case (.pilot, .veryHigh):
return "Stay on the ground."
case (.engineer, .veryHigh):
return "Defer all maintenance."
default:
fatalError("No remark for qualitative risk and occupation (\(qualitativeRisk), \(role))")
}
}
var riskScore: Int32 = 0 {
didSet {
qualitativeRisk = Result.getQualitativeRisk(forRiskScore: riskScore)
remark = Result.getRemark(forQualitativeRisk: qualitativeRisk!, role: UserDefaults.standard.role)
}
}
var remark: String = String()
var nextItem: QuestionnaireItem?
var qualitativeRisk: QualitativeRisk?
}
| 777b6622c0b89baf62598efeaaac57f0 | 34.482759 | 109 | 0.604956 | false | false | false | false |
buyiyang/iosstar | refs/heads/master | iOSStar/Scenes/Discover/CustomView/PlayVC.swift | gpl-3.0 | 3 | //
// PlayVC.swift
// iOSStar
//
// Created by sum on 2017/8/16.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import PLShortVideoKit
class PlayVC: UIViewController {
var asset : AVAsset?
var settings : [String : AnyObject]?
var shortVideoRecorder : PLShortVideoEditor?
var groupLb : UILabel?
var totaltime : CGFloat = 0
var timer : Timer?
var start : UIButton?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// self.navigationController?.setNavigationBarHidden(false, animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
self.shortVideoRecorder = PLShortVideoEditor.init(asset: asset)
self.shortVideoRecorder?.player.preview?.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
self.view.addSubview((self.shortVideoRecorder?.player.preview!)!)
self.shortVideoRecorder?.player.play()
gettotal()
initUI()
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateGrogress), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initUI(){
let share = UIButton.init(type: .custom)
share.frame = CGRect.init(x: kScreenWidth - 100, y: 80, width: 70, height: 30)
share.setTitle("关闭", for: .normal)
share.titleLabel?.font = UIFont.systemFont(ofSize: 15)
share.setTitleColor(UIColor.init(hexString: AppConst.Color.main), for: .normal)
// share.addTarget(self, action: #selector(publish), for: .touchUpInside)
self.view.addSubview(share)
start = UIButton.init(type: .custom)
start?.frame = CGRect.init(x:view.center.x - 35, y: view.center.y, width: 70, height: 70)
start?.setTitle("播放", for: .normal)
start?.titleLabel?.font = UIFont.systemFont(ofSize: 15)
start?.backgroundColor = UIColor.white
start?.setTitleColor(UIColor.init(hexString: AppConst.Color.main), for: .normal)
// share.addTarget(self, action: #selector(publish), for: .touchUpInside)
self.view.addSubview(start!)
start?.addTarget(self , action: #selector(dobegain), for: .touchUpInside)
start?.isHidden = true
}
func dobegain(){
self.shortVideoRecorder?.player.setItemBy(asset)
self.shortVideoRecorder?.player.play()
groupLb?.frame = CGRect.init(x: 20, y: 30, width: 0 , height: 5)
totaltime = 0
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateGrogress), userInfo: nil, repeats: true)
start?.isHidden = true
}
func updateGrogress(){
if let total = self.settings?["PLSDurationKey"] as? CGFloat{
let progress = (kScreenWidth - 40) / total
if (totaltime < total){
totaltime = totaltime + 0.1
if (totaltime * progress > (kScreenWidth - 40)){
groupLb?.frame = CGRect.init(x: 20, y: 30, width: kScreenWidth - 40 , height: 5)
}else{
groupLb?.frame = CGRect.init(x: 20, y: 30, width: totaltime * progress , height: 5)
}
}else{
timer?.invalidate()
// self.shortVideoRecorder?.player.pause()
start?.isHidden = false
}
}
}
func gettotal(){
let bgLabel = UILabel.init(frame: CGRect.init(x: 20, y: 30, width: self.view.frame.size.width - 40, height: 5))
bgLabel.backgroundColor = UIColor.init(red: 255, green: 255, blue: 255, alpha: 0.5)
self.view.addSubview(bgLabel)
groupLb = UILabel.init(frame: CGRect.init(x: 20, y: 30, width: 00, height: 5))
groupLb?.backgroundColor = UIColor.init(hexString: "FB9938")
self.view.addSubview(groupLb!)
}
}
| ab9bc2493332a85a27b8db6d1b00249b | 38.970297 | 136 | 0.620015 | false | false | false | false |
younata/RSSClient | refs/heads/master | Tethys/Generic/CoreGraphicsLinearAlgebra.swift | mit | 1 | import CoreGraphics
extension CGPoint {
static func - (lhs: CGPoint, rhs: CGPoint) -> CGVector {
return CGVector(dx: lhs.x - rhs.x, dy: lhs.y - rhs.y)
}
static func + (lhs: CGPoint, rhs: CGVector) -> CGPoint {
return CGPoint(x: lhs.x + rhs.dx, y: lhs.y + rhs.dy)
}
static func += (lhs: inout CGPoint, rhs: CGVector) {
lhs = lhs + rhs // swiftlint:disable:this shorthand_operator
}
}
extension CGVector {
func magnitudeSquared() -> CGFloat {
return pow(self.dx, 2) + pow(self.dy, 2)
}
func normalized() -> CGVector {
let x2 = pow(dx, 2)
let y2 = pow(dy, 2)
let mag = sqrt(x2 + y2)
return CGVector(dx: self.dx / mag, dy: self.dy / mag)
}
}
| ac4feeb6761f17bccaf0b59a27f175d8 | 24.793103 | 68 | 0.565508 | false | false | false | false |
csnu17/My-Swift-learning | refs/heads/master | collection-data-structures-swift/DataStructures/NSDictionaryManipulator.swift | mit | 1 | //
// NSDictionaryManipulator.swift
// DataStructures
//
// Created by Ellen Shapiro on 8/3/14.
// Copyright (c) 2014 Ray Wenderlich Tutorial Team. All rights reserved.
//
import Foundation
class NSDictionaryManipulator: DictionaryManipulator {
var intDictionary = NSMutableDictionary()
func dictHasEntries() -> Bool {
if (intDictionary.count == 0) {
return false
} else {
return true
}
}
//MARK: Setup
func setupWithEntryCount(_ count: Int) -> TimeInterval {
return Profiler.runClosureForTime() {
for i in 0 ..< count {
self.intDictionary.setObject(i, forKey: i as NSCopying)
}
}
}
fileprivate func nextElement() -> Int {
return self.intDictionary.count + 1
}
//MARK: Adding entries
func addEntries(_ count: Int) -> TimeInterval {
var dictionary = [Int: Int]()
let next = nextElement()
for i in 0 ..< count {
let plusI = next + i
dictionary[plusI] = plusI
}
let time = Profiler.runClosureForTime() {
self.intDictionary.addEntries(from: dictionary)
}
//Restore to original state
let keys = Array(dictionary.keys)
self.intDictionary.removeObjects(forKeys: keys)
return time
}
func add1Entry() -> TimeInterval {
return addEntries(1)
}
func add5Entries() -> TimeInterval {
return addEntries(5)
}
func add10Entries() -> TimeInterval {
return addEntries(10)
}
//MARK: Removing entries
func removeEntries(_ count: Int) -> TimeInterval {
var dictionary = [Int: Int]()
let next = nextElement()
for i in 0 ..< count {
let plusI = next + i
dictionary[plusI] = plusI
}
self.intDictionary.addEntries(from: dictionary)
//Restore to original state
let keys = Array(dictionary.keys)
return Profiler.runClosureForTime() {
self.intDictionary.removeObjects(forKeys: keys)
}
}
func remove1Entry() -> TimeInterval {
return removeEntries(1)
}
func remove5Entries() -> TimeInterval {
return removeEntries(5)
}
func remove10Entries() -> TimeInterval {
return removeEntries(10)
}
//MARK: Looking up entries
func lookupEntries(_ count: Int) -> TimeInterval {
var dictionary = [Int: Int]()
let next = nextElement()
for i in 0 ..< count {
let plusI = next + i
dictionary[plusI] = plusI
}
self.intDictionary.addEntries(from: dictionary)
let keys = Array(dictionary.keys)
let time = Profiler.runClosureForTime() {
for key in keys {
self.intDictionary.object(forKey: key)
}
}
//Restore to original state
self.intDictionary.removeObjects(forKeys: keys)
return time
}
func lookup1EntryTime() -> TimeInterval {
return lookupEntries(1)
}
func lookup10EntriesTime() -> TimeInterval {
return lookupEntries(10)
}
}
| a4724cc67f4c084aca515e5d1efa94b3 | 21.007463 | 73 | 0.62394 | false | false | false | false |
minikin/Algorithmics | refs/heads/master | Pods/PSOperations/PSOperations/OperationCondition.swift | mit | 1 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file contains the fundamental logic relating to Operation conditions.
*/
import Foundation
public let OperationConditionKey = "OperationCondition"
/**
A protocol for defining conditions that must be satisfied in order for an
operation to begin execution.
*/
public protocol OperationCondition {
/**
The name of the condition. This is used in userInfo dictionaries of `.ConditionFailed`
errors as the value of the `OperationConditionKey` key.
*/
static var name: String { get }
/**
Specifies whether multiple instances of the conditionalized operation may
be executing simultaneously.
*/
static var isMutuallyExclusive: Bool { get }
/**
Some conditions may have the ability to satisfy the condition if another
operation is executed first. Use this method to return an operation that
(for example) asks for permission to perform the operation
- parameter operation: The `Operation` to which the Condition has been added.
- returns: An `NSOperation`, if a dependency should be automatically added. Otherwise, `nil`.
- note: Only a single operation may be returned as a dependency. If you
find that you need to return multiple operations, then you should be
expressing that as multiple conditions. Alternatively, you could return
a single `GroupOperation` that executes multiple operations internally.
*/
func dependencyForOperation(operation: Operation) -> NSOperation?
/// Evaluate the condition, to see if it has been satisfied or not.
func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void)
}
/**
An enum to indicate whether an `OperationCondition` was satisfied, or if it
failed with an error.
*/
public enum OperationConditionResult {
case Satisfied
case Failed(NSError)
var error: NSError? {
switch self {
case .Failed(let error):
return error
default:
return nil
}
}
}
func ==(lhs: OperationConditionResult, rhs: OperationConditionResult) -> Bool {
switch (lhs, rhs) {
case (.Satisfied, .Satisfied):
return true
case (.Failed(let lError), .Failed(let rError)) where lError == rError:
return true
default:
return false
}
}
// MARK: Evaluate Conditions
struct OperationConditionEvaluator {
static func evaluate(conditions: [OperationCondition], operation: Operation, completion: [NSError] -> Void) {
// Check conditions.
let conditionGroup = dispatch_group_create()
var results = [OperationConditionResult?](count: conditions.count, repeatedValue: nil)
// Ask each condition to evaluate and store its result in the "results" array.
for (index, condition) in conditions.enumerate() {
dispatch_group_enter(conditionGroup)
condition.evaluateForOperation(operation) { result in
results[index] = result
dispatch_group_leave(conditionGroup)
}
}
// After all the conditions have evaluated, this block will execute.
dispatch_group_notify(conditionGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) {
// Aggregate the errors that occurred, in order.
var failures = results.flatMap { $0?.error }
/*
If any of the conditions caused this operation to be cancelled,
check for that.
*/
if operation.cancelled {
failures.append(NSError(code: .ConditionFailed))
}
completion(failures)
}
}
}
| 6fc9d91698a3b4e6f6fc044c415638ff | 33.875 | 113 | 0.650282 | false | false | false | false |
duming91/Hear-You | refs/heads/master | Hear You/Services/Request.swift | gpl-3.0 | 1 | //
// Request.swift
// Hear You
//
// Created by 董亚珣 on 16/5/12.
// Copyright © 2016年 snow. All rights reserved.
//
import Foundation
import Alamofire
/// api根路径
let baseURL = NSURL(string: "http://api.dongting.com/")!
let searchBaseURL = NSURL(string: "http://search.dongting.com/")!
let lricdBaseURL = NSURL(string: "http://lp.music.ttpod.com/")!
typealias NetworkSucceed = (result: JSONDictionary) -> ()
typealias NetworkFailed = (reason: NSError) -> ()
/**
post请求
- parameter URLString: 接口url
- parameter parameters: 参数
- parameter finished: 回调
*/
func apiRequest(apiName apiName: String, URLString: String, headers: [String : String]?, parameters: JSONDictionary?, encoding: ParameterEncoding, failed: NetworkFailed?, succeed: NetworkSucceed) {
println("\n***************************** Networking Request *****************************")
println("\nAPI: \(apiName)")
println("\nURL: \(URLString)")
println("\nParameters: \(parameters)")
println("\n******************************************************************************")
Alamofire.request(.GET, URLString, parameters: parameters, encoding: encoding, headers: headers).responseJSON { (response) in
println("\n***************************** Networking Response *****************************")
println("\nAPI: \(apiName)")
println("\nResponse:\n\(response.result.value)")
println("\n*******************************************************************************")
if let JSON = response.result.value {
if let dict = JSON as? JSONDictionary {
succeed(result: dict)
} else {
println("\nNetworking Failed: resopnse data is not a JSONDictionary")
}
} else {
println("\nNetworking Failed: \(response.result.error)")
if let failed = failed {
failed(reason: response.result.error!)
}
}
}
}
// MARK: - 搜索歌曲
func searchSongWithName(name: String, page: String, size: String, failed: NetworkFailed?, succeed: [Song] -> Void) {
let parameters: JSONDictionary = [
"q": name,
"page": page,
"size": size,
]
apiRequest(apiName: "搜索歌曲", URLString: "http://search.dongting.com/song/search", headers: nil, parameters: parameters, encoding: .URL, failed: failed) { (result) in
if let data = result["data"] as? [JSONDictionary] {
var searchSongList = [Song]()
for songInfo in data {
guard let song = Song.fromJSONDictionary(songInfo) else {
continue
}
searchSongList.append(song)
}
succeed(searchSongList)
}
}
}
// MARK: - 歌曲列表
func searchSongList(albumID: String, failed: NetworkFailed?, succeed: SongList -> Void) {
apiRequest(apiName: "搜索歌曲", URLString: "http://api.songlist.ttpod.com/songlists/" + albumID, headers: nil, parameters: nil, encoding: .URL, failed: failed) { (result) in
let songlist = SongList.fromJSONDictionary(result)
succeed(songlist)
}
}
// MARK: - 首页展示
func getFrontpageInformation(failed: NetworkFailed?, succeed: [FrontpageElement] -> Void) {
apiRequest(apiName: "首页展示", URLString: "http://api.dongting.com/frontpage/frontpage", headers: nil, parameters: nil, encoding: .URL, failed: failed) { (result) in
if let data = result["data"] as? [JSONDictionary] {
let frontpageElements = FrontpageElement.frmeJSONArray(data)
println(frontpageElements)
succeed(frontpageElements)
}
}
}
| 4679e95778514b16fa00dfc1ef2b29e5 | 32.539823 | 197 | 0.552243 | false | false | false | false |
dataich/TypetalkSwift | refs/heads/master | TypetalkSwift/Client.swift | mit | 1 | //
// Client.swift
// TypetalkSwift
//
// Created by Taichiro Yoshida on 2017/10/15.
// Copyright © 2017 Nulab Inc. All rights reserved.
//
import Alamofire
import OAuth2
public class Client {
static let shared: Client = Client()
static let ErrorDomain = "TypetalkSwift.err"
var oauth2: OAuth2!
var manager: SessionManager!
let decoder = JSONDecoder()
static var baseUrl: String = "https://typetalk.com"
private init() {
}
public class func setAPISettings(
baseUrl: String? = nil,
clientId: String,
clientSecret: String,
scopes: [OAuth2Scope],
redirectUri: String,
authorizeContext: Any) {
if let baseUrl = baseUrl {
Client.baseUrl = baseUrl
}
let settings = [
"client_id": clientId,
"client_secret": clientSecret,
"authorize_uri": "\(Client.baseUrl)/oauth2/authorize",
"token_uri": "\(Client.baseUrl)/oauth2/access_token",
"scope": scopes.map{$0.rawValue}.joined(separator: ","),
"redirect_uris": [redirectUri],
"keychain": true,
"verbose": true
] as OAuth2JSON
let oauth2 = CustomOAuth2CodeGrant(settings: settings)
oauth2.authConfig.authorizeEmbedded = true
oauth2.authConfig.authorizeContext = authorizeContext as AnyObject
oauth2.logger = OAuth2DebugLogger(.trace)
shared.oauth2 = oauth2
let manager = SessionManager()
let retrier = OAuth2RetryHandler(oauth2: oauth2)
manager.adapter = retrier
manager.retrier = retrier
shared.manager = manager
shared.decoder.dateDecodingStrategy = .iso8601
}
private func responseDecodableObject<T: Request>(_ request:T, dataRequest: DataRequest, completionHandler:@escaping ((Result<T.Response>) -> Void)) -> Void {
let statusCode = 200..<300
dataRequest
.validate(statusCode: statusCode)
.responseDecodableObject(decoder: decoder) { (response: DataResponse<T.Response>) in
let result: Result<T.Response>
if let value = response.value {
result = Result.success(value)
} else {
result = Result.failure(response.error ?? APIError.unknown)
}
completionHandler(result)
}
}
public class func send<T: Request>(_ request:T, completionHandler:@escaping ((Result<T.Response>) -> Void)) -> Void {
shared.oauth2.authorize { (authParameters, error) in
if let _ = authParameters {
guard let urlRequest = try? request.asURLRequest(Client.baseUrl) else { return }
if let bodyParameter = request.bodyParameter {
shared.manager.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(bodyParameter.data, withName: bodyParameter.withName, fileName: bodyParameter.fileName, mimeType: bodyParameter.mimeType)
}, with: urlRequest, encodingCompletion: { (encodingResult) in
switch encodingResult {
case .success(let dataRequest, _, _):
shared.responseDecodableObject(request, dataRequest: dataRequest, completionHandler: completionHandler)
case .failure(let error):
print(error)
}
})
} else {
shared.responseDecodableObject(request, dataRequest: shared.manager.request(urlRequest), completionHandler: completionHandler)
}
} else {
print("Authorization was canceled or went wrong: \(error.debugDescription)") // error will not be nil
}
}
}
public class func handleRedirectURL(url: URL) throws -> Void {
try shared.oauth2.handleRedirectURL(url)
}
}
| 6e2e4568251859e8f6540ff09975cb2e | 32.398148 | 159 | 0.659274 | false | false | false | false |
MagicianDL/Shark | refs/heads/master | Shark/Utils/SKUtils.swift | mit | 1 | //
// SKUtils.swift
// Shark
//
// Created by Dalang on 2017/3/3.
// Copyright © 2017年 青岛鲨鱼汇信息技术有限公司. All rights reserved.
//
/// 常用方法
import UIKit
class SKUtils: NSObject {
class func initializeAppDefaultSetting() {
initializeNavigationBar()
initializeTabbar()
}
/// tabbar 设置
class func initializeTabbar() {
let normalAttributes: Dictionary = [
NSForegroundColorAttributeName: UIColor(hexString: "#A9A8A8")
]
let selectedAttribute: Dictionary = [
NSForegroundColorAttributeName: UIColor.mainBlue
]
UITabBarItem.appearance().setTitleTextAttributes(normalAttributes, for: UIControlState.normal)
UITabBarItem.appearance().setTitleTextAttributes(selectedAttribute, for: UIControlState.selected)
UITabBar.appearance().tintColor = UIColor.mainBlue
}
/// 导航栏设置
class func initializeNavigationBar() {
let attributes = [
NSForegroundColorAttributeName: UIColor.mainBlue,
NSFontAttributeName: UIFont.systemFont(ofSize: 20)
]
UINavigationBar.appearance().titleTextAttributes = attributes
UINavigationBar.appearance().tintColor = UIColor.mainBlue
}
}
| 901c74edd7e7c18dfff4be427ca2ba03 | 25.571429 | 105 | 0.641321 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | Mac/MainWindow/AddFeed/FolderTreeMenu.swift | mit | 1 | //
// FolderTreeMenu.swift
// NetNewsWire
//
// Created by Maurice Parker on 9/12/18.
// Copyright © 2018 Ranchero Software, LLC. All rights reserved.
//
import AppKit
import RSCore
import RSTree
import Account
class FolderTreeMenu {
static func createFolderPopupMenu(with rootNode: Node, restrictToSpecialAccounts: Bool = false) -> NSMenu {
let menu = NSMenu(title: "Folders")
menu.autoenablesItems = false
for childNode in rootNode.childNodes {
guard let account = childNode.representedObject as? Account else {
continue
}
if restrictToSpecialAccounts && !(account.type == .onMyMac || account.type == .cloudKit) {
continue
}
let menuItem = NSMenuItem(title: account.nameForDisplay, action: nil, keyEquivalent: "")
menuItem.representedObject = childNode.representedObject
if account.behaviors.contains(.disallowFeedInRootFolder) {
menuItem.isEnabled = false
}
menu.addItem(menuItem)
let childNodes = childNode.childNodes
addFolderItemsToMenuWithNodes(menu: menu, nodes: childNodes, indentationLevel: 1)
}
return menu
}
static func select(account: Account, folder: Folder?, in popupButton: NSPopUpButton) {
for menuItem in popupButton.itemArray {
if let oneAccount = menuItem.representedObject as? Account, oneAccount == account && folder == nil {
popupButton.select(menuItem)
return
}
if let oneFolder = menuItem.representedObject as? Folder, oneFolder == folder {
if oneFolder.account == account {
popupButton.select(menuItem)
return
}
}
}
}
private static func addFolderItemsToMenuWithNodes(menu: NSMenu, nodes: [Node], indentationLevel: Int) {
nodes.forEach { (oneNode) in
if let nameProvider = oneNode.representedObject as? DisplayNameProvider {
let menuItem = NSMenuItem(title: nameProvider.nameForDisplay, action: nil, keyEquivalent: "")
menuItem.indentationLevel = indentationLevel
menuItem.representedObject = oneNode.representedObject
menu.addItem(menuItem)
if oneNode.numberOfChildNodes > 0 {
addFolderItemsToMenuWithNodes(menu: menu, nodes: oneNode.childNodes, indentationLevel: indentationLevel + 1)
}
}
}
}
}
| 4117730f3efd60697f9f03bc038bd590 | 26.493827 | 113 | 0.71621 | false | false | false | false |
CaiMiao/CGSSGuide | refs/heads/master | DereGuide/Unit/Editing/View/MemberGroupView.swift | mit | 1 | //
// MemberEditableItemView.swift
// DereGuide
//
// Created by zzk on 2017/6/16.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import SnapKit
class MemberEditableItemView: UIView {
var cardView: UnitSimulationCardView!
var overlayView: UIView!
var placeholderImageView: UIImageView!
var cardPlaceholder: UIView!
private(set) var isSelected: Bool = false
private var strokeColor: CGColor = UIColor.lightGray.cgColor {
didSet {
overlayView.layer.borderColor = isSelected ? strokeColor : UIColor.lightGray.cgColor
overlayView.layer.shadowColor = strokeColor
}
}
private func setSelected(_ selected: Bool) {
isSelected = selected
if selected {
overlayView.layer.shadowOpacity = 1
overlayView.layer.borderColor = strokeColor
overlayView.layer.shadowColor = strokeColor
overlayView.layer.borderWidth = 2
} else {
overlayView.layer.shadowOpacity = 0
overlayView.layer.borderColor = UIColor.lightGray.cgColor
overlayView.layer.borderWidth = 0
}
}
func setSelected(selected: Bool, animated: Bool) {
if animated {
overlayView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
self.overlayView.transform = .identity
self.setSelected(selected)
}, completion: nil)
} else {
setSelected(selected)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
overlayView = UIView()
addSubview(overlayView)
overlayView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
overlayView.layer.shadowOffset = CGSize.zero
setSelected(false)
cardView = UnitSimulationCardView()
cardView.icon.isUserInteractionEnabled = false
addSubview(cardView)
cardView.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4))
make.height.greaterThanOrEqualTo(cardView.snp.width).offset(29)
}
placeholderImageView = UIImageView(image: #imageLiteral(resourceName: "436-plus").withRenderingMode(.alwaysTemplate))
addSubview(placeholderImageView)
placeholderImageView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.height.width.equalTo(self.snp.width).dividedBy(3)
}
placeholderImageView.tintColor = .lightGray
cardPlaceholder = UIView()
addSubview(cardPlaceholder)
cardPlaceholder.snp.makeConstraints { (make) in
make.width.equalToSuperview().offset(-8)
make.height.equalTo(cardPlaceholder.snp.width)
make.center.equalToSuperview()
}
cardPlaceholder.layer.masksToBounds = true
cardPlaceholder.layer.cornerRadius = 4
cardPlaceholder.layer.borderWidth = 1 / Screen.scale
cardPlaceholder.layer.borderColor = UIColor.border.cgColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(with member: Member) {
placeholderImageView.isHidden = true
cardPlaceholder.isHidden = true
if let color = member.card?.attColor.cgColor {
strokeColor = color
}
cardView.setup(with: member)
bringSubview(toFront: cardView)
}
}
protocol MemberGroupViewDelegate: class {
func memberGroupView(_ memberGroupView: MemberGroupView, didLongPressAt item: MemberEditableItemView)
func memberEditableView(_ memberGroupView: MemberGroupView, didDoubleTap item: MemberEditableItemView)
}
class MemberGroupView: UIView {
weak var delegate: MemberGroupViewDelegate?
var descLabel: UILabel!
var stackView: UIStackView!
var editableItemViews: [MemberEditableItemView]!
var centerLabel: UILabel!
var guestLabel: UILabel!
var currentIndex: Int = 0 {
didSet {
if oldValue != currentIndex {
editableItemViews[oldValue].setSelected(selected: false, animated: false)
editableItemViews[currentIndex].setSelected(selected: true, animated: true)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
editableItemViews = [MemberEditableItemView]()
for _ in 0..<6 {
let view = MemberEditableItemView()
editableItemViews.append(view)
view.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(_:)))
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTapGesture(_:)))
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)
view.addGestureRecognizer(tap)
view.addGestureRecognizer(longPress)
}
editableItemViews[0].setSelected(selected: true, animated: false)
stackView = UIStackView(arrangedSubviews: editableItemViews)
stackView.spacing = 6
stackView.distribution = .fillEqually
stackView.alignment = .center
addSubview(stackView)
stackView.snp.remakeConstraints { (make) in
make.left.greaterThanOrEqualTo(10)
make.right.lessThanOrEqualTo(-10)
// make the view as wide as possible
make.right.equalTo(-10).priority(900)
make.left.equalTo(10).priority(900)
//
make.bottom.equalTo(-10)
make.width.lessThanOrEqualTo(104 * 6 + 30)
make.centerX.equalToSuperview()
}
centerLabel = UILabel()
centerLabel.text = NSLocalizedString("队长", comment: "")
centerLabel.font = UIFont.systemFont(ofSize: 12)
centerLabel.adjustsFontSizeToFitWidth = true
addSubview(centerLabel)
centerLabel.snp.makeConstraints { (make) in
make.top.equalTo(5)
make.centerX.equalTo(editableItemViews[0])
make.bottom.equalTo(stackView.snp.top).offset(-5)
make.width.lessThanOrEqualTo(editableItemViews[0].snp.width).offset(-4)
}
guestLabel = UILabel()
guestLabel.text = NSLocalizedString("好友", comment: "")
guestLabel.font = UIFont.systemFont(ofSize: 12)
guestLabel.adjustsFontSizeToFitWidth = true
addSubview(guestLabel)
guestLabel.snp.makeConstraints { (make) in
make.top.equalTo(centerLabel)
make.width.lessThanOrEqualTo(editableItemViews[5].snp.width).offset(-4)
make.centerX.equalTo(editableItemViews[5])
}
}
@objc func handleTapGesture(_ tap: UITapGestureRecognizer) {
if let view = tap.view as? MemberEditableItemView {
if let index = stackView.arrangedSubviews.index(of: view) {
currentIndex = index
}
}
}
@objc func handleLongPressGesture(_ longPress: UILongPressGestureRecognizer) {
if longPress.state == .began {
guard let view = longPress.view as? MemberEditableItemView else { return }
if let index = stackView.arrangedSubviews.index(of: view) {
currentIndex = index
}
delegate?.memberGroupView(self, didLongPressAt: view)
}
}
@objc func handleDoubleTapGesture(_ doubleTap: UITapGestureRecognizer) {
guard let view = doubleTap.view as? MemberEditableItemView else { return }
delegate?.memberEditableView(self, didDoubleTap: view)
}
func setup(with unit: Unit) {
for i in 0..<6 {
let member = unit[i]
setup(with: member, at: i)
}
}
func moveIndexToNext() {
var nextIndex = currentIndex + 1
if nextIndex == 6 {
nextIndex = 0
}
currentIndex = nextIndex
}
func setup(with member: Member, at index: Int) {
editableItemViews[index].setup(with: member)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 49e94ca397ecaf1eca8213871ebd593f | 34.785124 | 125 | 0.624942 | false | false | false | false |
blstream/TOZ_iOS | refs/heads/master | TOZ_iOS/OrganizationInfoResponseMapper.swift | apache-2.0 | 1 | //
// OrganizationInfoResponseMapper.swift
// TOZ_iOS
//
// Copyright © 2017 intive. All rights reserved.
//
import Foundation
/**
Parses response from OrganizationInfo operation. Inherits from generic ResponseMapper class.
*/
final class OrganizationInfoResponseMapper: ResponseMapper<OrganizationInfoItem>, ResponseMapperProtocol {
// swiftlint:disable cyclomatic_complexity
static func process(_ obj: AnyObject?) throws -> OrganizationInfoItem {
// swiftlint:enable cyclomatic_complexity
return try process(obj, parse: { json in
guard let name = json["name"] as? String else { return nil }
guard let invitationText = json["invitationText"] as? String? else { return nil }
guard let volunteerText = json["volunteerText"] as? String? else { return nil }
guard let address = json["address"] as? [String: Any] else { return nil }
guard let street = address["street"] as? String? else { return nil }
guard let houseNumber = address["houseNumber"] as? String? else { return nil }
guard let apartmentNumber = address["apartmentNumber"] as? String? else { return nil }
var adressApartmentNumber: String? = nil
if let apartmentNumber = apartmentNumber {
adressApartmentNumber = "/" + apartmentNumber
}
guard let postcode = address["postCode"] as? String? else { return nil }
guard let city = address["city"] as? String? else { return nil }
guard let country = address["country"] as? String? else { return nil }
guard let contact = json["contact"] as? [String: Any] else { return nil }
guard let email = contact["email"] as? String? else { return nil }
guard let phone = contact["phone"] as? String? else { return nil }
guard let fax = contact["fax"] as? String? else { return nil }
guard let website = contact["website"] as? String? else { return nil }
guard let bankAccount = json["bankAccount"] as? [String: Any] else { return nil }
guard let accountNumber = bankAccount["number"] as? String else { return nil }
guard let bankName = bankAccount["bankName"] as? String? else { return nil }
return OrganizationInfoItem(name: name, invitationText: invitationText, volunteerText: volunteerText, street: street, houseNumber: houseNumber, apartmentNumber: adressApartmentNumber, postCode: postcode, city: city, country: country, email: email, phone: phone, fax: fax, website: website, accountNumber: accountNumber, bankName: bankName)
})
}
}
| 2446ed6b12690b149eedaa7357de0bc4 | 59.272727 | 351 | 0.657617 | false | false | false | false |
gavrix/AnyAnimation | refs/heads/master | Examples/AnyAnimationTestbed/ManualAnimatorViewController.swift | mit | 1 | //
// ManualAnimatorViewController.swift
// AnyAnimationTestbed
//
// Created by Sergey Gavrilyuk on 2017-09-05.
// Copyright © 2017 Gavrix. All rights reserved.
//
import Foundation
import UIKit
import AnyAnimation
class ManualAnimatorViewController: UIViewController {
@IBOutlet weak var movingViewXConstraint: NSLayoutConstraint!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var movingView: UIView!
var animator = ManualAnimator()
lazy var xProperty: AnimatableProperty<CGFloat> = {
return AnimatableProperty(self.movingViewXConstraint.constant) {
[unowned self] in
self.movingViewXConstraint.constant = $0
}
}()
lazy var rotationProperty: AnimatableProperty<CGFloat> = {
return AnimatableProperty(0) { [unowned self] in
self.movingView.transform = CGAffineTransform(rotationAngle: $0)
}
}()
@IBAction func sliderValueChanged(_ slider: UISlider) {
self.animator.time = RelativeTimeInterval(interval: TimeInterval(slider.value), maxInterval: TimeInterval(slider.maximumValue))
}
override func viewDidLoad() {
super.viewDidLoad()
let animation =
AnimationGroup([
BasicAnimation(from: xProperty.value, to: containerView.frame.width - movingView.frame.width * CGFloat(0.5),
on: self.xProperty, duration: 1),
BasicAnimation(from: 0, to: CGFloat.pi, on: self.rotationProperty, duration: 1)
])
self.animator.run(animation: animation)
}
}
| 4ceac4c22d6a8d3a6d318426b71856d4 | 28.529412 | 131 | 0.707835 | false | false | false | false |
shyn/cs193p | refs/heads/master | Happiness/Happiness/FaceView.swift | mit | 2 | //
// FaceView.swift
// Happiness
//
// Created by deepwind on 4/29/17.
// Copyright © 2017 deepwind. All rights reserved.
//
import UIKit
protocol FaceViewDataSource: class {
// var happiness: Int { get set}
func smilinessForFaceView(sender: FaceView) -> Double?
}
@IBDesignable
class FaceView: UIView
{
@IBInspectable
var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay() } }
@IBInspectable
var scale:CGFloat = 0.9 { didSet { setNeedsDisplay() } }
@IBInspectable
var color:UIColor = UIColor.blue { didSet { setNeedsDisplay() } }
var faceCenter: CGPoint {
return convert(center, from: superview)
}
var faceRadius: CGFloat {
return min(bounds.height, bounds.width)/2 * scale
}
// do not keep this pointer in memory to avoid cycle reference
// but weak can not decorate protocol.. so we make our protocol a 'class':)
weak var dataSource: FaceViewDataSource?
func pinch(_ gesture: UIPinchGestureRecognizer) {
if gesture.state == .changed {
scale *= gesture.scale
gesture.scale = 1
}
}
override func draw(_ rect: CGRect) {
let facePath = UIBezierPath(arcCenter: faceCenter, radius: faceRadius, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true)
facePath.lineWidth = lineWidth
color.set()
facePath.stroke()
let smiliness = dataSource?.smilinessForFaceView(sender: self) ?? 0.5
bezierPathForEye(whichEye: .Left).stroke()
bezierPathForEye(whichEye: .Right).stroke()
bezierPathForSmile(fractionOfMaxSmile: smiliness).stroke()
}
private struct Scaling {
static let FaceRadiusToEyeRadiusRatio: CGFloat = 10
static let FaceRadiusToEyeOffsetRatio: CGFloat = 3
static let FaceRadiusToEyeSeparationRatio: CGFloat = 1.5
static let FaceRadiusToMouthWidthRatio: CGFloat = 1
static let FaceRadiusToMouthHeightRatio: CGFloat = 3
static let FaceRadiusToMouthOffsetRatio: CGFloat = 3
}
private enum Eye { case Left, Right }
private func bezierPathForSmile(fractionOfMaxSmile: Double) -> UIBezierPath
{
let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio
let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio
let mouthVerticleOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio
let smileHeight = CGFloat(max(min(fractionOfMaxSmile, 1), -1)) * mouthHeight
let start = CGPoint(x: faceCenter.x - mouthWidth/2, y: faceCenter.y + mouthVerticleOffset)
let end = CGPoint(x: start.x + mouthWidth, y: start.y)
let cp1 = CGPoint(x: start.x + mouthWidth/3, y: start.y + smileHeight)
let cp2 = CGPoint(x: end.x - mouthWidth/3, y: cp1.y)
let path = UIBezierPath()
path.move(to: start)
path.addCurve(to: end, controlPoint1: cp1, controlPoint2: cp2)
path.lineWidth = lineWidth
return path
}
private func bezierPathForEye(whichEye: Eye) -> UIBezierPath
{
let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio
let eyeVerticalOffset = faceRadius / Scaling.FaceRadiusToEyeOffsetRatio
let eyeHorizontalSeparation = faceRadius / Scaling.FaceRadiusToEyeSeparationRatio
var eyeCenter = faceCenter
eyeCenter.y -= eyeVerticalOffset
switch whichEye {
case .Left:
eyeCenter.x -= eyeHorizontalSeparation / 2
case .Right:
eyeCenter.x += eyeHorizontalSeparation / 2
}
let path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true)
path.lineWidth = lineWidth
return path
}
}
| 0195fc43877e16befc84d5186e1792bf | 35.638095 | 142 | 0.656875 | false | false | false | false |
bmroberts1987/MY_PLAID_BANK | refs/heads/master | Plaid.swift | gpl-2.0 | 1 | //
// Plaid.swift
// Plaid Swift Wrapper
//
// Created by Cameron Smith on 4/20/15.
// Copyright (c) 2015 Cameron Smith. All rights reserved.
//
import Foundation
struct Plaid {
static var baseURL:String!
static var clientId:String!
static var secret:String!
static func initializePlaid(clientId: String, secret: String, appStatus: BaseURL) {
Plaid.clientId = clientId
Plaid.secret =
switch appStatus {
case .Production:
baseURL = "https://api.plaid.com/"
case .Testing:
baseURL = "https://tartan.plaid.com/"
}
}
}
let session = NSURLSession.sharedSession()
enum BaseURL {
case Production
case Testing
}
public enum Type {
case Auth
case Connect
case Balance
}
public enum Institution {
case amex
case bofa
case capone360
case schwab
case chase
case citi
case fidelity
case pnc
case us
case usaa
case wells
}
public struct Account {
let institutionName: String
let id: String
let user: String
let balance: Double
let productName: String
let lastFourDigits: String
let limit: NSNumber?
public init (account: [String:AnyObject]) {
let meta = account["meta"] as! [String:AnyObject]
let accountBalance = account["balance"] as! [String:AnyObject]
institutionName = account["institution_type"] as! String
id = account["_id"] as! String
user = account["_user"] as! String
balance = accountBalance["current"] as! Double
productName = meta["name"] as! String
lastFourDigits = meta["number"] as! String
limit = meta["limit"] as? NSNumber
}
}
public struct Transaction {
let account: String
let id: String
let amount: Double
let date: String
let name: String
let pending: Bool
let address: String?
let city: String?
let state: String?
let zip: String?
let storeNumber: String?
let latitude: Double?
let longitude: Double?
let trxnType: String?
let locationScoreAddress: Double?
let locationScoreCity: Double?
let locationScoreState: Double?
let locationScoreZip: Double?
let nameScore: Double?
let category:NSArray?
public init(transaction: [String:AnyObject]) {
let meta = transaction["meta"] as! [String:AnyObject]
let location = meta["location"] as? [String:AnyObject]
let coordinates = location?["coordinates"] as? [String:AnyObject]
let score = transaction["score"] as? [String:AnyObject]
let locationScore = score?["location"] as? [String:AnyObject]
let type = transaction["type"] as? [String:AnyObject]
account = transaction["_account"] as! String
id = transaction["_id"] as! String
amount = transaction["amount"] as! Double
date = transaction["date"] as! String
name = transaction["name"] as! String
pending = transaction["pending"] as! Bool
address = location?["address"] as? String
city = location?["city"] as? String
state = location?["state"] as? String
zip = location?["zip"] as? String
storeNumber = location?["store_number"] as? String
latitude = coordinates?["lat"] as? Double
longitude = coordinates?["lon"] as? Double
trxnType = type?["primary"] as? String
locationScoreAddress = locationScore?["address"] as? Double
locationScoreCity = locationScore?["city"] as? Double
locationScoreState = locationScore?["state"] as? Double
locationScoreZip = locationScore?["zip"] as? Double
nameScore = score?["name"] as? Double
category = transaction["category"] as? NSArray
}
}
//MARK: Add Connect or Auth User
func PS_addUser(userType: Type, username: String, password: String, pin: String?, instiution: Institution, completion: (response: NSURLResponse?, accessToken:String, mfaType:String?, mfa:[[String:AnyObject]]?, accounts: [Account]?, transactions: [Transaction]?, error:NSError?) -> ()) {
let baseURL = Plaid.baseURL!
let clientId = Plaid.clientId!
let secret = Plaid.secret!
var institutionStr: String = institutionToString(institution: instiution)
if userType == .Auth {
//Fill in for Auth call
} else if userType == .Connect {
var optionsDict: [String:AnyObject] =
[
"list":true
]
let optionsDictStr = dictToString(optionsDict)
var urlString:String?
if pin != nil {
urlString = "\(baseURL)connect?client_id=\(clientId)&secret=\(secret)&username=\(username)&password=\(password.encodValue)&pin=\(pin!)&type=\(institutionStr)&\(optionsDictStr.encodValue)"
}
else {
urlString = "\(baseURL)connect?client_id=\(clientId)&secret=\(secret)&username=\(username)&password=\(password.encodValue)&type=\(institutionStr)&options=\(optionsDictStr.encodValue)"
}
println("urlString: \(urlString!)")
let url:NSURL! = NSURL(string: urlString!)
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: {
data, response, error in
var error:NSError?
var mfaDict:[[String:AnyObject]]?
var type:String?
let jsonResult:NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
//println("jsonResult: \(jsonResult!)")
if let token:String = jsonResult?.valueForKey("access_token") as? String {
if let mfaResponse = jsonResult!.valueForKey("mfa") as? [[String:AnyObject]] {
let mfaTwo = mfaResponse[0]
mfaDict = mfaResponse
if let typeMfa = jsonResult!.valueForKey("type") as? String {
type = typeMfa
}
completion(response: response, accessToken: token, mfaType: type, mfa: mfaDict, accounts: nil, transactions: nil, error: error)
} else {
let acctsArray:[[String:AnyObject]] = jsonResult?.valueForKey("accounts") as! [[String:AnyObject]]
let accts = acctsArray.map{Account(account: $0)}
let trxnArray:[[String:AnyObject]] = jsonResult?.valueForKey("transactions") as! [[String:AnyObject]]
let trxns = trxnArray.map{Transaction(transaction: $0)}
completion(response: response, accessToken: token, mfaType: nil, mfa: nil, accounts: accts, transactions: trxns, error: error)
}
} else {
//Handle invalid cred login
}
})
task.resume()
}
}
//MARK: MFA funcs
func PS_submitMFAResponse(accessToken: String, response: String, completion: (response: NSURLResponse?, accounts: [Account]?, transactions: [Transaction]?, error: NSError?) -> ()) {
let baseURL = Plaid.baseURL!
let clientId = Plaid.clientId!
let secret = Plaid.secret!
let urlString:String = "\(baseURL)connect/step?client_id=\(clientId)&secret=\(secret)&access_token=\(accessToken)&mfa=\(response.encodValue)"
println("urlString: \(urlString)")
let url:NSURL! = NSURL(string: urlString)
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
println("MFA request: \(request)")
let task = session.dataTaskWithRequest(request, completionHandler: {
data, response, error in
println("mfa response: \(response)")
println("mfa data: \(data)")
println(error)
var error:NSError?
let jsonResult:NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
if jsonResult?.valueForKey("accounts") != nil {
let acctsArray:[[String:AnyObject]] = jsonResult?.valueForKey("accounts") as! [[String:AnyObject]]
let accts = acctsArray.map{Account(account: $0)}
let trxnArray:[[String:AnyObject]] = jsonResult?.valueForKey("transactions") as! [[String:AnyObject]]
let trxns = trxnArray.map{Transaction(transaction: $0)}
completion(response: response, accounts: accts, transactions: trxns, error: error)
}
println("jsonResult: \(jsonResult!)")
})
task.resume()
}
//MARK: Get balance
func PS_getUserBalance(accessToken: String, completion: (response: NSURLResponse?, accounts:[Account], error:NSError?) -> ()) {
let baseURL = Plaid.baseURL!
let clientId = Plaid.clientId!
let secret = Plaid.secret!
let urlString:String = "\(baseURL)balance?client_id=\(clientId)&secret=\(secret)&access_token=\(accessToken)"
let url:NSURL! = NSURL(string: urlString)
let task = session.dataTaskWithURL(url) {
data, response, error in
var error: NSError?
let jsonResult:NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
let dataArray:[[String:AnyObject]] = jsonResult?.valueForKey("accounts") as! [[String : AnyObject]]
let userAccounts = dataArray.map{Account(account: $0)}
completion(response: response, accounts: userAccounts, error: error)
}
task.resume()
}
//MARK: Get transactions (Connect)
func PS_getUserTransactions(accessToken: String, showPending: Bool, beginDate: String?, endDate: String?, completion: (response: NSURLResponse?, transactions:[Transaction], error:NSError?) -> ()) {
let baseURL = Plaid.baseURL!
let clientId = Plaid.clientId!
let secret = Plaid.secret!
var optionsDict: [String:AnyObject] =
[
"pending": true
]
if let beginDate = beginDate {
optionsDict["gte"] = beginDate
}
if let endDate = endDate {
optionsDict["lte"] = endDate
}
let optionsDictStr = dictToString(optionsDict)
let urlString:String = "\(baseURL)connect?client_id=\(clientId)&secret=\(secret)&access_token=\(accessToken)&\(optionsDictStr.encodValue)"
let url:NSURL = NSURL(string: urlString)!
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {
data, response, error in
var error: NSError?
let jsonResult:NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
let dataArray:[[String:AnyObject]] = jsonResult?.valueForKey("transactions") as! [[String:AnyObject]]
let userTransactions = dataArray.map{Transaction(transaction: $0)}
completion(response: response, transactions: userTransactions, error: error)
}
task.resume()
}
//MARK: Helper funcs
func plaidDateFormatter(date: NSDate) -> String {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateStr = dateFormatter.stringFromDate(date)
return dateStr
}
func dictToString(value: AnyObject) -> NSString {
if NSJSONSerialization.isValidJSONObject(value) {
if let data = NSJSONSerialization.dataWithJSONObject(value, options: nil, error: nil) {
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string
}
}
}
return ""
}
func institutionToString(#institution: Institution) -> String {
var institutionStr: String {
switch institution {
case .amex:
return "amex"
case .bofa:
return "bofa"
case .capone360:
return "capone360"
case .chase:
return "chase"
case .citi:
return "citi"
case .fidelity:
return "fidelity"
case .pnc:
return "pnc"
case .schwab:
return "schwab"
case .us:
return "us"
case .usaa:
return "usaa"
case .wells:
return "wells"
}
}
return institutionStr
}
extension String {
var encodValue:String {
return self.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
}
}
extension NSString {
var encodValue:String {
return self.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
}
}
| 669daeaff6bd52efc10a4ccb2aa21bf9 | 33.7 | 286 | 0.622556 | false | false | false | false |
shu223/ARKit-Sampler | refs/heads/master | ARKit-Sampler/Samples/ARDrawing/ARDrawingViewController.swift | mit | 1 | //
// ARDrawingViewController.swift
// ARKit-Sampler
//
// Created by Shuichi Tsutsumi on 2017/09/20.
// Copyright © 2017 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
import ARKit
import ColorSlider
class ARDrawingViewController: UIViewController, ARSCNViewDelegate {
private var drawingNodes = [DynamicGeometryNode]()
private var isTouching = false {
didSet {
pen.isHidden = !isTouching
}
}
@IBOutlet var sceneView: ARSCNView!
@IBOutlet var statusLabel: UILabel!
@IBOutlet var pen: UILabel!
@IBOutlet var resetBtn: UIButton!
@IBOutlet var colorSlider: ColorSlider!
override func viewDidLoad() {
super.viewDidLoad()
// Setup the color picker
colorSlider.orientation = .horizontal
colorSlider.previewEnabled = true
sceneView.delegate = self
sceneView.debugOptions = [SCNDebugOptions.showFeaturePoints]
sceneView.scene = SCNScene()
statusLabel.text = "Wait..."
pen.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
sceneView.session.run()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
sceneView.session.pause()
}
// MARK: - Private
private func reset() {
for node in drawingNodes {
node.removeFromParentNode()
}
drawingNodes.removeAll()
}
private func isReadyForDrawing(trackingState: ARCamera.TrackingState) -> Bool {
switch trackingState {
case .normal:
return true
default:
return false
}
}
private func worldPositionForScreenCenter() -> SCNVector3 {
let screenBounds = UIScreen.main.bounds
let center = CGPoint(x: screenBounds.midX, y: screenBounds.midY)
let centerVec3 = SCNVector3Make(Float(center.x), Float(center.y), 0.99)
return sceneView.unprojectPoint(centerVec3)
}
// MARK: - ARSCNViewDelegate
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
guard isTouching else {return}
guard let currentDrawing = drawingNodes.last else {return}
DispatchQueue.main.async(execute: {
let vertice = self.worldPositionForScreenCenter()
currentDrawing.addVertice(vertice)
})
}
// MARK: - ARSessionObserver
func session(_ session: ARSession, didFailWithError error: Error) {
print("\(self.classForCoder)/\(#function), error: " + error.localizedDescription)
}
func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
print("trackingState: \(camera.trackingState)")
let state = camera.trackingState
let isReady = isReadyForDrawing(trackingState: state)
statusLabel.text = isReady ? "Touch the screen to draw." : "Wait. " + state.description
}
// MARK: - Touch Handlers
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let frame = sceneView.session.currentFrame else {return}
guard isReadyForDrawing(trackingState: frame.camera.trackingState) else {return}
let drawingNode = DynamicGeometryNode(color: colorSlider.color, lineWidth: 0.004)
sceneView.scene.rootNode.addChildNode(drawingNode)
drawingNodes.append(drawingNode)
statusLabel.text = "Move your device!"
isTouching = true
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouching = false
statusLabel.text = "Touch the screen to draw."
}
// MARK: - Actions
@IBAction func resetBtnTapped(_ sender: UIButton) {
reset()
}
}
| 7cfb204e55f71b649e7f008416296188 | 28.507576 | 95 | 0.639795 | false | false | false | false |
gearedupcoding/RadioPal | refs/heads/master | RadioPal/StationsViewController.swift | mit | 1 | //
// StationsViewController.swift
// RadioPal
//
// Created by Jami, Dheeraj on 9/20/17.
// Copyright © 2017 Jami, Dheeraj. All rights reserved.
//
import UIKit
import MediaPlayer
protocol StationsViewControllerDelegate : class {
func clearStations()
}
class StationsViewController: UIViewController {
var stations = [StationModel]()
var pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
var streamsVC = [StreamViewController]()
weak var delegate: StationsViewControllerDelegate?
init(stations: [StationModel]) {
super.init(nibName: nil, bundle: nil)
self.stations = stations
var index = 0
for station in self.stations {
let streamVC = StreamViewController(station: station)
streamVC.delegate = self
streamVC.index = index
print(station.name)
self.streamsVC.append(streamVC)
index += 1
}
print(self.stations.count)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = .white
self.pageViewController.do {
$0.dataSource = self
if let streamVC = self.streamsVC.first {
let arr = [streamVC]
$0.setViewControllers(arr, direction: .forward, animated: true, completion: nil)
}
self.addChildViewController($0)
self.view.addSubview($0.view)
$0.didMove(toParentViewController: self)
$0.view.snp.makeConstraints({ (make) in
make.top.equalTo(topLayoutGuide.snp.bottom)
make.left.right.bottom.equalTo(self.view)
})
}
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.delegate?.clearStations()
self.stations.removeAll()
self.streamsVC.removeAll()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension StationsViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = self.streamsVC.index(of: (viewController as? StreamViewController)!) else {
return nil
}
let nextIndex = index + 1
guard self.streamsVC.count != nextIndex else {
if let firstVC = self.streamsVC.first {
return firstVC
}
return nil
}
guard self.streamsVC.count > nextIndex else {
return nil
}
return self.streamsVC[nextIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = self.streamsVC.index(of: (viewController as? StreamViewController)!) else {
return nil
}
let prevIndex = index - 1
guard prevIndex >= 0 else {
if let lastVC = self.streamsVC.last {
return lastVC
}
return nil
}
guard self.streamsVC.count > prevIndex else {
return nil
}
return self.streamsVC[prevIndex]
}
}
extension StationsViewController: StreamViewControllerDelegate {
func setTitle(str: String) {
self.title = str
}
}
//
//extension StationsViewController: UIPageViewControllerDelegate {
// func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
//
// }
//
// func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
//
// }
//}
| 07e447175f72885c9c104df52996e16a | 30.77305 | 192 | 0.629241 | false | false | false | false |
philphilphil/isaacitems-ios | refs/heads/master | IsaacItems/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// IsaacItems
//
// Created by Philipp Baum on 01/11/15.
// Copyright © 2015 Thinkcoding. All rights reserved.
//
import CoreData
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 throttle down OpenGL ES frame rates. 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 inactive 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) {
self.saveContext()
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("IssacItems.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "thinkcoding", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| eab13842f0f606c74b6a60f4e4ff0391 | 52.636364 | 290 | 0.710678 | false | false | false | false |
cliqz-oss/browser-ios | refs/heads/development | Utils/Extensions/UIViewExtensions.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
extension UIView {
/**
* Takes a screenshot of the view with the given size.
*/
func screenshot(_ size: CGSize, offset: CGPoint? = nil, quality: CGFloat = 1) -> UIImage? {
assert(0...1 ~= quality)
let offset = offset ?? CGPoint(x: 0, y: 0)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale * quality)
drawHierarchy(in: CGRect(origin: offset, size: frame.size), afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/**
* Takes a screenshot of the view with the given aspect ratio.
* An aspect ratio of 0 means capture the entire view.
*/
func screenshot(_ aspectRatio: CGFloat = 0, offset: CGPoint? = nil, quality: CGFloat = 1) -> UIImage? {
assert(aspectRatio >= 0)
var size: CGSize
if aspectRatio > 0 {
size = CGSize()
let viewAspectRatio = frame.width / frame.height
if viewAspectRatio > aspectRatio {
size.height = frame.height
size.width = size.height * aspectRatio
} else {
size.width = frame.width
size.height = size.width / aspectRatio
}
} else {
size = frame.size
}
return screenshot(size, offset: offset, quality: quality)
}
/*
* Performs a deep copy of the view. Does not copy constraints.
*/
func clone() -> UIView {
let data = NSKeyedArchiver.archivedData(withRootObject: self)
return NSKeyedUnarchiver.unarchiveObject(with: data) as! UIView
}
/**
* rounds the requested corners of a view with the provided radius
*/
func addRoundedCorners(_ cornersToRound: UIRectCorner, cornerRadius: CGSize, color: UIColor) {
let rect = bounds
let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: cornersToRound, cornerRadii: cornerRadius)
// Create the shape layer and set its path
let maskLayer = CAShapeLayer()
maskLayer.frame = rect
maskLayer.path = maskPath.cgPath
let roundedLayer = CALayer()
roundedLayer.backgroundColor = color.cgColor
roundedLayer.frame = rect
roundedLayer.mask = maskLayer
layer.insertSublayer(roundedLayer, at: 0)
backgroundColor = UIColor.clear
}
/**
This allows us to find the view in a current view hierarchy that is currently the first responder
*/
static func findSubViewWithFirstResponder(_ view: UIView) -> UIView? {
let subviews = view.subviews
if subviews.count == 0 {
return nil
}
for subview: UIView in subviews {
if subview.isFirstResponder {
return subview
}
return findSubViewWithFirstResponder(subview)
}
return nil
}
// Cliqz: adding drop shadow to UIView
func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
self.layer.masksToBounds = false
self.layer.shadowColor = color.cgColor
self.layer.shadowOpacity = opacity
self.layer.shadowOffset = offSet
self.layer.shadowRadius = radius
self.layer.shouldRasterize = true
self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
| 5a1b7302a2b890ace2573c74ba4ed53a | 33.764151 | 116 | 0.622252 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.