repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
forwk1990/PropertyExchange | PropertyExchange/YPProjectInverstmentCellModel.swift | 1 | 1733 | //
// YPProjectInverstmentCellModel.swift
// PropertyExchange
//
// Created by itachi on 16/9/29.
// Copyright © 2016年 com.itachi. All rights reserved.
//
import Foundation
import SwiftyJSON
public struct YPProjectInverstmentCellModel
{
public var isSuggest:Bool = false
public var title:String?
public var totalMoney:Double = 0
public var rate:Float = 0
public var deadline:String?
public var remainMoney:Double = 0
public var payingWay:String?
public var min:Double = 0
public var max:Double = 0
public var borrower:String? = ""
public var borrowerDate:String? = ""
public init(_ json: JSON){
self.title = json.dictionary?["title"]?.stringValue
if let _isSuggect = json.dictionary?["isSuggest"]?.intValue , _isSuggect == 1{
self.isSuggest = true
}else{
self.isSuggest = false
}
self.totalMoney = (json.dictionary?["totalMoney"]?.doubleValue)!
self.rate = (json.dictionary?["rate"]?.floatValue)!
self.deadline = json.dictionary?["deadline"]?.stringValue
self.remainMoney = (json.dictionary?["remainMoney"]?.doubleValue)!
self.payingWay = json.dictionary?["payingWay"]?.stringValue
self.min = (json.dictionary?["min"]?.doubleValue)!
self.max = (json.dictionary?["max"]?.doubleValue)!
self.borrower = json.dictionary?["borrower"]?.stringValue
self.borrowerDate = json.dictionary?["borrowerDate"]?.stringValue
}
public static func models(json: JSON) -> [YPProjectInverstmentCellModel]{
var models = [YPProjectInverstmentCellModel]()
guard let jsonArray = json.array else {return models}
for i in 0..<jsonArray.count{
models.append(YPProjectInverstmentCellModel(jsonArray[i]))
}
return models
}
}
| mit | 423bf5829e91757a88ea40bbba3a121e | 31.037037 | 82 | 0.698844 | 3.827434 | false | false | false | false |
justindarc/firefox-ios | Extensions/ShareTo/InitialViewController.swift | 1 | 7465 | /* 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 UIKit
import SnapKit
import Shared
import Storage
// Reports portrait screen size regardless of the current orientation.
func screenSizeOrientationIndependent() -> CGSize {
let screenSize = UIScreen.main.bounds.size
return CGSize(width: min(screenSize.width, screenSize.height), height: max(screenSize.width, screenSize.height))
}
// Small iPhone screens in landscape require that the popup have a shorter height.
func isLandscapeSmallScreen(_ traitCollection: UITraitCollection) -> Bool {
if !UX.enableResizeRowsForSmallScreens {
return false
}
let hasSmallScreen = screenSizeOrientationIndependent().width <= CGFloat(UX.topViewWidth)
return hasSmallScreen && traitCollection.verticalSizeClass == .compact
}
/*
The initial view controller is full-screen and is the only one with a valid extension context.
It is just a wrapper with a semi-transparent background to darken the screen
that embeds the share view controller which is designed to look like a popup.
The share view controller is embedded using a navigation controller to get a nav bar
and standard iOS navigation behaviour.
*/
class EmbeddedNavController {
weak var parent: UIViewController?
var controllers = [UIViewController]()
var navigationController: UINavigationController
var heightConstraint: Constraint!
let isSearchMode: Bool
init(isSearchMode: Bool, parent: UIViewController, rootViewController: UIViewController) {
self.parent = parent
self.isSearchMode = isSearchMode
navigationController = UINavigationController(rootViewController: rootViewController)
parent.addChild(navigationController)
parent.view.addSubview(navigationController.view)
let width = min(screenSizeOrientationIndependent().width * 0.90, CGFloat(UX.topViewWidth))
let initialHeight = isSearchMode ? UX.topViewHeightForSearchMode : UX.topViewHeight
navigationController.view.snp.makeConstraints { make in
make.center.equalToSuperview()
make.width.equalTo(width)
heightConstraint = make.height.equalTo(initialHeight).constraint
layout(forTraitCollection: navigationController.traitCollection)
}
navigationController.view.layer.cornerRadius = UX.dialogCornerRadius
navigationController.view.layer.masksToBounds = true
}
func layout(forTraitCollection: UITraitCollection) {
if isSearchMode {
// Dialog size doesn't change
return
}
let updatedHeight: Int
if UX.enableResizeRowsForSmallScreens {
let shrinkage = UX.navBarLandscapeShrinkage + (UX.numberOfActionRows + 1 /*one info row*/) * UX.perRowShrinkageForLandscape
updatedHeight = isLandscapeSmallScreen(forTraitCollection) ? UX.topViewHeight - shrinkage : UX.topViewHeight
} else {
updatedHeight = forTraitCollection.verticalSizeClass == .compact ? UX.topViewHeight - UX.navBarLandscapeShrinkage : UX.topViewHeight
}
heightConstraint.update(offset: updatedHeight)
}
deinit {
navigationController.view.removeFromSuperview()
navigationController.removeFromParent()
}
}
@objc(InitialViewController)
class InitialViewController: UIViewController {
var embedController: EmbeddedNavController?
var shareViewController: ShareViewController?
override func viewDidLoad() {
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.0, alpha: UX.alphaForFullscreenOverlay)
view.alpha = 0
getShareItem().uponQueue(.main) { shareItem in
guard let shareItem = shareItem else {
let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.finish(afterDelay: 0) })
self.present(alert, animated: true, completion: nil)
return
}
// This is the view controller for the popup dialog
let shareController = ShareViewController()
shareController.delegate = self
shareController.shareItem = shareItem
self.shareViewController = shareController
self.embedController = EmbeddedNavController(isSearchMode: !shareItem.isUrlType(), parent: self, rootViewController: shareController)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// The system share dialog dims the screen, then once our share action is selected it closes and the
// screen undims and our view controller is shown which again dims the screen. Without a short fade in
// the effect appears flash-like.
UIView.animate(withDuration: 0.2) {
self.view.alpha = 1
}
}
func getShareItem() -> Deferred<ExtensionUtils.ExtractedShareItem?> {
let deferred = Deferred<ExtensionUtils.ExtractedShareItem?>()
ExtensionUtils.extractSharedItem(fromExtensionContext: extensionContext) { item, error in
if let item = item, error == nil {
deferred.fill(item)
} else {
deferred.fill(nil)
self.extensionContext?.cancelRequest(withError: CocoaError(.keyValueValidation))
}
}
return deferred
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
guard let embedController = embedController, let shareViewController = shareViewController else { return }
coordinator.animate(alongsideTransition: { _ in
embedController.layout(forTraitCollection: newCollection)
shareViewController.layout(forTraitCollection: newCollection)
}) { _ in
// There is a layout change propagation bug for this view setup (i.e. container view controller that is a UINavigationViewController).
// This is the only way to force UINavigationBar to perform a layout. Without this, the layout is for the previous size class.
embedController.navigationController.isNavigationBarHidden = true
embedController.navigationController.isNavigationBarHidden = false
}
}
}
extension InitialViewController: ShareControllerDelegate {
func finish(afterDelay: TimeInterval) {
UIView.animate(withDuration: 0.2, delay: afterDelay, options: [], animations: {
self.view.alpha = 0
}, completion: { _ in
self.extensionContext?.completeRequest(returningItems: [], completionHandler: nil)
})
}
func getValidExtensionContext() -> NSExtensionContext? {
return extensionContext
}
// At startup, the extension may show an alert that it can't share. In this case for a better UI, rather than showing
// 2 popup dialogs (the main one and then the alert), just show the alert.
func hidePopupWhenShowingAlert() {
embedController?.navigationController.view.alpha = 0
}
}
| mpl-2.0 | 08a51a96705509486d3654b73a235167 | 42.401163 | 146 | 0.703684 | 5.324536 | false | false | false | false |
goktugyil/EZLoadingActivity | EZLoadingActivity.swift | 1 | 13124 | //
// EZLoadingActivity.swift
// EZLoadingActivity
//
// Created by Goktug Yilmaz on 02/06/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
public struct EZLoadingActivity {
//==========================================================================================================
// Feel free to edit these variables
//==========================================================================================================
public struct Settings {
public static var BackgroundColor = UIColor(red: 31/255, green: 38/255, blue: 5/255, alpha: 0.5)
public static var ActivityColor = UIColor(red: 141/255, green: 141/255, blue: 6/255, alpha: 1.0)
public static var TextColor = UIColor(red: 250/255, green: 250/255, blue: 17/255, alpha: 1.0)
public static var FontName = "Cochin-BoldItalic"
// Other possible stuff: ✓ ✓ ✔︎ ✕ ✖︎ ✘
public static var SuccessIcon = "✔︎"
public static var FailIcon = "✘"
public static var SuccessText = "Success"
public static var FailText = "Failure"
public static var SuccessColor = UIColor(red: 68/255, green: 118/255, blue: 4/255, alpha: 1.0)
public static var FailColor = UIColor(red: 255/255, green: 75/255, blue: 56/255, alpha: 1.0)
public static var ActivityWidth = UIScreen.ScreenWidth / Settings.WidthDivision
public static var ActivityHeight = ActivityWidth / 3
public static var ShadowEnabled = true
public static var WidthDivision: CGFloat {
get {
if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad {
return 3.5
} else {
return 1.6
}
}
}
public static var LoadOverApplicationWindow = false
public static var DarkensBackground = false
}
fileprivate static var instance: LoadingActivity?
fileprivate static var hidingInProgress = false
fileprivate static var overlay: UIView!
/// Disable UI stops users touch actions until EZLoadingActivity is hidden. Return success status
@discardableResult
public static func show(_ text: String, disableUI: Bool) -> Bool {
guard instance == nil else {
print("EZLoadingActivity: You still have an active activity, please stop that before creating a new one")
return false
}
guard topMostController != nil else {
print("EZLoadingActivity Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
return false
}
// Separate creation from showing
instance = LoadingActivity(text: text, disableUI: disableUI)
DispatchQueue.main.async {
if Settings.DarkensBackground {
if overlay == nil {
overlay = UIView(frame: UIApplication.shared.keyWindow!.frame)
}
overlay.backgroundColor = UIColor.black.withAlphaComponent(0)
topMostController?.view.addSubview(overlay)
UIView.animate(withDuration: 0.2, animations: {overlay.backgroundColor = overlay.backgroundColor?.withAlphaComponent(0.5)})
}
instance?.showLoadingActivity()
}
return true
}
@discardableResult
public static func showWithDelay(_ text: String, disableUI: Bool, seconds: Double) -> Bool {
let showValue = show(text, disableUI: disableUI)
delay(seconds) { () -> () in
_ = hide(true, animated: false)
}
return showValue
}
public static func showOnController(_ text: String, disableUI: Bool, controller:UIViewController) -> Bool{
guard instance == nil else {
print("EZLoadingActivity: You still have an active activity, please stop that before creating a new one")
return false
}
instance = LoadingActivity(text: text, disableUI: disableUI)
DispatchQueue.main.async {
instance?.showLoadingWithController(controller)
}
return true
}
/// Returns success status
@discardableResult
public static func hide(_ success: Bool? = nil, animated: Bool = false) -> Bool {
guard instance != nil else {
print("EZLoadingActivity: You don't have an activity instance")
return false
}
guard hidingInProgress == false else {
print("EZLoadingActivity: Hiding already in progress")
return false
}
if !Thread.current.isMainThread {
DispatchQueue.main.async {
instance?.hideLoadingActivity(success, animated: animated)
}
} else {
instance?.hideLoadingActivity(success, animated: animated)
}
if overlay != nil {
UIView.animate(withDuration: 0.2, animations: {
overlay.backgroundColor = overlay.backgroundColor?.withAlphaComponent(0)
}, completion: { _ in
overlay.removeFromSuperview()
})
}
return true
}
fileprivate static func delay(_ seconds: Double, after: @escaping ()->()) {
let queue = DispatchQueue.main
let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: after)
}
fileprivate class LoadingActivity: UIView {
var textLabel: UILabel!
var activityView: UIActivityIndicatorView!
var icon: UILabel!
var UIDisabled = false
convenience init(text: String, disableUI: Bool) {
self.init(frame: CGRect(x: 0, y: 0, width: Settings.ActivityWidth, height: Settings.ActivityHeight))
center = CGPoint(x: topMostController!.view.bounds.midX, y: topMostController!.view.bounds.midY)
autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]
backgroundColor = Settings.BackgroundColor
alpha = 1
layer.cornerRadius = 8
if Settings.ShadowEnabled {
createShadow()
}
let yPosition = frame.height/2 - 20
activityView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge)
activityView.frame = CGRect(x: 10, y: yPosition, width: 40, height: 40)
activityView.color = Settings.ActivityColor
activityView.startAnimating()
textLabel = UILabel(frame: CGRect(x: 60, y: yPosition, width: Settings.ActivityWidth - 70, height: 40))
textLabel.textColor = Settings.TextColor
textLabel.font = UIFont(name: Settings.FontName, size: 30)
textLabel.adjustsFontSizeToFitWidth = true
textLabel.minimumScaleFactor = 0.25
textLabel.textAlignment = NSTextAlignment.center
textLabel.text = text
if disableUI {
UIApplication.shared.beginIgnoringInteractionEvents()
UIDisabled = true
}
}
func showLoadingActivity() {
addSubview(activityView)
addSubview(textLabel)
//make it smoothly
self.alpha = 0
if Settings.LoadOverApplicationWindow {
UIApplication.shared.windows.first?.addSubview(self)
} else {
topMostController!.view.addSubview(self)
}
//make it smoothly
UIView.animate(withDuration: 0.2, animations: {
self.alpha = 1
})
}
func showLoadingWithController(_ controller:UIViewController){
addSubview(activityView)
addSubview(textLabel)
//make it smoothly
self.alpha = 0
controller.view.addSubview(self)
UIView.animate(withDuration: 0.2, animations: {
self.alpha = 1
})
}
func createShadow() {
layer.shadowPath = createShadowPath().cgPath
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 5
layer.shadowOpacity = 0.5
}
func createShadowPath() -> UIBezierPath {
let myBezier = UIBezierPath()
myBezier.move(to: CGPoint(x: -3, y: -3))
myBezier.addLine(to: CGPoint(x: frame.width + 3, y: -3))
myBezier.addLine(to: CGPoint(x: frame.width + 3, y: frame.height + 3))
myBezier.addLine(to: CGPoint(x: -3, y: frame.height + 3))
myBezier.close()
return myBezier
}
func hideLoadingActivity(_ success: Bool?, animated: Bool) {
hidingInProgress = true
if UIDisabled {
UIApplication.shared.endIgnoringInteractionEvents()
}
var animationDuration: Double = 0
if success != nil {
if success! {
animationDuration = 0.5
} else {
animationDuration = 1
}
}
icon = UILabel(frame: CGRect(x: 10, y: frame.height/2 - 20, width: 40, height: 40))
icon.font = UIFont(name: Settings.FontName, size: 60)
icon.textAlignment = NSTextAlignment.center
if animated {
textLabel.fadeTransition(animationDuration)
}
if success != nil {
if success! {
icon.textColor = Settings.SuccessColor
icon.text = Settings.SuccessIcon
textLabel.text = Settings.SuccessText
} else {
icon.textColor = Settings.FailColor
icon.text = Settings.FailIcon
textLabel.text = Settings.FailText
}
}
addSubview(icon)
if animated {
icon.alpha = 0
activityView.stopAnimating()
UIView.animate(withDuration: animationDuration, animations: {
self.icon.alpha = 1
}, completion: { (value: Bool) in
UIView.animate(withDuration: 0.2, animations: {
self.alpha = 0
}, completion: { (success) in
self.callSelectorAsync(#selector(UIView.removeFromSuperview), delay: animationDuration)
})
instance = nil
hidingInProgress = false
})
} else {
activityView.stopAnimating()
self.callSelectorAsync(#selector(UIView.removeFromSuperview), delay: animationDuration)
instance = nil
hidingInProgress = false
}
}
}
}
private extension UIView {
/// Extension: insert view.fadeTransition right before changing content
func fadeTransition(_ duration: CFTimeInterval) {
let animation: CATransition = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
self.layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
private extension NSObject {
func callSelectorAsync(_ selector: Selector, delay: TimeInterval) {
let timer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: selector, userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: RunLoop.Mode.common)
}
}
private extension UIScreen {
class var Orientation: UIInterfaceOrientation {
get {
return UIApplication.shared.statusBarOrientation
}
}
class var ScreenWidth: CGFloat {
get {
if Orientation.isPortrait {
return UIScreen.main.bounds.size.width
} else {
return UIScreen.main.bounds.size.height
}
}
}
class var ScreenHeight: CGFloat {
get {
if Orientation.isPortrait {
return UIScreen.main.bounds.size.height
} else {
return UIScreen.main.bounds.size.width
}
}
}
}
private var topMostController: UIViewController? {
var presentedVC = UIApplication.shared.keyWindow?.rootViewController
while let pVC = presentedVC?.presentedViewController {
presentedVC = pVC
}
return presentedVC
}
| mit | 457634b2163c31c7ebbe00c8079315ab | 38.110448 | 142 | 0.562815 | 5.459167 | false | false | false | false |
chayelheinsen/GamingStreams-tvOS-App | StreamCenter/UIColor.swift | 3 | 2406 | //
// UIColor.swift
// GamingStreamsTVApp
//
// Created by Brendan Kirchner on 10/12/15.
// Copyright © 2015 Rivus Media Inc. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
convenience init(hexString: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if hexString.characters.count == 7 && hexString.hasPrefix("#") {
let index = hexString.startIndex.advancedBy(1)
let hex = hexString.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
switch (hex.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
Logger.Error("Invalid RGB Hex string, number of characters after '#' should be either 3, 4, 6 or 8")
self.init(red: 1, green: 1, blue: 1, alpha: 1)
return
}
} else {
self.init(red: 1, green: 1, blue: 1, alpha: 1)
return
}
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
} | mit | 2419a6d206cae4c29daef626426a0c09 | 39.779661 | 120 | 0.468607 | 4.090136 | false | false | false | false |
steelwheels/KiwiScript | KiwiLibrary/Test/UnitTest/UTFontManager.swift | 1 | 802 | /*
* @file UTFontManager.swift
* @brief Test KLFontManager class
* @par Copyright
* Copyright (C) 2019 Steel Wheels Project
*/
import KiwiLibrary
import KiwiEngine
import CoconutData
import JavaScriptCore
import Foundation
public func UTFontManager(context ctxt: KEContext, console cons: CNConsole) -> Bool
{
var result: Bool = true
cons.print(string: "[Available fonts]\n")
let manager = KLFontManager(context: ctxt)
let nameval = manager.availableFonts
if let names = nameval.toArray() {
for nameval in names {
if let name = nameval as? String {
cons.print(string: "\(name)\n")
} else {
cons.print(string: "[Error] Invalida data type\n")
result = false
}
}
} else {
cons.print(string: "[Error] Failed to get names\n")
result = false
}
return result
}
| lgpl-2.1 | 89709a24475f7df74adc4f958a3db722 | 20.675676 | 83 | 0.697007 | 3.383966 | false | false | false | false |
hsoi/RxSwift | Tests/RxCocoaTests/Driver+Extensions.swift | 2 | 321 | //
// Driver+Extensions.swift
// Tests
//
// Created by Krunoslav Zaher on 12/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
extension Driver : Equatable {
}
public func == <T>(lhs: Driver<T>, rhs: Driver<T>) -> Bool {
return lhs.asObservable() === rhs.asObservable()
} | mit | 41b126af7cf7c45c737b9e673ddd7530 | 17.882353 | 60 | 0.6625 | 3.404255 | false | true | false | false |
jfkilian/DataBinding | DataBinding/ViewModel.swift | 1 | 1341 | //
// ViewModel.swift
// DataBinding
//
// Created by Jürgen F. Kilian on 06.07.17.
// Copyright © 2017 Kilian IT-Consulting. All rights reserved.
//
import UIKit
class ViewModel: NSObject {
weak var delegate: DataBindingContextOwner?
var dataModel = DataModel()
init(delegate: DataBindingContextOwner) {
self.delegate = delegate
}
var name: String {
get {
return dataModel.name
delegate?.updateTargets()
}
set {
dataModel.name = newValue
}
}
var value: Float {
get {
return dataModel.value
}
set {
dataModel.value = newValue
delegate?.updateTargets()
}
}
var state: Bool {
get {
return dataModel.state
}
set {
dataModel.state = newValue
delegate?.updateTargets()
}
}
var backGroundColor: UIColor {
return dataModel.state ? UIColor.green : UIColor.yellow
}
var valueAsString : String {
get {
return "\(Int(value * 100))"
}
set {
if let n = NumberFormatter().number(from: newValue) {
value = n.floatValue / 100
} else {
value = 0
}
}
}
}
| mit | b5ef30c0f861e8b6cf1e10c16c395be6 | 18.985075 | 65 | 0.504854 | 4.649306 | false | false | false | false |
atrick/swift | test/Sema/typo_correction.swift | 4 | 6858 | // RUN: %target-typecheck-verify-swift -typo-correction-limit 23
// RUN: not %target-swift-frontend -typecheck -disable-typo-correction %s 2>&1 | %FileCheck %s -check-prefix=DISABLED
// RUN: not %target-swift-frontend -typecheck -typo-correction-limit 0 %s 2>&1 | %FileCheck %s -check-prefix=DISABLED
// RUN: not %target-swift-frontend -typecheck -DIMPORT_FAIL %s 2>&1 | %FileCheck %s -check-prefix=DISABLED
// DISABLED-NOT: did you mean
#if IMPORT_FAIL
import NoSuchModule
#endif
// This is close enough to get typo-correction.
func test_short_and_close() {
let foo = 4 // expected-note {{'foo' declared here}}
let bab = fob + 1
// expected-error@-1 {{cannot find 'fob' in scope; did you mean 'foo'?}}
}
// This is not.
func test_too_different() {
let moo = 4
let bbb = mbb + 1 // expected-error {{cannot find 'mbb' in scope}}
}
struct Whatever {}
func *(x: Whatever, y: Whatever) {}
// This works even for single-character identifiers.
func test_very_short() {
// Note that we don't suggest operators.
let x = 0 // expected-note {{did you mean 'x'?}}
let longer = y
// expected-error@-1 {{cannot find 'y' in scope}}
}
// It does not trigger in a variable's own initializer.
func test_own_initializer() {
let x = y // expected-error {{cannot find 'y' in scope}}
}
// Report candidates that are the same distance in different ways.
func test_close_matches() {
let match1 = 0 // expected-note {{did you mean 'match1'?}}
let match22 = 0 // expected-note {{did you mean 'match22'?}}
let x = match2 // expected-error {{cannot find 'match2' in scope}}
}
// Report not-as-good matches if they're still close enough to the best.
func test_keep_if_not_too_much_worse() {
let longmatch1 = 0 // expected-note {{did you mean 'longmatch1'?}}
let longmatch22 = 0 // expected-note {{did you mean 'longmatch22'?}}
let x = longmatch // expected-error {{cannot find 'longmatch' in scope}}
}
// Report not-as-good matches if they're still close enough to the best.
func test_drop_if_too_different() {
let longlongmatch1 = 0 // expected-note {{'longlongmatch1' declared here}}
let longlongmatch2222 = 0
let x = longlongmatch
// expected-error@-1 {{cannot find 'longlongmatch' in scope; did you mean 'longlongmatch1'?}}
}
// Candidates are suppressed if we have too many that are the same distance.
func test_too_many_same() {
let match1 = 0
let match2 = 0
let match3 = 0
let match4 = 0
let match5 = 0
let match6 = 0
let x = match // expected-error {{cannot find 'match' in scope}}
}
// But if some are better than others, just drop the worse tier.
func test_too_many_but_some_better() {
let mtch1 = 0 // expected-note {{did you mean 'mtch1'?}}
let mtch2 = 0 // expected-note {{did you mean 'mtch2'?}}
let match3 = 0
let match4 = 0
let match5 = 0
let match6 = 0
let x = mtch // expected-error {{cannot find 'mtch' in scope}}
}
// rdar://problem/28387684
// Don't crash performing typo correction on bound generic types with
// type variables.
_ = [Any]().withUnsafeBufferPointer { (buf) -> [Any] in
guard let base = buf.baseAddress else { return [] }
return (base ..< base + buf.count).m // expected-error {{value of type 'Range<UnsafePointer<Any>>' has no member 'm'}}
}
// Typo correction with class-bound archetypes.
class SomeClass {
func match1() {} // expected-note {{'match1' declared here}}
}
func takesSomeClassArchetype<T : SomeClass>(_ t: T) {
t.match0()
// expected-error@-1 {{value of type 'T' has no member 'match0'; did you mean 'match1'?}}{{5-11=match1}}
}
// Typo correction of unqualified lookup from generic context.
func match1() {}
// expected-note@-1 {{'match1' declared here}}
struct Generic<T> { // expected-note {{'T' declared as parameter to type 'Generic'}}
class Inner {
func doStuff() {
match0()
// expected-error@-1 {{cannot find 'match0' in scope; did you mean 'match1'?}}
}
}
}
protocol P { // expected-note {{'P' previously declared here}}
// expected-note@-1 2{{did you mean 'P'?}}
// expected-note@-2 {{'P' declared here}}
typealias a = Generic
}
protocol P {} // expected-error {{invalid redeclaration of 'P'}}
func hasTypo() {
_ = P.a.a // expected-error {{type 'Generic<T>' has no member 'a'}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
}
// Typo correction with AnyObject.
func takesAnyObject(_ t: AnyObject) {
_ = t.rawPointer
// expected-error@-1 {{value of type 'AnyObject' has no member 'rawPointer'}}
}
func takesAnyObjectArchetype<T : AnyObject>(_ t: T) {
_ = t.rawPointer
// expected-error@-1 {{value of type 'T' has no member 'rawPointer'}}
}
// Typo correction with an UnresolvedDotExpr.
enum Foo {
case flashing // expected-note {{'flashing' declared here}}
}
func foo(_ a: Foo) {
}
func bar() {
foo(.flashin)
// expected-error@-1 {{type 'Foo' has no member 'flashin'; did you mean 'flashing'?}}{{8-15=flashing}}
}
// Verify that we emit a fixit even if there are multiple
// declarations with the corrected name.
func overloaded(_: Int) {} // expected-note {{'overloaded' declared here}}
func overloaded(_: Float) {} // expected-note {{'overloaded' declared here}}
func test_overloaded() {
overloadd(0)
// expected-error@-1 {{cannot find 'overloadd' in scope; did you mean 'overloaded'?}}{{3-12=overloaded}}
}
// This is one of the backtraces from rdar://36434823 but got fixed along
// the way.
class CircularValidationWithTypo {
var cdcdcdcd = ababab { // expected-error {{cannot find 'ababab' in scope}}
didSet { }
}
var abababab = cdcdcdc { // expected-error {{cannot find 'cdcdcdc' in scope}}
didSet { }
}
}
// Crash with invalid extension that has not been bound -- https://bugs.swift.org/browse/SR-8984
protocol PP {}
func boo() {
extension PP { // expected-error {{declaration is only valid at file scope}}
func g() {
booo() // expected-error {{cannot find 'booo' in scope}}
}
}
}
// Don't show underscored names as typo corrections unless the typed name also
// begins with an underscore.
func test_underscored_no_match() {
let _ham = 0
_ = ham
// expected-error@-1 {{cannot find 'ham' in scope}}
}
func test_underscored_match() {
let _eggs = 4 // expected-note {{'_eggs' declared here}}
_ = _fggs + 1
// expected-error@-1 {{cannot find '_fggs' in scope; did you mean '_eggs'?}}
}
// Don't show values before declaration.
func testFwdRef() {
let _ = forward_refX + 1 // expected-error {{cannot find 'forward_refX' in scope}}
let forward_ref1 = 4
}
// Crash with protocol members.
protocol P1 {
associatedtype A1
associatedtype A2
}
protocol P2 {
associatedtype A1
associatedtype A2
func method<T: P1>(_: T) where T.A1 == A1, T.A2 == A2
}
extension P2 {
func f() { // expected-note {{did you mean 'f'?}}
_ = a // expected-error {{cannot find 'a' in scope}}
}
}
| apache-2.0 | acfe7eb7def12989f713a1dfe74a4900 | 30.172727 | 120 | 0.666667 | 3.358472 | false | true | false | false |
silence0201/Swift-Study | AdvancedSwift/错误处理/Cleaning Up Using defer.playgroundpage/Contents.swift | 1 | 3346 | /*:
## Cleaning Up Using `defer`
Let's go back to the `contents(ofFile:)` function from the beginning of this
chapter for a minute and have a look at the implementation. In many languages,
it's common to have a `try`/`finally` construct, where the block marked with
`finally` is always executed when the function returns, regardless of whether or
not an error was thrown. The `defer` keyword in Swift has a similar purpose but
works a bit differently. Like `finally`, a `defer` block is always executed when
a scope is exited, regardless of the reason of exiting — whether it's because a
value is successfully returned, because an error happened, or any other reason.
Unlike `finally`, a `defer` block doesn't require a leading `try` or `do` block,
and it's more flexible in terms of where you place it in your code:
*/
//#-hidden-code
import Foundation
func process(file: Int32) throws -> String { return "" }
//#-end-hidden-code
//#-editable-code
func contents(ofFile filename: String) throws -> String
{
let file = open("test.txt", O_RDONLY)
defer { close(file) }
let contents = try process(file: file)
return contents
}
//#-end-editable-code
/*:
While `defer` is often used together with error handling, it can be useful in
other contexts too — for example, when you want to keep the code for
initialization and cleanup of a resource close together. Putting related parts
of the code close to each other can make your code significantly more readable,
especially in longer functions.
The standard library uses `defer` in multiple places where a function needs to
increment a counter *and* return the counter's previous value. This saves
creating a local variable for the return value; `defer` essentially serves as a
replacement for the removed postfix increment operator. Here's a typical example
from the implementation of `EnumeratedIterator`:
``` swift-example
struct EnumeratedIterator<Base: IteratorProtocol>: IteratorProtocol, Sequence {
internal var _base: Base
internal var _count: Int
...
func next() -> Element? {
guard let b = _base.next() else { return nil }
defer { _count += 1 }
return (offset: _count, element: b)
}
}
```
If there are multiple `defer` blocks in the same scope, they're executed in
reverse order; you can think of them as a stack. At first, it might feel strange
that the `defer` blocks run in reverse order. However, if we look at an example,
it should quickly make sense:
``` swift-example
guard let database = openDatabase(...) else { return }
defer { closeDatabase(database) }
guard let connection = openConnection(database) else { return }
defer { closeConnection(connection) }
guard let result = runQuery(connection, ...) else { return }
```
If an error occurs — for example, during the `runQuery` call — we want to close
the connection first and the database second. Because the `defer` is executed in
reverse order, this happens automatically. The `runQuery` depends on
`openConnection`, which in turn depends on `openDatabase`. Therefore, cleaning
these resources up needs to happen in reverse order.
There are some cases in which `defer` blocks don't get executed: when your
program segfaults, or when it raises a fatal error (e.g. using `fatalError` or
by force-unwrapping a `nil`), all execution halts immediately.
*/
| mit | fbed12bd5e339c653c459273195665cc | 40.209877 | 80 | 0.743259 | 4.182957 | false | false | false | false |
zomeelee/actor-platform | actor-apps/app-ios/Actor/Controllers Support/AANavigationController.swift | 13 | 1684 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import UIKit
class AANavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.translucent = true
navigationBar.hideBottomHairline()
view.backgroundColor = MainAppTheme.list.backyardColor
}
// MARK: -
// MARK: Methods
// override func viewWillAppear(animated: Bool) {
// super.viewWillAppear(animated)
// navigationBar.hideBottomHairline()
// view.backgroundColor = MainAppTheme.list.backyardColor
// }
func makeBarTransparent() {
navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationBar.shadowImage = UIImage()
navigationBar.translucent = true
}
}
extension UINavigationBar {
func hideBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(self)
navigationBarImageView!.hidden = true
}
func showBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(self)
navigationBarImageView!.hidden = false
}
private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
if view.isKindOfClass(UIImageView) && view.bounds.height <= 1.0 {
return (view as! UIImageView)
}
let subviews = (view.subviews as! [UIView])
for subview: UIView in subviews {
if let imageView: UIImageView = hairlineImageViewInNavigationBar(subview) {
return imageView
}
}
return nil
}
} | mit | f39046bf780fd03a41b96aa55f8a81f2 | 28.051724 | 88 | 0.644299 | 5.295597 | false | false | false | false |
milseman/swift | test/IRGen/partial_apply_generic.swift | 18 | 2332 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
//
// Type parameters
//
infix operator ~> { precedence 255 }
func ~> <Target, Args, Result> (
target: Target,
method: (Target) -> (Args) -> Result)
-> (Args) -> Result
{
return method(target)
}
protocol Runcible {
associatedtype Element
}
struct Mince {}
struct Spoon: Runcible {
typealias Element = Mince
}
func split<Seq: Runcible>(_ seq: Seq) -> ((Seq.Element) -> Bool) -> () {
return {(isSeparator: (Seq.Element) -> Bool) in
return ()
}
}
var seq = Spoon()
var x = seq ~> split
//
// Indirect return
//
// CHECK-LABEL: define internal swiftcc { i8*, %swift.refcounted* } @_T021partial_apply_generic5split{{[_0-9a-zA-Z]*}}FTA(%T21partial_apply_generic5SpoonV* noalias nocapture, %swift.refcounted* swiftself)
// CHECK: [[REABSTRACT:%.*]] = bitcast %T21partial_apply_generic5SpoonV* %0 to %swift.opaque*
// CHECK: tail call swiftcc { i8*, %swift.refcounted* } @_T021partial_apply_generic5split{{[_0-9a-zA-Z]*}}F(%swift.opaque* noalias nocapture [[REABSTRACT]],
struct HugeStruct { var a, b, c, d: Int }
struct S {
func hugeStructReturn(_ h: HugeStruct) -> HugeStruct { return h }
}
let s = S()
var y = s.hugeStructReturn
// CHECK-LABEL: define internal swiftcc { i64, i64, i64, i64 } @_T021partial_apply_generic1SV16hugeStructReturnAA04HugeE0VAFFTA(i64, i64, i64, i64, %swift.refcounted* swiftself) #0 {
// CHECK: entry:
// CHECK: %5 = tail call swiftcc { i64, i64, i64, i64 } @_T021partial_apply_generic1SV16hugeStructReturnAA04HugeE0VAFF(i64 %0, i64 %1, i64 %2, i64 %3)
// CHECK: ret { i64, i64, i64, i64 } %5
// CHECK: }
//
// Witness method
//
protocol Protein {
static func veganOrNothing() -> Protein?
static func paleoDiet() throws -> Protein
}
enum CarbOverdose : Error {
case Mild
case Severe
}
class Chicken : Protein {
static func veganOrNothing() -> Protein? {
return nil
}
static func paleoDiet() throws -> Protein {
throw CarbOverdose.Severe
}
}
func healthyLunch<T: Protein>(_ t: T) -> () -> Protein? {
return T.veganOrNothing
}
let f = healthyLunch(Chicken())
func dietaryFad<T: Protein>(_ t: T) -> () throws -> Protein {
return T.paleoDiet
}
let g = dietaryFad(Chicken())
do {
try g()
} catch {}
| apache-2.0 | 39c4c2eaacd35c4ab1735af4c4dc7f22 | 24.075269 | 204 | 0.661664 | 3.060367 | false | false | false | false |
LeonardoCardoso/Clipboarded | Clipboarded/View Controllers/PasteViewController.swift | 1 | 3509 | //
// PasteViewController.swift
// Clipboarded
//
// Created by Leonardo Cardoso on 24/12/2016.
// Copyright © 2016 leocardz.com. All rights reserved.
//
import UIKit
import Photos
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class PasteViewController: BaseViewController {
// MARK: - Properties
private var pasteView: PasteView?
// MARK: - Initializers
convenience init(viewModel: PasteViewModelType) {
self.init()
self.edgesForExtendedLayout = []
// Attach the custom view to UIViewController's view
self.pasteView = PasteView(superview: self.view)
self.pasteView?.layout()
self.configureBindings(viewModel: viewModel)
PHPhotoLibrary
.requestAuthorization { status in
switch status {
case .authorized:
break
case .restricted:
self.askForPermission()
break
case .denied:
self.askForPermission()
break
default:
self.askForPermission()
break
}
}
}
// MARK: - ViewModel Configuration
private func configureBindings(viewModel: PasteViewModelType) {
guard
let pasteView: PasteView = self.pasteView,
let dataLabel: UILabel = pasteView.dataLabel,
let initialLabel: UILabel = pasteView.initialLabel,
let readingLabel: UILabel = pasteView.readingLabel,
let savedLabel: UILabel = pasteView.savedLabel,
let errorLabel: UILabel = pasteView.errorLabel
else { return }
// Input
pasteView.rx.controlEvent(.touchUpInside).bindNext({ viewModel.tapAction.onNext() }).addDisposableTo(self.disposeBag)
// Output
viewModel.pasteboardString.asObservable().map({ $0 }).bindTo(dataLabel.rx.text).addDisposableTo(self.disposeBag)
viewModel.tapTextHidden.asObservable().map({ $0 }).bindTo(initialLabel.rx.isHidden).addDisposableTo(self.disposeBag)
viewModel.readTextHidden.asObservable().map({ $0 }).bindTo(readingLabel.rx.isHidden).addDisposableTo(self.disposeBag)
viewModel.saveTextHidden.asObservable().map({ $0 }).bindTo(savedLabel.rx.isHidden).addDisposableTo(self.disposeBag)
viewModel.errorTextHidden.asObservable().map({ $0 }).bindTo(errorLabel.rx.isHidden).addDisposableTo(self.disposeBag)
viewModel.deliverPicture
.subscribe(
onNext: { [] image in
pasteView.imageView?.image = image
}
).addDisposableTo(self.disposeBag)
}
// MARK: - Functions
// Ask for permission
func askForPermission() {
let alert = UIAlertController(title: R.string.localizable.alert(), message: R.string.localizable.permissionMessage(), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: R.string.localizable.takeMeToSettings(), style: .default, handler: { action in self.openSettings() }))
Flow.async { self.present(alert, animated: true, completion: nil) }
}
// Open settings
func openSettings() { UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)! as URL) }
}
| mit | 9f750bfd6ed4f26840d83a5c4418c2f3 | 33.732673 | 149 | 0.600342 | 5.25937 | false | false | false | false |
slavapestov/swift | test/attr/attr_autoclosure.swift | 1 | 3985 | // RUN: %target-parse-verify-swift
// Simple case.
@autoclosure var fn : () -> Int = 4 // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{1-14=}} expected-error {{cannot convert value of type 'Int' to specified type '() -> Int'}}
@autoclosure func func1() {} // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{1-14=}}
func func1a(@autoclosure v1 : Int) {} // expected-error {{@autoclosure may only be applied to values of function type}}
func func2(@autoclosure fp : () -> Int) { func2(4)}
func func3(@autoclosure fp fpx : () -> Int) {func3(fp: 0)}
func func4(@autoclosure fp fp : () -> Int) {func4(fp: 0)}
func func6(@autoclosure _: () -> Int) {func6(0)}
// declattr and typeattr on the argument.
func func7(@autoclosure _: @noreturn () -> Int) {func7(0)}
// autoclosure + inout don't make sense.
func func8(@autoclosure inout x: () -> Bool) -> Bool { // expected-error {{@autoclosure may only be applied to values of function type}}
}
// <rdar://problem/19707366> QoI: @autoclosure declaration change fixit
let migrate4 : @autoclosure() -> () // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@autoclosure }} {{16-28=}}
struct SomeStruct {
@autoclosure let property : () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
init() {
}
}
class BaseClass {
@autoclosure var property : () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
init() {}
}
class DerivedClass {
var property : () -> Int { get {} set {} }
}
protocol P1 {
associatedtype Element
}
protocol P2 : P1 {
associatedtype Element
}
func overloadedEach<O: P1>(source: O, _ closure: () -> ()) {
}
func overloadedEach<P: P2>(source: P, _ closure: () -> ()) {
}
struct S : P2 {
typealias Element = Int
func each(@autoclosure closure: () -> ()) {
overloadedEach(self, closure) // expected-error {{invalid conversion from non-escaping function of type '@autoclosure () -> ()' to potentially escaping function type '() -> ()'}}
}
}
struct AutoclosureEscapeTest {
@autoclosure let delayed: () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
}
// @autoclosure(escaping)
func func10(@autoclosure(escaping _: () -> ()) { } // expected-error{{expected ')' in @autoclosure}}
// expected-note@-1{{to match this opening '('}}
func func11(@autoclosure(escaping) @noescape _: () -> ()) { } // expected-error{{@noescape conflicts with @autoclosure(escaping)}} {{36-46=}}
class Super {
func f1(@autoclosure(escaping) x: () -> ()) { }
func f2(@autoclosure(escaping) x: () -> ()) { }
func f3(@autoclosure x: () -> ()) { }
}
class Sub : Super {
override func f1(@autoclosure(escaping) x: () -> ()) { }
override func f2(@autoclosure x: () -> ()) { } // expected-error{{does not override any method}}
override func f3(@autoclosure(escaping) x: () -> ()) { } // expected-error{{does not override any method}}
}
func func12_sink(x: () -> Int) { }
func func12a(@autoclosure x: () -> Int) {
func12_sink(x) // expected-error{{invalid conversion from non-escaping function of type '@autoclosure () -> Int' to potentially escaping function type '() -> Int'}}
}
func func12b(@autoclosure(escaping) x: () -> Int) {
func12_sink(x)
}
class TestFunc12 {
var x: Int = 5
func foo() -> Int { return 0 }
func test() {
func12a(x + foo()) // okay
func12b(x + foo())
// expected-error@-1{{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{13-13=self.}}
// expected-error@-2{{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{17-17=self.}}
}
}
enum AutoclosureFailableOf<T> {
case Success(@autoclosure () -> T) // expected-error {{attribute can only be applied to declarations, not types}}
case Failure()
}
| apache-2.0 | cdbc2aaa17fdf09a9748270d94ad40d8 | 33.059829 | 210 | 0.646173 | 3.635949 | false | false | false | false |
AlexBianzd/NiceApp | NiceApp/Classes/Controller/ZDNiceForumDetailViewController.swift | 1 | 16076 | //
// ZDNiceForumDetailViewController.swift
// NiceApp
//
// Created by 边振东 on 8/14/16.
// Copyright © 2016 边振东. All rights reserved.
//
import UIKit
import SwiftyJSON
class ZDNiceForumDetailViewController: UIViewController {
fileprivate var datasource = [String:JSON]()
fileprivate var comments = [JSON]()
fileprivate var container = UIView()
init(datasource : Dictionary<String,JSON>) {
super.init(nibName: nil, bundle: nil)
self.datasource = datasource
self.comments = datasource["comments"]!.arrayValue
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.navigationController?.navigationBar.isHidden = true
self.setupUI()
let backBtn = UIButton.init(type: .custom)
backBtn.setImage(UIImage.init(named: "cnb_back"), for: .normal)
backBtn.setImage(UIImage.init(named: "cnb_back_highlight"), for: .highlighted)
backBtn.layer.cornerRadius = 35 / 2;
backBtn.addTarget(self, action: #selector(back), for: .touchUpInside)
self.view.addSubview(backBtn)
backBtn.snp.makeConstraints { (make) in
make.width.height.equalTo(35)
make.centerX.equalTo(self.view.snp.left).offset(44 / 2)
make.centerY.equalTo(self.view.snp.top).offset(44 / 2 + 20)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
func back() {
let navCon = self.navigationController as! ZDBaseNavigationController
navCon.touchBack()
}
//MARK: UI
private func setupUI() {
self.view.backgroundColor = .white
let tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: kSCREEN_WIDTH, height: kSCREEN_HEIGHT - 44), style: .grouped)
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = .white
tableView.separatorStyle = .none
tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 10, right: 0)
tableView.register(UINib(nibName: "ZDCommentTableViewCell", bundle: nil), forCellReuseIdentifier: "ZDCommentTableViewCell")
self.view.addSubview(tableView)
container.frame = self.view.bounds
self.view.addSubview(container)
var contentY : CGFloat = 0
container.addSubview(authorAvatar)
authorAvatar.snp.makeConstraints { (make) in
make.width.height.equalTo(35)
make.centerX.equalTo(container.snp.right).offset(-44 / 2)
make.centerY.equalTo(container.snp.top).offset(44 / 2)
}
container.addSubview(authorName)
authorName.snp.makeConstraints { (make) in
make.width.equalTo(150)
make.height.equalTo(35 / 2)
make.right.equalTo(authorAvatar.snp.left).offset(-10)
make.bottom.equalTo(authorAvatar.snp.centerY)
}
container.addSubview(authorCareer)
authorCareer.snp.makeConstraints { (make) in
make.width.equalTo(150)
make.height.equalTo(35 / 2)
make.right.equalTo(authorAvatar.snp.left).offset(-10)
make.top.equalTo(authorAvatar.snp.centerY)
}
let separatorLine = UIView.init(frame: CGRect.init(x: 0, y: 44, width: container.bounds.width, height: 1))
separatorLine.backgroundColor = UIColor.lightGray
container.addSubview(separatorLine)
contentY += 44
container.addSubview(iconImage)
iconImage.snp.makeConstraints { (make) in
make.width.height.equalTo(50)
make.left.equalTo(container).offset(15)
make.top.equalTo(separatorLine.snp.bottom).offset(15)
}
container.addSubview(appName)
appName.snp.makeConstraints { (make) in
make.height.equalTo(50)
make.centerY.equalTo(iconImage)
make.left.equalTo(iconImage.snp.right).offset(10)
make.right.equalTo(self.view).offset(-10)
}
contentY += 15 + 50
let rect = self.setupDescriptionUI()
contentY += 60 + rect.size.height
contentY += 10
contentY = self.setupImagesUI(contentY: &contentY)
contentY = self.setupUpUsersUI(contentY: &contentY)
contentY += 10
if self.comments.count > 0 {
let commentLabel = UILabel()
commentLabel.frame = CGRect.init(x: 10, y: contentY, width: 35, height: 20)
commentLabel.font = UIFont.systemFont(ofSize: 16)
commentLabel.text = "评论"
commentLabel.textColor = UIColor.black
container.addSubview(commentLabel)
let line = UIView()
line.frame = CGRect.init(x: commentLabel.frame.maxX + 10, y: commentLabel.center.y, width: kSCREEN_WIDTH - commentLabel.frame.maxX - 20, height: 1)
line.backgroundColor = UIColor.lightGray
container.addSubview(line)
contentY = commentLabel.frame.maxY+10;
}
container.frame = CGRect.init(x: 0, y: 0, width: kSCREEN_WIDTH, height: contentY)
tableView.tableHeaderView = container
let footer = ZDTableViewFooterView.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 40))
tableView.tableFooterView = footer
self.view.addSubview(bottomToolView)
}
private func setupDescriptionUI() -> CGRect {
let descriptionText = datasource["description"]?.stringValue.replacingOccurrences(of: "<br/>", with: "\n")
let descriptionAttText = NSMutableAttributedString.init(string: descriptionText!)
let range = NSMakeRange(0, descriptionAttText.length)
descriptionAttText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16), range: range)
descriptionAttText.addAttribute(NSForegroundColorAttributeName, value: UIColor.gray, range: range)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5.0
descriptionAttText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: range)
let description = UILabel()
description.attributedText = descriptionAttText
description.numberOfLines = 0
container.addSubview(description)
let rect = descriptionAttText.boundingRect(with: CGSize.init(width: kSCREEN_WIDTH - 20, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, context: nil)
description.snp.makeConstraints { (make) in
make.top.equalTo(appName.snp.bottom).offset(60)
make.height.equalTo(rect.size.height)
make.left.equalTo(container).offset(10)
make.right.equalTo(container).offset(-10)
}
return rect
}
private func setupImagesUI(contentY: inout CGFloat) -> CGFloat {
let all_images = datasource["all_images"]?.arrayValue
for i in 0..<all_images!.count {
let url : String = all_images![i].stringValue
let size : CGSize = self.sizeWithUrl(url)
let imgView = UIImageView.init()
imgView.frame = CGRect.init(origin: CGPoint.init(x: 10, y: contentY), size: size)
imgView.layer.borderColor = UIColor.lightGray.cgColor
imgView.layer.borderWidth = 0.5
container.addSubview(imgView)
imgView.kf.setImage(with: URL(string:url),
placeholder: nil,
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
contentY += size.height + 10
}
return contentY
}
private func setupUpUsersUI(contentY: inout CGFloat) -> CGFloat {
let up_users = datasource["up_users"]?.arrayValue
if up_users?.count != 0 {
let up_user = UILabel()
up_user.font = UIFont.systemFont(ofSize: 16)
up_user.text = "美过的美友"
up_user.textColor = UIColor.black
container.addSubview(up_user)
up_user.frame = CGRect.init(x: 10, y: contentY + 5, width: 80, height: 20)
let line = UIView()
line.backgroundColor = UIColor.lightGray
container.addSubview(line)
line.frame = CGRect.init(x: up_user.frame.maxX + 10, y: up_user.center.y, width: kSCREEN_WIDTH - up_user.frame.maxX - 20, height: 1)
contentY = up_user.frame.maxY+10;
let imgMargin : CGFloat = (kSCREEN_WIDTH-2*10-8*36)/7
if up_users!.count <= 18 {
for i in 0..<up_users!.count {
let userImg = UIImageView.init()
userImg.layer.cornerRadius = 18
userImg.clipsToBounds = true
userImg.frame = CGRect.init(x: 10+CGFloat(i%8)*(36+imgMargin),
y: contentY + (36+imgMargin) * CGFloat(i/8),
width: 36,
height: 36)
container.addSubview(userImg)
userImg.kf.setImage(with: URL(string:up_users![i]["avatar_url"].stringValue),
placeholder: nil,
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
if i == (up_users?.count)! - 1 {
contentY = userImg.frame.maxY;
}
}
} else {
let upusersContainer = UIScrollView()
upusersContainer.showsHorizontalScrollIndicator = false
upusersContainer.frame = CGRect.init(x: 0, y: contentY, width: kSCREEN_WIDTH, height: 36 * 2 + imgMargin)
upusersContainer.contentSize = CGSize.init(width: 10+NSInteger(up_users!.count/2)*NSInteger(36+imgMargin), height: 0)
container.addSubview(upusersContainer)
for i in 0..<up_users!.count {
let userImg = UIImageView.init()
userImg.layer.cornerRadius = 18
userImg.clipsToBounds = true
userImg.frame = CGRect.init(x: 10+CGFloat(NSInteger(i/2)%NSInteger(up_users!.count/2))*(36+imgMargin),
y: CGFloat(i%2)*(36+imgMargin),
width: 36,
height: 36)
upusersContainer.addSubview(userImg)
userImg.kf.setImage(with: URL(string:up_users![i]["avatar_url"].stringValue),
placeholder: nil,
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
}
contentY += upusersContainer.bounds.size.height
}
}
return contentY
}
//MARK: private method
private func sizeWithUrl(_ url : String) -> CGSize {
let start = url.characters.index(after: url.characters.index(of: "_")!)
let end = url.characters.index(of: "?")
var c = url.substring(to: end!).substring(from: start)
let dot = c.characters.index(of: ".")
c = c.substring(to: dot!)
let x = c.characters.index(of: "x")
let imgWidth = Float(c.substring(to: x!))
let imgHeight = Float(c.substring(from: c.characters.index(after: x!)))
let width = kSCREEN_WIDTH - 20
let height = width * CGFloat(imgHeight! / imgWidth!)
return CGSize.init(width: width, height: height)
}
//MARK: Lazy
lazy var authorAvatar: UIImageView = {
let authorAvatar = UIImageView()
authorAvatar.clipsToBounds = true
authorAvatar.layer.cornerRadius = 35 / 2
authorAvatar.kf.setImage(with: URL(string: (self.datasource["author_avatar_url"]?.stringValue)!),
placeholder: nil,
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
return authorAvatar
}()
lazy var authorName: UILabel = {
let authorName = UILabel()
authorName.font = UIFont.systemFont(ofSize: 13)
authorName.textColor = UIColor.black
authorName.textAlignment = .right
authorName.text = self.datasource["author_name"]?.stringValue
return authorName
}()
lazy var authorCareer: UILabel = {
let authorCareer = UILabel()
authorCareer.font = UIFont.systemFont(ofSize: 12)
authorCareer.textColor = UIColor.gray
authorCareer.textAlignment = .right
authorCareer.text = self.datasource["author_career"]?.stringValue
return authorCareer
}()
lazy var iconImage: UIImageView = {
let iconImage = UIImageView()
iconImage.clipsToBounds = true
iconImage.layer.cornerRadius = 10
iconImage.kf.setImage(with: URL(string: (self.datasource["icon_image"]?.stringValue)!),
placeholder: nil,
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
return iconImage
}()
lazy var appName: UILabel = {
let appName = UILabel()
appName.font = UIFont.systemFont(ofSize: 18)
appName.textColor = UIColor.black
appName.textAlignment = .left
appName.text = self.datasource["app_name"]?.stringValue
appName.numberOfLines = 0
return appName
}()
lazy var bottomToolView: ZDBottomToolView = {
let bottomToolView = ZDBottomToolView.init(frame: CGRect.init(x: 0, y: kSCREEN_HEIGHT - 44, width: kSCREEN_WIDTH, height: 44))
return bottomToolView
}()
}
// MARK: - UITableViewDelegate
extension ZDNiceForumDetailViewController: UITableViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y > scrollView.contentSize.height / 2 {
bottomToolView.setContentOffset(CGPoint.init(x: self.view.bounds.width, y: 0), animated: true)
} else {
bottomToolView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: true)
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let content = self.comments[indexPath.section]["content"].stringValue.replacingOccurrences(of: "<br/>", with: "\n").replacingOccurrences(of: "<br />", with: "\n")
let contentAttText = NSMutableAttributedString.init(string: content)
let range = NSMakeRange(0, contentAttText.length)
contentAttText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 12), range: range)
let rect = contentAttText.boundingRect(with: CGSize.init(width: kSCREEN_WIDTH - 20, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, context: nil)
return rect.size.height + 15 + 23 + 30
}
}
// MARK: - UITableViewDataSource
extension ZDNiceForumDetailViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
let count = self.comments.last?["count"].intValue
if self.comments.count == count || self.comments.count == 0 {
tableView.tableFooterView = nil
}
return self.comments.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ZDCommentTableViewCell", for: indexPath) as! ZDCommentTableViewCell
var model = self.comments[indexPath.section]
cell.author_avatar.kf.setImage(with: URL(string: (model["author_avatar_url"].stringValue)),
placeholder: nil,
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
cell.author_name.text = model["author_name"].stringValue
cell.author_career.text = model["author_career"].stringValue
cell.updated_at.text = model["updated_at"].stringValue
let content = model["content"].stringValue.replacingOccurrences(of: "<br/>", with: "\n").replacingOccurrences(of: "<br />", with: "\n")
cell.content.text = content
return cell
}
}
| mit | 70200425d261a25cbd7e439e99e61498 | 40.685714 | 167 | 0.654309 | 4.28316 | false | false | false | false |
lorentey/GlueKit | Tests/GlueKitTests/SimpleSourcesTests.swift | 1 | 986 | //
// SimpleSourcesTests.swift
// GlueKit
//
// Created by Károly Lőrentey on 2015-12-03.
// Copyright © 2015–2017 Károly Lőrentey.
//
import XCTest
import GlueKit
class SimpleSourcesTests: XCTestCase {
func testEmptySource() {
let source = AnySource<Int>.empty()
let sink = MockSink<Int>()
source.add(sink)
sink.expectingNothing {
// Ah, uhm, not sure what to test here, really
}
source.remove(sink)
}
func testNeverSource() {
let source = AnySource<Int>.never()
let sink = MockSink<Int>()
source.add(sink)
sink.expectingNothing {
// Ah, uhm, not sure what to test here, really
}
source.remove(sink)
}
func testJustSource() {
let source = AnySource<Int>.just(42)
let sink = MockSink<Int>()
_ = sink.expecting(42) {
source.add(sink)
}
source.remove(sink)
}
}
| mit | 1a832a7af5b654fdc57337b9b9899340 | 17.471698 | 58 | 0.558733 | 3.963563 | false | true | false | false |
roosmaa/Octowire-iOS | Octowire/UserProfileViewController.swift | 1 | 5916 | //
// UserProfileViewController.swift
// Octowire
//
// Created by Mart Roosmaa on 25/02/2017.
// Copyright © 2017 Mart Roosmaa. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import ReSwift
class UserProfileViewController: UIViewController {
@IBOutlet weak var avatarImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var bioLabel: UILabel!
@IBOutlet weak var locationRow: UIStackView!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var emailRow: UIStackView!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var websiteRow: UIStackView!
@IBOutlet weak var websiteLabel: UILabel!
public var username = ""
fileprivate var user: UserModel?
override func viewDidLoad() {
super.viewDidLoad()
self.avatarImage.layer.cornerRadius = 10.0
self.avatarImage.image = nil
self.nameLabel.isHidden = true
self.usernameLabel.isHidden = true
self.bioLabel.isHidden = true
setRowIsHidden(self.locationRow, to: true)
setRowIsHidden(self.emailRow, to: true)
setRowIsHidden(self.websiteRow, to: true)
self.title = self.username
self.emailRow.isUserInteractionEnabled = true
var tapGesture = UITapGestureRecognizer(target: self, action: #selector(rowTapped))
tapGesture.numberOfTapsRequired = 1
self.emailRow.addGestureRecognizer(tapGesture)
self.websiteRow.isUserInteractionEnabled = true
tapGesture = UITapGestureRecognizer(target: self, action: #selector(rowTapped))
tapGesture.numberOfTapsRequired = 1
self.websiteRow.addGestureRecognizer(tapGesture)
}
fileprivate func setRowIsHidden(_ row: UIView, to isHidden: Bool) {
row.isHidden = isHidden
// To avoid weird constraint warnings, we need to also zero out the
// layoutMargins of the row.
if isHidden {
row.layoutMargins = UIEdgeInsets.zero
} else {
row.layoutMargins = UIEdgeInsets(top: 5, left: 8, bottom: 5, right: 8)
}
}
fileprivate func setProfileLabelText(_ label: UILabel, text: String?) {
let text = text ?? ""
if text != "" {
label.text = text
label.isHidden = false
} else {
label.isHidden = true
}
}
@objc
private func rowTapped(sender: UITapGestureRecognizer) {
guard let user = self.user else {
return
}
if sender.view == self.emailRow {
let email = user.email ?? ""
if email != "" {
let mailto = URL(string: "mailto:\(email)")!
if UIApplication.shared.canOpenURL(mailto) {
UIApplication.shared.open(mailto, options: [:], completionHandler: nil)
} else {
mainStore.dispatch(showToast(type: .error, message: "Unable to open the mail client"))
}
}
} else if sender.view == self.websiteRow {
if var website = user.website?.absoluteString {
if !website.hasPrefix("http://") && !website.hasPrefix("https://") {
website = "http://\(website)"
}
if let url = URL(string: website) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
mainStore.dispatch(showToast(type: .error, message: "Unable to open the website"))
}
}
}
}
}
override func viewWillAppear(_ animated: Bool) {
mainStore.dispatch(loadUserProfile(username: self.username))
mainStore.subscribe(self) { (state: AppState) -> UserModel? in
return state.userProfileState.users
.first(where: { $0.username == self.username })
}
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
mainStore.unsubscribe(self)
super.viewWillDisappear(animated)
}
}
extension UserProfileViewController: StoreSubscriber {
func newState(state: UserModel?) {
guard let user = state else {
return
}
self.user = user
self.avatarImage.kf.setImage(with: user.avatarUrl,
placeholder: #imageLiteral(resourceName: "AvatarPlaceholder"),
options: nil,
progressBlock: nil,
completionHandler: nil)
self.setProfileLabelText(self.nameLabel, text: user.name)
self.setProfileLabelText(self.usernameLabel, text: user.username)
self.setProfileLabelText(self.bioLabel, text: user.bio)
let location = user.location ?? ""
if location != "" {
self.locationLabel.text = location
self.setRowIsHidden(self.locationRow, to: false)
} else {
self.setRowIsHidden(self.locationRow, to: true)
}
let email = user.email ?? ""
if email != "" {
self.emailLabel.text = email
self.setRowIsHidden(self.emailRow, to: false)
} else {
self.setRowIsHidden(self.emailRow, to: true)
}
let website = user.website?.absoluteString ?? ""
if website != "" {
self.websiteLabel.text = website
self.setRowIsHidden(self.websiteRow, to: false)
} else {
self.setRowIsHidden(self.websiteRow, to: true)
}
}
}
| mit | 64a43a80750f5d72743d804736b1e3bc | 34.208333 | 106 | 0.573288 | 4.995777 | false | false | false | false |
thorfroelich/TaylorSource | Sources/Base/Sectioned.swift | 2 | 6746 | import Foundation
/**
Objects adopting this protocol can be used as sections in a sectioned data source.
A section can be anything, as long as it supplies an array of items in that section.
Adding additional properties, such as the section title or an icon, will allow
you to properly customize supplementary views, such as section headers or footers.
*/
public protocol SectionType: SequenceType, CollectionType {
associatedtype ItemType
var items: [ItemType] { get }
}
// Let SectionType behave as a sequence of ItemType elements
extension SectionType where Self: SequenceType {
public func generate() -> Array<ItemType>.Generator {
return items.generate()
}
}
// Let SectionType behave as a collection of ItemType elements
extension SectionType where Self: CollectionType {
public var startIndex: Int {
return items.startIndex
}
public var endIndex: Int {
return items.endIndex
}
public subscript(i: Int) -> ItemType {
return items[i]
}
}
/**
A concrete implementation of `DatasourceType` for a fixed set of sectioned data.
The data source is initalized with the section models it contains. Each section
contains an immutable array of the items in that section.
The cell and supplementary index types are both `NSIndexPath`, making this class
compatible with a `BasicFactory`. This also means that the configuration block for
cells and supplementary views will receive an NSIndexPath as their index argument.
*/
public class StaticSectionDatasource<Factory, StaticSectionType where
Factory: _FactoryType,
Factory.CellIndexType == NSIndexPath,
Factory.SupplementaryIndexType == NSIndexPath,
StaticSectionType: SectionType,
StaticSectionType.ItemType == Factory.ItemType>: DatasourceType {
public typealias FactoryType = Factory
public var title: String?
public let factory: Factory
public let identifier: String
private var sections: [StaticSectionType]
/**
The designated initializer.
- parameter id: A `String` identifier.
- parameter factory: A `Factory` whose `CellIndexType` and `SupplementaryIndexType` must be `NSIndexPath`, such as `BasicFactory`.
- parameter sections: An array of `SectionType` instances where `SectionType.ItemType` matches `Factory.ItemType`.
*/
public init(id: String, factory f: Factory, sections s: [StaticSectionType]) {
identifier = id
factory = f
sections = s
}
/// The number of sections.
public var numberOfSections: Int {
return sections.count
}
/// The number of items in the section with the given index.
public func numberOfItemsInSection(sectionIndex: Int) -> Int {
return sections[sectionIndex].items.count
}
/**
Access the section model object for a given index.
Use this to configure any supplementary views, headers and footers.
- parameter index: The index of the section.
- returns: The section object at `index` or `.None` if `index` is out of bounds.
*/
public func sectionAtIndex(index: Int) -> StaticSectionType? {
if sections.startIndex <= index && index < sections.endIndex {
return sections[index]
}
return nil
}
/**
The item for a given index path.
- parameter indexPath: The index path of the item.
- returns: The item at `indexPath` or `.None` if `indexPath` is out of bounds.
*/
public func itemAtIndexPath(indexPath: NSIndexPath) -> Factory.ItemType? {
guard let section = sectionAtIndex(indexPath.section) else {
return .None
}
if sections.startIndex <= indexPath.item && indexPath.item < sections.endIndex {
return section[indexPath.item]
}
return nil
}
/**
Returns a configured cell.
The cell is dequeued from the supplied view and configured with the item at the
supplied index path.
Note, that while `itemAtIndexPath` will gracefully return `.None` if the
index path is out of range, this method will trigger a fatal error if
`indexPath` does not reference a valid entry in the dataset.
- parameter view: The containing view instance responsible for dequeueing.
- parameter indexPath: The `NSIndexPath` for the item.
- returns: A dequeued and configured instance of `Factory.CellType`.
*/
public func cellForItemInView(view: Factory.ViewType, atIndexPath indexPath: NSIndexPath) -> Factory.CellType {
if let item = itemAtIndexPath(indexPath) {
return factory.cellForItem(item, inView: view, atIndex: indexPath)
}
fatalError("No item available at index path: \(indexPath)")
}
/**
Returns a configured supplementary view.
This is the result of running any registered closure from the factory
for this supplementary element kind.
- parameter view: The containing view instance responsible for dequeueing.
- parameter kind: The `SupplementaryElementKind` of the supplementary view.
- parameter indexPath: The `NSIndexPath` for the item.
- returns: A dequeued and configured instance of `Factory.SupplementaryViewType`.
*/
public func viewForSupplementaryElementInView(view: Factory.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> Factory.SupplementaryViewType? {
return factory.supplementaryViewForKind(kind, inView: view, atIndex: indexPath)
}
/**
Returns an optional text for the supplementary element kind
- parameter view: The containing view instance responsible for dequeueing.
- parameter kind: The `SupplementaryElementKind` of the supplementary view.
- parameter indexPath: The `NSIndexPath` for the item.
- returns: A `TextType?` for the supplementary element.
*/
public func textForSupplementaryElementInView(view: Factory.ViewType, kind: SupplementaryElementKind, atIndexPath indexPath: NSIndexPath) -> Factory.TextType? {
return factory.supplementaryTextForKind(kind, atIndex: indexPath)
}
}
// Let StaticSectionDatasource behave as a sequence of StaticSectionType elements
extension StaticSectionDatasource: SequenceType {
public func generate() -> Array<StaticSectionType>.Generator {
return sections.generate()
}
}
// Let StaticSectionDatasource behave as a collection of StaticSectionType elements
extension StaticSectionDatasource: CollectionType {
public var startIndex: Int {
return sections.startIndex
}
public var endIndex: Int {
return sections.endIndex
}
public subscript(i: Int) -> StaticSectionType {
return sections[i]
}
}
| mit | b5e9e4c24aeb5953acae73ae7577f118 | 35.464865 | 177 | 0.708716 | 5.030574 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/CloudWatchLogs/CloudWatchLogs_Shapes.swift | 1 | 104042 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension CloudWatchLogs {
// MARK: Enums
public enum Distribution: String, CustomStringConvertible, Codable {
case bylogstream = "ByLogStream"
case random = "Random"
public var description: String { return self.rawValue }
}
public enum ExportTaskStatusCode: String, CustomStringConvertible, Codable {
case cancelled = "CANCELLED"
case completed = "COMPLETED"
case failed = "FAILED"
case pending = "PENDING"
case pendingCancel = "PENDING_CANCEL"
case running = "RUNNING"
public var description: String { return self.rawValue }
}
public enum OrderBy: String, CustomStringConvertible, Codable {
case lasteventtime = "LastEventTime"
case logstreamname = "LogStreamName"
public var description: String { return self.rawValue }
}
public enum QueryStatus: String, CustomStringConvertible, Codable {
case cancelled = "Cancelled"
case complete = "Complete"
case failed = "Failed"
case running = "Running"
case scheduled = "Scheduled"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct AssociateKmsKeyRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the CMK to use when encrypting log data. This must be a symmetric CMK. For more information, see Amazon Resource Names - AWS Key Management Service (AWS KMS) and Using Symmetric and Asymmetric Keys.
public let kmsKeyId: String
/// The name of the log group.
public let logGroupName: String
public init(kmsKeyId: String, logGroupName: String) {
self.kmsKeyId = kmsKeyId
self.logGroupName = logGroupName
}
public func validate(name: String) throws {
try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, max: 256)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
}
private enum CodingKeys: String, CodingKey {
case kmsKeyId
case logGroupName
}
}
public struct CancelExportTaskRequest: AWSEncodableShape {
/// The ID of the export task.
public let taskId: String
public init(taskId: String) {
self.taskId = taskId
}
public func validate(name: String) throws {
try self.validate(self.taskId, name: "taskId", parent: name, max: 512)
try self.validate(self.taskId, name: "taskId", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case taskId
}
}
public struct CreateExportTaskRequest: AWSEncodableShape {
/// The name of S3 bucket for the exported log data. The bucket must be in the same AWS region.
public let destination: String
/// The prefix used as the start of the key for every object exported. If you don't specify a value, the default is exportedlogs.
public let destinationPrefix: String?
/// The start time of the range for the request, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp earlier than this time are not exported.
public let from: Int64
/// The name of the log group.
public let logGroupName: String
/// Export only log streams that match the provided prefix. If you don't specify a value, no prefix filter is applied.
public let logStreamNamePrefix: String?
/// The name of the export task.
public let taskName: String?
/// The end time of the range for the request, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp later than this time are not exported.
public let to: Int64
public init(destination: String, destinationPrefix: String? = nil, from: Int64, logGroupName: String, logStreamNamePrefix: String? = nil, taskName: String? = nil, to: Int64) {
self.destination = destination
self.destinationPrefix = destinationPrefix
self.from = from
self.logGroupName = logGroupName
self.logStreamNamePrefix = logStreamNamePrefix
self.taskName = taskName
self.to = to
}
public func validate(name: String) throws {
try self.validate(self.destination, name: "destination", parent: name, max: 512)
try self.validate(self.destination, name: "destination", parent: name, min: 1)
try self.validate(self.from, name: "from", parent: name, min: 0)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.logStreamNamePrefix, name: "logStreamNamePrefix", parent: name, max: 512)
try self.validate(self.logStreamNamePrefix, name: "logStreamNamePrefix", parent: name, min: 1)
try self.validate(self.logStreamNamePrefix, name: "logStreamNamePrefix", parent: name, pattern: "[^:*]*")
try self.validate(self.taskName, name: "taskName", parent: name, max: 512)
try self.validate(self.taskName, name: "taskName", parent: name, min: 1)
try self.validate(self.to, name: "to", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case destination
case destinationPrefix
case from
case logGroupName
case logStreamNamePrefix
case taskName
case to
}
}
public struct CreateExportTaskResponse: AWSDecodableShape {
/// The ID of the export task.
public let taskId: String?
public init(taskId: String? = nil) {
self.taskId = taskId
}
private enum CodingKeys: String, CodingKey {
case taskId
}
}
public struct CreateLogGroupRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the CMK to use when encrypting log data. For more information, see Amazon Resource Names - AWS Key Management Service (AWS KMS).
public let kmsKeyId: String?
/// The name of the log group.
public let logGroupName: String
/// The key-value pairs to use for the tags.
public let tags: [String: String]?
public init(kmsKeyId: String? = nil, logGroupName: String, tags: [String: String]? = nil) {
self.kmsKeyId = kmsKeyId
self.logGroupName = logGroupName
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, max: 256)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.tags?.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.key, name: "tags.key", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+)$")
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
}
}
private enum CodingKeys: String, CodingKey {
case kmsKeyId
case logGroupName
case tags
}
}
public struct CreateLogStreamRequest: AWSEncodableShape {
/// The name of the log group.
public let logGroupName: String
/// The name of the log stream.
public let logStreamName: String
public init(logGroupName: String, logStreamName: String) {
self.logGroupName = logGroupName
self.logStreamName = logStreamName
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.logStreamName, name: "logStreamName", parent: name, max: 512)
try self.validate(self.logStreamName, name: "logStreamName", parent: name, min: 1)
try self.validate(self.logStreamName, name: "logStreamName", parent: name, pattern: "[^:*]*")
}
private enum CodingKeys: String, CodingKey {
case logGroupName
case logStreamName
}
}
public struct DeleteDestinationRequest: AWSEncodableShape {
/// The name of the destination.
public let destinationName: String
public init(destinationName: String) {
self.destinationName = destinationName
}
public func validate(name: String) throws {
try self.validate(self.destinationName, name: "destinationName", parent: name, max: 512)
try self.validate(self.destinationName, name: "destinationName", parent: name, min: 1)
try self.validate(self.destinationName, name: "destinationName", parent: name, pattern: "[^:*]*")
}
private enum CodingKeys: String, CodingKey {
case destinationName
}
}
public struct DeleteLogGroupRequest: AWSEncodableShape {
/// The name of the log group.
public let logGroupName: String
public init(logGroupName: String) {
self.logGroupName = logGroupName
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
}
private enum CodingKeys: String, CodingKey {
case logGroupName
}
}
public struct DeleteLogStreamRequest: AWSEncodableShape {
/// The name of the log group.
public let logGroupName: String
/// The name of the log stream.
public let logStreamName: String
public init(logGroupName: String, logStreamName: String) {
self.logGroupName = logGroupName
self.logStreamName = logStreamName
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.logStreamName, name: "logStreamName", parent: name, max: 512)
try self.validate(self.logStreamName, name: "logStreamName", parent: name, min: 1)
try self.validate(self.logStreamName, name: "logStreamName", parent: name, pattern: "[^:*]*")
}
private enum CodingKeys: String, CodingKey {
case logGroupName
case logStreamName
}
}
public struct DeleteMetricFilterRequest: AWSEncodableShape {
/// The name of the metric filter.
public let filterName: String
/// The name of the log group.
public let logGroupName: String
public init(filterName: String, logGroupName: String) {
self.filterName = filterName
self.logGroupName = logGroupName
}
public func validate(name: String) throws {
try self.validate(self.filterName, name: "filterName", parent: name, max: 512)
try self.validate(self.filterName, name: "filterName", parent: name, min: 1)
try self.validate(self.filterName, name: "filterName", parent: name, pattern: "[^:*]*")
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
}
private enum CodingKeys: String, CodingKey {
case filterName
case logGroupName
}
}
public struct DeleteQueryDefinitionRequest: AWSEncodableShape {
/// The ID of the query definition that you want to delete. You can use DescribeQueryDefinitions to retrieve the IDs of your saved query definitions.
public let queryDefinitionId: String
public init(queryDefinitionId: String) {
self.queryDefinitionId = queryDefinitionId
}
public func validate(name: String) throws {
try self.validate(self.queryDefinitionId, name: "queryDefinitionId", parent: name, max: 256)
try self.validate(self.queryDefinitionId, name: "queryDefinitionId", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case queryDefinitionId
}
}
public struct DeleteQueryDefinitionResponse: AWSDecodableShape {
/// A value of TRUE indicates that the operation succeeded. FALSE indicates that the operation failed.
public let success: Bool?
public init(success: Bool? = nil) {
self.success = success
}
private enum CodingKeys: String, CodingKey {
case success
}
}
public struct DeleteResourcePolicyRequest: AWSEncodableShape {
/// The name of the policy to be revoked. This parameter is required.
public let policyName: String?
public init(policyName: String? = nil) {
self.policyName = policyName
}
private enum CodingKeys: String, CodingKey {
case policyName
}
}
public struct DeleteRetentionPolicyRequest: AWSEncodableShape {
/// The name of the log group.
public let logGroupName: String
public init(logGroupName: String) {
self.logGroupName = logGroupName
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
}
private enum CodingKeys: String, CodingKey {
case logGroupName
}
}
public struct DeleteSubscriptionFilterRequest: AWSEncodableShape {
/// The name of the subscription filter.
public let filterName: String
/// The name of the log group.
public let logGroupName: String
public init(filterName: String, logGroupName: String) {
self.filterName = filterName
self.logGroupName = logGroupName
}
public func validate(name: String) throws {
try self.validate(self.filterName, name: "filterName", parent: name, max: 512)
try self.validate(self.filterName, name: "filterName", parent: name, min: 1)
try self.validate(self.filterName, name: "filterName", parent: name, pattern: "[^:*]*")
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
}
private enum CodingKeys: String, CodingKey {
case filterName
case logGroupName
}
}
public struct DescribeDestinationsRequest: AWSEncodableShape {
/// The prefix to match. If you don't specify a value, no prefix filter is applied.
public let destinationNamePrefix: String?
/// The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
public let limit: Int?
/// The token for the next set of items to return. (You received this token from a previous call.)
public let nextToken: String?
public init(destinationNamePrefix: String? = nil, limit: Int? = nil, nextToken: String? = nil) {
self.destinationNamePrefix = destinationNamePrefix
self.limit = limit
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.destinationNamePrefix, name: "destinationNamePrefix", parent: name, max: 512)
try self.validate(self.destinationNamePrefix, name: "destinationNamePrefix", parent: name, min: 1)
try self.validate(self.destinationNamePrefix, name: "destinationNamePrefix", parent: name, pattern: "[^:*]*")
try self.validate(self.limit, name: "limit", parent: name, max: 50)
try self.validate(self.limit, name: "limit", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case destinationNamePrefix = "DestinationNamePrefix"
case limit
case nextToken
}
}
public struct DescribeDestinationsResponse: AWSDecodableShape {
/// The destinations.
public let destinations: [Destination]?
public let nextToken: String?
public init(destinations: [Destination]? = nil, nextToken: String? = nil) {
self.destinations = destinations
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case destinations
case nextToken
}
}
public struct DescribeExportTasksRequest: AWSEncodableShape {
/// The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
public let limit: Int?
/// The token for the next set of items to return. (You received this token from a previous call.)
public let nextToken: String?
/// The status code of the export task. Specifying a status code filters the results to zero or more export tasks.
public let statusCode: ExportTaskStatusCode?
/// The ID of the export task. Specifying a task ID filters the results to zero or one export tasks.
public let taskId: String?
public init(limit: Int? = nil, nextToken: String? = nil, statusCode: ExportTaskStatusCode? = nil, taskId: String? = nil) {
self.limit = limit
self.nextToken = nextToken
self.statusCode = statusCode
self.taskId = taskId
}
public func validate(name: String) throws {
try self.validate(self.limit, name: "limit", parent: name, max: 50)
try self.validate(self.limit, name: "limit", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.taskId, name: "taskId", parent: name, max: 512)
try self.validate(self.taskId, name: "taskId", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case limit
case nextToken
case statusCode
case taskId
}
}
public struct DescribeExportTasksResponse: AWSDecodableShape {
/// The export tasks.
public let exportTasks: [ExportTask]?
public let nextToken: String?
public init(exportTasks: [ExportTask]? = nil, nextToken: String? = nil) {
self.exportTasks = exportTasks
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case exportTasks
case nextToken
}
}
public struct DescribeLogGroupsRequest: AWSEncodableShape {
/// The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
public let limit: Int?
/// The prefix to match.
public let logGroupNamePrefix: String?
/// The token for the next set of items to return. (You received this token from a previous call.)
public let nextToken: String?
public init(limit: Int? = nil, logGroupNamePrefix: String? = nil, nextToken: String? = nil) {
self.limit = limit
self.logGroupNamePrefix = logGroupNamePrefix
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.limit, name: "limit", parent: name, max: 50)
try self.validate(self.limit, name: "limit", parent: name, min: 1)
try self.validate(self.logGroupNamePrefix, name: "logGroupNamePrefix", parent: name, max: 512)
try self.validate(self.logGroupNamePrefix, name: "logGroupNamePrefix", parent: name, min: 1)
try self.validate(self.logGroupNamePrefix, name: "logGroupNamePrefix", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case limit
case logGroupNamePrefix
case nextToken
}
}
public struct DescribeLogGroupsResponse: AWSDecodableShape {
/// The log groups. If the retentionInDays value if not included for a log group, then that log group is set to have its events never expire.
public let logGroups: [LogGroup]?
public let nextToken: String?
public init(logGroups: [LogGroup]? = nil, nextToken: String? = nil) {
self.logGroups = logGroups
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case logGroups
case nextToken
}
}
public struct DescribeLogStreamsRequest: AWSEncodableShape {
/// If the value is true, results are returned in descending order. If the value is to false, results are returned in ascending order. The default value is false.
public let descending: Bool?
/// The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
public let limit: Int?
/// The name of the log group.
public let logGroupName: String
/// The prefix to match. If orderBy is LastEventTime, you cannot specify this parameter.
public let logStreamNamePrefix: String?
/// The token for the next set of items to return. (You received this token from a previous call.)
public let nextToken: String?
/// If the value is LogStreamName, the results are ordered by log stream name. If the value is LastEventTime, the results are ordered by the event time. The default value is LogStreamName. If you order the results by event time, you cannot specify the logStreamNamePrefix parameter. lastEventTimeStamp represents the time of the most recent log event in the log stream in CloudWatch Logs. This number is expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. lastEventTimeStamp updates on an eventual consistency basis. It typically updates in less than an hour from ingestion, but in rare situations might take longer.
public let orderBy: OrderBy?
public init(descending: Bool? = nil, limit: Int? = nil, logGroupName: String, logStreamNamePrefix: String? = nil, nextToken: String? = nil, orderBy: OrderBy? = nil) {
self.descending = descending
self.limit = limit
self.logGroupName = logGroupName
self.logStreamNamePrefix = logStreamNamePrefix
self.nextToken = nextToken
self.orderBy = orderBy
}
public func validate(name: String) throws {
try self.validate(self.limit, name: "limit", parent: name, max: 50)
try self.validate(self.limit, name: "limit", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.logStreamNamePrefix, name: "logStreamNamePrefix", parent: name, max: 512)
try self.validate(self.logStreamNamePrefix, name: "logStreamNamePrefix", parent: name, min: 1)
try self.validate(self.logStreamNamePrefix, name: "logStreamNamePrefix", parent: name, pattern: "[^:*]*")
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case descending
case limit
case logGroupName
case logStreamNamePrefix
case nextToken
case orderBy
}
}
public struct DescribeLogStreamsResponse: AWSDecodableShape {
/// The log streams.
public let logStreams: [LogStream]?
public let nextToken: String?
public init(logStreams: [LogStream]? = nil, nextToken: String? = nil) {
self.logStreams = logStreams
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case logStreams
case nextToken
}
}
public struct DescribeMetricFiltersRequest: AWSEncodableShape {
/// The prefix to match. CloudWatch Logs uses the value you set here only if you also include the logGroupName parameter in your request.
public let filterNamePrefix: String?
/// The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
public let limit: Int?
/// The name of the log group.
public let logGroupName: String?
/// Filters results to include only those with the specified metric name. If you include this parameter in your request, you must also include the metricNamespace parameter.
public let metricName: String?
/// Filters results to include only those in the specified namespace. If you include this parameter in your request, you must also include the metricName parameter.
public let metricNamespace: String?
/// The token for the next set of items to return. (You received this token from a previous call.)
public let nextToken: String?
public init(filterNamePrefix: String? = nil, limit: Int? = nil, logGroupName: String? = nil, metricName: String? = nil, metricNamespace: String? = nil, nextToken: String? = nil) {
self.filterNamePrefix = filterNamePrefix
self.limit = limit
self.logGroupName = logGroupName
self.metricName = metricName
self.metricNamespace = metricNamespace
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.filterNamePrefix, name: "filterNamePrefix", parent: name, max: 512)
try self.validate(self.filterNamePrefix, name: "filterNamePrefix", parent: name, min: 1)
try self.validate(self.filterNamePrefix, name: "filterNamePrefix", parent: name, pattern: "[^:*]*")
try self.validate(self.limit, name: "limit", parent: name, max: 50)
try self.validate(self.limit, name: "limit", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.metricName, name: "metricName", parent: name, max: 255)
try self.validate(self.metricName, name: "metricName", parent: name, pattern: "[^:*$]*")
try self.validate(self.metricNamespace, name: "metricNamespace", parent: name, max: 255)
try self.validate(self.metricNamespace, name: "metricNamespace", parent: name, pattern: "[^:*$]*")
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case filterNamePrefix
case limit
case logGroupName
case metricName
case metricNamespace
case nextToken
}
}
public struct DescribeMetricFiltersResponse: AWSDecodableShape {
/// The metric filters.
public let metricFilters: [MetricFilter]?
public let nextToken: String?
public init(metricFilters: [MetricFilter]? = nil, nextToken: String? = nil) {
self.metricFilters = metricFilters
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case metricFilters
case nextToken
}
}
public struct DescribeQueriesRequest: AWSEncodableShape {
/// Limits the returned queries to only those for the specified log group.
public let logGroupName: String?
/// Limits the number of returned queries to the specified number.
public let maxResults: Int?
public let nextToken: String?
/// Limits the returned queries to only those that have the specified status. Valid values are Cancelled, Complete, Failed, Running, and Scheduled.
public let status: QueryStatus?
public init(logGroupName: String? = nil, maxResults: Int? = nil, nextToken: String? = nil, status: QueryStatus? = nil) {
self.logGroupName = logGroupName
self.maxResults = maxResults
self.nextToken = nextToken
self.status = status
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case logGroupName
case maxResults
case nextToken
case status
}
}
public struct DescribeQueriesResponse: AWSDecodableShape {
public let nextToken: String?
/// The list of queries that match the request.
public let queries: [QueryInfo]?
public init(nextToken: String? = nil, queries: [QueryInfo]? = nil) {
self.nextToken = nextToken
self.queries = queries
}
private enum CodingKeys: String, CodingKey {
case nextToken
case queries
}
}
public struct DescribeQueryDefinitionsRequest: AWSEncodableShape {
/// Limits the number of returned query definitions to the specified number.
public let maxResults: Int?
public let nextToken: String?
/// Use this parameter to filter your results to only the query definitions that have names that start with the prefix you specify.
public let queryDefinitionNamePrefix: String?
public init(maxResults: Int? = nil, nextToken: String? = nil, queryDefinitionNamePrefix: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
self.queryDefinitionNamePrefix = queryDefinitionNamePrefix
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.queryDefinitionNamePrefix, name: "queryDefinitionNamePrefix", parent: name, max: 255)
try self.validate(self.queryDefinitionNamePrefix, name: "queryDefinitionNamePrefix", parent: name, min: 1)
try self.validate(self.queryDefinitionNamePrefix, name: "queryDefinitionNamePrefix", parent: name, pattern: "^([^:*\\/]+\\/?)*[^:*\\/]+$")
}
private enum CodingKeys: String, CodingKey {
case maxResults
case nextToken
case queryDefinitionNamePrefix
}
}
public struct DescribeQueryDefinitionsResponse: AWSDecodableShape {
public let nextToken: String?
/// The list of query definitions that match your request.
public let queryDefinitions: [QueryDefinition]?
public init(nextToken: String? = nil, queryDefinitions: [QueryDefinition]? = nil) {
self.nextToken = nextToken
self.queryDefinitions = queryDefinitions
}
private enum CodingKeys: String, CodingKey {
case nextToken
case queryDefinitions
}
}
public struct DescribeResourcePoliciesRequest: AWSEncodableShape {
/// The maximum number of resource policies to be displayed with one call of this API.
public let limit: Int?
public let nextToken: String?
public init(limit: Int? = nil, nextToken: String? = nil) {
self.limit = limit
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.limit, name: "limit", parent: name, max: 50)
try self.validate(self.limit, name: "limit", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case limit
case nextToken
}
}
public struct DescribeResourcePoliciesResponse: AWSDecodableShape {
public let nextToken: String?
/// The resource policies that exist in this account.
public let resourcePolicies: [ResourcePolicy]?
public init(nextToken: String? = nil, resourcePolicies: [ResourcePolicy]? = nil) {
self.nextToken = nextToken
self.resourcePolicies = resourcePolicies
}
private enum CodingKeys: String, CodingKey {
case nextToken
case resourcePolicies
}
}
public struct DescribeSubscriptionFiltersRequest: AWSEncodableShape {
/// The prefix to match. If you don't specify a value, no prefix filter is applied.
public let filterNamePrefix: String?
/// The maximum number of items returned. If you don't specify a value, the default is up to 50 items.
public let limit: Int?
/// The name of the log group.
public let logGroupName: String
/// The token for the next set of items to return. (You received this token from a previous call.)
public let nextToken: String?
public init(filterNamePrefix: String? = nil, limit: Int? = nil, logGroupName: String, nextToken: String? = nil) {
self.filterNamePrefix = filterNamePrefix
self.limit = limit
self.logGroupName = logGroupName
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.filterNamePrefix, name: "filterNamePrefix", parent: name, max: 512)
try self.validate(self.filterNamePrefix, name: "filterNamePrefix", parent: name, min: 1)
try self.validate(self.filterNamePrefix, name: "filterNamePrefix", parent: name, pattern: "[^:*]*")
try self.validate(self.limit, name: "limit", parent: name, max: 50)
try self.validate(self.limit, name: "limit", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case filterNamePrefix
case limit
case logGroupName
case nextToken
}
}
public struct DescribeSubscriptionFiltersResponse: AWSDecodableShape {
public let nextToken: String?
/// The subscription filters.
public let subscriptionFilters: [SubscriptionFilter]?
public init(nextToken: String? = nil, subscriptionFilters: [SubscriptionFilter]? = nil) {
self.nextToken = nextToken
self.subscriptionFilters = subscriptionFilters
}
private enum CodingKeys: String, CodingKey {
case nextToken
case subscriptionFilters
}
}
public struct Destination: AWSDecodableShape {
/// An IAM policy document that governs which AWS accounts can create subscription filters against this destination.
public let accessPolicy: String?
/// The ARN of this destination.
public let arn: String?
/// The creation time of the destination, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let creationTime: Int64?
/// The name of the destination.
public let destinationName: String?
/// A role for impersonation, used when delivering log events to the target.
public let roleArn: String?
/// The Amazon Resource Name (ARN) of the physical target where the log events are delivered (for example, a Kinesis stream).
public let targetArn: String?
public init(accessPolicy: String? = nil, arn: String? = nil, creationTime: Int64? = nil, destinationName: String? = nil, roleArn: String? = nil, targetArn: String? = nil) {
self.accessPolicy = accessPolicy
self.arn = arn
self.creationTime = creationTime
self.destinationName = destinationName
self.roleArn = roleArn
self.targetArn = targetArn
}
private enum CodingKeys: String, CodingKey {
case accessPolicy
case arn
case creationTime
case destinationName
case roleArn
case targetArn
}
}
public struct DisassociateKmsKeyRequest: AWSEncodableShape {
/// The name of the log group.
public let logGroupName: String
public init(logGroupName: String) {
self.logGroupName = logGroupName
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
}
private enum CodingKeys: String, CodingKey {
case logGroupName
}
}
public struct ExportTask: AWSDecodableShape {
/// The name of the S3 bucket to which the log data was exported.
public let destination: String?
/// The prefix that was used as the start of Amazon S3 key for every object exported.
public let destinationPrefix: String?
/// Execution information about the export task.
public let executionInfo: ExportTaskExecutionInfo?
/// The start time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp before this time are not exported.
public let from: Int64?
/// The name of the log group from which logs data was exported.
public let logGroupName: String?
/// The status of the export task.
public let status: ExportTaskStatus?
/// The ID of the export task.
public let taskId: String?
/// The name of the export task.
public let taskName: String?
/// The end time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp later than this time are not exported.
public let to: Int64?
public init(destination: String? = nil, destinationPrefix: String? = nil, executionInfo: ExportTaskExecutionInfo? = nil, from: Int64? = nil, logGroupName: String? = nil, status: ExportTaskStatus? = nil, taskId: String? = nil, taskName: String? = nil, to: Int64? = nil) {
self.destination = destination
self.destinationPrefix = destinationPrefix
self.executionInfo = executionInfo
self.from = from
self.logGroupName = logGroupName
self.status = status
self.taskId = taskId
self.taskName = taskName
self.to = to
}
private enum CodingKeys: String, CodingKey {
case destination
case destinationPrefix
case executionInfo
case from
case logGroupName
case status
case taskId
case taskName
case to
}
}
public struct ExportTaskExecutionInfo: AWSDecodableShape {
/// The completion time of the export task, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let completionTime: Int64?
/// The creation time of the export task, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let creationTime: Int64?
public init(completionTime: Int64? = nil, creationTime: Int64? = nil) {
self.completionTime = completionTime
self.creationTime = creationTime
}
private enum CodingKeys: String, CodingKey {
case completionTime
case creationTime
}
}
public struct ExportTaskStatus: AWSDecodableShape {
/// The status code of the export task.
public let code: ExportTaskStatusCode?
/// The status message related to the status code.
public let message: String?
public init(code: ExportTaskStatusCode? = nil, message: String? = nil) {
self.code = code
self.message = message
}
private enum CodingKeys: String, CodingKey {
case code
case message
}
}
public struct FilterLogEventsRequest: AWSEncodableShape {
/// The end of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp later than this time are not returned.
public let endTime: Int64?
/// The filter pattern to use. For more information, see Filter and Pattern Syntax. If not provided, all the events are matched.
public let filterPattern: String?
/// The maximum number of events to return. The default is 10,000 events.
public let limit: Int?
/// The name of the log group to search.
public let logGroupName: String
/// Filters the results to include only events from log streams that have names starting with this prefix. If you specify a value for both logStreamNamePrefix and logStreamNames, but the value for logStreamNamePrefix does not match any log stream names specified in logStreamNames, the action returns an InvalidParameterException error.
public let logStreamNamePrefix: String?
/// Filters the results to only logs from the log streams in this list. If you specify a value for both logStreamNamePrefix and logStreamNames, the action returns an InvalidParameterException error.
public let logStreamNames: [String]?
/// The token for the next set of events to return. (You received this token from a previous call.)
public let nextToken: String?
/// The start of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp before this time are not returned. If you omit startTime and endTime the most recent log events are retrieved, to up 1 MB or 10,000 log events.
public let startTime: Int64?
public init(endTime: Int64? = nil, filterPattern: String? = nil, limit: Int? = nil, logGroupName: String, logStreamNamePrefix: String? = nil, logStreamNames: [String]? = nil, nextToken: String? = nil, startTime: Int64? = nil) {
self.endTime = endTime
self.filterPattern = filterPattern
self.limit = limit
self.logGroupName = logGroupName
self.logStreamNamePrefix = logStreamNamePrefix
self.logStreamNames = logStreamNames
self.nextToken = nextToken
self.startTime = startTime
}
public func validate(name: String) throws {
try self.validate(self.endTime, name: "endTime", parent: name, min: 0)
try self.validate(self.filterPattern, name: "filterPattern", parent: name, max: 1024)
try self.validate(self.filterPattern, name: "filterPattern", parent: name, min: 0)
try self.validate(self.limit, name: "limit", parent: name, max: 10000)
try self.validate(self.limit, name: "limit", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.logStreamNamePrefix, name: "logStreamNamePrefix", parent: name, max: 512)
try self.validate(self.logStreamNamePrefix, name: "logStreamNamePrefix", parent: name, min: 1)
try self.validate(self.logStreamNamePrefix, name: "logStreamNamePrefix", parent: name, pattern: "[^:*]*")
try self.logStreamNames?.forEach {
try validate($0, name: "logStreamNames[]", parent: name, max: 512)
try validate($0, name: "logStreamNames[]", parent: name, min: 1)
try validate($0, name: "logStreamNames[]", parent: name, pattern: "[^:*]*")
}
try self.validate(self.logStreamNames, name: "logStreamNames", parent: name, max: 100)
try self.validate(self.logStreamNames, name: "logStreamNames", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.startTime, name: "startTime", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case endTime
case filterPattern
case limit
case logGroupName
case logStreamNamePrefix
case logStreamNames
case nextToken
case startTime
}
}
public struct FilterLogEventsResponse: AWSDecodableShape {
/// The matched events.
public let events: [FilteredLogEvent]?
/// The token to use when requesting the next set of items. The token expires after 24 hours.
public let nextToken: String?
/// IMPORTANT Starting on May 15, 2020, this parameter will be deprecated. This parameter will be an empty list after the deprecation occurs. Indicates which log streams have been searched and whether each has been searched completely.
public let searchedLogStreams: [SearchedLogStream]?
public init(events: [FilteredLogEvent]? = nil, nextToken: String? = nil, searchedLogStreams: [SearchedLogStream]? = nil) {
self.events = events
self.nextToken = nextToken
self.searchedLogStreams = searchedLogStreams
}
private enum CodingKeys: String, CodingKey {
case events
case nextToken
case searchedLogStreams
}
}
public struct FilteredLogEvent: AWSDecodableShape {
/// The ID of the event.
public let eventId: String?
/// The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let ingestionTime: Int64?
/// The name of the log stream to which this event belongs.
public let logStreamName: String?
/// The data contained in the log event.
public let message: String?
/// The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let timestamp: Int64?
public init(eventId: String? = nil, ingestionTime: Int64? = nil, logStreamName: String? = nil, message: String? = nil, timestamp: Int64? = nil) {
self.eventId = eventId
self.ingestionTime = ingestionTime
self.logStreamName = logStreamName
self.message = message
self.timestamp = timestamp
}
private enum CodingKeys: String, CodingKey {
case eventId
case ingestionTime
case logStreamName
case message
case timestamp
}
}
public struct GetLogEventsRequest: AWSEncodableShape {
/// The end of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp equal to or later than this time are not included.
public let endTime: Int64?
/// The maximum number of log events returned. If you don't specify a value, the maximum is as many log events as can fit in a response size of 1 MB, up to 10,000 log events.
public let limit: Int?
/// The name of the log group.
public let logGroupName: String
/// The name of the log stream.
public let logStreamName: String
/// The token for the next set of items to return. (You received this token from a previous call.) Using this token works only when you specify true for startFromHead.
public let nextToken: String?
/// If the value is true, the earliest log events are returned first. If the value is false, the latest log events are returned first. The default value is false. If you are using nextToken in this operation, you must specify true for startFromHead.
public let startFromHead: Bool?
/// The start of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. Events with a timestamp equal to this time or later than this time are included. Events with a timestamp earlier than this time are not included.
public let startTime: Int64?
public init(endTime: Int64? = nil, limit: Int? = nil, logGroupName: String, logStreamName: String, nextToken: String? = nil, startFromHead: Bool? = nil, startTime: Int64? = nil) {
self.endTime = endTime
self.limit = limit
self.logGroupName = logGroupName
self.logStreamName = logStreamName
self.nextToken = nextToken
self.startFromHead = startFromHead
self.startTime = startTime
}
public func validate(name: String) throws {
try self.validate(self.endTime, name: "endTime", parent: name, min: 0)
try self.validate(self.limit, name: "limit", parent: name, max: 10000)
try self.validate(self.limit, name: "limit", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.logStreamName, name: "logStreamName", parent: name, max: 512)
try self.validate(self.logStreamName, name: "logStreamName", parent: name, min: 1)
try self.validate(self.logStreamName, name: "logStreamName", parent: name, pattern: "[^:*]*")
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.startTime, name: "startTime", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case endTime
case limit
case logGroupName
case logStreamName
case nextToken
case startFromHead
case startTime
}
}
public struct GetLogEventsResponse: AWSDecodableShape {
/// The events.
public let events: [OutputLogEvent]?
/// The token for the next set of items in the backward direction. The token expires after 24 hours. This token is never null. If you have reached the end of the stream, it returns the same token you passed in.
public let nextBackwardToken: String?
/// The token for the next set of items in the forward direction. The token expires after 24 hours. If you have reached the end of the stream, it returns the same token you passed in.
public let nextForwardToken: String?
public init(events: [OutputLogEvent]? = nil, nextBackwardToken: String? = nil, nextForwardToken: String? = nil) {
self.events = events
self.nextBackwardToken = nextBackwardToken
self.nextForwardToken = nextForwardToken
}
private enum CodingKeys: String, CodingKey {
case events
case nextBackwardToken
case nextForwardToken
}
}
public struct GetLogGroupFieldsRequest: AWSEncodableShape {
/// The name of the log group to search.
public let logGroupName: String
/// The time to set as the center of the query. If you specify time, the 8 minutes before and 8 minutes after this time are searched. If you omit time, the past 15 minutes are queried. The time value is specified as epoch time, the number of seconds since January 1, 1970, 00:00:00 UTC.
public let time: Int64?
public init(logGroupName: String, time: Int64? = nil) {
self.logGroupName = logGroupName
self.time = time
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.time, name: "time", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case logGroupName
case time
}
}
public struct GetLogGroupFieldsResponse: AWSDecodableShape {
/// The array of fields found in the query. Each object in the array contains the name of the field, along with the percentage of time it appeared in the log events that were queried.
public let logGroupFields: [LogGroupField]?
public init(logGroupFields: [LogGroupField]? = nil) {
self.logGroupFields = logGroupFields
}
private enum CodingKeys: String, CodingKey {
case logGroupFields
}
}
public struct GetLogRecordRequest: AWSEncodableShape {
/// The pointer corresponding to the log event record you want to retrieve. You get this from the response of a GetQueryResults operation. In that response, the value of the @ptr field for a log event is the value to use as logRecordPointer to retrieve that complete log event record.
public let logRecordPointer: String
public init(logRecordPointer: String) {
self.logRecordPointer = logRecordPointer
}
private enum CodingKeys: String, CodingKey {
case logRecordPointer
}
}
public struct GetLogRecordResponse: AWSDecodableShape {
/// The requested log event, as a JSON string.
public let logRecord: [String: String]?
public init(logRecord: [String: String]? = nil) {
self.logRecord = logRecord
}
private enum CodingKeys: String, CodingKey {
case logRecord
}
}
public struct GetQueryResultsRequest: AWSEncodableShape {
/// The ID number of the query.
public let queryId: String
public init(queryId: String) {
self.queryId = queryId
}
public func validate(name: String) throws {
try self.validate(self.queryId, name: "queryId", parent: name, max: 256)
try self.validate(self.queryId, name: "queryId", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case queryId
}
}
public struct GetQueryResultsResponse: AWSDecodableShape {
/// The log events that matched the query criteria during the most recent time it ran. The results value is an array of arrays. Each log event is one object in the top-level array. Each of these log event objects is an array of field/value pairs.
public let results: [[ResultField]]?
/// Includes the number of log events scanned by the query, the number of log events that matched the query criteria, and the total number of bytes in the log events that were scanned. These values reflect the full raw results of the query.
public let statistics: QueryStatistics?
/// The status of the most recent running of the query. Possible values are Cancelled, Complete, Failed, Running, Scheduled, Timeout, and Unknown. Queries time out after 15 minutes of execution. To avoid having your queries time out, reduce the time range being searched or partition your query into a number of queries.
public let status: QueryStatus?
public init(results: [[ResultField]]? = nil, statistics: QueryStatistics? = nil, status: QueryStatus? = nil) {
self.results = results
self.statistics = statistics
self.status = status
}
private enum CodingKeys: String, CodingKey {
case results
case statistics
case status
}
}
public struct InputLogEvent: AWSEncodableShape {
/// The raw event message.
public let message: String
/// The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let timestamp: Int64
public init(message: String, timestamp: Int64) {
self.message = message
self.timestamp = timestamp
}
public func validate(name: String) throws {
try self.validate(self.message, name: "message", parent: name, min: 1)
try self.validate(self.timestamp, name: "timestamp", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case message
case timestamp
}
}
public struct ListTagsLogGroupRequest: AWSEncodableShape {
/// The name of the log group.
public let logGroupName: String
public init(logGroupName: String) {
self.logGroupName = logGroupName
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
}
private enum CodingKeys: String, CodingKey {
case logGroupName
}
}
public struct ListTagsLogGroupResponse: AWSDecodableShape {
/// The tags for the log group.
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct LogGroup: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the log group.
public let arn: String?
/// The creation time of the log group, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let creationTime: Int64?
/// The Amazon Resource Name (ARN) of the CMK to use when encrypting log data.
public let kmsKeyId: String?
/// The name of the log group.
public let logGroupName: String?
/// The number of metric filters.
public let metricFilterCount: Int?
public let retentionInDays: Int?
/// The number of bytes stored.
public let storedBytes: Int64?
public init(arn: String? = nil, creationTime: Int64? = nil, kmsKeyId: String? = nil, logGroupName: String? = nil, metricFilterCount: Int? = nil, retentionInDays: Int? = nil, storedBytes: Int64? = nil) {
self.arn = arn
self.creationTime = creationTime
self.kmsKeyId = kmsKeyId
self.logGroupName = logGroupName
self.metricFilterCount = metricFilterCount
self.retentionInDays = retentionInDays
self.storedBytes = storedBytes
}
private enum CodingKeys: String, CodingKey {
case arn
case creationTime
case kmsKeyId
case logGroupName
case metricFilterCount
case retentionInDays
case storedBytes
}
}
public struct LogGroupField: AWSDecodableShape {
/// The name of a log field.
public let name: String?
/// The percentage of log events queried that contained the field.
public let percent: Int?
public init(name: String? = nil, percent: Int? = nil) {
self.name = name
self.percent = percent
}
private enum CodingKeys: String, CodingKey {
case name
case percent
}
}
public struct LogStream: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the log stream.
public let arn: String?
/// The creation time of the stream, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let creationTime: Int64?
/// The time of the first event, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let firstEventTimestamp: Int64?
/// The time of the most recent log event in the log stream in CloudWatch Logs. This number is expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. The lastEventTime value updates on an eventual consistency basis. It typically updates in less than an hour from ingestion, but in rare situations might take longer.
public let lastEventTimestamp: Int64?
/// The ingestion time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let lastIngestionTime: Int64?
/// The name of the log stream.
public let logStreamName: String?
/// The sequence token.
public let uploadSequenceToken: String?
public init(arn: String? = nil, creationTime: Int64? = nil, firstEventTimestamp: Int64? = nil, lastEventTimestamp: Int64? = nil, lastIngestionTime: Int64? = nil, logStreamName: String? = nil, uploadSequenceToken: String? = nil) {
self.arn = arn
self.creationTime = creationTime
self.firstEventTimestamp = firstEventTimestamp
self.lastEventTimestamp = lastEventTimestamp
self.lastIngestionTime = lastIngestionTime
self.logStreamName = logStreamName
self.uploadSequenceToken = uploadSequenceToken
}
private enum CodingKeys: String, CodingKey {
case arn
case creationTime
case firstEventTimestamp
case lastEventTimestamp
case lastIngestionTime
case logStreamName
case uploadSequenceToken
}
}
public struct MetricFilter: AWSDecodableShape {
/// The creation time of the metric filter, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let creationTime: Int64?
/// The name of the metric filter.
public let filterName: String?
public let filterPattern: String?
/// The name of the log group.
public let logGroupName: String?
/// The metric transformations.
public let metricTransformations: [MetricTransformation]?
public init(creationTime: Int64? = nil, filterName: String? = nil, filterPattern: String? = nil, logGroupName: String? = nil, metricTransformations: [MetricTransformation]? = nil) {
self.creationTime = creationTime
self.filterName = filterName
self.filterPattern = filterPattern
self.logGroupName = logGroupName
self.metricTransformations = metricTransformations
}
private enum CodingKeys: String, CodingKey {
case creationTime
case filterName
case filterPattern
case logGroupName
case metricTransformations
}
}
public struct MetricFilterMatchRecord: AWSDecodableShape {
/// The raw event data.
public let eventMessage: String?
/// The event number.
public let eventNumber: Int64?
/// The values extracted from the event data by the filter.
public let extractedValues: [String: String]?
public init(eventMessage: String? = nil, eventNumber: Int64? = nil, extractedValues: [String: String]? = nil) {
self.eventMessage = eventMessage
self.eventNumber = eventNumber
self.extractedValues = extractedValues
}
private enum CodingKeys: String, CodingKey {
case eventMessage
case eventNumber
case extractedValues
}
}
public struct MetricTransformation: AWSEncodableShape & AWSDecodableShape {
/// (Optional) The value to emit when a filter pattern does not match a log event. This value can be null.
public let defaultValue: Double?
/// The name of the CloudWatch metric.
public let metricName: String
/// A custom namespace to contain your metric in CloudWatch. Use namespaces to group together metrics that are similar. For more information, see Namespaces.
public let metricNamespace: String
/// The value to publish to the CloudWatch metric when a filter pattern matches a log event.
public let metricValue: String
public init(defaultValue: Double? = nil, metricName: String, metricNamespace: String, metricValue: String) {
self.defaultValue = defaultValue
self.metricName = metricName
self.metricNamespace = metricNamespace
self.metricValue = metricValue
}
public func validate(name: String) throws {
try self.validate(self.metricName, name: "metricName", parent: name, max: 255)
try self.validate(self.metricName, name: "metricName", parent: name, pattern: "[^:*$]*")
try self.validate(self.metricNamespace, name: "metricNamespace", parent: name, max: 255)
try self.validate(self.metricNamespace, name: "metricNamespace", parent: name, pattern: "[^:*$]*")
try self.validate(self.metricValue, name: "metricValue", parent: name, max: 100)
}
private enum CodingKeys: String, CodingKey {
case defaultValue
case metricName
case metricNamespace
case metricValue
}
}
public struct OutputLogEvent: AWSDecodableShape {
/// The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let ingestionTime: Int64?
/// The data contained in the log event.
public let message: String?
/// The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let timestamp: Int64?
public init(ingestionTime: Int64? = nil, message: String? = nil, timestamp: Int64? = nil) {
self.ingestionTime = ingestionTime
self.message = message
self.timestamp = timestamp
}
private enum CodingKeys: String, CodingKey {
case ingestionTime
case message
case timestamp
}
}
public struct PutDestinationPolicyRequest: AWSEncodableShape {
/// An IAM policy document that authorizes cross-account users to deliver their log events to the associated destination. This can be up to 5120 bytes.
public let accessPolicy: String
/// A name for an existing destination.
public let destinationName: String
public init(accessPolicy: String, destinationName: String) {
self.accessPolicy = accessPolicy
self.destinationName = destinationName
}
public func validate(name: String) throws {
try self.validate(self.accessPolicy, name: "accessPolicy", parent: name, min: 1)
try self.validate(self.destinationName, name: "destinationName", parent: name, max: 512)
try self.validate(self.destinationName, name: "destinationName", parent: name, min: 1)
try self.validate(self.destinationName, name: "destinationName", parent: name, pattern: "[^:*]*")
}
private enum CodingKeys: String, CodingKey {
case accessPolicy
case destinationName
}
}
public struct PutDestinationRequest: AWSEncodableShape {
/// A name for the destination.
public let destinationName: String
/// The ARN of an IAM role that grants CloudWatch Logs permissions to call the Amazon Kinesis PutRecord operation on the destination stream.
public let roleArn: String
/// The ARN of an Amazon Kinesis stream to which to deliver matching log events.
public let targetArn: String
public init(destinationName: String, roleArn: String, targetArn: String) {
self.destinationName = destinationName
self.roleArn = roleArn
self.targetArn = targetArn
}
public func validate(name: String) throws {
try self.validate(self.destinationName, name: "destinationName", parent: name, max: 512)
try self.validate(self.destinationName, name: "destinationName", parent: name, min: 1)
try self.validate(self.destinationName, name: "destinationName", parent: name, pattern: "[^:*]*")
try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1)
try self.validate(self.targetArn, name: "targetArn", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case destinationName
case roleArn
case targetArn
}
}
public struct PutDestinationResponse: AWSDecodableShape {
/// The destination.
public let destination: Destination?
public init(destination: Destination? = nil) {
self.destination = destination
}
private enum CodingKeys: String, CodingKey {
case destination
}
}
public struct PutLogEventsRequest: AWSEncodableShape {
/// The log events.
public let logEvents: [InputLogEvent]
/// The name of the log group.
public let logGroupName: String
/// The name of the log stream.
public let logStreamName: String
/// The sequence token obtained from the response of the previous PutLogEvents call. An upload in a newly created log stream does not require a sequence token. You can also get the sequence token using DescribeLogStreams. If you call PutLogEvents twice within a narrow time period using the same value for sequenceToken, both calls might be successful or one might be rejected.
public let sequenceToken: String?
public init(logEvents: [InputLogEvent], logGroupName: String, logStreamName: String, sequenceToken: String? = nil) {
self.logEvents = logEvents
self.logGroupName = logGroupName
self.logStreamName = logStreamName
self.sequenceToken = sequenceToken
}
public func validate(name: String) throws {
try self.logEvents.forEach {
try $0.validate(name: "\(name).logEvents[]")
}
try self.validate(self.logEvents, name: "logEvents", parent: name, max: 10000)
try self.validate(self.logEvents, name: "logEvents", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.logStreamName, name: "logStreamName", parent: name, max: 512)
try self.validate(self.logStreamName, name: "logStreamName", parent: name, min: 1)
try self.validate(self.logStreamName, name: "logStreamName", parent: name, pattern: "[^:*]*")
try self.validate(self.sequenceToken, name: "sequenceToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case logEvents
case logGroupName
case logStreamName
case sequenceToken
}
}
public struct PutLogEventsResponse: AWSDecodableShape {
/// The next sequence token.
public let nextSequenceToken: String?
/// The rejected events.
public let rejectedLogEventsInfo: RejectedLogEventsInfo?
public init(nextSequenceToken: String? = nil, rejectedLogEventsInfo: RejectedLogEventsInfo? = nil) {
self.nextSequenceToken = nextSequenceToken
self.rejectedLogEventsInfo = rejectedLogEventsInfo
}
private enum CodingKeys: String, CodingKey {
case nextSequenceToken
case rejectedLogEventsInfo
}
}
public struct PutMetricFilterRequest: AWSEncodableShape {
/// A name for the metric filter.
public let filterName: String
/// A filter pattern for extracting metric data out of ingested log events.
public let filterPattern: String
/// The name of the log group.
public let logGroupName: String
/// A collection of information that defines how metric data gets emitted.
public let metricTransformations: [MetricTransformation]
public init(filterName: String, filterPattern: String, logGroupName: String, metricTransformations: [MetricTransformation]) {
self.filterName = filterName
self.filterPattern = filterPattern
self.logGroupName = logGroupName
self.metricTransformations = metricTransformations
}
public func validate(name: String) throws {
try self.validate(self.filterName, name: "filterName", parent: name, max: 512)
try self.validate(self.filterName, name: "filterName", parent: name, min: 1)
try self.validate(self.filterName, name: "filterName", parent: name, pattern: "[^:*]*")
try self.validate(self.filterPattern, name: "filterPattern", parent: name, max: 1024)
try self.validate(self.filterPattern, name: "filterPattern", parent: name, min: 0)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.metricTransformations.forEach {
try $0.validate(name: "\(name).metricTransformations[]")
}
try self.validate(self.metricTransformations, name: "metricTransformations", parent: name, max: 1)
try self.validate(self.metricTransformations, name: "metricTransformations", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case filterName
case filterPattern
case logGroupName
case metricTransformations
}
}
public struct PutQueryDefinitionRequest: AWSEncodableShape {
/// Use this parameter to include specific log groups as part of your query definition. If you are updating a query definition and you omit this parameter, then the updated definition will contain no log groups.
public let logGroupNames: [String]?
/// A name for the query definition. If you are saving a lot of query definitions, we recommend that you name them so that you can easily find the ones you want by using the first part of the name as a filter in the queryDefinitionNamePrefix parameter of DescribeQueryDefinitions.
public let name: String
/// If you are updating a query definition, use this parameter to specify the ID of the query definition that you want to update. You can use DescribeQueryDefinitions to retrieve the IDs of your saved query definitions. If you are creating a query definition, do not specify this parameter. CloudWatch generates a unique ID for the new query definition and include it in the response to this operation.
public let queryDefinitionId: String?
/// The query string to use for this definition. For more information, see CloudWatch Logs Insights Query Syntax.
public let queryString: String
public init(logGroupNames: [String]? = nil, name: String, queryDefinitionId: String? = nil, queryString: String) {
self.logGroupNames = logGroupNames
self.name = name
self.queryDefinitionId = queryDefinitionId
self.queryString = queryString
}
public func validate(name: String) throws {
try self.logGroupNames?.forEach {
try validate($0, name: "logGroupNames[]", parent: name, max: 512)
try validate($0, name: "logGroupNames[]", parent: name, min: 1)
try validate($0, name: "logGroupNames[]", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
}
try self.validate(self.name, name: "name", parent: name, max: 255)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "^([^:*\\/]+\\/?)*[^:*\\/]+$")
try self.validate(self.queryDefinitionId, name: "queryDefinitionId", parent: name, max: 256)
try self.validate(self.queryDefinitionId, name: "queryDefinitionId", parent: name, min: 0)
try self.validate(self.queryString, name: "queryString", parent: name, max: 10000)
try self.validate(self.queryString, name: "queryString", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case logGroupNames
case name
case queryDefinitionId
case queryString
}
}
public struct PutQueryDefinitionResponse: AWSDecodableShape {
/// The ID of the query definition.
public let queryDefinitionId: String?
public init(queryDefinitionId: String? = nil) {
self.queryDefinitionId = queryDefinitionId
}
private enum CodingKeys: String, CodingKey {
case queryDefinitionId
}
}
public struct PutResourcePolicyRequest: AWSEncodableShape {
/// Details of the new policy, including the identity of the principal that is enabled to put logs to this account. This is formatted as a JSON string. This parameter is required. The following example creates a resource policy enabling the Route 53 service to put DNS query logs in to the specified log group. Replace "logArn" with the ARN of your CloudWatch Logs resource, such as a log group or log stream. { "Version": "2012-10-17", "Statement": [ { "Sid": "Route53LogsToCloudWatchLogs", "Effect": "Allow", "Principal": { "Service": [ "route53.amazonaws.com" ] }, "Action":"logs:PutLogEvents", "Resource": "logArn" } ] }
public let policyDocument: String?
/// Name of the new policy. This parameter is required.
public let policyName: String?
public init(policyDocument: String? = nil, policyName: String? = nil) {
self.policyDocument = policyDocument
self.policyName = policyName
}
public func validate(name: String) throws {
try self.validate(self.policyDocument, name: "policyDocument", parent: name, max: 5120)
try self.validate(self.policyDocument, name: "policyDocument", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case policyDocument
case policyName
}
}
public struct PutResourcePolicyResponse: AWSDecodableShape {
/// The new policy.
public let resourcePolicy: ResourcePolicy?
public init(resourcePolicy: ResourcePolicy? = nil) {
self.resourcePolicy = resourcePolicy
}
private enum CodingKeys: String, CodingKey {
case resourcePolicy
}
}
public struct PutRetentionPolicyRequest: AWSEncodableShape {
/// The name of the log group.
public let logGroupName: String
public let retentionInDays: Int
public init(logGroupName: String, retentionInDays: Int) {
self.logGroupName = logGroupName
self.retentionInDays = retentionInDays
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
}
private enum CodingKeys: String, CodingKey {
case logGroupName
case retentionInDays
}
}
public struct PutSubscriptionFilterRequest: AWSEncodableShape {
/// The ARN of the destination to deliver matching log events to. Currently, the supported destinations are: An Amazon Kinesis stream belonging to the same account as the subscription filter, for same-account delivery. A logical destination (specified using an ARN) belonging to a different account, for cross-account delivery. An Amazon Kinesis Firehose delivery stream belonging to the same account as the subscription filter, for same-account delivery. An AWS Lambda function belonging to the same account as the subscription filter, for same-account delivery.
public let destinationArn: String
/// The method used to distribute log data to the destination. By default, log data is grouped by log stream, but the grouping can be set to random for a more even distribution. This property is only applicable when the destination is an Amazon Kinesis stream.
public let distribution: Distribution?
/// A name for the subscription filter. If you are updating an existing filter, you must specify the correct name in filterName. Otherwise, the call fails because you cannot associate a second filter with a log group. To find the name of the filter currently associated with a log group, use DescribeSubscriptionFilters.
public let filterName: String
/// A filter pattern for subscribing to a filtered stream of log events.
public let filterPattern: String
/// The name of the log group.
public let logGroupName: String
/// The ARN of an IAM role that grants CloudWatch Logs permissions to deliver ingested log events to the destination stream. You don't need to provide the ARN when you are working with a logical destination for cross-account delivery.
public let roleArn: String?
public init(destinationArn: String, distribution: Distribution? = nil, filterName: String, filterPattern: String, logGroupName: String, roleArn: String? = nil) {
self.destinationArn = destinationArn
self.distribution = distribution
self.filterName = filterName
self.filterPattern = filterPattern
self.logGroupName = logGroupName
self.roleArn = roleArn
}
public func validate(name: String) throws {
try self.validate(self.destinationArn, name: "destinationArn", parent: name, min: 1)
try self.validate(self.filterName, name: "filterName", parent: name, max: 512)
try self.validate(self.filterName, name: "filterName", parent: name, min: 1)
try self.validate(self.filterName, name: "filterName", parent: name, pattern: "[^:*]*")
try self.validate(self.filterPattern, name: "filterPattern", parent: name, max: 1024)
try self.validate(self.filterPattern, name: "filterPattern", parent: name, min: 0)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case destinationArn
case distribution
case filterName
case filterPattern
case logGroupName
case roleArn
}
}
public struct QueryDefinition: AWSDecodableShape {
/// The date that the query definition was most recently modified.
public let lastModified: Int64?
/// If this query definition contains a list of log groups that it is limited to, that list appears here.
public let logGroupNames: [String]?
/// The name of the query definition.
public let name: String?
/// The unique ID of the query definition.
public let queryDefinitionId: String?
/// The query string to use for this definition. For more information, see CloudWatch Logs Insights Query Syntax.
public let queryString: String?
public init(lastModified: Int64? = nil, logGroupNames: [String]? = nil, name: String? = nil, queryDefinitionId: String? = nil, queryString: String? = nil) {
self.lastModified = lastModified
self.logGroupNames = logGroupNames
self.name = name
self.queryDefinitionId = queryDefinitionId
self.queryString = queryString
}
private enum CodingKeys: String, CodingKey {
case lastModified
case logGroupNames
case name
case queryDefinitionId
case queryString
}
}
public struct QueryInfo: AWSDecodableShape {
/// The date and time that this query was created.
public let createTime: Int64?
/// The name of the log group scanned by this query.
public let logGroupName: String?
/// The unique ID number of this query.
public let queryId: String?
/// The query string used in this query.
public let queryString: String?
/// The status of this query. Possible values are Cancelled, Complete, Failed, Running, Scheduled, and Unknown.
public let status: QueryStatus?
public init(createTime: Int64? = nil, logGroupName: String? = nil, queryId: String? = nil, queryString: String? = nil, status: QueryStatus? = nil) {
self.createTime = createTime
self.logGroupName = logGroupName
self.queryId = queryId
self.queryString = queryString
self.status = status
}
private enum CodingKeys: String, CodingKey {
case createTime
case logGroupName
case queryId
case queryString
case status
}
}
public struct QueryStatistics: AWSDecodableShape {
/// The total number of bytes in the log events scanned during the query.
public let bytesScanned: Double?
/// The number of log events that matched the query string.
public let recordsMatched: Double?
/// The total number of log events scanned during the query.
public let recordsScanned: Double?
public init(bytesScanned: Double? = nil, recordsMatched: Double? = nil, recordsScanned: Double? = nil) {
self.bytesScanned = bytesScanned
self.recordsMatched = recordsMatched
self.recordsScanned = recordsScanned
}
private enum CodingKeys: String, CodingKey {
case bytesScanned
case recordsMatched
case recordsScanned
}
}
public struct RejectedLogEventsInfo: AWSDecodableShape {
/// The expired log events.
public let expiredLogEventEndIndex: Int?
/// The log events that are too new.
public let tooNewLogEventStartIndex: Int?
/// The log events that are too old.
public let tooOldLogEventEndIndex: Int?
public init(expiredLogEventEndIndex: Int? = nil, tooNewLogEventStartIndex: Int? = nil, tooOldLogEventEndIndex: Int? = nil) {
self.expiredLogEventEndIndex = expiredLogEventEndIndex
self.tooNewLogEventStartIndex = tooNewLogEventStartIndex
self.tooOldLogEventEndIndex = tooOldLogEventEndIndex
}
private enum CodingKeys: String, CodingKey {
case expiredLogEventEndIndex
case tooNewLogEventStartIndex
case tooOldLogEventEndIndex
}
}
public struct ResourcePolicy: AWSDecodableShape {
/// Timestamp showing when this policy was last updated, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let lastUpdatedTime: Int64?
/// The details of the policy.
public let policyDocument: String?
/// The name of the resource policy.
public let policyName: String?
public init(lastUpdatedTime: Int64? = nil, policyDocument: String? = nil, policyName: String? = nil) {
self.lastUpdatedTime = lastUpdatedTime
self.policyDocument = policyDocument
self.policyName = policyName
}
private enum CodingKeys: String, CodingKey {
case lastUpdatedTime
case policyDocument
case policyName
}
}
public struct ResultField: AWSDecodableShape {
/// The log event field.
public let field: String?
/// The value of this field.
public let value: String?
public init(field: String? = nil, value: String? = nil) {
self.field = field
self.value = value
}
private enum CodingKeys: String, CodingKey {
case field
case value
}
}
public struct SearchedLogStream: AWSDecodableShape {
/// The name of the log stream.
public let logStreamName: String?
/// Indicates whether all the events in this log stream were searched.
public let searchedCompletely: Bool?
public init(logStreamName: String? = nil, searchedCompletely: Bool? = nil) {
self.logStreamName = logStreamName
self.searchedCompletely = searchedCompletely
}
private enum CodingKeys: String, CodingKey {
case logStreamName
case searchedCompletely
}
}
public struct StartQueryRequest: AWSEncodableShape {
/// The end of the time range to query. The range is inclusive, so the specified end time is included in the query. Specified as epoch time, the number of seconds since January 1, 1970, 00:00:00 UTC.
public let endTime: Int64
/// The maximum number of log events to return in the query. If the query string uses the fields command, only the specified fields and their values are returned. The default is 1000.
public let limit: Int?
/// The log group on which to perform the query. A StartQuery operation must include a logGroupNames or a logGroupName parameter, but not both.
public let logGroupName: String?
/// The list of log groups to be queried. You can include up to 20 log groups. A StartQuery operation must include a logGroupNames or a logGroupName parameter, but not both.
public let logGroupNames: [String]?
/// The query string to use. For more information, see CloudWatch Logs Insights Query Syntax.
public let queryString: String
/// The beginning of the time range to query. The range is inclusive, so the specified start time is included in the query. Specified as epoch time, the number of seconds since January 1, 1970, 00:00:00 UTC.
public let startTime: Int64
public init(endTime: Int64, limit: Int? = nil, logGroupName: String? = nil, logGroupNames: [String]? = nil, queryString: String, startTime: Int64) {
self.endTime = endTime
self.limit = limit
self.logGroupName = logGroupName
self.logGroupNames = logGroupNames
self.queryString = queryString
self.startTime = startTime
}
public func validate(name: String) throws {
try self.validate(self.endTime, name: "endTime", parent: name, min: 0)
try self.validate(self.limit, name: "limit", parent: name, max: 10000)
try self.validate(self.limit, name: "limit", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.logGroupNames?.forEach {
try validate($0, name: "logGroupNames[]", parent: name, max: 512)
try validate($0, name: "logGroupNames[]", parent: name, min: 1)
try validate($0, name: "logGroupNames[]", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
}
try self.validate(self.queryString, name: "queryString", parent: name, max: 10000)
try self.validate(self.queryString, name: "queryString", parent: name, min: 0)
try self.validate(self.startTime, name: "startTime", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case endTime
case limit
case logGroupName
case logGroupNames
case queryString
case startTime
}
}
public struct StartQueryResponse: AWSDecodableShape {
/// The unique ID of the query.
public let queryId: String?
public init(queryId: String? = nil) {
self.queryId = queryId
}
private enum CodingKeys: String, CodingKey {
case queryId
}
}
public struct StopQueryRequest: AWSEncodableShape {
/// The ID number of the query to stop. To find this ID number, use DescribeQueries.
public let queryId: String
public init(queryId: String) {
self.queryId = queryId
}
public func validate(name: String) throws {
try self.validate(self.queryId, name: "queryId", parent: name, max: 256)
try self.validate(self.queryId, name: "queryId", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case queryId
}
}
public struct StopQueryResponse: AWSDecodableShape {
/// This is true if the query was stopped by the StopQuery operation.
public let success: Bool?
public init(success: Bool? = nil) {
self.success = success
}
private enum CodingKeys: String, CodingKey {
case success
}
}
public struct SubscriptionFilter: AWSDecodableShape {
/// The creation time of the subscription filter, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
public let creationTime: Int64?
/// The Amazon Resource Name (ARN) of the destination.
public let destinationArn: String?
public let distribution: Distribution?
/// The name of the subscription filter.
public let filterName: String?
public let filterPattern: String?
/// The name of the log group.
public let logGroupName: String?
public let roleArn: String?
public init(creationTime: Int64? = nil, destinationArn: String? = nil, distribution: Distribution? = nil, filterName: String? = nil, filterPattern: String? = nil, logGroupName: String? = nil, roleArn: String? = nil) {
self.creationTime = creationTime
self.destinationArn = destinationArn
self.distribution = distribution
self.filterName = filterName
self.filterPattern = filterPattern
self.logGroupName = logGroupName
self.roleArn = roleArn
}
private enum CodingKeys: String, CodingKey {
case creationTime
case destinationArn
case distribution
case filterName
case filterPattern
case logGroupName
case roleArn
}
}
public struct TagLogGroupRequest: AWSEncodableShape {
/// The name of the log group.
public let logGroupName: String
/// The key-value pairs to use for the tags.
public let tags: [String: String]
public init(logGroupName: String, tags: [String: String]) {
self.logGroupName = logGroupName
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.tags.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.key, name: "tags.key", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+)$")
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
}
}
private enum CodingKeys: String, CodingKey {
case logGroupName
case tags
}
}
public struct TestMetricFilterRequest: AWSEncodableShape {
public let filterPattern: String
/// The log event messages to test.
public let logEventMessages: [String]
public init(filterPattern: String, logEventMessages: [String]) {
self.filterPattern = filterPattern
self.logEventMessages = logEventMessages
}
public func validate(name: String) throws {
try self.validate(self.filterPattern, name: "filterPattern", parent: name, max: 1024)
try self.validate(self.filterPattern, name: "filterPattern", parent: name, min: 0)
try self.logEventMessages.forEach {
try validate($0, name: "logEventMessages[]", parent: name, min: 1)
}
try self.validate(self.logEventMessages, name: "logEventMessages", parent: name, max: 50)
try self.validate(self.logEventMessages, name: "logEventMessages", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case filterPattern
case logEventMessages
}
}
public struct TestMetricFilterResponse: AWSDecodableShape {
/// The matched events.
public let matches: [MetricFilterMatchRecord]?
public init(matches: [MetricFilterMatchRecord]? = nil) {
self.matches = matches
}
private enum CodingKeys: String, CodingKey {
case matches
}
}
public struct UntagLogGroupRequest: AWSEncodableShape {
/// The name of the log group.
public let logGroupName: String
/// The tag keys. The corresponding tags are removed from the log group.
public let tags: [String]
public init(logGroupName: String, tags: [String]) {
self.logGroupName = logGroupName
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.logGroupName, name: "logGroupName", parent: name, max: 512)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, min: 1)
try self.validate(self.logGroupName, name: "logGroupName", parent: name, pattern: "[\\.\\-_/#A-Za-z0-9]+")
try self.tags.forEach {
try validate($0, name: "tags[]", parent: name, max: 128)
try validate($0, name: "tags[]", parent: name, min: 1)
try validate($0, name: "tags[]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+)$")
}
try self.validate(self.tags, name: "tags", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case logGroupName
case tags
}
}
}
| apache-2.0 | e9e47f1d002ed62da4d88f194a9b9d4c | 45.844665 | 645 | 0.635839 | 4.730472 | false | false | false | false |
LawrenceHan/iOS-project-playground | iOSRACSwift/Pods/ReactiveCocoa/ReactiveCocoa/Swift/SignalProducer.swift | 25 | 53050 | import Result
/// A SignalProducer creates Signals that can produce values of type `Value` and/or
/// fail with errors of type `Error`. If no failure should be possible, NoError
/// can be specified for `Error`.
///
/// SignalProducers can be used to represent operations or tasks, like network
/// requests, where each invocation of start() will create a new underlying
/// operation. This ensures that consumers will receive the results, versus a
/// plain Signal, where the results might be sent before any observers are
/// attached.
///
/// Because of the behavior of start(), different Signals created from the
/// producer may see a different version of Events. The Events may arrive in a
/// different order between Signals, or the stream might be completely
/// different!
public struct SignalProducer<Value, Error: ErrorType> {
public typealias ProducedSignal = Signal<Value, Error>
private let startHandler: (Signal<Value, Error>.Observer, CompositeDisposable) -> ()
/// Initializes a SignalProducer that will emit the same events as the given signal.
///
/// If the Disposable returned from start() is disposed or a terminating
/// event is sent to the observer, the given signal will be
/// disposed.
public init<S: SignalType where S.Value == Value, S.Error == Error>(signal: S) {
self.init { observer, disposable in
disposable += signal.observe(observer)
}
}
/// Initializes a SignalProducer that will invoke the given closure once
/// for each invocation of start().
///
/// The events that the closure puts into the given observer will become
/// the events sent by the started Signal to its observers.
///
/// If the Disposable returned from start() is disposed or a terminating
/// event is sent to the observer, the given CompositeDisposable will be
/// disposed, at which point work should be interrupted and any temporary
/// resources cleaned up.
public init(_ startHandler: (Signal<Value, Error>.Observer, CompositeDisposable) -> ()) {
self.startHandler = startHandler
}
/// Creates a producer for a Signal that will immediately send one value
/// then complete.
public init(value: Value) {
self.init { observer, disposable in
observer.sendNext(value)
observer.sendCompleted()
}
}
/// Creates a producer for a Signal that will immediately fail with the
/// given error.
public init(error: Error) {
self.init { observer, disposable in
observer.sendFailed(error)
}
}
/// Creates a producer for a Signal that will immediately send one value
/// then complete, or immediately fail, depending on the given Result.
public init(result: Result<Value, Error>) {
switch result {
case let .Success(value):
self.init(value: value)
case let .Failure(error):
self.init(error: error)
}
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
public init<S: SequenceType where S.Generator.Element == Value>(values: S) {
self.init { observer, disposable in
for value in values {
observer.sendNext(value)
if disposable.disposed {
break
}
}
observer.sendCompleted()
}
}
/// A producer for a Signal that will immediately complete without sending
/// any values.
public static var empty: SignalProducer {
return self.init { observer, disposable in
observer.sendCompleted()
}
}
/// A producer for a Signal that never sends any events to its observers.
public static var never: SignalProducer {
return self.init { _ in return }
}
/// Creates a queue for events that replays them when new signals are
/// created from the returned producer.
///
/// When values are put into the returned observer (observer), they will be
/// added to an internal buffer. If the buffer is already at capacity,
/// the earliest (oldest) value will be dropped to make room for the new
/// value.
///
/// Signals created from the returned producer will stay alive until a
/// terminating event is added to the queue. If the queue does not contain
/// such an event when the Signal is started, all values sent to the
/// returned observer will be automatically forwarded to the Signal’s
/// observers until a terminating event is received.
///
/// After a terminating event has been added to the queue, the observer
/// will not add any further events. This _does not_ count against the
/// value capacity so no buffered values will be dropped on termination.
public static func buffer(capacity: Int = Int.max) -> (SignalProducer, Signal<Value, Error>.Observer) {
precondition(capacity >= 0)
// This is effectively used as a synchronous mutex, but permitting
// limited recursive locking (see below).
//
// The queue is a "variable" just so we can use its address as the key
// and the value for dispatch_queue_set_specific().
var queue = dispatch_queue_create("org.reactivecocoa.ReactiveCocoa.SignalProducer.buffer", DISPATCH_QUEUE_SERIAL)
dispatch_queue_set_specific(queue, &queue, &queue, nil)
// Used as an atomic variable so we can remove observers without needing
// to run on the queue.
let state: Atomic<BufferState<Value, Error>> = Atomic(BufferState())
let producer = self.init { observer, disposable in
// Assigned to when replay() is invoked synchronously below.
var token: RemovalToken?
let replay: () -> () = {
let originalState = state.modify { (var state) in
token = state.observers?.insert(observer)
return state
}
for value in originalState.values {
observer.sendNext(value)
}
if let terminationEvent = originalState.terminationEvent {
observer.action(terminationEvent)
}
}
// Prevent other threads from sending events while we're replaying,
// but don't deadlock if we're replaying in response to a buffer
// event observed elsewhere.
//
// In other words, this permits limited signal recursion for the
// specific case of replaying past events.
if dispatch_get_specific(&queue) != nil {
replay()
} else {
dispatch_sync(queue, replay)
}
if let token = token {
disposable.addDisposable {
state.modify { (var state) in
state.observers?.removeValueForToken(token)
return state
}
}
}
}
let bufferingObserver: Signal<Value, Error>.Observer = Observer { event in
// Send serially with respect to other senders, and never while
// another thread is in the process of replaying.
dispatch_sync(queue) {
let originalState = state.modify { (var state) in
if let value = event.value {
state.addValue(value, upToCapacity: capacity)
} else {
// Disconnect all observers and prevent future
// attachments.
state.terminationEvent = event
state.observers = nil
}
return state
}
if let observers = originalState.observers {
for observer in observers {
observer.action(event)
}
}
}
}
return (producer, bufferingObserver)
}
/// Creates a SignalProducer that will attempt the given operation once for
/// each invocation of start().
///
/// Upon success, the started signal will send the resulting value then
/// complete. Upon failure, the started signal will fail with the error that
/// occurred.
public static func attempt(operation: () -> Result<Value, Error>) -> SignalProducer {
return self.init { observer, disposable in
operation().analysis(ifSuccess: { value in
observer.sendNext(value)
observer.sendCompleted()
}, ifFailure: { error in
observer.sendFailed(error)
})
}
}
/// Creates a Signal from the producer, passes it into the given closure,
/// then starts sending events on the Signal when the closure has returned.
///
/// The closure will also receive a disposable which can be used to
/// interrupt the work associated with the signal and immediately send an
/// `Interrupted` event.
public func startWithSignal(@noescape setUp: (Signal<Value, Error>, Disposable) -> ()) {
let (signal, observer) = Signal<Value, Error>.pipe()
// Disposes of the work associated with the SignalProducer and any
// upstream producers.
let producerDisposable = CompositeDisposable()
// Directly disposed of when start() or startWithSignal() is disposed.
let cancelDisposable = ActionDisposable {
observer.sendInterrupted()
producerDisposable.dispose()
}
setUp(signal, cancelDisposable)
if cancelDisposable.disposed {
return
}
let wrapperObserver: Signal<Value, Error>.Observer = Observer { event in
observer.action(event)
if event.isTerminating {
// Dispose only after notifying the Signal, so disposal
// logic is consistently the last thing to run.
producerDisposable.dispose()
}
}
startHandler(wrapperObserver, producerDisposable)
}
}
private struct BufferState<Value, Error: ErrorType> {
// All values in the buffer.
var values: [Value] = []
// Any terminating event sent to the buffer.
//
// This will be nil if termination has not occurred.
var terminationEvent: Event<Value, Error>?
// The observers currently attached to the buffered producer, or nil if the
// producer was terminated.
var observers: Bag<Signal<Value, Error>.Observer>? = Bag()
// Appends a new value to the buffer, trimming it down to the given capacity
// if necessary.
mutating func addValue(value: Value, upToCapacity capacity: Int) {
values.append(value)
let overflow = values.count - capacity
if overflow > 0 {
values.removeRange(0..<overflow)
}
}
}
public protocol SignalProducerType {
/// The type of values being sent on the producer
typealias Value
/// The type of error that can occur on the producer. If errors aren't possible
/// then `NoError` can be used.
typealias Error: ErrorType
/// Extracts a signal producer from the receiver.
var producer: SignalProducer<Value, Error> { get }
/// Creates a Signal from the producer, passes it into the given closure,
/// then starts sending events on the Signal when the closure has returned.
func startWithSignal(@noescape setUp: (Signal<Value, Error>, Disposable) -> ())
}
extension SignalProducer: SignalProducerType {
public var producer: SignalProducer {
return self
}
}
extension SignalProducerType {
/// Creates a Signal from the producer, then attaches the given observer to
/// the Signal as an observer.
///
/// Returns a Disposable which can be used to interrupt the work associated
/// with the signal and immediately send an `Interrupted` event.
public func start(observer: Signal<Value, Error>.Observer = Signal<Value, Error>.Observer()) -> Disposable {
var disposable: Disposable!
startWithSignal { signal, innerDisposable in
signal.observe(observer)
disposable = innerDisposable
}
return disposable
}
/// Convenience override for start(_:) to allow trailing-closure style
/// invocations.
public func start(observerAction: Signal<Value, Error>.Observer.Action) -> Disposable {
return start(Observer(observerAction))
}
/// Creates a Signal from the producer, then adds exactly one observer to
/// the Signal, which will invoke the given callback when `next` events are
/// received.
///
/// Returns a Disposable which can be used to interrupt the work associated
/// with the Signal, and prevent any future callbacks from being invoked.
public func startWithNext(next: Value -> ()) -> Disposable {
return start(Observer(next: next))
}
/// Creates a Signal from the producer, then adds exactly one observer to
/// the Signal, which will invoke the given callback when a `completed` event is
/// received.
///
/// Returns a Disposable which can be used to interrupt the work associated
/// with the Signal.
public func startWithCompleted(completed: () -> ()) -> Disposable {
return start(Observer(completed: completed))
}
/// Creates a Signal from the producer, then adds exactly one observer to
/// the Signal, which will invoke the given callback when a `failed` event is
/// received.
///
/// Returns a Disposable which can be used to interrupt the work associated
/// with the Signal.
public func startWithFailed(failed: Error -> ()) -> Disposable {
return start(Observer(failed: failed))
}
/// Creates a Signal from the producer, then adds exactly one observer to
/// the Signal, which will invoke the given callback when an `interrupted` event is
/// received.
///
/// Returns a Disposable which can be used to interrupt the work associated
/// with the Signal.
public func startWithInterrupted(interrupted: () -> ()) -> Disposable {
return start(Observer(interrupted: interrupted))
}
/// Lifts an unary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new SignalProducer which will apply
/// the given Signal operator to _every_ created Signal, just as if the
/// operator had been applied to each Signal yielded from start().
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func lift<U, F>(transform: Signal<Value, Error> -> Signal<U, F>) -> SignalProducer<U, F> {
return SignalProducer { observer, outerDisposable in
self.startWithSignal { signal, innerDisposable in
outerDisposable.addDisposable(innerDisposable)
transform(signal).observe(observer)
}
}
}
/// Lifts a binary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new SignalProducer which will apply
/// the given Signal operator to _every_ Signal created from the two
/// producers, just as if the operator had been applied to each Signal
/// yielded from start().
///
/// Note: starting the returned producer will start the receiver of the operator,
/// which may not be adviseable for some operators.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func lift<U, F, V, G>(transform: Signal<Value, Error> -> Signal<U, F> -> Signal<V, G>) -> SignalProducer<U, F> -> SignalProducer<V, G> {
return liftRight(transform)
}
/// Right-associative lifting of a binary signal operator over producers. That
/// is, the argument producer will be started before the receiver. When both
/// producers are synchronous this order can be important depending on the operator
/// to generate correct results.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
private func liftRight<U, F, V, G>(transform: Signal<Value, Error> -> Signal<U, F> -> Signal<V, G>) -> SignalProducer<U, F> -> SignalProducer<V, G> {
return { otherProducer in
return SignalProducer { observer, outerDisposable in
self.startWithSignal { signal, disposable in
outerDisposable.addDisposable(disposable)
otherProducer.startWithSignal { otherSignal, otherDisposable in
outerDisposable.addDisposable(otherDisposable)
transform(signal)(otherSignal).observe(observer)
}
}
}
}
}
/// Left-associative lifting of a binary signal operator over producers. That
/// is, the receiver will be started before the argument producer. When both
/// producers are synchronous this order can be important depending on the operator
/// to generate correct results.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
private func liftLeft<U, F, V, G>(transform: Signal<Value, Error> -> Signal<U, F> -> Signal<V, G>) -> SignalProducer<U, F> -> SignalProducer<V, G> {
return { otherProducer in
return SignalProducer { observer, outerDisposable in
otherProducer.startWithSignal { otherSignal, otherDisposable in
outerDisposable.addDisposable(otherDisposable)
self.startWithSignal { signal, disposable in
outerDisposable.addDisposable(disposable)
transform(signal)(otherSignal).observe(observer)
}
}
}
}
}
/// Lifts a binary Signal operator to operate upon a Signal and a SignalProducer instead.
///
/// In other words, this will create a new SignalProducer which will apply
/// the given Signal operator to _every_ Signal created from the two
/// producers, just as if the operator had been applied to each Signal
/// yielded from start().
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func lift<U, F, V, G>(transform: Signal<Value, Error> -> Signal<U, F> -> Signal<V, G>) -> Signal<U, F> -> SignalProducer<V, G> {
return { otherSignal in
return SignalProducer { observer, outerDisposable in
self.startWithSignal { signal, disposable in
outerDisposable += disposable
outerDisposable += transform(signal)(otherSignal).observe(observer)
}
}
}
}
/// Maps each value in the producer to a new value.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func map<U>(transform: Value -> U) -> SignalProducer<U, Error> {
return lift { $0.map(transform) }
}
/// Maps errors in the producer to a new error.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func mapError<F>(transform: Error -> F) -> SignalProducer<Value, F> {
return lift { $0.mapError(transform) }
}
/// Preserves only the values of the producer that pass the given predicate.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func filter(predicate: Value -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.filter(predicate) }
}
/// Returns a producer that will yield the first `count` values from the
/// input producer.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func take(count: Int) -> SignalProducer<Value, Error> {
return lift { $0.take(count) }
}
/// Returns a signal that will yield an array of values when `signal` completes.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func collect() -> SignalProducer<[Value], Error> {
return lift { $0.collect() }
}
/// Forwards all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func observeOn(scheduler: SchedulerType) -> SignalProducer<Value, Error> {
return lift { $0.observeOn(scheduler) }
}
/// Combines the latest value of the receiver with the latest value from
/// the given producer.
///
/// The returned producer will not send a value until both inputs have sent at
/// least one value each. If either producer is interrupted, the returned producer
/// will also be interrupted.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatestWith<U>(otherProducer: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
return liftRight(Signal.combineLatestWith)(otherProducer)
}
/// Combines the latest value of the receiver with the latest value from
/// the given signal.
///
/// The returned producer will not send a value until both inputs have sent at
/// least one value each. If either input is interrupted, the returned producer
/// will also be interrupted.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatestWith<U>(otherSignal: Signal<U, Error>) -> SignalProducer<(Value, U), Error> {
return lift(Signal.combineLatestWith)(otherSignal)
}
/// Delays `Next` and `Completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// `Failed` and `Interrupted` events are always scheduled immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func delay(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<Value, Error> {
return lift { $0.delay(interval, onScheduler: scheduler) }
}
/// Returns a producer that will skip the first `count` values, then forward
/// everything afterward.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func skip(count: Int) -> SignalProducer<Value, Error> {
return lift { $0.skip(count) }
}
/// Treats all Events from the input producer as plain values, allowing them to be
/// manipulated just like any other value.
///
/// In other words, this brings Events “into the monad.”
///
/// When a Completed or Failed event is received, the resulting producer will send
/// the Event itself and then complete. When an Interrupted event is received,
/// the resulting producer will send the Event itself and then interrupt.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func materialize() -> SignalProducer<Event<Value, Error>, NoError> {
return lift { $0.materialize() }
}
/// Forwards the latest value from `self` whenever `sampler` sends a Next
/// event.
///
/// If `sampler` fires before a value has been observed on `self`, nothing
/// happens.
///
/// Returns a producer that will send values from `self`, sampled (possibly
/// multiple times) by `sampler`, then complete once both input producers have
/// completed, or interrupt if either input producer is interrupted.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func sampleOn(sampler: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
return liftLeft(Signal.sampleOn)(sampler)
}
/// Forwards the latest value from `self` whenever `sampler` sends a Next
/// event.
///
/// If `sampler` fires before a value has been observed on `self`, nothing
/// happens.
///
/// Returns a producer that will send values from `self`, sampled (possibly
/// multiple times) by `sampler`, then complete once both inputs have
/// completed, or interrupt if either input is interrupted.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func sampleOn(sampler: Signal<(), NoError>) -> SignalProducer<Value, Error> {
return lift(Signal.sampleOn)(sampler)
}
/// Forwards events from `self` until `trigger` sends a Next or Completed
/// event, at which point the returned producer will complete.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func takeUntil(trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
return liftRight(Signal.takeUntil)(trigger)
}
/// Forwards events from `self` until `trigger` sends a Next or Completed
/// event, at which point the returned producer will complete.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func takeUntil(trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> {
return lift(Signal.takeUntil)(trigger)
}
/// Does not forward any values from `self` until `trigger` sends a Next or
/// Completed, at which point the returned signal behaves exactly like `signal`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func skipUntil(trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
return liftRight(Signal.skipUntil)(trigger)
}
/// Does not forward any values from `self` until `trigger` sends a Next or
/// Completed, at which point the returned signal behaves exactly like `signal`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func skipUntil(trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> {
return lift(Signal.skipUntil)(trigger)
}
/// Forwards events from `self` with history: values of the returned producer
/// are a tuple whose first member is the previous value and whose second member
/// is the current value. `initial` is supplied as the first member when `self`
/// sends its first value.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combinePrevious(initial: Value) -> SignalProducer<(Value, Value), Error> {
return lift { $0.combinePrevious(initial) }
}
/// Like `scan`, but sends only the final value and then immediately completes.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func reduce<U>(initial: U, _ combine: (U, Value) -> U) -> SignalProducer<U, Error> {
return lift { $0.reduce(initial, combine) }
}
/// Aggregates `self`'s values into a single combined value. When `self` emits
/// its first value, `combine` is invoked with `initial` as the first argument and
/// that emitted value as the second argument. The result is emitted from the
/// producer returned from `scan`. That result is then passed to `combine` as the
/// first argument when the next value is emitted, and so on.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func scan<U>(initial: U, _ combine: (U, Value) -> U) -> SignalProducer<U, Error> {
return lift { $0.scan(initial, combine) }
}
/// Forwards only those values from `self` which do not pass `isRepeat` with
/// respect to the previous value. The first value is always forwarded.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func skipRepeats(isRepeat: (Value, Value) -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.skipRepeats(isRepeat) }
}
/// Does not forward any values from `self` until `predicate` returns false,
/// at which point the returned signal behaves exactly like `self`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func skipWhile(predicate: Value -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.skipWhile(predicate) }
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// Returns a producer which passes through `Next`, `Failed`, and `Interrupted`
/// events from `self` until `replacement` sends an event, at which point the
/// returned producer will send that event and switch to passing through events
/// from `replacement` instead, regardless of whether `self` has sent events
/// already.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func takeUntilReplacement(replacement: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return liftRight(Signal.takeUntilReplacement)(replacement)
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// Returns a producer which passes through `Next`, `Error`, and `Interrupted`
/// events from `self` until `replacement` sends an event, at which point the
/// returned producer will send that event and switch to passing through events
/// from `replacement` instead, regardless of whether `self` has sent events
/// already.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func takeUntilReplacement(replacement: Signal<Value, Error>) -> SignalProducer<Value, Error> {
return lift(Signal.takeUntilReplacement)(replacement)
}
/// Waits until `self` completes and then forwards the final `count` values
/// on the returned producer.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func takeLast(count: Int) -> SignalProducer<Value, Error> {
return lift { $0.takeLast(count) }
}
/// Forwards any values from `self` until `predicate` returns false,
/// at which point the returned producer will complete.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func takeWhile(predicate: Value -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.takeWhile(predicate) }
}
/// Zips elements of two producers into pairs. The elements of any Nth pair
/// are the Nth elements of the two input producers.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zipWith<U>(otherProducer: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
return liftRight(Signal.zipWith)(otherProducer)
}
/// Zips elements of this producer and a signal into pairs. The elements of
/// any Nth pair are the Nth elements of the two.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zipWith<U>(otherSignal: Signal<U, Error>) -> SignalProducer<(Value, U), Error> {
return lift(Signal.zipWith)(otherSignal)
}
/// Applies `operation` to values from `self` with `Success`ful results
/// forwarded on the returned producer and `Failure`s sent as `Failed` events.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func attempt(operation: Value -> Result<(), Error>) -> SignalProducer<Value, Error> {
return lift { $0.attempt(operation) }
}
/// Applies `operation` to values from `self` with `Success`ful results mapped
/// on the returned producer and `Failure`s sent as `Failed` events.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func attemptMap<U>(operation: Value -> Result<U, Error>) -> SignalProducer<U, Error> {
return lift { $0.attemptMap(operation) }
}
/// Throttle values sent by the receiver, so that at least `interval`
/// seconds pass between each, then forwards them on the given scheduler.
///
/// If multiple values are received before the interval has elapsed, the
/// latest value is the one that will be passed on.
///
/// If `self` terminates while a value is being throttled, that value
/// will be discarded and the returned producer will terminate immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func throttle(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<Value, Error> {
return lift { $0.throttle(interval, onScheduler: scheduler) }
}
/// Forwards events from `self` until `interval`. Then if producer isn't completed yet,
/// fails with `error` on `scheduler`.
///
/// If the interval is 0, the timeout will be scheduled immediately. The producer
/// must complete synchronously (or on a faster scheduler) to avoid the timeout.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func timeoutWithError(error: Error, afterInterval interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<Value, Error> {
return lift { $0.timeoutWithError(error, afterInterval: interval, onScheduler: scheduler) }
}
}
extension SignalProducerType where Value: OptionalType {
/// Unwraps non-`nil` values and forwards them on the returned signal, `nil`
/// values are dropped.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func ignoreNil() -> SignalProducer<Value.Wrapped, Error> {
return lift { $0.ignoreNil() }
}
}
extension SignalProducerType where Value: EventType, Error == NoError {
/// The inverse of materialize(), this will translate a signal of `Event`
/// _values_ into a signal of those events themselves.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func dematerialize() -> SignalProducer<Value.Value, Value.Error> {
return lift { $0.dematerialize() }
}
}
extension SignalProducerType where Error == NoError {
/// Promotes a producer that does not generate failures into one that can.
///
/// This does not actually cause failers to be generated for the given producer,
/// but makes it easier to combine with other producers that may fail; for
/// example, with operators like `combineLatestWith`, `zipWith`, `flatten`, etc.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func promoteErrors<F: ErrorType>(_: F.Type) -> SignalProducer<Value, F> {
return lift { $0.promoteErrors(F) }
}
}
extension SignalProducerType where Value: Equatable {
/// Forwards only those values from `self` which are not duplicates of the
/// immedately preceding value. The first value is always forwarded.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func skipRepeats() -> SignalProducer<Value, Error> {
return lift { $0.skipRepeats() }
}
}
/// Creates a repeating timer of the given interval, with a reasonable
/// default leeway, sending updates on the given scheduler.
///
/// This timer will never complete naturally, so all invocations of start() must
/// be disposed to avoid leaks.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func timer(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> SignalProducer<NSDate, NoError> {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return timer(interval, onScheduler: scheduler, withLeeway: interval * 0.1)
}
/// Creates a repeating timer of the given interval, sending updates on the
/// given scheduler.
///
/// This timer will never complete naturally, so all invocations of start() must
/// be disposed to avoid leaks.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func timer(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType, withLeeway leeway: NSTimeInterval) -> SignalProducer<NSDate, NoError> {
precondition(interval >= 0)
precondition(leeway >= 0)
return SignalProducer { observer, compositeDisposable in
compositeDisposable += scheduler.scheduleAfter(scheduler.currentDate.dateByAddingTimeInterval(interval), repeatingEvery: interval, withLeeway: leeway) {
observer.sendNext(scheduler.currentDate)
}
}
}
extension SignalProducerType {
/// Injects side effects to be performed upon the specified signal events.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func on(started started: (() -> ())? = nil, event: (Event<Value, Error> -> ())? = nil, failed: (Error -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, terminated: (() -> ())? = nil, disposed: (() -> ())? = nil, next: (Value -> ())? = nil) -> SignalProducer<Value, Error> {
return SignalProducer { observer, compositeDisposable in
started?()
self.startWithSignal { signal, disposable in
compositeDisposable += disposable
compositeDisposable += signal
.on(
event: event,
failed: failed,
completed: completed,
interrupted: interrupted,
terminated: terminated,
disposed: disposed,
next: next
)
.observe(observer)
}
}
}
/// Starts the returned signal on the given Scheduler.
///
/// This implies that any side effects embedded in the producer will be
/// performed on the given scheduler as well.
///
/// Events may still be sent upon other schedulers—this merely affects where
/// the `start()` method is run.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func startOn(scheduler: SchedulerType) -> SignalProducer<Value, Error> {
return SignalProducer { observer, compositeDisposable in
compositeDisposable += scheduler.schedule {
self.startWithSignal { signal, signalDisposable in
compositeDisposable.addDisposable(signalDisposable)
signal.observe(observer)
}
}
}
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(A, B), Error> {
return a.combineLatestWith(b)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(A, B, C), Error> {
return combineLatest(a, b)
.combineLatestWith(c)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(A, B, C, D), Error> {
return combineLatest(a, b, c)
.combineLatestWith(d)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(A, B, C, D, E), Error> {
return combineLatest(a, b, c, d)
.combineLatestWith(e)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, F, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(A, B, C, D, E, F), Error> {
return combineLatest(a, b, c, d, e)
.combineLatestWith(f)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, F, G, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>) -> SignalProducer<(A, B, C, D, E, F, G), Error> {
return combineLatest(a, b, c, d, e, f)
.combineLatestWith(g)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, F, G, H, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H), Error> {
return combineLatest(a, b, c, d, e, f, g)
.combineLatestWith(h)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, F, G, H, I, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I), Error> {
return combineLatest(a, b, c, d, e, f, g, h)
.combineLatestWith(i)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<A, B, C, D, E, F, G, H, I, J, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I, J), Error> {
return combineLatest(a, b, c, d, e, f, g, h, i)
.combineLatestWith(j)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatestWith`. Will return an empty `SignalProducer` if the sequence is empty.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func combineLatest<S: SequenceType, Value, Error where S.Generator.Element == SignalProducer<Value, Error>>(producers: S) -> SignalProducer<[Value], Error> {
var generator = producers.generate()
if let first = generator.next() {
let initial = first.map { [$0] }
return GeneratorSequence(generator).reduce(initial) { producer, next in
producer.combineLatestWith(next).map { $0.0 + [$0.1] }
}
}
return .empty
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(A, B), Error> {
return a.zipWith(b)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(A, B, C), Error> {
return zip(a, b)
.zipWith(c)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(A, B, C, D), Error> {
return zip(a, b, c)
.zipWith(d)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(A, B, C, D, E), Error> {
return zip(a, b, c, d)
.zipWith(e)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, F, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(A, B, C, D, E, F), Error> {
return zip(a, b, c, d, e)
.zipWith(f)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, F, G, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>) -> SignalProducer<(A, B, C, D, E, F, G), Error> {
return zip(a, b, c, d, e, f)
.zipWith(g)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, F, G, H, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H), Error> {
return zip(a, b, c, d, e, f, g)
.zipWith(h)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, F, G, H, I, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I), Error> {
return zip(a, b, c, d, e, f, g, h)
.zipWith(i)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<A, B, C, D, E, F, G, H, I, J, Error>(a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>) -> SignalProducer<(A, B, C, D, E, F, G, H, I, J), Error> {
return zip(a, b, c, d, e, f, g, h, i)
.zipWith(j)
.map(repack)
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`. Will return an empty `SignalProducer` if the sequence is empty.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func zip<S: SequenceType, Value, Error where S.Generator.Element == SignalProducer<Value, Error>>(producers: S) -> SignalProducer<[Value], Error> {
var generator = producers.generate()
if let first = generator.next() {
let initial = first.map { [$0] }
return GeneratorSequence(generator).reduce(initial) { producer, next in
producer.zipWith(next).map { $0.0 + [$0.1] }
}
}
return .empty
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Flattens the inner producers sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` or an active inner producer fails, the returned
/// producer will forward that failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return lift { (signal: Signal<Value, Error>) -> Signal<Value.Value, Error> in
return signal.flatten(strategy)
}
}
}
extension SignalProducerType where Value: SignalType, Error == Value.Error {
/// Flattens the inner signals sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` or an active inner signal emits an error, the returned
/// producer will forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.lift { $0.flatten(strategy) }
}
}
extension SignalProducerType {
/// Maps each event from `producer` to a new producer, then flattens the
/// resulting producers (into a single producer of values), according to the
/// semantics of the given strategy.
///
/// If `producer` or any of the created producers fail, the returned
/// producer will forward that failure immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `producer` to a new signal, then flattens the
/// resulting signals (into a single producer of values), according to the
/// semantics of the given strategy.
///
/// If `producer` or any of the created signals emit an error, the returned
/// producer will forward that error immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Catches any failure that may occur on the input producer, mapping to a new producer
/// that starts in its place.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> SignalProducer<Value, F> {
return self.lift { $0.flatMapError(handler) }
}
/// `concat`s `next` onto `self`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func concat(next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer<SignalProducer<Value, Error>, Error>(values: [self.producer, next]).flatten(.Concat)
}
}
extension SignalProducerType {
/// Repeats `self` a total of `count` times. Repeating `1` times results in
/// an equivalent signal producer.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func times(count: Int) -> SignalProducer<Value, Error> {
precondition(count >= 0)
if count == 0 {
return .empty
} else if count == 1 {
return producer
}
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable.addDisposable(serialDisposable)
func iterate(current: Int) {
self.startWithSignal { signal, signalDisposable in
serialDisposable.innerDisposable = signalDisposable
signal.observe { event in
if case .Completed = event {
let remainingTimes = current - 1
if remainingTimes > 0 {
iterate(remainingTimes)
} else {
observer.sendCompleted()
}
} else {
observer.action(event)
}
}
}
}
iterate(count)
}
}
/// Ignores failures up to `count` times.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func retry(count: Int) -> SignalProducer<Value, Error> {
precondition(count >= 0)
if count == 0 {
return producer
} else {
return flatMapError { _ in
self.retry(count - 1)
}
}
}
/// Waits for completion of `producer`, *then* forwards all events from
/// `replacement`. Any failure sent from `producer` is forwarded immediately, in
/// which case `replacement` will not be started, and none of its events will be
/// be forwarded. All values sent from `producer` are ignored.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func then<U>(replacement: SignalProducer<U, Error>) -> SignalProducer<U, Error> {
let relay = SignalProducer<U, Error> { observer, observerDisposable in
self.startWithSignal { signal, signalDisposable in
observerDisposable.addDisposable(signalDisposable)
signal.observe { event in
switch event {
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
case .Next:
break
}
}
}
}
return relay.concat(replacement)
}
/// Starts the producer, then blocks, waiting for the first value.
@warn_unused_result(message="Did you forget to check the result?")
public func first() -> Result<Value, Error>? {
return take(1).single()
}
/// Starts the producer, then blocks, waiting for events: Next and Completed.
/// When a single value or error is sent, the returned `Result` will represent
/// those cases. However, when no values are sent, or when more than one value
/// is sent, `nil` will be returned.
@warn_unused_result(message="Did you forget to check the result?")
public func single() -> Result<Value, Error>? {
let semaphore = dispatch_semaphore_create(0)
var result: Result<Value, Error>?
take(2).start { event in
switch event {
case let .Next(value):
if result != nil {
// Move into failure state after recieving another value.
result = nil
return
}
result = .Success(value)
case let .Failed(error):
result = .Failure(error)
dispatch_semaphore_signal(semaphore)
case .Completed, .Interrupted:
dispatch_semaphore_signal(semaphore)
}
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return result
}
/// Starts the producer, then blocks, waiting for the last value.
@warn_unused_result(message="Did you forget to check the result?")
public func last() -> Result<Value, Error>? {
return takeLast(1).single()
}
/// Starts the producer, then blocks, waiting for completion.
@warn_unused_result(message="Did you forget to check the result?")
public func wait() -> Result<(), Error> {
return then(SignalProducer<(), Error>(value: ())).last() ?? .Success(())
}
}
| mit | df5779f082994d2af0619bfa17f83542 | 41.948988 | 429 | 0.709381 | 3.810215 | false | false | false | false |
vishnuvaradaraj/firefox-ios | Client/Frontend/Settings/ClearPrivateDataTableViewController.swift | 3 | 5060 | /* 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 UIKit
import Shared
private let SectionToggles = 0
private let SectionButton = 1
private let NumberOfSections = 2
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
private let HeaderHeight: CGFloat = 44
class ClearPrivateDataTableViewController: UITableViewController {
private var clearButton: UITableViewCell?
var profile: Profile!
var tabManager: TabManager!
private lazy var clearables: [Clearable] = {
return [
HistoryClearable(profile: self.profile),
CacheClearable(tabManager: self.tabManager),
CookiesClearable(tabManager: self.tabManager),
SiteDataClearable(tabManager: self.tabManager),
PasswordsClearable(profile: self.profile),
]
}()
private lazy var toggles: [Bool] = {
return [Bool](count: self.clearables.count, repeatedValue: true)
}()
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Clear Private Data", comment: "Navigation title for clearing private data.")
tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
tableView.tableFooterView = UIView()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
if indexPath.section == SectionToggles {
cell.textLabel?.text = clearables[indexPath.item].label
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = true
cell.accessoryView = control
cell.selectionStyle = .None
control.tag = indexPath.item
} else {
assert(indexPath.section == SectionButton)
cell.textLabel?.text = NSLocalizedString("Clear Private Data", comment: "Button in settings that clears private data for the selected items.")
cell.textLabel?.textAlignment = NSTextAlignment.Center
cell.textLabel?.textColor = UIConstants.DestructiveRed
clearButton = cell
}
// Make the separator line fill the entire table width.
cell.separatorInset = UIEdgeInsetsZero
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return NumberOfSections
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == SectionToggles {
return clearables.count
}
assert(section == SectionButton)
return 1
}
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
guard indexPath.section == SectionButton else { return false }
// Highlight the button only if at least one clearable is enabled.
return toggles.contains(true)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
guard indexPath.section == SectionButton else { return }
clearables
.enumerate()
.filter { (i, _) in toggles[i] }
.map { (_, clearable) in clearable.clear() }
.allSucceed()
.upon { result in
// TODO: Need some kind of success/failure UI. Bug 1202093.
if result.isSuccess {
print("Private data cleared")
} else {
print("Error clearing private data")
assertionFailure("\(result.failureValue)")
}
dispatch_async(dispatch_get_main_queue()) {
self.navigationController?.popViewControllerAnimated(true)
}
}
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return HeaderHeight
}
@objc func switchValueChanged(toggle: UISwitch) {
toggles[toggle.tag] = toggle.on
// Dim the clear button if no clearables are selected.
clearButton?.textLabel?.textColor = toggles.contains(true) ? UIConstants.DestructiveRed : UIColor.lightGrayColor()
}
} | mpl-2.0 | 6e1391caa9748b8c4e4089c66175c3e5 | 37.930769 | 154 | 0.668972 | 5.641026 | false | false | false | false |
dnevera/IMProcessing | IMProcessing/Classes/Histogram/IMPHistogram.swift | 1 | 32044 | //
// IMPHistogram.swift
// IMProcessing
//
// Created by denis svinarchuk on 30.11.15.
// Copyright © 2015 IMetalling. All rights reserved.
//
import Accelerate
import simd
///
/// Представление гистограммы для произвольного цветового пространства
/// с максимальным количеством каналов от одного до 4х.
///
public class IMPHistogram {
public enum ChannelsType:Int{
case PLANAR = 1
case XY = 2
case XYZ = 3
case XYZW = 4
};
public enum ChannelNo:Int{
case X = 0
case Y = 1
case Z = 2
case W = 3
};
public enum DistributionType:Int{
case SOURCE = 0
case CDF = 1
}
///
/// Histogram width
///
public let size:Int
/// Channels type: .PLANAR - one channel, XYZ - 3 channels, XYZW - 4 channels per histogram
public let type:ChannelsType
private var _distributionType:DistributionType = .SOURCE
public var distributionType:DistributionType {
return _distributionType
}
///
/// Поканальная таблица счетов. Используем представление в числах с плавающей точкой.
/// Нужно это для упрощения выполнения дополнительных акселерированных вычислений на DSP,
/// поскольку все операции на DSP выполняются либо во float либо в double.
///
public var channels:[[Float]]
public subscript(channel:ChannelNo)->[Float]{
get{
return channels[channel.rawValue]
}
}
private var binCounts:[Float]
public func binCount(channel:ChannelNo)->Float{
return binCounts[channel.rawValue]
}
///
/// Конструктор пустой гистограммы.
///
public init(size:Int = Int(kIMP_HistogramSize), type:ChannelsType = .XYZW, distributionType:DistributionType = .SOURCE){
self.size = size
self.type = type
channels = [[Float]](count: Int(type.rawValue), repeatedValue: [Float](count: size, repeatedValue: 0))
binCounts = [Float](count: Int(type.rawValue), repeatedValue: 0)
_distributionType = distributionType
}
/// Create normal distributed histogram
///
/// - parameter fi: fi
/// - parameter mu: points of mu's
/// - parameter sigma: points of sigma's, must be the same number that is in mu's
/// - parameter size: histogram size, by default is kIMP_HistogramSize
/// - parameter type: channels type
///
public init(gauss fi:Float, mu:[Float], sigma:[Float], size:Int = Int(kIMP_HistogramSize), type: ChannelsType = .XYZW){
self.size = size
self.type = type
channels = [[Float]](count: Int(type.rawValue), repeatedValue: [Float](count: self.size, repeatedValue: 0))
binCounts = [Float](count: Int(type.rawValue), repeatedValue: 0)
let m = Float(size-1)
for c in 0 ..< channels.count {
for i in 0 ..< size {
let v = Float(i)/m
for p in 0 ..< mu.count {
channels[c][i] += v.gaussianPoint(fi: fi, mu: mu[p], sigma: sigma[p])
}
}
updateBinCountForChannel(c)
}
}
public init(ramp:Range<Int>, size:Int = Int(kIMP_HistogramSize), type: ChannelsType = .XYZW){
self.size = size
self.type = type
channels = [[Float]](
count: Int(type.rawValue), repeatedValue: [Float](count: self.size, repeatedValue: 0))
binCounts = [Float](count: Int(type.rawValue), repeatedValue: 0)
for c in 0 ..< channels.count {
self.ramp(&channels[c], ramp: ramp)
updateBinCountForChannel(c)
}
}
///
/// Конструктор копии каналов.
///
/// - parameter channels: каналы с данными исходной гистограммы
///
public init(channels ch:[[Float]]){
self.size = ch[0].count
switch ch.count {
case 1:
type = .PLANAR
case 2:
type = .XY
case 3:
type = .XYZ
case 4:
type = .XYZW
default:
fatalError("Number of channels is great then it posible: \(ch.count)")
}
channels = [[Float]](count: type.rawValue, repeatedValue: [Float](count: size, repeatedValue: 0))
binCounts = [Float](count: Int(type.rawValue), repeatedValue: 0)
for c in 0 ..< channels.count {
for i in 0..<ch[c].count {
channels[c][i] = ch[c][i]
}
updateBinCountForChannel(c)
}
}
public init(histogram:IMPHistogram){
size = histogram.size
type = histogram.type
channels = [[Float]](count: type.rawValue, repeatedValue: [Float](count: size, repeatedValue: 0))
binCounts = [Float](count: Int(type.rawValue), repeatedValue: 0)
for c in 0 ..< channels.count {
for i in 0..<histogram.channels[c].count {
channels[c][i] = histogram.channels[c][i]
}
updateBinCountForChannel(c)
}
}
///
/// Метод обновления данных котейнера гистограммы.
///
/// - parameter dataIn: обновить значение интенсивностей по сырым данным. Сырые данные должны быть преставлены в формате IMPHistogramBuffer.
///
public func update(data dataIn: UnsafePointer<Void>){
clearHistogram()
let address = UnsafePointer<UInt32>(dataIn)
for c in 0..<channels.count{
updateChannel(&channels[c], address: address, index: c)
updateBinCountForChannel(c)
}
}
/// Метод обновления сборки данных гистограммы из частичных гистограмм.
///
/// - parameter dataIn:
/// - parameter dataCount:
public func update(data dataIn: UnsafePointer<Void>, dataCount: Int){
self.clearHistogram()
for i in 0..<dataCount{
let dataIn = UnsafePointer<IMPHistogramBuffer>(dataIn)+i
let address = UnsafePointer<UInt32>(dataIn)
for c in 0..<channels.count{
var data:[Float] = [Float](count: Int(self.size), repeatedValue: 0)
self.updateChannel(&data, address: address, index: c)
self.addFromData(data, toChannel: &channels[c])
updateBinCountForChannel(c)
}
}
}
public func update(channel:ChannelNo, fromHistogram:IMPHistogram, fromChannel:ChannelNo) {
if fromHistogram.size != size {
fatalError("Histogram sizes are not equal: \(size) != \(fromHistogram.size)")
}
let address = UnsafeMutablePointer<Float>(channels[channel.rawValue])
let from_address = UnsafeMutablePointer<Float>(fromHistogram.channels[fromChannel.rawValue])
vDSP_vclr(address, 1, vDSP_Length(size))
vDSP_vadd(address, 1, from_address, 1, address, 1, vDSP_Length(size));
updateBinCountForChannel(channel.rawValue)
}
public func updateWithConinuesData(dataIn: UnsafeMutablePointer<UInt32>){
self.clearHistogram()
let address = UnsafePointer<UInt32>(dataIn)
for c in 0..<channels.count{
self.updateContinuesData(&channels[c], address: address, index: c)
}
}
public func update(red red:[vImagePixelCount], green:[vImagePixelCount], blue:[vImagePixelCount], alpha:[vImagePixelCount]){
self.clearHistogram()
self.updateChannel(&channels[0], address: red, index: 0)
self.updateChannel(&channels[1], address: green, index: 0)
self.updateChannel(&channels[2], address: blue, index: 0)
self.updateChannel(&channels[3], address: alpha, index: 0)
for c in 0..<channels.count{
updateBinCountForChannel(c)
}
}
///
/// Текущий CDF (комулятивная функция распределения) гистограммы.
///
/// - parameter scale: масштабирование значений, по умолчанию CDF приводится к 1
///
/// - returns: контейнер значений гистограммы с комулятивным распределением значений интенсивностей
///
public func cdf(scale:Float = 1, power pow:Float=1) -> IMPHistogram {
let _cdf = IMPHistogram(channels:channels);
_cdf._distributionType = .CDF
for c in 0..<_cdf.channels.count{
power(pow: pow, A: _cdf.channels[c], B: &_cdf.channels[c])
integrate(A: &_cdf.channels[c], B: &_cdf.channels[c], size: _cdf.channels[c].count, scale:scale)
_cdf.updateBinCountForChannel(c)
}
return _cdf;
}
/// Текущий PDF (распределенией плотностей) гистограммы.
///
/// - parameter scale: scale
///
/// - returns: return value histogram
///
public func pdf(scale:Float = 1) -> IMPHistogram {
let _pdf = IMPHistogram(channels:channels);
for c in 0..<_pdf.channels.count{
self.scale(A: &_pdf.channels[c], size: _pdf.channels[c].count, scale:scale)
_pdf.updateBinCountForChannel(c)
}
return _pdf;
}
///
/// Среднее значение интенсивностей канала с заданным индексом.
/// Возвращается значение нормализованное к 1.
///
/// - parameter index: индекс канала начиная от 0
///
/// - returns: нормализованное значние средней интенсивности канала
///
public func mean(channel index:ChannelNo) -> Float{
let m = mean(A: &channels[index.rawValue], size: channels[index.rawValue].count)
let denom = sum(A: &channels[index.rawValue], size: channels[index.rawValue].count)
return m/denom
}
///
/// Минимальное значение интенсивности в канале с заданным клипингом.
///
/// - parameter index: индекс канала
/// - parameter clipping: значение клиппинга интенсивностей в тенях
///
/// - returns: Возвращается значение нормализованное к 1.
///
public func low(channel index:ChannelNo, clipping:Float) -> Float{
let size = channels[index.rawValue].count
var (low,p) = search_clipping(channel: index.rawValue, size: size, clipping: clipping)
if p == 0 { low = 0 }
low = low>0 ? low-1 : 0
return Float(low)/Float(size)
}
///
/// Максимальное значение интенсивности в канале с заданным клипингом.
///
/// - parameter index: индекс канала
/// - parameter clipping: значение клиппинга интенсивностей в светах
///
/// - returns: Возвращается значение нормализованное к 1.
///
public func high(channel index:ChannelNo, clipping:Float) -> Float{
let size = channels[index.rawValue].count
var (high,p) = search_clipping(channel: index.rawValue, size: size, clipping: 1.0-clipping)
if p == 0 { high = vDSP_Length(size) }
high = high<vDSP_Length(size) ? high+1 : vDSP_Length(size)
return Float(high)/Float(size)
}
///
/// Look up interpolated values by indeces in the histogram
///
///
public func lookup(values:[Float], channel index:ChannelNo) -> [Float] {
var lookup = self[index]
var b = values
return interpolate(&lookup, b: &b)
}
func interpolate(inout a: [Float], inout b: [Float]) -> [Float] {
var c = [Float](count: b.count, repeatedValue: 0)
vDSP_vlint(&a, &b, 1, &c, 1, UInt(b.count), UInt(a.count))
return c
}
/// Convolve histogram channel with filter presented another histogram distribution with phase-lead and scale.
///
/// - parameter filter: filter distribution histogram
/// - parameter lead: phase-lead in ticks of the histogram
/// - parameter scale: scale
public func convolve(filter:IMPHistogram, lead:Int, scale:Float=1){
for c in 0 ..< channels.count {
convolve(filter.channels[c], channel: ChannelNo(rawValue: c)!, lead: lead, scale: scale)
}
}
/// Convolve histogram channel with filter distribution with phase-lead and scale.
///
/// - parameter filter: filter distribution
/// - parameter channel: histogram which should be convolved
/// - parameter lead: phase-lead in ticks of the histogram
/// - parameter scale: scale
public func convolve(filter:[Float], channel c:ChannelNo, lead:Int, scale:Float=1){
if filter.count == 0 {
return
}
let halfs = vDSP_Length(filter.count)
var asize = size+filter.count*2
var addata = [Float](count: asize, repeatedValue: 0)
//
// we need to supplement source distribution to apply filter right
//
vDSP_vclr(&addata, 1, vDSP_Length(asize))
var zero = channels[c.rawValue][0]
vDSP_vsadd(&addata, 1, &zero, &addata, 1, vDSP_Length(filter.count))
var one = channels[c.rawValue][self.size-1]
let rest = UnsafeMutablePointer<Float>(addata)+size+Int(halfs)
vDSP_vsadd(rest, 1, &one, rest, 1, halfs-1)
var addr = UnsafeMutablePointer<Float>(addata)+Int(halfs)
let os = UnsafeMutablePointer<Float>(channels[c.rawValue])
vDSP_vadd(os, 1, addr, 1, addr, 1, vDSP_Length(size))
//
// apply filter
//
asize = size+filter.count-1
vDSP_conv(addata, 1, filter, 1, &addata, 1, vDSP_Length(asize), vDSP_Length(filter.count))
//
// normalize coordinates
//
addr = UnsafeMutablePointer<Float>(addata)+lead
memcpy(os, addr, size*sizeof(Float))
var left = -channels[c.rawValue][0]
vDSP_vsadd(os, 1, &left, os, 1, vDSP_Length(size))
//
// normalize
//
var denom:Float = 0
if (scale>0) {
vDSP_maxv (os, 1, &denom, vDSP_Length(size))
denom /= scale
vDSP_vsdiv(os, 1, &denom, os, 1, vDSP_Length(size))
}
updateBinCountForChannel(c.rawValue)
}
/// Generate random distributed values and creat from it a histogram instance
///
/// - parameter scale: scale value
///
/// - returns: a random distributed histogram
public func random(scale scale:Float = 1) -> IMPHistogram {
let h = IMPHistogram(ramp: 0..<size, size:size, type: type)
for c in 0 ..< h.channels.count {
var data = [UInt8](count: h.size, repeatedValue: 0)
SecRandomCopyBytes(kSecRandomDefault, data.count, &data)
h.channels[c] = [Float](count: h.size, repeatedValue: 0)
let addr = UnsafeMutablePointer<Float>(h.channels[c])
let sz = vDSP_Length(h.channels[c].count)
vDSP_vfltu8(data, 1, addr, 1, sz);
if scale > 0 {
var denom:Float = 0;
vDSP_maxv (addr, 1, &denom, sz);
denom /= scale
vDSP_vsdiv(addr, 1, &denom, addr, 1, sz);
}
}
return h
}
/// Add a histogram to the self
///
/// - parameter histogram: another histogram
public func add(histogram:IMPHistogram){
for c in 0 ..< histogram.channels.count {
addFromData(histogram.channels[c], toChannel: &channels[c])
}
}
/// Add values to the histogram channel
///
/// - parameter values: array of values, should have the equal size of the histogrram
/// - parameter channel: channel number
public func add(values:[Float], channel:ChannelNo){
if values.count != size {
fatalError("IMPHistogram: source and values vector must have equal size")
}
addFromData(values, toChannel: &channels[channel.rawValue])
}
/// Multiply two histograms
///
/// - parameter histogram: another histogram
public func mul(histogram:IMPHistogram){
for c in 0 ..< histogram.channels.count {
mulFromData(histogram.channels[c], toChannel: &channels[c])
}
}
/// Multyply a histogram channel by vector of values
///
/// - parameter values: array of values
/// - parameter channel: histogram channel number
public func mul(values:[Float], channel:ChannelNo){
if values.count != size {
fatalError("IMPHistogram: source and values vector must have equal size")
}
mulFromData(values, toChannel: &channels[channel.rawValue])
}
//
// Утилиты работы с векторными данными на DSP
//
// ..........................................
private func updateBinCountForChannel(channel:Int){
var denom:Float = 0
let c = channels[channel]
vDSP_sve(c, 1, &denom, vDSP_Length(c.count))
binCounts[channel] = denom
}
//
// Реальная размерность беззнакового целого. Может отличаться в зависимости от среды исполнения.
//
private let dim = sizeof(UInt32)/sizeof(simd.uint);
//
// Обновить данные контейнера гистограммы и сконвертировать из UInt во Float
//
private func updateChannel(inout channel:[Float], address:UnsafePointer<UInt32>, index:Int){
let p = address+Int(self.size)*Int(index)
let dim = self.dim<1 ? 1 : self.dim;
vDSP_vfltu32(p, dim, &channel, 1, vDSP_Length(size))
}
private func updateChannel(inout channel:[Float], address:UnsafePointer<vImagePixelCount>, index:Int){
let p = UnsafePointer<UInt32>(address+Int(self.size)*Int(index))
let dim = sizeof(vImagePixelCount)/sizeof(UInt32);
vDSP_vfltu32(p, dim, &channel, 1, vDSP_Length(size));
}
private func updateContinuesData(inout channel:[Float], address:UnsafePointer<UInt32>, index:Int){
let p = address+Int(size)*index
vDSP_vfltu32(p, 1, &channel, 1, vDSP_Length(size))
}
//
// Поиск индекса отсечки клипинга
//
private func search_clipping(channel index:Int, size:Int, clipping:Float) -> (vDSP_Length,vDSP_Length) {
if tempBuffer.count != size {
tempBuffer = [Float](count: size, repeatedValue: 0)
}
//
// интегрируем сумму
//
integrate(A: &channels[index], B: &tempBuffer, size: size, scale:1)
var cp = clipping
var one = Float(1)
//
// Отсекаем точку перехода из минимума в остальное
//
vDSP_vthrsc(&tempBuffer, 1, &cp, &one, &tempBuffer, 1, vDSP_Length(size))
var position:vDSP_Length = 0
var all:vDSP_Length = 0
//
// Ищем точку пересечения с осью
//
vDSP_nzcros(tempBuffer, 1, 1, &position, &all, vDSP_Length(size))
return (position,all);
}
//
// Временные буфер под всякие конвреторы
//
private var tempBuffer:[Float] = [Float]()
//
// Распределение абсолютных значений интенсивностей гистограммы в зависимости от индекса
//
private var intensityDistribution:(Int,[Float])!
//
// Сборка распределения интенсивностей
//
private func createIntensityDistribution(size:Int) -> (Int,[Float]){
let m:Float = Float(size-1)
var h:[Float] = [Float](count: size, repeatedValue: 0)
var zero:Float = 0
var v:Float = 1.0/m
// Создает вектор с монотонно возрастающими или убывающими значениями
vDSP_vramp(&zero, &v, &h, 1, vDSP_Length(size))
return (size,h);
}
private func ramp(inout C:[Float], ramp:Range<Int>){
let m:Float = Float(C.count-1)
var zero:Float = Float(ramp.startIndex)/m
var v:Float = Float(ramp.endIndex-ramp.startIndex)/m
vDSP_vramp(&zero, &v, &C, 1, vDSP_Length(C.count))
}
//
// Вычисление среднего занчения распределния вектора
//
private func mean(inout A A:[Float], size:Int) -> Float {
intensityDistribution = intensityDistribution ?? self.createIntensityDistribution(size)
if intensityDistribution.0 != size {
intensityDistribution = self.createIntensityDistribution(size)
}
if tempBuffer.count != size {
tempBuffer = [Float](count: size, repeatedValue: 0)
}
//
// Перемножаем два вектора вектор
//
vDSP_vmul(&A, 1, &intensityDistribution.1, 1, &tempBuffer, 1, vDSP_Length(size))
return sum(A: &tempBuffer, size: size)
}
//
// Вычисление скалярной суммы вектора
//
private func sum(inout A A:[Float], size:Int) -> Float {
var sum:Float = 0
vDSP_sve(&A, 1, &sum, vDSP_Length(self.size));
return sum
}
private func power(pow pow:Float, A:[Float], inout B:[Float]){
var y = pow;
var sz:Int32 = Int32(size);
// Set z[i] to pow(x[i],y) for i=0,..,n-1
// void vvpowsf (float * /* z */, const float * /* y */, const float * /* x */, const int * /* n */)
var a = A
vvpowsf(&B, &y, &a, &sz);
}
//
// Вычисление интегральной суммы вектора приведенной к определенной размерности задаваймой
// параметом scale
//
private func integrate(inout A A:[Float], inout B:[Float], size:Int, scale:Float){
var one:Float = 1
let rsize = vDSP_Length(size)
vDSP_vrsum(&A, 1, &one, &B, 1, rsize)
if scale > 0 {
var denom:Float = 0;
vDSP_maxv (&B, 1, &denom, rsize);
denom /= scale
vDSP_vsdiv(&B, 1, &denom, &B, 1, rsize);
}
}
private func scale(inout A A:[Float], size:Int, scale:Float){
let rsize = vDSP_Length(size)
if scale > 0 {
var denom:Float = 0;
vDSP_maxv (&A, 1, &denom, rsize);
denom /= scale
vDSP_vsdiv(&A, 1, &denom, &A, 1, rsize);
}
}
private func addFromData(data:[Float], inout toChannel:[Float]){
vDSP_vadd(&toChannel, 1, data, 1, &toChannel, 1, vDSP_Length(self.size))
}
private func mulFromData(data:[Float], inout toChannel:[Float]){
vDSP_vmul(&toChannel, 1, data, 1, &toChannel, 1, vDSP_Length(self.size))
}
private func clearChannel(inout channel:[Float]){
vDSP_vclr(&channel, 1, vDSP_Length(self.size))
}
private func clearHistogram(){
for c in 0..<channels.count{
clearChannel(&channels[c]);
}
}
}
// MARK: - Statistical measurements
public extension IMPHistogram {
public func entropy(channel index:ChannelNo) -> Float{
var e:Float = 0
let sum = binCount(index)
for i in 0 ..< size {
let Hc = self[index][i]
if Hc > 0 {
e += -(Hc/sum) * log2(Hc/sum);
}
}
return e
}
}
// MARK: - Peaks and valleys
public extension IMPHistogram{
public struct Extremum {
public let i:Int
public let y:Float
public init(i:Int,y:Float){
self.i = i
self.y = y
}
}
convenience init(ƒ:Float, µ:Float, ß:Float){
self.init(gauss: ƒ, mu: [µ], sigma: [ß], size: ß.int*2, type: .PLANAR)
}
/// Find local suffisient peeks of the histogram channel
///
/// - parameter channel: channel no
/// - parameter window: window size
///
/// - returns: array of extremums
///
/// Source: http://stackoverflow.com/questions/22169492/number-of-peaks-in-histogram
///
public func peaks(channel channel:ChannelNo, window:Int = 5, threshold:Float = 0 ) -> [Extremum] {
let N = window
let xt:Float = N.float
let yt:Float = threshold > 0 ? threshold : 1/size.float
// Result indices
var indices = [Extremum]()
let avrg = IMPHistogram(channels: [[Float](count: N, repeatedValue: 1/N.float)])
// Copy self histogram to avoid smothing effect for itself
let src = IMPHistogram(channels: [self[channel]])
// Convolve gaussian filter with filter 3ß
src.convolve(avrg[.X], channel: .X, lead: N/2+N%2)
// Analyzed histogram channel
let y = src[.X]
// Find all local maximas
var imax = 0
var max = y[0]
var inc = true
var dec = false
for i in 1 ..< y.count {
// Changed from decline to increase, reset maximum
if (dec && y[i - 1] < y[i]) {
max = 0
dec = false
inc = true
}
// Changed from increase to decline, save index of maximum
if (inc && y[i - 1] > y[i]) {
indices.append(Extremum(i: imax, y: max));
dec = true
inc = false
}
// Update maximum
if (y[i] > max) {
max = y[i]
imax = i
}
}
// If peak size is too small, ignore it
var i = 0
while (indices.count >= 1 && i < indices.count) {
if (y[indices[i].i] < yt) {
indices.removeAtIndex(i)
} else {
i += 1
}
}
// If two peaks are near to each other, take nly the largest one
i = 1;
while (indices.count >= 2 && i < indices.count) {
let index1 = indices[i - 1].i
let index2 = indices[i].i
if (abs(index1 - index2).float < xt) {
indices.removeAtIndex(y[index1] < y[index2] ? i-1 : i)
} else {
i += 1
}
}
return indices;
}
/// Get histogram channel multipeak mean
///
/// - parameter channel: channel no
/// - parameter window: window size
///
/// - returns: mean value
public func peaksMean(channel channel:ChannelNo, window:Int = 5, threshold:Float = 0 ) -> Float {
let p = peaks(channel: channel, window: window, threshold: threshold)
var sum:Float = 0
for i in p {
sum += i.y * i.i.float
}
return sum/p.count.float/size.float
}
}
// MARK: - Histogram matching
public extension IMPHistogram{
/// Match histogram by vector values
///
/// - parameter values: vector values
/// - parameter channel: channel number
///
/// - returns: matched histogram instance has .PLANAR type and .CDF distribution type
public func match(inout values:[Float], channel:ChannelNo) -> IMPHistogram {
if values.count != size {
fatalError("IMPHistogram: source and values vector histograms must have equal size")
}
var outcdf = IMPHistogram(size: size, type: .PLANAR, distributionType:.CDF)
if distributionType == .CDF {
matchData(&values, target: &channels[channel.rawValue], outcdf: &outcdf, c:0)
}
else {
matchData(&values, target: &cdf().channels[channel.rawValue], outcdf: &outcdf, c:0)
}
return outcdf
}
/// Match two histogram
///
/// - parameter histogram: source specification histogram
///
/// - returns: matched histogram instance has .CDF distribution type
public func match(histogram:IMPHistogram) -> IMPHistogram {
if histogram.size != size {
fatalError("IMPHistogram: source and target histograms must have equal size")
}
if histogram.channels.count != channels.count {
fatalError("IMPHistogram: source and target histograms must have equal channels count")
}
var outcdf = IMPHistogram(size: size, type: type, distributionType:.CDF)
var source:IMPHistogram!
if histogram.distributionType == .CDF {
source = self
}
else{
source = cdf()
}
var target:IMPHistogram!
if distributionType == .CDF {
target = histogram
}
else{
target = histogram.cdf()
}
for c in 0 ..< channels.count {
matchData(&source.channels[c], target: &target.channels[c], outcdf: &outcdf, c: c)
//// j=size-1
//// repeat {
//// outcdf.channels[c][i] = j.float/(outcdf.size.float-1); j--
//// } while (j>=0 && source[i] <= target[j] );
}
return outcdf
}
private func matchData(inout source:[Float], inout target:[Float], inout outcdf:IMPHistogram, c:Int) {
var j=0
let denom = (outcdf.size.float-1)
for i in 0 ..< source.count {
if j >= target.count {
continue
}
if source[i] <= target[j] {
outcdf.channels[c][i] = j.float/denom
}
else {
while source[i] > target[j] {
j += 1;
if j >= target.count {
break
}
if (target[j] - source[i]) > (source[i] - target[j-1] ) {
outcdf.channels[c][i] = j.float/denom
}
else{
outcdf.channels[c][i] = (j.float - 1)/denom
}
}
}
}
}
}
public extension CollectionType where Generator.Element == IMPHistogram.Extremum {
///
/// Get mean of IMPHistogram peaks
///
public func mean() -> Float {
var sum:Float = 0
for i in self {
sum += i.y * i.i.float
}
return sum/(self.count as! Int).float
}
}
| mit | 92b8ad572a0b4cf0be1a3abba074282e | 32.463929 | 144 | 0.554708 | 3.829185 | false | false | false | false |
Dwarfartisan/sparsec | sparsec/sparsec/axiom.swift | 1 | 1516 | //
// axiom.swift
// sparsec
//
// Created by Mars Liu on 15/3/22.
// Copyright (c) 2015年 Dwarf Artisan. All rights reserved.
//
import Foundation
enum ParsecError<I> : ErrorType {
case Eof(pos:I)
case Parse(pos:I, message:String)
}
struct Parsec<T, S:State> {
typealias Parser = (S) throws -> T
}
func bind<T, R, S:State>(x:Parsec<T, S>.Parser, _ binder:(T)->Parsec<R, S>.Parser) -> Parsec<R, S>.Parser {
return {( state: S) throws -> R in
let data = try x(state)
return try binder(data)(state)
}
}
infix operator >>= { associativity left }
func >>= <T, R, S:State>(x: Parsec<T, S>.Parser, binder:(T)->Parsec<R, S>.Parser) -> Parsec<R, S>.Parser {
return bind(x, binder)
}
func then<T, R, S:State >(x: Parsec<T, S>.Parser,
_ y:Parsec<R, S>.Parser) -> Parsec<R, S>.Parser {
return {(state: S) throws -> R in
try x(state)
return try y(state)
}
}
infix operator >> { associativity left }
func >> <T, R, S:State>(x: Parsec<T, S>.Parser, y: Parsec<R, S>.Parser) -> Parsec<R, S>.Parser {
return then(x, y)
}
func over<T, R, S:State >(x: Parsec<T, S>.Parser,
_ y:Parsec<R, S>.Parser) -> Parsec<T, S>.Parser {
return {( state: S) throws -> T in
let data = try x(state)
try y(state)
return data
}
}
infix operator =>> { associativity left }
func =>> <T, R, S:State>(x: Parsec<T, S>.Parser, y: Parsec<R, S>.Parser) -> Parsec<T, S>.Parser {
return over(x, y)
}
| mit | 9d77957d3942cabb9f4101396de08e16 | 25.561404 | 107 | 0.56605 | 2.814126 | false | false | false | false |
dvor/Antidote | Antidote/ChatIncomingFileCell.swift | 2 | 3058 | // 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 UIKit
import SnapKit
private struct Constants {
static let BigOffset = 20.0
static let SmallOffset = 8.0
static let ImageButtonSize = 180.0
static let CloseButtonSize = 25.0
}
class ChatIncomingFileCell: ChatGenericFileCell {
override func setButtonImage(_ image: UIImage) {
super.setButtonImage(image)
loadingView.bottomLabel.isHidden = true
}
override func createViews() {
super.createViews()
contentView.addSubview(loadingView)
contentView.addSubview(cancelButton)
}
override func installConstraints() {
super.installConstraints()
loadingView.snp.makeConstraints {
$0.leading.equalTo(contentView).offset(Constants.BigOffset)
$0.top.equalTo(contentView).offset(Constants.SmallOffset)
$0.bottom.equalTo(contentView).offset(-Constants.SmallOffset)
$0.size.equalTo(Constants.ImageButtonSize)
}
cancelButton.snp.makeConstraints {
$0.leading.equalTo(loadingView.snp.trailing).offset(Constants.SmallOffset)
$0.top.equalTo(loadingView)
$0.size.equalTo(Constants.CloseButtonSize)
}
}
override func updateViewsWithState(_ state: ChatGenericFileCellModel.State, fileModel: ChatGenericFileCellModel) {
loadingView.imageButton.isUserInteractionEnabled = true
loadingView.progressView.isHidden = true
loadingView.topLabel.isHidden = false
loadingView.topLabel.text = fileModel.fileName
loadingView.bottomLabel.text = fileModel.fileSize
loadingView.bottomLabel.isHidden = false
cancelButton.isHidden = false
switch state {
case .waitingConfirmation:
loadingView.centerImageView.image = UIImage.templateNamed("chat-file-download-big")
case .loading:
loadingView.progressView.isHidden = false
case .paused:
break
case .cancelled:
loadingView.setCancelledImage()
loadingView.imageButton.isUserInteractionEnabled = false
cancelButton.isHidden = true
loadingView.bottomLabel.text = String(localized: "chat_file_cancelled")
case .done:
cancelButton.isHidden = true
loadingView.topLabel.isHidden = true
loadingView.bottomLabel.text = fileModel.fileName
}
}
override func loadingViewPressed() {
switch state {
case .waitingConfirmation:
startLoadingHandle?()
case .loading:
pauseOrResumeHandle?()
case .paused:
pauseOrResumeHandle?()
case .cancelled:
break
case .done:
openHandle?()
}
}
}
| mit | 57505c7f2d501f5ec51c53c3cc3360f2 | 33.75 | 118 | 0.632112 | 5.079734 | false | false | false | false |
visenze/visearch-sdk-swift | ViSearchSDK/ViSearchSDK/Classes/Request/ViColorSearchParams.swift | 1 | 1317 | //
// ViColorSearchParams.swift
// ViSearchSDK
//
// Created by Hung on 3/10/16.
// Copyright © 2016 Hung. All rights reserved.
//
import UIKit
/// Construct color search parameter request
public class ViColorSearchParams: ViBaseSearchParams {
public var color: String
public init? (color: String ) {
self.color = color
//verify that color is exactly 6 digits
if self.color.count != 6 {
print("\(type(of: self)).\(#function)[line:\(#line)] - error: color length must be 6")
return nil
}
// verify color is of valid format i.e. only a-fA-F0-9
let regex = try! NSRegularExpression(pattern: "[^a-fA-F|0-9]", options: [])
let numOfMatches = regex.numberOfMatches(in: self.color, options: [.reportCompletion], range: NSMakeRange(0, self.color.count ))
if numOfMatches != 0 {
print("\(type(of: self)).\(#function)[line:\(#line)] - error: invalid color format")
return nil
}
}
public convenience init (color: UIColor){
self.init(color: color.hexString())!
}
public override func toDict() -> [String: Any] {
var dict = super.toDict()
dict["color"] = color
return dict;
}
}
| mit | 451e4b36e397c77c019b1145fa50ac7c | 27.608696 | 136 | 0.570669 | 4.217949 | false | false | false | false |
dokun1/Lumina | Sources/Lumina/Camera/Extensions/Delegates/PhotoCaptureDelegateExtension.swift | 1 | 1118 | //
// PhotoCaptureDelegateExtension.swift
// Lumina
//
// Created by David Okun on 11/20/17.
// Copyright © 2017 David Okun. All rights reserved.
//
import Foundation
import AVFoundation
extension LuminaCamera: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
LuminaLogger.notice(message: "finished processing photo")
guard let image = photo.normalizedImage(forCameraPosition: self.position) else {
return
}
photoCollectionQueue.sync {
if self.currentPhotoCollection == nil {
var collection = LuminaPhotoCapture()
collection.camera = self
collection.depthData = photo.depthData
collection.stillImage = image
self.currentPhotoCollection = collection
} else {
guard var collection = self.currentPhotoCollection else {
return
}
collection.camera = self
collection.depthData = photo.depthData
collection.stillImage = image
self.currentPhotoCollection = collection
}
}
}
}
| mit | 65783e316c875df01955686896f286d0 | 30.027778 | 115 | 0.693823 | 4.920705 | false | false | false | false |
Logicalshift/SwiftRebound | SwiftRebound/Lifetime/CallbackLifetime.swift | 1 | 1114 | //
// CallbackLifetime.swift
// SwiftRebound
//
// Created by Andrew Hunter on 10/07/2016.
//
//
import Foundation
///
/// Lifetime that calls a function when it is finished with
///
open class CallbackLifetime : Lifetime {
/// Called when this object has been finished with (set to nil immediately after calling)
fileprivate var _done: Optional<() -> ()>;
/// True if we should not call done() from deinit
fileprivate var _isKept = false;
public init(done: @escaping () -> ()) {
_done = done;
}
deinit {
if let done = _done {
if !_isKept {
done();
_done = nil;
}
}
}
///
/// Indicates that this object should survive even when this Lifetime object has been deinitialised
///
open func forever() -> Void {
_isKept = true;
_done = nil;
}
///
/// Indicates that this object has been finished with
///
open func done() -> Void {
if let done = _done {
done();
_done = nil;
}
}
}
| apache-2.0 | 29b7042841dfcffedd05f99f8e052afb | 20.843137 | 103 | 0.523339 | 4.284615 | false | false | false | false |
JohnSansoucie/MyProject2 | BlueCap/Beacon/BeaconRegionViewController.swift | 1 | 2918 | //
// BeaconRegionViewController.swift
// BlueCap
//
// Created by Troy Stribling on 9/13/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import UIKit
import BlueCapKit
class BeaconRegionViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var nameTextField : UITextField!
@IBOutlet var uuidTextField : UITextField!
var regionName : String?
required init(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
if let regionName = self.regionName {
self.navigationItem.title = regionName
self.nameTextField.text = regionName
let beacons = BeaconStore.getBeacons()
if let uuid = beacons[regionName] {
self.uuidTextField.text = uuid.UUIDString
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func didResignActive() {
Logger.debug("BeaconRegionsViewController#didResignActive")
self.navigationController?.popToRootViewControllerAnimated(false)
}
func didBecomeActive() {
Logger.debug("BeaconRegionsViewController#didBecomeActive")
}
// UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.nameTextField.resignFirstResponder()
let enteredUUID = self.uuidTextField.text
let enteredName = self.nameTextField.text
if enteredName != nil && enteredUUID != nil {
if !enteredName!.isEmpty && !enteredUUID!.isEmpty {
if let uuid = NSUUID(UUIDString:enteredUUID) {
BeaconStore.addBeacon(enteredName!, uuid:uuid)
if let regionName = self.regionName {
if regionName != enteredName! {
BeaconStore.removeBeacon(regionName)
}
}
self.navigationController?.popViewControllerAnimated(true)
return true
} else {
self.presentViewController(UIAlertController.alertOnErrorWithMessage("UUID '\(enteredUUID)' is Invalid"), animated:true, completion:nil)
return false
}
} else {
return false
}
} else {
return false
}
}
}
| mit | 3164bc69149147313a01adc509a18aff | 34.585366 | 156 | 0.620973 | 5.677043 | false | false | false | false |
SoufianeLasri/Sisley | Sisley/BluryView.swift | 1 | 1535 | //
// BluryView.swift
// Sisley
//
// Created by Soufiane Lasri on 07/01/2016.
// Copyright © 2016 Soufiane Lasri. All rights reserved.
//
import UIKit
class BluryView: UIView {
override init( frame: CGRect ) {
super.init( frame: frame )
self.layer.cornerRadius = self.frame.width / 2
self.backgroundColor = UIColor(red:0.78, green:0.82, blue:0.85, alpha:0.45)
let bubbleImageView = UIImageView( frame: CGRect( x: 0, y: 0, width: self.frame.width, height: self.frame.height ) )
bubbleImageView.image = UIImage( named: "bubble.png" )
self.addSubview( bubbleImageView )
let purchaseImageView = UIImageView( frame: CGRect( x: 0, y: 0, width: 50, height: 50 ) )
purchaseImageView.image = UIImage( named: "purchase.png" )
purchaseImageView.center = CGPoint( x: self.frame.width / 2, y: self.frame.height / 2 - 15 )
self.addSubview( purchaseImageView )
let goToShopLabel = UILabel( frame: CGRect( x: 0, y: self.frame.height / 2 + 15, width: self.frame.width, height: 60 ) )
goToShopLabel.text = "Retrouvez ce soin\nen boutique"
goToShopLabel.numberOfLines = 2
goToShopLabel.font = UIFont( name: "Bellota-Bold", size: 17.0 )
goToShopLabel.textAlignment = .Center
goToShopLabel.textColor = UIColor.whiteColor()
self.addSubview( goToShopLabel )
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | mit | 188eda41e12ea944507f5fec534cd65d | 38.358974 | 128 | 0.640156 | 3.626478 | false | false | false | false |
Dan2552/Napkin | Example/Example for Napkin/ViewControllers/Event/EventIndex.swift | 1 | 1472 | import UIKit
import Placemat
class EventIndexViewController: UITableViewController {
var events = [Event]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = BlockBarButtonItem(barButtonSystemItem: .add) {
let edit = EventEditViewController()
Navigation(viewController: self).show(target: edit, modally: true)
}
loadEvents()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
loadEvents()
tableView.reloadData()
}
func loadEvents() {
events = Event.all() as! [Event]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = event(indexPath).title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let show = EventShowViewController()
show.event = event(indexPath)
Navigation(viewController: self).show(target: show)
}
fileprivate func event(_ indexPath: IndexPath) -> Event {
return events[(indexPath as NSIndexPath).row]
}
}
| mit | e762473c8c7a6550723520db94b24f65 | 31.711111 | 109 | 0.660326 | 5.314079 | false | false | false | false |
LX314/GitHubApp | VC/Main/MainVC.swift | 1 | 3355 | //
// MainVC.swift
// MyGitHub
//
// Created by John LXThyme on 2017/3/29.
// Copyright © 2017年 John LXThyme. All rights reserved.
//
import UIKit
class MainVC: BaseVC {
let authVC = OAuthVC()
lazy var btnLogin: UIButton = {
let btn = UIButton(type: .roundedRect)
btn.setTitle("登录", for: .normal)
btn.setTitleColor(UIColor.white, for: .normal)
btn.backgroundColor = UIColor.purple
btn.center = self.view.center
btn.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: 250, height: 60))
btn.addTarget(nil, action: #selector(self.btnLogin(sender:)), for: .touchUpInside)
return btn
}()
lazy var btnRequest: UIButton = {
let btn = UIButton(type: .roundedRect)
btn.setTitle("Request Starring Repo List", for: .normal)
btn.setTitleColor(UIColor.white, for: .normal)
btn.backgroundColor = UIColor.purple
btn.center = CGPoint(x: self.view.center.x, y: self.view.center.y + 100)
btn.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: 250, height: 60))
btn.addTarget(nil, action: #selector(self.btnRequest(sender:)), for: .touchUpInside)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
//
initNav()
self.view.addSubview(btnLogin)
self.view.addSubview(btnRequest)
}
func initNav() {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Left", style: .done, target: self, action: #selector(leftBarButtonItemAction(sender:)))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Right", style: .done, target: self, action: #selector(rightBarButtonItemAction(sender:)))
}
func leftBarButtonItemAction(sender: Any) {
self.sideMenuViewController.presentLeftMenuViewController()
}
func rightBarButtonItemAction(sender: Any) {
self.sideMenuViewController.presentRightMenuViewController()
}
func navBack(sender: Any) {
authVC.navigationController?.dismiss(animated: true, completion: nil)
}
func btnRequest(sender: Any) {
let userVC = UserVC(nibName: "UserVC", bundle: Bundle.main)
self.navigationController?.pushViewController(userVC, animated: true)
// RepoApi.loadRepoList()
}
func btnLogin(sender: Any) {
if kGitHubAccessToken.characters.count != 40 {
loginAction()
} else {
let alert = UIAlertController(title: "", message: "已经登录, 是否确定重新登录?", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .destructive, handler: { (action) in
self.loginAction()
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(okAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
}
func loginAction() {
let nav = UINavigationController(rootViewController: authVC)
authVC.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(navBack(sender:)))
self.showDetailViewController(nav, sender: self)
}
deinit {
print("---deinit---")
}
}
| mit | 4eb3746084d20c97b38efeb28e3b00cb | 39 | 162 | 0.644277 | 4.283871 | false | false | false | false |
natecook1000/swift | test/attr/attr_ibaction.swift | 9 | 5120 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}}
var iboutlet_global: Int
var iboutlet_accessor: Int {
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{3-13=}}
get { return 42 }
}
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}}
class IBOutletClassTy {}
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}}
struct IBStructTy {}
@IBAction // expected-error {{only instance methods can be declared @IBAction}} {{1-11=}}
func IBFunction() -> () {}
class IBActionWrapperTy {
@IBAction
func click(_: AnyObject) -> () {} // no-warning
func outer(_: AnyObject) -> () {
@IBAction // expected-error {{only instance methods can be declared @IBAction}} {{5-15=}}
func inner(_: AnyObject) -> () {}
}
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{3-13=}}
var value : Void = ()
@IBAction
func process(x: AnyObject) -> Int {} // expected-error {{methods declared @IBAction must return 'Void' (not 'Int')}}
// @IBAction does /not/ semantically imply @objc.
@IBAction // expected-note {{attribute already specified here}}
@IBAction // expected-error {{duplicate attribute}}
func doMagic(_: AnyObject) -> () {}
@IBAction @objc
func moreMagic(_: AnyObject) -> () {} // no-warning
@objc @IBAction
func evenMoreMagic(_: AnyObject) -> () {} // no-warning
}
struct S { }
enum E { }
protocol P1 { }
protocol P2 { }
protocol CP1 : class { }
protocol CP2 : class { }
@objc protocol OP1 { }
@objc protocol OP2 { }
// Check which argument types @IBAction can take.
@objc class X {
// Class type
@IBAction func action1(_: X) {}
@IBAction func action2(_: X?) {}
@IBAction func action3(_: X!) {}
// AnyObject
@IBAction func action4(_: AnyObject) {}
@IBAction func action5(_: AnyObject?) {}
@IBAction func action6(_: AnyObject!) {}
// Any
@IBAction func action4a(_: Any) {}
@IBAction func action5a(_: Any?) {}
@IBAction func action6a(_: Any!) {}
// Protocol types
@IBAction func action7(_: P1) {} // expected-error{{argument to @IBAction method cannot have non-object type 'P1'}}
@IBAction func action8(_: CP1) {} // expected-error{{argument to @IBAction method cannot have non-object type 'CP1'}}
@IBAction func action9(_: OP1) {}
@IBAction func action10(_: P1?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action11(_: CP1?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action12(_: OP1?) {}
@IBAction func action13(_: P1!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action14(_: CP1!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action15(_: OP1!) {}
// Class metatype
@IBAction func action15b(_: X.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action16(_: X.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action17(_: X.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// AnyClass
@IBAction func action18(_: AnyClass) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action19(_: AnyClass?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action20(_: AnyClass!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// Protocol types
@IBAction func action21(_: P1.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action22(_: CP1.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action23(_: OP1.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action24(_: P1.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action25(_: CP1.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action26(_: OP1.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action27(_: P1.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action28(_: CP1.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action29(_: OP1.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// Other bad cases
@IBAction func action30(_: S) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action31(_: E) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
init() { }
}
| apache-2.0 | 3b52a3a78d9cffcdd335d4f55c40f8d9 | 44.714286 | 120 | 0.681445 | 3.896499 | false | false | false | false |
MrSongzj/MSDouYuZB | MSDouYuZB/MSDouYuZB/Classes/Home/Controller/AmuseViewController.swift | 1 | 1212 | //
// AmuseViewController.swift
// MSDouYuZB
//
// Created by jiayuan on 2017/8/8.
// Copyright © 2017年 mrsong. All rights reserved.
//
import UIKit
private let kMenuVH: CGFloat = 200
class AmuseViewController: BaseTVCateViewController
{
// MARK: - 属性
private lazy var presenter = AmusePresenter()
private lazy var menuV: AmuseMenuView = {
let menuV = AmuseMenuView.getView()
menuV.frame = CGRect(x: 0, y: -kMenuVH, width: kScreenW, height: kMenuVH)
return menuV
}()
// MARK: - Private Methods
override func loadData() {
dataSource = presenter
showLoading()
presenter.requestAmuseData {
self.hideLoading()
self.collectionV.reloadData()
// 设置菜单数据
var cateArr = self.presenter.tvCateArr
cateArr.removeFirst()
self.menuV.cateArr = cateArr
}
}
// MARK: - UI
override func setupUI() {
super.setupUI()
collectionV.addSubview(menuV)
collectionV.contentInset = UIEdgeInsets(top: kMenuVH, left: 0, bottom: 0, right: 0)
}
}
| mit | 917c4324148d4e9f39626e1406b345dd | 21.509434 | 91 | 0.573345 | 4.418519 | false | false | false | false |
wmcginty/Edits | Sources/Editors/Substitution.swift | 1 | 1781 | //
// Substitution.swift
// Edits
//
// Created by William McGinty on 11/9/16.
//
//
import Foundation
struct Substitution<T: RangeReplaceableCollection>: Editor, Equatable where T.Element: Equatable {
// MARK: Properties
let from: T.Element
let to: T.Element
let offset: Int
init(source: T, from: T.Element, to: T.Element, atIndex index: T.Index) {
let offset = source.distance(from: source.startIndex, to: index)
self.init(from: from, to: to, atIndexOffset: offset)
}
init(from: T.Element, to: T.Element, atIndexOffset offset: Int) {
self.from = from
self.to = to
self.offset = offset
}
// MARK: CustomStringConvertible
var description: String {
return "Substitute \(to) for the \(from) at index \(offset)"
}
// MARK: Editor
func perform(with input: T) -> T {
var output = input
output.remove(at: input.index(input.startIndex, offsetBy: offset))
output.insert(to, at: input.index(input.startIndex, offsetBy: offset))
return output
}
func affectedIndexPath(forSection section: Int) -> IndexPath {
return IndexPath(item: offset, section: section)
}
func edit(forSection section: Int, in tableView: UITableView) {
tableView.reloadRows(at: [affectedIndexPath(forSection: section)], with: .automatic)
}
func edit(forSection section: Int, in collectionView: UICollectionView) {
collectionView.reloadItems(at: [affectedIndexPath(forSection: section)])
}
// MARK: Equatable
static func == (lhs: Substitution<T>, rhs: Substitution<T>) -> Bool {
return lhs.from == rhs.from && lhs.to == rhs.to && lhs.offset == rhs.offset
}
}
| mit | 2277cc84439cb13af1755c7838c48ea0 | 29.186441 | 98 | 0.627176 | 4.084862 | false | false | false | false |
davepagurek/raytracer | Sources/Materials/Transparent.swift | 1 | 1782 | import VectorMath
import RaytracerLib
import Foundation
public struct Transparent: Absorber {
let tintColor: Color
let refractionIndex: Scalar
let fuzziness: Scalar
public init(tintColor: Color, refractionIndex: Scalar, fuzziness: Scalar) {
self.tintColor = tintColor
self.refractionIndex = refractionIndex
self.fuzziness = fuzziness
}
private func refract(_ i: Vector4, _ n: Vector4, _ ratio: Scalar) -> Vector4? {
let descriminant = 1 - (pow(ratio, 2) * (1 - pow(i.dot(n), 2)))
if descriminant > 0 && shouldRefract(i, n, ratio) {
return i*ratio + n*(-sqrt(descriminant) - i.dot(n)*ratio)
} else {
return nil
}
}
private func shouldRefract(_ i: Vector4, _ n: Vector4, _ ratio: Scalar) -> Bool {
let n1, n2: Scalar
if ratio == refractionIndex {
(n1, n2) = (refractionIndex, 1)
} else {
(n1, n2) = (1, refractionIndex)
}
let cosTheta = -n.dot(i)
let r0 = pow((n1-n2)/(n1+n2), 2)
let probability = r0 + (1-r0)*pow(1 - cosTheta, 5)
return rand(0,1) >= probability
}
public func scatter(_ intersection: Intersection) -> Ray {
let i = intersection.ray.direction.normalized()
let normal = intersection.normal.normalized()
let ratio: Scalar
let n: Vector4
// If the ray is exiting the object
if i.dot(normal) > 0 {
n = normal * -1
ratio = refractionIndex // n / n_0
} else {
n = normal
ratio = 1/refractionIndex // n_0 / n
}
let bounced = refract(i, n, ratio) ?? i.reflectAround(n)
return Ray(
point: intersection.point,
direction: bounced
+ (randomVector() * fuzziness),
color: intersection.ray.color.multiply(tintColor),
time: intersection.ray.time
)
}
}
| mit | 1c444352a3ccd31fb0e4fb0204e33205 | 27.285714 | 83 | 0.614478 | 3.355932 | false | false | false | false |
m-alani/contests | leetcode/repeatedSubstringPattern.swift | 1 | 854 | //
// repeatedSubstringPattern.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/repeated-substring-pattern/
// Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code
//
class Solution {
func repeatedSubstringPattern(_ input: String) -> Bool {
guard input.count > 1 else { return false }
let s = [Character](input)
var result = false
var length = s.count / 2
while length > 0 {
if s.count % length == 0 {
var start = 0, end = length
while end < s.count && s[start] == s[end] {
start += 1; end += 1
}
if end == s.count {
length = 0
result = true
}
}
length -= 1
}
return result
}
}
| mit | 69ab674424afdd7af09b22aa2f01f106 | 26.548387 | 117 | 0.581967 | 3.795556 | false | false | false | false |
HeartRateLearning/HRLApp | HRLApp/Modules/ListWorkoutDates/View/ListWorkoutDatesViewController.swift | 1 | 2001 | //
// ListWorkoutDatesListWorkoutDatesViewController.swift
// HRLApp
//
// Created by Enrique de la Torre on 30/01/2017.
// Copyright © 2017 Enrique de la Torre. All rights reserved.
//
import UIKit
// MARK: - Main body
@objc(HRLListWorkoutDatesViewController)
final class ListWorkoutDatesViewController: UITableViewController {
// MARK: - Dependencies
var output: ListWorkoutDatesViewOutput!
// MARK: - Private properties
private lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .short
return formatter
}()
fileprivate var dates = [] as [Date]
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - UITableViewDataSource methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dates.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.cellIdentifier,
for: indexPath)
let date = dates[indexPath.row]
cell.textLabel?.text = dateFormatter.string(from: date)
return cell
}
// MARK: - UITableViewDelegate methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
output.didSelectDate(at: indexPath.row)
}
}
// MARK: - ListWorkoutDatesViewInput methods
extension ListWorkoutDatesViewController: ListWorkoutDatesViewInput {
func setup(with dates: [Date]) {
self.dates = dates
if isViewLoaded {
tableView.reloadData()
}
}
}
// MARK: - Private body
private extension ListWorkoutDatesViewController {
enum Constants {
static let cellIdentifier = "DateCell"
}
}
| mit | b13c869f90d2ca390f42cd3598c3cbfc | 24 | 98 | 0.6575 | 4.987531 | false | false | false | false |
letvargo/LVGUtilities | Source/FourCharCodeUtilities.swift | 1 | 4619 | //
// FourCharCodeUtilities.swift
// Pods
//
// Created by doof nugget on 4/23/16.
//
//
import Foundation
// MARK: CodeStringConvertible - Definition
/**
A protocol for converting 4-byte integer types to a 4-character `String`.
By default, only `UInt32` and `Int32` conform to this protocol.
Various `typealias`es for these two types will also conform, including
`OSStatus` and `FourCharCode`.
Many Apple APIs have error codes or constants that can be converted
to a 4-character string. Valid 4-character code strings are exactly
4 characers long and every character is between ASCII values `32..<127`.
For example, the constant `kAudioServicesBadPropertySizeError` defined in
Audio Toolbox has a 4-character code string '`!siz`'. Many `OSStatus` error
codes have 4-character code strings associated with them, and these
can be useful for debugging.
*/
public protocol CodeStringConvertible {
/**
A `String`, exactly 4 ASCII characters in length, that represents
the 'FourCharCode' of the value.
If the value that this is called on is not exactly 4 bytes in size,
or if any of the bytes (interpreted as a `UInt8`) does not represent an
ASCII value contained in `32..<127`, the `codeString` property will be `nil`.
*/
var codeString: String? { get }
}
extension CodeStringConvertible {
/// A 4-character String representation of the value.
public var codeString: String? {
let size = MemoryLayout<Self>.size
guard size == 4 else { fatalError("Only types whose size is exactly 4 bytes can conform to `CodeStringConvertible`") }
func parseBytes(_ value: UnsafeRawPointer) -> [UInt8]? {
let ptr = value.bindMemory(to: UInt8.self, capacity: 4)
var bytes = [UInt8]()
for index in (0..<size).reversed() {
let byte = ptr.advanced(by: index).pointee
if (32..<127).contains(byte) {
bytes.append(byte)
} else {
return nil
}
}
return bytes
}
if let bytes = parseBytes([self]),
let output = NSString(
bytes: bytes
, length: size
, encoding: String.Encoding.utf8.rawValue) as? String {
return output
}
return nil
}
}
extension OSStatus: CodeStringConvertible { }
extension UInt32: CodeStringConvertible { }
// MARK: String - Extension adding the code property
extension String {
/**
Converts a 4-character string to a `UInt32` value.
This property is the reverse of the `codeString` property defined
in `CodeStringConvertible`.
- precondition: `self.unicodeScalars.count == 4` where every scalar
has a value in the range `32..<127`. If these conditions are not met
the function will return `nil`.
*/
public func propertyCode() -> UInt32? {
let codePoints = Array(self.utf8.reversed())
guard codePoints.count == 4 else {
return nil
}
guard codePoints.reduce(true, { $0 && (32..<127).contains($1) }) else {
return nil
}
let rawPointer = UnsafeRawPointer(codePoints)
return rawPointer.load(as: UInt32.self)
}
/**
Converts a 4-character string to an `Int32` value.
This property is the reverse of the `codeString` property defined
in `CodeStringConvertible`.
- precondition: `self.unicodeScalars.count == 4` where every scalar
has a value in the range `32..<127`. If these conditions are not met
the function will return `nil`.
*/
public func statusCode() -> OSStatus? {
func pointsToInt32(_ points: UnsafePointer<UInt8>) -> Int32 {
return UnsafeRawPointer(points).load(as: Int32.self)
// return UnsafePointer<Int32>(points).pointee
}
let codePoints = Array(self.utf8.reversed())
guard
codePoints.count == 4
else {
return nil
}
guard
codePoints.reduce(true, { $0 && (32..<127).contains($1) })
else {
return nil
}
return pointsToInt32(codePoints)
}
}
| mit | 6baa9b1d54347859eb89cf8611eb5ac8 | 26.993939 | 126 | 0.570903 | 4.761856 | false | false | false | false |
SimonFairbairn/SwiftyMarkdown | Sources/SwiftyMarkdown/SwiftyLineProcessor.swift | 2 | 7823 | //
// SwiftyLineProcessor.swift
// SwiftyMarkdown
//
// Created by Simon Fairbairn on 16/12/2019.
// Copyright © 2019 Voyage Travel Apps. All rights reserved.
//
import Foundation
import os.log
extension OSLog {
private static var subsystem = "SwiftyLineProcessor"
static let swiftyLineProcessorPerformance = OSLog(subsystem: subsystem, category: "Swifty Line Processor Performance")
}
public protocol LineStyling {
var shouldTokeniseLine : Bool { get }
func styleIfFoundStyleAffectsPreviousLine() -> LineStyling?
}
public struct SwiftyLine : CustomStringConvertible {
public let line : String
public let lineStyle : LineStyling
public var description: String {
return self.line
}
}
extension SwiftyLine : Equatable {
public static func == ( _ lhs : SwiftyLine, _ rhs : SwiftyLine ) -> Bool {
return lhs.line == rhs.line
}
}
public enum Remove {
case leading
case trailing
case both
case entireLine
case none
}
public enum ChangeApplication {
case current
case previous
case untilClose
}
public struct FrontMatterRule {
let openTag : String
let closeTag : String
let keyValueSeparator : Character
}
public struct LineRule {
let token : String
let removeFrom : Remove
let type : LineStyling
let shouldTrim : Bool
let changeAppliesTo : ChangeApplication
public init(token : String, type : LineStyling, removeFrom : Remove = .leading, shouldTrim : Bool = true, changeAppliesTo : ChangeApplication = .current ) {
self.token = token
self.type = type
self.removeFrom = removeFrom
self.shouldTrim = shouldTrim
self.changeAppliesTo = changeAppliesTo
}
}
public class SwiftyLineProcessor {
public var processEmptyStrings : LineStyling?
public internal(set) var frontMatterAttributes : [String : String] = [:]
var closeToken : String? = nil
let defaultType : LineStyling
let lineRules : [LineRule]
let frontMatterRules : [FrontMatterRule]
let perfomanceLog = PerformanceLog(with: "SwiftyLineProcessorPerformanceLogging", identifier: "Line Processor", log: OSLog.swiftyLineProcessorPerformance)
public init( rules : [LineRule], defaultRule: LineStyling, frontMatterRules : [FrontMatterRule] = []) {
self.lineRules = rules
self.defaultType = defaultRule
self.frontMatterRules = frontMatterRules
}
func findLeadingLineElement( _ element : LineRule, in string : String ) -> String {
var output = string
if let range = output.index(output.startIndex, offsetBy: element.token.count, limitedBy: output.endIndex), output[output.startIndex..<range] == element.token {
output.removeSubrange(output.startIndex..<range)
return output
}
return output
}
func findTrailingLineElement( _ element : LineRule, in string : String ) -> String {
var output = string
let token = element.token.trimmingCharacters(in: .whitespaces)
if let range = output.index(output.endIndex, offsetBy: -(token.count), limitedBy: output.startIndex), output[range..<output.endIndex] == token {
output.removeSubrange(range..<output.endIndex)
return output
}
return output
}
func processLineLevelAttributes( _ text : String ) -> SwiftyLine? {
if text.isEmpty, let style = processEmptyStrings {
return SwiftyLine(line: "", lineStyle: style)
}
let previousLines = lineRules.filter({ $0.changeAppliesTo == .previous })
for element in lineRules {
guard element.token.count > 0 else {
continue
}
var output : String = (element.shouldTrim) ? text.trimmingCharacters(in: .whitespaces) : text
let unprocessed = output
if let hasToken = self.closeToken, unprocessed != hasToken {
return nil
}
if !text.contains(element.token) {
continue
}
switch element.removeFrom {
case .leading:
output = findLeadingLineElement(element, in: output)
case .trailing:
output = findTrailingLineElement(element, in: output)
case .both:
output = findLeadingLineElement(element, in: output)
output = findTrailingLineElement(element, in: output)
case .entireLine:
let maybeOutput = output.replacingOccurrences(of: element.token, with: "")
output = ( maybeOutput.isEmpty ) ? maybeOutput : output
default:
break
}
// Only if the output has changed in some way
guard unprocessed != output else {
continue
}
if element.changeAppliesTo == .untilClose {
self.closeToken = (self.closeToken == nil) ? element.token : nil
return nil
}
output = (element.shouldTrim) ? output.trimmingCharacters(in: .whitespaces) : output
return SwiftyLine(line: output, lineStyle: element.type)
}
for element in previousLines {
let output = (element.shouldTrim) ? text.trimmingCharacters(in: .whitespaces) : text
let charSet = CharacterSet(charactersIn: element.token )
if output.unicodeScalars.allSatisfy({ charSet.contains($0) }) {
return SwiftyLine(line: "", lineStyle: element.type)
}
}
return SwiftyLine(line: text.trimmingCharacters(in: .whitespaces), lineStyle: defaultType)
}
func processFrontMatter( _ strings : [String] ) -> [String] {
guard let firstString = strings.first?.trimmingCharacters(in: .whitespacesAndNewlines) else {
return strings
}
var rulesToApply : FrontMatterRule? = nil
for matter in self.frontMatterRules {
if firstString == matter.openTag {
rulesToApply = matter
break
}
}
guard let existentRules = rulesToApply else {
return strings
}
var outputString = strings
// Remove the first line, which is the front matter opening tag
let _ = outputString.removeFirst()
var closeFound = false
while !closeFound {
let nextString = outputString.removeFirst()
if nextString == existentRules.closeTag {
closeFound = true
continue
}
var keyValue = nextString.components(separatedBy: "\(existentRules.keyValueSeparator)")
if keyValue.count < 2 {
continue
}
let key = keyValue.removeFirst()
let value = keyValue.joined()
self.frontMatterAttributes[key] = value
}
while outputString.first?.isEmpty ?? false {
outputString.removeFirst()
}
return outputString
}
public func process( _ string : String ) -> [SwiftyLine] {
var foundAttributes : [SwiftyLine] = []
self.perfomanceLog.start()
var lines = string.components(separatedBy: CharacterSet.newlines)
lines = self.processFrontMatter(lines)
self.perfomanceLog.tag(with: "(Front matter completed)")
for heading in lines {
if processEmptyStrings == nil && heading.isEmpty {
continue
}
guard let input = processLineLevelAttributes(String(heading)) else {
continue
}
if let existentPrevious = input.lineStyle.styleIfFoundStyleAffectsPreviousLine(), foundAttributes.count > 0 {
if let idx = foundAttributes.firstIndex(of: foundAttributes.last!) {
let updatedPrevious = foundAttributes.last!
foundAttributes[idx] = SwiftyLine(line: updatedPrevious.line, lineStyle: existentPrevious)
}
continue
}
foundAttributes.append(input)
self.perfomanceLog.tag(with: "(line completed: \(heading)")
}
return foundAttributes
}
}
| mit | b1f4ea43d9bc62df844eb4e665586841 | 30.413655 | 167 | 0.649962 | 4.367393 | false | false | false | false |
ivasic/Fargo | FargoTests/FoundationTests.swift | 1 | 2682 | //
// FoundationTests.swift
// Fargo
//
// Created by Ivan Vasic on 25/07/15.
// Copyright © 2015 Ivan Vasic. All rights reserved.
//
import XCTest
import Fargo
class FoundationTests: XCTestCase {
func testDecodingString() {
let json = JSON(object: "string")
do {
let a: String = try json.decode()
XCTAssertEqual(a, "string")
} catch {
XCTFail("Failed decoding String \(error)")
}
}
func testDecodingErrorString() {
let json = JSON(object: 0)
do {
let a: String = try json.decode()
XCTFail("Expected DecodeError, got valid object: \(a)")
} catch {
XCTAssert(error is JSON.Error)
}
}
func testDecodingBool() {
let json = JSON(object: true)
do {
let a: Bool = try json.decode()
XCTAssertEqual(a, true)
} catch {
XCTFail("Failed decoding Bool \(error)")
}
}
func testDecodingErrorBool() {
let json = JSON(object: "s")
do {
let a: Bool = try json.decode()
XCTFail("Expected DecodeError, got valid object: \(a)")
} catch {
XCTAssert(error is JSON.Error)
}
}
func testDecodingFloat() {
let json = JSON(object: 0)
do {
let a: Float = try json.decode()
XCTAssertEqual(a, 0)
} catch {
XCTFail("Failed decoding Float \(error)")
}
}
func testDecodingErrorFloat() {
let json = JSON(object: "0")
do {
let a: Float = try json.decode()
XCTFail("Expected JSON.Error, got valid object: \(a)")
} catch {
XCTAssert(error is JSON.Error)
}
}
func testDecodingDouble() {
let json = JSON(object: 0)
do {
let a: Double = try json.decode()
XCTAssertEqual(a, 0)
} catch {
XCTFail("Failed decoding Double \(error)")
}
}
func testDecodingErrorDouble() {
let json = JSON(object: "0")
do {
let a: Double = try json.decode()
XCTFail("Expected JSON.Error, got valid object: \(a)")
} catch {
XCTAssert(error is JSON.Error)
}
}
func testDecodingInt() {
let json = JSON(object: 0)
do {
let a: Int = try json.decode()
XCTAssertEqual(a, 0)
} catch {
XCTFail("Failed decoding Int \(error)")
}
}
func testDecodingErrorInt() {
let json = JSON(object: "0")
do {
let a: Int = try json.decode()
XCTFail("Expected JSON.Error, got valid object: \(a)")
} catch {
XCTAssert(error is JSON.Error)
}
}
func testDecodingUInt() {
let json = JSON(object: 0)
do {
let a: UInt = try json.decode()
XCTAssertEqual(a, 0)
} catch {
XCTFail("Failed decoding UInt \(error)")
}
}
func testDecodingErrorUInt() {
let json = JSON(object: "0")
do {
let a: UInt = try json.decode()
XCTFail("Expected JSON.Error, got valid object: \(a)")
} catch {
XCTAssert(error is JSON.Error)
}
}
}
| mit | 801ca7a82b9145fa8ef907fd0ef7d48e | 19.157895 | 58 | 0.621037 | 3.057013 | false | true | false | false |
jozsef-vesza/algorithms | Swift/Algorithms.playground/Pages/Misc.xcplaygroundpage/Contents.swift | 1 | 2352 | //: [Previous](@previous)
let arr = [2, -2, 6, -6, 8]
func zeroSumArrayExists(input: [Int]) -> Bool {
var sums = [Int : Int]()
var sum = 0
for (index, num) in input.enumerate() {
sum += num
if input[index] == 0 || sum == 0 || sums[sum] != nil {
return true
}
sums[sum] = index
}
return false
}
func createSumArray(input: [Int]) -> [Int] {
let output = input.map { num -> Int in
let index = input.indexOf(num)!
var sum = 0
for i in 0 ... index {
sum += input[i]
}
return sum
}
return output
}
func numberOfZeroSums(input: [Int]) -> Int {
var numOfSums = 0
for j in 0 ..< input.count {
if input[j] == 0 {
numOfSums += 1
}
for k in j + 1 ..< input.count {
if input[k] == input[j] {
numOfSums += 1
}
}
}
return numOfSums
}
let result = zeroSumArrayExists(arr)
let sumArray = createSumArray(arr)
let numOfSums = numberOfZeroSums(sumArray)
let complexArr = [0,-9,-2,9,8,-3,9,-1,-6,1,-1,-6,8,-3,-10,-4,-8,8,6,6,-8,-10,-7,-10,-8,-6,4,3,8,-10,0,-3,-9,9,-4,9,-7,-8,-5,-3,3,3,-1,-2,10,0,4,-9,-3,0]
let complexCntains = zeroSumArrayExists(complexArr)
let complexSum = createSumArray(complexArr)
let complexNum = numberOfZeroSums(complexSum)
extension Int {
func factorial() -> Int {
if self == 0 {
return 1
}
return self * (self - 1).factorial()
}
}
0.factorial()
1.factorial()
2.factorial()
3.factorial()
4.factorial()
extension String {
func palindrome() -> Bool {
if characters.count < 2 {
return true
}
if characters.first == characters.last {
return String(characters[startIndex.successor() ..< endIndex.predecessor()]).palindrome()
}
return false
}
}
"rotor".palindrome()
"motor".palindrome()
extension Int {
func power(n: Int) -> Int {
if n == 0 {
return 1
}
return self * self.power(n - 1)
}
}
3.power(0)
3.power(2)
2.power(8)
//: [Next](@next)
| mit | 3399c5e4b68ee1aba1d4708dfdbe23ba | 17.519685 | 152 | 0.479592 | 3.526237 | false | false | false | false |
a2/passcards | Sources/Passcards/main.swift | 1 | 3072 | import Commander
import Foundation
import HeliumLogger
import Kitura
import MongoKitten
import PasscardsServer
import Shove
let databaseOption = Option("database", "mongodb://localhost:27017/passcards", flag: "d", description: "The MongoDB server and database (in valid connection string format)")
let keyPath = Option("key", "", flag: "k", description: "Path to the APNS token private key in .p8 format")
let passphrase = Option("passphrase", "", flag: "p", description: "Passphrase to decrypt the key file")
let keyID = Option("key-id", "", flag: "i", description: "The APNS token key ID as prescribed by Apple")
let teamID = Option("team-id", "", flag: "t", description: "The team ID for which the APNS token key was generated")
let updateToken = Option("update-token", "", flag: "u", description: "The authentication token to require for uploading or updating passes")
let port = Option("port", 8080, flag: "p", description: "The port on which to run the server")
enum PasscardsError: Error {
case invalidDatabaseURI
case badDatabaseCredentials
case missingKey
case invalidKeyCredentials
case invalidAPNSCredentials
}
let main = command(databaseOption, keyPath, passphrase, keyID, teamID, updateToken, port) { databaseURI, keyPath, passphrase, keyID, teamID, updateToken, port in
guard let urlComponents = URLComponents(string: databaseURI) else {
throw PasscardsError.invalidDatabaseURI
}
let authentication: (String, String, String)?
if let user = urlComponents.user, let password = urlComponents.password {
authentication = (user, password, "admin")
} else {
authentication = nil
}
let server = try Server(at: urlComponents.host!, port: UInt16(urlComponents.port ?? 27017), using: authentication, automatically: false)
let cwd = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
guard let keyURL = URL(string: keyPath, relativeTo: cwd) else {
throw PasscardsError.missingKey
}
guard let key = SigningKey(url: keyURL, passphrase: (!passphrase.isEmpty ? passphrase : nil)) else {
throw PasscardsError.invalidKeyCredentials
}
let jwtGenerator = JSONWebTokenGenerator(key: key, keyID: keyID, teamID: teamID)
let shoveClient = ShoveClient(tokenGenerator: jwtGenerator)
do {
try server.connect()
} catch {
throw PasscardsError.badDatabaseCredentials
}
var database = urlComponents.path
if database.hasPrefix("/") {
database = database.substring(from: database.index(after: database.startIndex))
}
let passcardsServer = PasscardsServer(database: server[database], shoveClient: shoveClient, updateToken: updateToken)
let router = Router()
router.all("pass", middleware: passcardsServer.vanityRouter)
router.all("web", middleware: passcardsServer.walletRouter)
router.all { request, response, next in
try response.send(status: .notFound).end()
}
HeliumLogger.use()
Kitura.addHTTPServer(onPort: port, with: router)
Kitura.run()
}
main.run()
| mit | a5385026b7e759b77e56ed740bf70e90 | 39.96 | 173 | 0.718424 | 4.254848 | false | false | false | false |
Pluto-tv/RxSwift | RxSwift/DataStructures/Bag.swift | 1 | 3185 | //
// Bag.swift
// Rx
//
// Created by Krunoslav Zaher on 2/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Class that enables using memory allocations as a means to uniquely identify objects.
*/
class Identity {
// weird things have known to happen with Swift
var _forceAllocation: Int32 = 0
}
/**
Unique identifier for object added to `Bag`.
*/
public struct BagKey : Equatable {
let uniqueIdentity: Identity?
let key: Int
}
/**
Compares two `BagKey`s.
*/
public func == (lhs: BagKey, rhs: BagKey) -> Bool {
return lhs.key == rhs.key && lhs.uniqueIdentity === rhs.uniqueIdentity
}
/**
Data structure that represents a bag of elements typed `T`.
Single element can be stored multiple times.
Time and space complexity of insertion an deletion is O(n).
It is suitable for storing small number of elements.
*/
public struct Bag<T> : CustomStringConvertible {
/**
Type of identifier for inserted elements.
*/
public typealias KeyType = BagKey
private typealias ScopeUniqueTokenType = Int
typealias Entry = (key: BagKey, value: T)
private var uniqueIdentity: Identity?
private var nextKey: ScopeUniqueTokenType = 0
var pairs = [Entry]()
/**
Creates new empty `Bag`.
*/
public init() {
}
/**
- returns: Bag description.
*/
public var description : String {
get {
return "\(self.count) elements in Bag"
}
}
/**
Inserts `value` into bag.
- parameter element: Element to insert.
- returns: Key that can be used to remove element from bag.
*/
public mutating func insert(element: T) -> BagKey {
nextKey = nextKey &+ 1
#if DEBUG
nextKey = nextKey % 20
#endif
if nextKey == 0 {
uniqueIdentity = Identity()
}
let key = BagKey(uniqueIdentity: uniqueIdentity, key: nextKey)
pairs.append(key: key, value: element)
return key
}
/**
- returns: Number of elements in bag.
*/
public var count: Int {
return pairs.count
}
/**
Removes all elements from bag and clears capacity.
*/
public mutating func removeAll() {
pairs.removeAll(keepCapacity: false)
}
/**
Removes element with a specific `key` from bag.
- parameter key: Key that identifies element to remove from bag.
- returns: Element that bag contained, or nil in case element was already removed.
*/
public mutating func removeKey(key: BagKey) -> T? {
for i in 0 ..< pairs.count {
if pairs[i].key == key {
let value = pairs[i].value
pairs.removeAtIndex(i)
return value
}
}
return nil
}
}
extension Bag {
/**
Enumerates elements inside the bag.
- parameter action: Enumeration closure.
*/
public func forEach(@noescape action: (T) -> Void) {
let pairs = self.pairs
for i in 0 ..< pairs.count {
action(pairs[i].value)
}
}
} | mit | cae42a520dfddb0ab97cdc8fe8b0b51a | 21.27972 | 86 | 0.588697 | 4.375 | false | false | false | false |
loganSims/wsdot-ios-app | wsdot/MountianPassItem.swift | 2 | 1825 | //
// MountianPassItem.swift
// WSDOT
//
// Copyright (c) 2016 Washington State Department of Transportation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
import RealmSwift
class MountainPassItem: Object {
@objc dynamic var id: Int = 0
@objc dynamic var name: String = ""
@objc dynamic var weatherCondition: String = ""
@objc dynamic var elevationInFeet: Int = 0
let temperatureInFahrenheit = RealmOptional<Int>()
@objc dynamic var travelAdvisoryActive: Bool = false
@objc dynamic var latitude: Double = 0.0
@objc dynamic var longitude: Double = 0.0
@objc dynamic var roadCondition: String = ""
@objc dynamic var dateUpdated: Date = Date(timeIntervalSince1970: 0)
@objc dynamic var restrictionOneText: String = ""
@objc dynamic var restrictionOneTravelDirection: String = ""
@objc dynamic var restrictionTwoText: String = ""
@objc dynamic var restrictionTwoTravelDirection: String = ""
@objc dynamic var selected: Bool = false
let cameraIds = List<PassCameraIDItem>()
let forecast = List<ForecastItem>()
@objc dynamic var delete: Bool = false
override static func primaryKey() -> String? {
return "id"
}
}
| gpl-3.0 | 93e281be57d988f9219b1e1a916ef1be | 37.020833 | 72 | 0.707945 | 4.244186 | false | false | false | false |
OpenStreetMap-Monitoring/OsMoiOs | iOsmo/SendingManager.swift | 2 | 5309 | //
// CoordinatesSender.swift
// iOsmo
//
// Created by Olga Grineva on 15/12/14.
// Copyright (c) 2014 Olga Grineva, (c) 2016 Alexey Sirotkin. All rights reserved.
//
//used lib from https://mikeash.com/pyblog/friday-qa-2015-01-23-lets-build-swift-notifications.html
import Foundation
import UIKit
open class SendingManager: NSObject{
let sentObservers = ObserverSet<LocationModel>()
fileprivate let connectionManager = ConnectionManager.sharedConnectionManager
public let locationTracker = LocationTracker()
fileprivate let log = LogQueue.sharedLogQueue
var onLocationUpdated : ObserverSetEntry<(LocationModel)>?
fileprivate var lcSendTimer: Timer?
let aSelector : Selector = #selector(SendingManager.sending)
fileprivate var onConnectionRun: ObserverSetEntry<(Int, String)>?
fileprivate var onSessionRun: ObserverSetEntry<(Int, String)>?
let sessionStarted = ObserverSet<(Int)>()
let sessionPaused = ObserverSet<(Int)>()
var lastLocations = [LocationModel]()
class var sharedSendingManager: SendingManager {
struct Static {
static let instance: SendingManager = SendingManager()
}
return Static.instance
}
override init(){
super.init()
self.onLocationUpdated = locationTracker.locationUpdated.add {
self.log.enqueue("SendingManager: onLocationUpdated")
if self.connectionManager.isGettingLocation {
self.connectionManager.sendCoordinate($0)
self.connectionManager.isGettingLocation = false
} else {
if self.connectionManager.sessionOpened {
self.connectionManager.sendCoordinates([$0])
}
self.sentObservers.notify($0)
}
}
}
open func startSendingCoordinates(_ once: Bool){
locationTracker.turnMonitorinOn(once: once) //start getting coordinates
if (once) {
return
}
if !connectionManager.connected {
self.onConnectionRun = connectionManager.connectionRun.add{
if $0.0 == 0{
self.onSessionRun = self.connectionManager.sessionRun.add{
if $0.0 == 0{
self.startSending()
}
}
self.connectionManager.openSession()
}
// unsubscribe because it is single event
if let onConRun = self.onConnectionRun {
self.connectionManager.connectionRun.remove(onConRun)
}
}
connectionManager.connect()
} else if !connectionManager.sessionOpened {
self.onSessionRun = self.connectionManager.sessionRun.add{
if ($0.0 == 0){
self.startSending()
} else {
//unsibscribe when stop monitoring
if let onSesRun = self.onSessionRun {
self.connectionManager.sessionRun.remove(onSesRun)
}
}
}
self.connectionManager.openSession()
} else {
startSending()
}
}
open func pauseSendingCoordinates(_ pause: Bool){
locationTracker.turnMonitoringOff()
if (pause) {
sessionPaused.notify((0))
}
UIApplication.shared.isIdleTimerDisabled = false
}
open func stopSendingCoordinates(){
pauseSendingCoordinates(false)
connectionManager.closeSession()
}
@objc open func sending(){
//MUST REFACTOR
if (connectionManager.sessionOpened || connectionManager.isGettingLocation) && connectionManager.connected {
let coors: [LocationModel] = locationTracker.getLastLocations()
log.enqueue("SendingManager: got \(coors.count) coordinates")
if coors.count > 0 {
log.enqueue("SendingManager: sending \(coors.count) coordinates")
if connectionManager.isGettingLocation {
self.connectionManager.sendCoordinate(coors[0])
}
if connectionManager.sessionOpened {
self.connectionManager.sendCoordinates(coors)
}
for c in coors {
//notify about all - because it draw on map
self.sentObservers.notify(c)
}
}
}
}
fileprivate func startSending(){
if (connectionManager.sessionOpened || connectionManager.isGettingLocation) {
log.enqueue("Sending Manager: start Sending")
//self.lcSendTimer?.invalidate()
//self.lcSendTimer = nil
//self.lcSendTimer = Timer.scheduledTimer(timeInterval: 0, target: self, selector: aSelector, userInfo: nil, repeats: true)
if connectionManager.sessionOpened {
sessionStarted.notify((0))
}
UIApplication.shared.isIdleTimerDisabled = true
}
}
}
| gpl-3.0 | a9cf1154efa13666c3295c6286e13509 | 33.251613 | 135 | 0.568845 | 5.330321 | false | false | false | false |
ztyjr888/WeChat | WeChat/Plugins/Chat/WeChatChatToolBar.swift | 1 | 9490 | //
// WeChatChatToolBar.swift
// WeChat
//
// Created by Smile on 16/3/29.
// Copyright © 2016年 [email protected]. All rights reserved.
//
import UIKit
extension UIColor {
public func hexStringToColor(hexString: String) -> UIColor{
var cString: String = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if cString.characters.count < 6 {return UIColor.blackColor()}
if cString.hasPrefix("0X") {cString = cString.substringFromIndex(cString.startIndex.advancedBy(2))}
if cString.hasPrefix("#") {cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))}
if cString.characters.count != 6 {return UIColor.blackColor()}
var range: NSRange = NSMakeRange(0, 2)
let rString = (cString as NSString).substringWithRange(range)
range.location = 2
let gString = (cString as NSString).substringWithRange(range)
range.location = 4
let bString = (cString as NSString).substringWithRange(range)
var r: UInt32 = 0x0
var g: UInt32 = 0x0
var b: UInt32 = 0x0
NSScanner.init(string: rString).scanHexInt(&r)
NSScanner.init(string: gString).scanHexInt(&g)
NSScanner.init(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(1))
}
}
//聊天窗口询问toolbar
class WeChatChatToolBar: UIView {
var textView: UITextView!
var voiceButton: UIButton!
var emotionButton: UIButton!
var moreButton: UIButton!
var recordButton: UIButton!
convenience init(taget: UIViewController, voiceSelector: Selector, recordSelector: Selector, emotionSelector: Selector, moreSelector: Selector) {
self.init()
//backgroundColor = UIColor().hexStringToColor("D8EBF2")
backgroundColor = UIColor.whiteColor()
voiceButton = UIButton(type: .Custom)
voiceButton.setImage(UIImage(named: "ToolViewInputVoice"), forState: .Normal)
voiceButton.setImage(UIImage(named: "ToolViewInputVoiceHL"), forState: .Highlighted)
voiceButton.addTarget(taget, action: voiceSelector, forControlEvents: .TouchUpInside)
self.addSubview(voiceButton)
textView = InputTextView()
textView.font = UIFont.systemFontOfSize(17)
textView.layer.borderColor = UIColor().hexStringToColor("DADADA").CGColor
textView.layer.borderWidth = 1
textView.layer.cornerRadius = 5.0
textView.scrollsToTop = false
textView.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5)
//textView.backgroundColor = UIColor().hexStringToColor("f8fefb")
textView.returnKeyType = .Send
self.addSubview(textView)
emotionButton = UIButton(type: .Custom)
emotionButton.tag = 1
emotionButton.setImage(UIImage(named: "ToolViewEmotion"), forState: .Normal)
emotionButton.setImage(UIImage(named: "ToolViewEmotionHL"), forState: .Highlighted)
emotionButton.addTarget(taget, action: emotionSelector, forControlEvents: .TouchUpInside)
self.addSubview(emotionButton)
moreButton = UIButton(type: .Custom)
moreButton.tag = 2
moreButton.setImage(UIImage(named: "TypeSelectorBtn_Black"), forState: .Normal)
moreButton.setImage(UIImage(named: "TypeSelectorBtnHL_Black"), forState: .Highlighted)
moreButton.addTarget(taget, action: moreSelector, forControlEvents: .TouchUpInside)
self.addSubview(moreButton)
recordButton = UIButton(type: .Custom)
recordButton.setTitle("按住 说话", forState: .Normal)
recordButton.titleLabel?.font = UIFont.systemFontOfSize(14.0)
recordButton.setBackgroundImage(UIImage.imageWithColor(UIColor.whiteColor()), forState: .Normal)
recordButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
recordButton.addTarget(taget, action: recordSelector, forControlEvents: .TouchDown)
recordButton.layer.borderColor = UIColor().hexStringToColor("DADADA").CGColor
recordButton.layer.cornerRadius = 5.0
recordButton.layer.masksToBounds = true
recordButton.hidden = true
self.addSubview(recordButton)
voiceButton.translatesAutoresizingMaskIntoConstraints = false
textView.translatesAutoresizingMaskIntoConstraints = false
emotionButton.translatesAutoresizingMaskIntoConstraints = false
moreButton.translatesAutoresizingMaskIntoConstraints = false
self.addConstraint(NSLayoutConstraint(item: voiceButton, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 5))
self.addConstraint(NSLayoutConstraint(item: voiceButton, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 5))
self.addConstraint(NSLayoutConstraint(item: textView, attribute: .Left, relatedBy: .Equal, toItem: voiceButton, attribute: .Right, multiplier: 1, constant: 5))
self.addConstraint(NSLayoutConstraint(item: textView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 5))
textView.addConstraint(NSLayoutConstraint(item: textView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 35.0))
self.addConstraint(NSLayoutConstraint(item: textView, attribute: .Right, relatedBy: .Equal, toItem: emotionButton, attribute: .Left, multiplier: 1, constant: -5))
self.addConstraint(NSLayoutConstraint(item: emotionButton, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 5))
self.addConstraint(NSLayoutConstraint(item: emotionButton, attribute: .Right, relatedBy: .Equal, toItem: moreButton, attribute: .Left, multiplier: 1, constant: -5))
self.addConstraint(NSLayoutConstraint(item: moreButton, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: -5))
self.addConstraint(NSLayoutConstraint(item: moreButton, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 5))
createLineOnTop()
}
//MARKS: 顶部画线
func createLineOnTop(){
let shape = WeChatDrawView().drawLine(beginPointX: 0, beginPointY: 0, endPointX: UIScreen.mainScreen().bounds.width, endPointY: 0,color:UIColor(red: 153/255, green: 153/255, blue: 153/255, alpha: 1))
shape.lineWidth = 0.2
self.layer.addSublayer(shape)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func showRecord(show: Bool) {
if show {
recordButton.hidden = false
recordButton.frame = textView.frame
recordButton.layer.borderWidth = 1
textView.hidden = true
recordButton.setTitle("按住 说话", forState: .Normal)
recordButton.titleLabel?.font = UIFont.boldSystemFontOfSize(16)
recordButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
voiceButton.setImage(UIImage(named: "ToolViewKeyboard"), forState: .Normal)
voiceButton.setImage(UIImage(named: "ToolViewKeyboardHL"), forState: .Highlighted)
showEmotion(false)
showMore(false)
} else {
recordButton.hidden = true
textView.hidden = false
textView.inputView = nil
voiceButton.setImage(UIImage(named: "ToolViewInputVoice"), forState: .Normal)
voiceButton.setImage(UIImage(named: "ToolViewInputVoiceHL"), forState: .Highlighted)
}
}
internal func showEmotion(show: Bool) {
if show {
emotionButton.tag = 0
emotionButton.setImage(UIImage(named: "ToolViewKeyboard"), forState: .Normal)
emotionButton.setImage(UIImage(named: "ToolViewKeyboardHL"), forState: .Highlighted)
showRecord(false)
showMore(false)
} else {
emotionButton.tag = 1
textView.inputView = nil
emotionButton.setImage(UIImage(named: "ToolViewEmotion"), forState: .Normal)
emotionButton.setImage(UIImage(named: "ToolViewEmotionHL"), forState: .Highlighted)
}
}
internal func showMore(show: Bool) {
if show {
moreButton.tag = 3
showRecord(false)
showEmotion(false)
} else {
textView.inputView = nil
moreButton.tag = 2
}
}
}
// only show copy action when editing textview
class InputTextView: UITextView {
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if (delegate as! WeChatChatViewController).tableView.indexPathForSelectedRow != nil {
return action == "copyAction:"
} else {
return super.canPerformAction(action, withSender: sender)
}
}
func copyAction(menuController: UIMenuController) {
(delegate as! WeChatChatViewController).copyAction(menuController)
}
}
| apache-2.0 | 4e7dc914cb6591ca9f4386bbafcec7a8 | 45.328431 | 207 | 0.669136 | 4.742097 | false | false | false | false |
gautierdelorme/JPOINSA-beacons | JPOINSA/PresentationManager.swift | 1 | 3364 | //
// PresentationManager.swift
// JPOINSA
//
// Created by Gautier Delorme on 26/01/16.
// Copyright © 2016 gautierdelorme. All rights reserved.
//
import UIKit
class PresentationManager: NSObject, UITableViewDataSource {
static let sharedInstance = PresentationManager()
let presentations: [String:[Presentation]]
private override init() {
presentations = [
"firstFloor": [
Presentation(title: "Club Robot", place: "Local du club", image: "robot.jpg", summary: "Le club robot réunit chaque année une quinzaine d'étudiants qui participent à la Coupe de France de Robotique organisée par Planètes Sciences, avec chaque année sur un nouveau cahier des charges en combinant leur savoir-faire."),
Presentation(title: "Équipe TIM", place: "Hall du GEI", image: "tim.jpg", summary: "Equipe TIM (Toulouse Ingénierie Multidisciplinaire), association étudiante, dont la mission est de relever des défis technologiques en développant et optimisant des véhicules les plus économes en énergie possible. En ligne de mire : l’Educ-Eco et le Shell Eco-Marathon, pour se confronter à plus de 200 équipes du monde entier!")
],
"secondFloor": [
Presentation(title: "Démonstration réseaux", place: "Salle 101", image: "network.jpg", summary: ""),
Presentation(title: "Innovative Smart Systems", place: "Salle 105", image: "iot.jpg", summary: "Sécurité de l'Internet des Objets, dans le cadre de la 5ème année Innovative Smart Systems."),
Presentation(title: "Démonstration en informatique embarquée et électronique", place: "Salle 111", image: "embedded-systems.jpg", summary: "")
],
"thirdFloor": [
Presentation(title: "Bâtiment ADREAM", place: "Salle 213", image: "adream.jpg", summary: "Présentation de la recherche au LAAS/CNRS: maquette du bâtiment ADREAM"),
Presentation(title: "Démonstration 4x4 et projets drones", place: "Salle 213", image: "drone.jpg", summary: ""),
Presentation(title: "Démonstration automatique", place: "Salle 224", image: "automatic.jpg", summary: "")
]
]
}
func floor(floor: String) -> [Presentation] {
return presentations[floor]!
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let currentRegion = BeaconManager.sharedInstance.currentRegion else {
return 0
}
return floor(currentRegion.identifier).count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier(PresentationCell.ReuseIdentifier, forIndexPath: indexPath) as? PresentationCell else {
fatalError("unexpected cell dequeued from tableView")
}
guard let currentRegion = BeaconManager.sharedInstance.currentRegion else {
fatalError("currentRegion does not exist")
}
cell.presentation = floor(currentRegion.identifier)[indexPath.row]
return cell
}
}
| mit | 0076fdacdc5f11d18a17fc333b5ae1bd | 51.857143 | 429 | 0.673273 | 4.08589 | false | false | false | false |
cezheng/Fuzi | Sources/NodeSet.swift | 3 | 3328 | // NodeSet.swift
// Copyright (c) 2015 Ce Zheng
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import libxml2
/// An enumerable set of XML nodes
open class NodeSet: Collection {
// Index type for `Indexable` protocol
public typealias Index = Int
// IndexDistance type for `Indexable` protocol
public typealias IndexDistance = Int
fileprivate var cursor = 0
open func next() -> XMLElement? {
defer {
cursor += 1
}
if cursor < self.count {
return self[cursor]
}
return nil
}
/// Number of nodes
open fileprivate(set) lazy var count: Int = {
return Int(self.cNodeSet?.pointee.nodeNr ?? 0)
}()
/// First Element
open var first: XMLElement? {
return count > 0 ? self[startIndex] : nil
}
/// if nodeset is empty
open var isEmpty: Bool {
return (cNodeSet == nil) || (cNodeSet!.pointee.nodeNr == 0) || (cNodeSet!.pointee.nodeTab == nil)
}
/// Start index
open var startIndex: Index {
return 0
}
/// End index
open var endIndex: Index {
return count
}
/**
Get the Nth node from set.
- parameter idx: node index
- returns: the idx'th node, nil if out of range
*/
open subscript(_ idx: Index) -> XMLElement {
precondition(idx >= startIndex && idx < endIndex, "Index of out bound")
return XMLElement(cNode: (cNodeSet!.pointee.nodeTab[idx])!, document: document)
}
/**
Get the index after `idx`
- parameter idx: node index
- returns: the index after `idx`
*/
open func index(after idx: Index) -> Index {
return idx + 1
}
internal let cNodeSet: xmlNodeSetPtr?
internal let document: XMLDocument!
internal init(cNodeSet: xmlNodeSetPtr?, document: XMLDocument?) {
self.cNodeSet = cNodeSet
self.document = document
}
}
/// XPath selector result node set
open class XPathNodeSet: NodeSet {
/// Empty node set
public static let emptySet = XPathNodeSet(cXPath: nil, document: nil)
fileprivate var cXPath: xmlXPathObjectPtr?
internal init(cXPath: xmlXPathObjectPtr?, document: XMLDocument?) {
self.cXPath = cXPath
let nodeSet = cXPath?.pointee.nodesetval
super.init(cNodeSet: nodeSet, document: document)
}
deinit {
if cXPath != nil {
xmlXPathFreeObject(cXPath)
}
}
}
| mit | ed4441944deb3b39441a957834abab7c | 26.733333 | 101 | 0.689603 | 4.234097 | false | false | false | false |
SoneeJohn/WWDC | WWDC/ImageDownloadCenter.swift | 1 | 7202 | //
// ImageDownloadOperation.swift
// JPEG Core
//
// Created by Guilherme Rambo on 09/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RealmSwift
typealias ImageDownloadCompletionBlock = (_ sourceURL: URL, _ original: NSImage?, _ thumbnail: NSImage?) -> Void
final class ImageDownloadCenter {
static let shared: ImageDownloadCenter = ImageDownloadCenter()
private let cacheProvider = ImageCacheProvider()
private let queue = OperationQueue()
func downloadImage(from url: URL, thumbnailHeight: CGFloat, thumbnailOnly: Bool = false, completion: @escaping ImageDownloadCompletionBlock) -> Operation? {
if let cache = cacheProvider.cacheEntity(for: url) {
var original: NSImage?
if !thumbnailOnly {
original = NSImage(data: cache.original)
}
let thumb = NSImage(data: cache.thumbnail)
original?.cacheMode = .never
thumb?.cacheMode = .never
completion(url, original, thumb)
return nil
}
guard !hasActiveOperation(for: url) else { return nil }
let operation = ImageDownloadOperation(url: url, cache: cacheProvider, thumbnailHeight: thumbnailHeight)
operation.imageCompletionHandler = completion
queue.addOperation(operation)
return operation
}
func hasActiveOperation(for url: URL) -> Bool {
return queue.operations.contains { op in
guard let op = op as? ImageDownloadOperation else { return false }
return op.url == url && op.isExecuting
}
}
}
final class ImageCacheEntity: Object {
@objc dynamic var key: String = ""
@objc dynamic var createdAt: Date = Date()
@objc dynamic var original: Data = Data()
@objc dynamic var thumbnail: Data = Data()
override class func primaryKey() -> String {
return "key"
}
}
private final class ImageCacheProvider {
private var originalCaches: [URL: URL] = [:]
private var thumbCaches: [URL: URL] = [:]
private let upperLimit = 16 * 1024 * 1024
private func makeRealm() -> Realm? {
let filePath = PathUtil.appSupportPath + "/ImageCache.realm"
var realmConfig = Realm.Configuration(fileURL: URL(fileURLWithPath: filePath))
realmConfig.objectTypes = [ImageCacheEntity.self]
realmConfig.schemaVersion = 1
realmConfig.migrationBlock = { _, _ in }
return try? Realm(configuration: realmConfig)
}
private lazy var realm: Realm? = {
return self.makeRealm()
}()
func cacheEntity(for url: URL) -> ImageCacheEntity? {
return realm?.object(ofType: ImageCacheEntity.self, forPrimaryKey: url.absoluteString)
}
func cacheImage(for key: URL, original: Data?, thumbnail: Data?) {
guard let original = original, let thumbnail = thumbnail else { return }
guard original.count < upperLimit, thumbnail.count < upperLimit else { return }
DispatchQueue.global(qos: .utility).async {
autoreleasepool {
guard let bgRealm = self.makeRealm() else { return }
let entity = ImageCacheEntity()
entity.key = key.absoluteString
entity.original = original
entity.thumbnail = thumbnail
do {
try bgRealm.write {
bgRealm.add(entity, update: true)
}
bgRealm.invalidate()
} catch {
NSLog("Error saving cached image: \(error)")
}
}
}
}
}
private final class ImageDownloadOperation: Operation {
var imageCompletionHandler: ImageDownloadCompletionBlock?
let url: URL
let thumbnailHeight: CGFloat
let cacheProvider: ImageCacheProvider
init(url: URL, cache: ImageCacheProvider, thumbnailHeight: CGFloat = 1.0) {
self.url = url
cacheProvider = cache
self.thumbnailHeight = thumbnailHeight
}
open override var isAsynchronous: Bool {
return true
}
internal var _executing = false {
willSet {
willChangeValue(forKey: "isExecuting")
}
didSet {
didChangeValue(forKey: "isExecuting")
}
}
open override var isExecuting: Bool {
return _executing
}
internal var _finished = false {
willSet {
willChangeValue(forKey: "isFinished")
}
didSet {
didChangeValue(forKey: "isFinished")
}
}
open override var isFinished: Bool {
return _finished
}
override func start() {
_executing = true
URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
guard let welf = self else { return }
guard !welf.isCancelled else { return }
guard let data = data, let httpResponse = response as? HTTPURLResponse, error == nil else {
DispatchQueue.main.async { welf.imageCompletionHandler?(welf.url, nil, nil) }
welf._executing = false
welf._finished = true
return
}
guard httpResponse.statusCode == 200 else {
DispatchQueue.main.async { welf.imageCompletionHandler?(welf.url, nil, nil) }
welf._executing = false
welf._finished = true
return
}
guard data.count > 0 else {
DispatchQueue.main.async { welf.imageCompletionHandler?(welf.url, nil, nil) }
welf._executing = false
welf._finished = true
return
}
guard let originalImage = NSImage(data: data) else {
DispatchQueue.main.async { welf.imageCompletionHandler?(welf.url, nil, nil) }
welf._executing = false
welf._finished = true
return
}
guard !welf.isCancelled else { return }
let thumbnailImage = originalImage.resized(to: welf.thumbnailHeight)
originalImage.cacheMode = .never
thumbnailImage.cacheMode = .never
DispatchQueue.main.async {
welf.imageCompletionHandler?(welf.url, originalImage, thumbnailImage)
}
welf.cacheProvider.cacheImage(for: welf.url, original: data, thumbnail: thumbnailImage.tiffRepresentation)
welf._executing = false
welf._finished = true
}.resume()
}
}
private extension NSImage {
func resized(to maxHeight: CGFloat) -> NSImage {
let scaleFactor = maxHeight / size.height
let newWidth = size.width * scaleFactor
let newHeight = size.height * scaleFactor
let resizedImage = NSImage(size: NSSize(width: newWidth, height: newHeight))
resizedImage.lockFocus()
draw(in: NSRect(x: 0, y: 0, width: newWidth, height: newHeight))
resizedImage.unlockFocus()
return resizedImage
}
}
| bsd-2-clause | ea45ad410187c9f08cf1c1f210b8f9d5 | 28.391837 | 160 | 0.591307 | 4.993759 | false | false | false | false |
JudoPay/JudoKit | Source/Transaction.swift | 1 | 16240 | //
// Transaction.swift
// Judo
//
// Copyright (c) 2016 Alternative Payments Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CoreLocation
import PassKit
/// intended for subclassing paths
public protocol TransactionPath {
/// path variable made for subclassing
static var path: String { get }
}
/// intended for classes that can be queried for lists
public protocol SessionProtocol {
/// the current API Session
var APISession: Session? { get set }
/**
a method to set the API session in a fluent way
- parameter session: the session to set
- returns: Self
*/
func apiSession(_ session: Session) -> Self
/**
designated initializer
- returns: an instance of the receiving type
*/
init()
}
/// Superclass Helper for Payment, Pre-auth and RegisterCard
open class Transaction: SessionProtocol {
/// The current transaction if there is one - for preventing multiple transactions running at the same time
fileprivate var currentTransactionReference: String? = nil
internal var parameters = [String:AnyObject]();
/// The current Session to access the Judo API
open var APISession: Session?
/// The judo ID for the transaction
open fileprivate (set) var judoId: String {
didSet {
self.parameters["judoId"] = judoId as AnyObject?
}
}
/// The reference of the transaction
open fileprivate (set) var reference: Reference {
didSet {
self.parameters["yourConsumerReference"] = reference.yourConsumerReference as AnyObject?
self.parameters["yourPaymentReference"] = reference.yourPaymentReference as AnyObject?
if let metaData = reference.yourPaymentMetaData {
self.parameters["yourPaymentMetaData"] = metaData as AnyObject?
}
}
}
/// The amount and currency of the transaction
open fileprivate (set) var amount: Amount? {
didSet {
guard let amount = amount else { return }
self.parameters["amount"] = amount.amount
self.parameters["currency"] = amount.currency.rawValue as AnyObject?
}
}
/// The card info of the transaction
open fileprivate (set) var card: Card? {
didSet {
self.parameters["cardNumber"] = card?._number as AnyObject?
self.parameters["expiryDate"] = card?.expiryDate as AnyObject?
self.parameters["cv2"] = card?._securityCode as AnyObject?
self.parameters["cardAddress"] = card?.address?.dictionaryRepresentation()
self.parameters["startDate"] = card?.startDate as AnyObject?
self.parameters["issueNumber"] = card?.issueNumber as AnyObject?
}
}
/// The payment token of the transaction
open fileprivate (set) var payToken: PaymentToken? {
didSet {
self.parameters["consumerToken"] = payToken?.consumerToken as AnyObject?
self.parameters["cardToken"] = payToken?.cardToken as AnyObject?
self.parameters["cv2"] = payToken?.cv2 as AnyObject?
}
}
/// Device identification for this transaction
open fileprivate (set) var deviceSignal: JSONDictionary? {
didSet {
self.parameters["clientDetails"] = deviceSignal as AnyObject?
}
}
/// Mobile number of the entity initiating the transaction
open fileprivate (set) var mobileNumber: String? {
didSet {
self.parameters["mobileNumber"] = mobileNumber as AnyObject?
}
}
/// Email address of the entity initiating the transaction
open fileprivate (set) var emailAddress: String? {
didSet {
self.parameters["emailAddress"] = emailAddress as AnyObject?
}
}
/// Support for Apple Pay transactions added in Base
open fileprivate (set) var pkPayment: PKPayment? {
didSet {
guard let pkPayment = pkPayment else { return }
var tokenDict = JSONDictionary()
if #available(iOS 9.0, *) {
tokenDict["paymentInstrumentName"] = pkPayment.token.paymentMethod.displayName as AnyObject?
} else {
tokenDict["paymentInstrumentName"] = pkPayment.token.paymentInstrumentName as AnyObject?
}
if #available(iOS 9.0, *) {
tokenDict["paymentNetwork"] = pkPayment.token.paymentMethod.network as AnyObject?
} else {
tokenDict["paymentNetwork"] = pkPayment.token.paymentNetwork as AnyObject?
}
do {
tokenDict["paymentData"] = try JSONSerialization.jsonObject(with: pkPayment.token.paymentData, options: JSONSerialization.ReadingOptions.mutableLeaves) as? JSONDictionary as AnyObject?
} catch {
// Allow empty paymentData on simulator for test cards
#if !(arch(i386) || arch(x86_64)) && (os(iOS) || os(watchOS) || os(tvOS))
return
#endif
}
self.parameters["pkPayment"] = ["token":tokenDict] as AnyObject?
}
}
/// Support for Visa Checkout payments
open fileprivate (set) var vcoResult: VCOResult? {
didSet {
guard let vcoResult = vcoResult else { return }
var walletDict = JSONDictionary()
walletDict["callid"] = vcoResult.callId as AnyObject?
walletDict["encryptedKey"] = vcoResult.encryptedKey as AnyObject?
walletDict["encryptedPaymentData"] = vcoResult.encryptedPaymentData as AnyObject?
self.parameters["wallet"] = walletDict as AnyObject?
}
}
/// hidden parameter to enable recurring payments
open fileprivate (set) var initialRecurringPayment: Bool = false {
didSet {
self.parameters["InitialRecurringPayment"] = initialRecurringPayment as AnyObject?
}
}
/**
Starting point and a reactive method to create a payment or pre-auth
- Parameter judoId: the number (e.g. "123-456" or "654321") identifying the Merchant you wish to pay - has to be between 6 and 10 characters and luhn-valid
- Parameter amount: The amount to process
- Parameter reference: the reference
- Throws: JudoIDInvalidError judoId does not match the given length or is not luhn valid
*/
public init(judoId: String, amount: Amount?, reference: Reference) throws {
self.judoId = judoId
self.amount = amount
self.reference = reference
self.parameters["judoId"] = judoId as AnyObject?
self.parameters["yourConsumerReference"] = reference.yourConsumerReference as AnyObject?
self.parameters["yourPaymentReference"] = reference.yourPaymentReference as AnyObject?
if let metaData = reference.yourPaymentMetaData {
self.parameters["yourPaymentMetaData"] = metaData as AnyObject?
}
if let amount = amount {
self.parameters["amount"] = amount.amount
self.parameters["currency"] = amount.currency.rawValue as AnyObject?
}
// judo ID validation
let strippedJudoID = judoId.stripped
if !strippedJudoID.isLuhnValid() {
throw JudoError(.luhnValidationError)
}
if kJudoIDLenght ~= strippedJudoID.count {
self.judoId = strippedJudoID
} else {
throw JudoError(.judoIDInvalidError)
}
}
/**
Internal initializer for the purpose of creating an instance for listing payments or preAuths
*/
public required init() {
self.judoId = ""
self.amount = nil
self.reference = Reference(consumerRef: "")!
}
/**
If making a card payment, add the details here
- Parameter card: a card object containing the information from which to make a payment
- Returns: reactive self
*/
@discardableResult open func card(_ card: Card) -> Self {
self.card = card
return self
}
/**
If a card payment or a card registration has been previously made, add the token to make a repeat payment
- Parameter token: a token-string from a previous payment or registration
- Returns: reactive self
*/
@discardableResult open func paymentToken(_ token: PaymentToken) -> Self {
self.payToken = token
return self
}
/**
Reactive method to set device signal information of the device, this method is optional and is used for fraud prevention
- Parameter deviceSignal: a Dictionary which contains information about the device
- Returns: reactive self
*/
@discardableResult open func deviceSignal(_ deviceSignal: JSONDictionary) -> Self {
self.deviceSignal = deviceSignal
return self
}
/**
Reactive method to set contact information of the user such as mobile number and email address, this method is optional
- Parameter mobileNumber: a mobile number String
- Parameter emailAddress: an email address String
- Returns: reactive self
*/
@discardableResult open func contact(_ mobileNumber : String?, _ emailAddress : String? = nil) -> Self {
self.mobileNumber = mobileNumber
self.emailAddress = emailAddress
return self
}
/**
For creating an Apple Pay Transaction, use this method to add the PKPayment object
- Parameter payment: the PKPayment object
- Returns: reactive self
*/
@discardableResult open func pkPayment(_ payment: PKPayment) -> Self {
self.pkPayment = payment
return self
}
/**
For creating an Visa Checkout Transaction, use this method to add the VCOResult object
- Parameter vcoResult: the VCOResult object
- Returns: reactive self
*/
@discardableResult open func vcoResult(_ vcoResult: VCOResult) -> Self {
self.vcoResult = vcoResult
return self
}
/**
apiSession caller - this method sets the session variable and returns itself for further use
- Parameter session: the API session which is used to call the Judo endpoints
- Returns: reactive self
*/
@discardableResult open func apiSession(_ session: Session) -> Self {
self.APISession = session
return self
}
/**
Completion caller - this method will automatically trigger a Session Call to the judo REST API and execute the request based on the information that were set in the previous methods
- Parameter block: a completion block that is called when the request finishes
- Returns: reactive self
- Throws: ParameterError one or more of the given parameters were in the incorrect format or nil
- Throws: CardAndTokenError multiple methods of payment have been provided, please make sure to only provide one method
- Throws: CardOrTokenMissingError no method of transaction was provided, please provide either a card, paymentToken, PKPayment or VCOResult
- Throws: AmountMissingError no amount has been provided
- Throws: DuplicateTransactionError please provide a new Reference object if this transaction is not a duplicate
*/
@discardableResult open func completion(_ block: @escaping JudoCompletionBlock) throws -> Self {
if self.card != nil && self.payToken != nil {
throw JudoError(.cardAndTokenError)
} else if self.card == nil && self.payToken == nil && self.pkPayment == nil && self.vcoResult == nil {
throw JudoError(.cardOrTokenMissingError)
}
if !(type(of: self) == RegisterCard.self) && !(type(of: self) == SaveCard.self) && self.amount == nil {
throw JudoError(.amountMissingError)
}
if self.reference.yourPaymentReference == self.currentTransactionReference {
throw JudoError(.duplicateTransactionError)
}
self.currentTransactionReference = self.reference.yourPaymentReference
self.APISession?.POST(self.path(), parameters: self.parameters, completion: block)
return self
}
/**
threeDSecure call - this method will automatically trigger a Session Call to the judo REST API and execute the finalizing 3DS call on top of the information that had been sent in the previous methods
- Parameter dictionary: the dictionary that contains all the information from the 3DS UIWebView Request
- Parameter receiptId: the receipt for the given Transaction
- Parameter block: a completion block that is called when the request finishes
- Returns: reactive self
*/
@discardableResult open func threeDSecure(_ dictionary: JSONDictionary, receiptId: String, block: @escaping JudoCompletionBlock) -> Self {
var paymentDetails = JSONDictionary()
if let paRes = dictionary["PaRes"] as? String {
paymentDetails["PaRes"] = paRes as AnyObject?
}
if let md = dictionary["MD"] as? String {
paymentDetails["md"] = md as AnyObject?
}
paymentDetails["receiptId"] = receiptId as AnyObject?
self.APISession?.PUT("transactions/" + receiptId, parameters: paymentDetails, completion: block)
return self
}
/**
This method will return a list of transactions, filtered to just show the payment or preAuth transactions. The method will show the first 10 items in a Time Descending order
See [List all transactions](<https://www.judopay.com/docs/v4_1/restful-api/api-reference/#transactions>) for more information.
- Parameter block: a completion block that is called when the request finishes
*/
open func list(_ block: @escaping JudoCompletionBlock) {
self.list(nil, block: block)
}
/**
This method will return a list of transactions, filtered to just show the payment or pre-auth transactions.
See [List all transactions](<https://www.judopay.com/docs/v4_1/restful-api/api-reference/#transactions>) for more information.
- Parameter pagination: The offset, number of items and order in which to return the items
- Parameter block: a completion block that is called when the request finishes
*/
open func list(_ pagination: Pagination?, block: @escaping JudoCompletionBlock) {
var path = self.path()
if let pag = pagination {
path = path + "?pageSize=\(pag.pageSize)&offset=\(pag.offset)&sort=\(pag.sort.rawValue)"
}
self.APISession?.GET(path, parameters: nil, completion: block)
}
/**
Helper method for extensions of this class to be able to access the dynamic path value
:returns: the rest api access path of the current class
*/
open func path() -> String {
return (type(of: self) as! TransactionPath.Type).path
}
}
| mit | 766a010aa2b06379c398971329d72ac1 | 36.505774 | 203 | 0.649261 | 5.003081 | false | false | false | false |
gribozavr/swift | test/Constraints/patterns.swift | 2 | 10775 | // RUN: %target-typecheck-verify-swift
// Leaf expression patterns are matched to corresponding pieces of a switch
// subject (TODO: or ~= expression) using ~= overload resolution.
switch (1, 2.5, "three") {
case (1, _, _):
()
// Double is ExpressibleByIntegerLiteral
case (_, 2, _),
(_, 2.5, _),
(_, _, "three"):
()
// ~= overloaded for (Range<Int>, Int)
case (0..<10, _, _),
(0..<10, 2.5, "three"),
(0...9, _, _),
(0...9, 2.5, "three"):
()
default:
()
}
switch (1, 2) {
case (var a, a): // expected-error {{use of unresolved identifier 'a'}}
()
}
// 'is' patterns can perform the same checks that 'is' expressions do.
protocol P { func p() }
class B : P {
init() {}
func p() {}
func b() {}
}
class D : B {
override init() { super.init() }
func d() {}
}
class E {
init() {}
func e() {}
}
struct S : P {
func p() {}
func s() {}
}
// Existential-to-concrete.
var bp : P = B()
switch bp {
case is B,
is D,
is S:
()
case is E:
()
default:
()
}
switch bp {
case let b as B:
b.b()
case let d as D:
d.b()
d.d()
case let s as S:
s.s()
case let e as E:
e.e()
default:
()
}
// Super-to-subclass.
var db : B = D()
switch db {
case is D:
()
case is E: // expected-warning {{always fails}}
()
default:
()
}
// Raise an error if pattern productions are used in expressions.
var b = var x // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
// TODO: Bad recovery in these cases. Although patterns are never valid
// expr-unary productions, it would be good to parse them anyway for recovery.
//var e = 2 + var y
//var e = var y + 2
// 'E.Case' can be used in a dynamic type context as an equivalent to
// '.Case as E'.
protocol HairType {}
enum MacbookHair: HairType {
case HairSupply(S)
}
enum iPadHair<T>: HairType {
case HairForceOne
}
enum Watch {
case Sport, Watch, Edition
}
let hair: HairType = MacbookHair.HairSupply(S())
switch hair {
case MacbookHair.HairSupply(let s):
s.s()
case iPadHair<S>.HairForceOne:
()
case iPadHair<E>.HairForceOne:
()
case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'HairType'}}
()
case Watch.Edition: // expected-warning {{cast from 'HairType' to unrelated type 'Watch' always fails}}
()
case .HairForceOne: // expected-error{{type 'HairType' has no member 'HairForceOne'}}
()
default:
break
}
// <rdar://problem/19382878> Introduce new x? pattern
switch Optional(42) {
case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}}
case nil: break
}
func SR2066(x: Int?) {
// nil literals should still work when wrapped in parentheses
switch x {
case (nil): break
case _?: break
}
switch x {
case ((nil)): break
case _?: break
}
switch (x, x) {
case ((nil), _): break
case (_?, _): break
}
}
// Test x???? patterns.
switch (nil as Int???) {
case let x???: print(x, terminator: "")
case let x??: print(x as Any, terminator: "")
case let x?: print(x as Any, terminator: "")
case 4???: break
case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
default: break
}
switch ("foo" as String?) {
case "what": break
default: break
}
// Test some value patterns.
let x : Int?
extension Int {
func method() -> Int { return 42 }
}
func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs
}
switch 4 as Int? {
case x?.method(): break // match value
default: break
}
switch 4 {
case x ?? 42: break // match value
default: break
}
for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}}
for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}}
for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}}
var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}}
let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}}
// Crash when re-typechecking EnumElementPattern.
// FIXME: This should actually type-check -- the diagnostics are bogus. But
// at least we don't crash anymore.
protocol PP {
associatedtype E
}
struct A<T> : PP {
typealias E = T
}
extension PP {
func map<T>(_ f: (Self.E) -> T) -> T {}
}
enum EE {
case A
case B
}
func good(_ a: A<EE>) -> Int {
return a.map {
switch $0 {
case .A:
return 1
default:
return 2
}
}
}
func bad(_ a: A<EE>) {
a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{none}}
let _: EE = $0
return 1
}
}
func ugly(_ a: A<EE>) {
a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{none}}
switch $0 {
case .A:
return 1
default:
return 2
}
}
}
// SR-2057
enum SR2057 {
case foo
}
let sr2057: SR2057?
if case .foo = sr2057 { } // Ok
// Invalid 'is' pattern
class SomeClass {}
if case let doesNotExist as SomeClass:AlsoDoesNotExist {}
// expected-error@-1 {{use of undeclared type 'AlsoDoesNotExist'}}
// expected-error@-2 {{variable binding in a condition requires an initializer}}
// `.foo` and `.bar(...)` pattern syntax should also be able to match
// static members as expr patterns
struct StaticMembers: Equatable {
init() {}
init(_: Int) {}
init?(opt: Int) {}
static var prop = StaticMembers()
static var optProp: Optional = StaticMembers()
static func method(_: Int) -> StaticMembers { return prop }
// expected-note@-1 {{found candidate with type '(Int) -> StaticMembers'}}
static func method(withLabel: Int) -> StaticMembers { return prop }
// expected-note@-1 {{found candidate with type '(Int) -> StaticMembers'}}
static func optMethod(_: Int) -> StaticMembers? { return optProp }
static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true }
}
let staticMembers = StaticMembers()
let optStaticMembers: Optional = StaticMembers()
switch staticMembers {
case .init: break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}}
case .init(opt:): break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}}
case .init(): break
case .init(0): break
case .init(_): break // expected-error{{'_' can only appear in a pattern}}
case .init(let x): break // expected-error{{cannot appear in an expression}}
case .init(opt: 0): break // expected-error{{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}}
// expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
// expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}}
case .prop: break
// TODO: repeated error message
case .optProp: break // expected-error* {{not unwrapped}}
case .method: break // expected-error{{no exact matches in call to static method 'method'}}
case .method(0): break
case .method(_): break // expected-error{{'_' can only appear in a pattern}}
case .method(let x): break // expected-error{{cannot appear in an expression}}
case .method(withLabel:): break // expected-error{{member 'method(withLabel:)' expects argument of type 'Int'}}
case .method(withLabel: 0): break
case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}}
case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}}
case .optMethod: break // expected-error{{member 'optMethod' expects argument of type 'Int'}}
case .optMethod(0): break
// expected-error@-1 {{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}}
// expected-note@-2 {{coalesce}}
// expected-note@-3 {{force-unwrap}}
}
_ = 0
// rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining
struct S_32241441 {
enum E_32241441 {
case foo
case bar
}
var type: E_32241441 = E_32241441.foo
}
func rdar32241441() {
let s: S_32241441? = S_32241441()
switch s?.type { // expected-error {{switch must be exhaustive}} expected-note {{add missing case: '.none'}}
case .foo: // Ok
break;
case .bar: // Ok
break;
}
}
// SR-6100
struct One<Two> {
public enum E: Error {
// if you remove associated value, everything works
case SomeError(String)
}
}
func testOne() {
do {
} catch let error { // expected-warning{{'catch' block is unreachable because no errors are thrown in 'do' block}}
if case One.E.SomeError = error {} // expected-error{{generic enum type 'One.E' is ambiguous without explicit generic parameters when matching value of type 'Error'}}
}
}
// SR-8347
// constrain initializer expressions of optional some pattern bindings to be optional
func test8347() -> String {
struct C {
subscript (s: String) -> String? {
return ""
}
subscript (s: String) -> [String] {
return [""]
}
func f() -> String? {
return ""
}
func f() -> Int {
return 3
}
func g() -> String {
return ""
}
func h() -> String {
return ""
}
func h() -> Double {
return 3.0
}
func h() -> Int? { //expected-note{{found this candidate}}
return 2
}
func h() -> Float? { //expected-note{{found this candidate}}
return nil
}
}
let c = C()
if let s = c[""] {
return s
}
if let s = c.f() {
return s
}
if let s = c.g() { //expected-error{{initializer for conditional binding must have Optional type, not 'String'}}
return s
}
if let s = c.h() { //expected-error{{ambiguous use of 'h()'}}
return s
}
}
enum SR_7799 {
case baz
case bar
}
let sr7799: SR_7799? = .bar
switch sr7799 {
case .bar?: break // Ok
case .baz: break // Ok
default: break
}
let sr7799_1: SR_7799?? = .baz
switch sr7799_1 {
case .bar?: break // Ok
case .baz: break // Ok
default: break
}
if case .baz = sr7799_1 {} // Ok
if case .bar? = sr7799_1 {} // Ok
| apache-2.0 | d771d11eaa75d287434040d275d4cea7 | 23.770115 | 208 | 0.63536 | 3.597663 | false | false | false | false |
fdstevex/FrameX | FrameX/FrameX/FacebookFrames.swift | 1 | 5135 | //
// FacebookFrames.swift
//
// This is a wrapper for the Facebook set of device frames, and the offsets.json file that's included
// with them. You can find these on Github here:
//
// https://github.com/fastlane/frameit-frames (mirrored https://github.com/fdstevex/frameit-frames)
//
// Created by Steve Tibbett on 2016-12-27.
// Copyright © 2016 Fall Day Software Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
import Foundation
import CoreGraphics
import AppKit
/**
* Class to parse the Facebook device frames.
* Currently expects the downloaded frames to be at deviceFramesPath
*/
struct FacebookFrames {
struct OffsetInfo {
// Device key from the offsets.png, for example, "iPhone 6s"
let deviceName: String
// Offset from frame origin where the screenshot shoudl be placed
let offset: CGSize
// Width of the screenshot (height would be proportional)
let width: CGFloat
}
struct FrameInfo {
// Path to the device frame PNG
let frameURL:URL
// Offset information for this frame
let offsetInfo: OffsetInfo
}
var frames = [FrameInfo]()
init(deviceFramesPath: String) throws {
let relativePath = deviceFramesPath
let resolvedPath = NSString(string: relativePath).expandingTildeInPath
let offsets = try readOffsets(path: resolvedPath)
frames = try correlateFiles(path: resolvedPath, offsets: offsets)
}
// Correlate the files on disk with the entries in the offsets.json file.
func correlateFiles(path: String, offsets: [OffsetInfo]) throws -> [FrameInfo] {
let framesURL = URL(fileURLWithPath: path)
let fileNames = try FileManager.default.contentsOfDirectory(atPath: framesURL.path)
var frames = [FrameInfo]()
for fileName in fileNames {
let imageURL = framesURL.appendingPathComponent(fileName)
if FileManager.default.fileExists(atPath:imageURL.path) {
// Use a substring match to find the OffsetInfo
let baseName = imageURL.lastPathComponent
for offsetInfo in offsets {
if baseName.range(of: offsetInfo.deviceName) != nil {
let frameInfo = FrameInfo(frameURL: imageURL, offsetInfo: offsetInfo)
frames.append(frameInfo)
}
}
}
}
return frames
}
func readOffsets(path: String) throws -> [OffsetInfo] {
let frames = try readFrames(path: path)
return try parseOffsets(path: path, frameDict: frames)
}
func parseOffsets(path: String, frameDict: [String: Any]) throws -> [OffsetInfo] {
let offsets = try readFrames(path: path)
var frames = [OffsetInfo]()
for key in offsets.keys {
if let dict = offsets[key] as? [String: AnyObject] {
if let offsetString = dict["offset"] as? String {
if let width = dict["width"] as? NSNumber {
let offsetComponents = offsetString.components(separatedBy: "+")
let offsetx = (offsetComponents[1] as NSString).floatValue
let offsety = (offsetComponents[2] as NSString).floatValue
let offset = CGSize(width: CGFloat(offsetx), height: CGFloat(offsety))
let frame = OffsetInfo(deviceName: key, offset: offset, width: CGFloat(width))
frames.append(frame)
}
}
}
}
return frames
}
// Read the JSON offset file, return a [String: Dictionary] where the dictionary looks
// like this:
// "iPhone SE": {
// "offset": "+64+237",
// "width": 640
// }
func readFrames(path: String) throws -> [String: Any] {
let jsonPath = URL(fileURLWithPath: path).appendingPathComponent("offsets.json")
let data = try Data.init(contentsOf: jsonPath)
let json = try? JSONSerialization.jsonObject(with: data, options: [])
if let root = json as? [String: Any] {
if let portrait = root["portrait"] as? [String: Any] {
return portrait
} else {
throw NSError()
}
} else {
throw NSError()
}
}
}
| mit | 9e2b8d01978123376c83d010e0b09ce4 | 36.202899 | 102 | 0.59739 | 4.798131 | false | false | false | false |
ahoppen/swift | test/IRGen/big_types_corner_cases.swift | 2 | 16783 | // XFAIL: CPU=powerpc64le
// XFAIL: CPU=s390x
// RUN: %target-swift-frontend -disable-type-layout %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
// REQUIRES: optimized_stdlib
// UNSUPPORTED: CPU=powerpc64le
public struct BigStruct {
var i0 : Int32 = 0
var i1 : Int32 = 1
var i2 : Int32 = 2
var i3 : Int32 = 3
var i4 : Int32 = 4
var i5 : Int32 = 5
var i6 : Int32 = 6
var i7 : Int32 = 7
var i8 : Int32 = 8
}
func takeClosure(execute block: () -> Void) {
}
class OptionalInoutFuncType {
private var lp : BigStruct?
private var _handler : ((BigStruct?, Error?) -> ())?
func execute(_ error: Error?) {
var p : BigStruct?
var handler: ((BigStruct?, Error?) -> ())?
takeClosure {
p = self.lp
handler = self._handler
self._handler = nil
}
handler?(p, error)
}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} i32 @main(i32 %0, i8** %1)
// CHECK: call void @llvm.lifetime.start
// CHECK: call void @llvm.memcpy
// CHECK: call void @llvm.lifetime.end
// CHECK: ret i32 0
let bigStructGlobalArray : [BigStruct] = [
BigStruct()
]
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal swiftcc void @"$s22big_types_corner_cases21OptionalInoutFuncTypeC7executeyys5Error_pSgFyyXEfU_"(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}) %0, %T22big_types_corner_cases21OptionalInoutFuncTypeC* %1, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_Sg* nocapture dereferenceable({{.*}})
// CHECK: call void @"$s22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_SgWOe
// CHECK: call void @"$s22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_SgWOy
// CHECK: ret void
public func f1_returns_BigType(_ x: BigStruct) -> BigStruct {
return x
}
public func f2_returns_f1() -> (_ x: BigStruct) -> BigStruct {
return f1_returns_BigType
}
public func f3_uses_f2() {
let x = BigStruct()
let useOfF2 = f2_returns_f1()
let _ = useOfF2(x)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10f3_uses_f2yyF"()
// CHECK: call swiftcc void @"$s22big_types_corner_cases9BigStructVACycfC"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret({{.*}})
// CHECK: call swiftcc { i8*, %swift.refcounted* } @"$s22big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF"()
// CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructV* noalias nocapture sret({{.*}}) {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK: ret void
public func f4_tuple_use_of_f2() {
let x = BigStruct()
let tupleWithFunc = (f2_returns_f1(), x)
let useOfF2 = tupleWithFunc.0
let _ = useOfF2(x)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18f4_tuple_use_of_f2yyF"()
// CHECK: [[TUPLE:%.*]] = call swiftcc { i8*, %swift.refcounted* } @"$s22big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF"()
// CHECK: [[TUPLE_EXTRACT:%.*]] = extractvalue { i8*, %swift.refcounted* } [[TUPLE]], 0
// CHECK: [[CAST_EXTRACT:%.*]] = bitcast i8* [[TUPLE_EXTRACT]] to void (%T22big_types_corner_cases9BigStructV*, %T22big_types_corner_cases9BigStructV*, %swift.refcounted*)*
// CHECK: call swiftcc void [[CAST_EXTRACT]](%T22big_types_corner_cases9BigStructV* noalias nocapture sret({{.*}}) {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself %{{.*}})
// CHECK: ret void
public class BigClass {
public init() {
}
public var optVar: ((BigStruct)-> Void)? = nil
func useBigStruct(bigStruct: BigStruct) {
optVar!(bigStruct)
}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases8BigClassC03useE6Struct0aH0yAA0eH0V_tF"(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %T22big_types_corner_cases8BigClassC* swiftself %1)
// CHECK: [[BITCAST:%.*]] = bitcast i8* {{.*}} to void (%T22big_types_corner_cases9BigStructV*, %swift.refcounted*)*
// CHECK: call swiftcc void [[BITCAST]](%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %swift.refcounted* swiftself
// CHECK: ret void
public struct MyStruct {
public let a: Int
public let b: String?
}
typealias UploadFunction = ((MyStruct, Int?) -> Void) -> Void
func takesUploader(_ u: UploadFunction) { }
class Foo {
func blam() {
takesUploader(self.myMethod) // crash compiling this
}
func myMethod(_ callback: (MyStruct, Int) -> Void) -> Void { }
}
// CHECK-LABEL: define internal swiftcc void @"$s22big_types_corner_cases3FooC4blamyyFyyAA8MyStructV_SitXEcACcfu_yyAF_SitXEcfu0_"(i8* %0, %swift.opaque* %1, %T22big_types_corner_cases3FooC* %2)
public enum LargeEnum {
public enum InnerEnum {
case simple(Int64)
case hard(Int64, String?, Int64)
}
case Empty1
case Empty2
case Full(InnerEnum)
}
public func enumCallee(_ x: LargeEnum) {
switch x {
case .Full(let inner): print(inner)
case .Empty1: break
case .Empty2: break
}
}
// CHECK-64-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10enumCalleeyyAA9LargeEnumOF"(%T22big_types_corner_cases9LargeEnumO* noalias nocapture dereferenceable({{.*}}) %0) #0 {
// CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO05InnerF0O
// CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO
// CHECK-64: $ss5print_9separator10terminatoryypd_S2StF
// CHECK-64: ret void
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal swiftcc void @"$s22big_types_corner_cases8SuperSubC1fyyFAA9BigStructVycfU_"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret({{.*}}) %0, %T22big_types_corner_cases8SuperSubC* %1)
// CHECK-64: [[ALLOC1:%.*]] = alloca %T22big_types_corner_cases9BigStructV
// CHECK-64: [[ALLOC2:%.*]] = alloca %T22big_types_corner_cases9BigStructV
// CHECK-64: [[ALLOC3:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg
// CHECK-64: call swiftcc void @"$s22big_types_corner_cases9SuperBaseC4boomAA9BigStructVyF"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret({{.*}}) [[ALLOC1]], %T22big_types_corner_cases9SuperBaseC* swiftself {{.*}})
// CHECK: ret void
class SuperBase {
func boom() -> BigStruct {
return BigStruct()
}
}
class SuperSub : SuperBase {
override func boom() -> BigStruct {
return BigStruct()
}
func f() {
let _ = {
nil ?? super.boom()
}
}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10MUseStructV16superclassMirrorAA03BigF0VSgvg"(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret({{.*}}) %0, %T22big_types_corner_cases10MUseStructV* noalias nocapture swiftself dereferenceable({{.*}}) %1)
// CHECK: [[ALLOC:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg
// CHECK: [[LOAD:%.*]] = load %swift.refcounted*, %swift.refcounted** %.callInternalLet.data
// CHECK: call swiftcc void %{{[0-9]+}}(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret({{.*}}) [[ALLOC]], %swift.refcounted* swiftself [[LOAD]])
// CHECK: ret void
public struct MUseStruct {
var x = BigStruct()
public var superclassMirror: BigStruct? {
return callInternalLet()
}
internal let callInternalLet: () -> BigStruct?
}
// CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18stringAndSubstringSS_s0G0VtyF"(<{ %TSS, %Ts9SubstringV }>* noalias nocapture sret({{.*}}) %0) #0 {
// CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18stringAndSubstringSS_s0G0VtyF"(<{ %TSS, [4 x i8], %Ts9SubstringV }>* noalias nocapture sret({{.*}}) %0) #0 {
// CHECK: alloca %TSs
// CHECK: alloca %TSs
// CHECK: ret void
public func stringAndSubstring() -> (String, Substring) {
let s = "Hello, World"
let a = Substring(s).dropFirst()
return (s, a)
}
func bigStructGet() -> BigStruct {
return BigStruct()
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases11testGetFuncyyF"()
// CHECK: ret void
public func testGetFunc() {
let testGetPtr: @convention(thin) () -> BigStruct = bigStructGet
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases7TestBigC4testyyF"(%T22big_types_corner_cases7TestBigC* swiftself %0)
// CHECK: [[CALL1:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$sSayy22big_types_corner_cases9BigStructVcSgGMD"
// CHECK: [[CALL2:%.*]] = call i8** @"$sSayy22big_types_corner_cases9BigStructVcSgGSayxGSlsWl
// CHECK: call swiftcc void @"$sSlsE10firstIndex5where0B0QzSgSb7ElementQzKXE_tKF"(%swift.opaque* noalias nocapture sret({{.*}}) %{{[0-9]+}}, i8* bitcast ({{.*}}* @"$s22big_types_corner_cases7TestBig{{.*}}" to i8*), %swift.opaque* null, %swift.type* %{{[0-9]+}}, i8** [[CALL2]]
class TestBig {
typealias Handler = (BigStruct) -> Void
func test() {
let arr = [Handler?]()
let d = arr.firstIndex(where: { _ in true })
}
func test2() {
let arr: [(ID: String, handler: Handler?)] = []
for (_, handler) in arr {
takeClosure {
handler?(BigStruct())
}
}
}
}
struct BigStructWithFunc {
var incSize : BigStruct
var foo: ((BigStruct) -> Void)?
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases20UseBigStructWithFuncC5crashyyF"(%T22big_types_corner_cases20UseBigStructWithFuncC* swiftself %0)
// CHECK: call swiftcc void @"$s22big_types_corner_cases20UseBigStructWithFuncC10callMethod
// CHECK: ret void
class UseBigStructWithFunc {
var optBigStructWithFunc: BigStructWithFunc?
func crash() {
guard let bigStr = optBigStructWithFunc else { return }
callMethod(ptr: bigStr.foo)
}
private func callMethod(ptr: ((BigStruct) -> Void)?) -> () {
}
}
struct BiggerString {
var str: String
var double: Double
}
struct LoadableStructWithBiggerString {
public var a1: BiggerString
public var a2: [String]
public var a3: [String]
}
class ClassWithLoadableStructWithBiggerString {
public func f() -> LoadableStructWithBiggerString {
return LoadableStructWithBiggerString(a1: BiggerString(str:"", double:0.0), a2: [], a3: [])
}
}
//===----------------------------------------------------------------------===//
// SR-8076
//===----------------------------------------------------------------------===//
public typealias sr8076_Filter = (BigStruct) -> Bool
public protocol sr8076_Query {
associatedtype Returned
}
public protocol sr8076_ProtoQueryHandler {
func forceHandle_1<Q: sr8076_Query>(query: Q) -> Void
func forceHandle_2<Q: sr8076_Query>(query: Q) -> (Q.Returned, BigStruct?)
func forceHandle_3<Q: sr8076_Query>(query: Q) -> (Q.Returned, sr8076_Filter?)
func forceHandle_4<Q: sr8076_Query>(query: Q) throws -> (Q.Returned, sr8076_Filter?)
}
public protocol sr8076_QueryHandler: sr8076_ProtoQueryHandler {
associatedtype Handled: sr8076_Query
func handle_1(query: Handled) -> Void
func handle_2(query: Handled) -> (Handled.Returned, BigStruct?)
func handle_3(query: Handled) -> (Handled.Returned, sr8076_Filter?)
func handle_4(query: Handled) throws -> (Handled.Returned, sr8076_Filter?)
}
public extension sr8076_QueryHandler {
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_15queryyqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %1)
// CHECK: call swiftcc void {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK: ret void
func forceHandle_1<Q: sr8076_Query>(query: Q) -> Void {
guard let body = handle_1 as? (Q) -> Void else {
fatalError("handler \(self) is expected to handle query \(query)")
}
body(query)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_25query8ReturnedQyd___AA9BigStructVSgtqd___tAA0e1_F0Rd__lF"(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret({{.*}}) %0, %swift.opaque* noalias nocapture %1, %swift.opaque* noalias nocapture %2, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %3)
// CHECK: [[ALLOC:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg
// CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret({{.*}}) [[ALLOC]], %swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK: ret void
func forceHandle_2<Q: sr8076_Query>(query: Q) -> (Q.Returned, BigStruct?) {
guard let body = handle_2 as? (Q) -> (Q.Returned, BigStruct?) else {
fatalError("handler \(self) is expected to handle query \(query)")
}
return body(query)
}
// CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc { i64, i64 } @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_35query8ReturnedQyd___SbAA9BigStructVcSgtqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.opaque* noalias nocapture %1, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %2)
// CHECK-64: {{.*}} = call swiftcc { i64, i64 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK-64: ret { i64, i64 }
// CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc { i32, i32} @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_35query8ReturnedQyd___SbAA9BigStructVcSgtqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.opaque* noalias nocapture %1, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %2)
// CHECK-32: {{.*}} = call swiftcc { i32, i32 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}})
// CHECK-32: ret { i32, i32 }
func forceHandle_3<Q: sr8076_Query>(query: Q) -> (Q.Returned, sr8076_Filter?) {
guard let body = handle_3 as? (Q) -> (Q.Returned, sr8076_Filter?) else {
fatalError("handler \(self) is expected to handle query \(query)")
}
return body(query)
}
// CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc { i64, i64 } @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_45query8ReturnedQyd___SbAA9BigStructVcSgtqd___tKAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.opaque* noalias nocapture %1, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %2, %swift.error** swifterror %3)
// CHECK-64: {{.*}} = call swiftcc { i64, i64 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}, %swift.error** noalias nocapture swifterror {{.*}})
// CHECK-64: ret { i64, i64 }
// CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc { i32, i32} @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_45query8ReturnedQyd___SbAA9BigStructVcSgtqd___tKAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.opaque* noalias nocapture %1, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself %2, %swift.error** swifterror %3)
// CHECK-32: {{.*}} = call swiftcc { i32, i32 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}, %swift.error** noalias nocapture {{.*}})
// CHECK-32: ret { i32, i32 }
func forceHandle_4<Q: sr8076_Query>(query: Q) throws -> (Q.Returned, sr8076_Filter?) {
guard let body = handle_4 as? (Q) throws -> (Q.Returned, sr8076_Filter?) else {
fatalError("handler \(self) is expected to handle query \(query)")
}
return try body(query)
}
}
public func foo() -> Optional<(a: Int?, b: Bool, c: (Int?)->BigStruct?)> {
return nil
}
public func dontAssert() {
let _ = foo()
}
| apache-2.0 | 218e605146906bee90da6175a8b103f6 | 47.646377 | 492 | 0.667878 | 3.472584 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Views/Chat/New Chat/Cells/ImageCell.swift | 1 | 3043 | //
// ImageMessageCell.swift
// Rocket.Chat
//
// Created by Rafael Streit on 01/10/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
import RocketChatViewController
import FLAnimatedImage
final class ImageCell: BaseImageMessageCell, SizingCell {
static let identifier = String(describing: ImageCell.self)
static let sizingCell: UICollectionViewCell & ChatCell = {
guard let cell = ImageCell.instantiateFromNib() else {
return ImageCell()
}
return cell
}()
@IBOutlet weak var labelDescriptionTopConstraint: NSLayoutConstraint!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var imageView: FLAnimatedImageView! {
didSet {
imageView.layer.cornerRadius = 4
imageView.layer.borderWidth = 1
imageView.clipsToBounds = true
}
}
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelDescription: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
setupWidthConstraint()
insertGesturesIfNeeded(with: nil)
}
override func configure(completeRendering: Bool) {
guard let viewModel = viewModel?.base as? ImageMessageChatItem else {
return
}
widthConstriant.constant = messageWidth
labelTitle.text = viewModel.title
if let description = viewModel.descriptionText, !description.isEmpty {
labelDescription.text = description
labelDescriptionTopConstraint.constant = 10
} else {
labelDescription.text = ""
labelDescriptionTopConstraint.constant = 0
}
if completeRendering {
loadImage(on: imageView, startLoadingBlock: { [weak self] in
self?.activityIndicator.startAnimating()
}, stopLoadingBlock: { [weak self] in
self?.activityIndicator.stopAnimating()
})
}
}
// MARK: IBAction
@IBAction func buttonImageHandlerDidPressed(_ sender: Any) {
guard
let viewModel = viewModel?.base as? ImageMessageChatItem,
let imageURL = viewModel.imageURL
else {
return
}
delegate?.openImageFromCell(url: imageURL, thumbnail: imageView)
}
override func handleLongPressMessageCell(recognizer: UIGestureRecognizer) {
guard
let viewModel = viewModel?.base as? BaseMessageChatItem,
let managedObject = viewModel.message?.managedObject?.validated()
else {
return
}
delegate?.handleLongPressMessageCell(managedObject, view: contentView, recognizer: recognizer)
}
}
extension ImageCell {
override func applyTheme() {
super.applyTheme()
let theme = self.theme ?? .light
labelTitle.textColor = theme.bodyText
labelDescription.textColor = theme.bodyText
imageView.layer.borderColor = theme.borderColor.cgColor
}
}
| mit | 8dbf2c33856a3deb0cbad5cdae4f6d69 | 27.971429 | 102 | 0.646285 | 5.51087 | false | false | false | false |
KlubJagiellonski/pola-ios | BuyPolish/Pola/Manager/KeyboardManager/NotificationCenterKeyboardManager.swift | 1 | 2627 | import UIKit
final class NotificationCenterKeyboardManager: KeyboardManager {
weak var delegate: KeyboardManagerDelegate?
private let notificationCenter: NotificationCenter
private var notificationTokens = [NSObjectProtocol]()
init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
}
deinit {
turnOff()
}
func turnOn() {
guard notificationTokens.isEmpty else {
return
}
let willShownToken =
notificationCenter.addObserver(forName: UIResponder.keyboardWillShowNotification,
object: nil,
queue: .main,
using: { self.keyboardWillShow(notification: $0) })
let willHideToken =
notificationCenter.addObserver(forName: UIResponder.keyboardWillHideNotification,
object: nil,
queue: .main,
using: { self.keyboardWillHide(notification: $0) })
notificationTokens.append(contentsOf: [willShownToken, willHideToken])
}
func turnOff() {
notificationTokens.forEach { self.notificationCenter.removeObserver($0) }
notificationTokens.removeAll()
}
private func keyboardWillHide(notification: Notification) {
guard let userInfo = notification.userInfo,
let animationOptions = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt,
let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else {
return
}
delegate?.keyboardWillHide(animationDuration: animationDuration,
animationOptions: .init(rawValue: animationOptions))
}
private func keyboardWillShow(notification: Notification) {
guard let userInfo = notification.userInfo,
let keyboardRect = userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect,
let animationOptions = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt,
let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else {
return
}
delegate?.keyboardWillShow(height: keyboardRect.size.height,
animationDuration: animationDuration,
animationOptions: .init(rawValue: animationOptions))
}
}
| gpl-2.0 | 6ff223b530446574db923250d176d20f | 41.370968 | 120 | 0.618576 | 6.96817 | false | false | false | false |
codeOfRobin/eSubziiOS | eSubzi/signupViewController.swift | 1 | 2401 | import UIKit
import Alamofire
import SwiftyJSON
class SignUpViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBAction func signUp(sender: AnyObject)
{
let parameters = ["email":emailTextField.text!,"password":passwordTextField.text!]
print(passwordTextField.text)
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.setNeedsStatusBarAppearanceUpdate()
Alamofire.request(.POST, API().signupURL, parameters: parameters).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(json["token"].string, forKeyPath: "token")
defaults.synchronize()
self.performSegueWithIdentifier("successSignUp", sender: self)
}
case .Failure(let error):
print(NSString(data: response.data!, encoding: NSUTF8StringEncoding))
print(error)
}
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle
{
return .LightContent
}
override func viewDidLoad()
{
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
if let _ = defaults.valueForKey("token")
{
self.performSegueWithIdentifier("successSignUp", sender: self)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print("yay")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | a4b18039d690a2521b8fa0de74445858 | 33.797101 | 111 | 0.627239 | 5.813559 | false | false | false | false |
frootloops/swift | stdlib/public/SDK/Foundation/NSString.swift | 1 | 4089 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
//===----------------------------------------------------------------------===//
// Strings
//===----------------------------------------------------------------------===//
@available(*, unavailable, message: "Please use String or NSString")
public class NSSimpleCString {}
@available(*, unavailable, message: "Please use String or NSString")
public class NSConstantString {}
// Called by the SwiftObject implementation.
public func _convertStringToNSString(_ string: String) -> NSString {
return string._bridgeToObjectiveC()
}
extension NSString : ExpressibleByStringLiteral {
/// Create an instance initialized to `value`.
public required convenience init(stringLiteral value: StaticString) {
var immutableResult: NSString
if value.hasPointerRepresentation {
immutableResult = NSString(
bytesNoCopy: UnsafeMutableRawPointer(mutating: value.utf8Start),
length: Int(value.utf8CodeUnitCount),
encoding: value.isASCII ? String.Encoding.ascii.rawValue : String.Encoding.utf8.rawValue,
freeWhenDone: false)!
} else {
var uintValue = value.unicodeScalar
immutableResult = NSString(
bytes: &uintValue,
length: 4,
encoding: String.Encoding.utf32.rawValue)!
}
self.init(string: immutableResult as String)
}
}
extension NSString : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to prevent infinite recursion trying to bridge
// AnyHashable to NSObject.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
// Consistently use Swift equality and hashing semantics for all strings.
return AnyHashable(self as String)
}
}
extension NSString {
public convenience init(format: NSString, _ args: CVarArg...) {
// We can't use withVaList because 'self' cannot be captured by a closure
// before it has been initialized.
let va_args = getVaList(args)
self.init(format: format as String, arguments: va_args)
}
public convenience init(
format: NSString, locale: Locale?, _ args: CVarArg...
) {
// We can't use withVaList because 'self' cannot be captured by a closure
// before it has been initialized.
let va_args = getVaList(args)
self.init(format: format as String, locale: locale, arguments: va_args)
}
public class func localizedStringWithFormat(
_ format: NSString, _ args: CVarArg...
) -> Self {
return withVaList(args) {
self.init(format: format as String, locale: Locale.current, arguments: $0)
}
}
public func appendingFormat(_ format: NSString, _ args: CVarArg...)
-> NSString {
return withVaList(args) {
self.appending(NSString(format: format as String, arguments: $0) as String) as NSString
}
}
}
extension NSMutableString {
public func appendFormat(_ format: NSString, _ args: CVarArg...) {
return withVaList(args) {
self.append(NSString(format: format as String, arguments: $0) as String)
}
}
}
extension NSString {
/// Returns an `NSString` object initialized by copying the characters
/// from another given string.
///
/// - Returns: An `NSString` object initialized by copying the
/// characters from `aString`. The returned object may be different
/// from the original receiver.
@nonobjc
public convenience init(string aString: NSString) {
self.init(string: aString as String)
}
}
extension NSString : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(self as String)
}
}
| apache-2.0 | ae1bc71e0d760ac3f2dc9ed869671112 | 33.361345 | 97 | 0.652971 | 4.833333 | false | false | false | false |
oisdk/Swift-at-Artsy | Informed/Lesson Three/Lesson Three.playground/Contents.swift | 4 | 13564 | //: # Lesson Three
//:
//: Welcome back! [In the previous lesson](https://github.com/orta/Swift-at-Artsy/tree/master/Informed/Lesson%20Two), we took a look through _a lot_ of stuff. We covered structs and classes, including the differences between the two. We learnt that structs are value types and classes are reference types, and how this affects Swift constant references declared with `let`. We also took a look at Swift enums, associated values on enums, and tuples. Finally, we looked at generics and got an idea of how they let us write abstract data structures.
//:
//: This time, we're going to take a look at some of the cool higher order stuff Swift lets us do. We're going to look at closures and treating code as data, then look at lazily-loading properties for efficiency and style, and wrap up with protocols. We'll even briefly touch on generics.
//:
//: ## Closures
//:
//: A "closure" is a difficult term to define precisely because to different people, the term connotes different ideas and different amounts of precision. For _this_ lesson, we're going to define closures as code that is can be referred to and invoked, but that _isn't_ a function.
//:
//: Closures have a place in most modern programming languages, even if they're called by a different name. For example, Javascript has anonymous functions.
//:
//: `var a = function() {`
//:
//: ` console.log("hi!");`
//:
//: `}`
//:
//: `a();`
//:
//: Ruby has blocks and closures, with slightly different semantics, and Python has anonymous functions. Until OS X 10.6 and iOS 4, Objective-C developers didn't have _any_ concept of closures beyond C function pointers. This made things difficult.
//:
//: Not so with Swift. Closures have been an integral part of the Swift language since day one, and have seen them advance since then.
//:
//: A closure is very easy to use in Swift. The simplest example is this:
let c = { print("hi!") }
//: `c` is a constant that refers to a closure. The _type_ of `c` is `() -> ()`. This means it takes no arguments and has no return value. We can invoke `c` the way you'd normally invoke a function:
c()
let p = { (thing: String) -> () in
print(thing)
}
p("hi!")
//: With `c`, we omitted the explicit parameter/return type specification. They're assumed to be empty if not specified.
//:
//: And of course, we can return a value from a closure.
let double = { (thing: String) -> String in
return "\(thing) \(thing)"
}
double("hi!")
//: Neat!
//:
//: (Notice that the syntax for the parameters and return types of a closure look eerily similar to tuples with labels. Spooky.)
//:
//: But that can be defined as a function just as easily as a closure. What benefit do closures have?
//:
//: Well, the thing is that closures and functions are pretty much _the same thing_. We can actually [define a function within another function](https://github.com/artsy/eidolon/blob/f22a7a0d5b338e8d934f0d4fdca2de51d07e367f/Kiosk/Sale%20Artwork%20Details/SaleArtworkDetailsViewController.swift#L76-L98) instead of a closure. However, the benefit of closures is that you can declare them _inline_. We'll see more of that momentarily.
//:
//: Often times, closures are used to execute code more than once. Take the following example.
let range = 0..<10
range.forEach({ (number: Int) -> () in
print(number)
})
//: (Note: I had to define `range` in a constant because `0..<10.forEach` introduces problems with operator precedence.)
//:
//: The `forEach` function is defined on the `Range` type (sort of, we'll talk about that later). `forEach` takes a closure as a parameter and invokes it – once for every element in the range. It passes the element into the closure as a parameter, which we define as `number`.
//:
//: Swift knows that we call functions like `forEach` _a lot_, and it tries to make this easier for us by letting us omit the parentheses around the closure definition.
range.forEach { (number: Int) -> () in
print(number)
}
//: _Way_ cool. But we can do even better.
//:
//: Since the parameter type for `forEach` is known to the compiler, it's able to infer the number and type of the arguments passed into the closure. This lets us refer to them by index instead of name. The following is semantically identical.
range.forEach { print($0) }
//: Neat! Another great function that takes a closure is `map`. This closure is passed in each element, just like `forEach`, but it has a _generic return value_. The return values for each invocation are used to make a new array that `map` returns.
range.map { return "\($0)" }
//: This returns an array of `String`s, zero through to nine. This convention is so common that for single-expression closures, Swift will infer the `return` statement.
range.map { "\($0)" }
//: A great use of closures is in the `reduce` function. This is a function that reduces a series of things into just one thing. For example, it can take a range of numbers and turn it into just one number. Or just one string or whatever – the series of things and what they're reduced to don't need to be the same type.
//:
//: If we wanted to sum the numbers from 0 to 10, we could use `reduce`.
let sum = (0...10).reduce(0, combine: { $0 + $1} )
//: And remember, `sum`'s type is inferred by the compiler. How cool is that!
//:
//: What's even more cool is that the type of the closure we used is `(Int, Int) -> Int`. Since closures and functions are interchangeable, I could pass in a function that adds two numbers.
func add(lhs: Int, rhs: Int) -> Int { return lhs + rhs }
(0...10).reduce(0, combine: add)
//: This seems like _way_ too much work. Luckily, Swift has a built-in `add` function called `+`.
(0...10).reduce(0, combine: +)
//: Reduce is good for more than just summing, though. The following will return the largest value in the array:
[5,1,88, 3, -100, 44].reduce(Int.min, combine: max)
//: We could also use closures to sort things:
[5,1,88, 3, -100, 44].sort(<)
//: Closures are a powerful tool that let programmers refer to executed code as data – parameters to be passed in to other functions and other closures. As we'll see over the next few lessons, they are used extensively throughout Swift.
//:
//: Now that we've taken a look at closures, let's take a break and discuss efficiency.
//:
//: ## Lazy Loading
//:
//: A _lazy_ variable is one that doesn't have its value set until it is first accessed. That means if it is set to a type that get initialized, that initialization will be delayed until the lazy variable is first read from.
//:
//: This is valuable when you have a resource-intensive thing that shouldn't be created before it's used. For example, an image that takes up a lot of RAM (which is scarce on iPhones), or a complex computation that takes several seconds to execute.
//:
//: (Note: all global variables are lazy to avoid consuming too many at app startup, probably.)
//:
//: Of course, the downside of lazy properties is that they delay execution of code that could be done before its needed. It's a balance that's up to each coder in each circumstance.
//:
//: You _could_ do lazy properties yourself, like this:
//struct Whatever {
// private var internalThing: Thing?
//
// var thing: Thing {
// if let internalThing = internalThing {
// return internalThing
// } else {
// internalThing = Thing()
// return internalThing!
// }
// }
//}
//: ... except that setting `internalThing` is not allowed because that mutates the instance. Anyway, this _same_ code could be accomplished with _one_ keyword:
//struct Whatever {
// lazy var thing = Thing()
//}
//: Lazy properties can be helpful in unit testing with dependency injection, but not in the limited way we've seen them so far. We now need to look at lazy computed properties.
//:
//: ## Lazy Closure Properties
//:
//: Before we dive into lazy computed properties, which are _really_ cool, I'd like to go back to first principles on why they're useful. We've already seen how lazy variables are good at delaying expensive resource allocations, but I believe that their power goes beyond just efficiency. They present a way to write codes that is simply _more awesome_.
//:
//: Typically, members of a struct or class with a default value have that value set when the instance is initialized.
struct PersonDefault {
var name = ""
}
//: When we call `Person()`, we create a new instance, and the name property is set to an empty string. However, not all properties need to exhibit this behaviour. For example, let's consider a new `Person` struct.
struct PersonNonDef {
let firstName: String
let lastName: String
}
//: OK, so `firstName` and `secondName` never change. We _could_, if we wanted to, create a computed property for `fullName`.
struct OKPerson {
let firstName: String
let lastName: String
var fullName: String {
return "\(firstName) \(lastName)"
}
}
//: This is _OK_ – the code will run and work as you expect.
var orta = OKPerson(firstName: "Orta", lastName: "Therox")
orta.fullName // returns "Orta Therox"
//: But every time you call `fullName`, you're performing the same computation based on the same two constant properties. The `fullName` computed property will _always_ return the exact same values. It would be better if we could compute the value _once_, and then remember it.
//:
//: This is possible by combining lazy variables and closures. A lazy property can be set to a self-evaluating closure. When the property is first accessed, the closure is executed and its return value is set to the property. The closure is guaranteed to only ever be executed once, if ever, in a lifetime of an instance. Let's see this in action.
struct Person {
let firstName: String
let lastName: String
lazy var fullName: String = {
return "\(self.firstName) \(self.lastName)"
}()
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
//: There's a lot to unwrap here. First, the `fullName` property is no longer computed – it's value is stored – so we need a custom initializer (the inferred initializer is `init(firstName: String, lastName: String, fullName: String)`, which is silly).
//:
//: The next thing is the `fullName` property. It's marked as `lazy` to indicate that the right-hand side of the `=` sign shouldn't be evaluated until the property is first accessed. When it is, the right-hand side is a closure that is immediately evaluated (notice the `()` on the end). Its return value is set to the instance, and the computation is never performed again.
//:
//: This _self-evaluating, lazily-evaluated closure properties_ approach has a lot of advantages. First, unlike normal lazy properties, the closure has access to `self`, so it can use the current state of the instance when setting up the property value.
//:
//: More than that is that it allows us to easily inject dependencies when unit testing. Simply inject a tests _own_ stubbed dependency before the subject's is accessed. The closure will never be executed.
//:
//: ## Protocols & Generic Constraints
//:
//: Protocols are a way to loosely couple code together by indicating that a type conforms to a certain set of functions. Other languages sometimes call these interfaces.
//:
//: Conforming to a protocol is easy.
//struct MyInt: BooleanType {
// let value: Int
//}
//: This struct conforms to the `BooleanType` protocol. However, this doesn't compile; we haven't implemented the necessary functions.
struct MyInt: BooleanType {
let value: Int
var boolValue: Bool {
return value != 0
}
}
//: Now we're fine.
//:
//: But why conform at all? Well, now that we conform to BooleanType, we can use boolean operators and logic on instances of our struct.
let a = MyInt(value: 1)
let b = MyInt(value: 0)
a && b
a || b
!b
//: Mostly, you'll use protocols to hook into existing Swift features, but they're also useful for loosely coupling types. That's beyond the scope of this lesson, though it's an important concept for writing iOS and OS X apps.
//:
//: We can also combine protocols with generics, which is super-fun. We're going to touch on this _briefly_, and return to it next week.
//:
//: Here, we see a struct that conforms to `BooleanType` and operate on a generic type `T`, which _also_ must conform to `BooleanType`.
struct MyBool<T: BooleanType>: BooleanType {
let value: T
var boolValue: Bool {
return value.boolValue
}
}
//: `MyBool` will pass through calls to `boolValue` to its underlying value, which we constrain. `T` _must_ conform to `BooleanType`, or you'll get a compiler error.
// Uncomment for an error
//MyBool(value: "what is this???")
//: We can now use and reason about `MyBool` instances with the same boolean logic as `MyInt`, since they both conform to `BooleanType`.
let x = MyBool(value: true)
!x
let y = MyBool(value: MyInt(value: 1))
!y
//: Protocols and generics get _way_ more powerful when you combine other Swift features like operator overloading and protocol extensions, which we'll cover soon.
//:
//: ----------------
//:
//: We've seen a lot in this lesson, mostly abstract concepts. Try playing around with protocols – how could you create your own? Why would that be useful? What other uses could you see for lazy computed values using closures? Could you combine them with protocols somehow, like a lazy property whose type is defined as a generic conforming to a protocol?
//:
//: Until next time!
//:
//: 
| cc0-1.0 | 61c5a235c55e39f3afc5e81c0727b435 | 60.590909 | 547 | 0.72428 | 4.001772 | false | false | false | false |
marc-medley/004.45macOS_CotEditorSwiftScripting | templates/CotEditorScripting.swift | 1 | 281 | public enum CotEditorScripting: String {
case textSelection = "text selection"
case richText = "rich text"
case character = "character"
case paragraph = "paragraph"
case word = "word"
case attributeRun = "attribute run"
case attachment = "attachment"
}
| mit | dcb1e35b42fe1d4c66a76bb5d49b2367 | 30.222222 | 41 | 0.683274 | 4.390625 | false | false | false | false |
evering7/iSpeak8 | Pods/FeedKit/Sources/FeedKit/Parser/FeedParser.swift | 1 | 3244 | //
// FeedParser.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Dispatch
/// An RSS and Atom feed parser. `FeedParser` uses `Foundation`'s `XMLParser`.
public class FeedParser {
/// A FeedParser handler provider.
let parser: FeedParserProtocol
/// Initializes the parser with the xml or json contents encapsulated in a
/// given data object.
///
/// - Parameter data: An instance of `FeedParser`.
public init?(data: Data) {
guard let feedDataType = FeedDataType(data: data) else { return nil }
switch feedDataType {
case .json: self.parser = JSONFeedParser(data: data)
case .xml: self.parser = XMLFeedParser(data: data)
}
}
/// Initializes the parser with the XML content referenced by the given URL.
///
/// - Parameter URL: An instance of `FeedParser`.
public convenience init?(URL: URL) {
guard let data = try? Data(contentsOf: URL) else {
return nil
}
self.init(data: data)
}
/// Starts parsing the feed.
///
/// - Returns: The parsed `Result`.
public func parse() -> Result {
return self.parser.parse()
}
/// Starts parsing the feed asynchronously. Parsing runs by default on the
/// global queue. You are responsible to manually bring the result closure
/// to whichever queue is apropriate, if any.
///
/// Usually to the Main queue if UI Updates are needed.
///
/// DispatchQueue.main.async {
/// // UI Updates
/// }
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched.
/// - result: The parsed `Result`.
public func parseAsync(
queue: DispatchQueue = DispatchQueue.global(),
result: @escaping (Result) -> Void)
{
queue.async {
result(self.parse())
}
}
/// Stops parsing XML feeds.
public func abortParsing() {
guard let xmlFeedParser = self.parser as? XMLFeedParser else { return }
xmlFeedParser.xmlParser.abortParsing()
}
}
| mit | cbf24c04ebe02ce6a7d1a7a2bf141a72 | 34.648352 | 82 | 0.651973 | 4.48686 | false | false | false | false |
khizkhiz/swift | test/ClangModules/availability.swift | 2 | 6875 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify -I %S/Inputs/custom-modules %s
// REQUIRES: objc_interop
import Dispatch
import Foundation
import stdio
import AvailabilityExtras
// Test if an instance method marked __attribute__((unavailable)) on
// the *class* NSObject can be used.
func test_unavailable_instance_method(x : NSObject) -> Bool {
return x.allowsWeakReference() // expected-error {{'allowsWeakReference()' is unavailable}}
}
func test_unavailable_method_in_protocol(x : NSObjectProtocol) {
x.retain() // expected-error {{'retain()' is unavailable}}
}
func test_unavailable_method_in_protocol_use_class_instance(x : NSObject) {
x.retain() // expected-error {{'retain()' is unavailable}}
}
func test_unavailable_func(x : NSObject) {
NSDeallocateObject(x) // expected-error {{'NSDeallocateObject' is unavailable}}
}
func test_deprecated_imported_as_unavailable(s:UnsafeMutablePointer<CChar>) {
_ = tmpnam(s) // expected-warning {{'tmpnam' is deprecated: Due to security concerns inherent in the design of tmpnam(3), it is highly recommended that you use mkstemp(3) instead.}}
}
func test_NSInvocation(x: NSInvocation, // expected-error {{'NSInvocation' is unavailable}}
y: NSInvocationOperation,// expected-error {{'NSInvocationOperation' is unavailable}}
z: NSMethodSignature) {} // expected-error {{'NSMethodSignature' is unavailable}}
func test_class_avail(x:NSObject, obj: AnyObject) {
x.`class`() // expected-error {{'class()' is unavailable in Swift: use 'dynamicType' instead}}
NSObject.`class`() // expected-error {{'class()' is unavailable in Swift: use 'self' instead}}
obj.`class`!() // expected-error {{'class()' is unavailable in Swift: use 'dynamicType' instead}}
}
func test_unavailable_app_extension() {
// No expected error here. See corresponding App extension test.
_ = SomeCrazyAppExtensionForbiddenAPI() // no-error
}
func test_swift_unavailable() {
NSSwiftOldUnavailableFunction() // expected-error {{'NSSwiftOldUnavailableFunction()' is unavailable in Swift}}
NSSwiftNewUnavailableFunction() // expected-error {{'NSSwiftNewUnavailableFunction()' is unavailable in Swift}}
NSSwiftNewUnavailableFunction2() // expected-error {{'NSSwiftNewUnavailableFunction2()' is unavailable in Swift}}
NSSwiftNewUnavailableFunctionPremium() // expected-error {{'NSSwiftNewUnavailableFunctionPremium()' is unavailable in Swift: You didn't want to use it anyway.}}
let x: NSSwiftUnavailableStruct? = nil // expected-error {{'NSSwiftUnavailableStruct' is unavailable in Swift}}
}
func test_CFReleaseRetainAutorelease(x : CFTypeRef, color : CGColor ) {
CFRelease(x) // expected-error {{'CFRelease' is unavailable: Core Foundation objects are automatically memory managed}}
CGColorRelease(color) // expected-error {{'CGColorRelease' is unavailable: Core Foundation objects are automatically memory managed}}
CFRetain(x) // expected-error {{'CFRetain' is unavailable: Core Foundation objects are automatically memory managed}}
CGColorRetain(color) // expected-error {{'CGColorRetain' is unavailable: Core Foundation objects are automatically memory managed}}
CFAutorelease(x) // expected-error {{'CFAutorelease' is unavailable: Core Foundation objects are automatically memory managed}}
}
func testRedeclarations() {
unavail1() // expected-error {{is unavailable: first}}
unavail2() // expected-error {{is unavailable: middle}}
unavail3() // expected-error {{is unavailable: last}}
UnavailClass1.self // expected-error {{is unavailable: first}}
UnavailClass2.self // expected-error {{is unavailable: middle}}
UnavailClass3.self // expected-error {{is unavailable: last}}
let _: UnavailStruct1 // expected-error {{is unavailable: first}}
let _: UnavailStruct2 // expected-error {{is unavailable: first}}
let _: UnavailStruct3 // expected-error {{is unavailable: first}}
let _: UnavailStruct4 // expected-error {{is unavailable: middle}}
let _: UnavailStruct5 // expected-error {{is unavailable: middle}}
let _: UnavailStruct6 // expected-error {{is unavailable: last}}
let _: UnavailProto1 // expected-error {{is unavailable: first}}
let _: UnavailProto2 // expected-error {{is unavailable: middle}}
let _: UnavailProto3 // expected-error {{is unavailable: last}}
}
func test_NSZone(z : NSZone) {
NSCreateZone(1, 1, true) // expected-error {{'NSCreateZone' is unavailable}}
NSSetZoneName(z, "name") // expected-error {{'NSSetZoneName' is unavailable}}
NSZoneName(z) // expected-error {{'NSZoneName' is unavailable}}
}
func test_DistributedObjects(o: NSObject,
a: NSConnection, // expected-error {{'NSConnection' is unavailable in Swift: Use NSXPCConnection instead}}
b: NSConnectionDelegate, // expected-error {{'NSConnectionDelegate' is unavailable in Swift: Use NSXPCConnection instead}}
c: NSDistantObjectRequest, // expected-error {{'NSDistantObjectRequest' is unavailable in Swift: Use NSXPCConnection instead}}
d: NSDistantObject, // expected-error {{'NSDistantObject' is unavailable in Swift: Use NSXPCConnection instead}}
e: NSPortNameServer, // expected-error {{'NSPortNameServer' is unavailable in Swift: Use NSXPCConnection instead}}
f: NSMachBootstrapServer, // expected-error {{'NSMachBootstrapServer' is unavailable in Swift: Use NSXPCConnection instead}}
g: NSMessagePortNameServer, // expected-error {{'NSMessagePortNameServer' is unavailable in Swift: Use NSXPCConnection instead}}
h: NSSocketPortNameServer, // expected-error {{'NSSocketPortNameServer' is unavailable in Swift: Use NSXPCConnection instead}}
i: NSPortCoder) { // expected-error {{'NSPortCoder' is unavailable in Swift: Use NSXPCConnection instead}}
let ca = NSConnectionDidDieNotification // expected-error {{'NSConnectionDidDieNotification' is unavailable in Swift: Use NSXPCConnection instead}}
let cc = NSConnectionReplyMode // expected-error {{'NSConnectionReplyMode' is unavailable in Swift: Use NSXPCConnection instead}}
o.classForPortCoder // expected-error {{'classForPortCoder' is unavailable in Swift: Use NSXPCConnection instead}}
}
func test_NSCalendarDate(o: NSCalendarDate) {} // expected-error {{'NSCalendarDate' is unavailable in Swift: Use NSCalendar and NSDateComponents and NSDateFormatter instead}}
func test_dispatch(object: dispatch_object_t) {
dispatch_retain(object); // expected-error {{'dispatch_retain' is unavailable}}
dispatch_release(object); // expected-error {{'dispatch_release' is unavailable}}
}
| apache-2.0 | 7c11aa7a81c30e864a879328e67ede22 | 60.936937 | 183 | 0.710255 | 4.586391 | false | true | false | false |
Zewo/Core | Sources/Axis/URLEncodedForm/URLEncodedFormMapSerializer.swift | 2 | 1960 | enum URLEncodedFormMapSerializerError : Error {
case invalidMap
}
public final class URLEncodedFormMapSerializer : MapSerializer {
private var buffer: String = ""
private var bufferSize: Int = 0
private typealias Body = (UnsafeBufferPointer<Byte>) throws -> Void
public init() {}
/// Serializes input `map` into URL-encoded form using a buffer of speficied size.
///
/// - parameters:
/// - map: The `Map` to encode/serialize. Only `.dictionary` is supported.
/// - bufferSize: The size of the internal buffer to be use as intermediate storage before writing the results out to `body` closure.
/// - body: The closure to pass the results of the serialization to.
public func serialize(_ map: Map, bufferSize: Int, body: Body) throws {
self.bufferSize = bufferSize
switch map {
case .dictionary(let dictionary):
for (offset: index, element: (key: key, value: map)) in dictionary.enumerated() {
if index != 0 {
try append(string: "&", body: body)
}
try append(string: key + "=", body: body)
let value = try map.asString(converting: true)
try append(string: value.percentEncoded(allowing: UnicodeScalars.uriQueryAllowed.utf8), body: body)
}
default:
throw URLEncodedFormMapSerializerError.invalidMap
}
try write(body: body)
}
private func append(string: String, body: Body) throws {
buffer += string
if buffer.unicodeScalars.count >= bufferSize {
try write(body: body)
}
}
private func write(body: Body) throws {
try buffer.withCString {
try $0.withMemoryRebound(to: Byte.self, capacity: buffer.utf8.count) {
try body(UnsafeBufferPointer(start: $0, count: buffer.utf8.count))
}
}
buffer = ""
}
}
| mit | 2583d584fca1e186332fcf5b2458ba1c | 34.636364 | 139 | 0.603061 | 4.579439 | false | false | false | false |
terietor/GTSegmentedControl | Example/SegmentedTableViewCell.swift | 1 | 2759 | // Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import GTSegmentedControl
class SegmentedTableViewCell: UITableViewCell {
let label: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
private let segmentedControl: SegmentedControl = {
let segmentedControl = SegmentedControl()
segmentedControl.items = [
"one", "two", "three",
"four", "five", "six",
"seven", "eight", "nine"
]
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
segmentedControl.itemsPerRow = 3
segmentedControl.spacing = 10
segmentedControl.tintColor = UIColor.red
segmentedControl.textColor = UIColor.black
return segmentedControl
}()
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.addSubview(self.label)
self.contentView.addSubview(self.segmentedControl)
self.label.snp.makeConstraints() { make in
make.left.top.equalTo(self.contentView).offset(10)
make.bottom.equalTo(self.contentView).offset(-10)
}
self.segmentedControl.snp.makeConstraints() { make in
make.centerY.equalTo(self.label.snp.centerY).priority(UILayoutPriorityDefaultLow)
make.right.equalTo(self.contentView).offset(-10)
make.left.equalTo(self.label.snp.right)
make.height.lessThanOrEqualTo(self.contentView).offset(-10)
}
}
}
| mit | 8713d064e7ce0af77d1e1acdb86e0a3e | 37.859155 | 93 | 0.686118 | 4.918004 | false | false | false | false |
devpunk/velvet_room | Source/Model/Vita/MVitaConfigurationFactoryTools.swift | 1 | 1738 | import Foundation
extension MVitaConfiguration
{
private static let kResourceName:String = "vitaConfiguration"
private static let kResourceExtension:String = "plist"
//MARK: internal
static func factoryMap() -> [String:Any]?
{
guard
let resourceUrl:URL = Bundle.main.url(
forResource:kResourceName,
withExtension:kResourceExtension)
else
{
return nil
}
let data:Data
do
{
try data = Data(
contentsOf:resourceUrl,
options:Data.ReadingOptions.mappedIfSafe)
}
catch
{
return nil
}
let propertyList:Any
do
{
try propertyList = PropertyListSerialization.propertyList(
from:data,
options:PropertyListSerialization.ReadOptions(),
format:nil)
}
catch
{
return nil
}
guard
let map:[String:Any] = propertyList as? [String:Any]
else
{
return nil
}
return map
}
static func removeDoubleScaping(string:String) -> String
{
let cleanedNewLine:String = string.replacingOccurrences(
of:"\\n",
with:"\n")
let cleanedReturn:String = cleanedNewLine.replacingOccurrences(
of:"\\r",
with:"\r")
let cleanedEnd:String = cleanedReturn.replacingOccurrences(
of:"\\0",
with:"\0")
return cleanedEnd
}
}
| mit | 224838ac78e507fdb7ae4928bc65bc20 | 21.868421 | 71 | 0.480437 | 5.754967 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | Solutions/Solutions/Easy/Easy_028_Implement_StrStr.swift | 1 | 2569 | /*
https://leetcode.com/problems/implement-strstr/
#28 Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Brute-force inspired by @shichaotan at https://leetcode.com/discuss/19962/a-very-clean-solution-brute-force
KMP inspired by @zhenhai at https://leetcode.com/discuss/11814/accepted-kmp-solution-in-java-for-reference
*/
import Foundation
private extension String {
subscript (index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}
}
class Easy_028_Implement_StrStr {
class func strStr_brute_force(hayStack: String?, needle: String?) -> Int {
if hayStack == nil || needle == nil {
return -1
}
var i = 0
while true {
var j = 0
while true {
if j >= (needle!).count {
return i
}
if i + j >= (hayStack!).count {
return -1
}
if hayStack![i+j] != needle![j] {
break
}
j += 1
}
i += 1
}
}
class func strStr_KMP(hayStack: String?, needle: String?) -> Int {
if hayStack == nil || needle == nil {
return -1
}
if (needle!).count == 0 {
return 0
}
if (hayStack!).count == 0 {
return -1
}
let arr: [Character] = Array((needle!))
let next: [Int] = makeNext(arr)
var i = 0
var j = 0
let end = (hayStack!).count
while i < end {
if j == -1 || hayStack![i] == arr[j] {
j += 1
i += 1
if j == arr.count {
return i - arr.count
}
}
if i < end && hayStack![i] != arr[j] {
j = next[j]
}
}
return -1
}
class func makeNext(_ arr: [Character]) -> [Int] {
var next: [Int] = [Int](repeating: -1, count: arr.count)
var i = 0
var j = -1
while i + 1 < arr.count {
if j == -1 || arr[i] == arr[j] {
next[i+1] = j+1
if arr[i+1] == arr[j+1] {
next[i+1] = next[j+1]
}
i += 1
j += 1
}
if arr[i] != arr[j] {
j = next[j]
}
}
return next
}
}
| mit | fdd37a9abbcf0f996f54928c8e137b65 | 25.484536 | 107 | 0.428571 | 3.904255 | false | false | false | false |
stephentyrone/swift | test/decl/func/vararg.swift | 6 | 1100 | // RUN: %target-typecheck-verify-swift
var t1a: (Int...) = (1) // expected-error{{cannot create a variadic tuple}}
var t2d: (Double = 0.0) = 1 // expected-error {{default argument not permitted in a tuple type}} {{18-23=}}
func f1(_ a: Int...) { for _ in a {} }
f1()
f1(1)
f1(1,2)
func f2(_ a: Int, _ b: Int...) { for _ in b {} }
f2(1)
f2(1,2)
f2(1,2,3)
func f3(_ a: (String) -> Void) { }
f3({ print($0) })
func f4(_ a: Int..., b: Int) { }
// rdar://16008564
func inoutVariadic(_ i: inout Int...) { // expected-error {{'inout' must not be used on variadic parameters}}
}
// rdar://19722429
func invalidVariadic(_ e: NonExistentType) { // expected-error {{cannot find type 'NonExistentType' in scope}}
{ (e: ExtraCrispy...) in }() // expected-error {{cannot find type 'ExtraCrispy' in scope}}
}
func twoVariadics(_ a: Int..., b: Int...) { } // expected-error{{only a single variadic parameter '...' is permitted}} {{38-41=}}
// rdar://22056861
func f5(_ list: Any..., end: String = "") {}
f5(String())
// rdar://18083599
enum E1 {
case On, Off
}
func doEV(_ state: E1...) {}
doEV(.On)
| apache-2.0 | d35d636b8f3d41e2c40172853490096c | 25.190476 | 129 | 0.599091 | 2.756892 | false | false | false | false |
TeletronicsDotAe/TLTMediaSelector | TLTMediaSelector/MediaSelection.swift | 1 | 21413 | //
// MediaSelection.swift
//
// Created by Martin Rehder on 27.06.16.
// Copyright © 2016 Teletronics, MIT License
/*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import Foundation
import MobileCoreServices
import StyledOverlay
import MJRFlexStyleComponents
import RSKImageCropper
import IQAudioRecorderController
open class MediaSelection: NSObject {
public override init() {
super.init()
}
open class func getPhotoWithCallback(getPhotoWithCallback callback: @escaping (_ photo: UIImage, _ info: [AnyHashable: Any]) -> Void) {
let mSel = MediaSelection()
mSel.allowsVideo = false
mSel.allowsPhoto = true
mSel.allowsVoiceRecording = false
mSel.didGetPhoto = callback
mSel.present()
}
open class func getVideoWithCallback(getVideoWithCallback callback: @escaping (_ video: URL, _ info: [AnyHashable: Any]) -> Void) {
let mSel = MediaSelection()
mSel.allowsVideo = true
mSel.allowsPhoto = false
mSel.allowsVoiceRecording = false
mSel.didGetVideo = callback
mSel.present()
}
open class func getVoiceRecordingWithCallback(getVoiceRecordingWithCallback callback: @escaping (_ recording: String) -> Void) {
let mSel = MediaSelection()
mSel.allowsVideo = false
mSel.allowsPhoto = false
mSel.allowsVoiceRecording = true
mSel.didGetVoiceRecording = callback
mSel.present()
}
// MARK: - Configuration options
open var allowsPhoto = true
open var allowsVideo = false
open var allowsVoiceRecording = false
open var allowsTake = true
open var allowsSelectFromLibrary = true
open var allowsEditing = false
open var allowsMasking = false
open var customMaskDatasource: RSKImageCropViewControllerDataSource?
open var iPadUsesFullScreenCamera = false
open var defaultsToFrontCamera = false
open var videoMaximumDuration = TimeInterval()
open var voiceRecordingMaximumDuration = TimeInterval()
open var videoQuality = UIImagePickerControllerQualityType.typeHigh
// Need to set this when using the control on an iPad
open var presentingView: UIView? = nil
open lazy var presentingViewController: UIViewController = {
return UIApplication.shared.keyWindow!.rootViewController!
}()
// MARK: - Callbacks
/// A photo was selected
open var didGetPhoto: ((_ photo: UIImage, _ info: [AnyHashable: Any]) -> Void)?
/// A video was selected
open var didGetVideo: ((_ video: URL, _ info: [AnyHashable: Any]) -> Void)?
/// A voice recording was made
open var didGetVoiceRecording: ((_ recording: String) -> Void)?
/// The user selected did not attempt to select a photo
open var didDeny: (() -> Void)?
/// The user started selecting a photo or took a photo and then hit cancel
open var didCancel: (() -> Void)?
/// A photo or video was selected but the ImagePicker had NIL for EditedImage and OriginalImage
open var didFail: (() -> Void)?
open var customButtonPressed: (() -> Void)?
// MARK: - Localization overrides
open var title = "Select"
open var subtitle = ""
open var headIcon: UIImage?
open var headIconBackgroundColor: UIColor?
open var customButtonText: String?
open var appearance: StyledMenuPopoverConfiguration?
open var buttonBackgroundColor: UIColor?
open var closeButtonBackgroundColor: UIColor?
open var closeButtonTextColor: UIColor?
open var buttonTextColor: UIColor?
open var recorderTintColor: UIColor?
open var recorderHighlightedTintColor: UIColor?
open var titleFont: UIFont = UIFont.systemFont(ofSize: 18)
open var subtitleFont: UIFont = UIFont.systemFont(ofSize: 12)
open var buttonTextFont: UIFont = UIFont.systemFont(ofSize: 14)
open var closeButtonTextFont: UIFont = UIFont.systemFont(ofSize: 14)
/// Custom UI text (skips localization)
open var takePhotoText: String? = nil
/// Custom UI text (skips localization)
open var takeVideoText: String? = nil
/// Custom UI text (skips localization)
open var takePhotoOrVideoText: String? = nil
/// Custom UI text (skips localization)
open var makeVoiceRecordingText: String? = nil
/// Custom UI text (skips localization)
open var chooseFromPhotoLibraryText: String? = nil
/// Custom UI text (skips localization)
open var chooseFromVideoLibraryText: String? = nil
/// Custom UI text (skips localization)
open var chooseFromPhotoOrVideoLibraryText: String? = nil
/// Custom UI text (skips localization)
open var chooseFromPhotoRollText: String? = nil
/// Custom UI text (skips localization)
open var cancelText: String? = nil
/// Custom UI text (skips localization)
open var noSourcesText: String? = nil
fileprivate var selectedSource: UIImagePickerControllerSourceType?
// MARK: - String constants
fileprivate let kTakePhotoKey: String = "takePhoto"
fileprivate let kTakeVideoKey: String = "takeVideo"
fileprivate let kTakePhotoOrVideoKey: String = "takePhotoOrVideo"
fileprivate let kMakeVoiceRecordingKey: String = "makeVoiceRecording"
fileprivate let kChooseFromPhotoLibraryKey: String = "chooseFromPhotoLibrary"
fileprivate let kChooseFromVideoLibraryKey: String = "chooseFromVideoLibrary"
fileprivate let kChooseFromPhotoOrVideoLibraryKey : String = "chooseFromPhotoOrVideoLibrary"
fileprivate let kChooseFromPhotoRollKey: String = "chooseFromPhotoRoll"
fileprivate let kCancelKey: String = "cancel"
fileprivate let kNoSourcesKey: String = "noSources"
open func isLastPhotoFromCamera() -> Bool {
if let source = self.selectedSource, source == .camera {
return true
}
return false
}
// MARK: - Private
// Used as temporary storage for returned image info from the iOS image picker, in order to pass it back to the caller after crop & scale operations
fileprivate var selectedMediaInfo: [String : AnyObject]?
fileprivate lazy var imagePicker: UIImagePickerController = {
[unowned self] in
let retval = UIImagePickerController()
retval.delegate = self
retval.allowsEditing = true
return retval
}()
fileprivate var alertController: StyledMenuPopover? = nil
// MARK: - Localization
fileprivate func textForButtonWithTitle(_ title: String) -> String {
switch title {
case kTakePhotoKey:
return self.takePhotoText ?? "Photo"
case kTakeVideoKey:
return self.takeVideoText ?? "Video"
case kTakePhotoOrVideoKey:
return self.takePhotoOrVideoText ?? "Photo or Video"
case kMakeVoiceRecordingKey:
return self.makeVoiceRecordingText ?? "Voice Recorder"
case kChooseFromPhotoLibraryKey:
return self.chooseFromPhotoLibraryText ?? "Photo Library"
case kChooseFromVideoLibraryKey:
return self.chooseFromVideoLibraryText ?? "Video Library"
case kChooseFromPhotoOrVideoLibraryKey:
return self.chooseFromPhotoOrVideoLibraryText ?? "Photo or Video Library"
case kChooseFromPhotoRollKey:
return self.chooseFromPhotoRollText ?? "Photo Roll"
case kCancelKey:
return self.cancelText ?? "Cancel"
case kNoSourcesKey:
return self.noSourcesText ?? "Not Available"
default:
NSLog("Invalid title passed to textForButtonWithTitle:")
return "ERROR"
}
}
/**
* Presents the user with an option to take a photo or choose a photo from the library
*/
open func present() {
var titleToSource = [(buttonTitle: String, source: UIImagePickerControllerSourceType)]()
if self.allowsTake && UIImagePickerController.isSourceTypeAvailable(.camera) {
if self.allowsPhoto && !self.allowsVideo {
titleToSource.append((buttonTitle: kTakePhotoKey, source: .camera))
}
else if self.allowsVideo && !self.allowsPhoto {
titleToSource.append((buttonTitle: kTakeVideoKey, source: .camera))
}
else {
titleToSource.append((buttonTitle: kTakePhotoOrVideoKey, source: .camera))
}
}
if self.allowsSelectFromLibrary {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
if self.allowsPhoto && !self.allowsVideo {
titleToSource.append((buttonTitle: kChooseFromPhotoLibraryKey, source: .photoLibrary))
}
else if self.allowsVideo && !self.allowsPhoto {
titleToSource.append((buttonTitle: kChooseFromVideoLibraryKey, source: .photoLibrary))
}
else {
titleToSource.append((buttonTitle: kChooseFromPhotoOrVideoLibraryKey, source: .photoLibrary))
}
} else if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
titleToSource.append((buttonTitle: kChooseFromPhotoRollKey, source: .savedPhotosAlbum))
}
}
if self.allowsVoiceRecording {
titleToSource.append((buttonTitle: kMakeVoiceRecordingKey, source: .camera))
}
var showDefaultCloseButton = true
if closeButtonBackgroundColor != nil && closeButtonTextColor != nil {
showDefaultCloseButton = false
}
var configuration = self.appearance
if configuration == nil {
configuration = StyledMenuPopoverConfiguration()
configuration?.closeButtonEnabled = showDefaultCloseButton
configuration?.menuItemSize = CGSize(width: 200, height: 40)
configuration?.displayType = .normal
configuration?.showTitleInHeader = false
if self.headIcon == nil {
configuration?.showHeader = false
}
}
let buttonTextColor = self.buttonTextColor ?? UIColor.black
let rTintColor = self.recorderTintColor ?? UIColor.blue
let rHighlightedTintColor = self.recorderHighlightedTintColor ?? UIColor.red
configuration?.menuItemStyleColor = self.buttonBackgroundColor ?? UIColor.white
configuration?.closeButtonStyleColor = self.closeButtonBackgroundColor ?? UIColor.white
configuration?.headerIconBackgroundColor = self.headIconBackgroundColor ?? UIColor.clear
var items: [FlexCollectionItem] = []
for (title, source) in titleToSource {
let buttonText = self.textForButtonWithTitle(title)
let abt = self.applyFontAndColorToString(self.buttonTextFont, color: buttonTextColor, text: buttonText)
let menuItem = FlexBaseCollectionItem(reference: UUID().uuidString, text: abt)
items.append(menuItem)
menuItem.itemSelectionActionHandler = {
DispatchQueue.main.async {
self.alertController?.hide()
if title == self.kMakeVoiceRecordingKey {
let controller = IQAudioRecorderViewController()
controller.delegate = self
controller.title = "Recorder"
controller.maximumRecordDuration = self.voiceRecordingMaximumDuration
controller.allowCropping = self.allowsEditing
controller.barStyle = UIBarStyle.default
controller.normalTintColor = rTintColor
controller.highlightedTintColor = rHighlightedTintColor
self.presentAudioRecorderViewControllerAnimated(controller)
}
else {
self.imagePicker.sourceType = source
self.selectedSource = source
if source == .camera && self.defaultsToFrontCamera && UIImagePickerController.isCameraDeviceAvailable(.front) {
self.imagePicker.cameraDevice = .front
}
// set the media type: photo or video
var mediaTypes = [String]()
if title == self.kTakePhotoOrVideoKey || title == self.kChooseFromPhotoOrVideoLibraryKey {
self.imagePicker.videoQuality = self.videoQuality
self.imagePicker.videoMaximumDuration = self.videoMaximumDuration
self.imagePicker.allowsEditing = false
mediaTypes.append(String(kUTTypeMovie))
mediaTypes.append(String(kUTTypeImage))
}
else if title == self.kTakeVideoKey || title == self.kChooseFromVideoLibraryKey {
self.imagePicker.videoQuality = self.videoQuality
self.imagePicker.allowsEditing = self.allowsEditing
self.imagePicker.videoMaximumDuration = self.videoMaximumDuration
mediaTypes.append(String(kUTTypeMovie))
}
else {
self.imagePicker.allowsEditing = false
mediaTypes.append(String(kUTTypeImage))
}
self.imagePicker.mediaTypes = mediaTypes
self.presentAVViewController(self.imagePicker, source: source)
}
}
}
}
if let cbt = self.customButtonText {
let abt = self.applyFontAndColorToString(self.buttonTextFont, color: buttonTextColor, text: cbt)
let menuItem = FlexBaseCollectionItem(reference: UUID().uuidString, text: abt)
items.append(menuItem)
menuItem.itemSelectionActionHandler = {
DispatchQueue.main.async {
self.alertController?.hide()
self.customButtonPressed?()
}
}
}
if !showDefaultCloseButton {
let abt = self.applyFontAndColorToString(self.closeButtonTextFont, color: closeButtonTextColor ?? .black, text: "Close")
let menuItem = FlexBaseCollectionItem(reference: UUID().uuidString, text: abt)
items.append(menuItem)
menuItem.itemSelectionActionHandler = {
DispatchQueue.main.async {
self.alertController?.hide()
}
}
}
if let configuration = configuration {
self.alertController = StyledMenuPopover(frame: UIScreen.main.bounds, configuration: configuration)
self.alertController?.preferredSize = CGSize(width: 200, height: 200)
for mi in items {
self.alertController?.addMenuItem(mi)
}
let title = self.applyFontAndColorToString(self.titleFont, color: .black, text: self.title)
let subtitle = self.applyFontAndColorToString(self.subtitleFont, color: .black, text: self.subtitle)
if let icon = self.headIcon {
self.alertController?.show(title: title, subTitle: subtitle, icon: icon)
}
else {
self.alertController?.show(title: title, subTitle: subtitle)
}
}
}
func presentAVViewController(_ controller: UIViewController, source: UIImagePickerControllerSourceType) {
if let topVC = UIApplication.topViewController() {
if UI_USER_INTERFACE_IDIOM() == .phone || (source == .camera && self.iPadUsesFullScreenCamera) {
topVC.present(controller, animated: true, completion: { })
}
else {
// On iPad use pop-overs.
controller.modalPresentationStyle = .popover
controller.popoverPresentationController?.sourceView = self.presentingView
topVC.present(controller, animated:true, completion:nil)
}
}
}
/**
* Dismisses the displayed view (actionsheet or imagepicker).
* Especially handy if the sheet is displayed while suspending the app,
* and you want to go back to a default state of the UI.
*/
open func dismiss() {
alertController?.hide()
imagePicker.dismiss(animated: true, completion: nil)
}
func applyFontAndColorToString(_ font: UIFont, color: UIColor, text: String) -> NSAttributedString {
let attributedString = NSAttributedString(string: text, attributes:
[ NSAttributedStringKey.font : font,
NSAttributedStringKey.foregroundColor: color
])
return attributedString
}
}
extension MediaSelection : UIImagePickerControllerDelegate, UINavigationControllerDelegate, RSKImageCropViewControllerDelegate, IQAudioRecorderViewControllerDelegate {
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType: String = info[UIImagePickerControllerMediaType] as! String
// Handle a still image capture
if mediaType == kUTTypeImage as String {
var imageToSave: UIImage
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
imageToSave = editedImage
} else if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageToSave = originalImage
} else {
self.didCancel?()
return
}
if self.allowsMasking {
self.selectedMediaInfo = info as [String : AnyObject]?
picker.dismiss(animated: true, completion: {
DispatchQueue.main.async(execute: {
let imageCropVC = RSKImageCropViewController(image: imageToSave)
imageCropVC.avoidEmptySpaceAroundImage = true
imageCropVC.dataSource = self.customMaskDatasource
imageCropVC.delegate = self
if let topVC = UIApplication.topViewController() {
topVC.present(imageCropVC, animated: true, completion: { })
}
})
})
// Skip other cleanup, as we exit with image elsewhere
return
}
else {
self.didGetPhoto?(imageToSave, info)
}
} else if mediaType == kUTTypeMovie as String {
self.didGetVideo?(info[UIImagePickerControllerMediaURL] as! URL, info)
}
imagePicker.dismiss(animated: true, completion: nil)
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: { })
self.didDeny?()
}
// MARK: - RSKImageCropViewControllerDelegate
public func imageCropViewController(_ controller: RSKImageCropViewController, didCropImage croppedImage: UIImage, usingCropRect cropRect: CGRect, rotationAngle: CGFloat) {
self.didGetPhoto?(croppedImage, self.selectedMediaInfo!)
controller.dismiss(animated: true, completion: nil)
}
public func imageCropViewControllerDidCancelCrop(_ controller: RSKImageCropViewController) {
controller.dismiss(animated: true, completion: nil)
}
// MARK: - IQAudioRecorderViewControllerDelegate
public func audioRecorderController(_ controller: IQAudioRecorderViewController, didFinishWithAudioAtPath filePath: String) {
self.didGetVoiceRecording?(filePath)
controller.dismiss(animated: true, completion: nil)
}
public func audioRecorderControllerDidCancel(_ controller: IQAudioRecorderViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
| mit | a68ba84306350177aa32dfda3d9895da | 41.149606 | 175 | 0.635858 | 5.379899 | false | false | false | false |
exyte/Macaw | Source/model/scene/Text.swift | 1 | 4376 | #if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
open class Text: Node {
public let textVar: Variable<String>
open var text: String {
get { return textVar.value }
set(val) { textVar.value = val }
}
public let fontVar: Variable<Font?>
open var font: Font? {
get { return fontVar.value }
set(val) { fontVar.value = val }
}
public let fillVar: Variable<Fill?>
open var fill: Fill? {
get { return fillVar.value }
set(val) { fillVar.value = val }
}
public let strokeVar: Variable<Stroke?>
open var stroke: Stroke? {
get { return strokeVar.value }
set(val) { strokeVar.value = val }
}
public let alignVar: Variable<Align>
open var align: Align {
get { return alignVar.value }
set(val) { alignVar.value = val }
}
public let baselineVar: Variable<Baseline>
open var baseline: Baseline {
get { return baselineVar.value }
set(val) { baselineVar.value = val }
}
public let kerningVar: Variable<Float>
open var kerning: Float {
get { return kerningVar.value }
set(val) { kerningVar.value = val }
}
public init(text: String, font: Font? = nil, fill: Fill? = Color.black, stroke: Stroke? = nil, align: Align = .min, baseline: Baseline = .top, kerning: Float = 0.0, place: Transform = Transform.identity, opaque: Bool = true, opacity: Double = 1, clip: Locus? = nil, mask: Node? = nil, effect: Effect? = nil, visible: Bool = true, tag: [String] = []) {
self.textVar = Variable<String>(text)
self.fontVar = Variable<Font?>(font)
self.fillVar = Variable<Fill?>(fill)
self.strokeVar = Variable<Stroke?>(stroke)
self.alignVar = Variable<Align>(align)
self.baselineVar = Variable<Baseline>(baseline)
self.kerningVar = Variable<Float>(kerning)
super.init(
place: place,
opaque: opaque,
opacity: opacity,
clip: clip,
mask: mask,
effect: effect,
visible: visible,
tag: tag
)
}
override open var bounds: Rect {
let font: MFont
if let f = self.font {
if let customFont = RenderUtils.loadFont(name: f.name, size: f.size, weight: f.weight) {
font = customFont
} else {
font = MFont.systemFont(ofSize: CGFloat(f.size), weight: getWeight(f.weight))
}
} else {
font = MFont.systemFont(ofSize: MFont.mSystemFontSize)
}
var stringAttributes: [NSAttributedString.Key: AnyObject] = [:]
stringAttributes[NSAttributedString.Key.font] = font
if self.kerning != 0.0 {
stringAttributes[NSAttributedString.Key.kern] = NSNumber(value: self.kerning)
}
let size = (text as NSString).size(withAttributes: stringAttributes)
return Rect(
x: calculateAlignmentOffset(font: font),
y: calculateBaselineOffset(font: font),
w: size.width.doubleValue,
h: size.height.doubleValue
)
}
fileprivate func getWeight(_ weight: String) -> MFont.Weight {
switch weight {
case "normal":
return MFont.Weight.regular
case "bold":
return MFont.Weight.bold
case "bolder":
return MFont.Weight.semibold
case "lighter":
return MFont.Weight.light
default:
return MFont.Weight.regular
}
}
fileprivate func calculateBaselineOffset(font: MFont) -> Double {
var baselineOffset = 0.0
switch baseline {
case .alphabetic:
baselineOffset = font.ascender.doubleValue
case .bottom:
baselineOffset = (font.ascender - font.descender).doubleValue
case .mid:
baselineOffset = ((font.ascender - font.descender) / 2).doubleValue
default:
break
}
return -baselineOffset
}
fileprivate func calculateAlignmentOffset(font: MFont) -> Double {
let textAttributes = [
NSAttributedString.Key.font: font
]
let textSize = NSString(string: text).size(withAttributes: textAttributes)
return -align.align(size: textSize.width.doubleValue)
}
}
| mit | f17a448ed83f3e76407b91c30faca1de | 31.414815 | 355 | 0.585695 | 4.179561 | false | false | false | false |
matthewpurcell/firefox-ios | Client/Frontend/Home/RemoteTabsPanel.swift | 1 | 22461 | /* 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 UIKit
import Account
import Shared
import SnapKit
import Storage
import Sync
import XCGLogger
private let log = Logger.browserLogger
private struct RemoteTabsPanelUX {
static let HeaderHeight = SiteTableViewControllerUX.RowHeight // Not HeaderHeight!
static let RowHeight = SiteTableViewControllerUX.RowHeight
static let HeaderBackgroundColor = UIColor(rgb: 0xf8f8f8)
static let EmptyStateTitleTextColor = UIColor.darkGrayColor()
static let EmptyStateInstructionsTextColor = UIColor.grayColor()
static let EmptyStateInstructionsWidth = 252
static let EmptyStateTopPaddingInBetweenItems: CGFloat = 15 // UX TODO I set this to 8 so that it all fits on landscape
static let EmptyStateSignInButtonColor = UIColor(red:0.3, green:0.62, blue:1, alpha:1)
static let EmptyStateSignInButtonTitleColor = UIColor.whiteColor()
static let EmptyStateSignInButtonCornerRadius: CGFloat = 4
static let EmptyStateSignInButtonHeight = 44
static let EmptyStateSignInButtonWidth = 200
// Backup and active strings added in Bug 1205294.
static let EmptyStateInstructionsSyncTabsPasswordsBookmarksString = NSLocalizedString("Sync your tabs, bookmarks, passwords and more.", comment: "Sync tabs, bookmarks, passwords empty state instructions.")
static let EmptyStateInstructionsSyncTabsPasswordsString = NSLocalizedString("Sync your tabs, passwords and more.", comment: "Sync tabs and passwords empty state instructions.")
static let EmptyStateInstructionsGetTabsBookmarksPasswordsString = NSLocalizedString("Get your open tabs, bookmarks, and passwords from your other devices.", comment: "A re-worded offer about Sync that emphasizes one-way data transfer, not syncing.")
}
private let RemoteClientIdentifier = "RemoteClient"
private let RemoteTabIdentifier = "RemoteTab"
class RemoteTabsPanel: UITableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
var profile: Profile!
init() {
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil)
}
required init!(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(TwoLineHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: RemoteClientIdentifier)
tableView.registerClass(TwoLineTableViewCell.self, forCellReuseIdentifier: RemoteTabIdentifier)
tableView.rowHeight = RemoteTabsPanelUX.RowHeight
tableView.separatorInset = UIEdgeInsetsZero
tableView.delegate = nil
tableView.dataSource = nil
refreshControl = UIRefreshControl()
view.backgroundColor = UIConstants.PanelBackgroundColor
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
refreshControl?.addTarget(self, action: "SELrefreshTabs", forControlEvents: UIControlEvents.ValueChanged)
refreshTabs()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
refreshControl?.removeTarget(self, action: "SELrefreshTabs", forControlEvents: UIControlEvents.ValueChanged)
}
func notificationReceived(notification: NSNotification) {
switch notification.name {
case NotificationFirefoxAccountChanged:
refreshTabs()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
var tableViewDelegate: RemoteTabsPanelDataSource? {
didSet {
self.tableView.delegate = tableViewDelegate
self.tableView.dataSource = tableViewDelegate
}
}
func refreshTabs() {
tableView.scrollEnabled = false
tableView.allowsSelection = false
tableView.tableFooterView = UIView(frame: CGRectZero)
// Short circuit if the user is not logged in
if !profile.hasAccount() {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NotLoggedIn)
self.endRefreshing()
return
}
self.profile.getCachedClientsAndTabs().uponQueue(dispatch_get_main_queue()) { result in
if let clientAndTabs = result.successValue {
self.updateDelegateClientAndTabData(clientAndTabs)
}
// Otherwise, fetch the tabs cloud if its been more than 1 minute since last sync
let lastSyncTime = self.profile.prefs.timestampForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
if NSDate.now() - (lastSyncTime ?? 0) > OneMinuteInMilliseconds && !(self.refreshControl?.refreshing ?? false) {
self.startRefreshing()
self.profile.getClientsAndTabs().uponQueue(dispatch_get_main_queue()) { result in
if let clientAndTabs = result.successValue {
self.profile.prefs.setTimestamp(NSDate.now(), forKey: PrefsKeys.KeyLastRemoteTabSyncTime)
self.updateDelegateClientAndTabData(clientAndTabs)
}
self.endRefreshing()
}
} else {
// If we failed before and didn't sync, show the failure delegate
if let _ = result.failureValue {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .FailedToSync)
}
self.endRefreshing()
}
}
}
private func startRefreshing() {
if let refreshControl = self.refreshControl {
let height = -refreshControl.bounds.size.height
self.tableView.setContentOffset(CGPointMake(0, height), animated: true)
refreshControl.beginRefreshing()
}
}
func endRefreshing() {
if self.refreshControl?.refreshing ?? false {
self.refreshControl?.endRefreshing()
}
self.tableView.scrollEnabled = true
self.tableView.reloadData()
}
func updateDelegateClientAndTabData(clientAndTabs: [ClientAndTabs]) {
if clientAndTabs.count == 0 {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NoClients)
} else {
let nonEmptyClientAndTabs = clientAndTabs.filter { $0.tabs.count > 0 }
if nonEmptyClientAndTabs.count == 0 {
self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NoTabs)
} else {
self.tableViewDelegate = RemoteTabsPanelClientAndTabsDataSource(homePanel: self, clientAndTabs: nonEmptyClientAndTabs)
self.tableView.allowsSelection = true
}
}
}
@objc private func SELrefreshTabs() {
refreshTabs()
}
}
enum RemoteTabsError {
case NotLoggedIn
case NoClients
case NoTabs
case FailedToSync
func localizedString() -> String {
switch self {
case NotLoggedIn:
return "" // This does not have a localized string because we have a whole specific screen for it.
case NoClients:
return NSLocalizedString("You don't have any other devices connected to this Firefox Account available to sync.", comment: "Error message in the remote tabs panel")
case NoTabs:
return NSLocalizedString("You don't have any tabs open in Firefox on your other devices.", comment: "Error message in the remote tabs panel")
case FailedToSync:
return NSLocalizedString("There was a problem accessing tabs from your other devices. Try again in a few moments.", comment: "Error message in the remote tabs panel")
}
}
}
protocol RemoteTabsPanelDataSource: UITableViewDataSource, UITableViewDelegate {
}
class RemoteTabsPanelClientAndTabsDataSource: NSObject, RemoteTabsPanelDataSource {
weak var homePanel: HomePanel?
private var clientAndTabs: [ClientAndTabs]
init(homePanel: HomePanel, clientAndTabs: [ClientAndTabs]) {
self.homePanel = homePanel
self.clientAndTabs = clientAndTabs
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.clientAndTabs.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.clientAndTabs[section].tabs.count
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return RemoteTabsPanelUX.HeaderHeight
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let clientTabs = self.clientAndTabs[section]
let client = clientTabs.client
let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(RemoteClientIdentifier) as! TwoLineHeaderFooterView
view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: RemoteTabsPanelUX.HeaderHeight)
view.textLabel?.text = client.name
view.contentView.backgroundColor = RemoteTabsPanelUX.HeaderBackgroundColor
/*
* A note on timestamps.
* We have access to two timestamps here: the timestamp of the remote client record,
* and the set of timestamps of the client's tabs.
* Neither is "last synced". The client record timestamp changes whenever the remote
* client uploads its record (i.e., infrequently), but also whenever another device
* sends a command to that client -- which can be much later than when that client
* last synced.
* The client's tabs haven't necessarily changed, but it can still have synced.
* Ideally, we should save and use the modified time of the tabs record itself.
* This will be the real time that the other client uploaded tabs.
*/
let timestamp = clientTabs.approximateLastSyncTime()
let label = NSLocalizedString("Last synced: %@", comment: "Remote tabs last synced time. Argument is the relative date string.")
view.detailTextLabel?.text = String(format: label, NSDate.fromTimestamp(timestamp).toRelativeTimeString())
let image: UIImage?
if client.type == "desktop" {
image = UIImage(named: "deviceTypeDesktop")
image?.accessibilityLabel = NSLocalizedString("computer", comment: "Accessibility label for Desktop Computer (PC) image in remote tabs list")
} else {
image = UIImage(named: "deviceTypeMobile")
image?.accessibilityLabel = NSLocalizedString("mobile device", comment: "Accessibility label for Mobile Device image in remote tabs list")
}
view.imageView.image = image
view.mergeAccessibilityLabels()
return view
}
private func tabAtIndexPath(indexPath: NSIndexPath) -> RemoteTab {
return clientAndTabs[indexPath.section].tabs[indexPath.item]
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(RemoteTabIdentifier, forIndexPath: indexPath) as! TwoLineTableViewCell
let tab = tabAtIndexPath(indexPath)
cell.setLines(tab.title, detailText: tab.URL.absoluteString)
// TODO: Bug 1144765 - Populate image with cached favicons.
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let tab = tabAtIndexPath(indexPath)
if let homePanel = self.homePanel {
// It's not a bookmark, so let's call it Typed (which means History, too).
homePanel.homePanelDelegate?.homePanel(homePanel, didSelectURL: tab.URL, visitType: VisitType.Typed)
}
}
}
// MARK: -
class RemoteTabsPanelErrorDataSource: NSObject, RemoteTabsPanelDataSource {
weak var homePanel: HomePanel?
var error: RemoteTabsError
var notLoggedCell: UITableViewCell?
init(homePanel: HomePanel, error: RemoteTabsError) {
self.homePanel = homePanel
self.error = error
self.notLoggedCell = nil
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let cell = self.notLoggedCell {
cell.updateConstraints()
}
return tableView.bounds.height
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// Making the footer height as small as possible because it will disable button tappability if too high.
return 1
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch error {
case .NotLoggedIn:
let cell = RemoteTabsNotLoggedInCell(homePanel: homePanel)
self.notLoggedCell = cell
return cell
default:
let cell = RemoteTabsErrorCell(error: self.error)
self.notLoggedCell = nil
return cell
}
}
}
// MARK: -
class RemoteTabsErrorCell: UITableViewCell {
static let Identifier = "RemoteTabsErrorCell"
init(error: RemoteTabsError) {
super.init(style: .Default, reuseIdentifier: RemoteTabsErrorCell.Identifier)
separatorInset = UIEdgeInsetsMake(0, 1000, 0, 0)
let containerView = UIView()
contentView.addSubview(containerView)
let imageView = UIImageView()
imageView.image = UIImage(named: "emptySync")
containerView.addSubview(imageView)
imageView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(containerView)
make.centerX.equalTo(containerView)
}
let instructionsLabel = UILabel()
instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
instructionsLabel.text = error.localizedString()
instructionsLabel.textAlignment = NSTextAlignment.Center
instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor
instructionsLabel.numberOfLines = 0
containerView.addSubview(instructionsLabel)
instructionsLabel.snp_makeConstraints { make in
make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(containerView)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
}
containerView.snp_makeConstraints { make in
// Let the container wrap around the content
make.top.equalTo(imageView.snp_top)
make.left.bottom.right.equalTo(instructionsLabel)
// And then center it in the overlay view that sits on top of the UITableView
make.centerX.equalTo(contentView)
make.centerY.equalTo(contentView).offset(HomePanelUX.EmptyTabContentOffset).priorityMedium()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: -
class RemoteTabsNotLoggedInCell: UITableViewCell {
static let Identifier = "RemoteTabsNotLoggedInCell"
var homePanel: HomePanel?
var instructionsLabel: UILabel
var signInButton: UIButton
var titleLabel: UILabel
init(homePanel: HomePanel?) {
let titleLabel = UILabel()
let instructionsLabel = UILabel()
let signInButton = UIButton()
self.instructionsLabel = instructionsLabel
self.signInButton = signInButton
self.titleLabel = titleLabel
super.init(style: .Default, reuseIdentifier: RemoteTabsErrorCell.Identifier)
self.homePanel = homePanel
let createAnAccountButton = UIButton(type: .System)
let imageView = UIImageView()
imageView.image = UIImage(named: "emptySync")
contentView.addSubview(imageView)
titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont
titleLabel.text = NSLocalizedString("Welcome to Sync", comment: "See http://mzl.la/1Qtkf0j")
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor
contentView.addSubview(titleLabel)
instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
instructionsLabel.text = RemoteTabsPanelUX.EmptyStateInstructionsGetTabsBookmarksPasswordsString
instructionsLabel.textAlignment = NSTextAlignment.Center
instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor
instructionsLabel.numberOfLines = 0
contentView.addSubview(instructionsLabel)
signInButton.backgroundColor = RemoteTabsPanelUX.EmptyStateSignInButtonColor
signInButton.setTitle(NSLocalizedString("Sign in", comment: "See http://mzl.la/1Qtkf0j"), forState: .Normal)
signInButton.setTitleColor(RemoteTabsPanelUX.EmptyStateSignInButtonTitleColor, forState: .Normal)
signInButton.titleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
signInButton.layer.cornerRadius = RemoteTabsPanelUX.EmptyStateSignInButtonCornerRadius
signInButton.clipsToBounds = true
signInButton.addTarget(self, action: "SELsignIn", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(signInButton)
createAnAccountButton.setTitle(NSLocalizedString("Create an account", comment: "See http://mzl.la/1Qtkf0j"), forState: .Normal)
createAnAccountButton.titleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
createAnAccountButton.addTarget(self, action: "SELcreateAnAccount", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(createAnAccountButton)
imageView.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(instructionsLabel)
// Sets proper top constraint for iPhone 6 in portait and for iPad.
make.centerY.equalTo(contentView.snp_centerY).offset(HomePanelUX.EmptyTabContentOffset).priorityMedium()
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(contentView.snp_top).offset(50).priorityHigh()
}
titleLabel.snp_makeConstraints { make in
make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(imageView)
}
createAnAccountButton.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(signInButton)
make.top.equalTo(signInButton.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func SELsignIn() {
if let homePanel = self.homePanel {
homePanel.homePanelDelegate?.homePanelDidRequestToSignIn(homePanel)
}
}
@objc private func SELcreateAnAccount() {
if let homePanel = self.homePanel {
homePanel.homePanelDelegate?.homePanelDidRequestToCreateAccount(homePanel)
}
}
override func updateConstraints() {
if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) && !(DeviceInfo.deviceModel().rangeOfString("iPad") != nil) {
instructionsLabel.snp_remakeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
// Sets proper landscape layout for bigger phones: iPhone 6 and on.
make.left.lessThanOrEqualTo(contentView.snp_left).offset(80).priorityMedium()
// Sets proper landscape layout for smaller phones: iPhone 4 & 5.
make.right.lessThanOrEqualTo(contentView.snp_centerX).offset(-10).priorityHigh()
}
signInButton.snp_remakeConstraints { make in
make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth)
make.centerY.equalTo(titleLabel.snp_centerY)
// Sets proper landscape layout for bigger phones: iPhone 6 and on.
make.right.greaterThanOrEqualTo(contentView.snp_right).offset(-80).priorityMedium()
// Sets proper landscape layout for smaller phones: iPhone 4 & 5.
make.left.greaterThanOrEqualTo(contentView.snp_centerX).offset(10).priorityHigh()
}
} else {
instructionsLabel.snp_remakeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.centerX.equalTo(contentView)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth)
}
signInButton.snp_remakeConstraints { make in
make.centerX.equalTo(contentView)
make.top.equalTo(instructionsLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems)
make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight)
make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth)
}
}
super.updateConstraints()
}
}
| mpl-2.0 | 2f652a8a53b8068ad9132385e4a2248f | 42.194231 | 254 | 0.694938 | 5.336422 | false | false | false | false |
J-Mendes/Weather | Weather/Weather/Views/Custom Cells/WeatherInfoTableViewCell.swift | 1 | 2242 | //
// WeatherInfoTableViewCell.swift
// Weather
//
// Created by Jorge Mendes on 05/07/2017.
// Copyright © 2017 Jorge Mendes. All rights reserved.
//
import UIKit
class WeatherInfoTableViewCell: UITableViewCell {
static var key: String = String(describing: WeatherInfoTableViewCell.self)
static var nib: UINib = UINib(nibName: WeatherInfoTableViewCell.key, bundle: Bundle.main)
static var height: CGFloat = 170.0
@IBOutlet fileprivate weak var weatherImageView: UIImageView!
@IBOutlet fileprivate weak var weatherLabel: UILabel!
@IBOutlet fileprivate weak var maxTemperatureLabel: UILabel!
@IBOutlet fileprivate weak var minTemperatureLabel: UILabel!
@IBOutlet fileprivate weak var currentTemperatureLabel: UILabel!
@IBOutlet fileprivate weak var currentTemperatureUnitLabel: UILabel!
fileprivate var imageLink: String = ""
override func awakeFromNib() {
super.awakeFromNib()
self.resetView()
}
override func prepareForReuse() {
super.prepareForReuse()
self.weatherImageView.cancelLoadImageFrom(link: self.imageLink)
self.resetView()
}
internal func configure(weatherData: WeatherData) {
self.imageLink = weatherData.weather.condition.imageUrl
self.weatherImageView.loadImageFrom(link: self.imageLink, placeholder: "no_picture")
self.weatherLabel.text = weatherData.weather.condition.text
self.currentTemperatureLabel.text = "\(weatherData.weather.condition.temperature!)º"
self.currentTemperatureUnitLabel.text = weatherData.units.temperature.capitalized
if let forecast: Forecast = weatherData.weather.todayForecast {
self.maxTemperatureLabel.text = "\(forecast.high!)º"
self.minTemperatureLabel.text = "\(forecast.low!)º"
}
}
// MARK: - Private methods
fileprivate func resetView() {
self.weatherImageView.image = nil
self.weatherLabel.text = ""
self.maxTemperatureLabel.text = ""
self.minTemperatureLabel.text = ""
self.currentTemperatureLabel.text = ""
self.currentTemperatureUnitLabel.text = ""
}
}
| gpl-3.0 | 316c8ce04178ba24f76f3a7eaea74a66 | 33.430769 | 93 | 0.68588 | 4.98441 | false | false | false | false |
gerlandiolucena/iosvisits | iOSVisits/iOSVisits/Components/Annotations/AnnotationView.swift | 1 | 6637 | //
// AnnotationView.swift
// iOSVisits
//
// Created by Gerlandio da Silva Lucena on 6/3/16.
// Copyright © 2016 ZAP Imóveis. All rights reserved.
//
//
// PriceAnnotationView.swift
// QuantoVale
//
// Created by Caio Cezar Lopes on 7/6/15.
// Copyright (c) 2015 Zap Imóveis. All rights reserved.
//
import UIKit
import MapKit
class AnnotationView: MKAnnotationView {
var title = ""
var numberLabel: UILabel?
let bigFontSize: CGFloat = 14.0
let smallFontSize: CGFloat = 12.0
let backgroundPinColor = UIColor(red: 58.0 / 255.0, green: 130.0 / 255.0, blue: 168.0 / 255.0, alpha: 1.0)
let backgroundSelectedPinColor = UIColor.darkGray
let backgroundVisualizedPinColor = UIColor.lightGray
override init(annotation: MKAnnotation!, reuseIdentifier: String!) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
if let offerAnnotation = self.annotation as? PlaceAnnotation {
title = offerAnnotation.title ?? ""
}
self.resizeToFitText()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
//let color = getRealColor()
super.draw(rect)
// if !isCluster {
// self.drawBellowArrowWithRect(rect, color: color)
// }
}
func getRealColor() -> UIColor {
// switch(self.atualState) {
// case .Selected:
// return backgroundSelectedPinColor
// case .Visualized:
// return backgroundVisualizedPinColor
// case .None:
return backgroundPinColor
// }
}
func drawBellowArrowWithRect(_ rect: CGRect, color: UIColor) {
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: (rect.size.width / 2.0) - 4.0, y: rect.size.height - 4.0))
bezierPath.addLine(to: CGPoint(x: (rect.size.width / 2.0), y: rect.size.height))
bezierPath.addLine(to: CGPoint(x: (rect.size.width / 2.0) + 4.0, y: rect.size.height - 4.0))
color.setFill()
bezierPath.fill()
}
func sizeOfString(_ string: NSString) -> CGSize {
let font = UIFont.systemFont(ofSize: bigFontSize)
let size = string.size(attributes: [NSFontAttributeName: font])
return CGSize(width: size.width, height: size.height)
}
func resizeString(_ value: NSMutableAttributedString, range: NSRange) -> NSMutableAttributedString {
let fontSize: CGFloat = smallFontSize
let boldFont = UIFont.systemFont(ofSize: bigFontSize)
let regularFont = UIFont.systemFont(ofSize: fontSize)
// Create the attributes
let attrs = [NSFontAttributeName: boldFont]
let subAttrs = [NSFontAttributeName: regularFont]
let response = NSMutableAttributedString(string: value.string, attributes: attrs)
response.setAttributes(subAttrs, range: range)
return response
}
func formatPriceString(_ priceString: NSString) -> NSMutableAttributedString {
var response = NSMutableAttributedString(string: priceString as String)
do {
let finalNumbersRegex = try NSRegularExpression(pattern: "\\.+[0-9]{3,3}", options: NSRegularExpression.Options.allowCommentsAndWhitespace)
let regexResult = finalNumbersRegex.firstMatch(in: response.string, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, response.string.characters.count ))
if regexResult!.range.location != NSNotFound {
response = self.resizeString(response, range: regexResult!.range)
}
}
catch {}
var range = response.string.range(of: "mi")
if range?.isEmpty == false {
let start = response.string.characters.distance(from: response.string.startIndex, to: range!.lowerBound)
response = self.resizeString(response, range: NSMakeRange(start, 2))
}
range = response.string.range(of: "+")
if range?.isEmpty == false {
let start = response.string.characters.distance(from: response.string.startIndex, to: range!.lowerBound)
response = self.resizeString(response, range: NSMakeRange(start, 1))
}
return response
}
func configureNumberLabel(_ text: String, cornerRadius: CGFloat, isCluster: Bool) {
if self.numberLabel == nil {
self.numberLabel = UILabel(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
self.numberLabel!.textColor = UIColor(white: 1.0, alpha: 1.0)
self.numberLabel!.textAlignment = .center
self.numberLabel!.backgroundColor = UIColor.clear
self.addSubview(self.numberLabel!)
} else {
self.numberLabel!.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
}
self.numberLabel!.font = UIFont.systemFont(ofSize: bigFontSize)
self.numberLabel!.text = text
self.numberLabel!.backgroundColor = getRealColor()
self.numberLabel!.layer.cornerRadius = cornerRadius
self.numberLabel!.clipsToBounds = true
}
func resizeToFitText() {
let formatedPrice = ""
var frame = self.frame
// if let annotation = self.annotation as? OfferAnnotation {
// isCluster = annotation.offersDetail.count > 1
// }
// if isCluster {
// if let offerAnnotation = self.annotation as? OfferAnnotation {
// let defaultSize = self.sizeOfString(String(offerAnnotation.offersDetail.count))
// frame.size = CGSizeMake(defaultSize.height + 6, defaultSize.height + 6)
// configureNumberLabel(String(offerAnnotation.offersDetail.count), cornerRadius: frame.size.height / 2, isCluster: true)
// }
// } else {
frame.size = self.sizeOfString(formatedPrice as NSString)
configureNumberLabel(formatedPrice, cornerRadius: 5, isCluster: false)
// }
self.backgroundColor = UIColor.clear
// if !isCluster {
// frame.size.width += 10.0
// }
//
super.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: frame.size.height + 4)
if self.numberLabel != nil {
self.numberLabel!.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
}
}
}
| gpl-3.0 | 4ddcc37342c019622b8040850aae268f | 38.488095 | 198 | 0.622852 | 4.310591 | false | false | false | false |
onekiloparsec/siesta | Source/Request/NetworkRequest.swift | 1 | 7789 | //
// NetworkRequest.swift
// Siesta
//
// Created by Paul on 2015/12/15.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
internal final class NetworkRequest: RequestWithDefaultCallbacks, CustomDebugStringConvertible
{
// Basic metadata
private let resource: Resource
private let requestDescription: String
internal var config: Configuration
{ return resource.config(forRequest: nsreq) }
// Networking
private let nsreq: NSURLRequest
internal var networking: RequestNetworking? // present only after start()
internal var underlyingNetworkRequestCompleted = false // so tests can wait for it to finish
// Progress
private var progressTracker: ProgressTracker
var progress: Double
{ return progressTracker.progress }
// Result
private var responseCallbacks = CallbackGroup<ResponseInfo>()
private var wasCancelled: Bool = false
var isCompleted: Bool
{
dispatch_assert_main_queue()
return responseCallbacks.completedValue != nil
}
// MARK: Managing request
init(resource: Resource, nsreq: NSURLRequest)
{
self.resource = resource
self.nsreq = nsreq
self.requestDescription = debugStr([nsreq.HTTPMethod, nsreq.URL])
progressTracker = ProgressTracker(isGet: nsreq.HTTPMethod == "GET")
}
func start() -> Self
{
dispatch_assert_main_queue()
guard self.networking == nil else
{ fatalError("NetworkRequest.start() called twice") }
guard !wasCancelled else
{
debugLog(.Network, [requestDescription, "will not start because it was already cancelled"])
underlyingNetworkRequestCompleted = true
return self
}
debugLog(.Network, [requestDescription])
let networking = resource.service.networkingProvider.startRequest(nsreq)
{
res, data, err in
dispatch_async(dispatch_get_main_queue())
{ self.responseReceived(nsres: res, body: data, error: err) }
}
self.networking = networking
progressTracker.start(
networking,
reportingInterval: config.progressReportingInterval)
return self
}
func cancel()
{
dispatch_assert_main_queue()
guard !isCompleted else
{
debugLog(.Network, ["cancel() called but request already completed:", requestDescription])
return
}
debugLog(.Network, ["Cancelled", requestDescription])
networking?.cancel()
// Prevent start() from have having any effect if it hasn't been called yet
wasCancelled = true
broadcastResponse((
response: .Failure(Error(
userMessage: NSLocalizedString("Request cancelled", comment: "userMessage"),
cause: Error.Cause.RequestCancelled(networkError: nil))),
isNew: true))
}
// MARK: Callbacks
internal func addResponseCallback(callback: ResponseCallback)
{
responseCallbacks.addCallback(callback)
}
func onProgress(callback: Double -> Void) -> Self
{
progressTracker.callbacks.addCallback(callback)
return self
}
// MARK: Response handling
// Entry point for response handling. Triggered by RequestNetworking completion callback.
private func responseReceived(nsres nsres: NSHTTPURLResponse?, body: NSData?, error: ErrorType?)
{
dispatch_assert_main_queue()
underlyingNetworkRequestCompleted = true
debugLog(.Network, [nsres?.statusCode ?? error, "←", requestDescription])
debugLog(.NetworkDetails, ["Raw response headers:", nsres?.allHeaderFields])
debugLog(.NetworkDetails, ["Raw response body:", body?.length ?? 0, "bytes"])
let responseInfo = interpretResponse(nsres, body, error)
if shouldIgnoreResponse(responseInfo.response)
{ return }
transformResponse(responseInfo, then: broadcastResponse)
}
private func interpretResponse(nsres: NSHTTPURLResponse?, _ body: NSData?, _ error: ErrorType?)
-> ResponseInfo
{
if nsres?.statusCode >= 400 || error != nil
{
return (.Failure(Error(response:nsres, content: body, cause: error)), true)
}
else if nsres?.statusCode == 304
{
if let entity = resource.latestData
{
return (.Success(entity), false)
}
else
{
return (
.Failure(Error(
userMessage: NSLocalizedString("No data available", comment: "userMessage"),
cause: Error.Cause.NoLocalDataFor304())),
true)
}
}
else
{
return (.Success(Entity(response: nsres, content: body ?? NSData())), true)
}
}
private func transformResponse(rawInfo: ResponseInfo, then afterTransformation: ResponseInfo -> Void)
{
let cacheKey = resource.cacheKey
let pipeline = config.pipeline
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0))
{
let processedInfo =
rawInfo.isNew
? (pipeline.process(rawInfo.response, cacheKey: cacheKey), true)
: rawInfo
dispatch_async(dispatch_get_main_queue())
{ afterTransformation(processedInfo) }
}
}
private func broadcastResponse(newInfo: ResponseInfo)
{
dispatch_assert_main_queue()
if shouldIgnoreResponse(newInfo.response)
{ return }
debugLog(.NetworkDetails, ["Response after transformer pipeline:", newInfo.isNew ? " (new data)" : " (data unchanged)", newInfo.response.dump(" ")])
progressTracker.complete()
responseCallbacks.notifyOfCompletion(newInfo)
}
private func shouldIgnoreResponse(newResponse: Response) -> Bool
{
guard let existingResponse = responseCallbacks.completedValue?.response else
{ return false }
// We already received a response; don't broadcast another one.
if !existingResponse.isCancellation
{
debugLog(.Network,
[
"WARNING: Received response for request that was already completed:", requestDescription,
"This may indicate a bug in the NetworkingProvider you are using, or in Siesta.",
"Please file a bug report: https://github.com/bustoutsolutions/siesta/issues/new",
"\n Previously received:", existingResponse,
"\n New response:", newResponse
])
}
else if !newResponse.isCancellation
{
// Sometimes the network layer sends a cancellation error. That’s not of interest if we already knew
// we were cancelled. If we received any other response after cancellation, log that we ignored it.
debugLog(.NetworkDetails,
[
"Received response, but request was already cancelled:", requestDescription,
"\n New response:", newResponse
])
}
return true
}
// MARK: Debug
var debugDescription: String
{
return "Siesta.Request:"
+ String(ObjectIdentifier(self).uintValue, radix: 16)
+ "("
+ requestDescription
+ ")"
}
}
| mit | 3f930f5cbc67798d283d4c9e445f3d49 | 31.569038 | 158 | 0.59314 | 5.443357 | false | false | false | false |
MatthewYork/DateTools | DateToolsSwift/DateTools/Date+TimeAgo.swift | 2 | 10410 | //
// Date+TimeAgo.swift
// DateToolsTests
//
// Created by Matthew York on 8/23/16.
// Copyright © 2016 Matthew York. All rights reserved.
//
import Foundation
/**
* Extends the Date class by adding convenient methods to display the passage of
* time in String format.
*/
public extension Date {
//MARK: - Time Ago
/**
* Takes in a date and returns a string with the most convenient unit of time representing
* how far in the past that date is from now.
*
* - parameter date: Date to be measured from now
*
* - returns String - Formatted return string
*/
static func timeAgo(since date:Date) -> String{
return date.timeAgo(since: Date(), numericDates: false, numericTimes: false)
}
/**
* Takes in a date and returns a shortened string with the most convenient unit of time representing
* how far in the past that date is from now.
*
* - parameter date: Date to be measured from now
*
* - returns String - Formatted return string
*/
static func shortTimeAgo(since date:Date) -> String {
return date.shortTimeAgo(since:Date())
}
/**
* Returns a string with the most convenient unit of time representing
* how far in the past that date is from now.
*
* - returns String - Formatted return string
*/
var timeAgoSinceNow: String {
return self.timeAgo(since:Date())
}
/**
* Returns a shortened string with the most convenient unit of time representing
* how far in the past that date is from now.
*
* - returns String - Formatted return string
*/
var shortTimeAgoSinceNow: String {
return self.shortTimeAgo(since:Date())
}
func timeAgo(since date:Date, numericDates: Bool = false, numericTimes: Bool = false) -> String {
let calendar = NSCalendar.current
let unitFlags = Set<Calendar.Component>([.second,.minute,.hour,.day,.weekOfYear,.month,.year])
let earliest = self.earlierDate(date)
let latest = (earliest == self) ? date : self //Should be triple equals, but not extended to Date at this time
let components = calendar.dateComponents(unitFlags, from: earliest, to: latest)
let yesterday = date.subtract(1.days)
let isYesterday = yesterday.day == self.day
//Not Yet Implemented/Optional
//The following strings are present in the translation files but lack logic as of 2014.04.05
//@"Today", @"This week", @"This month", @"This year"
//and @"This morning", @"This afternoon"
if (components.year! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@years ago", value: components.year!)
}
else if (components.year! >= 1) {
if (numericDates) {
return DateToolsLocalizedStrings("1 year ago");
}
return DateToolsLocalizedStrings("Last year");
}
else if (components.month! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@months ago", value: components.month!)
}
else if (components.month! >= 1) {
if (numericDates) {
return DateToolsLocalizedStrings("1 month ago");
}
return DateToolsLocalizedStrings("Last month");
}
else if (components.weekOfYear! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@weeks ago", value: components.weekOfYear!)
}
else if (components.weekOfYear! >= 1) {
if (numericDates) {
return DateToolsLocalizedStrings("1 week ago");
}
return DateToolsLocalizedStrings("Last week");
}
else if (components.day! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@days ago", value: components.day!)
}
else if (isYesterday) {
if (numericDates) {
return DateToolsLocalizedStrings("1 day ago");
}
return DateToolsLocalizedStrings("Yesterday");
}
else if (components.hour! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@hours ago", value: components.hour!)
}
else if (components.hour! >= 1) {
if (numericTimes) {
return DateToolsLocalizedStrings("1 hour ago");
}
return DateToolsLocalizedStrings("An hour ago");
}
else if (components.minute! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@minutes ago", value: components.minute!)
}
else if (components.minute! >= 1) {
if (numericTimes) {
return DateToolsLocalizedStrings("1 minute ago");
}
return DateToolsLocalizedStrings("A minute ago");
}
else if (components.second! >= 3) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@seconds ago", value: components.second!)
}
else {
if (numericTimes) {
return DateToolsLocalizedStrings("1 second ago");
}
return DateToolsLocalizedStrings("Just now");
}
}
func shortTimeAgo(since date:Date) -> String {
let calendar = NSCalendar.current
let unitFlags = Set<Calendar.Component>([.second,.minute,.hour,.day,.weekOfYear,.month,.year])
let earliest = self.earlierDate(date)
let latest = (earliest == self) ? date : self //Should pbe triple equals, but not extended to Date at this time
let components = calendar.dateComponents(unitFlags, from: earliest, to: latest)
let yesterday = date.subtract(1.days)
let isYesterday = yesterday.day == self.day
if (components.year! >= 1) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@y", value: components.year!)
}
else if (components.month! >= 1) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@M", value: components.month!)
}
else if (components.weekOfYear! >= 1) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@w", value: components.weekOfYear!)
}
else if (components.day! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@d", value: components.day!)
}
else if (isYesterday) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@d", value: 1)
}
else if (components.hour! >= 1) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@h", value: components.hour!)
}
else if (components.minute! >= 1) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@m", value: components.minute!)
}
else if (components.second! >= 3) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@s", value: components.second!)
}
else {
return self.logicalLocalizedStringFromFormat(format: "%%d%@s", value: components.second!)
//return DateToolsLocalizedStrings(@"Now"); //string not yet translated 2014.04.05
}
}
private func logicalLocalizedStringFromFormat(format: String, value: Int) -> String{
#if os(Linux)
let localeFormat = String.init(format: format, getLocaleFormatUnderscoresWithValue(Double(value)) as! CVarArg) // this may not work, unclear!!
#else
let localeFormat = String.init(format: format, getLocaleFormatUnderscoresWithValue(Double(value)))
#endif
return String.init(format: DateToolsLocalizedStrings(localeFormat), value)
}
private func getLocaleFormatUnderscoresWithValue(_ value: Double) -> String{
let localCode = Bundle.main.preferredLocalizations[0]
if (localCode == "ru" || localCode == "uk") {
let XY = Int(floor(value).truncatingRemainder(dividingBy: 100))
let Y = Int(floor(value).truncatingRemainder(dividingBy: 10))
if(Y == 0 || Y > 4 || (XY > 10 && XY < 15)) {
return ""
}
if(Y > 1 && Y < 5 && (XY < 10 || XY > 20)) {
return "_"
}
if(Y == 1 && XY != 11) {
return "__"
}
}
return ""
}
// MARK: - Localization
private func DateToolsLocalizedStrings(_ string: String) -> String {
//let classBundle = Bundle(for:TimeChunk.self as! AnyClass.Type).resourcePath!.appending("DateTools.bundle")
//let bundelPath = Bundle(path:classBundle)!
#if os(Linux)
// NSLocalizedString() is not available yet, see: https://github.com/apple/swift-corelibs-foundation/blob/16f83ddcd311b768e30a93637af161676b0a5f2f/Foundation/NSData.swift
// However, a seemingly-equivalent method from NSBundle is: https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSBundle.swift
return Bundle.main.localizedString(forKey: string, value: "", table: "DateTools")
#else
return NSLocalizedString(string, tableName: "DateTools", bundle: Bundle.dateToolsBundle(), value: "", comment: "")
#endif
}
// MARK: - Date Earlier/Later
/**
* Return the earlier of two dates, between self and a given date.
*
* - parameter date: The date to compare to self
*
* - returns: The date that is earlier
*/
func earlierDate(_ date:Date) -> Date{
return (self.timeIntervalSince1970 <= date.timeIntervalSince1970) ? self : date
}
/**
* Return the later of two dates, between self and a given date.
*
* - parameter date: The date to compare to self
*
* - returns: The date that is later
*/
func laterDate(_ date:Date) -> Date{
return (self.timeIntervalSince1970 >= date.timeIntervalSince1970) ? self : date
}
}
| mit | 048bd68c567e3c120831e18e259bff98 | 36.850909 | 178 | 0.583149 | 4.618012 | false | false | false | false |
KieranHarper/KJHUIKit | Sources/CrossfadingImageView.swift | 1 | 1165 | //
// CrossfadingImageView.swift
// KJHUIKit
//
// Created by Kieran Harper on 1/7/17.
// Copyright © 2017 Kieran Harper. All rights reserved.
//
import UIKit
/// Simple crossfading UIImageView subclass.
@objc open class CrossfadingImageView: UIImageView {
/// The duration to perform the crossfade over.
@objc open var crossfadeDuration: TimeInterval = 0.25
/// Master switch to disable crossfade, which is useful in situations where the code setting the image isn't aware of some other condition, or when you'd like to temporarily make it instant but can't store the current duration and apply it later.
@objc open var disableCrossfade = false
/// Set the image, with or without crossfading.
@objc open func setImage(_ image: UIImage?, crossfading: Bool, completion: ((Bool) -> Void)? = nil) {
if crossfading, !disableCrossfade, crossfadeDuration > 0.0 {
UIView.transition(with: self, duration: crossfadeDuration, options: .transitionCrossDissolve, animations: {
super.image = image
}, completion: completion)
} else {
super.image = image
}
}
}
| mit | f5d147bb828fb71f70a6675234004a2c | 37.8 | 250 | 0.682131 | 4.248175 | false | false | false | false |
unige-semantics-2017/minotaur | Sources/minotaur.swift | 1 | 1121 | import LogicKit
let zero = Value (0)
func succ (_ of: Term) -> Map {
return ["succ": of]
}
func toNat (_ n : Int) -> Term {
var result : Term = zero
for _ in 1...n {
result = succ (result)
}
return result
}
struct Position : Equatable, CustomStringConvertible {
let x : Int
let y : Int
var description: String {
return "\(self.x):\(self.y)"
}
static func ==(lhs: Position, rhs: Position) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
// rooms are numbered:
// x:1,y:1 ... x:n,y:1
// ... ...
// x:1,y:m ... x:n,y:m
func room (_ x: Int, _ y: Int) -> Term {
return Value (Position (x: x, y: y))
}
func doors (from: Term, to: Term) -> Goal {
// TODO
}
func entrance (location: Term) -> Goal {
// TODO
}
func exit (location: Term) -> Goal {
// TODO
}
func minotaur (location: Term) -> Goal {
// TODO
}
func path (from: Term, to: Term, through: Term) -> Goal {
// TODO
}
func battery (through: Term, level: Term) -> Goal {
// TODO
}
func winning (through: Term, level: Term) -> Goal {
// TODO
}
| mit | 4cac103f74570a68eedb41f97ead8187 | 15.984848 | 58 | 0.531668 | 3.021563 | false | false | false | false |
groue/GRDB.swift | Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerCreationView.swift | 1 | 1597 | import SwiftUI
/// The view that creates a new player.
struct PlayerCreationView: View {
/// Write access to the database
@Environment(\.appDatabase) private var appDatabase
@Environment(\.dismiss) private var dismiss
@State private var form = PlayerForm(name: "", score: "")
@State private var errorAlertIsPresented = false
@State private var errorAlertTitle = ""
var body: some View {
NavigationView {
PlayerFormView(form: $form)
.alert(
isPresented: $errorAlertIsPresented,
content: { Alert(title: Text(errorAlertTitle)) })
.navigationBarTitle("New Player")
.navigationBarItems(
leading: Button(role: .cancel) {
dismiss()
} label: {
Text("Cancel")
},
trailing: Button {
save()
} label: {
Text("Save")
})
}
}
private func save() {
do {
var player = Player(id: nil, name: "", score: 0)
form.apply(to: &player)
try appDatabase.savePlayer(&player)
dismiss()
} catch {
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
errorAlertIsPresented = true
}
}
}
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
PlayerCreationView()
}
}
| mit | a1148f513a6669930d1d70a142df50a4 | 30.94 | 97 | 0.509706 | 5.377104 | false | false | false | false |
tiusender/JVToolkit | JVToolkit/Classes/JVSimpleTableViewController.swift | 1 | 2392 | //
// JVSimpleTableViewController.swift
// Pods
//
// Created by Jorge Villalobos Beato on 12/21/16.
//
//
import Foundation
open class JVSimpleTableViewController: UITableViewController, JVSimplifiedTVCProtocol, JVRemotableViewController {
open func fetchRemoteData(_ completion: @escaping (JVResult<Any>) -> Void) {
completion(JVResult.Failure(RemoteError.unimplemented))
}
public typealias T = Any
public var useRefreshControl: Bool = true
public var items:[T] = []
open var cellIdentifier:String = ""
public func itemForIndexPath(_ indexPath:IndexPath) -> T? {
if items.count > indexPath.row {
return items[indexPath.row] as T
} else {
return nil
}
}
open func configureCell<T>(_ cell:UITableViewCell, item:T?, indexPath:IndexPath) {
}
open func cellDidDisappear(_ cell:UITableViewCell, indexPath:IndexPath) {
}
override open func viewDidLoad() {
self.tableView.delegate = self
self.tableView.dataSource = self
self.cellIdentifier = "cell"
self.customViewDidLoad(self.tableView)
super.viewDidLoad()
}
override open func viewWillDisappear(_ animated: Bool) {
self.customViewWillDisappear(animated)
super.viewWillDisappear(animated)
}
public func reloadData() {
self.tableView.reloadData()
}
override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
let item = self.itemForIndexPath(indexPath)
self.configureCell(cell, item:item, indexPath: indexPath)
return cell
}
override open func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if tableView.indexPathsForVisibleRows?.index(of: indexPath) == nil {
self.cellDidDisappear(cell, indexPath: indexPath)
}
}
override open func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
}
| mit | 5e0ba78836d32e5b14d0ee986c51c133 | 28.530864 | 131 | 0.647993 | 5.122056 | false | false | false | false |
hirohisa/ImageLoaderSwift | Example/ImageLoaderExample/Utils.swift | 1 | 1506 | //
// Utils.swift
// ImageLoaderExample
//
// Created by Hirohisa Kawasaki on 12/18/14.
// Copyright (c) 2014 Hirohisa Kawasaki. All rights reserved.
//
import Foundation
import UIKit
extension String {
static func imageURL(_ index: Int) -> String {
var number = index.description
while (number.count < 3) {
number = "0\(number)"
}
return "https://s3.amazonaws.com/fast-image-cache/demo-images/FICDDemoImage\(number).jpg"
}
}
extension URL {
static func imageURL(_ index: Int) -> URL {
var number = index.description
while (number.count < 3) {
number = "0\(number)"
}
let string = "https://s3.amazonaws.com/fast-image-cache/demo-images/FICDDemoImage\(number).jpg"
return URL(string: string)!
}
}
extension UIImage {
public convenience init?(color: UIColor) {
self.init(color: color, size: CGSize(width: 1, height: 1))
}
public convenience init?(color: UIColor, size: CGSize) {
let frameFor1px = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(frameFor1px.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(frameFor1px)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image!.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
| mit | cb407fd921e4e4887bf1277f33bb0585 | 24.525424 | 103 | 0.633466 | 4.059299 | false | false | false | false |
DanielAsher/SwiftReferenceApp | SwiftReferenceApp/Playgrounds/PatternMatchingOperator.playground/Pages/Either Pattern Matcher.xcplaygroundpage/Contents.swift | 1 | 655 | /*:
# PatternMatching.playground
## SwiftReferenceApp
### Created by Daniel Asher on 3/09/2015.
### Copyright (c) 2015 StoryShare. All rights reserved.
*/
import UIKit
var str = "Hello, playground"
enum Either {
case Left, Right
}
extension Either : CustomStringConvertible {
var description : String {
switch self {
case .Left: return "Left"
case .Right: return "Right"
}
}
}
func ~=(pattern: String, value: Either) -> Bool {
return pattern == value.description
}
let either : Either -> Bool = { either in
switch either {
case "Left": return true
default: return false
}
}
either
| mit | 83da3e6ede8141eb9566d54e2ab696da | 16.236842 | 55 | 0.633588 | 3.852941 | false | false | false | false |
Piwigo/Piwigo-Mobile | piwigo/Settings/Images/DefaultImageThumbnailSizeViewController.swift | 1 | 13122 | //
// DefaultImageThumbnailSizeViewController.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 04/06/2017.
// Copyright © 2017 Piwigo.org. All rights reserved.
//
// Converted to Swift 5 by Eddy Lelièvre-Berna on 05/04/2020.
//
import UIKit
import piwigoKit
protocol DefaultImageThumbnailSizeDelegate: NSObjectProtocol {
func didSelectImageDefaultThumbnailSize(_ thumbnailSize: kPiwigoImageSize)
}
class DefaultImageThumbnailSizeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
weak var delegate: DefaultImageThumbnailSizeDelegate?
private var currentThumbnailSize = kPiwigoImageSize(AlbumVars.shared.defaultThumbnailSize)
@IBOutlet var tableView: UITableView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("settingsHeader_images", comment: "Images")
// Set colors, fonts, etc.
applyColorPalette()
}
@objc func applyColorPalette() {
// Background color of the view
view.backgroundColor = .piwigoColorBackground()
// Navigation bar
let attributes = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorWhiteCream(),
NSAttributedString.Key.font: UIFont.piwigoFontNormal()
]
navigationController?.navigationBar.titleTextAttributes = attributes
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = false
}
navigationController?.navigationBar.barStyle = AppVars.shared.isDarkPaletteActive ? .black : .default
navigationController?.navigationBar.tintColor = .piwigoColorOrange()
navigationController?.navigationBar.barTintColor = .piwigoColorBackground()
navigationController?.navigationBar.backgroundColor = .piwigoColorBackground()
if #available(iOS 15.0, *) {
/// In iOS 15, UIKit has extended the usage of the scrollEdgeAppearance,
/// which by default produces a transparent background, to all navigation bars.
let barAppearance = UINavigationBarAppearance()
barAppearance.configureWithOpaqueBackground()
barAppearance.backgroundColor = .piwigoColorBackground()
navigationController?.navigationBar.standardAppearance = barAppearance
navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
}
// Table view
tableView.separatorColor = .piwigoColorSeparator()
tableView.indicatorStyle = AppVars.shared.isDarkPaletteActive ? .white : .black
tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Register palette changes
NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette),
name: .pwgPaletteChanged, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Return selected image thumbnail size
delegate?.didSelectImageDefaultThumbnailSize(currentThumbnailSize)
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil)
}
// MARK: - UITableView - Header
private func getContentOfHeader() -> (String, String) {
let title = String(format: "%@\n", NSLocalizedString("defaultThumbnailFile>414px", comment: "Images Thumbnail File"))
let text = NSLocalizedString("defaultThumbnailSizeHeader", comment: "Please select an image thumbnail size")
return (title, text)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let (title, text) = getContentOfHeader()
return TableViewUtilities.shared.heightOfHeader(withTitle: title, text: text,
width: tableView.frame.size.width)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let (title, text) = getContentOfHeader()
return TableViewUtilities.shared.viewOfHeader(withTitle: title, text: text)
}
// MARK: - UITableView - Rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int(kPiwigoImageSizeEnumCount.rawValue)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let imageSize = kPiwigoImageSize(UInt32(indexPath.row))
// Appearance
cell.backgroundColor = .piwigoColorCellBackground()
cell.tintColor = .piwigoColorOrange()
cell.textLabel?.font = .piwigoFontNormal()
cell.textLabel?.textColor = .piwigoColorLeftLabel()
cell.textLabel?.adjustsFontSizeToFitWidth = false
// Add checkmark in front of selected item
if imageSize == currentThumbnailSize {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
// Disable unavailable and useless sizes
switch imageSize {
case kPiwigoImageSizeSquare:
if AlbumVars.shared.hasSquareSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeThumb:
if AlbumVars.shared.hasThumbSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeXXSmall:
if AlbumVars.shared.hasXXSmallSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeXSmall:
if AlbumVars.shared.hasXSmallSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeSmall:
if AlbumVars.shared.hasSmallSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeMedium:
if AlbumVars.shared.hasMediumSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeLarge:
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
if !AlbumVars.shared.hasLargeSizeImages {
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
} else {
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: true)
}
case kPiwigoImageSizeXLarge:
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
if !AlbumVars.shared.hasXLargeSizeImages {
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
} else {
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: true)
}
case kPiwigoImageSizeXXLarge:
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
if !AlbumVars.shared.hasXXLargeSizeImages {
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
} else {
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: true)
}
case kPiwigoImageSizeFullRes:
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forImageThumbnailSizeType: imageSize, withInfo: true)
default:
break
}
return cell
}
// MARK: - UITableView - Footer
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let footer = NSLocalizedString("defaultSizeFooter", comment: "Greyed sizes are not advised or not available on Piwigo server.")
return TableViewUtilities.shared.heightOfFooter(withText: footer, width: tableView.frame.width)
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footer = NSLocalizedString("defaultSizeFooter", comment: "Greyed sizes are not advised or not available on Piwigo server.")
return TableViewUtilities.shared.viewOfFooter(withText: footer, alignment: .center)
}
// MARK: - UITableViewDelegate Methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// Did the user change of default size
if kPiwigoImageSize(UInt32(indexPath.row)) == currentThumbnailSize { return }
// Update default size
tableView.cellForRow(at: IndexPath(row: Int(currentThumbnailSize.rawValue), section: 0))?.accessoryType = .none
currentThumbnailSize = kPiwigoImageSize(UInt32(indexPath.row))
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
}
| mit | 92730c50db13c30d030686485a7509b3 | 48.134831 | 145 | 0.665904 | 5.457155 | false | false | false | false |
cherrythia/FYP | FYP Table/Array3D.swift | 1 | 780 | //
// Array3d.swift
// FYP Table
//
// Created by Chia Wei Zheng Terry on 22/1/15.
// Copyright (c) 2015 Chia Wei Zheng Terry. All rights reserved.
//
import Foundation
import UIKit
class Array3D {
var zs:Int, ys:Int, xs:Int
var matrix: [Float]
init(zs: Int, ys:Int, xs:Int)
{
self.zs = zs
self.ys = ys
self.xs = xs
matrix = Array(repeating: 0, count: zs*ys*xs)
}
subscript(z:Int, y:Int, x:Int) -> Float
{
get {
return matrix[ z * ys * xs + y * xs + x ]
}
set {
matrix[ z * ys * xs + y * xs + x ] = newValue
}
}
var description : String
{
return String(format: "\(matrix) zs:%d ys:%d xs:%d", zs, ys, zs)
}
}
| mit | d340fa13e180b785e085b7172287c479 | 17.571429 | 71 | 0.489744 | 3.22314 | false | false | false | false |
huonw/swift | test/Migrator/Inputs/string_to_substring_conversion.swift | 25 | 1401 | // RUN: %target-swift-frontend -typecheck -verify fix-string-substring-conversion %s
let s = "Hello"
let ss = s[s.startIndex..<s.endIndex]
// CTP_Initialization
do {
let s1: Substring = { return s }()
_ = s1
}
// CTP_ReturnStmt
do {
func returnsASubstring() -> Substring {
return s
}
}
// CTP_ThrowStmt
// Doesn't really make sense for this fix-it - see case in diagnoseContextualConversionError:
// The conversion destination of throw is always ErrorType (at the moment)
// if this ever expands, this should be a specific form like () is for
// return.
// CTP_EnumCaseRawValue
// Substrings can't be raw values because they aren't literals.
// CTP_DefaultParameter
do {
func foo(x: Substring = s) {}
}
// CTP_CalleeResult
do {
func getString() -> String { return s }
let gottenSubstring: Substring = getString()
_ = gottenSubstring
}
// CTP_CallArgument
do {
func takesASubstring(_ ss: Substring) {}
takesASubstring(s)
}
// CTP_ClosureResult
do {
[s].map { (x: String) -> Substring in x }
}
// CTP_ArrayElement
do {
let a: [Substring] = [ s ]
_ = a
}
// CTP_DictionaryKey
do {
let d: [ Substring : Substring ] = [ s : ss ]
_ = d
}
// CTP_DictionaryValue
do {
let d: [ Substring : Substring ] = [ ss : s ]
_ = d
}
// CTP_CoerceOperand
do {
let s1: Substring = s as Substring
_ = s1
}
// CTP_AssignSource
do {
let s1: Substring = s
_ = s1
}
| apache-2.0 | c3415508f3c32fbd899d1e0693e544c0 | 16.5125 | 93 | 0.645967 | 3.191344 | false | false | false | false |
ljcoder2015/LJTool | LJToolDemo/LJToolDemo/ViewController.swift | 1 | 3329 | //
// ViewController.swift
// LJToolDemo
//
// Created by ljcoder on 2017/7/10.
// Copyright © 2017年 ljcoder. All rights reserved.
//
import UIKit
import LJTool
class ViewController: UIViewController {
fileprivate lazy var tableView: UITableView = {
let tableView: UITableView = UITableView.lj.tableView(dataSource: self, delegate: self)
tableView.backgroundColor = UIColor.lj.background
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "LJTool"
tableView.frame = view.bounds
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: TableView Delegate & DataSource
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
switch indexPath.row {
case 0:
cell.textLabel?.text = "UI Color"
case 1:
cell.textLabel?.text = "UI Create"
case 2:
cell.textLabel?.text = "LJTool Image"
case 3:
cell.textLabel?.text = "LJTool Button"
case 4:
cell.textLabel?.text = "LJTool String"
case 5:
cell.textLabel?.text = "UI Style"
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.001
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return nil
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
let color = LJColorViewController()
navigationController?.pushViewController(color, animated: true)
}
if indexPath.row == 1 {
let UI = LJTool_UICreateViewController()
navigationController?.pushViewController(UI, animated: true)
}
if indexPath.row == 2 {
let image = LJTool_ImageViewController()
navigationController?.pushViewController(image, animated: true)
}
if indexPath.row == 3 {
let button = LJButtonViewController()
navigationController?.pushViewController(button, animated: true)
}
if indexPath.row == 4 {
let string = LJStringViewController()
navigationController?.pushViewController(string, animated: true)
}
if indexPath.row == 5 {
let style = LJStyleViewController()
navigationController?.pushViewController(style, animated: true)
}
}
}
| mit | ca8353b7699445bfd3e7994d70adebe1 | 30.67619 | 100 | 0.625075 | 5.213166 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/QuizResultsCourses.swift | 1 | 1421 | //
// QuizResultsCourses.swift
// AwesomeCore
//
// Created by Leonardo Vinicius Kaminski Ferreira on 06/03/18.
//
import Foundation
public struct QuizResultsCourses: Codable {
public let courses: [QuizCourses]
}
public struct QuizCourses: Codable {
public let coverUrl: String
public let description: String
public let courseUrl: String
public let productId: Int?
public let academyId: Int?
public let courseId: Int?
init(coverUrl: String,
description: String,
courseUrl: String,
productId: Int?,
academyId: Int? = nil,
courseId: Int? = nil) {
self.coverUrl = coverUrl
self.description = description
self.courseUrl = courseUrl
self.productId = productId
self.academyId = academyId
self.courseId = courseId
}
}
// MARK: - Coding keys
extension QuizCourses {
private enum CodingKeys: String, CodingKey {
case coverUrl
case description
case courseUrl
case productId
case academyId = "academy_id"
case courseId = "course_id"
}
}
// MARK: - Equatable
extension QuizResultsCourses {
public static func ==(lhs: QuizResultsCourses, rhs: QuizResultsCourses) -> Bool {
if lhs.courses.first?.productId != rhs.courses.first?.productId {
return false
}
return true
}
}
| mit | 295c3c9642565323ff80f81a16d8dbee | 21.919355 | 85 | 0.625616 | 4.454545 | false | false | false | false |
zenangst/MarvinXcode | MarvinPlugin/Source/MarvinPlugin/NSDocument+Propersave.swift | 1 | 1507 | import Foundation
import Cocoa
final class SaveSwizzler {
fileprivate static var swizzled = false
fileprivate init() {
fatalError()
}
class func swizzle() {
if swizzled { return }
swizzled = true
var original, swizzle: Method
original = class_getInstanceMethod(NSDocument.self, #selector(NSDocument.save(withDelegate:didSave:contextInfo:)))
swizzle = class_getInstanceMethod(NSDocument.self, #selector(NSDocument.zen_saveDocumentWithDelegate(_:didSaveSelector:contextInfo:)))
method_exchangeImplementations(original, swizzle)
}
}
extension NSDocument {
dynamic func zen_saveDocumentWithDelegate(_ delegate: AnyObject?, didSaveSelector: Selector, contextInfo: UnsafeMutableRawPointer) {
if shouldFormat() {
NotificationCenter.default.post(name: Notification.Name(rawValue: "Save properly"), object: nil)
}
let delayTime = DispatchTime.now() + 0.25
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.zen_saveDocumentWithDelegate(delegate, didSaveSelector: didSaveSelector, contextInfo: contextInfo)
}
}
func shouldFormat() -> Bool {
guard let fileURL = fileURL
else { return false }
let pathExtension = fileURL.pathExtension
return [
"",
"c",
"cc",
"cpp",
"h",
"hpp",
"ipp",
"m", "mm",
"plist",
"rb",
"strings",
"swift",
"playground",
"md",
"yml"
]
.contains(pathExtension.lowercased())
}
}
| mit | 961f4dfc91d27f80faeb9ad2b3e8b4a6 | 22.920635 | 138 | 0.661579 | 4.525526 | false | false | false | false |
lockersoft/Winter2016-iOS | BMICalcLecture/Charts/Classes/Renderers/BarChartRenderer.swift | 1 | 23680 | //
// BarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class BarChartRenderer: ChartDataRendererBase
{
public weak var dataProvider: BarChartDataProvider?
public init(dataProvider: BarChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
public override func drawData(context context: CGContext)
{
guard let dataProvider = dataProvider, barData = dataProvider.barData else { return }
for (var i = 0; i < barData.dataSetCount; i++)
{
guard let set = barData.getDataSetByIndex(i) else { continue }
if set.isVisible && set.entryCount > 0
{
if !(set is IBarChartDataSet)
{
fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset")
}
drawDataSet(context: context, dataSet: set as! IBarChartDataSet, index: i)
}
}
}
public func drawDataSet(context context: CGContext, dataSet: IBarChartDataSet, index: Int)
{
guard let
dataProvider = dataProvider,
barData = dataProvider.barData,
animator = animator
else { return }
CGContextSaveGState(context)
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let drawBarShadowEnabled: Bool = dataProvider.isDrawBarShadowEnabled
let dataSetOffset = (barData.dataSetCount - 1)
let groupSpace = barData.groupSpace
let groupSpaceHalf = groupSpace / 2.0
let barSpace = dataSet.barSpace
let barSpaceHalf = barSpace / 2.0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(dataSet.axisDependency)
let barWidth: CGFloat = 0.5
let phaseY = animator.phaseY
var barRect = CGRect()
var barShadow = CGRect()
var y: Double
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)); j < count; j++)
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
// calculate the x-position, depending on datasetcount
let x = CGFloat(e.xIndex + e.xIndex * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(e.xIndex) + groupSpaceHalf
var vals = e.values
if (!containsStacks || vals == nil)
{
y = e.value
let left = x - barWidth + barSpaceHalf
let right = x + barWidth - barSpaceHalf
var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (top > 0)
{
top *= phaseY
}
else
{
bottom *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = barRect.origin.x
barShadow.origin.y = viewPortHandler.contentTop
barShadow.size.width = barRect.size.width
barShadow.size.height = viewPortHandler.contentHeight
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
CGContextFillRect(context, barRect)
}
else
{
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value
let left = x - barWidth + barSpaceHalf
let right = x + barWidth - barSpaceHalf
var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (top > 0)
{
top *= phaseY
}
else
{
bottom *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
barShadow.origin.x = barRect.origin.x
barShadow.origin.y = viewPortHandler.contentTop
barShadow.size.width = barRect.size.width
barShadow.size.height = viewPortHandler.contentHeight
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// fill the stack
for (var k = 0; k < vals!.count; k++)
{
let value = vals![k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let left = x - barWidth + barSpaceHalf
let right = x + barWidth - barSpaceHalf
var top: CGFloat, bottom: CGFloat
if isInverted
{
bottom = y >= yStart ? CGFloat(y) : CGFloat(yStart)
top = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
else
{
top = y >= yStart ? CGFloat(y) : CGFloat(yStart)
bottom = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
// multiply the height of the rect with the phase
top *= phaseY
bottom *= phaseY
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
// Skip to next bar
break
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor)
CGContextFillRect(context, barRect)
}
}
}
CGContextRestoreGState(context)
}
/// Prepares a bar for being highlighted.
public func prepareBarHighlight(x x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect)
{
let barWidth: CGFloat = 0.5
let left = x - barWidth + barspacehalf
let right = x + barWidth - barspacehalf
let top = CGFloat(y1)
let bottom = CGFloat(y2)
rect.origin.x = left
rect.origin.y = top
rect.size.width = right - left
rect.size.height = bottom - top
trans.rectValueToPixel(&rect, phaseY: animator?.phaseY ?? 1.0)
}
public override func drawValues(context context: CGContext)
{
// if values are drawn
if (passesCheck())
{
guard let
dataProvider = dataProvider,
barData = dataProvider.barData,
animator = animator
else { return }
var dataSets = barData.dataSets
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
var posOffset: CGFloat
var negOffset: CGFloat
for (var dataSetIndex = 0, count = barData.dataSetCount; dataSetIndex < count; dataSetIndex++)
{
guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue }
if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0
{
continue
}
let isInverted = dataProvider.isInverted(dataSet.axisDependency)
// calculate the correct offset depending on the draw position of the value
let valueOffsetPlus: CGFloat = 4.5
let valueFont = dataSet.valueFont
let valueTextHeight = valueFont.lineHeight
posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus)
negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus))
if (isInverted)
{
posOffset = -posOffset - valueTextHeight
negOffset = -negOffset - valueTextHeight
}
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let phaseY = animator.phaseY
let dataSetCount = barData.dataSetCount
let groupSpace = barData.groupSpace
// if only single values are drawn (sum)
if (!dataSet.isStacked)
{
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)); j < count; j++)
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let valuePoint = trans.getTransformedValueBarChart(
entry: e,
xIndex: e.xIndex,
dataSetIndex: dataSetIndex,
phaseY: phaseY,
dataSetCount: dataSetCount,
groupSpace: groupSpace
)
if (!viewPortHandler.isInBoundsRight(valuePoint.x))
{
break
}
if (!viewPortHandler.isInBoundsY(valuePoint.y)
|| !viewPortHandler.isInBoundsLeft(valuePoint.x))
{
continue
}
let val = e.value
drawValue(context: context,
value: formatter.stringFromNumber(val)!,
xPos: valuePoint.x,
yPos: valuePoint.y + (val >= 0.0 ? posOffset : negOffset),
font: valueFont,
align: .Center,
color: dataSet.valueTextColorAt(j))
}
}
else
{
// if we have stacks
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)); j < count; j++)
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let values = e.values
let valuePoint = trans.getTransformedValueBarChart(entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace)
// we still draw stacked bars, but there is one non-stacked in between
if (values == nil)
{
if (!viewPortHandler.isInBoundsRight(valuePoint.x))
{
break
}
if (!viewPortHandler.isInBoundsY(valuePoint.y)
|| !viewPortHandler.isInBoundsLeft(valuePoint.x))
{
continue
}
drawValue(context: context,
value: formatter.stringFromNumber(e.value)!,
xPos: valuePoint.x,
yPos: valuePoint.y + (e.value >= 0.0 ? posOffset : negOffset),
font: valueFont,
align: .Center,
color: dataSet.valueTextColorAt(j))
}
else
{
// draw stack values
let vals = values!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for (var k = 0; k < vals.count; k++)
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: 0.0, y: CGFloat(y) * animator.phaseY))
}
trans.pointValuesToPixel(&transformed)
for (var k = 0; k < transformed.count; k++)
{
let x = valuePoint.x
let y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset)
if (!viewPortHandler.isInBoundsRight(x))
{
break
}
if (!viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x))
{
continue
}
drawValue(context: context,
value: formatter.stringFromNumber(vals[k])!,
xPos: x,
yPos: y,
font: valueFont,
align: .Center,
color: dataSet.valueTextColorAt(j))
}
}
}
}
}
}
}
/// Draws a value at the specified x and y position.
public func drawValue(context context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: UIFont, align: NSTextAlignment, color: UIColor)
{
ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
}
public override func drawExtras(context context: CGContext)
{
}
private var _highlightArrowPtsBuffer = [CGPoint](count: 3, repeatedValue: CGPoint())
public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight])
{
guard let
dataProvider = dataProvider,
barData = dataProvider.barData,
animator = animator
else { return }
CGContextSaveGState(context)
let setCount = barData.dataSetCount
let drawHighlightArrowEnabled = dataProvider.isDrawHighlightArrowEnabled
var barRect = CGRect()
for (var i = 0; i < indices.count; i++)
{
let h = indices[i]
let index = h.xIndex
let dataSetIndex = h.dataSetIndex
guard let set = barData.getDataSetByIndex(dataSetIndex) as? IBarChartDataSet else { continue }
if (!set.isHighlightEnabled)
{
continue
}
let barspaceHalf = set.barSpace / 2.0
let trans = dataProvider.getTransformer(set.axisDependency)
CGContextSetFillColorWithColor(context, set.highlightColor.CGColor)
CGContextSetAlpha(context, set.highlightAlpha)
// check outofbounds
if (CGFloat(index) < (CGFloat(dataProvider.chartXMax) * animator.phaseX) / CGFloat(setCount))
{
let e = set.entryForXIndex(index) as! BarChartDataEntry!
if (e === nil || e.xIndex != index)
{
continue
}
let groupspace = barData.groupSpace
let isStack = h.stackIndex < 0 ? false : true
// calculate the correct x-position
let x = CGFloat(index * setCount + dataSetIndex) + groupspace / 2.0 + groupspace * CGFloat(index)
let y1: Double
let y2: Double
if (isStack)
{
y1 = h.range?.from ?? 0.0
y2 = h.range?.to ?? 0.0
}
else
{
y1 = e.value
y2 = 0.0
}
prepareBarHighlight(x: x, y1: y1, y2: y2, barspacehalf: barspaceHalf, trans: trans, rect: &barRect)
CGContextFillRect(context, barRect)
if (drawHighlightArrowEnabled)
{
CGContextSetAlpha(context, 1.0)
// distance between highlight arrow and bar
let offsetY = animator.phaseY * 0.07
CGContextSaveGState(context)
let pixelToValueMatrix = trans.pixelToValueMatrix
let xToYRel = abs(sqrt(pixelToValueMatrix.b * pixelToValueMatrix.b + pixelToValueMatrix.d * pixelToValueMatrix.d) / sqrt(pixelToValueMatrix.a * pixelToValueMatrix.a + pixelToValueMatrix.c * pixelToValueMatrix.c))
let arrowWidth = set.barSpace / 2.0
let arrowHeight = arrowWidth * xToYRel
let yArrow = (y1 > -y2 ? y1 : y1) * Double(animator.phaseY)
_highlightArrowPtsBuffer[0].x = CGFloat(x) + 0.4
_highlightArrowPtsBuffer[0].y = CGFloat(yArrow) + offsetY
_highlightArrowPtsBuffer[1].x = CGFloat(x) + 0.4 + arrowWidth
_highlightArrowPtsBuffer[1].y = CGFloat(yArrow) + offsetY - arrowHeight
_highlightArrowPtsBuffer[2].x = CGFloat(x) + 0.4 + arrowWidth
_highlightArrowPtsBuffer[2].y = CGFloat(yArrow) + offsetY + arrowHeight
trans.pointValuesToPixel(&_highlightArrowPtsBuffer)
CGContextBeginPath(context)
CGContextMoveToPoint(context, _highlightArrowPtsBuffer[0].x, _highlightArrowPtsBuffer[0].y)
CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[1].x, _highlightArrowPtsBuffer[1].y)
CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[2].x, _highlightArrowPtsBuffer[2].y)
CGContextClosePath(context)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
}
}
CGContextRestoreGState(context)
}
internal func passesCheck() -> Bool
{
guard let dataProvider = dataProvider, barData = dataProvider.barData else { return false }
return CGFloat(barData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX
}
} | unlicense | efd7255af2cf94fcb59380706cb575d7 | 40.184348 | 232 | 0.443581 | 6.518029 | false | false | false | false |
Paludis/Swifter | Swifter/SwifterStreaming.swift | 2 | 11188 | //
// SwifterStreaming.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
/*
POST statuses/filter
Returns public statuses that match one or more filter predicates. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Both GET and POST requests are supported, but GET requests with too many parameters may cause the request to be rejected for excessive URL length. Use a POST request to avoid long URLs.
The track, follow, and locations fields should be considered to be combined with an OR operator. track=foo&follow=1234 returns Tweets matching "foo" OR created by user 1234.
The default access level allows up to 400 track keywords, 5,000 follow userids and 25 0.1-360 degree location boxes. If you need elevated access to the Streaming API, you should explore our partner providers of Twitter data here: https://dev.twitter.com/programs/twitter-certified-products/products#Certified-Data-Products
At least one predicate parameter (follow, locations, or track) must be specified.
*/
public func postStatusesFilterWithFollow(follow: [String]? = nil, track: [String]? = nil, locations: [String]? = nil, delimited: Bool? = nil, stallWarnings: Bool? = nil, progress: ((status: Dictionary<String, JSONValue>? ) -> Void)? = nil, stallWarningHandler: ((code: String?, message: String?, percentFull: Int?) -> Void)? = nil, failure: FailureHandler? = nil) -> SwifterHTTPRequest {
assert(follow != nil || track != nil || locations != nil, "At least one predicate parameter (follow, locations, or track) must be specified")
let path = "statuses/filter.json"
var parameters = Dictionary<String, Any>()
if follow != nil {
parameters["follow"] = (follow!).joinWithSeparator(",")
}
if track != nil {
parameters["track"] = (track!).joinWithSeparator(",")
}
if locations != nil {
parameters["locations"] = (locations!).joinWithSeparator(",")
}
if delimited != nil {
parameters["delimited"] = delimited!
}
if stallWarnings != nil {
parameters["stall_warnings"] = stallWarnings!
}
return self.postJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: {
json, response in
if let stallWarning = json["warning"].object {
stallWarningHandler?(code: stallWarning["code"]?.string, message: stallWarning["message"]?.string, percentFull: stallWarning["percent_full"]?.integer)
}
else {
progress?(status: json.object)
}
}, success: {
json, response in
progress?(status: json.object)
return
}, failure: failure)
}
/*
GET statuses/sample
Returns a small random sample of all public statuses. The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.
*/
public func getStatusesSampleDelimited(delimited: Bool? = nil, stallWarnings: Bool? = nil, progress: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, stallWarningHandler: ((code: String?, message: String?, percentFull: Int?) -> Void)? = nil, failure: FailureHandler? = nil) -> SwifterHTTPRequest {
let path = "statuses/sample.json"
var parameters = Dictionary<String, Any>()
if delimited != nil {
parameters["delimited"] = delimited!
}
if stallWarnings != nil {
parameters["stall_warnings"] = stallWarnings!
}
return self.getJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: {
json, response in
if let stallWarning = json["warning"].object {
stallWarningHandler?(code: stallWarning["code"]?.string, message: stallWarning["message"]?.string, percentFull: stallWarning["percent_full"]?.integer)
}
else {
progress?(status: json.object)
}
}, success: {
json, response in
progress?(status: json.object)
return
}, failure: failure)
}
/*
GET statuses/firehose
This endpoint requires special permission to access.
Returns all public statuses. Few applications require this level of access. Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.
*/
public func getStatusesFirehose(count: Int? = nil, delimited: Bool? = nil, stallWarnings: Bool? = nil, progress: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, stallWarningHandler: ((code: String?, message: String?, percentFull: Int?) -> Void)? = nil, failure: FailureHandler? = nil) -> SwifterHTTPRequest {
let path = "statuses/firehose.json"
var parameters = Dictionary<String, Any>()
if count != nil {
parameters["count"] = count!
}
if delimited != nil {
parameters["delimited"] = delimited!
}
if stallWarnings != nil {
parameters["stall_warnings"] = stallWarnings!
}
return self.getJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: {
json, response in
if let stallWarning = json["warning"].object {
stallWarningHandler?(code: stallWarning["code"]?.string, message: stallWarning["message"]?.string, percentFull: stallWarning["percent_full"]?.integer)
}
else {
progress?(status: json.object)
}
}, success: {
json, response in
progress?(status: json.object)
return
}, failure: failure)
}
/*
GET user
Streams messages for a single user, as described in User streams https://dev.twitter.com/docs/streaming-apis/streams/user
*/
public func getUserStreamDelimited(delimited: Bool? = nil, stallWarnings: Bool? = nil, includeMessagesFromFollowedAccounts: Bool? = nil, includeReplies: Bool? = nil, track: [String]? = nil, locations: [String]? = nil, stringifyFriendIDs: Bool? = nil, progress: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, stallWarningHandler: ((code: String?, message: String?, percentFull: Int?) -> Void)? = nil, failure: FailureHandler? = nil) -> SwifterHTTPRequest {
let path = "user.json"
var parameters = Dictionary<String, Any>()
if delimited != nil {
parameters["delimited"] = delimited!
}
if stallWarnings != nil {
parameters["stall_warnings"] = stallWarnings!
}
if includeMessagesFromFollowedAccounts != nil {
if includeMessagesFromFollowedAccounts! {
parameters["with"] = "user"
}
}
if includeReplies != nil {
if includeReplies! {
parameters["replies"] = "all"
}
}
if track != nil {
parameters["track"] = (track!).joinWithSeparator(",")
}
if locations != nil {
parameters["locations"] = (locations!).joinWithSeparator(",")
}
if stringifyFriendIDs != nil {
parameters["stringify_friend_ids"] = stringifyFriendIDs!
}
return self.getJSONWithPath(path, baseURL: self.userStreamURL, parameters: parameters, uploadProgress: nil, downloadProgress: {
json, response in
if let stallWarning = json["warning"].object {
stallWarningHandler?(code: stallWarning["code"]?.string, message: stallWarning["message"]?.string, percentFull: stallWarning["percent_full"]?.integer)
}
else {
progress?(status: json.object)
}
}, success: {
json, response in
progress?(status: json.object)
return
}, failure: failure)
}
/*
GET site
Streams messages for a set of users, as described in Site streams https://dev.twitter.com/docs/streaming-apis/streams/site
*/
public func getSiteStreamDelimited(delimited: Bool? = nil, stallWarnings: Bool? = nil, restrictToUserMessages: Bool? = nil, includeReplies: Bool? = nil, stringifyFriendIDs: Bool? = nil, progress: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, stallWarningHandler: ((code: String?, message: String?, percentFull: Int?) -> Void)? = nil, failure: FailureHandler? = nil) -> SwifterHTTPRequest {
let path = "site.json"
var parameters = Dictionary<String, Any>()
if delimited != nil {
parameters["delimited"] = delimited!
}
if stallWarnings != nil {
parameters["stall_warnings"] = stallWarnings!
}
if restrictToUserMessages != nil {
if restrictToUserMessages! {
parameters["with"] = "user"
}
}
if includeReplies != nil {
if includeReplies! {
parameters["replies"] = "all"
}
}
if stringifyFriendIDs != nil {
parameters["stringify_friend_ids"] = stringifyFriendIDs!
}
return self.getJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: {
json, response in
stallWarningHandler?(code: json["warning"]["code"].string, message: json["warning"]["message"].string, percentFull: json["warning"]["percent_full"].integer)
}, success: {
json, response in
progress?(status: json.object)
return
}, failure: failure)
}
}
| mit | e3218adf4c32e9a6295c715afeda4777 | 43.047244 | 471 | 0.623257 | 4.809974 | false | false | false | false |
frajaona/LiFXSwiftKit | Sources/LiFXDevice.swift | 1 | 6159 | /*
* Copyright (C) 2016 Fred Rajaona
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public class LiFXDevice {
static let maxPowerLevel = 65535
static let minPowerLevel = 0
enum Service: Int {
case udp = 1
}
fileprivate let sourceNumber = 12345 as UInt32
fileprivate var generatedSequence: UInt8 = 0
fileprivate let transmitProtocolHandler: TransmitProtocolHandler
fileprivate let commandQueue = Queue<Command>()
fileprivate var currentCommand: Command?
let port: Int
let service: UInt8
let address: String
public var label: String?
var group: LiFXGroup?
var stateMessage: LiFXMessage!
var powerLevel = 0 {
didSet {
powerLevelProperty.value = powerLevel
}
}
public let powerLevelProperty = Property(value: 0)
var hue = 0 {
didSet {
hueProperty.value = hue
}
}
public let hueProperty = Property(value: 0)
var saturation = 0 {
didSet {
saturationProperty.value = hue
}
}
public let saturationProperty = Property(value: 0)
var brightness = 0 {
didSet {
brightnessProperty.value = hue
}
}
public let brightnessProperty = Property(value: 0)
var kelvin = 0 {
didSet {
kelvinProperty.value = hue
}
}
public let kelvinProperty = Property(value: 0)
public var uid: String {
return address + ":" + port.description
}
init(fromMessage message: LiFXMessage, address: String, session: LiFXSession) {
self.address = address
stateMessage = message
var payload = message.payload!
service = payload[0]
var value = 0
for index in 1...4 {
value += Int(payload[index]) << ((index - 1) * 8)
}
port = value
transmitProtocolHandler = TransmitProtocolHandler(socket: session.udpSocket.udpSocket!, address: self.address)
}
func switchOn() {
let command = CommandSwitchOn(transmitProtocolHandler: transmitProtocolHandler, sourceNumber: sourceNumber)
execute(command)
}
func switchOff() {
let command = CommandSwitchOff(transmitProtocolHandler: transmitProtocolHandler, sourceNumber: sourceNumber)
execute(command)
}
func toggle() {
let command = CommandToggle(transmitProtocolHandler: transmitProtocolHandler, sourceNumber: sourceNumber)
execute(command)
}
func getPower() {
let command = CommandGetPower(transmitProtocolHandler: transmitProtocolHandler, sourceNumber: sourceNumber)
execute(command)
}
func getInfo() {
let command = CommandGetLightInfo(transmitProtocolHandler: transmitProtocolHandler, sourceNumber: sourceNumber)
execute(command)
}
func getLabel() {
let command = CommandGetLabel(transmitProtocolHandler: transmitProtocolHandler, sourceNumber: sourceNumber)
execute(command)
}
func getGroup() {
let command = CommandGetGroup(transmitProtocolHandler: transmitProtocolHandler, sourceNumber: sourceNumber)
execute(command)
}
func setBrightness(_ brightness: Int) {
let command = CommandSetColor(transmitProtocolHandler: transmitProtocolHandler, sourceNumber: sourceNumber)
_ = command.setBrightness(brightness)
execute(command)
}
fileprivate func execute(_ command: Command) {
if let c = currentCommand , !c.isComplete() {
commandQueue.enQueue(c)
} else {
currentCommand = command
command.execute()
}
}
func onNewMessage(_ message: LiFXMessage) {
switch message.messageType {
case LiFXMessage.MessageType.lightStatePower:
powerLevel = LiFXMessage.getIntValue(fromData: message.payload!)
case LiFXMessage.MessageType.deviceStateGroup:
let g = LiFXGroup(fromData: message.payload!)
if g.valid {
group = g
}
case LiFXMessage.MessageType.deviceStateLabel:
label = LiFXMessage.getStringValue(fromData: message.payload!)
Log.debug("Device Label is \(label)")
case LiFXMessage.MessageType.lightState:
let info = LiFXLightInfo(fromData: message.payload!)
label = info.label
powerLevel = info.power
hue = info.hue
saturation = info.saturation
brightness = info.brightness
kelvin = info.kelvin
case LiFXMessage.MessageType.ack:
if sourceNumber == message.getSourceNumber() {
transmitProtocolHandler.handleReceivedAckNotification(message.getSequenceNumber())
}
default:
break
}
if let pendingCommand = currentCommand , pendingCommand.sourceNumber == message.getSourceNumber() {
currentCommand?.onNewMessage(message)
}
if let command = currentCommand {
if command.isComplete() {
handleNextCommand()
}
} else {
handleNextCommand()
}
}
func handleNextCommand() {
if commandQueue.size() > 0 {
currentCommand = commandQueue.deQueue()
if currentCommand != nil {
execute(currentCommand!)
}
} else {
currentCommand = nil
}
}
}
| apache-2.0 | 162ccbc93dc945dcdcbb3204dcb47fa5 | 29.043902 | 119 | 0.61471 | 4.861089 | false | false | false | false |
ngquerol/Diurna | App/Sources/Extensions/NSOutlineView+Additions.swift | 1 | 902 | //
// NSOutlineView+Additions.swift
// Diurna
//
// Created by Nicolas Gaulard-Querol on 02/07/2020.
// Copyright © 2020 Nicolas Gaulard-Querol. All rights reserved.
//
import AppKit
extension NSOutlineView {
func children(ofItem item: Any?) -> [Any?] {
let childCount = numberOfChildren(ofItem: item)
if childCount == 0 { return [] }
return (0..<childCount).map { child($0, ofItem: item) }
}
func numberOfDescendants(ofItem item: Any?) -> Int {
let childCount = numberOfChildren(ofItem: item)
guard childCount > 0 else { return 0 }
var descendantCount = childCount,
stack = children(ofItem: item)
while let child = stack.popLast() {
descendantCount += numberOfChildren(ofItem: child)
stack.append(contentsOf: children(ofItem: child))
}
return descendantCount
}
}
| mit | c43af4a85b9cb27c849e6c25c14e28fc | 24.742857 | 65 | 0.623751 | 4.25 | false | false | false | false |
wikimedia/apps-ios-wikipedia | FeaturedArticleWidget/FeaturedArticleWidget.swift | 1 | 6785 | import UIKit
import NotificationCenter
import WMF
private final class EmptyView: SetupView {
private let label = UILabel()
var theme: Theme = .widget
override func setup() {
super.setup()
label.text = WMFLocalizedString("featured-article-empty-title", value: "No featured article available today", comment: "Title that displays when featured article is not available")
label.textColor = theme.colors.primaryText
label.textAlignment = .center
label.numberOfLines = 0
wmf_addSubviewWithConstraintsToEdges(label)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
label.font = UIFont.wmf_font(.headline, compatibleWithTraitCollection: traitCollection)
}
}
class FeaturedArticleWidget: UIViewController, NCWidgetProviding {
let collapsedArticleView = ArticleRightAlignedImageCollectionViewCell()
let expandedArticleView = ArticleFullWidthImageCollectionViewCell()
var isExpanded = true
var currentArticleKey: String?
private lazy var emptyView = EmptyView()
override func viewDidLoad() {
super.viewDidLoad()
view.translatesAutoresizingMaskIntoConstraints = false
let tapGR = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
view.addGestureRecognizer(tapGR)
collapsedArticleView.preservesSuperviewLayoutMargins = true
collapsedArticleView.frame = view.bounds
view.addSubview(collapsedArticleView)
expandedArticleView.preservesSuperviewLayoutMargins = true
expandedArticleView.saveButton.addTarget(self, action: #selector(saveButtonPressed), for: .touchUpInside)
expandedArticleView.frame = view.bounds
view.addSubview(expandedArticleView)
view.wmf_addSubviewWithConstraintsToEdges(emptyView)
}
var isEmptyViewHidden = true {
didSet {
extensionContext?.widgetLargestAvailableDisplayMode = isEmptyViewHidden ? .expanded : .compact
emptyView.isHidden = isEmptyViewHidden
collapsedArticleView.isHidden = !isEmptyViewHidden
expandedArticleView.isHidden = !isEmptyViewHidden
}
}
var dataStore: MWKDataStore? {
return SessionSingleton.sharedInstance()?.dataStore
}
var article: WMFArticle? {
guard
let dataStore = dataStore,
let featuredContentGroup = dataStore.viewContext.newestVisibleGroup(of: .featuredArticle) ?? dataStore.viewContext.newestGroup(of: .featuredArticle),
let articleURL = featuredContentGroup.contentPreview as? URL else {
return nil
}
return dataStore.fetchArticle(with: articleURL)
}
func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) {
defer {
updateView()
}
guard let article = self.article,
let articleKey = article.key else {
isEmptyViewHidden = false
completionHandler(.failed)
return
}
guard articleKey != currentArticleKey else {
completionHandler(.noData)
return
}
currentArticleKey = articleKey
isEmptyViewHidden = true
let theme:Theme = .widget
collapsedArticleView.configure(article: article, displayType: .relatedPages, index: 0, shouldShowSeparators: false, theme: theme, layoutOnly: false)
collapsedArticleView.titleTextStyle = .body
collapsedArticleView.updateFonts(with: traitCollection)
collapsedArticleView.tintColor = theme.colors.link
expandedArticleView.configure(article: article, displayType: .pageWithPreview, index: 0, theme: theme, layoutOnly: false)
expandedArticleView.tintColor = theme.colors.link
expandedArticleView.saveButton.saveButtonState = article.savedDate == nil ? .longSave : .longSaved
completionHandler(.newData)
}
func updateViewAlpha(isExpanded: Bool) {
expandedArticleView.alpha = isExpanded ? 1 : 0
collapsedArticleView.alpha = isExpanded ? 0 : 1
}
@objc func updateView() {
guard viewIfLoaded != nil else {
return
}
var maximumSize = CGSize(width: view.bounds.size.width, height: UIView.noIntrinsicMetric)
if let context = extensionContext {
isExpanded = context.widgetActiveDisplayMode == .expanded
maximumSize = context.widgetMaximumSize(for: context.widgetActiveDisplayMode)
}
updateViewAlpha(isExpanded: isExpanded)
updateViewWithMaximumSize(maximumSize, isExpanded: isExpanded)
}
func updateViewWithMaximumSize(_ maximumSize: CGSize, isExpanded: Bool) {
let sizeThatFits: CGSize
if isExpanded {
sizeThatFits = expandedArticleView.sizeThatFits(CGSize(width: maximumSize.width, height:UIView.noIntrinsicMetric), apply: true)
expandedArticleView.frame = CGRect(origin: .zero, size:sizeThatFits)
} else {
collapsedArticleView.imageViewDimension = maximumSize.height - 30 //hax
sizeThatFits = collapsedArticleView.sizeThatFits(CGSize(width: maximumSize.width, height:UIView.noIntrinsicMetric), apply: true)
collapsedArticleView.frame = CGRect(origin: .zero, size:sizeThatFits)
}
preferredContentSize = CGSize(width: maximumSize.width, height: sizeThatFits.height)
}
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
debounceViewUpdate()
}
func debounceViewUpdate() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(updateView), object: nil)
perform(#selector(updateView), with: nil, afterDelay: 0.1)
}
@objc func saveButtonPressed() {
guard let article = self.article, let articleKey = article.key else {
return
}
let isSaved = dataStore?.savedPageList.toggleSavedPage(forKey: articleKey) ?? false
expandedArticleView.saveButton.saveButtonState = isSaved ? .longSaved : .longSave
}
@objc func handleTapGesture(_ tapGR: UITapGestureRecognizer) {
guard tapGR.state == .recognized else {
return
}
guard let article = self.article, let articleURL = article.url else {
return
}
let URL = articleURL as NSURL?
let URLToOpen = URL?.wmf_wikipediaScheme ?? NSUserActivity.wmf_baseURLForActivity(of: .explore)
self.extensionContext?.open(URLToOpen)
}
}
| mit | 0a7c1854d7ce15e20e084f916a692472 | 38.219653 | 188 | 0.68224 | 5.458568 | false | false | false | false |
tktsubota/CareKit | testing/OCKTest/OCKTest/CareCardTableViewController.swift | 2 | 26823 | /*
Copyright (c) 2016, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CareKit
class CareCardTableViewController: UITableViewController, OCKCarePlanStoreDelegate, OCKCareCardViewControllerDelegate {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 8
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") {
switch (indexPath as NSIndexPath).row {
case 0:
cell.textLabel?.text = "Many Activities, Many Schedules"
case 1:
cell.textLabel?.text = "With Delegate & Images"
case 2:
cell.textLabel?.text = "No Activities"
case 3:
cell.textLabel?.text = "Auto-Complete, No Edges"
case 4:
cell.textLabel?.text = "Activities don't complete"
case 5:
cell.textLabel?.text = "Custom Details (Run 'With Delegate' first)"
case 6:
cell.textLabel?.text = "Save an Image"
case 7:
cell.textLabel?.text = "Delete all Activites"
default:
cell.textLabel?.text = nil
}
return cell
} else {
return UITableViewCell.init()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let documentsDirectory = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
if (indexPath as NSIndexPath).row == 0 {
// Many Activities, Many Schedules
var startDateComponents = DateComponents.init()
startDateComponents.day = 20
startDateComponents.month = 2
startDateComponents.year = 2015
let dailySchedule:OCKCareSchedule = OCKCareSchedule.dailySchedule(withStartDate: startDateComponents, occurrencesPerDay: 2)
let weeklySchedule = OCKCareSchedule.weeklySchedule(withStartDate: startDateComponents, occurrencesOnEachDay:[4, 0, 4, 0, 4, 0, 4])
let alternateWeeklySchedule = OCKCareSchedule.weeklySchedule(withStartDate: startDateComponents, occurrencesOnEachDay: [0, 1, 0, 0, 0, 0, 0], weeksToSkip: 1, endDate: nil)
let skipDaysSchedule = OCKCareSchedule.dailySchedule(withStartDate: startDateComponents, occurrencesPerDay: 5, daysToSkip: 2, endDate: nil)
var carePlanActivities = [OCKCarePlanActivity]()
let firstGroupId = "Group I1"
carePlanActivities.append(OCKCarePlanActivity.init(identifier: "Intervention Activity #1", groupIdentifier: firstGroupId, type: OCKCarePlanActivityType.intervention, title: "Daily Intervention Activity Title 1", text: "Read the instructions about this task", tintColor: nil, instructions: "Perform the described task and report the results. Talk to your doctor if you need help", imageURL: nil, schedule: dailySchedule, resultResettable: true, userInfo: ["Key1":"Value1" as NSCoding,"Key2":"Value2" as NSCoding]))
carePlanActivities.append(OCKCarePlanActivity.init(identifier: "Intervention Activity #2", groupIdentifier: firstGroupId, type: OCKCarePlanActivityType.intervention, title: "Alternate-Day Intervention Activity Title 2", text: "Complete this activity ASAP. No Instructions!", tintColor: UIColor.brown, instructions: nil, imageURL: nil, schedule: weeklySchedule, resultResettable: true, userInfo: ["Key1":"Value1" as NSCoding, "Key2":"Value2" as NSCoding]))
carePlanActivities.append(OCKCarePlanActivity.init(identifier: "Intervention Activity 3", groupIdentifier: firstGroupId, type: OCKCarePlanActivityType.intervention, title: "Repeats Every Three Days", text: "This is a long line of text. It describes the Activity in detail", tintColor: UIColor.red, instructions: LoremIpsum, imageURL: nil, schedule: skipDaysSchedule, resultResettable: false, userInfo:nil))
carePlanActivities.append(OCKCarePlanActivity.init(identifier: "Intervention Activity #4", groupIdentifier: firstGroupId, type: OCKCarePlanActivityType.intervention, title: "Every other-Monday", text: "I am activity #4", tintColor: UIColor.green, instructions: nil, imageURL: nil, schedule: alternateWeeklySchedule, resultResettable: false, userInfo: nil))
carePlanActivities.append(OCKCarePlanActivity.init(identifier: "Intervention Activity #5", groupIdentifier: firstGroupId, type: OCKCarePlanActivityType.intervention, title: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.", text: "This is the text", tintColor: nil, instructions: "Take pain medication", imageURL: nil, schedule: dailySchedule, resultResettable: false, userInfo: nil))
let activity6 = OCKCarePlanActivity.init(identifier: "Intervention Activity #6", groupIdentifier: firstGroupId, type: OCKCarePlanActivityType.intervention, title: "Activity Ended Yesterday", text: LoremIpsum, tintColor: UIColor.gray, instructions: LoremIpsum, imageURL: nil, schedule: dailySchedule, resultResettable: true, userInfo: nil)
carePlanActivities.append(activity6)
carePlanActivities.append(OCKCarePlanActivity.intervention(withIdentifier: "Intervention Activity #7", groupIdentifier: nil, title: "No Group, No Text Activity", text: nil, tintColor: nil, instructions: nil, imageURL: nil, schedule: dailySchedule, userInfo: nil))
carePlanActivities.append(OCKCarePlanActivity.intervention(withIdentifier: "Intervention Activity #8", groupIdentifier: nil, title: "", text: "Missing Title", tintColor: UIColor.purple, instructions: "Some Instructions", imageURL: nil, schedule: dailySchedule, userInfo: ["":""]))
let carePlanStore = OCKCarePlanStore.init(persistenceDirectoryURL: URL.init(string: documentsDirectory[0])!)
for carePlanActivity in carePlanActivities {
carePlanStore.add(carePlanActivity, completion: { (boolVal, error) in
assert(boolVal, (error?.localizedDescription)!)
})
}
let dateComponents = NSCalendar.current.dateComponents([.year, .month, .day, .era], from: Date().addingTimeInterval(-86400.0))
carePlanStore.setEndDate(dateComponents, for: activity6, completion: { (boolVal, activity, error) in
})
let careCardController = OCKCareCardViewController.init(carePlanStore: carePlanStore)
careCardController.showEdgeIndicators = true
self.navigationController?.pushViewController(careCardController, animated: true)
} else if (indexPath as NSIndexPath).row == 1 {
// With Delegate & Images
let dateComponents = DateComponents.init(year: 2015, month: 2, day: 20)
let schedule = OCKCareSchedule.dailySchedule(withStartDate: dateComponents, occurrencesPerDay: 6)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let imageFileURL = documentsURL.appendingPathComponent("Triangles.jpg")
let secondGroupId = "Group I2"
let carePlanActivity1 = OCKCarePlanActivity.init(identifier: "Intervention Activity 1", groupIdentifier: secondGroupId, type: OCKCarePlanActivityType.intervention, title: "1. This is the first Intervention Activity", text: "", tintColor: UIColor.red, instructions: "No instructions required", imageURL: imageFileURL, schedule: schedule, resultResettable: true, userInfo: ["Key1":"Value1" as NSCoding,"Key2":"Value2" as NSCoding])
let carePlanActivity2 = OCKCarePlanActivity.init(identifier: "Intervention Activity 2", groupIdentifier: secondGroupId, type: OCKCarePlanActivityType.intervention, title: "2. Another Intervention Activity", text: "Complete this activity ASAP. No Instructions!", tintColor: nil, instructions: nil, imageURL: imageFileURL, schedule: schedule, resultResettable: true, userInfo: nil)
let carePlanActivity3 = OCKCarePlanActivity.intervention(withIdentifier: "Intervention Activity 3", groupIdentifier: secondGroupId, title: "3. Activity #3 is the last one", text: "Some Text", tintColor: UIColor.purple, instructions: "Some Instructions", imageURL: imageFileURL, schedule: schedule, userInfo: ["Key":"Val"])
let dataPath = documentsDirectory[0] + "/CarePlan2"
if !FileManager.default.fileExists(atPath: dataPath) {
do {
try FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
} catch(_) {
assertionFailure("Unable to Create Directory for CarePlan2")
}
}
let carePlanStore = OCKCarePlanStore.init(persistenceDirectoryURL: URL.init(string: dataPath)!)
carePlanStore.delegate = self
carePlanStore.add(carePlanActivity1, completion: { (boolVal, error) in
assert(boolVal, (error?.localizedDescription)!)
})
carePlanStore.add(carePlanActivity2, completion: { (boolVal, error) in
assert(boolVal, (error?.localizedDescription)!)
})
carePlanStore.add(carePlanActivity3, completion: { (boolVal, error) in
assert(boolVal, (error?.localizedDescription)!)
})
let careCardController = OCKCareCardViewController.init(carePlanStore: carePlanStore)
careCardController.maskImage = UIImage.init(named: "Stars")
careCardController.smallMaskImage = UIImage.init(named: "Triangles.jpg")
careCardController.maskImageTintColor = UIColor.cyan
careCardController.showEdgeIndicators = true
self.navigationController?.pushViewController(careCardController, animated: true)
} else if (indexPath as NSIndexPath).row == 2 {
// No Activities
let dataPath = documentsDirectory[0] + "/EmptyCarePlan"
if !FileManager.default.fileExists(atPath: dataPath) {
do {
try FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
} catch(_) {
assertionFailure("Unable to Create Directory for EmptyCarePlan")
}
}
let carePlanStore = OCKCarePlanStore.init(persistenceDirectoryURL: URL.init(string: dataPath)!)
let careCardController = OCKCareCardViewController.init(carePlanStore: carePlanStore)
careCardController.maskImageTintColor = UIColor.orange
self.navigationController?.pushViewController(careCardController, animated: true)
} else if (indexPath as NSIndexPath).row == 3 {
// Auto-Complete, No Edges
let startDateComponents = DateComponents.init(year: 2012, month: 12, day: 12)
let endDateComponents = DateComponents.init(year: 3000, month: 03, day: 30)
let schedule = OCKCareSchedule.dailySchedule(withStartDate: startDateComponents, occurrencesPerDay: 5, daysToSkip: 0, endDate: endDateComponents)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let imageFileURL = documentsURL.appendingPathComponent("Triangles.jpg")
let dataPath = documentsDirectory[0] + "/CarePlanAuto"
if !FileManager.default.fileExists(atPath: dataPath) {
do {
try FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
} catch(_) {
assertionFailure("Unable to Create Directory for CarePlanAuto")
}
}
let carePlanStore = OCKCarePlanStore.init(persistenceDirectoryURL: URL.init(string: dataPath)!)
for index in 1...30 {
let carePlanActivity = OCKCarePlanActivity.init(identifier: "Intervention Activity" + String(index), groupIdentifier: "Group I2", type: OCKCarePlanActivityType.intervention, title: "Activity Title"+String(index), text: "Text Text Text" + String(index), tintColor: UIColor.init(red: 0.2, green: 0.4, blue: 0.9, alpha: 0.4), instructions: "This is a set of instructions for activity #" + String(index), imageURL: imageFileURL, schedule: schedule, resultResettable: true, userInfo: nil)
carePlanStore.add(carePlanActivity, completion: { (boolVal, error) in
assert(boolVal, (error?.localizedDescription)!)
})
}
let dateComponents = NSCalendar.current.dateComponents([.year, .month, .day, .era], from: Date())
carePlanStore.events(onDate: dateComponents, type: OCKCarePlanActivityType.intervention, completion: { (allEventsArray, error) in
for activityEvents in allEventsArray {
for event in activityEvents {
carePlanStore.update(event, with: nil, state: OCKCarePlanEventState.completed, completion: { (boolVal, event, error) in
})
}
}
})
let careCardController = OCKCareCardViewController.init(carePlanStore: carePlanStore)
careCardController.maskImageTintColor = UIColor.init(red: 0.2, green: 0.4, blue: 0.9, alpha: 0.4)
self.navigationController?.pushViewController(careCardController, animated: true)
} else if (indexPath as NSIndexPath).row == 4 {
// Activities don't complete
let dateComponents = DateComponents.init(year: 2015, month: 2, day: 20)
let schedule = OCKCareSchedule.dailySchedule(withStartDate: dateComponents, occurrencesPerDay: 14)
let fourthGroupId = "Group I4"
let carePlanActivity1 = OCKCarePlanActivity.init(identifier: "ActivityDoesntComplete1", groupIdentifier: fourthGroupId, type: OCKCarePlanActivityType.intervention, title: "Does not Complete", text: "Tint color changes on tap", tintColor: UIColor.blue, instructions: "No instructions required", imageURL: nil, schedule: schedule, resultResettable: true, userInfo:nil)
let carePlanActivity2 = OCKCarePlanActivity.init(identifier: "ActivityDoesntComplete2", groupIdentifier: fourthGroupId, type: OCKCarePlanActivityType.intervention, title: "Does not Complete", text: "Tint color changes on tap", tintColor: UIColor.purple, instructions: "", imageURL: nil, schedule: schedule, resultResettable: true, userInfo:nil)
let dataPath = documentsDirectory[0] + "/CarePlanIncomplete"
if !FileManager.default.fileExists(atPath: dataPath) {
do {
try FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
} catch(_) {
assertionFailure("Unable to Create Directory for CarePlanIncomplete")
}
}
let carePlanStore = OCKCarePlanStore.init(persistenceDirectoryURL: URL.init(string: dataPath)!)
carePlanStore.delegate = self
carePlanStore.add(carePlanActivity1, completion: { (boolVal, error) in
assert(boolVal, (error?.localizedDescription)!)
})
carePlanStore.add(carePlanActivity2, completion: { (boolVal, error) in
assert(boolVal, (error?.localizedDescription)!)
})
let careCardController = OCKCareCardViewController.init(carePlanStore: carePlanStore)
careCardController.delegate = self
careCardController.smallMaskImage = UIImage.init(named: "Stars")
careCardController.showEdgeIndicators = true
self.navigationController?.pushViewController(careCardController, animated: true)
} else if (indexPath as NSIndexPath).row == 5 {
// Custom Details for Activities
let dataPath = documentsDirectory[0] + "/CarePlan2"
if !FileManager.default.fileExists(atPath: dataPath) {
return
}
let carePlanStore = OCKCarePlanStore.init(persistenceDirectoryURL: URL.init(string: dataPath)!)
let careCardController = OCKCareCardViewController.init(carePlanStore: carePlanStore)
careCardController.delegate = self
careCardController.showEdgeIndicators = true
self.navigationController?.pushViewController(careCardController, animated: true)
} else if (indexPath as NSIndexPath).row == 6 {
// Save an Image
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
if let image = UIImage.init(named: "Triangles.jpg") {
let imageFileURL = documentsURL.appendingPathComponent("Triangles.jpg")
if let jpgImageData = UIImageJPEGRepresentation(image,0.5) {
try? jpgImageData.write(to: imageFileURL, options: [])
}
}
tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.green
tableView.cellForRow(at: indexPath)?.isSelected = false
} else if (indexPath as NSIndexPath).row == 7 {
// Delete all Activites
tableView.cellForRow(at: indexPath)?.isSelected = false
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let store = OCKCarePlanStore.init(persistenceDirectoryURL: URL.init(string: paths[0])!)
store.activities(with: OCKCarePlanActivityType.intervention, completion: { (boolVal, activities, error) in
for activity:OCKCarePlanActivity in activities {
store.remove(activity, completion: { (boolVal, error) in
if boolVal == true {
tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.green
} else {
tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.red
}
assert(boolVal, (error?.localizedDescription)!)
})
}
})
if FileManager.default.fileExists(atPath: paths[0] + "/CarePlan2") {
let dataPath = URL.init(string:paths[0] + "/CarePlan2")
let store2 = OCKCarePlanStore.init(persistenceDirectoryURL: dataPath!)
store2.activities(withGroupIdentifier: "Group I2", completion: { (boolVal, activities, error) in
for activity:OCKCarePlanActivity in activities {
store2.remove(activity, completion: { (bool, error) in
if boolVal == true {
tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.green
} else {
tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.red
}
assert(boolVal, (error?.localizedDescription)!)
})
}
})
}
if FileManager.default.fileExists(atPath: paths[0] + "/CarePlanAuto") {
let dataPath = URL.init(string:paths[0] + "/CarePlanAuto")
let store3 = OCKCarePlanStore.init(persistenceDirectoryURL: dataPath!)
store3.activities(completion: { (boolVal, activities, error) in
for activity in activities
{
store3.remove(activity, completion: { (boolVal, error) in
if boolVal == true {
tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.green
} else {
tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.red
}
assert(boolVal, (error?.localizedDescription)!)
})
}
})
}
if FileManager.default.fileExists(atPath: paths[0] + "/CarePlanIncomplete") {
let dataPath = URL.init(string:paths[0] + "/CarePlanIncomplete")
let store4 = OCKCarePlanStore.init(persistenceDirectoryURL: dataPath!)
store4.activities(completion: { (boolVal, activities, error) in
for activity in activities {
store4.remove(activity, completion: { (boolVal, error) in
if boolVal == true {
tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.green
} else {
tableView.cellForRow(at: indexPath)?.textLabel?.textColor = UIColor.red
}
assert(boolVal, (error?.localizedDescription)!)
})
}
})
}
}
}
func careCardViewController(_ viewController: OCKCareCardViewController, shouldHandleEventCompletionFor interventionActivity: OCKCarePlanActivity) -> Bool {
if interventionActivity.groupIdentifier == "Group I4" {
return false
}
return true
}
func careCardViewController(_ viewController: OCKCareCardViewController, didSelectButtonWithInterventionEvent interventionEvent: OCKCarePlanEvent) {
if interventionEvent.activity.groupIdentifier == "Group I4" {
viewController.maskImageTintColor = interventionEvent.activity.tintColor
}
}
func careCardViewController(_ viewController: OCKCareCardViewController, didSelectRowWithInterventionActivity interventionActivity: OCKCarePlanActivity) {
if interventionActivity.groupIdentifier == "Group I2" {
let detailsViewController = UIViewController.init()
detailsViewController.view.backgroundColor = UIColor.gray
let textView = UITextView.init(frame: CGRect(x: 30, y: 100, width: 300, height: 400))
textView.backgroundColor = UIColor.white
textView.isEditable = false
var text = interventionActivity.title + "\n"
let dateComponents = NSCalendar.current.dateComponents([.year, .month, .day, .era], from: Date())
viewController.store.enumerateEvents(of: interventionActivity, startDate: dateComponents, endDate: dateComponents, handler:
{ (event, stop) in
text = text + ("Occurence #" + String(event!.occurrenceIndexOfDay))
text = text + (" : State " + String(event!.state.rawValue) + "\n")
}, completion: { (completed, error) in
if completed == true {
DispatchQueue.main.async{
textView.text = text
detailsViewController.view.addSubview(textView)
viewController.navigationController?.pushViewController(detailsViewController, animated: true)
}
} else {
assert(completed, (error?.localizedDescription)!)
}
})
}
}
func carePlanStoreActivityListDidChange(_ store: OCKCarePlanStore) {
print("carePlanStoreActivityListDidChange")
}
func carePlanStore(_ store: OCKCarePlanStore, didReceiveUpdateOf event: OCKCarePlanEvent) {
print("Care Event Details\n")
print("Occurence: " + String(event.occurrenceIndexOfDay))
print("Days Since Start: " + String(event.numberOfDaysSinceStart))
print("Date: " + String(describing: event.date))
print("Activity: " + String(event.activity.title))
print("State: " + String(event.state.rawValue))
print("Result: " + String(describing: event.result))
}
}
| bsd-3-clause | 930da9a68d0aba357e4a91531a3c9c16 | 60.946882 | 525 | 0.636991 | 5.165222 | false | false | false | false |
coach-plus/ios | CoachPlus/helperclasses/Helpers.swift | 1 | 2438 | //
// Helpers.swift
// CoachPlus
//
// Created by Breit, Maurice on 25.03.17.
// Copyright © 2017 Mathandoro GbR. All rights reserved.
//
import Foundation
import SwiftyJSON
import MBProgressHUD
protocol JSONable {
init?(json: JSON)
}
protocol BackJSONable {
func toJson() -> JSON
}
extension Array where Element:Event {
func upcoming() -> [Event] {
return self.filterEvents(selection: .upcoming).sorted(by: {(eventA, eventB) in
return eventA.start < eventB.start
})
}
func past() -> [Event] {
return self.filterEvents(selection: .past).sorted(by: {(eventA, eventB) in
return eventA.end > eventB.end
})
}
func filterEvents(selection: EventListViewController.Selection) -> [Event] {
let filterPast = selection == .past
let events = self.filter({event in
return filterPast == event.isInPast()
})
return events
}
}
extension Array where Element:BackJSONable {
func toJsonArray() -> [JSON] {
return self.map({(element:BackJSONable) -> (JSON) in
return element.toJson()
})
}
func toStrings() -> [String] {
return self.toJsonArray().toStringsArray()
}
func toString() -> String {
var jsonArray = [JSON]()
jsonArray = self.toStrings().map({itemString in
return JSON(parseJSON: itemString)
})
return JSON(jsonArray).rawString()!
}
}
extension Sequence where Iterator.Element == JSON {
func toStringsArray() -> [String] {
return self.map({(element:JSON) -> (String) in
return element.rawString()!
})
}
}
extension String {
func toObject<T:JSONable>(_ t:T.Type) -> T {
let json = JSON(parseJSON: self)
return T(json: json)!
}
func toArray<T:JSONable>(_ t:T.Type) -> [T] {
let json = JSON(parseJSON: self)
return json.arrayValue.map({json in
return T(json: json)!
})
}
}
extension MBProgressHUD {
static func createHUD(view:UIView, msg:String) -> MBProgressHUD {
let hud = MBProgressHUD(view: view)
hud.graceTime = 0.5
hud.detailsLabel.text = msg.localize()
hud.mode = .indeterminate
hud.animationType = .zoom
view.addSubview(hud)
hud.show(animated: true)
return hud
}
}
| mit | 9e945428ef44779cd85f052ea5a74710 | 23.37 | 86 | 0.579811 | 4.095798 | false | false | false | false |
jasnig/UsefulPickerView | Source/UsefulPickerView.swift | 2 | 14581 | //
// UsefulPickerView.swift
// UsefulPickerVIew
//
// Created by jasnig on 16/4/16.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public class UsefulPickerView: UIView {
public typealias BtnAction = () -> Void
public typealias SingleDoneAction = (selectedIndex: Int, selectedValue: String) -> Void
public typealias MultipleDoneAction = (selectedIndexs: [Int], selectedValues: [String]) -> Void
public typealias DateDoneAction = (selectedDate: NSDate) -> Void
public typealias MultipleAssociatedDataType = [[[String: [String]?]]]
private var pickerView: PickerView!
//MARK:- 常量
private let pickerViewHeight:CGFloat = 260.0
private let screenWidth = UIScreen.mainScreen().bounds.size.width
private let screenHeight = UIScreen.mainScreen().bounds.size.height
private var hideFrame: CGRect {
return CGRect(x: 0.0, y: screenHeight, width: screenWidth, height: pickerViewHeight)
}
private var showFrame: CGRect {
return CGRect(x: 0.0, y: screenHeight - pickerViewHeight, width: screenWidth, height: pickerViewHeight)
}
/// 使用NSArray 可以存任何"东西", 如果使用 [Any], 那么当
/// let a = ["1", "2"] var b:[Any] = a 会报错
// MARK:- 初始化
// 单列
convenience init(frame: CGRect, toolBarTitle: String, singleColData: [String], defaultSelectedIndex: Int?, doneAction: SingleDoneAction?) {
self.init(frame: frame)
pickerView = PickerView.singleColPicker(toolBarTitle, singleColData: singleColData, defaultIndex: defaultSelectedIndex, cancelAction: {[unowned self] in
// 点击取消的时候移除
self.hidePicker()
}, doneAction: {[unowned self] (selectedIndex, selectedValue) in
doneAction?(selectedIndex: selectedIndex, selectedValue: selectedValue)
self.hidePicker()
})
pickerView.frame = hideFrame
addSubview(pickerView)
// 点击背景移除self
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
addGestureRecognizer(tap)
}
// 多列不关联
convenience init(frame: CGRect, toolBarTitle: String, multipleColsData: [[String]], defaultSelectedIndexs: [Int]?, doneAction: MultipleDoneAction?) {
self.init(frame: frame)
pickerView = PickerView.multipleCosPicker(toolBarTitle, multipleColsData: multipleColsData, defaultSelectedIndexs: defaultSelectedIndexs, cancelAction: {[unowned self] in
// 点击取消的时候移除
self.hidePicker()
}, doneAction: {[unowned self] (selectedIndexs, selectedValues) in
doneAction?(selectedIndexs: selectedIndexs, selectedValues: selectedValues)
self.hidePicker()
})
pickerView.frame = hideFrame
addSubview(pickerView)
// 点击背景移除self
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
addGestureRecognizer(tap)
}
// 多列关联
convenience init(frame: CGRect, toolBarTitle: String, multipleAssociatedColsData: MultipleAssociatedDataType, defaultSelectedValues: [String]?, doneAction: MultipleDoneAction?) {
self.init(frame: frame)
pickerView = PickerView.multipleAssociatedCosPicker(toolBarTitle, multipleAssociatedColsData: multipleAssociatedColsData, defaultSelectedValues: defaultSelectedValues, cancelAction: {[unowned self] in
// 点击取消的时候移除
self.hidePicker()
}, doneAction: {[unowned self] (selectedIndexs, selectedValues) in
doneAction?(selectedIndexs: selectedIndexs, selectedValues: selectedValues)
self.hidePicker()
})
pickerView.frame = hideFrame
addSubview(pickerView)
// 点击背景移除self
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
addGestureRecognizer(tap)
}
// 城市选择器
convenience init(frame: CGRect, toolBarTitle: String, defaultSelectedValues: [String]?, doneAction: MultipleDoneAction?) {
self.init(frame: frame)
pickerView = PickerView.citiesPicker(toolBarTitle, defaultSelectedValues: defaultSelectedValues, cancelAction: {[unowned self] in
// 点击取消的时候移除
self.hidePicker()
}, doneAction: {[unowned self] (selectedIndexs, selectedValues) in
doneAction?(selectedIndexs: selectedIndexs, selectedValues: selectedValues)
self.hidePicker()
})
pickerView.frame = hideFrame
addSubview(pickerView)
// 点击背景移除self
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
addGestureRecognizer(tap)
}
// 日期选择器
convenience init(frame: CGRect, toolBarTitle: String, datePickerSetting: DatePickerSetting, doneAction: DateDoneAction?) {
self.init(frame: frame)
pickerView = PickerView.datePicker(toolBarTitle, datePickerSetting: datePickerSetting, cancelAction: {[unowned self] in
// 点击取消的时候移除
self.hidePicker()
}, doneAction: {[unowned self] (selectedDate) in
doneAction?(selectedDate: selectedDate)
self.hidePicker()
})
pickerView.frame = hideFrame
addSubview(pickerView)
// 点击背景移除self
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
addGestureRecognizer(tap)
}
override init(frame: CGRect) {
super.init(frame: frame)
addOrentationObserver()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
print("\(self.debugDescription) --- 销毁")
}
}
// MARK:- selector
extension UsefulPickerView {
private func addOrentationObserver() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.statusBarOrientationChange), name: UIApplicationDidChangeStatusBarOrientationNotification, object: nil)
}
// 屏幕旋转时移除pickerView
func statusBarOrientationChange() {
removeFromSuperview()
}
func tapAction(tap: UITapGestureRecognizer) {
let location = tap.locationInView(self)
// 点击空白背景移除self
if location.y <= screenHeight - pickerViewHeight {
self.hidePicker()
}
}
}
// MARK:- 弹出和移除self
extension UsefulPickerView {
private func showPicker() {
// 通过window 弹出view
let window = UIApplication.sharedApplication().keyWindow
guard let currentWindow = window else { return }
currentWindow.addSubview(self)
// let pickerX = NSLayoutConstraint(item: self, attribute: .Leading, relatedBy: .Equal, toItem: currentWindow, attribute: .Leading, multiplier: 1.0, constant: 0.0)
//
// let pickerY = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: currentWindow, attribute: .Top, multiplier: 1.0, constant: 0.0)
// let pickerW = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal, toItem: currentWindow, attribute: .Width, multiplier: 1.0, constant: 0.0)
// let pickerH = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: currentWindow, attribute: .Height, multiplier: 1.0, constant: 0.0)
// self.translatesAutoresizingMaskIntoConstraints = false
//
// currentWindow.addConstraints([pickerX, pickerY, pickerW, pickerH])
UIView.animateWithDuration(0.25, animations: {[unowned self] in
self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.1)
self.pickerView.frame = self.showFrame
}, completion: nil)
}
func hidePicker() {
// 把self从window中移除
UIView.animateWithDuration(0.25, animations: { [unowned self] in
self.backgroundColor = UIColor.clearColor()
self.pickerView.frame = self.hideFrame
}) {[unowned self] (_) in
self.removeFromSuperview()
}
}
}
// MARK: - 快速使用方法
extension UsefulPickerView {
/// 单列选择器 /// @author ZeroJ, 16-04-23 18:04:59
///
/// - parameter title: 标题
/// - parameter data: 数据
/// - parameter defaultSeletedIndex: 默认选中的行数
/// - parameter doneAction: 响应完成的Closure
///
/// - returns:
public class func showSingleColPicker(toolBarTitle: String, data: [String], defaultSelectedIndex: Int?, doneAction: SingleDoneAction?) {
let window = UIApplication.sharedApplication().keyWindow
guard let currentWindow = window else { return }
let testView = UsefulPickerView(frame: currentWindow.bounds, toolBarTitle: toolBarTitle, singleColData: data,defaultSelectedIndex: defaultSelectedIndex ,doneAction: doneAction)
testView.showPicker()
}
/// 多列不关联选择器 /// @author ZeroJ, 16-04-23 18:04:59
///
/// - parameter title: 标题
/// - parameter data: 数据
/// - parameter defaultSeletedIndexs: 默认选中的每一列的行数
/// - parameter doneAction: 响应完成的Closure
///
/// - returns:
public class func showMultipleColsPicker(toolBarTitle: String, data: [[String]], defaultSelectedIndexs: [Int]?,doneAction: MultipleDoneAction?) {
let window = UIApplication.sharedApplication().keyWindow
guard let currentWindow = window else { return }
let testView = UsefulPickerView(frame: currentWindow.bounds, toolBarTitle: toolBarTitle, multipleColsData: data, defaultSelectedIndexs: defaultSelectedIndexs, doneAction: doneAction)
testView.showPicker()
}
/// 多列关联选择器 /// @author ZeroJ, 16-04-23 18:04:59
///
/// - parameter title: 标题
/// - parameter data: 数据, 数据的格式参照示例
/// - parameter defaultSeletedIndexs: 默认选中的每一列的行数
/// - parameter doneAction: 响应完成的Closure
///
/// - returns:
public class func showMultipleAssociatedColsPicker(toolBarTitle: String, data: MultipleAssociatedDataType, defaultSelectedValues: [String]?, doneAction: MultipleDoneAction?) {
let window = UIApplication.sharedApplication().keyWindow
guard let currentWindow = window else { return }
let testView = UsefulPickerView(frame: currentWindow.bounds, toolBarTitle: toolBarTitle, multipleAssociatedColsData: data, defaultSelectedValues: defaultSelectedValues, doneAction: doneAction)
testView.showPicker()
}
/// 城市选择器 /// @author ZeroJ, 16-04-23 18:04:59
///
/// - parameter title: 标题
/// - parameter defaultSeletedValues: 默认选中的每一列的值, 注意不是行数
/// - parameter doneAction: 响应完成的Closure
///
/// - returns:
public class func showCitiesPicker(toolBarTitle: String, defaultSelectedValues: [String]?, doneAction: MultipleDoneAction?) {
let window = UIApplication.sharedApplication().keyWindow
guard let currentWindow = window else { return }
let testView = UsefulPickerView(frame: currentWindow.bounds, toolBarTitle: toolBarTitle, defaultSelectedValues: defaultSelectedValues, doneAction: doneAction)
testView.showPicker()
}
/// 日期选择器 /// @author ZeroJ, 16-04-23 18:04:59
///
/// - parameter title: 标题
/// - parameter datePickerSetting: 可配置UIDatePicker的样式
/// - parameter doneAction: 响应完成的Closure
///
/// - returns:
public class func showDatePicker(toolBarTitle: String, datePickerSetting: DatePickerSetting = DatePickerSetting(), doneAction: DateDoneAction?) {
let window = UIApplication.sharedApplication().keyWindow
guard let currentWindow = window else { return }
let testView = UsefulPickerView(frame: currentWindow.bounds, toolBarTitle: toolBarTitle, datePickerSetting: datePickerSetting, doneAction: doneAction)
testView.showPicker()
}
}
| mit | 73c533d2f74f78ccc8940770efdfda58 | 39.810496 | 208 | 0.632876 | 4.899545 | false | false | false | false |
el-hoshino/NotAutoLayout | Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/LeftTopBottom.Individual.swift | 1 | 1288 | //
// LeftTopBottom.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct LeftTopBottom {
let left: LayoutElement.Horizontal
let top: LayoutElement.Vertical
let bottom: LayoutElement.Vertical
}
}
// MARK: - Make Frame
extension IndividualProperty.LeftTopBottom {
private func makeFrame(left: Float, top: Float, bottom: Float, width: Float) -> Rect {
let x = left
let y = top
let height = bottom - top
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Length -
// MARK: Width
extension IndividualProperty.LeftTopBottom: LayoutPropertyCanStoreWidthToEvaluateFrameType {
public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let left = self.left.evaluated(from: parameters)
let top = self.top.evaluated(from: parameters)
let bottom = self.bottom.evaluated(from: parameters)
let height = bottom - top
let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height))
return self.makeFrame(left: left, top: top, bottom: bottom, width: width)
}
}
| apache-2.0 | b8c1503510d21cac740a3da40c8e67d5 | 21.333333 | 115 | 0.713276 | 3.766272 | false | false | false | false |
silence0201/Swift-Study | Learn/05.控制语句/fallthrough语句.playground/section-1.swift | 1 | 205 |
var j = 1
var x = 4
switch x {
case 1:
j += 1
case 2:
j += 1
case 3:
j += 1
case 4:
j += 1
fallthrough
case 5:
j += 1
fallthrough
default:
j += 1
}
print("j = \(j)")
| mit | baaa052e236ac022e636653d4d94fe5b | 6.884615 | 17 | 0.439024 | 2.594937 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/StudyNote/StudyNote/ScrollView/SNListViewController.swift | 1 | 3870 | //
// SNListViewController.swift
// StudyNote
//
// Created by wuyp on 2019/3/2.
// Copyright © 2019 Raymond. All rights reserved.
//
import UIKit
private let kMenuTopHeight: CGFloat = 100
private let kHeaderHeight: CGFloat = 100
private let kMenuHeight: CGFloat = 40
class SNListViewController: UIViewController {
@objc private lazy dynamic var table: UITableView = {
let list = UITableView(frame: CGRect(x: 0, y: 88, width: ScreenWidth, height: ScreenHeight - 88), style: .grouped)
list.delegate = self
list.dataSource = self
list.layer.borderWidth = 1
list.layer.borderColor = UIColor.green.cgColor
list.estimatedRowHeight = 0
list.estimatedSectionHeaderHeight = 0
list.estimatedSectionHeaderHeight = 0
list.tableHeaderView = self.header
list.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
if #available(iOS 11, *) {
list.contentInsetAdjustmentBehavior = .never
}
return list
}()
@objc private lazy dynamic var header: UIView = {
let head = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: kHeaderHeight))
head.backgroundColor = UIColor.orange
head.addSubview(self.testBtn)
return head
}()
@objc private lazy dynamic var testBtn: UIButton = {
let btn = UIButton(frame: CGRect(x: 15, y: 20, width: 42, height: 30))
btn.backgroundColor = .purple
btn.setTitle("测试", for: .normal)
btn.titleLabel?.font = .systemFont(ofSize: 11)
btn.setImage(UIImage(named: "tuangou_report_proceduce"), for: .normal)
btn.addTarget(self, action: #selector(testBtnClickAction), for: .touchUpInside)
let imv = btn.imageView ?? UIImageView()
let lbl = btn.titleLabel ?? UILabel()
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: btn.width - imv.maxX, bottom: 0, right: -(btn.width - imv.maxX))
btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: btn.width - imv.width - 4 - lbl.maxX, bottom: 0, right: -(btn.width - imv.width - 4 - lbl.maxX))
return btn
}()
@objc override dynamic func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(table)
}
}
extension SNListViewController {
@objc private dynamic func testBtnClickAction() {
UIView.animate(withDuration: 0.1) {
self.testBtn.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
}
self.header.height = self.header.height == 100 ? 200 : 100
self.table.tableHeaderView = self.header
}
}
extension SNListViewController: UITableViewDelegate, UITableViewDataSource {
@objc dynamic func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
@objc dynamic func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Row:\(indexPath.row)"
return cell
}
@objc dynamic func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
@objc dynamic func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10
}
}
extension SNListViewController: SNRoutePageProtocol {
@objc static dynamic func routeKey() -> [String] {
return ["scrollModule/list", "main/list"]
}
}
| apache-2.0 | 897fc2941bbc4b0b3b35ddd9d40e25df | 33.508929 | 153 | 0.645278 | 4.552415 | false | false | false | false |
shinjukunian/core-plot | examples/CPTTestApp-iPhone/Classes/PieChartController.swift | 1 | 2843 | import UIKit
class PieChartController : UIViewController, CPTPieChartDataSource, CPTPieChartDelegate {
private var pieGraph : CPTXYGraph? = nil
let dataForChart = [20.0, 30.0, 60.0]
// MARK: Initialization
override func viewDidAppear(_ animated : Bool)
{
super.viewDidAppear(animated)
// Create graph from theme
let newGraph = CPTXYGraph(frame: .zero)
newGraph.apply(CPTTheme(named: .darkGradientTheme))
let hostingView = self.view as! CPTGraphHostingView
hostingView.hostedGraph = newGraph
// Paddings
newGraph.paddingLeft = 20.0
newGraph.paddingRight = 20.0
newGraph.paddingTop = 20.0
newGraph.paddingBottom = 20.0
newGraph.axisSet = nil
let whiteText = CPTMutableTextStyle()
whiteText.color = .white()
newGraph.titleTextStyle = whiteText
newGraph.title = "Graph Title"
// Add pie chart
let piePlot = CPTPieChart(frame: .zero)
piePlot.dataSource = self
piePlot.pieRadius = 131.0
piePlot.identifier = "Pie Chart 1" as NSString
piePlot.startAngle = CGFloat(.pi / 4.0)
piePlot.sliceDirection = .counterClockwise
piePlot.centerAnchor = CGPoint(x: 0.5, y: 0.38)
piePlot.borderLineStyle = CPTLineStyle()
piePlot.delegate = self
newGraph.add(piePlot)
self.pieGraph = newGraph
}
// MARK: - Plot Data Source Methods
func numberOfRecords(for plot: CPTPlot) -> UInt
{
return UInt(self.dataForChart.count)
}
func number(for plot: CPTPlot, field: UInt, record: UInt) -> Any?
{
if Int(record) > self.dataForChart.count {
return nil
}
else {
switch CPTPieChartField(rawValue: Int(field))! {
case .sliceWidth:
return (self.dataForChart)[Int(record)] as NSNumber
default:
return record as NSNumber
}
}
}
func dataLabel(for plot: CPTPlot, record: UInt) -> CPTLayer?
{
let label = CPTTextLayer(text:"\(record)")
if let textStyle = label.textStyle?.mutableCopy() as? CPTMutableTextStyle {
textStyle.color = .lightGray()
label.textStyle = textStyle
}
return label
}
func radialOffset(for piePlot: CPTPieChart, record recordIndex: UInt) -> CGFloat
{
var offset: CGFloat = 0.0
if ( recordIndex == 0 ) {
offset = piePlot.pieRadius / 8.0
}
return offset
}
// MARK: - Delegate Methods
private func pieChart(_ plot: CPTPlot, sliceWasSelectedAtRecordIndex recordIndex: UInt)
{
self.pieGraph?.title = "Selected index: \(recordIndex)"
}
}
| bsd-3-clause | 423a95357a78c2b714f972c8513e8b80 | 26.601942 | 91 | 0.592332 | 4.144315 | false | false | false | false |
NSJoe/ListUpdater | source/ListUpdater.swift | 1 | 3435 | //
// ListUpdater.swift
// ListUpdater
//
// Created by Joe's MacBook Pro on 2017/7/9.
// Copyright © 2017年 joe. All rights reserved.
//
import UIKit
let defaultThrottle : Float = 0.1
open class ListUpdater {
public var dataSource = [SectionDiffable]()
private let throttle = ThrottleTask(throttle: defaultThrottle)
public func update(dataSource:[SectionDiffable], animation:@escaping ((DiffIndexResult, DiffSectionResult)) -> Void) -> Void {
throttle.add {
let diff = sectionedDiff(from: self.dataSource, to: dataSource)
self.dataSource = dataSource
DispatchQueue.main.sync {
animation(diff)
}
}
}
}
open class TableViewUpdater: ListUpdater {
public var tableView:UITableView
public init(tableView:UITableView) {
self.tableView = tableView
}
public func animateReload(newData:[SectionDiffable]) -> Void {
if self.tableView.window == nil {
self.immedateReload(newData: newData)
return
}
self.update(dataSource: newData) { (result) in
self.tableView.beginUpdates()
let indexDiff = result.0
let sectionDiff = result.1
self.tableView.deleteSections(indexDiff.deletes, with: .top)
self.tableView.insertSections(indexDiff.inserts, with: .top)
for move in indexDiff.moveIndexes {
self.tableView.moveSection(move.from, toSection: move.to)
}
self.tableView.deleteRows(at: sectionDiff.deletes, with: .top)
self.tableView.insertRows(at: sectionDiff.inserts, with: .top)
for move in sectionDiff.moveRows {
self.tableView.moveRow(at: move.from, to: move.to)
}
self.tableView.endUpdates()
}
}
public func immedateReload(newData:[SectionDiffable]) -> Void {
self.dataSource = newData
self.tableView.reloadData()
}
}
open class CollectionViewUpdater: ListUpdater {
public var collectionView:UICollectionView
public init(collectionView:UICollectionView) {
self.collectionView = collectionView
}
public func animateReload(newData:[SectionDiffable]) -> Void {
if self.collectionView.window == nil {
self.immedateReload(newData: newData)
return
}
self.update(dataSource: newData) { (result) in
self.collectionView.performBatchUpdates({
let indexDiff = result.0
let sectionDiff = result.1
self.collectionView.deleteSections(indexDiff.deletes)
self.collectionView.insertSections(indexDiff.inserts)
for move in indexDiff.moveIndexes {
self.collectionView.moveSection(move.from, toSection: move.to)
}
self.collectionView.deleteItems(at: sectionDiff.deletes)
self.collectionView.insertItems(at: sectionDiff.inserts)
for move in sectionDiff.moveRows {
self.collectionView.moveItem(at: move.from, to: move.to)
}
}, completion: nil)
}
}
public func immedateReload(newData:[SectionDiffable]) -> Void {
self.dataSource = newData
self.collectionView.reloadData()
}
}
| mit | 52568ff8c64721d5812aaffbdd357516 | 31.685714 | 130 | 0.605478 | 4.840621 | false | false | false | false |
debugsquad/nubecero | nubecero/View/PhotosAlbum/VPhotosAlbumCell.swift | 1 | 3422 | import UIKit
class VPhotosAlbumCell:UICollectionViewCell
{
private weak var imageView:UIImageView!
private weak var model:MPhotosItemPhoto?
private let kAnimationDuration:TimeInterval = 1.5
private let kAlphaSelected:CGFloat = 0.3
private let kAlphaNotSelected:CGFloat = 1
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor(
red:0.88,
green:0.91,
blue:0.93,
alpha:1)
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.scaleAspectFill
imageView.layer.borderColor = UIColor.black.cgColor
self.imageView = imageView
addSubview(imageView)
let views:[String:UIView] = [
"imageView":imageView]
let metrics:[String:CGFloat] = [:]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[imageView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[imageView]-0-|",
options:[],
metrics:metrics,
views:views))
NotificationCenter.default.addObserver(
self,
selector:#selector(notifiedThumbnailReady(sender:)),
name:Notification.thumbnailReady,
object:nil)
}
required init?(coder:NSCoder)
{
fatalError()
}
deinit
{
NotificationCenter.default.removeObserver(self)
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: notified
func notifiedThumbnailReady(sender notification:Notification)
{
DispatchQueue.main.async
{ [weak self] in
guard
let picture:MPhotosItemPhoto = notification.object as? MPhotosItemPhoto
else
{
return
}
if picture === self?.model
{
self?.animateLoadThumb()
}
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
alpha = kAlphaSelected
}
else
{
alpha = kAlphaNotSelected
}
}
private func animateLoadThumb()
{
guard
let image:UIImage = model?.state?.loadThumbnail()
else
{
imageView.image = nil
return
}
imageView.alpha = 0
imageView.image = image
UIView.animate(withDuration:kAnimationDuration)
{ [weak self] in
self?.imageView.alpha = 1
}
}
//MARK: public
func config(model:MPhotosItemPhoto)
{
self.model = model
animateLoadThumb()
hover()
}
}
| mit | fabae00ddbf395fd826d604a232ca48d | 22.121622 | 87 | 0.516072 | 5.693844 | false | false | false | false |
SuPair/firefox-ios | Client/Frontend/Browser/URIFixup.swift | 6 | 1991 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
class URIFixup {
static func getURL(_ entry: String) -> URL? {
let trimmed = entry.trimmingCharacters(in: .whitespacesAndNewlines)
guard let escaped = trimmed.addingPercentEncoding(withAllowedCharacters: .URLAllowed) else {
return nil
}
// Then check if the URL includes a scheme. This will handle
// all valid requests starting with "http://", "about:", etc.
// However, we ensure that the scheme is one that is listed in
// the official URI scheme list, so that other such search phrases
// like "filetype:" are recognised as searches rather than URLs.
if let url = punycodedURL(escaped), url.schemeIsValid {
return url
}
// If there's no scheme, we're going to prepend "http://". First,
// make sure there's at least one "." in the host. This means
// we'll allow single-word searches (e.g., "foo") at the expense
// of breaking single-word hosts without a scheme (e.g., "localhost").
if trimmed.range(of: ".") == nil {
return nil
}
if trimmed.range(of: " ") != nil {
return nil
}
// If there is a ".", prepend "http://" and try again. Since this
// is strictly an "http://" URL, we also require a host.
if let url = punycodedURL("http://\(escaped)"), url.host != nil {
return url
}
return nil
}
static func punycodedURL(_ string: String) -> URL? {
var components = URLComponents(string: string)
if AppConstants.MOZ_PUNYCODE {
let host = components?.host?.utf8HostToAscii()
components?.host = host
}
return components?.url
}
}
| mpl-2.0 | 43ce75c2abdc98940ebb5dabce8994e5 | 36.566038 | 100 | 0.598192 | 4.395143 | false | false | false | false |
mobilabsolutions/jenkins-ios | JenkinsiOS/Model/JenkinsAPI/Build/Actions.swift | 1 | 1460 | //
// Action.swift
// JenkinsiOS
//
// Created by Robert on 25.09.16.
// Copyright © 2016 MobiLab Solutions. All rights reserved.
//
import Foundation
class Actions {
/// The causes associated with the action
var causes: [Cause] = []
/// The count of failed causes
var failCount: Int?
/// The count of skipped causes
var skipCount: Int?
/// The total count of causes
var totalCount: Int?
/// The name of the url
var urlName: String?
/// Initialize an Actions object
///
/// - parameter json: The json to initialize the actions object from
///
/// - returns: An initialized Actions object
init(json: [[String: AnyObject]]) {
for action in json {
if let causesJson = action["causes"] as? [[String: AnyObject]] {
for causeJson in causesJson {
if let cause = Cause(json: causeJson) {
causes.append(cause)
}
}
}
// Set these fields to the value of that field in the json action
// If it doesn't exist, set it to its previous value, as not to overwrite good data
failCount = action["failCount"] as? Int ?? failCount
skipCount = action["skipCount"] as? Int ?? skipCount
totalCount = action["totalCount"] as? Int ?? totalCount
urlName = action["urlName"] as? String ?? urlName
}
}
}
| mit | a5985b32190991ce6d9098815e2dd7e6 | 30.717391 | 95 | 0.570254 | 4.461774 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.