repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
getwagit/Baya | refs/heads/master | Baya/layouts/BayaLinearLayout.swift | mit | 1 | //
// Copyright (c) 2016-2017 wag it GmbH.
// License: MIT
//
import Foundation
import UIKit
/**
A simple layout that places children in a linear order.
This Layout respects the margins of its children.
*/
public struct BayaLinearLayout: BayaLayout, BayaLayoutIterator {
public var bayaMargins: UIEdgeInsets
public var frame: CGRect
var orientation: BayaLayoutOptions.Orientation
var spacing: CGFloat
private var elements: [BayaLayoutable]
private var measures = [CGSize]()
init(
elements: [BayaLayoutable],
orientation: BayaLayoutOptions.Orientation,
spacing: CGFloat = 0,
bayaMargins: UIEdgeInsets) {
self.elements = elements
self.orientation = orientation
self.bayaMargins = bayaMargins
self.spacing = spacing
self.frame = CGRect()
}
mutating public func layoutWith(frame: CGRect) {
self.frame = frame
guard elements.count > 0 else {
return
}
let measures = measureIfNecessary(&elements, cache: self.measures, size: frame.size)
switch orientation {
case .horizontal:
iterate(&elements, measures) { e1, e2, e2s in
let size = BayaLinearLayout.calculateSizeForLayout(
withOrientation: .horizontal,
forChild: e2,
cachedSize: e2s,
ownSize: frame.size)
let origin: CGPoint
if let e1 = e1 {
origin = CGPoint(
x: e1.frame.maxX
+ e1.bayaMargins.right
+ spacing
+ e2.bayaMargins.left,
y: frame.minY + e2.bayaMargins.top)
} else {
origin = CGPoint(
x: frame.minX + e2.bayaMargins.left,
y: frame.minY + e2.bayaMargins.top)
}
return CGRect(origin: origin, size: size)
}
case .vertical:
iterate(&elements, measures) { e1, e2, e2s in
let size = BayaLinearLayout.calculateSizeForLayout(
withOrientation: .vertical,
forChild: e2,
cachedSize: e2s,
ownSize: frame.size)
let origin: CGPoint
if let e1 = e1 {
origin = CGPoint(
x: frame.minX + e2.bayaMargins.left,
y: e1.frame.maxY
+ e1.bayaMargins.bottom
+ spacing
+ e2.bayaMargins.top)
} else {
origin = CGPoint(
x: frame.minX + e2.bayaMargins.left,
y: frame.minY + e2.bayaMargins.top)
}
return CGRect(origin: origin, size: size)
}
}
}
mutating public func sizeThatFits(_ size: CGSize) -> CGSize {
measures = measure(&elements, size: size)
var resultSize: CGSize = CGSize()
switch orientation {
case .horizontal:
let elementCount = elements.count
resultSize.width = elementCount > 1 ? (CGFloat(elementCount - 1) * spacing) : 0
for i in 0..<elements.count {
let fit = measures[i]
let element = elements[i]
resultSize.width += fit.width + element.bayaMargins.left + element.bayaMargins.right
resultSize.height = max(
resultSize.height,
fit.height + element.bayaMargins.top + element.bayaMargins.bottom)
}
case .vertical:
let elementCount = elements.count
resultSize.height = elementCount > 1 ? (CGFloat(elementCount - 1) * spacing) : 0
for i in 0..<elements.count {
let fit = measures[i]
let element = elements[i]
resultSize.width = max(
resultSize.width,
fit.width + element.bayaMargins.left + element.bayaMargins.right)
resultSize.height += fit.height + element.bayaMargins.top + element.bayaMargins.bottom
}
}
return resultSize
}
private static func calculateSizeForLayout(
withOrientation orientation: BayaLayoutOptions.Orientation,
forChild element: BayaLayoutable,
cachedSize: CGSize,
ownSize availableSize: CGSize)
-> CGSize {
switch orientation {
case .horizontal:
guard element.bayaModes.height == .matchParent else {
return cachedSize
}
return CGSize(
width: cachedSize.width,
height: availableSize.height - element.verticalMargins)
case .vertical:
guard element.bayaModes.width == .matchParent else {
return cachedSize
}
return CGSize(
width: availableSize.width - element.horizontalMargins,
height: cachedSize.height)
}
}
}
public extension Sequence where Iterator.Element: BayaLayoutable {
/// Aligns all elements in a single direction.
/// - parameter orientation: Determines if the elements should be laid out in horizontal or vertical direction.
/// - parameter spacing: The gap between the elements.
/// - parameter bayaMargins: The layout's margins.
/// - returns: A `BayaLinearLayout`.
func layoutLinearly(
orientation: BayaLayoutOptions.Orientation,
spacing: CGFloat = 0,
bayaMargins: UIEdgeInsets = UIEdgeInsets.zero)
-> BayaLinearLayout {
return BayaLinearLayout(
elements: self.array(),
orientation: orientation,
spacing: spacing,
bayaMargins: bayaMargins)
}
}
public extension Sequence where Iterator.Element == BayaLayoutable {
/// Aligns all elements in a single direction.
/// - parameter orientation: Determines if the elements should be laid out in horizontal or vertical direction.
/// - parameter spacing: The gap between the elements.
/// - parameter bayaMargins: The layout's margins.
/// - returns: A `BayaLinearLayout`.
func layoutLinearly(
orientation: BayaLayoutOptions.Orientation,
spacing: CGFloat = 0,
bayaMargins: UIEdgeInsets = UIEdgeInsets.zero)
-> BayaLinearLayout {
return BayaLinearLayout(
elements: self.array(),
orientation: orientation,
spacing: spacing,
bayaMargins: bayaMargins)
}
}
| 716f5567596b5bbf68efa4e01d127478 | 36.821229 | 115 | 0.553176 | false | false | false | false |
jessesquires/JSQCoreDataKit | refs/heads/main | Example/ExampleModel/ExampleModel/Employee.swift | mit | 1 | //
// Created by Jesse Squires
// https://www.jessesquires.com
//
//
// Documentation
// https://jessesquires.github.io/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015-present Jesse Squires
// Released under an MIT license: https://opensource.org/licenses/MIT
//
import CoreData
import Foundation
import JSQCoreDataKit
public final class Employee: NSManagedObject, CoreDataEntityProtocol {
// MARK: CoreDataEntityProtocol
public static let defaultSortDescriptors = [ NSSortDescriptor(key: "name", ascending: true) ]
// MARK: Properties
@NSManaged public var name: String
@NSManaged public var birthDate: Date
@NSManaged public var salary: NSDecimalNumber
@NSManaged public var company: Company?
// MARK: Init
public init(context: NSManagedObjectContext,
name: String,
birthDate: Date,
salary: NSDecimalNumber,
company: Company? = nil) {
super.init(entity: Self.entity(context: context), insertInto: context)
self.name = name
self.birthDate = birthDate
self.salary = salary
self.company = company
}
@objc
override private init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: context)
}
public static func newEmployee(_ context: NSManagedObjectContext, company: Company? = nil) -> Employee {
let name = "Employee " + String(UUID().uuidString.split { $0 == "-" }.first!)
return Employee(context: context,
name: name,
birthDate: Date.distantPast,
salary: NSDecimalNumber(value: Int.random(in: 0...100_000)),
company: company)
}
public static func fetchRequest(for company: Company) -> NSFetchRequest<Employee> {
let fetch = self.fetchRequest
fetch.predicate = NSPredicate(format: "company == %@", company)
return fetch
}
}
| 89b8c410a18856647e22abae79cb4660 | 29.318841 | 108 | 0.639579 | false | false | false | false |
lioonline/Swift | refs/heads/master | CoreDataSample2/CoreDataSample2/AppDelegate.swift | gpl-3.0 | 1 | //
// AppDelegate.swift
// CoreDataSample2
//
// Created by Carlos Butron on 02/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "es.carlosbutron.CoreDataSample2" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CoreDataSample2", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreDataSample2.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| c75d954824efee6668a3c8a878e00fa1 | 55.915966 | 290 | 0.721837 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformUIKit/Components/WalletBalanceView/WalletBalanceViewPresenter.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import ComposableArchitectureExtensions
import PlatformKit
import RxCocoa
import RxRelay
import RxSwift
public final class WalletBalanceViewPresenter {
typealias AccessibilityId = Accessibility.Identifier.Activity.WalletBalance
public typealias PresentationState = LoadingState<WalletBalance>
public struct WalletBalance {
/// The balance in fiat
public let fiatBalance: LabelContent
/// The fiat currency code
public let currencyCode: LabelContent
/// Descriptors that allows customized content and style
public struct Descriptors {
let fiatFont: UIFont
let fiatTextColor: UIColor
let descriptionFont: UIFont
let descriptionTextColor: UIColor
public init(
fiatFont: UIFont,
fiatTextColor: UIColor,
descriptionFont: UIFont,
descriptionTextColor: UIColor
) {
self.fiatFont = fiatFont
self.fiatTextColor = fiatTextColor
self.descriptionFont = descriptionFont
self.descriptionTextColor = descriptionTextColor
}
}
// MARK: - Setup
public init(
with value: WalletBalanceViewInteractor.WalletBalance,
descriptors: Descriptors = .default
) {
fiatBalance = LabelContent(
text: value.fiatValue.displayString,
font: descriptors.fiatFont,
color: descriptors.fiatTextColor,
accessibility: .id(AccessibilityId.fiatBalance)
)
currencyCode = LabelContent(
text: value.fiatCurrency.displayCode,
font: descriptors.descriptionFont,
color: descriptors.descriptionTextColor,
accessibility: .id(AccessibilityId.currencyCode)
)
}
}
// MARK: - Exposed Properties
let accessibility: Accessibility = .id(AccessibilityId.view)
public var state: Observable<PresentationState> {
stateRelay
.observe(on: MainScheduler.instance)
}
var alignment: Driver<UIStackView.Alignment> {
alignmentRelay.asDriver()
}
// MARK: - Injected
private let interactor: WalletBalanceViewInteractor
// MARK: - Private Accessors
private let alignmentRelay = BehaviorRelay<UIStackView.Alignment>(value: .fill)
private let stateRelay = BehaviorRelay<PresentationState>(value: .loading)
private let disposeBag = DisposeBag()
// MARK: - Setup
public init(
alignment: UIStackView.Alignment = .trailing,
interactor: WalletBalanceViewInteractor,
descriptors: WalletBalanceViewPresenter.WalletBalance.Descriptors = .default
) {
self.interactor = interactor
alignmentRelay.accept(alignment)
/// Map interaction state into presnetation state
/// and bind it to `stateRelay`
interactor.state
.map { .init(with: $0, descriptors: descriptors) }
.bindAndCatch(to: stateRelay)
.disposed(by: disposeBag)
}
}
extension WalletBalanceViewPresenter.WalletBalance.Descriptors {
public typealias Descriptors = WalletBalanceViewPresenter.WalletBalance.Descriptors
public static let `default` = Descriptors(
fiatFont: .main(.semibold, 16.0),
fiatTextColor: .textFieldText,
descriptionFont: .main(.medium, 14.0),
descriptionTextColor: .descriptionText
)
}
extension LoadingState where Content == WalletBalanceViewPresenter.WalletBalance {
init(
with state: LoadingState<WalletBalanceViewInteractor.WalletBalance>,
descriptors: WalletBalanceViewPresenter.WalletBalance.Descriptors
) {
switch state {
case .loading:
self = .loading
case .loaded(next: let content):
self = .loaded(
next: .init(
with: content,
descriptors: descriptors
)
)
}
}
}
| 499e39934ead610b7bf24131e3e6b9cc | 30.598485 | 87 | 0.630065 | false | false | false | false |
pennlabs/penn-mobile-ios | refs/heads/main | PennMobile/GSR-Booking/Views/GSRGroups/GroupSettingsCell.swift | mit | 1 | //
// GroupSettingsCell.swift
// PennMobile
//
// Created by Rehaan Furniturewala on 10/20/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import UIKit
class GroupSettingsCell: UITableViewCell {
static let cellHeight: CGFloat = 100
static let identifier = "gsrGroupSettingsCell"
fileprivate var titleLabel: UILabel!
fileprivate var descriptionLabel: UILabel!
fileprivate var isEnabledSwitch: UISwitch!
fileprivate var holderView: UIView!
var delegate: GSRGroupIndividualSettingDelegate?
var userSetting: GSRGroupIndividualSetting!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupCell(with userSetting: GSRGroupIndividualSetting) {
self.userSetting = userSetting
if titleLabel == nil || descriptionLabel == nil || isEnabledSwitch == nil {
prepareUI()
}
titleLabel.text = userSetting.title
descriptionLabel.text = userSetting.descr
isEnabledSwitch.setOn(userSetting.isEnabled, animated: false)
}
@objc fileprivate func switchValueChanged() {
if let delegate = delegate {
userSetting.isEnabled = isEnabledSwitch.isOn
delegate.updateSetting(setting: userSetting)
}
}
}
// MARK: - Setup UI
extension GroupSettingsCell {
fileprivate func prepareUI() {
self.heightAnchor.constraint(equalToConstant: GroupSettingsCell.cellHeight).isActive = true
prepareHolderView()
prepareTitleLabel()
prepareDescriptionLabel()
prepareIsEnabledSwitch()
titleLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -100).isActive = true
// backgroundColor = .uiBackgroundSecondary
}
fileprivate func prepareHolderView() {
holderView = UIView()
addSubview(holderView)
let inset: CGFloat = 14.0
_ = holderView.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: inset, leftConstant: inset, bottomConstant: inset, rightConstant: inset, widthConstant: 0, heightConstant: 0)
}
fileprivate func prepareTitleLabel() {
titleLabel = UILabel()
holderView.addSubview(titleLabel)
_ = titleLabel.anchor(holderView.topAnchor, left: holderView.leftAnchor, bottom: nil, right: holderView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 30)
titleLabel.font = UIFont.systemFont(ofSize: 17.0, weight: .regular)
}
fileprivate func prepareDescriptionLabel() {
descriptionLabel = UILabel()
holderView.addSubview(descriptionLabel)
_ = descriptionLabel.anchor(titleLabel.bottomAnchor, left: titleLabel.leftAnchor, bottom: holderView.bottomAnchor, right: titleLabel.rightAnchor, topConstant: 5, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
descriptionLabel.numberOfLines = 3
descriptionLabel.textColor = UIColor.init(r: 153, g: 153, b: 153)
descriptionLabel.font = UIFont.systemFont(ofSize: 14.0, weight: .light)
}
fileprivate func prepareIsEnabledSwitch() {
isEnabledSwitch = UISwitch()
holderView.addSubview(isEnabledSwitch)
_ = isEnabledSwitch.anchor(titleLabel.topAnchor, left: nil, bottom: nil, right: holderView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 51, heightConstant: 0)
isEnabledSwitch.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
}
}
| ec04a857e1816db15dd4fdaa06a07853 | 38.479167 | 260 | 0.708443 | false | false | false | false |
007HelloWorld/DouYuZhiBo | refs/heads/develop | Apps/Forum17/2017/Pods/Kingfisher/Sources/AnimatedImageView.swift | apache-2.0 | 32 | //
// AnimatableImageView.swift
// Kingfisher
//
// Created by bl4ckra1sond3tre on 4/22/16.
//
// The AnimatableImageView, AnimatedFrame and Animator is a modified version of
// some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu)
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Reda Lemeden.
//
// 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.
//
// The name and characters used in the demo of this software are property of their
// respective owners.
import UIKit
import ImageIO
/// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image.
open class AnimatedImageView: UIImageView {
/// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView.
class TargetProxy {
private weak var target: AnimatedImageView?
init(target: AnimatedImageView) {
self.target = target
}
@objc func onScreenUpdate() {
target?.updateFrame()
}
}
// MARK: - Public property
/// Whether automatically play the animation when the view become visible. Default is true.
public var autoPlayAnimatedImage = true
/// The size of the frame cache.
public var framePreloadCount = 10
/// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true.
public var needsPrescaling = true
/// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling.
public var runLoopMode = RunLoopMode.commonModes {
willSet {
if runLoopMode == newValue {
return
} else {
stopAnimating()
displayLink.remove(from: .main, forMode: runLoopMode)
displayLink.add(to: .main, forMode: newValue)
startAnimating()
}
}
}
// MARK: - Private property
/// `Animator` instance that holds the frames of a specific image in memory.
private var animator: Animator?
/// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D
private var isDisplayLinkInitialized: Bool = false
/// A display link that keeps calling the `updateFrame` method on every screen refresh.
private lazy var displayLink: CADisplayLink = {
self.isDisplayLinkInitialized = true
let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
displayLink.add(to: .main, forMode: self.runLoopMode)
displayLink.isPaused = true
return displayLink
}()
// MARK: - Override
override open var image: Image? {
didSet {
if image != oldValue {
reset()
}
setNeedsDisplay()
layer.setNeedsDisplay()
}
}
deinit {
if isDisplayLinkInitialized {
displayLink.invalidate()
}
}
override open var isAnimating: Bool {
if isDisplayLinkInitialized {
return !displayLink.isPaused
} else {
return super.isAnimating
}
}
/// Starts the animation.
override open func startAnimating() {
if self.isAnimating {
return
} else {
displayLink.isPaused = false
}
}
/// Stops the animation.
override open func stopAnimating() {
super.stopAnimating()
if isDisplayLinkInitialized {
displayLink.isPaused = true
}
}
override open func display(_ layer: CALayer) {
if let currentFrame = animator?.currentFrame {
layer.contents = currentFrame.cgImage
} else {
layer.contents = image?.cgImage
}
}
override open func didMoveToWindow() {
super.didMoveToWindow()
didMove()
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
didMove()
}
// This is for back compatibility that using regular UIImageView to show animated image.
override func shouldPreloadAllAnimation() -> Bool {
return false
}
// MARK: - Private method
/// Reset the animator.
private func reset() {
animator = nil
if let imageSource = image?.kf.imageSource?.imageRef {
animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount)
animator?.needsPrescaling = needsPrescaling
animator?.prepareFramesAsynchronously()
}
didMove()
}
private func didMove() {
if autoPlayAnimatedImage && animator != nil {
if let _ = superview, let _ = window {
startAnimating()
} else {
stopAnimating()
}
}
}
/// Update the current frame with the displayLink duration.
private func updateFrame() {
let duration: CFTimeInterval
// CA based display link is opt-out from ProMotion by default.
// So the duration and its FPS might not match.
// See [#718](https://github.com/onevcat/Kingfisher/issues/718)
if #available(iOS 10.0, tvOS 10.0, *) {
// By setting CADisableMinimumFrameDuration to YES in Info.plist may
// cause the preferredFramesPerSecond being 0
if displayLink.preferredFramesPerSecond == 0 {
duration = displayLink.duration
} else {
// Some devices (like iPad Pro 10.5) will have a different FPS.
duration = 1.0 / Double(displayLink.preferredFramesPerSecond)
}
} else {
duration = displayLink.duration
}
if animator?.updateCurrentFrame(duration: duration) ?? false {
layer.setNeedsDisplay()
}
}
}
/// Keeps a reference to an `Image` instance and its duration as a GIF frame.
struct AnimatedFrame {
var image: Image?
let duration: TimeInterval
static let null: AnimatedFrame = AnimatedFrame(image: .none, duration: 0.0)
}
// MARK: - Animator
class Animator {
// MARK: Private property
fileprivate let size: CGSize
fileprivate let maxFrameCount: Int
fileprivate let imageSource: CGImageSource
fileprivate var animatedFrames = [AnimatedFrame]()
fileprivate let maxTimeStep: TimeInterval = 1.0
fileprivate var frameCount = 0
fileprivate var currentFrameIndex = 0
fileprivate var currentPreloadIndex = 0
fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0
fileprivate var needsPrescaling = true
/// Loop count of animated image.
private var loopCount = 0
var currentFrame: UIImage? {
return frame(at: currentFrameIndex)
}
var contentMode = UIViewContentMode.scaleToFill
private lazy var preloadQueue: DispatchQueue = {
return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
}()
/**
Init an animator with image source reference.
- parameter imageSource: The reference of animated image.
- parameter contentMode: Content mode of AnimatedImageView.
- parameter size: Size of AnimatedImageView.
- parameter framePreloadCount: Frame cache size.
- returns: The animator object.
*/
init(imageSource source: CGImageSource, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount count: Int) {
self.imageSource = source
self.contentMode = mode
self.size = size
self.maxFrameCount = count
}
func frame(at index: Int) -> Image? {
return animatedFrames[safe: index]?.image
}
func prepareFramesAsynchronously() {
preloadQueue.async { [weak self] in
self?.prepareFrames()
}
}
private func prepareFrames() {
frameCount = CGImageSourceGetCount(imageSource)
if let properties = CGImageSourceCopyProperties(imageSource, nil),
let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int
{
self.loopCount = loopCount
}
let frameToProcess = min(frameCount, maxFrameCount)
animatedFrames.reserveCapacity(frameToProcess)
animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame(at: $1))}
currentPreloadIndex = (frameToProcess + 1) % frameCount
}
private func prepareFrame(at index: Int) -> AnimatedFrame {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else {
return AnimatedFrame.null
}
let defaultGIFFrameDuration = 0.100
let frameDuration = imageSource.kf.gifProperties(at: index).map {
gifInfo -> Double in
let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double?
let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double?
let duration = unclampedDelayTime ?? delayTime ?? 0.0
/**
http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
Many annoying ads specify a 0 duration to make an image flash as quickly as
possible. We follow Safari and Firefox's behavior and use a duration of 100 ms
for any frames that specify a duration of <= 10 ms.
See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
*/
return duration > 0.011 ? duration : defaultGIFFrameDuration
} ?? defaultGIFFrameDuration
let image = Image(cgImage: imageRef)
let scaledImage: Image?
if needsPrescaling {
scaledImage = image.kf.resize(to: size, for: contentMode)
} else {
scaledImage = image
}
return AnimatedFrame(image: scaledImage, duration: frameDuration)
}
/**
Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`.
*/
func updateCurrentFrame(duration: CFTimeInterval) -> Bool {
timeSinceLastFrameChange += min(maxTimeStep, duration)
guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration, frameDuration <= timeSinceLastFrameChange else {
return false
}
timeSinceLastFrameChange -= frameDuration
let lastFrameIndex = currentFrameIndex
currentFrameIndex += 1
currentFrameIndex = currentFrameIndex % animatedFrames.count
if animatedFrames.count < frameCount {
preloadFrameAsynchronously(at: lastFrameIndex)
}
return true
}
private func preloadFrameAsynchronously(at index: Int) {
preloadQueue.async { [weak self] in
self?.preloadFrame(at: index)
}
}
private func preloadFrame(at index: Int) {
animatedFrames[index] = prepareFrame(at: currentPreloadIndex)
currentPreloadIndex += 1
currentPreloadIndex = currentPreloadIndex % frameCount
}
}
extension CGImageSource: KingfisherCompatible { }
extension Kingfisher where Base: CGImageSource {
func gifProperties(at index: Int) -> [String: Double]? {
let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary?
return properties?[kCGImagePropertyGIFDictionary] as? [String: Double]
}
}
extension Array {
subscript(safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
private func pure<T>(_ value: T) -> [T] {
return [value]
}
// MARK: - Deprecated. Only for back compatibility.
extension AnimatedImageView {
// This is for back compatibility that using regular UIImageView to show GIF.
@available(*, deprecated, renamed: "shouldPreloadAllAnimation")
override func shouldPreloadAllGIF() -> Bool {
return false
}
}
| c1c1e27c6d5db53a27075e94f2eb9c40 | 34.617801 | 184 | 0.641996 | false | false | false | false |
ashare80/RVTTextScannerView | refs/heads/master | TextScanner/MyScanViewController.swift | bsd-3-clause | 1 | //
// MyScanViewController.swift
// PassportOCR
//
// Created by Edwin Vermeer on 9/7/15.
// Copyright (c) 2015 mirabeau. All rights reserved.
//
import Foundation
class MyScanViewController: UIViewController, RVTTextScannerViewDelegate {
@IBOutlet weak var textScannerView: RVTTextScannerView!
/// Delegate set by the calling controler so that we can pass on ProcessMRZ events.
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.textScannerView.delegate = self
self.textScannerView.showCropView = true
self.textScannerView.cropView?.edgeColor = UIColor.lightGrayColor()
self.textScannerView.cropView?.progressColor = UIColor.redColor()
self.textScannerView.startScan()
}
@IBAction func dismiss(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func scannerDidRecognizeText(scanner: RVTTextScannerView, textResult: RVTTextResult, image: UIImage?) {
}
func scannerDidFindCommontextResult(scanner: RVTTextScannerView, textResult: RVTTextResult, image: UIImage?) {
self.label.text = textResult.lines.first
self.imageView.image = image
print(textResult.text, textResult.lines.first, textResult.whiteSpacedComponents)
self.view.layoutIfNeeded()
// self.textScannerView.stopScan()
// self.dismissViewControllerAnimated(true, completion: nil)
}
}
| 5a4c54748dd04039ff592cb017b7be11 | 31.763636 | 114 | 0.694229 | false | false | false | false |
Yummypets/YPImagePicker | refs/heads/master | Source/Helpers/YPLoadingView.swift | mit | 1 | //
// YPLoadingView.swift
// YPImagePicker
//
// Created by Sacha DSO on 24/04/2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
import Stevia
class YPLoadingView: UIView {
let spinner = UIActivityIndicatorView(style: .whiteLarge)
let processingLabel = UILabel()
convenience init() {
self.init(frame: .zero)
// View Hiearachy
let stack = UIStackView(arrangedSubviews: [spinner, processingLabel])
stack.axis = .vertical
stack.spacing = 20
subviews(
stack
)
// Layout
stack.centerInContainer()
processingLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 751), for: .horizontal)
// Style
backgroundColor = UIColor.ypLabel.withAlphaComponent(0.8)
processingLabel.textColor = .ypSystemBackground
spinner.hidesWhenStopped = true
// Content
processingLabel.text = YPConfig.wordings.processing
spinner.startAnimating()
}
func toggleLoading() {
if !spinner.isAnimating {
spinner.startAnimating()
alpha = 1
} else {
spinner.stopAnimating()
alpha = 0
}
}
}
| 73f935e93bbd87653312df28a2069c40 | 23.980769 | 114 | 0.596613 | false | false | false | false |
louisdh/lioness | refs/heads/master | Sources/Lioness/Standard Library/StdLib.swift | mit | 1 | //
// StdLib.swift
// Lioness
//
// Created by Louis D'hauwe on 11/12/2016.
// Copyright © 2016 - 2017 Silver Fox. All rights reserved.
//
import Foundation
public class StdLib {
private let sources = ["Arithmetic", "Geometry", "Graphics"]
public init() {
}
public func stdLibCode() throws -> String {
var stdLib = ""
#if SWIFT_PACKAGE
// Swift packages don't currently have a resources folder
var url = URL(fileURLWithPath: #file)
url.deleteLastPathComponent()
url.appendPathComponent("Sources")
let resourcesPath = url.path
#else
let bundle = Bundle(for: type(of: self))
guard let resourcesPath = bundle.resourcePath else {
throw StdLibError.resourceNotFound
}
#endif
for sourceName in sources {
let resourcePath = "\(resourcesPath)/\(sourceName).lion"
let source = try String(contentsOfFile: resourcePath, encoding: .utf8)
stdLib += source
}
return stdLib
}
enum StdLibError: Error {
case resourceNotFound
}
}
| c2fa72c22a90910d709ea23f448c36b5 | 16.305085 | 73 | 0.666014 | false | false | false | false |
merlos/iOS-Open-GPX-Tracker | refs/heads/master | OpenGpxTracker-Watch Extension/GPXFileTableInterfaceController.swift | gpl-3.0 | 1 | //
// GPXFileTableInterfaceController.swift
// OpenGpxTracker-Watch Extension
//
// Created by Vincent on 7/2/19.
// Copyright © 2019 TransitBox. All rights reserved.
//
import WatchKit
import WatchConnectivity
/// Text displayed when there are no GPX files in the folder.
let kNoFiles = NSLocalizedString("NO_FILES", comment: "no comment")
///
/// WKInterfaceTable that displays the list of files that have been saved in previous sessions.
///
/// This interface controller allows users to manage their GPX Files.
///
/// Currently the following actions with a file are supported
///
/// 1. Send file to iOS App
/// 3. Delete the file
///
/// It also displays a back button to return to the main controls view.
///
class GPXFileTableInterfaceController: WKInterfaceController {
/// Main table that displays list of files
@IBOutlet var fileTable: WKInterfaceTable!
@IBOutlet var progressGroup: WKInterfaceGroup!
@IBOutlet var progressTitle: WKInterfaceLabel!
@IBOutlet var progressFileName: WKInterfaceLabel!
@IBOutlet var progressImageView: WKInterfaceImage!
/// List of strings with the filenames.
var fileList: NSMutableArray = [kNoFiles]
/// Is there any GPX file in the directory?
var gpxFilesFound = false
/// Temporary variable to manage
var selectedRowIndex = -1
/// true if a gpx file will be sent.
var willSendFile: Bool {
return session?.outstandingFileTransfers.count != 0
}
/// To ensure hide animation properly timed.
var time = DispatchTime.now()
/// Watch communication session
private let session: WCSession? = WCSession.isSupported() ? WCSession.default: nil
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
}
// MARK: Progress Indicators
/// States of sending files
enum SendingStatus {
/// represents current state as sending
case sending
/// represents current state as successful
case success
/// represents current state as failure
case failure
}
/// Hides progress indicator's group, such that group will not appear when not needed.
func hideProgressIndicators() {
self.progressGroup.setHidden(true)
self.progressImageView.stopAnimating()
self.progressFileName.setText("")
self.progressTitle.setText("")
}
/// Animate hiding of progress indicator's group, when needed.
func hideProgressIndicatorsWithAnimation() {
DispatchQueue.main.asyncAfter(deadline: time + 3) {
self.animate(withDuration: 1, animations: {
self.progressGroup.setHeight(0)
})
}
// imageview do not have to be set with stop animating,
// as image indicator should already have been set as successful or failure image, which is static.
}
/// Displays progress indicators.
///
/// Details like status and filename should be updated accordingly using `updateProgressIndicators(status:fileName:)`
func showProgressIndicators() {
self.progressGroup.setHeight(30)
self.progressGroup.setHidden(false)
progressImageView.setImageNamed("Progress-")
progressImageView.startAnimatingWithImages(in: NSRange(location: 0, length: 12), duration: 1, repeatCount: 0)
}
/// Updates progress indicators according to status when sending.
///
/// If status is success or failure, method will hide and animate progress indicators when done
func updateProgressIndicators(status: SendingStatus, fileName: String?) {
switch status {
case .sending:
progressTitle.setText(NSLocalizedString("SENDING", comment: "no comment"))
guard let fileName = fileName else { return }
/// count of pending files, does not seem to include the current one
let fileTransfersCount = session?.outstandingFileTransfers.count ?? 0
// if there are files pending for sending, filename will not be displayed with the name of file.
if fileTransfersCount >= 1 {
progressFileName.setText(String(format: NSLocalizedString("X_FILES", comment: "no comment"), fileTransfersCount + 1))
} else {
progressFileName.setText(fileName)
}
case .success:
progressImageView.stopAnimating()
progressImageView.setImage(UIImage(named: "Progress-success"))
progressTitle.setText(NSLocalizedString("SUCCESSFULLY_SENT", comment: "no comment"))
hideProgressIndicatorsWithAnimation()
case .failure:
progressImageView.stopAnimating()
progressImageView.setImage(UIImage(named: "Progress-failure"))
progressTitle.setText(NSLocalizedString("FAILED_TO_SEND", comment: "no comment"))
hideProgressIndicatorsWithAnimation()
}
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
print("GPXFileTableInterfaceController:: willActivate willSendFile: \(willSendFile)")
self.setTitle(NSLocalizedString("YOUR_FILES", comment: "no comment"))
session?.delegate = self
if willSendFile == true {
self.showProgressIndicators()
} else {
self.hideProgressIndicators()
}
// get gpx files
let list: [GPXFileInfo] = GPXFileManager.fileList
if list.count != 0 {
self.fileList.removeAllObjects()
self.fileList.addObjects(from: list)
self.gpxFilesFound = true
}
loadTableData()
}
override func didAppear() {
session?.delegate = self
session?.activate()
}
override func willDisappear() {
}
/// Closes this view controller.
@objc func closeGPXFilesTableViewController() {
print("closeGPXFIlesTableViewController()")
}
/// Loads data on the table
func loadTableData() {
fileTable.setNumberOfRows(fileList.count, withRowType: "GPXFile")
if gpxFilesFound {
for index in 0..<fileTable.numberOfRows {
guard let cell = fileTable.rowController(at: index) as? GPXFileTableRowController else { continue }
// swiftlint:disable force_cast
let gpxFileInfo = fileList.object(at: index) as! GPXFileInfo
cell.fileLabel.setText(gpxFileInfo.fileName)
}
} else {
guard let cell = fileTable.rowController(at: 0) as? GPXFileTableRowController else { return }
cell.fileLabel.setText(kNoFiles)
}
}
/// Invokes when one of the cells of the table is clicked.
override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
// required, if not, hide group animation will be faster than expected when display the next time.
self.time = .now()
/// checks if there is any files in directory
if gpxFilesFound {
/// Option lets user send selected file to iOS app
let shareOption = WKAlertAction(title: NSLocalizedString("SEND_TO_IOS", comment: "no comment"), style: .default) {
self.actionTransferFileAtIndex(rowIndex)
}
/// Option for users to cancel
let cancelOption = WKAlertAction(title: NSLocalizedString("CANCEL", comment: "no comment"), style: .cancel) {
self.actionSheetCancel()
}
/// Option to delete selected file
let deleteOption = WKAlertAction(title: NSLocalizedString("DELETE", comment: "no comment"), style: .destructive) {
self.actionDeleteFileAtIndex(rowIndex)
self.loadTableData()
}
/// Array of all available options
let options = [shareOption, cancelOption, deleteOption]
presentAlert(withTitle: NSLocalizedString("FILE_SELECTED_TITLE", comment: "no comment"),
message: NSLocalizedString("FILE_SELECTED_MESSAGE", comment: "no comment"),
preferredStyle: .actionSheet, actions: options)
}
}
//
// MARK: Action Sheet - Actions
//
/// Attempts to transfer file to iOS app
func actionTransferFileAtIndex(_ rowIndex: Int) {
session?.activate()
guard let fileURL: URL = (fileList.object(at: rowIndex) as? GPXFileInfo)?.fileURL else {
print("GPXFileTableViewController:: actionTransferFileAtIndex: failed to get fileURL")
self.hideProgressIndicators()
return
}
// swiftlint:disable force_cast
let gpxFileInfo = fileList.object(at: rowIndex) as! GPXFileInfo
self.scroll(to: progressGroup, at: .top, animated: true) // scrolls to top when indicator is shown.
self.updateProgressIndicators(status: .sending, fileName: gpxFileInfo.fileName)
DispatchQueue.global().async {
self.session?.transferFile(fileURL, metadata: ["fileName": "\(gpxFileInfo.fileName).gpx"])
}
}
// Cancel button is tapped.
//
// Does nothing, it only displays a log message
internal func actionSheetCancel() {
print("ActionSheet cancel")
}
/// Deletes from the disk storage the file of `fileList` at `rowIndex`
internal func actionDeleteFileAtIndex(_ rowIndex: Int) {
guard let fileURL: URL = (fileList.object(at: rowIndex) as? GPXFileInfo)?.fileURL else {
print("GPXFileTableViewController:: actionDeleteFileAtIndex: failed to get fileURL")
return
}
GPXFileManager.removeFileFromURL(fileURL)
//Delete from list and Table
fileList.removeObject(at: rowIndex)
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
// MARK: WCSessionDelegate
///
/// Handles all the file transfer to iOS app processes
///
extension GPXFileTableInterfaceController: WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
let prefixText = "GPXFileTableInterfaceController:: activationDidCompleteWithActivationState:"
switch activationState {
case .activated:
print("\(prefixText) session activated")
case .inactive:
print("\(prefixText) session inactive")
case .notActivated:
print("\(prefixText) session not activated, error:\(String(describing: error))")
default:
print("\(prefixText) default, error:\(String(describing: error))")
}
}
func session(_ session: WCSession, didFinish fileTransfer: WCSessionFileTransfer, error: Error?) {
let doneAction = WKAlertAction(title: NSLocalizedString("DONE", comment: "no comment"), style: .default) { }
guard let error = error else {
print("WCSession: didFinish fileTransfer: \(fileTransfer.file.fileURL.absoluteString)")
// presenting success indicator to user if file is successfully transferred
// will only present once all files are sent (if multiple in queue)
if session.outstandingFileTransfers.count == 1 {
self.updateProgressIndicators(status: .success, fileName: nil)
}
return
}
// presents indicator first, if file transfer failed, without error message
self.updateProgressIndicators(status: .failure, fileName: nil)
// presents alert after 1.5s, with error message
// MARK: "as CVarArg" was suggested by XCode and my intruduce a bug...
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
self.presentAlert(withTitle: NSLocalizedString("ERROR_OCCURED_TITLE", comment: "no comment"),
message: String(format: NSLocalizedString("ERROR_OCCURED_MESSAGE", comment: "no comment"), error as CVarArg),
preferredStyle: .alert, actions: [doneAction])
}
}
}
| 75983e8d4d98327a1f4f8ee03ea27c32 | 38.512579 | 139 | 0.635018 | false | false | false | false |
phimage/MomXML | refs/heads/master | Sources/FromXML/MomAttribute+XMLObject.swift | mit | 1 | // Created by Eric Marchand on 07/06/2017.
// Copyright © 2017 Eric Marchand. All rights reserved.
//
import Foundation
extension MomAttribute: XMLObject {
public init?(xml: XML) {
guard let element = xml.element, element.name == "attribute" else {
return nil
}
guard let name = element.attribute(by: "name")?.text,
let attributeTypeString = element.attribute(by: "attributeType")?.text,
let attributeType = AttributeType(rawValue: attributeTypeString) else {
return nil
}
self.init(name: name, attributeType: attributeType)
self.isOptional = element.attribute(by: "optional")?.text.fromXMLToBool ?? false
self.usesScalarValueType = element.attribute(by: "usesScalarValueType")?.text.fromXMLToBool ?? false
self.isIndexed = element.attribute(by: "indexed")?.text.fromXMLToBool ?? false
self.isTransient = element.attribute(by: "transient")?.text.fromXMLToBool ?? false
self.syncable = element.attribute(by: "syncable")?.text.fromXMLToBool ?? false
self.isDerived = element.attribute(by: "derived")?.text.fromXMLToBool ?? false
self.defaultValueString = element.attribute(by: "defaultValueString")?.text
self.defaultDateTimeInterval = element.attribute(by: "defaultDateTimeInterval")?.text
self.minValueString = element.attribute(by: "minValueString")?.text
self.maxValueString = element.attribute(by: "maxValueString")?.text
self.derivationExpression = element.attribute(by: "derivationExpression")?.text
self.valueTransformerName = element.attribute(by: "valueTransformerName")?.text
for xml in xml.children {
if let object = MomUserInfo(xml: xml) {
userInfo = object
} else {
MomXML.orphanCallback?(xml, MomUserInfo.self)
}
}
}
}
| 2d6074d0b4f7b1c869559de88f19fc37 | 43.395349 | 108 | 0.662127 | false | false | false | false |
5lucky2xiaobin0/PandaTV | refs/heads/master | PandaTV/PandaTV/Classes/Show/Controller/ShowXYanVC.swift | mit | 1 | //
// ShowXYanVC.swift
// PandaTV
//
// Created by 钟斌 on 2017/4/5.
// Copyright © 2017年 xiaobin. All rights reserved.
//
import UIKit
import MJRefresh
class ShowXYanVC: ShowBasicVC {
var showxyanvm : ShowXYanVM = ShowXYanVM()
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
showCollectionView.contentInset = UIEdgeInsets(top: cycleViewH, left: 0, bottom: 0, right: 0)
}
}
extension ShowXYanVC {
override func setUI(){
showCollectionView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadData))
showCollectionView.mj_header.ignoredScrollViewContentInsetTop = cycleViewH
view.addSubview(showCollectionView)
showCollectionView.addSubview(scrollImageView)
}
}
extension ShowXYanVC {
override func loadData() {
showxyanvm.requestShowData { _ in
self.showCollectionView.mj_header.endRefreshing()
//判断是否有轮播图片
if self.self.showxyanvm.cycleImageArr.count == 0 {
self.scrollImageView.isHidden = true
self.showCollectionView.contentInset = UIEdgeInsets.zero
self.showCollectionView.mj_header.ignoredScrollViewContentInsetTop = 0
}else {
self.scrollImageView.isHidden = false
self.showCollectionView.contentInset = UIEdgeInsets(top: cycleViewH, left: 0, bottom: 0, right: 0)
self.showCollectionView.mj_header.ignoredScrollViewContentInsetTop = cycleViewH
self.scrollImageView.items = self.self.showxyanvm.cycleImageArr
}
self.showCollectionView.reloadData()
self.removeLoadImage()
}
}
}
extension ShowXYanVC {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: gameItemW, height: showItemH)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.showxyanvm.showArr.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: showCell, for: indexPath) as! ShowCell
cell.showItem = showxyanvm.showArr[indexPath.item]
return cell
}
}
| 554d4ddc9b251ab5fbc4b134f547b065 | 33.849315 | 160 | 0.680031 | false | false | false | false |
Ivacker/swift | refs/heads/master | stdlib/private/SwiftPrivate/ShardedAtomicCounter.swift | apache-2.0 | 10 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
public func _stdlib_getHardwareConcurrency() -> Int {
// This is effectively a re-export of this shims function
// for consumers of the unstable library (like unittest) to
// use.
return _swift_stdlib_getHardwareConcurrency()
}
/// An atomic counter for contended applications.
///
/// This is a struct to prevent extra retains/releases. You are required to
/// call `deinit()` to release the owned memory.
public struct _stdlib_ShardedAtomicCounter {
// Using an array causes retains/releases, which create contention on the
// reference count.
// FIXME: guard every element against false sharing.
var _shardsPtr: UnsafeMutablePointer<Int>
var _shardsCount: Int
public init() {
let hardwareConcurrency = _stdlib_getHardwareConcurrency()
let count = max(8, hardwareConcurrency * hardwareConcurrency)
let shards = UnsafeMutablePointer<Int>.alloc(count)
for var i = 0; i != count; i++ {
(shards + i).initialize(0)
}
self._shardsPtr = shards
self._shardsCount = count
}
public func `deinit`() {
self._shardsPtr.destroy(self._shardsCount)
self._shardsPtr.dealloc(self._shardsCount)
}
public func add(operand: Int, randomInt: Int) {
let shardIndex = Int(UInt(bitPattern: randomInt) % UInt(self._shardsCount))
_swift_stdlib_atomicFetchAddInt(
object: self._shardsPtr + shardIndex, operand: operand)
}
// FIXME: non-atomic as a whole!
public func getSum() -> Int {
var result = 0
let shards = self._shardsPtr
let count = self._shardsCount
for var i = 0; i != count; i++ {
result += _swift_stdlib_atomicLoadInt(object: shards + i)
}
return result
}
public struct PRNG {
var _state: Int
public init() {
_state = Int(Int32(bitPattern: rand32()))
}
public mutating func randomInt() -> Int {
var result = 0
for var i = 0; i != Int._sizeInBits; ++i {
result = (result << 1) | (_state & 1)
_state = (_state >> 1) ^ (-(_state & 1) & Int(bitPattern: 0xD0000001))
}
return result
}
}
}
| 662ef169dbbec6c59d341ee920853249 | 30.421687 | 80 | 0.624233 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/Interpreter/SDK/objc_subclass.swift | apache-2.0 | 18 | // RUN: %target-run-simple-swift foo | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
class SuperString : NSString {
var len = Int()
override init() { super.init() }
init(_ len:Int) {
super.init()
self.len = len
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override var length: Int {
return len
}
override func character(at n: Int) -> unichar {
return unichar(0x30 + n)
}
override func substring(with r: NSRange) -> String {
if (r.location == 0) {
return SuperString(r.length) as String
}
return super.substring(with: r)
}
}
// CHECK: 0123456789
print(SuperString(10))
// CHECK: 0123456789
print(NSString(string: SuperString(10) as String))
// CHECK: 012
print(SuperString(10).substring(with: NSRange(location: 0, length: 3)))
// CHECK: 345
print(SuperString(10).substring(with: NSRange(location: 3, length: 3)))
class X {
var label: String
init(_ label: String) {
self.label = label
print("Initializing \(label)");
}
deinit {
print("Destroying \(label)");
}
}
@requires_stored_property_inits
class A : NSObject {
var x1 = X("A.x1")
var x2 = X("A.x2")
override init() {
print("Initializing A instance");
}
deinit {
print("Destroying A instance");
}
}
class B : A {
var y1 = X("B.y1")
var y2 = X("B.y2")
override init() {
super.init()
print("Initializing B instance");
}
deinit {
print("Destroying B instance");
}
}
func testB() -> B {
return B()
}
// CHECK: Initializing A.x1
// CHECK: Initializing A.x2
// CHECK: Initializing B.y1
// CHECK: Initializing B.y2
// CHECK: Initializing A instance
// CHECK: Initializing B instance
// CHECK: Destroying B instance
// CHECK: Destroying A instance
// CHECK: Destroying B.y1
// CHECK: Destroying B.y2
// CHECK: Destroying A.x1
// CHECK: Destroying A.x2
testB()
// Propagating nil init out of a superclass initialization.
class MyNSData : NSData {
init?(base64EncodedString str: String) {
super.init(base64Encoded:str,
options:[])
print("MyNSData code should not be executed")
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
// CHECK-NOT: should not be executed
if let myNSData = MyNSData(base64EncodedString:"\n\n\n") {
print("NSData came back non-nil?")
} else {
// CHECK: nil MyNSData as expected
print("nil MyNSData as expected")
}
// Propagating nil out of delegating initialization.
extension NSData {
convenience init?(myString str: String) {
self.init(base64Encoded:str,
options:[])
print("NSData code should not be executed")
}
}
// CHECK-NOT: NSData code should not be executed
var nsData : NSData! = NSData(myString:"\n\n\n")
if nsData == nil {
// CHECK: nil NSData as expected
print("nil NSData as expected")
}
| db23b3e58405492cc45d170d4f8bf937 | 19.28169 | 71 | 0.651042 | false | false | false | false |
EagleKing/SwiftStudy | refs/heads/master | 闭包.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import Cocoa
//闭包排序以及简化写法****************************************
let names = ["Chris","Alex","Ewa","Barry","Daniella"]
func backwards(s1:String,s2:String) -> Bool
{
return s1 > s2
}
var reversed = names.sort(backwards)
reversed = names.sort(
{(s1:String,s2:String) -> Bool in return s1 > s2 })//返回yes即在前面
reversed = names.sort(
{s1,s2 in return s1 > s2})
reversed = names.sort(
{s1,s2 in s1 > s2})
reversed = names.sort({$0 > $1})
reversed = names.sort(>)
//***********************************************
//尾随闭包****************************************
reversed = names.sort(){$0>$1}//尾随闭包
reversed = names.sort{$0>$1}//尾随闭包省略括号()
//尾随闭包应用
let digitNames =
[
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16,58,510]
let strings = numbers.map()
{
(var number) -> String in
var output = ""
while number > 0
{
output = digitNames[number%10]! + output//取余
number /= 10
}
return output
}
//捕获值**************************************
func makeIncrementor(forIncrement amount:Int)->()->Int //注意,这里返回的是函数
{
var runningTotal = 0
func incrementor()->Int
{
runningTotal += amount//捕获变量的引用
return runningTotal
}
return incrementor
}
let incrementByTen = makeIncrementor(forIncrement: 10)
var a = incrementByTen();
a = incrementByTen();
a = incrementByTen();
a = incrementByTen();
let incermentBySeven = makeIncrementor(forIncrement: 7)
var b = incermentBySeven()
b = incermentBySeven()
let alsoIncrementByTen = incrementByTen
let c = alsoIncrementByTen()
//非逃逸性闭包
//在参数前面加上@noescape
//逃逸性闭包
var completionHandlers:[()-> Void] = []
func someFuncWithEscapingclosure( completionHandler:()-> Void)
{
completionHandlers.append(completionHandler)
}
func someFuncWithNoEscapingclosure(@noescape completionHandler:() -> Void)
{
completionHandler()
}
class SomeClass
{
var x = 10
func doSomething()
{
someFuncWithEscapingclosure {self.x = 100}
someFuncWithNoEscapingclosure(){x = 200}//逃逸性闭包可以隐式引用self,尾随闭包
}
}
let instance = SomeClass()
instance.doSomething()
let aProperty = instance.x
completionHandlers.first?()//逃逸性闭包延迟执行
print(instance.x)
//自动闭包是一种自动创建的闭包,用来包装给函数作为参数的表达式
var customersInLine = ["chris","alex","ewa","barry","daniella"]
print(customersInLine.count)
let customerProvider = {customersInLine.removeAtIndex(0)}//此为自动闭包
print(customersInLine.count)
print("Now serving \(customersInLine.removeAtIndex(0))")
print(customersInLine.count)
func serveCustomer(customerProvider:()->String)
{
print("Now serving \(customerProvider())!")
}
serveCustomer({customersInLine.removeAtIndex(0)})
//@autoclosures(escaping)允许闭包逃逸
var customerProviders:[()->String] = []
func collectCustomerProviders(@autoclosure(escaping) cutomerProvider:()->String)
{
customerProviders.append(customerProvider)
}
collectCustomerProviders(customersInLine.removeAtIndex(0))
collectCustomerProviders(customersInLine.removeAtIndex(0))
print("Collected \(customerProviders.count)closures.")
for customerProvider in customerProviders
{
print("Now serving \(customerProvider())!")
}
| d2cd6a7938b1c9c5c49df53e53d60939 | 22.882353 | 80 | 0.663177 | false | false | false | false |
pozi119/VOVCManager.Swift | refs/heads/master | VOVCManager.Swift/VCManager/VCManager.swift | gpl-3.0 | 2 | //
// VCManager.swift
// VOVCManagerDemo
//
// Created by Valo on 15/6/29.
// Copyright (c) 2015年 Valo. All rights reserved.
//
import UIKit
//MARK:调试开关
let VO_DEBUG = true
//MARK:注册信息Key
let VCName:String = "name"
let VCController:String = "controller"
let VCStoryBoard:String = "storyboard"
let VCISPresent:String = "present"
//MARK:全局方法
/**
设置指定对象的参数
:param: params 参数
:param: obj 指定对象
*/
private func setParams(params:Dictionary<String,AnyObject>, forObject obj:AnyObject){
for (key,val) in params{
let sel:Selector? = Selector(key)
if(sel != nil && obj.respondsToSelector(sel!)){
obj.setValue(val, forKey: key)
}
}
}
func swiftClassFromString(className: String) -> AnyClass! {
if var appName: String? = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as! String? {
appName = appName?.stringByReplacingOccurrencesOfString(".", withString: "_", options: NSStringCompareOptions.LiteralSearch, range: nil)
let classStringName = "\(appName!).\(className)"
var cls: AnyClass? = NSClassFromString(classStringName)
assert(cls != nil, "class notfound,please check className")
return cls
}
return nil;
}
class VCRegistration: NSObject{
var name:String?
var controller:String?
var storyboard:String?
var isPresent:Bool = false
convenience init?(spec:Dictionary<String,AnyObject>?){
self.init()
if(spec != nil){
setParams(spec!, forObject: self)
}
}
}
class VCManager: NSObject{
//MARK:私有属性
private var viewControllers = [UIViewController]()
private var naviControllers = [UINavigationController]()
private var registerList:Set<VCRegistration> = []
//MARK:公共属性
var curViewController:UIViewController?{
get{
return self.viewControllers.last
}
}
var curNaviController:UINavigationController?{
get {
var navi = self.viewControllers.last?.navigationController
if(navi == nil){
navi = self.naviControllers.last
}
return navi
}
}
//MARK:单例对象
/// 生成单例对象
class func sharedManager()->VCManager{
struct Singleton{
static var predicate:dispatch_once_t = 0
static var instance:VCManager? = nil
}
dispatch_once(&Singleton.predicate,{
Singleton.instance = VCManager()
Singleton.instance?.commonInit()
}
)
return Singleton.instance!
}
//MARK:viewController管理
/**
将viewController添加到缓存列表
:param: viewController 要添加的viewController
*/
func addViewController(viewController:UIViewController){
if(viewController.isKindOfClass(UIViewController.classForCoder()) && NSStringFromClass(viewController.classForCoder) != "UIInputWindowController"){
self.viewControllers.append(viewController)
self.printWithTag("Appear")
}
if(viewController.isKindOfClass(UINavigationController.classForCoder())){
self.naviControllers.append(viewController as! UINavigationController)
}
}
/**
从保存的viewController列表中删除指定的viewController
:param: viewController 要删除的viewController
*/
func removeViewController(viewController:UIViewController){
var index:Int = -1
for i in 0..<self.viewControllers.count{
let tmpVc = self.viewControllers[i]
if(tmpVc == viewController){
index = i
break
}
}
if(index >= 0){
self.viewControllers.removeAtIndex(index)
self.printWithTag("DisAppear")
}
index = -1
if(viewController.isKindOfClass(UINavigationController.classForCoder())){
for i in 0..<self.naviControllers.count{
let tmpVc = self.naviControllers[i]
if(tmpVc == viewController){
index = i
break
}
}
if(index >= 0){
self.naviControllers.removeAtIndex(index)
}
}
}
//MARK: viewController生成
/**
根据ViewController名称和Storyboard名称生成ViewController,无参数
:param: aController 页面名称
:param: aStoryboard 故事版名称
:returns: viewController or nil
*/
func viewController(aController:String, storyboard aStoryboard:String?)->UIViewController?{
return self.viewController(aController, storyboard: aStoryboard, params: nil)
}
/**
根据ViewController名称和Storyboard名称生成ViewController
:param: aController 页面名称
:param: aStoryboard 故事版名称
:param: params 页面参数
:returns: viewController or nil
*/
func viewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?)->UIViewController?{
let aClass:AnyClass? = swiftClassFromString(aController)
if(aClass == nil){
return nil
}
var viewController:AnyObject? = nil
if(aStoryboard?.lengthOfBytesUsingEncoding(NSASCIIStringEncoding) > 0){
let storyboard:UIStoryboard? = UIStoryboard(name: aStoryboard!, bundle: nil)
if(storyboard != nil){
viewController = storyboard?.instantiateViewControllerWithIdentifier(aController)
}
}
if(viewController == nil){
let aControllerClass = aClass as! UIViewController.Type
viewController = aControllerClass(nibName: aController, bundle: nil)
if(viewController == nil){
viewController = aControllerClass()
}
}
if(viewController != nil && params != nil){
setParams(params!, forObject: viewController!)
}
return viewController as? UIViewController
}
//MARK: 页面跳转
/**
页面跳转,push
:param: aController 页面名称
:param: aStoryboard 故事版名称
*/
func pushViewController(aController:String, storyboard aStoryboard:String?){
self.pushViewController(aController, storyboard: aStoryboard, params: nil, animated: true)
}
/**
页面跳转,push,指定是否有动画效果
:param: aController 页面名称
:param: aStoryboard 故事版名称
:param: animated 是否有动画效果
*/
func pushViewController(aController:String, storyboard aStoryboard:String?, animated:Bool){
self.pushViewController(aController, storyboard: aStoryboard, params: nil, animated: animated)
}
/**
页面跳转,push,设置参数
:param: aController 页面名称
:param: aStoryboard 故事版名称
:param: params 页面参数
*/
func pushViewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?){
self.pushViewController(aController, storyboard: aStoryboard, params: params, animated: true)
}
/**
页面跳转,push,设置参数,并指定是否有动画效果
:param: aController 页面名称
:param: aStoryboard 故事版名称
:param: params 页面参数
:param: animated 是否有动画效果
*/
func pushViewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?, animated:Bool){
let viewController = self.viewController(aController, storyboard: aStoryboard, params: params)
if(viewController == nil){
return
}
self.curNaviController?.pushViewController(viewController!, animated: animated)
}
/**
页面跳转,push,跳转至指定页面,并移除中间页面
:param: aController 页面名称
:param: aStoryboard 故事版名称
:param: params 页面参数
:param: animated 是否有动画效果
:param: removeControllers 要移除的页面名称数组
*/
func pushViewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?, animated:Bool, removeControllers:[String]?){
self.pushViewController(aController, storyboard: aStoryboard, params: params, animated:animated)
if(removeControllers == nil || self.curNaviController == nil){
return
}
for removeController in removeControllers!{
if(removeController != aController){
var removeIndexes = [Int]()
for i in 0..<self.curNaviController!.viewControllers.count{
let viewController:AnyObject = self.curNaviController!.viewControllers[i]
if(viewController.type == removeController){
removeIndexes.append(i)
}
}
for index in removeIndexes{
self.curNaviController?.viewControllers.removeAtIndex(index)
}
}
}
}
//MARK: 页面出栈
/**
页面出栈,指定是否有动画效果
:param: animated 是否有动画效果
:returns: 出栈的页面
*/
func popViewControllerAnimated(animated:Bool)->UIViewController?{
return self.curNaviController?.popViewControllerAnimated(animated)
}
/**
页面出栈,至根页面,指定是否有动画效果
:param: animated 指定是否有动画效果
:returns: 出栈的页面数组
*/
func popToRootViewControllerAnimated(animated:Bool)->[AnyObject]?{
return self.curNaviController?.popToRootViewControllerAnimated(animated)
}
/**
页面出栈,至指定页面,设置参数,指定是否有动画效果
:param: aController 要显示的页面
:param: params 要显示页面的参数
:param: animated 是否有动画效果
:returns: 出栈的页面数组
*/
func popToViewController(aController:String, params:Dictionary<String,AnyObject>?, animated:Bool)->[AnyObject]?{
if(self.curNaviController == nil){
return nil
}
var targetVC:UIViewController? = nil
for viewController in self.curNaviController!.viewControllers{
if(viewController.type == aController){
targetVC = viewController as? UIViewController
break;
}
}
if(targetVC != nil){
if(params != nil){
setParams(params!, forObject: targetVC!)
}
return self.curNaviController?.popToViewController(targetVC!, animated: animated)
}
return nil;
}
//MARK:页面显示
/**
页面显示,present方式,设置参数,指定动画等
:param: aController 页面名称
:param: aStoryboard 故事版名称
:param: params 页面参数
:param: animated 是否有动画效果
:param: completion 显示完成后的操作
*/
func presentViewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?, animated:Bool, completion:(()->Void)?){
self.presentViewController(aController, storyboard: aStoryboard, params: params, animated: animated, isInNavi: false, completion: completion)
}
/**
页面显示,present方式,设置参数,指定动画,是否包含在导航页中
:param: aController 页面名称
:param: aStoryboard 故事版名称
:param: params 页面参数
:param: animated 是否有动画效果
:param: inNavi 是否包含在导航页中
:param: completion 显示完成后的操作
*/
func presentViewController(aController:String, storyboard aStoryboard:String?, params:Dictionary<String,AnyObject>?, animated:Bool,isInNavi inNavi:Bool, completion:(()->Void)?){
let viewController = self.viewController(aController, storyboard: aStoryboard, params: params)
if(viewController == nil||self.curViewController == nil){
return
}
if(inNavi){
if(self.curNaviController == nil){
let navi = UINavigationController(rootViewController: viewController!)
self.curViewController?.presentViewController(navi, animated: animated, completion: completion)
}
else{
self.curNaviController!.presentViewController(viewController!, animated: animated, completion: completion)
}
}
else{
self.curViewController!.presentViewController(viewController!, animated: animated, completion: completion)
}
}
/**
页面销毁
:param: animated 是否有动画效果
:param: completion 页面销毁后的操作
*/
func dismissViewControllerAnimated(animated:Bool, completion:(()->Void)?){
if(self.curViewController == nil){
return
}
self.curViewController!.dismissViewControllerAnimated(animated, completion: completion)
}
//MARK:页面URL管理
/**
注册页面
:param: spec 页面特征参数
*/
func registerWithSpec(spec:Dictionary<String,AnyObject>){
let vcReg:VCRegistration? = VCRegistration(spec: spec)
if(vcReg != nil){
self.addRegistration(vcReg!)
}
}
/**
注册页面
:param: name 页面注册名
:param: aController 页面名称
:param: aStoryboard 故事版名称
:param: isPresent 是否present方式显示,是-present,否-push
*/
func registerName(name:String,forViewController aController:String, storyboard aStoryboard:String?, isPresent:Bool){
let vcReg = VCRegistration()
vcReg.name = name
vcReg.controller = aController
vcReg.storyboard = aStoryboard
vcReg.isPresent = isPresent
self.addRegistration(vcReg)
}
/**
取消注册页面
:param: name 页面注册名
*/
func cancelRegisterName(name:String){
var removeVcReg:VCRegistration? = nil
for vcReg in self.registerList{
vcReg.name == name
removeVcReg = vcReg
break
}
if(removeVcReg != nil){
self.registerList.remove(removeVcReg!)
}
}
/**
处理URL
:param: url 以AppScheme开始的URL
:returns: 是否成功处理
*/
func handleURL(url:NSURL)->Bool{
/** 1.检查scheme是否匹配 */
let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: true)
let urlTypes:[Dictionary<String, AnyObject>]? = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleURLTypes") as? [Dictionary<String, AnyObject>]
var schemes = [String]()
if(urlTypes == nil){
return false
}
for dic in urlTypes!{
let tmpArray:[String]? = dic["CFBundleURLSchemes"] as? [String]
if(tmpArray != nil){
schemes += tmpArray!
}
}
var match:Bool = false
for scheme in schemes{
if(scheme == components?.scheme){
match = true
}
}
if(!match){
return false
}
/** 2.获取页面名 */
let name = (components?.path?.lengthOfBytesUsingEncoding(NSASCIIStringEncoding) == 0) ? components?.host : components?.path?.lastPathComponent
/** 3.获取页面参数 */
var params:Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
let tmpArray = components?.query?.componentsSeparatedByString("&")
if(tmpArray == nil){
return false
}
for paramStr in tmpArray!{
let range = paramStr.rangeOfString("=", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)
if(range != nil){
let key = paramStr.substringToIndex(range!.startIndex)
let val = paramStr.substringFromIndex(range!.endIndex)
params[key] = val
}
}
/** 4.打开对应页面 */
self.showViewControllerWithRegisterName(name!, params: params)
return true
}
/**
显示指定页面
:param: name 页面注册名
:param: params 页面参数
*/
func showViewControllerWithRegisterName(name:String, params:Dictionary<String, AnyObject>){
/** 1.检查是否注册,若注册,则获取相应的参数 */
var registration:VCRegistration? = nil
for tmpReg in self.registerList{
if(tmpReg.name == name){
registration = tmpReg
break
}
}
if(registration == nil || registration?.controller == nil){
return
}
/** 2.打开指定页面 */
if(registration!.isPresent){
self.presentViewController(registration!.controller!, storyboard: registration!.storyboard, params: params, animated: true, completion: nil)
}
else{
self.pushViewController(registration!.controller!, storyboard: registration!.storyboard, params: params)
}
}
//MARK:私有函数
private func commonInit(){
UIViewController.record()
}
/**
打印viewController层级信息
:param: tag 打印标签
*/
private func printWithTag(tag:String){
if(VO_DEBUG){
var paddingItems:String = ""
for tmpVc in self.viewControllers{
paddingItems = paddingItems + "--"
}
println("\(tag):\(paddingItems)>\(self.viewControllers.last?.description)")
}
}
/**
添加注册信息
:param: registration 注册信息
:returns: 是否添加成功
*/
private func addRegistration(registration:VCRegistration)->Bool{
for vcReg in self.registerList{
if(vcReg.name == registration.name){
return false
}
}
self.registerList.insert(registration)
return true
}
} | 32f3ff2853886c0ce335a53cae8dd492 | 30.483456 | 181 | 0.607089 | false | false | false | false |
verticon/VerticonsToolbox | refs/heads/master | VerticonsToolbox/NumericType.swift | mit | 1 | //
// NumericType.swift
// VerticonsToolbox
//
// Created by Robert Vaessen on 6/9/17.
// Copyright © 2017 Verticon. All rights reserved.
//
import Foundation
public enum NumericType : CustomStringConvertible {
case int8
case uint8
case int16
case uint16
case int32
case uint32
case int64
case uint64
case float
case double
public static let all: [NumericType] = [.int8, .uint8, .int16, .uint16, .int32, .uint32, .int64, .uint64, .float, .double]
public var description: String { return self.name }
public var name: String {
switch self {
case .int8: return "\(Int8.self)"
case .uint8: return "\(UInt8.self)"
case .int16: return "\(Int16.self)"
case .uint16: return "\(UInt16.self)"
case .int32: return "\(Int32.self)"
case .uint32: return "\(UInt32.self)"
case .int64: return "\(Int64.self)"
case .uint64: return "\(UInt64.self)"
case .float: return "\(Float.self)"
case .double: return "\(Double.self)"
}
}
/// The index of this numeric type in the NumericType.all array
public var index: Int {
return NumericType.all.firstIndex { self == $0 }!
}
public func valueToData(value: String) -> Data? {
switch self {
case .int8:
return Int8(value)?.data
case .uint8:
return UInt8(value)?.data
case .int16:
return Int16(value)?.data
case .uint16:
return UInt16(value)?.data
case .int32:
return Int32(value)?.data
case .uint32:
return UInt32(value)?.data
case .int64:
return Int64(value)?.data
case .uint64:
return UInt64(value)?.data
case .float:
return Float(value)?.data
case .double:
return Double(value)?.data
}
}
public func valueFromData(data: Data, hex: Bool) -> String? {
switch self {
case .int8:
guard let number = Int8(data: data) else { return nil }
return String(format: hex ? "%02hhX" : "%hhd", number)
case .uint8:
guard let number = UInt8(data: data) else { return nil }
return String(format: hex ? "%02hhX" : "%hhu", number)
case .int16:
guard let number = Int16(data: data) else { return nil }
return String(format: hex ? "%04hX " : "%hd ", number)
case .uint16:
guard let number = UInt16(data: data) else { return nil }
return String(format: hex ? "%04hX " : "%hu ", number)
case .int32:
guard let number = Int32(data: data) else { return nil }
return String(format: hex ? "%08X " : "%d ", number)
case .uint32:
guard let number = UInt32(data: data) else { return nil }
return String(format: hex ? "%08X " : "%u ", number)
case .int64:
guard let number = Int64(data: data) else { return nil }
return String(format: hex ? "%016X " : "%ld ", number)
case .uint64:
guard let number = UInt64(data: data) else { return nil }
return String(format: hex ? "%016X " : "%lu ", number)
case .float:
guard let number = Float(data: data) else { return nil }
return String(format: "%f ", number)
case .double:
guard let number = Double(data: data) else { return nil }
return String(format: "%f ", number)
}
}
}
| 0b9724ceb123a0975632c9ca45416d86 | 28.906977 | 126 | 0.506739 | false | false | false | false |
Desgard/Calendouer-iOS | refs/heads/master | Calendouer/Calendouer/App/Model/WeatherObject.swift | mit | 1 | //
// WeatherObject.swift
// Calendouer
//
// Created by 段昊宇 on 2017/3/8.
// Copyright © 2017年 Desgard_Duan. All rights reserved.
//
import UIKit
class WeatherObject: NSObject, NSCoding {
var id: String = ""
var name: String = ""
var country: String = ""
var path: String = ""
var timezone: String = ""
var timezone_offset: String = ""
var date: String = ""
var text_day: String = ""
var code_day: String = ""
var text_night: String = ""
var code_night: String = ""
var high: String = ""
var low: String = ""
var precip: String = ""
var wind_direction: String = ""
var wind_direction_degree: String = ""
var wind_speed: String = ""
var wind_scale: String = ""
var last_update: String = ""
var city: String = ""
init(Dictionary dic: [String: String]) {
super.init()
if let id = dic["id"] {
self.id = id
}
if let name = dic["name"] {
self.name = name
}
if let country = dic["country"] {
self.country = country
}
if let path = dic["path"] {
self.path = path
}
if let timezone = dic["timezone"] {
self.timezone = timezone
}
if let timezone_offset = dic["timezone_offset"] {
self.timezone_offset = timezone_offset
}
if let date = dic["date"] {
self.date = date
}
if let text_day = dic["text_day"] {
self.text_day = text_day
}
if let code_day = dic["code_day"] {
self.code_day = code_day
}
if let code_night = dic["code_night"] {
self.code_night = code_night
}
if let text_night = dic["text_night"] {
self.text_night = text_night
}
if let high = dic["high"] {
self.high = high
}
if let low = dic["low"] {
self.low = low
}
if let precip = dic["precip"] {
self.precip = precip
}
if let wind_direction = dic["wind_direction"] {
self.wind_direction = wind_direction
}
if let wind_direction_degree = dic["wind_direction_degree"] {
self.wind_direction_degree = wind_direction_degree
}
if let wind_speed = dic["wind_speed"] {
self.wind_speed = wind_speed
}
if let wind_scale = dic["wind_scale"] {
self.wind_scale = wind_scale
}
if let last_update = dic["last_update"] {
if last_update.characters.count != 0 {
self.last_update = (last_update as NSString).substring(to: 10)
}
}
if let city = dic["city"] {
self.city = city
}
}
public func getWeatherIcon() -> String {
let time: DayObject = DayObject()
var judgeCode = ""
if time.hour >= 5 && time.hour <= 18 {
judgeCode = code_day
} else {
judgeCode = code_night
}
switch judgeCode {
case "0": return "sunny"// 晴天
case "1": return "sunny"
case "2": return "sunny"
case "3": return "sunny"
case "4": return "cloudy"
case "5": return "partly_cloudy_day"
case "6": return "partly_cloudy_day"
case "7": return "mostly_cloudy_day"
case "8": return "mostly_cloudy_day"
case "9": return "mostly_cloudy_day"
case "10": return "shower"
case "11": return "thunder_shower"
case "12": return "thunder_shower"
case "13": return "light_rain"
case "14": return "moderate_rain"
case "15": return "heavy_rain"
case "16": return "heavy_rain"
case "17": return "heavy_rain"
case "18": return "heavy_rain"
case "19": return "ice_rain"
case "20": return "heavy_rain"
case "21": return "snow"
case "22": return "snow"
case "23": return "snow"
case "24": return "snow"
case "25": return "snow"
case "26": return "mist"
case "27": return "mist"
case "28": return "mist"
case "29": return "mist"
case "30": return "mist"
case "31": return "mist"
case "32": return "wind"
case "33": return "wind"
case "34": return "wind"
case "35": return "wind"
case "36": return "wind"
case "37": return "wind"
case "38": return "sunny"
default:
return "sunny"
}
}
required override init() {
}
// MARK: - NSCoding -
private struct WeatherObjectCodingKey {
static let kCodingID = "id"
static let kCodingName = "name"
static let kCodingCountry = "country"
static let kCodingPath = "path"
static let kCodingTimezone = "timezone"
static let kCodingTimezone_offset = "timezone_offset"
static let kCodingDate = "date"
static let kCodingText_day = "text_day"
static let kCodingCode_day = "code_day"
static let kCodingText_night = "text_night"
static let kCodingCode_night = "code_night"
static let kCodingHigh = "high"
static let kCodingLow = "low"
static let kCodingPrecip = "precip"
static let kCodingWind_direction = "wind_direction"
static let kCodingWind_direction_degree = "wind_direction_degree"
static let kCodingWind_speed = "wind_speed"
static let kCodingWind_scale = "wind_scale"
static let kCodingLast_update = "last_update"
static let kCodingCity = "city"
}
required init?(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingID) as! String
self.name = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingName) as! String
self.country = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingCountry) as! String
self.path = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingPath) as! String
self.timezone = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingTimezone) as! String
self.timezone_offset = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingTimezone_offset) as! String
self.date = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingDate) as! String
self.text_day = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingText_day) as! String
self.code_day = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingCode_day) as! String
self.text_night = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingText_night) as! String
self.code_night = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingCode_night) as! String
self.high = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingHigh) as! String
self.low = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingLow) as! String
self.precip = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingPrecip) as! String
self.wind_direction = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingWind_direction) as! String
self.wind_direction_degree = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingWind_direction_degree) as! String
self.wind_speed = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingWind_speed) as! String
self.wind_scale = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingWind_scale) as! String
self.last_update = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingLast_update) as! String
self.city = aDecoder.decodeObject(forKey: WeatherObjectCodingKey.kCodingCity) as! String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.id, forKey: WeatherObjectCodingKey.kCodingID)
aCoder.encode(self.name, forKey: WeatherObjectCodingKey.kCodingName)
aCoder.encode(self.country, forKey: WeatherObjectCodingKey.kCodingCountry)
aCoder.encode(self.path, forKey: WeatherObjectCodingKey.kCodingPath)
aCoder.encode(self.timezone, forKey: WeatherObjectCodingKey.kCodingTimezone)
aCoder.encode(self.timezone_offset, forKey: WeatherObjectCodingKey.kCodingTimezone_offset)
aCoder.encode(self.date, forKey: WeatherObjectCodingKey.kCodingDate)
aCoder.encode(self.text_day, forKey: WeatherObjectCodingKey.kCodingText_day)
aCoder.encode(self.code_day, forKey: WeatherObjectCodingKey.kCodingCode_day)
aCoder.encode(self.text_night, forKey: WeatherObjectCodingKey.kCodingText_night)
aCoder.encode(self.code_night, forKey: WeatherObjectCodingKey.kCodingCode_night)
aCoder.encode(self.high, forKey: WeatherObjectCodingKey.kCodingHigh)
aCoder.encode(self.low, forKey: WeatherObjectCodingKey.kCodingLow)
aCoder.encode(self.precip, forKey: WeatherObjectCodingKey.kCodingPrecip)
aCoder.encode(self.wind_direction, forKey: WeatherObjectCodingKey.kCodingWind_direction)
aCoder.encode(self.wind_direction_degree, forKey: WeatherObjectCodingKey.kCodingWind_direction_degree)
aCoder.encode(self.wind_speed, forKey: WeatherObjectCodingKey.kCodingWind_speed)
aCoder.encode(self.wind_scale, forKey: WeatherObjectCodingKey.kCodingWind_scale)
aCoder.encode(self.last_update, forKey: WeatherObjectCodingKey.kCodingLast_update)
aCoder.encode(self.city, forKey: WeatherObjectCodingKey.kCodingCity)
}
}
| c2c7093c70e4d4fc141a73db1369ff1a | 45.084444 | 130 | 0.580577 | false | false | false | false |
nearspeak/iOS-SDK | refs/heads/master | NearspeakKit/NSKManager.swift | lgpl-3.0 | 1 | //
// NSKManager.swift
// NearspeakKit
//
// Created by Patrick Steiner on 27.01.15.
// Copyright (c) 2015 Nearspeak. All rights reserved.
//
import UIKit
import CoreLocation
import CoreBluetooth
private let _NSKManagerSharedInstance = NSKManager()
/**
Nearspeak Manager class.
*/
public class NSKManager: NSObject {
/**
Get the singelton object of this class.
*/
public class var sharedInstance: NSKManager {
return _NSKManagerSharedInstance
}
private let tagQueue = dispatch_queue_create("at.nearspeak.manager.tagQueue", DISPATCH_QUEUE_CONCURRENT)
private var _nearbyTags = [NSKTag]()
private var activeUUIDs = Set<NSUUID>()
private var unkownTagID = -1
/**
Array of all currently nearby Nearspeak tags.
*/
public var nearbyTags: [NSKTag] {
var nearbyTagsCopy = [NSKTag]()
var tags = [NSKTag]()
dispatch_sync(tagQueue) {
nearbyTagsCopy = self._nearbyTags
}
if showUnassingedBeacons {
return nearbyTagsCopy
} else {
for tag in nearbyTagsCopy {
if let _ = tag.tagIdentifier {
tags.append(tag)
}
}
}
return tags
}
public var unassignedTags: [NSKTag] {
var nearbyTagsCopy = [NSKTag]()
var unassingedTags = [NSKTag]()
dispatch_sync(tagQueue) {
nearbyTagsCopy = self._nearbyTags
}
// remove assigend tags
for tag in nearbyTagsCopy {
if tag.tagIdentifier == nil {
unassingedTags.append(tag)
}
}
return unassingedTags
}
private var api = NSKApi(devMode: false)
private var beaconManager: NSKBeaconManager?
private var showUnassingedBeacons = false
// Current beacons
private var beacons = [CLBeacon]()
/**
The standard constructor.
*/
public override init() {
super.init()
setupBeaconManager()
}
// MARK: - NearbyBeacons - public
/**
Check if the device has all necessary features enabled to support beacons.
:return: True if all necessary features are enabled, else false.
*/
public func checkForBeaconSupport() -> Bool {
if let bManager = beaconManager {
return bManager.checkForBeaconSupport()
}
return false
}
/**
Add a custom UUID for monitoring.
*/
public func addCustomUUID(uuid: String) {
if let uuid = NSUUID(UUIDString: uuid) {
var uuids = Set<NSUUID>()
uuids.insert(uuid)
beaconManager?.addUUIDs(uuids)
activeUUIDs.insert(uuid)
}
}
/**
Add the UUIDs from the Nearspeak server.
*/
public func addServerUUIDs() {
getActiveUUIDs()
}
/**
Start monitoring for iBeacons.
*/
public func startBeaconMonitoring() {
if let beaconManager = beaconManager {
beaconManager.startMonitoringForNearspeakBeacons()
}
}
/**
Stop monitoring for iBeacons.
*/
public func stopBeaconMonitoring() {
if let beaconManager = beaconManager {
beaconManager.stopMonitoringForNearspeakBeacons()
}
}
/**
Start the Nearspeak beacon discovery / ranging.
- parameter showUnassingedBeacons: True if unassinged Nearspeak beacons should also be shown.
*/
public func startBeaconDiscovery(showUnassingedBeacons: Bool) {
if let bManager = beaconManager {
bManager.startRangingForNearspeakBeacons()
}
self.showUnassingedBeacons = showUnassingedBeacons
}
/**
Stop the Nearspeak beacon discovery.
*/
public func stopBeaconDiscovery() {
if let bManager = beaconManager {
bManager.stopRangingForNearspeakBeacons()
}
}
/**
Get a Nearspeak tag object from the nearby beacons array.
- parameter index: The index of the Nearspeak tag object.
*/
public func getTagAtIndex(index: Int) -> NSKTag? {
return _nearbyTags[index]
}
/**
Show or hide unassigned Nearspeak tags.
- parameter show: True if unassinged Nearspeak beacons should als be show.
*/
public func showUnassingedBeacons(show: Bool) {
if show != showUnassingedBeacons {
showUnassingedBeacons = show
self.reset()
}
}
/**
Add a demo tag for the simulator.
*/
public func addDemoTag(hardwareIdentifier: String, majorId: String, minorId: String) {
self.api.getTagByHardwareId(hardwareIdentifier: hardwareIdentifier, beaconMajorId: majorId, beaconMinorId: minorId) { (succeeded, tag) -> () in
if succeeded {
if let tag = tag {
self.addTag(tag)
}
}
}
}
/**
Reset the NSKManager.
*/
public func reset() {
self.removeAllTags()
self.removeAllBeacons()
}
// MARK: - private
private func getActiveUUIDs() {
api.getSupportedBeaconsUUIDs { (succeeded, uuids) -> () in
if succeeded {
var newUUIDS = Set<NSUUID>()
for uuid in uuids {
if newUUIDS.count < NSKApiUtils.maximalBeaconUUIDs {
if let id = NSKApiUtils.hardwareIdToUUID(uuid) {
newUUIDS.insert(id)
self.activeUUIDs.insert(id)
}
}
}
if let beaconManager = self.beaconManager {
beaconManager.addUUIDs(newUUIDS)
}
}
}
}
private func setupBeaconManager() {
beaconManager = NSKBeaconManager(uuids: activeUUIDs)
beaconManager!.delegate = self
}
// MARK: - NearbyBeacons - private
private func addTagWithBeacon(beacon: CLBeacon) {
// check if this beacon currently gets added
for addedBeacon in beacons {
if beaconsAreTheSame(beaconOne: addedBeacon, beaconTwo: beacon) {
// beacon is already in the beacon array, update the current tag
updateTagWithBeacon(beacon)
return
}
}
// add the new beacon to the waiting array
beacons.append(beacon)
self.api.getTagByHardwareId(hardwareIdentifier: beacon.proximityUUID.UUIDString, beaconMajorId: beacon.major.stringValue, beaconMinorId: beacon.minor.stringValue) { (succeeded, tag) -> () in
if succeeded {
if let currentTag = tag {
// set the discovered beacon as hardware beacon on the new tag
currentTag.hardwareBeacon = beacon
self.addTag(currentTag)
} else { // beacon is not assigned to a tag in the system
self.addUnknownTagWithBeacon(beacon)
}
} else { // beacon is not assigned to a tag in the system
self.addUnknownTagWithBeacon(beacon)
}
}
}
private func addUnknownTagWithBeacon(beacon: CLBeacon) {
let tag = NSKTag(id: unkownTagID)
tag.name = "Unassigned Tag: \(beacon.major) - \(beacon.minor)"
tag.hardwareBeacon = beacon
self.addTag(tag)
unkownTagID -= 1
}
private func addTag(tag: NSKTag) {
dispatch_barrier_async(tagQueue, { () -> Void in
self._nearbyTags.append(tag)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.postContentUpdateNotification()
})
})
}
private func removeTagWithId(id: Int) {
var index = 0
for tag in _nearbyTags {
if tag.id.integerValue == id {
dispatch_barrier_sync(tagQueue, { () -> Void in
self._nearbyTags.removeAtIndex(index)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.postContentUpdateNotification()
})
})
// also remove the beacon from the beacons array
if let beacon = tag.hardwareBeacon {
removeBeacon(beacon)
}
}
index += 1
}
}
private func removeBeacon(beacon: CLBeacon) {
var index = 0
for currentBeacon in beacons {
if beaconsAreTheSame(beaconOne: beacon, beaconTwo: currentBeacon) {
self.beacons.removeAtIndex(index)
}
index += 1
}
}
private func removeAllTags() {
dispatch_barrier_async(tagQueue, { () -> Void in
self._nearbyTags = []
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.postContentUpdateNotification()
})
})
}
private func removeAllBeacons() {
self.beacons = []
}
private func beaconsAreTheSame(beaconOne beaconOne: CLBeacon, beaconTwo: CLBeacon) -> Bool {
if beaconOne.proximityUUID.UUIDString == beaconTwo.proximityUUID.UUIDString {
if beaconOne.major.longLongValue == beaconTwo.major.longLongValue {
if beaconOne.minor.longLongValue == beaconTwo.minor.longLongValue {
return true
}
}
}
return false
}
private func getTagByBeacon(beacon: CLBeacon) -> NSKTag? {
for tag in self._nearbyTags {
if let hwBeacon = tag.hardwareBeacon {
if beaconsAreTheSame(beaconOne: hwBeacon, beaconTwo: beacon) {
return tag
}
}
}
return nil
}
private func updateTagWithBeacon(beacon: CLBeacon) {
if let tag = getTagByBeacon(beacon) {
tag.hardwareBeacon = beacon
postContentUpdateNotification()
}
}
private func processFoundBeacons(beacons: [CLBeacon]) {
// add or update tags
for beacon in beacons {
addTagWithBeacon(beacon)
}
var tagsToRemove = Set<Int>()
// remove old tags
for tag in _nearbyTags {
var isNewBeacon = false
if let hwBeacon = tag.hardwareBeacon {
for beacon in beacons {
// if the beacon is not found. remove the tag
if self.beaconsAreTheSame(beaconOne: beacon, beaconTwo: hwBeacon) {
isNewBeacon = true
}
}
}
if !isNewBeacon {
tagsToRemove.insert(tag.id.integerValue)
}
}
for tagId in tagsToRemove {
removeTagWithId(tagId)
}
}
private func postContentUpdateNotification() {
NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationNearbyTagsUpdatedKey, object: nil)
}
}
// MARK: - NSKBeaconManagerDelegate
extension NSKManager: NSKBeaconManagerDelegate {
/**
Delegate method which gets called, when new beacons are found.
*/
public func beaconManager(manager: NSKBeaconManager!, foundBeacons: [CLBeacon]) {
self.processFoundBeacons(foundBeacons)
}
/**
Delegate method which gets called, when the bluetooth state changed.
*/
public func beaconManager(manager: NSKBeaconManager!, bluetoothStateDidChange bluetoothState: CBCentralManagerState) {
switch bluetoothState {
case .PoweredOn:
NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationBluetoothOkKey, object: nil)
default:
NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationBluetoothErrorKey, object: nil)
}
}
/**
Delegate method which gets called, when the location state changed.
*/
public func beaconManager(manager: NSKBeaconManager!, locationStateDidChange locationState: CLAuthorizationStatus) {
switch locationState {
case .AuthorizedAlways:
NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationLocationAlwaysOnKey, object: nil)
case .AuthorizedWhenInUse:
NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationLocationWhenInUseOnKey, object: nil)
default:
NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationLocationErrorKey, object: nil)
}
}
/**
Delegate method which gets called, when a region is entered.
*/
public func beaconManager(manager: NSKBeaconManager, didEnterRegion region: CLRegion) {
NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationRegionEnterKey, object: region, userInfo: ["region" : region])
}
/**
Delegate method which gets called, when a region is exited.
*/
public func beaconManager(manager: NSKBeaconManager, didExitRegion region: CLRegion) {
NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationRegionExitKey, object: nil, userInfo: ["region" : region])
}
/**
Delegate method which gets called, when new regions are added from the Nearspeak server.
*/
public func newRegionsAdded(manager: NSKBeaconManager) {
NSNotificationCenter.defaultCenter().postNotificationName(NSKConstants.managerNotificationNewRegionAddedKey, object: nil)
}
}
| ab4ab5ef3be40165f1aef980bab184cf | 29.833333 | 198 | 0.5755 | false | false | false | false |
donileo/RMessage | refs/heads/master | Sources/RMessage/Animators/SlideAnimator.swift | mit | 1 | //
// SlideAnimator.swift
//
// Created by Adonis Peralta on 8/6/18.
// Copyright © 2018 None. All rights reserved.
//
import Foundation
import UIKit
private enum Constants {
enum KVC {
static let safeAreaInsets = "view.safeAreaInsets"
}
}
/// Implements an animator that slides the message from the top to target position or
/// bottom to target position. This animator handles the layout of its managed view in the managed
/// view's superview.
class SlideAnimator: NSObject, RMAnimator {
/// Animator delegate.
weak var delegate: RMessageAnimatorDelegate?
// MARK: - Start the customizable animation properties
/// The amount of time to perform the presentation animation in.
var presentationDuration = 0.5
/// The amount of time to perform the dismiss animation in.
var dismissalDuration = 0.3
/// The alpha value the view should have prior to starting animations.
var animationStartAlpha: CGFloat = 0
/// The alpha value the view should have at the end of animations.
var animationEndAlpha: CGFloat = 1
/// A custom vertical offset to apply to the animation. positive values move the view upward,
/// negative values move it downward.
var verticalOffset = CGFloat(0)
/// Enables/disables the use animation padding so as to prevent a visual white gap from appearing when
/// animating with a spring animation.
var disableAnimationPadding = false
private let superview: UIView
@objc private let view: UIView
private let contentView: UIView
private let targetPosition: RMessagePosition
/** The starting animation constraint for the view */
private var viewStartConstraint: NSLayoutConstraint?
/** The ending animation constraint for the view */
private var viewEndConstraint: NSLayoutConstraint?
private var contentViewSafeAreaGuideConstraint: NSLayoutConstraint?
/** The amount of vertical padding/height to add to RMessage's height so as to perform a spring animation without
visually showing an empty gap due to the spring animation overbounce. This value changes dynamically due to
iOS changing the overbounce dynamically according to view size. */
private var springAnimationPadding = CGFloat(0)
private var springAnimationPaddingCalculated = false
private var isPresenting = false
private var isDismissing = false
private var hasPresented = false
private var hasDismissed = true
private var kvcContext = 0
init(targetPosition: RMessagePosition, view: UIView, superview: UIView, contentView: UIView) {
self.targetPosition = targetPosition
self.superview = superview
self.contentView = contentView
self.view = view
super.init()
// Sign up to be notified for when the safe area of our view changes
addObserver(self, forKeyPath: Constants.KVC.safeAreaInsets, options: [.new], context: &kvcContext)
}
/// Ask the animator to present the view with animation. This call may or may not succeed depending on whether
/// the animator was already previously asked to animate or where in the presentation cycle the animator is.
/// In cases when the animator refuses to present this method returns false, otherwise it returns true.
///
/// - Note: Your implementation of this method must allow for this method to be called multiple times by ignoring
/// subsequent requests.
/// - Parameter completion: A completion closure to execute after presentation is complete.
/// - Returns: A boolean value indicating if the animator executed your instruction to present.
func present(withCompletion completion: (() -> Void)?) -> Bool {
// Guard against being called under the following conditions:
// 1. If currently presenting or dismissing
// 2. If already presented or have not yet dismissed
guard !isPresenting && !hasPresented && hasDismissed else {
return false
}
layoutView()
setupFinalAnimationConstraints()
setupStartingAnimationConstraints()
delegate?.animatorWillAnimatePresentation?(self)
animatePresentation(withCompletion: completion)
return true
}
/// Ask the animator to dismiss the view with animation. This call may or may not succeed depending on whether
/// the animator was already previously asked to animate or where in the presentation cycle the animator is.
/// In cases when the animator refuses to dismiss this method returns false, otherwise it returns true.
///
/// - Note: Your implementation of this method must allow for this method to be called multiple times by ignoring
/// subsequent requests.
/// - Parameter completion: A completion closure to execute after presentation is complete.
/// - Returns: A boolean value indicating if the animator executed your instruction to dismiss.
func dismiss(withCompletion completion: (() -> Void)?) -> Bool {
// Guard against being called under the following conditions:
// 1. If currently presenting or dismissing
// 2. If already dismissed or have not yet presented
guard !isDismissing && hasDismissed && hasPresented else {
return false
}
delegate?.animatorWillAnimateDismissal?(self)
animateDismissal(withCompletion: completion)
return true
}
private func animatePresentation(withCompletion completion: (() -> Void)?) {
guard let viewSuper = view.superview else {
assertionFailure("view must have superview by this point")
return
}
guard let viewStartConstraint = viewStartConstraint, let viewEndConstraint = viewEndConstraint else { return }
isPresenting = true
viewStartConstraint.isActive = true
DispatchQueue.main.async {
viewSuper.layoutIfNeeded()
self.view.alpha = self.animationStartAlpha
// For now lets be safe and not call this code inside the animation block. Though there may be some slight timing
// issue in notifying exactly when the animator is animating it should be fine.
self.delegate?.animatorIsAnimatingPresentation?(self)
UIView.animate(
withDuration: self.presentationDuration, delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [.curveEaseInOut, .beginFromCurrentState, .allowUserInteraction],
animations: {
viewStartConstraint.isActive = false
viewEndConstraint.isActive = true
self.contentViewSafeAreaGuideConstraint?.isActive = true
self.delegate?.animationBlockForPresentation?(self)
self.view.alpha = self.animationEndAlpha
viewSuper.layoutIfNeeded()
}, completion: { finished in
self.isPresenting = false
self.hasPresented = true
self.delegate?.animatorDidPresent?(self)
if finished { completion?() }
}
)
}
}
/** Dismiss the view with a completion block */
private func animateDismissal(withCompletion completion: (() -> Void)?) {
guard let viewSuper = view.superview else {
assertionFailure("view must have superview by this point")
return
}
guard let viewStartConstraint = viewStartConstraint, let viewEndConstraint = viewEndConstraint else { return }
isDismissing = true
DispatchQueue.main.async {
viewSuper.layoutIfNeeded()
// For now lets be safe and not call this code inside the animation block. Though there may be some slight timing
// issue in notifying exactly when the animator is animating it should be fine.
self.delegate?.animatorIsAnimatingDismissal?(self)
UIView.animate(
withDuration: self.dismissalDuration, animations: {
viewEndConstraint.isActive = false
self.contentViewSafeAreaGuideConstraint?.isActive = false
viewStartConstraint.isActive = true
self.delegate?.animationBlockForDismissal?(self)
self.view.alpha = self.animationStartAlpha
viewSuper.layoutIfNeeded()
}, completion: { finished in
self.isDismissing = false
self.hasPresented = false
self.hasDismissed = true
self.view.removeFromSuperview()
self.delegate?.animatorDidDismiss?(self)
if finished { completion?() }
}
)
}
}
// MARK: - View notifications
override func observeValue(
forKeyPath keyPath: String?, of _: Any?, change _: [NSKeyValueChangeKey: Any]?,
context _: UnsafeMutableRawPointer?
) {
if keyPath == Constants.KVC.safeAreaInsets {
safeAreaInsetsDidChange(forView: view)
}
}
private func safeAreaInsetsDidChange(forView view: UIView) {
var constant = CGFloat(0)
if targetPosition == .bottom {
constant = springAnimationPadding + view.safeAreaInsets.bottom
} else {
constant = -springAnimationPadding - view.safeAreaInsets.top
}
viewEndConstraint?.constant = constant
}
// MARK: - Layout
/// Lay's out the view in its superview for presentation
private func layoutView() {
setupContentViewLayoutGuideConstraint()
// Add RMessage to superview and prepare the ending constraints
if view.superview == nil { superview.addSubview(view) }
view.translatesAutoresizingMaskIntoConstraints = false
delegate?.animatorDidAddToSuperview?(self)
NSLayoutConstraint.activate([
view.centerXAnchor.constraint(equalTo: superview.centerXAnchor),
view.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
view.trailingAnchor.constraint(equalTo: superview.trailingAnchor)
])
delegate?.animatorDidLayout?(self)
calculateSpringAnimationPadding()
}
private func setupContentViewLayoutGuideConstraint() {
// Install a constraint that guarantees the title subtitle container view is properly spaced from the top layout
// guide when animating from top or the bottom layout guide when animating from bottom
let safeAreaLayoutGuide = superview.safeAreaLayoutGuide
switch targetPosition {
case .top, .navBarOverlay:
contentViewSafeAreaGuideConstraint = contentView.topAnchor.constraint(
equalTo: safeAreaLayoutGuide.topAnchor,
constant: 10
)
case .bottom:
contentViewSafeAreaGuideConstraint = contentView.bottomAnchor.constraint(
equalTo: safeAreaLayoutGuide.bottomAnchor,
constant: -10
)
}
}
private func setupStartingAnimationConstraints() {
guard let viewSuper = view.superview else {
assertionFailure("view must have superview by this point")
return
}
if targetPosition != .bottom {
viewStartConstraint = view.bottomAnchor.constraint(equalTo: viewSuper.topAnchor)
} else {
viewStartConstraint = view.topAnchor.constraint(equalTo: viewSuper.bottomAnchor)
}
}
private func setupFinalAnimationConstraints() {
assert(springAnimationPaddingCalculated, "spring animation padding must have been calculated by now!")
guard let viewSuper = view.superview else {
assertionFailure("view must have superview by this point")
return
}
var viewAttribute: NSLayoutAttribute
var layoutGuideAttribute: NSLayoutAttribute
var constant = CGFloat(0)
view.layoutIfNeeded()
if targetPosition == .bottom {
viewAttribute = .bottom
layoutGuideAttribute = .bottom
constant = springAnimationPadding + viewSuper.safeAreaInsets.bottom
} else {
viewAttribute = .top
layoutGuideAttribute = .top
constant = -springAnimationPadding - viewSuper.safeAreaInsets.top
}
viewEndConstraint = NSLayoutConstraint(
item: view, attribute: viewAttribute, relatedBy: .equal,
toItem: viewSuper.safeAreaLayoutGuide,
attribute: layoutGuideAttribute, multiplier: 1,
constant: constant
)
viewEndConstraint?.constant += verticalOffset
}
// Calculate the padding after the view has had a chance to perform its own custom layout changes via the delegate
// call to animatorWillLayout, animatorDidLayout
private func calculateSpringAnimationPadding() {
guard !disableAnimationPadding else {
springAnimationPadding = CGFloat(0)
springAnimationPaddingCalculated = true
return
}
// Tell the view to layout so that we may properly calculate the spring padding
view.layoutIfNeeded()
// Base the spring animation padding on an estimated height considering we need the spring animation padding itself
// to truly calculate the height of the view.
springAnimationPadding = (view.bounds.size.height / 120.0).rounded(.up) * 5
springAnimationPaddingCalculated = true
}
deinit {
removeObserver(self, forKeyPath: Constants.KVC.safeAreaInsets)
}
}
| 3c85a68da43e01c0565a749a5923e259 | 36.176991 | 119 | 0.723161 | false | false | false | false |
Wolox/ReactiveArray | refs/heads/master | ReactiveArrayTests/OperationSpec.swift | mit | 2 | //
// OperationSpec.swift
// ReactiveArray
//
// Created by Guido Marucci Blas on 7/2/15.
// Copyright (c) 2015 Wolox. All rights reserved.
//
import Quick
import Nimble
import ReactiveArray
import ReactiveCocoa
class OperationSpec: QuickSpec {
override func spec() {
var operation: Operation<Int>!
describe("#map") {
context("when the operation is an Append operation") {
beforeEach {
operation = Operation.Append(value: 10)
}
it("maps the value to be appended") {
let mappedOperation = operation.map { $0 * 2 }
let areEqual = mappedOperation == Operation.Append(value: 20)
expect(areEqual).to(beTrue())
}
}
context("when the operation is an Insert operation") {
beforeEach {
operation = Operation.Insert(value: 10, atIndex: 5)
}
it("maps the value to be inserted") {
let mappedOperation = operation.map { $0 * 2 }
let areEqual = mappedOperation == Operation.Insert(value: 20, atIndex: 5)
expect(areEqual).to(beTrue())
}
}
context("when the operation is an Update operation") {
beforeEach {
operation = Operation.Update(value: 10, atIndex: 5)
}
it("maps the value to be updated") {
let mappedOperation = operation.map { $0 * 2 }
let areEqual = mappedOperation == Operation.Update(value: 20, atIndex: 5)
expect(areEqual).to(beTrue())
}
}
context("when the operation is a Delete operation") {
beforeEach {
operation = Operation.RemoveElement(atIndex: 5)
}
it("does nothing") {
let mappedOperation = operation.map { $0 * 2 }
let areEqual = mappedOperation == operation
expect(areEqual).to(beTrue())
}
}
}
describe("#value") {
context("when the operation is an Append operation") {
beforeEach {
operation = Operation.Append(value: 10)
}
it("returns the appended value") {
expect(operation.value).to(equal(10))
}
}
context("when the operation is an Insert operation") {
beforeEach {
operation = Operation.Insert(value: 10, atIndex: 5)
}
it("returns the inserted value") {
expect(operation.value).to(equal(10))
}
}
context("when the operation is an Update operation") {
beforeEach {
operation = Operation.Update(value: 10, atIndex: 5)
}
it("returns the updated value") {
expect(operation.value).to(equal(10))
}
}
context("when the operation is an Remove operation") {
beforeEach {
operation = Operation.RemoveElement(atIndex: 5)
}
it("returns .None") {
expect(operation.value).to(beNil())
}
}
}
}
} | db51c31da5f6aadad7553a8c222ec39c | 29.376812 | 93 | 0.396803 | false | false | false | false |
CodaFi/swift | refs/heads/master | test/SILOptimizer/Inputs/cross-module.swift | apache-2.0 | 7 | import Submodule
private enum PE<T> {
case A
case B(T)
}
public struct Container {
private final class Base {
}
@inline(never)
public func testclass<T>(_ t: T) -> T {
var arr = Array<Base>()
arr.append(Base())
print(arr)
return t
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func testclass_gen<T>(_ t: T) -> T {
var arr = Array<Base>()
arr.append(Base())
print(arr)
return t
}
@inline(never)
public func testenum<T>(_ t: T) -> T {
var arr = Array<PE<T>>()
arr.append(.B(t))
print(arr)
return t
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func testenum_gen<T>(_ t: T) -> T {
var arr = Array<PE<T>>()
arr.append(.B(t))
print(arr)
return t
}
public init() { }
}
private class PrivateBase<T> {
var t: T
func foo() -> Int { return 27 }
init(_ t: T) { self.t = t }
}
private class PrivateDerived<T> : PrivateBase<T> {
override func foo() -> Int { return 28 }
}
@inline(never)
private func getClass<T>(_ t : T) -> PrivateBase<T> {
return PrivateDerived<T>(t)
}
@inline(never)
public func createClass<T>(_ t: T) -> Int {
return getClass(t).foo()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func createClass_gen<T>(_ t: T) -> Int {
return getClass(t).foo()
}
private struct PrivateError: Error { }
public func returnPrivateError<V>(_ v: V) -> Error {
return PrivateError()
}
struct InternalError: Error { }
public func returnInternalError<V>(_ v: V) -> Error {
return InternalError()
}
private protocol PrivateProtocol {
func foo() -> Int
}
open class OpenClass<T> {
public init() { }
@inline(never)
fileprivate func bar(_ t: T) {
print(t)
}
}
extension OpenClass {
@inline(never)
public func testit() -> Bool {
return self is PrivateProtocol
}
}
@inline(never)
public func checkIfClassConforms<T>(_ t: T) {
let x = OpenClass<T>()
print(x.testit())
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func checkIfClassConforms_gen<T>(_ t: T) {
let x = OpenClass<T>()
print(x.testit())
}
@inline(never)
public func callClassMethod<T>(_ t: T) {
let k = OpenClass<T>()
k.bar(t)
}
extension Int : PrivateProtocol {
func foo() -> Int { return self }
}
@inline(never)
@_semantics("optimize.no.crossmodule")
private func printFooExistential(_ p: PrivateProtocol) {
print(p.foo())
}
@inline(never)
private func printFooGeneric<T: PrivateProtocol>(_ p: T) {
print(p.foo())
}
@inline(never)
public func callFoo<T>(_ t: T) {
printFooExistential(123)
printFooGeneric(1234)
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callFoo_gen<T>(_ t: T) {
printFooExistential(123)
printFooGeneric(1234)
}
fileprivate protocol PrivateProto {
func foo()
}
public class FooClass: PrivateProto {
func foo() {
print(321)
}
}
final class Internalclass {
public var publicint: Int = 27
}
final public class Outercl {
var ic: Internalclass = Internalclass()
}
@inline(never)
public func classWithPublicProperty<T>(_ t: T) -> Int {
return createInternal().ic.publicint
}
@inline(never)
func createInternal() -> Outercl {
return Outercl()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
fileprivate func callProtocolFoo<T: PrivateProto>(_ t: T) {
t.foo()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callFooViaConformance<T>(_ t: T) {
let c = FooClass()
callProtocolFoo(c)
}
@inline(never)
public func callGenericSubmoduleFunc<T>(_ t: T) {
genericSubmoduleFunc(t)
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callGenericSubmoduleFunc_gen<T>(_ t: T) {
genericSubmoduleFunc(t)
}
@inline(never)
public func genericClosure<T>(_ t: T) -> T {
let c : () -> T = { return t }
return c()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func genericClosure_gen<T>(_ t: T) -> T {
let c : () -> T = { return t }
return c()
}
struct Abc {
var x: Int { return 27 }
var y: Int { return 28 }
}
class Myclass {
var x: Int { return 27 }
var y: Int { return 28 }
}
class Derived : Myclass {
override var x: Int { return 29 }
override var y: Int { return 30 }
}
@inline(never)
func getStructKeypath<T>(_ t: T) -> KeyPath<Abc, Int> {
return \Abc.x
}
@inline(never)
public func useStructKeypath<T>(_ t: T) -> Int {
let abc = Abc()
return abc[keyPath: getStructKeypath(t)]
}
@inline(never)
func getClassKeypath<T>(_ t: T) -> KeyPath<Myclass, Int> {
return \Myclass.x
}
@inline(never)
public func useClassKeypath<T>(_ t: T) -> Int {
let c = Derived()
return c[keyPath: getClassKeypath(t)]
}
@inline(never)
func unrelated<U>(_ u: U) {
print(u)
}
@inline(never)
public func callUnrelated<T>(_ t: T) -> T {
unrelated(43)
return t
}
public let globalLet = 529387
| 47235e37b2ef79ce37838bca57f61d90 | 17.388889 | 59 | 0.652165 | false | false | false | false |
BlinkOCR/blinkocr-ios | refs/heads/master | Samples/FieldByField-sample-Swift/FieldByField-sample-Swift/ViewController.swift | apache-2.0 | 2 | //
// ViewController.swift
// FieldByField-sample-Swift
//
// Created by Jura Skrlec on 10/05/2018.
// Copyright © 2018 Jura Skrlec. All rights reserved.
//
import UIKit
import BlinkInput
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func startScanTapped(_ sender: Any) {
// Create MBIFieldByFieldOverlaySettings
let settings = MBIFieldByFieldOverlaySettings(scanElements: MBGenericPreset.getPreset()!)
// Create field by field VC
let fieldByFieldVC = MBIFieldByFieldOverlayViewController(settings: settings, delegate: self)
// Create scanning VC
let recognizerRunnerViewController: (UIViewController & MBIRecognizerRunnerViewController)? = MBIViewControllerFactory.recognizerRunnerViewController(withOverlayViewController: fieldByFieldVC)
// Present VC
self.present(recognizerRunnerViewController!, animated: true, completion: nil)
}
}
extension ViewController : MBIFieldByFieldOverlayViewControllerDelegate {
func field(_ fieldByFieldOverlayViewController: MBIFieldByFieldOverlayViewController, didFinishScanningWith scanElements: [MBIScanElement]) {
fieldByFieldOverlayViewController.recognizerRunnerViewController?.pauseScanning()
var dict = [String: String]()
for element: MBIScanElement in scanElements {
if (element.scanned) {
dict[element.identifier] = element.value
}
}
var description : String = ""
for (key, value) in dict {
description += "\(key): \(value)\n"
}
let alert = UIAlertController(title: "Field by field Result", message: "\(description)", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
self.dismiss(animated: true, completion: nil)
}))
fieldByFieldOverlayViewController.present(alert, animated: true, completion: nil)
}
func field(byFieldOverlayViewControllerWillClose fieldByFieldOverlayViewController: MBIFieldByFieldOverlayViewController) {
self.dismiss(animated: true, completion: nil)
}
}
| d380d99faaa8f3c3d27c502cf99cfb5d | 35.485714 | 200 | 0.682067 | false | false | false | false |
cliqz-oss/browser-ios | refs/heads/development | Client/Cliqz/Frontend/Browser/Settings/LimitMobileDataUsageTableViewController.swift | mpl-2.0 | 2 | //
// LimitMobileDataUsageTableViewController.swift
// Client
//
// Created by Mahmoud Adam on 5/9/17.
// Copyright © 2017 Mozilla. All rights reserved.
//
import UIKit
class LimitMobileDataUsageTableViewController: SubSettingsTableViewController {
private let toggleTitles = [
NSLocalizedString("Limit Mobile Data Usage", tableName: "Cliqz", comment: "[Settings] Limit Mobile Data Usage")
]
private let sectionFooters = [
NSLocalizedString("Download videos on Wi-Fi Only", tableName: "Cliqz", comment: "[Settings -> Limit Mobile Data Usage] toogle footer")
]
private lazy var toggles: [Bool] = {
return [SettingsPrefs.shared.getLimitMobileDataUsagePref()]
}()
override func getSectionFooter(section: Int) -> String {
guard section < sectionFooters.count else {
return ""
}
return sectionFooters[section]
}
override func getViewName() -> String {
return "limit_mobile_data_usage"
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = getUITableViewCell()
cell.textLabel?.text = toggleTitles[indexPath.row]
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: #selector(switchValueChanged(_:)), for: UIControlEvents.valueChanged)
control.isOn = toggles[indexPath.row]
cell.accessoryView = control
cell.selectionStyle = .none
cell.isUserInteractionEnabled = true
cell.textLabel?.textColor = UIColor.black
control.isEnabled = true
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return super.tableView(tableView, heightForHeaderInSection: section)
}
@objc func switchValueChanged(_ toggle: UISwitch) {
self.toggles[toggle.tag] = toggle.isOn
saveToggles()
self.tableView.reloadData()
// log telemetry signal
let state = toggle.isOn == true ? "off" : "on" // we log old value
let valueChangedSignal = TelemetryLogEventType.Settings(getViewName(), "click", "enable", state, nil)
TelemetryLogger.sharedInstance.logEvent(valueChangedSignal)
}
private func saveToggles() {
SettingsPrefs.shared.updateLimitMobileDataUsagePref(self.toggles[0])
}
}
| 7a07e70b7950ce0f9b6aa8a6f21b63de | 33.325 | 142 | 0.658776 | false | false | false | false |
iOSDevLog/iOSDevLog | refs/heads/master | MyLocations/MyLocations/LocationsTableViewController.swift | mit | 1 | //
// LocationsTableViewController.swift
// MyLocations
//
// Created by iosdevlog on 16/2/17.
// Copyright © 2016年 iosdevlog. All rights reserved.
//
import UIKit
import CoreData
import CoreLocation
class LocationsTableViewController: UITableViewController {
// MARK: - property
var managedObjectContext: NSManagedObjectContext!
lazy var fetchedResultsController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest()
let entity = NSEntityDescription.entityForName("Location", inManagedObjectContext: self.managedObjectContext)
fetchRequest.entity = entity
let sortDescriptor1 = NSSortDescriptor(key: "category", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "date", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor1, sortDescriptor2]
fetchRequest.fetchBatchSize = 20
let fetchedResultsController = NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: self.managedObjectContext,
sectionNameKeyPath: "category",
cacheName: "Locations")
fetchedResultsController.delegate = self
return fetchedResultsController
}()
// MARK: - lifeCycle
override func viewDidLoad() {
super.viewDidLoad()
performFetch()
navigationItem.rightBarButtonItem = editButtonItem()
tableView.backgroundColor = UIColor.blackColor()
tableView.separatorColor = UIColor(white: 1.0, alpha: 0.2)
tableView.indicatorStyle = .White
}
deinit {
fetchedResultsController.delegate = nil
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count
}
override func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
let sectionInfo = fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionInfo = fetchedResultsController.sections![section]
return sectionInfo.name.uppercaseString
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("LocationCell", forIndexPath: indexPath) as! LocationCell
let location = fetchedResultsController.objectAtIndexPath(indexPath) as! Location
cell.configureForLocation(location)
return cell
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let location = fetchedResultsController.objectAtIndexPath(indexPath) as! Location
location.removePhotoFile()
managedObjectContext.deleteObject(location)
do {
try managedObjectContext.save()
} catch {
fatalCoreDataError(error)
}
}
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let labelRect = CGRect(x: 15, y: tableView.sectionHeaderHeight - 14, width: 300, height: 14)
let label = UILabel(frame: labelRect)
label.font = UIFont.boldSystemFontOfSize(11)
label.text = tableView.dataSource!.tableView!(tableView, titleForHeaderInSection: section)
label.textColor = UIColor(white: 1.0, alpha: 0.4)
label.backgroundColor = UIColor.clearColor()
let separatorRect = CGRect(x: 15, y: tableView.sectionHeaderHeight - 0.5, width: tableView.bounds.size.width - 15, height: 0.5)
let separator = UIView(frame: separatorRect)
separator.backgroundColor = tableView.separatorColor
let viewRect = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.sectionHeaderHeight)
let view = UIView(frame: viewRect)
view.backgroundColor = UIColor(white: 0, alpha: 0.85)
view.addSubview(label)
view.addSubview(separator)
return view
}
// MARK: - prepareForSegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditLocation" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! LocationDetailsViewController
controller.managedObjectContext = managedObjectContext
if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell) {
let location = fetchedResultsController.objectAtIndexPath(indexPath) as! Location
controller.locationToEdit = location
}
}
}
// MARK: - Helper
func performFetch() {
do {
try fetchedResultsController.performFetch()
} catch {
fatalCoreDataError(error)
}
}
}
extension LocationsTableViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(controller: NSFetchedResultsController) {
print("*** controllerWillChangeContent")
tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
print("*** NSFetchedResultsChangeInsert (object)")
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
print("*** NSFetchedResultsChangeDelete (object)")
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
print("*** NSFetchedResultsChangeUpdate (object)")
if let cell = tableView.cellForRowAtIndexPath(indexPath!) as? LocationCell {
let location = controller.objectAtIndexPath(indexPath!) as! Location
cell.configureForLocation(location)
}
case .Move:
print("*** NSFetchedResultsChangeMove (object)")
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
}
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
print("*** NSFetchedResultsChangeInsert (section)")
tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
print("*** NSFetchedResultsChangeDelete (section)")
tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Update:
print("*** NSFetchedResultsChangeUpdate (section)")
case .Move:
print("*** NSFetchedResultsChangeMove (section)")
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
print("*** controllerDidChangeContent")
tableView.endUpdates()
}
} | b431a8ef2225d44e03f805ced9948124 | 39.376289 | 211 | 0.665858 | false | false | false | false |
Coderian/SwiftedKML | refs/heads/master | SwiftedKML/Elements/ViewVolume.swift | mit | 1 | //
// ViewVolume.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML ViewVolume
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="ViewVolume" type="kml:ViewVolumeType" substitutionGroup="kml:AbstractObjectGroup"/>
public class ViewVolume :SPXMLElement, AbstractObjectGroup ,HasXMLElementValue {
public static var elementName: String = "ViewVolume"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as PhotoOverlay: v.value.viewVolume = self
default: break
}
}
}
}
public var value : ViewVolumeType
public required init(attributes:[String:String]){
self.value = ViewVolumeType(attributes: attributes)
super.init(attributes: attributes)
}
public var abstractObject : AbstractObjectType { return self.value }
}
/// KML ViewVolumeType
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <complexType name="ViewVolumeType" final="#all">
/// <complexContent>
/// <extension base="kml:AbstractObjectType">
/// <sequence>
/// <element ref="kml:leftFov" minOccurs="0"/>
/// <element ref="kml:rightFov" minOccurs="0"/>
/// <element ref="kml:bottomFov" minOccurs="0"/>
/// <element ref="kml:topFov" minOccurs="0"/>
/// <element ref="kml:near" minOccurs="0"/>
/// <element ref="kml:ViewVolumeSimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/>
/// <element ref="kml:ViewVolumeObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/>
/// </sequence>
/// </extension>
/// </complexContent>
/// </complexType>
/// <element name="ViewVolumeSimpleExtensionGroup" abstract="true" type="anySimpleType"/>
/// <element name="ViewVolumeObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/>
public class ViewVolumeType: AbstractObjectType {
public var leftFov: LeftFov! // = 0.0
public var rightFov: RightFov! // = 0.0
public var bottomFov: BottomFov! // = 0.0
public var topFov: TopFov! // = 0.0
public var near: Near! // = 0.0
public var viewVolumeSimpleExtensionGroup: [AnyObject] = []
public var viewVolumeObjectExtensionGroup: [AbstractObjectGroup] = []
}
| 853540d89f2e673f07443fa49480042c | 37.848485 | 116 | 0.650936 | false | false | false | false |
lioonline/Swift | refs/heads/master | MapKit iPad/MapKit iPad/ViewController.swift | gpl-3.0 | 1 | //
// ViewController.swift
// MapKit iPad
//
// Created by Carlos Butron on 02/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var latitude: UILabel!
@IBOutlet weak var longitude: UILabel!
@IBOutlet weak var myMap: MKMapView!
var set = NSMutableArray()
@IBAction func createAnotation(sender: AnyObject) {
var a = MyAnotation(c: myMap.centerCoordinate, t: "Center", st: "The map center")
mapView(myMap, viewForAnnotation: a)
myMap.addAnnotation(a)
set.addObject(a)
}
@IBAction func deleteAnotation(sender: AnyObject) {
for (var i=0; i<myMap.annotations.count; i++) {
myMap.removeAnnotations(set)
}
}
@IBAction func coordinates(sender: AnyObject) {
latitude.text = "\(myMap.centerCoordinate.latitude)"
longitude.text = "\(myMap.centerCoordinate.longitude)"
}
override func viewDidLoad() {
super.viewDidLoad()
self.myMap.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation:
MKAnnotation!) -> MKAnnotationView!{
var pinView:MKPinAnnotationView = MKPinAnnotationView(annotation:
annotation, reuseIdentifier: "Custom")
//purple color to anotation
//pinView.pinColor = MKPinAnnotationColor.Purple
pinView.image = UIImage(named:"mypin.png")
return pinView
}
}
| 02d09dea6c2db8ae05d03ffb06347684 | 26.989247 | 121 | 0.627737 | false | false | false | false |
AnRanScheme/magiGlobe | refs/heads/master | magi/magiGlobe/magiGlobe/Classes/Tool/Extension/UIKit/UIApplication/UIApplication+Man.swift | mit | 1 | //
// UIApplication+Man.swift
// swift-magic
//
// Created by 安然 on 17/2/15.
// Copyright © 2017年 安然. All rights reserved.
//
import UIKit
public extension UIApplication{
public var m_applicationFileSize: String {
func sizeOfFolderPath(_ folderPath: String) -> Int64 {
let contents: [String]?
do {
contents = try FileManager.default.contentsOfDirectory(atPath: folderPath)
} catch _ {
contents = nil
}
var folderSize: Int64 = 0
if let tempContents = contents{
for file in tempContents {
let dict = try? FileManager.default.attributesOfItem(atPath: (folderPath as NSString).appendingPathComponent(file))
if dict != nil {
folderSize += (dict![FileAttributeKey.size] as? Int64) ?? 0
}
}
}
return folderSize
}
let docSize = sizeOfFolderPath(self.m_documentPath)
let libSzie = sizeOfFolderPath(self.m_libraryPath)
let cacheSize = sizeOfFolderPath(self.m_cachePath)
let total = docSize + libSzie + cacheSize + cacheSize
let folderSizeStr = ByteCountFormatter.string(fromByteCount: total, countStyle: .file)
return folderSizeStr
}
public var m_documentPath: String {
let dstPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
return dstPath
}
public var m_libraryPath: String {
let dstPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first!
return dstPath
}
public var m_cachePath: String {
let dstPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
return dstPath
}
}
/*
- (NSString *)ez_applicationFileSize{
unsigned long long docSize = [self __ez_sizeOfFolder:[self __ez_documentPath]];
unsigned long long libSize = [self __ez_sizeOfFolder:[self __ez_libraryPath]];
unsigned long long cacheSize = [self __ez_sizeOfFolder:[self __ez_cachePath]];
unsigned long long total = docSize + libSize + cacheSize;
NSString *folderSizeStr = [NSByteCountFormatter stringFromByteCount:total countStyle:NSByteCountFormatterCountStyleFile];
return folderSizeStr;
}
-(unsigned long long)__ez_sizeOfFolder:(NSString *)folderPath
{
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:nil];
NSEnumerator *contentsEnumurator = [contents objectEnumerator];
NSString *file;
unsigned long long folderSize = 0;
while (file = [contentsEnumurator nextObject]) {
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[folderPath stringByAppendingPathComponent:file] error:nil];
folderSize += [[fileAttributes objectForKey:NSFileSize] intValue];
}
return folderSize;
}
*/
| a22b96bda51bcc38821bc1f5949b24d9 | 31.666667 | 147 | 0.654707 | false | false | false | false |
iceman201/NZAirQuality | refs/heads/master | Classes/Plots/DotPlot.swift | mit | 4 |
import UIKit
open class DotPlot : Plot {
// Customisation
// #############
/// The shape to draw for each data point.
open var dataPointType = ScrollableGraphViewDataPointType.circle
/// The size of the shape to draw for each data point.
open var dataPointSize: CGFloat = 5
/// The colour with which to fill the shape.
open var dataPointFillColor: UIColor = UIColor.black
/// If dataPointType is set to .Custom then you,can provide a closure to create any kind of shape you would like to be displayed instead of just a circle or square. The closure takes a CGPoint which is the centre of the shape and it should return a complete UIBezierPath.
open var customDataPointPath: ((_ centre: CGPoint) -> UIBezierPath)?
// Private State
// #############
private var dataPointLayer: DotDrawingLayer?
public init(identifier: String) {
super.init()
self.identifier = identifier
}
override func layers(forViewport viewport: CGRect) -> [ScrollableGraphViewDrawingLayer?] {
createLayers(viewport: viewport)
return [dataPointLayer]
}
private func createLayers(viewport: CGRect) {
dataPointLayer = DotDrawingLayer(
frame: viewport,
fillColor: dataPointFillColor,
dataPointType: dataPointType,
dataPointSize: dataPointSize,
customDataPointPath: customDataPointPath)
dataPointLayer?.owner = self
}
}
@objc public enum ScrollableGraphViewDataPointType : Int {
case circle
case square
case custom
}
| 4add75844111c2ace56b6bf5842371a7 | 31.959184 | 275 | 0.663158 | false | false | false | false |
finder39/Swimgur | refs/heads/master | SWNetworking/Comment.swift | mit | 1 | //
// Comment.swift
// Swimgur
//
// Created by Joseph Neuman on 11/2/14.
// Copyright (c) 2014 Joseph Neuman. All rights reserved.
//
import Foundation
public class Comment {
public var id: Int!
public var imageID: String?
public var comment: String?
public var author: String?
public var authorID: String?
public var onAlbum: Bool?
public var albumCover: String?
public var ups: Int?
public var downs: Int?
public var points: Int?
public var datetime: Int = 0
public var parentID: String?
public var deleted: Bool?
public var vote: String?
public var children: [Comment] = []
// expansion management in table
public var expanded = false
public var depth = 0
public init(dictionary:Dictionary<String, AnyObject>, depth theDepth:Int) {
id = dictionary["id"] as AnyObject! as Int!
imageID = dictionary["image_id"] as AnyObject? as? String
comment = dictionary["comment"] as AnyObject? as? String
author = dictionary["author"] as AnyObject? as? String
authorID = dictionary["author_id"] as AnyObject? as? String
onAlbum = dictionary["on_album"] as AnyObject? as? Bool
albumCover = dictionary["album_cover"] as AnyObject? as? String
ups = dictionary["ups"] as AnyObject? as? Int
downs = dictionary["downs"] as AnyObject? as? Int
points = dictionary["points"] as AnyObject? as? Int
datetime = dictionary["datetime"] as AnyObject! as Int!
parentID = dictionary["parent_id"] as AnyObject? as? String
deleted = dictionary["deleted"] as AnyObject? as? Bool
vote = dictionary["vote"] as AnyObject? as? String
depth = theDepth
if let children = (dictionary["children"] as AnyObject?) as? [Dictionary<String, AnyObject>] {
for child in children {
self.children.append(Comment(dictionary: child, depth:depth+1))
}
}
}
public convenience init(dictionary:Dictionary<String, AnyObject>) {
self.init(dictionary: dictionary, depth:0)
}
} | efa9fb59ed2a84fdfc0f69a216b63706 | 32.033333 | 98 | 0.684503 | false | false | false | false |
PimCoumans/Foil | refs/heads/master | Foil/Animation/AnimationCurve.swift | mit | 2 | //
// Interpolatable.swift
// Foil
//
// Created by Pim Coumans on 25/01/17.
// Copyright © 2017 pixelrock. All rights reserved.
//
import CoreGraphics
protocol Lerpable: Equatable {
mutating func lerp(to: Self, t: Double)
func lerped(to: Self, t: Double) -> Self
static func + (lhs: Self, rhs: Self) -> Self
}
extension Lerpable {
func lerped(to: Self, t: Double) -> Self {
var value = self
value.lerp(to: to, t: t)
return value
}
}
extension CGFloat: Lerpable {
mutating internal func lerp(to: CGFloat, t: Double) {
self += (to - self) * CGFloat(t)
}
}
protocol AnimationCurve {
func value(for progress: Double) -> Double
}
struct Linear: AnimationCurve {
func value(for progress: Double) -> Double {
return progress
}
}
struct EaseIn: AnimationCurve {
func value(for progress: Double) -> Double {
return progress * progress
}
}
struct EaseOut: AnimationCurve {
func value(for progress: Double) -> Double {
return -(progress * (progress - 2));
}
}
struct ElasticIn: AnimationCurve {
func value(for p: Double) -> Double {
return sin(13 * (Double.pi / 2) * p) * pow(2, 10 * (p - 1));
}
}
struct ElasticOut: AnimationCurve {
func value(for p: Double) -> Double {
return sin(-13 * (Double.pi / 2) * (p + 1)) * pow(2, -10 * p) + 1;
}
}
struct Spring: AnimationCurve {
var damping: Double
var mass: Double
var stiffness: Double
var velocity: Double = 0
func value(for progress: Double) -> Double {
if damping <= 0.0 || stiffness <= 0.0 || mass <= 0.0 {
fatalError("Incorrect animation values")
}
let beta = damping / (2 * mass)
let omega0 = sqrt(stiffness / mass)
let omega1 = sqrt((omega0 * omega0) - (beta * beta))
let omega2 = sqrt((beta * beta) - (omega0 * omega0))
let x0: Double = -1
let oscillation: (Double) -> Double
if beta < omega0 {
// Underdamped
oscillation = {t in
let envelope = exp(-beta * t)
let part2 = x0 * cos(omega1 * t)
let part3 = ((beta * x0 + self.velocity) / omega1) * sin(omega1 * t)
return -x0 + envelope * (part2 + part3)
}
} else if beta == omega0 {
// Critically damped
oscillation = {t in
let envelope = exp(-beta * t)
return -x0 + envelope * (x0 + (beta * x0 + self.velocity) * t)
}
} else {
// Overdamped
oscillation = {t in
let envelope = exp(-beta * t)
let part2 = x0 * cosh(omega2 * t)
let part3 = ((beta * x0 + self.velocity) / omega2) * sinh(omega2 * t)
return -x0 + envelope * (part2 + part3)
}
}
return oscillation(progress)
}
}
| d35b3d227651170b91e140453236c647 | 25.60177 | 85 | 0.52495 | false | false | false | false |
IAskWind/IAWExtensionTool | refs/heads/master | IAWExtensionTool/IAWExtensionTool/Classes/RatingBar/RatingBar.swift | mit | 1 | //
// RatingBar.swift
// Stareal
//
// Created by Nino on 16/9/1.
// Copyright © 2016年 mirroon. All rights reserved.
//
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
public protocol RatingBarDelegate {
func ratingChanged(_ ratingBar:RatingBar,newRating:Float)
}
open class RatingBar: UIView {
var delegate:RatingBarDelegate?
open var starRating:Float?
open var lastRating:Float?
var starWidth:CGFloat?
var starHeight:CGFloat?
var unSelectedImage:UIImage?
var halfSelectedImage:UIImage?
var fullSelectedImage:UIImage?
var s1:UIImageView?
var s2:UIImageView?
var s3:UIImageView?
var s4:UIImageView?
var s5:UIImageView?
//是否是指示器 默认 true,表示用来显示,不用来打分
open var isIndicator:Bool = true
//默认支持半颗星
open var supportHalfStar:Bool = true
/**设置星星显示状态
deselectedName 满星图片名
halfSelectedName 半星图片名
fullSelectedName 空星图片名
starSideLength 星星边长
*/
open func setSeletedState(_ deselectedName:String?,halfSelectedName:String?,fullSelectedName:String?,starSideLength:CGFloat, delegate:RatingBarDelegate){
self.delegate = delegate
unSelectedImage = UIImage(named: deselectedName!)
fullSelectedImage = UIImage(named: fullSelectedName!)
halfSelectedImage = halfSelectedName == nil ? fullSelectedImage:UIImage(named: halfSelectedName!)
starWidth = 0
starHeight = 0
if (starHeight < starSideLength) {
starHeight = starSideLength
}
if (starWidth < starSideLength) {
starWidth = starSideLength
}
//控件宽度适配
var frame = self.frame
var viewWidth:CGFloat = starWidth! * 5
if (frame.size.width) > viewWidth {
viewWidth = frame.size.width
}
frame.size.width = viewWidth
self.frame = frame
starRating = 0
lastRating = 0
s1 = UIImageView(image: unSelectedImage)
s2 = UIImageView(image: unSelectedImage)
s3 = UIImageView(image: unSelectedImage)
s4 = UIImageView(image: unSelectedImage)
s5 = UIImageView(image: unSelectedImage)
//星星间距
let space:CGFloat = (viewWidth - starWidth!*5)/6
var starX = space
let starY = (frame.height - starHeight!)/2
s1?.frame = CGRect(x: starX, y: starY, width: starWidth!, height: starHeight!)
starX = starX + starWidth! + space
s2?.frame = CGRect(x: starX, y: starY, width: starWidth!, height: starHeight!)
starX = starX + starWidth! + space
s3?.frame = CGRect(x: starX, y: starY, width: starWidth!, height: starHeight!)
starX = starX + starWidth! + space
s4?.frame = CGRect(x: starX, y: starY, width: starWidth!, height: starHeight!)
starX = starX + starWidth! + space
s5?.frame = CGRect(x: starX, y: starY, width: starWidth!, height: starHeight!)
starX = starX + starWidth! + space
s1?.isUserInteractionEnabled = false
s2?.isUserInteractionEnabled = false
s3?.isUserInteractionEnabled = false
s4?.isUserInteractionEnabled = false
s5?.isUserInteractionEnabled = false
self.addSubview(s1!)
self.addSubview(s2!)
self.addSubview(s3!)
self.addSubview(s4!)
self.addSubview(s5!)
}
//设置评分值
open func displayRating(_ rating:Float){
s1?.image = unSelectedImage
s2?.image = unSelectedImage
s3?.image = unSelectedImage
s4?.image = unSelectedImage
s5?.image = unSelectedImage
if (rating >= 1) {
s1?.image = halfSelectedImage
}
if (rating >= 2) {
s1?.image = fullSelectedImage
}
if (rating >= 3) {
s2?.image = halfSelectedImage
}
if (rating >= 4) {
s2?.image = fullSelectedImage
}
if (rating >= 5) {
s3?.image = halfSelectedImage
}
if (rating >= 6) {
s3?.image = fullSelectedImage
}
if (rating >= 7) {
s4?.image = halfSelectedImage
}
if (rating >= 8) {
s4?.image = fullSelectedImage
}
if (rating >= 9) {
s5?.image = halfSelectedImage
}
if (rating >= 10) {
s5?.image = fullSelectedImage
}
starRating = rating
lastRating = rating
delegate?.ratingChanged(self, newRating: rating)
}
open func rating() -> Float{
return starRating!
}
//手势
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
self.touchesRating(touches as NSSet)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
self.touchesRating(touches as NSSet)
}
//触发
open func touchesRating(_ touches:NSSet){
if(self.isIndicator == true){
return
}
let point:CGPoint = (touches.anyObject()! as AnyObject).location(in: self)
let space:CGFloat = (self.frame.size.width - starWidth!*5)/6
//这里为10分制 可根据逻辑改为五分制
var newRating:Float = 0
if (point.x >= 0 && point.x <= self.frame.size.width) {
if (point.x <= space+starWidth!*0.5) {
if supportHalfStar{
newRating = 1;
}else{
newRating = 2;
}
}else if (point.x < space*2+starWidth!){
newRating = 2;
}else if (point.x < space*2+starWidth!*1.5){
if supportHalfStar{
newRating = 3;
}else{
newRating = 4;
}
}else if (point.x <= 3*space+2*starWidth!){
newRating = 4;
}else if (point.x <= 3*space+2.5*starWidth!){
if supportHalfStar{
newRating = 5;
}else{
newRating = 6;
}
}else if (point.x <= 4*space+3*starWidth!){
newRating = 6;
}else if (point.x <= 4*space+3.5*starWidth!){
if supportHalfStar{
newRating = 7;
}else{
newRating = 8;
}
}else if (point.x <= 5*space+4*starWidth!){
newRating = 8;
}else if (point.x <= 5*space+4.5*starWidth!){
if supportHalfStar{
newRating = 9;
}else{
newRating = 10;
}
}else {
newRating = 10;
}
}
if (newRating != lastRating){
self.displayRating(newRating)
}
}
}
| aa0b60d8af3c3eda1fda4e256c3c2f6b | 28.703252 | 157 | 0.538251 | false | false | false | false |
sschiau/swift | refs/heads/master | test/Generics/function_defs.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift
//===----------------------------------------------------------------------===//
// Type-check function definitions
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Basic type checking
//===----------------------------------------------------------------------===//
protocol EqualComparable {
func isEqual(_ other: Self) -> Bool
}
func doCompare<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) -> Bool {
var b1 = t1.isEqual(t2)
if b1 {
return true
}
return t1.isEqual(u) // expected-error {{cannot convert value of type 'U' to expected argument type 'T'}}
}
protocol MethodLessComparable {
func isLess(_ other: Self) -> Bool
}
func min<T : MethodLessComparable>(_ x: T, y: T) -> T {
if (y.isLess(x)) { return y }
return x
}
//===----------------------------------------------------------------------===//
// Interaction with existential types
//===----------------------------------------------------------------------===//
func existential<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) {
var eqComp : EqualComparable = t1 // expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}}
eqComp = u
if t1.isEqual(eqComp) {} // expected-error{{cannot convert value of type 'EqualComparable' to expected argument type 'T'}}
if eqComp.isEqual(t2) {} // expected-error{{member 'isEqual' cannot be used on value of protocol type 'EqualComparable'; use a generic constraint instead}}
}
protocol OtherEqualComparable {
func isEqual(_ other: Self) -> Bool
}
func otherExistential<T : EqualComparable>(_ t1: T) {
var otherEqComp : OtherEqualComparable = t1 // expected-error{{value of type 'T' does not conform to specified type 'OtherEqualComparable'}}
otherEqComp = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}}
_ = otherEqComp
var otherEqComp2 : OtherEqualComparable // expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}}
otherEqComp2 = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}}
_ = otherEqComp2
_ = t1 as EqualComparable & OtherEqualComparable // expected-error{{'T' is not convertible to 'EqualComparable & OtherEqualComparable'; did you mean to use 'as!' to force downcast?}} {{10-12=as!}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}}
}
protocol Runcible {
func runce<A>(_ x: A)
func spoon(_ x: Self)
}
func testRuncible(_ x: Runcible) { // expected-error{{protocol 'Runcible' can only be used as a generic constraint}}
x.runce(5)
}
//===----------------------------------------------------------------------===//
// Overloading
//===----------------------------------------------------------------------===//
protocol Overload {
associatedtype A
associatedtype B
func getA() -> A
func getB() -> B
func f1(_: A) -> A // expected-note {{candidate expects value of type 'OtherOvl.A' at position #0}}
func f1(_: B) -> B // expected-note {{candidate expects value of type 'OtherOvl.B' at position #0}}
func f2(_: Int) -> A // expected-note{{found this candidate}}
func f2(_: Int) -> B // expected-note{{found this candidate}}
func f3(_: Int) -> Int // expected-note {{found this candidate}}
func f3(_: Float) -> Float // expected-note {{found this candidate}}
func f3(_: Self) -> Self // expected-note {{found this candidate}}
var prop : Self { get }
}
func testOverload<Ovl : Overload, OtherOvl : Overload>(_ ovl: Ovl, ovl2: Ovl,
other: OtherOvl) {
var a = ovl.getA()
var b = ovl.getB()
// Overloading based on arguments
_ = ovl.f1(a)
a = ovl.f1(a)
_ = ovl.f1(b)
b = ovl.f1(b)
// Overloading based on return type
a = ovl.f2(17)
b = ovl.f2(17)
ovl.f2(17) // expected-error{{ambiguous use of 'f2'}}
// Check associated types from different objects/different types.
a = ovl2.f2(17)
a = ovl2.f1(a)
other.f1(a) // expected-error{{no exact matches in call to instance method 'f1'}}
// Overloading based on context
var f3i : (Int) -> Int = ovl.f3
var f3f : (Float) -> Float = ovl.f3
var f3ovl_1 : (Ovl) -> Ovl = ovl.f3
var f3ovl_2 : (Ovl) -> Ovl = ovl2.f3
var f3ovl_3 : (Ovl) -> Ovl = other.f3 // expected-error{{ambiguous reference to member 'f3'}}
var f3i_unbound : (Ovl) -> (Int) -> Int = Ovl.f3
var f3f_unbound : (Ovl) -> (Float) -> Float = Ovl.f3
var f3f_unbound2 : (OtherOvl) -> (Float) -> Float = OtherOvl.f3
var f3ovl_unbound_1 : (Ovl) -> (Ovl) -> Ovl = Ovl.f3
var f3ovl_unbound_2 : (OtherOvl) -> (OtherOvl) -> OtherOvl = OtherOvl.f3
}
//===----------------------------------------------------------------------===//
// Subscripting
//===----------------------------------------------------------------------===//
protocol Subscriptable {
associatedtype Index
associatedtype Value
func getIndex() -> Index
func getValue() -> Value
subscript (index : Index) -> Value { get set }
}
protocol IntSubscriptable {
associatedtype ElementType
func getElement() -> ElementType
subscript (index : Int) -> ElementType { get }
}
func subscripting<T : Subscriptable & IntSubscriptable>(_ t: T) {
var index = t.getIndex()
var value = t.getValue()
var element = t.getElement()
value = t[index]
t[index] = value // expected-error{{cannot assign through subscript: 't' is a 'let' constant}}
element = t[17]
t[42] = element // expected-error{{cannot assign through subscript: subscript is get-only}}
// Suggests the Int form because we prefer concrete matches to generic matches in diagnosis.
t[value] = 17 // expected-error{{cannot convert value of type 'T.Value' to expected argument type 'Int'}}
}
//===----------------------------------------------------------------------===//
// Static functions
//===----------------------------------------------------------------------===//
protocol StaticEq {
static func isEqual(_ x: Self, y: Self) -> Bool
}
func staticEqCheck<T : StaticEq, U : StaticEq>(_ t: T, u: U) {
if t.isEqual(t, t) { return } // expected-error{{static member 'isEqual' cannot be used on instance of type 'T'}} // expected-error {{missing argument label 'y:' in call}}
if T.isEqual(t, y: t) { return }
if U.isEqual(u, y: u) { return }
T.isEqual(t, y: u) // expected-error{{cannot convert value of type 'U' to expected argument type 'T'}}
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
protocol Ordered {
static func <(lhs: Self, rhs: Self) -> Bool
}
func testOrdered<T : Ordered>(_ x: T, y: Int) {
if y < 100 || 500 < y { return }
if x < x { return }
}
//===----------------------------------------------------------------------===//
// Requires clauses
//===----------------------------------------------------------------------===//
func conformanceViaRequires<T>(_ t1: T, t2: T) -> Bool
where T : EqualComparable, T : MethodLessComparable {
let b1 = t1.isEqual(t2)
if b1 || t1.isLess(t2) {
return true
}
}
protocol GeneratesAnElement {
associatedtype Element : EqualComparable
func makeIterator() -> Element
}
protocol AcceptsAnElement {
associatedtype Element : MethodLessComparable
func accept(_ e : Element)
}
func impliedSameType<T : GeneratesAnElement>(_ t: T)
where T : AcceptsAnElement {
t.accept(t.makeIterator())
let e = t.makeIterator(), e2 = t.makeIterator()
if e.isEqual(e2) || e.isLess(e2) {
return
}
}
protocol GeneratesAssoc1 {
associatedtype Assoc1 : EqualComparable
func get() -> Assoc1
}
protocol GeneratesAssoc2 {
associatedtype Assoc2 : MethodLessComparable
func get() -> Assoc2
}
func simpleSameType<T : GeneratesAssoc1, U : GeneratesAssoc2>
(_ t: T, u: U) -> Bool
where T.Assoc1 == U.Assoc2 {
return t.get().isEqual(u.get()) || u.get().isLess(t.get())
}
protocol GeneratesMetaAssoc1 {
associatedtype MetaAssoc1 : GeneratesAnElement
func get() -> MetaAssoc1
}
protocol GeneratesMetaAssoc2 {
associatedtype MetaAssoc2 : AcceptsAnElement
func get() -> MetaAssoc2
}
func recursiveSameType
<T : GeneratesMetaAssoc1, U : GeneratesMetaAssoc2, V : GeneratesAssoc1>
(_ t: T, u: U, v: V)
where T.MetaAssoc1 == V.Assoc1, V.Assoc1 == U.MetaAssoc2
{
t.get().accept(t.get().makeIterator())
let e = t.get().makeIterator(), e2 = t.get().makeIterator()
if e.isEqual(e2) || e.isLess(e2) {
return
}
}
// <rdar://problem/13985164>
protocol P1 {
associatedtype Element
}
protocol P2 {
associatedtype AssocP1 : P1
func getAssocP1() -> AssocP1
}
func beginsWith2<E0: P1, E1: P1>(_ e0: E0, _ e1: E1) -> Bool
where E0.Element == E1.Element,
E0.Element : EqualComparable
{
}
func beginsWith3<S0: P2, S1: P2>(_ seq1: S0, _ seq2: S1) -> Bool
where S0.AssocP1.Element == S1.AssocP1.Element,
S1.AssocP1.Element : EqualComparable {
return beginsWith2(seq1.getAssocP1(), seq2.getAssocP1())
}
// FIXME: Test same-type constraints that try to equate things we
// don't want to equate, e.g., T == U.
//===----------------------------------------------------------------------===//
// Bogus requirements
//===----------------------------------------------------------------------===//
func nonTypeReq<T>(_: T) where T : Wibble {} // expected-error{{use of undeclared type 'Wibble'}}
func badProtocolReq<T>(_: T) where T : Int {} // expected-error{{type 'T' constrained to non-protocol, non-class type 'Int'}}
func nonTypeSameType<T>(_: T) where T == Wibble {} // expected-error{{use of undeclared type 'Wibble'}}
func nonTypeSameType2<T>(_: T) where Wibble == T {} // expected-error{{use of undeclared type 'Wibble'}}
func sameTypeEq<T>(_: T) where T = T {} // expected-error{{use '==' for same-type requirements rather than '='}} {{34-35===}}
// expected-warning@-1{{redundant same-type constraint 'T' == 'T'}}
func badTypeConformance1<T>(_: T) where Int : EqualComparable {} // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}}
func badTypeConformance2<T>(_: T) where T.Blarg : EqualComparable { } // expected-error{{'Blarg' is not a member type of 'T'}}
func badTypeConformance3<T>(_: T) where (T) -> () : EqualComparable { }
// expected-error@-1{{type '(T) -> ()' in conformance requirement does not refer to a generic parameter or associated type}}
func badTypeConformance4<T>(_: T) where @escaping (inout T) throws -> () : EqualComparable { }
// expected-error@-1{{type '(inout T) throws -> ()' in conformance requirement does not refer to a generic parameter or associated type}}
// expected-error@-2 2 {{@escaping attribute may only be used in function parameter position}}
// FIXME: Error emitted twice.
func badTypeConformance5<T>(_: T) where T & Sequence : EqualComparable { }
// expected-error@-1 2 {{non-protocol, non-class type 'T' cannot be used within a protocol-constrained type}}
// expected-error@-2{{type 'Sequence' in conformance requirement does not refer to a generic parameter or associated type}}
func badTypeConformance6<T>(_: T) where [T] : Collection { }
// expected-error@-1{{type '[T]' in conformance requirement does not refer to a generic parameter or associated type}}
func badTypeConformance7<T, U>(_: T, _: U) where T? : U { }
// expected-error@-1{{type 'T?' constrained to non-protocol, non-class type 'U'}}
func badSameType<T, U : GeneratesAnElement, V>(_ : T, _ : U)
where T == U.Element, U.Element == V {} // expected-error{{same-type requirement makes generic parameters 'T' and 'V' equivalent}}
| 5e25f5c5b622a49aef6332dc0a601585 | 36.847619 | 375 | 0.59386 | false | false | false | false |
JohnEstropia/Animo | refs/heads/master | AnimoDemo/AnimoDemo/ViewController.swift | mit | 2 | //
// ViewController.swift
// AnimoDemo
//
// Copyright © 2016 eureka, Inc.
//
// 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 Animo
// MARK: - ViewController
final class ViewController: UIViewController {
// MARK: UIViewController
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.startSqureView1()
self.startSquareView2()
let fromPoint = CGPoint(x: 0, y: 0)
let toPoint = CGPoint(x: 20, y: 20)
let fromColor = UIColor.red
let toColor = UIColor.blue
let someView = UIView()
let positionAnimation = CABasicAnimation(keyPath: "position")
positionAnimation.duration = 1
positionAnimation.fromValue = NSValue(cgPoint: fromPoint)
positionAnimation.toValue = NSValue(cgPoint: toPoint)
let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
colorAnimation.duration = 1
colorAnimation.fromValue = fromColor.cgColor
colorAnimation.toValue = toColor.cgColor
let animationGroup = CAAnimationGroup()
animationGroup.animations = [positionAnimation, colorAnimation]
animationGroup.fillMode = kCAFillModeForwards
animationGroup.isRemovedOnCompletion = false
animationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
someView.layer.add(animationGroup, forKey: "animationGroup")
_ = someView.layer.runAnimation(
Animo.group(
Animo.move(from: fromPoint, to: toPoint, duration: 1),
Animo.keyPath("backgroundColor", from: fromColor, to: toColor, duration: 1),
timingMode: .easeInOut,
options: Options(fillMode: .forwards)
)
)
}
// MARK: Private
@IBOutlet private dynamic weak var squareView1: UIView?
@IBOutlet private dynamic weak var squareView2: UIView?
private func startSqureView1() {
_ = self.squareView1?.layer.runAnimation(
Animo.replayForever(
Animo.group(
Animo.autoreverse(
Animo.rotateDegrees(
by: 360,
duration: 1.5,
timingMode: .easeInOutSine
)
),
Animo.sequence(
Animo.wait(1),
Animo.autoreverse(
Animo.move(
to: CGPoint(x: 200, y: 100),
duration: 1,
timingMode: .easeInOutSine
)
)
),
Animo.autoreverse(
Animo.keyPath(
"cornerRadius",
to: self.squareView1?.layer.bounds.width ?? 0,
duration: 1.5,
timingMode: .easeInOutSine
)
),
Animo.autoreverse(
Animo.keyPath(
"borderWidth",
to: 2,
duration: 1.5
)
),
Animo.sequence(
Animo.keyPath(
"backgroundColor",
from: UIColor.red,
to: UIColor.blue,
duration: 1,
timingMode: .easeInOut
),
Animo.keyPath(
"backgroundColor",
to: UIColor.yellow,
duration: 1,
timingMode: .easeInOut
),
Animo.keyPath(
"backgroundColor",
to: UIColor.red,
duration: 1,
timingMode: .easeInOut
)
)
)
)
)
}
private func startSquareView2() {
_ = self.squareView2?.layer.runAnimation(
Animo.sequence(
Animo.wait(1),
Animo.replayForever(
Animo.sequence(
Animo.move(
by: CGPoint(x: 100, y: 200),
duration: 2,
timingMode: .easeInOutBack
),
Animo.rotateDegrees(
by: -180,
duration: 1,
timingMode: .easeInOutBack
),
Animo.group(
Animo.scaleX(
by: 2,
duration: 1,
timingMode: .easeInOutBack
),
Animo.scaleY(
by: 0.5,
duration: 1,
timingMode: .easeInOutBack
)
),
Animo.wait(1),
Animo.move(
by: CGPoint(x: -100, y: -200),
duration: 2,
timingMode: .easeInOutBack
),
Animo.rotateDegrees(
by: 180,
duration: 1,
timingMode: .easeInOutBack
),
Animo.group(
Animo.scaleX(
to: 1,
duration: 1,
timingMode: .easeInOutBack
),
Animo.scaleY(
to: 1,
duration: 1,
timingMode: .easeInOutBack
)
)
)
)
)
)
}
}
| c4c30245de6ea3444b62a75b23b8cd47 | 35.404762 | 104 | 0.431524 | false | false | false | false |
machelix/Swift-SpriteKit-Analog-Stick | refs/heads/master | AnalogStick Demo/AnalogStick Demo/AnalogStick/AnalogStick.swift | mit | 1 | //
// AnalogStick.swift
// Joystick
//
// Created by Dmitriy Mitrophanskiy on 28.09.14.
//
//
import SpriteKit
public typealias AnalogStickMoveHandler = (AnalogStick) -> ()
public struct AnalogStickData: CustomStringConvertible {
var velocity: CGPoint = CGPointZero
var angular: CGFloat = 0
public var description: String {
return "velocity: \(velocity), angular: \(angular)"
}
}
let kStickOfSubstrateWidthPercent: CGFloat = 0.5 // [0..1]
public class AnalogStick: SKNode {
let stickNode = SKSpriteNode()
let substrateNode = SKSpriteNode()
private var tracking = false
private var velocityLoop: CADisplayLink?
var data = AnalogStickData()
var trackingHandler: AnalogStickMoveHandler?
private var _stickColor = UIColor.lightGrayColor()
private var _substrateColor = UIColor.darkGrayColor()
var stickColor: UIColor {
get { return _stickColor }
set(newColor) {
stickImage = UIImage.circleWithRadius(diameter * kStickOfSubstrateWidthPercent, color: newColor)
_stickColor = newColor
}
}
var substrateColor: UIColor {
get { return _substrateColor }
set(newColor) {
substrateImage = UIImage.circleWithRadius(diameter, color: newColor, borderWidth: 5, borderColor: UIColor.blackColor())
_substrateColor = newColor
}
}
var stickImage: UIImage? {
didSet {
guard let newImage = stickImage else {
stickColor = _stickColor
return
}
stickNode.texture = SKTexture(image: newImage)
}
}
var substrateImage: UIImage? {
didSet {
guard let newImage = substrateImage else {
substrateColor = _substrateColor
return
}
substrateNode.texture = SKTexture(image: newImage)
}
}
var diameter: CGFloat {
get { return max(substrateNode.size.width, substrateNode.size.height) }
set {
substrateNode.size = CGSizeMake(newValue, newValue)
stickNode.size = CGSizeMake(newValue * kStickOfSubstrateWidthPercent, newValue * kStickOfSubstrateWidthPercent)
}
}
func listen() {
guard tracking else { return }
trackingHandler?(self)
}
let kThumbSpringBackDuration: NSTimeInterval = 0.15 // action duration
var anchorPointInPoints = CGPointZero
init(diameter: CGFloat, substrateImage: UIImage? = nil, stickImage: UIImage? = nil) {
super.init()
userInteractionEnabled = true;
self.diameter = diameter
self.stickImage = stickImage
self.substrateImage = substrateImage
addChild(substrateNode)
addChild(stickNode)
velocityLoop = CADisplayLink(target: self, selector: Selector("listen"))
velocityLoop!.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}
convenience init(diameter: CGFloat, substrateImage: UIImage?) {
self.init(diameter: diameter, substrateImage: substrateImage, stickImage: nil)
}
convenience init(diameter: CGFloat, stickImage: UIImage?) {
self.init(diameter: diameter, substrateImage: nil, stickImage: stickImage)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func resetStick() {
tracking = false
data.velocity = CGPointZero
data.angular = 0
let easeOut = SKAction.moveTo(anchorPointInPoints, duration: kThumbSpringBackDuration)
easeOut.timingMode = .EaseOut
stickNode.runAction(easeOut)
}
//MARK: - Overrides
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
for touch in touches {
let touchedNode = nodeAtPoint(touch.locationInNode(self))
guard self.stickNode == touchedNode && !tracking else { return }
tracking = true
}
}
public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesMoved(touches, withEvent: event);
for touch: AnyObject in touches {
let location = touch.locationInNode(self);
let xDistance: Float = Float(location.x - self.stickNode.position.x)
let yDistance: Float = Float(location.y - self.stickNode.position.y)
guard tracking && sqrtf(powf(xDistance, 2) + powf(yDistance, 2)) <= Float(diameter * 2) else { return }
let xAnchorDistance: CGFloat = (location.x - anchorPointInPoints.x)
let yAnchorDistance: CGFloat = (location.y - anchorPointInPoints.y)
if sqrt(pow(xAnchorDistance, 2) + pow(yAnchorDistance, 2)) <= self.stickNode.size.width {
let moveDifference: CGPoint = CGPointMake(xAnchorDistance , yAnchorDistance)
stickNode.position = CGPointMake(anchorPointInPoints.x + moveDifference.x, anchorPointInPoints.y + moveDifference.y)
} else {
let magV = sqrt(xAnchorDistance * xAnchorDistance + yAnchorDistance * yAnchorDistance)
let aX = anchorPointInPoints.x + xAnchorDistance / magV * stickNode.size.width
let aY = anchorPointInPoints.y + yAnchorDistance / magV * stickNode.size.width
stickNode.position = CGPointMake(aX, aY)
}
let tNAnchPoinXDiff = stickNode.position.x - anchorPointInPoints.x;
let tNAnchPoinYDiff = stickNode.position.y - anchorPointInPoints.y
data = AnalogStickData(velocity: CGPointMake(tNAnchPoinXDiff, tNAnchPoinYDiff), angular: CGFloat(-atan2f(Float(tNAnchPoinXDiff), Float(tNAnchPoinYDiff))))
}
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
resetStick()
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
resetStick()
}
}
extension UIImage {
static func circleWithRadius(radius: CGFloat, color: UIColor, borderWidth: CGFloat = 0, borderColor: UIColor? = nil) -> UIImage {
let diametr = radius * 2
UIGraphicsBeginImageContextWithOptions(CGSizeMake(diametr + borderWidth * 2, diametr + borderWidth * 2), false, 0)
let bPath = UIBezierPath(ovalInRect: CGRect(origin: CGPoint(x: borderWidth, y: borderWidth), size: CGSizeMake(diametr, diametr)))
if let bC = borderColor {
bC.setStroke()
bPath.lineWidth = borderWidth
bPath.stroke()
}
color.setFill()
bPath.fill()
let rImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return rImage
}
}
| fdf61ef217f9e245b439a519fe12cdd0 | 31.590517 | 166 | 0.598995 | false | false | false | false |
IngmarStein/swift | refs/heads/master | stdlib/public/core/BidirectionalCollection.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that provides subscript access to its elements, with bidirectional
/// index traversal.
///
/// In most cases, it's best to ignore this protocol and use the
/// `BidirectionalCollection` protocol instead, because it has a more complete
/// interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'BidirectionalCollection' instead")
public typealias BidirectionalIndexable = _BidirectionalIndexable
public protocol _BidirectionalIndexable : _Indexable {
// FIXME(ABI)#22 (Recursive Protocol Constraints): there is no reason for this protocol
// to exist apart from missing compiler features that we emulate with it.
// rdar://problem/20531108
//
// This protocol is almost an implementation detail of the standard
// library.
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
func index(before i: Index) -> Index
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
func formIndex(before i: inout Index)
}
/// A collection that supports backward as well as forward traversal.
///
/// Bidirectional collections offer traversal backward from any valid index,
/// not including a collection's `startIndex`. Bidirectional collections can
/// therefore offer additional operations, such as a `last` property that
/// provides efficient access to the last element and a `reversed()` method
/// that presents the elements in reverse order. In addition, bidirectional
/// collections have more efficient implementations of some sequence and
/// collection methods, such as `suffix(_:)`.
///
/// Conforming to the BidirectionalCollection Protocol
/// ==================================================
///
/// To add `BidirectionalProtocol` conformance to your custom types, implement
/// the `index(before:)` method in addition to the requirements of the
/// `Collection` protocol.
///
/// Indices that are moved forward and backward in a bidirectional collection
/// move by the same amount in each direction. That is, for any index `i` into
/// a bidirectional collection `c`:
///
/// - If `i >= c.startIndex && i < c.endIndex`,
/// `c.index(before: c.index(after: i)) == i`.
/// - If `i > c.startIndex && i <= c.endIndex`
/// `c.index(after: c.index(before: i)) == i`.
public protocol BidirectionalCollection
: _BidirectionalIndexable, Collection {
// TODO: swift-3-indexing-model - replaces functionality in BidirectionalIndex
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
func index(before i: Index) -> Index
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
func formIndex(before i: inout Index)
/// A sequence that can represent a contiguous subrange of the collection's
/// elements.
associatedtype SubSequence : _BidirectionalIndexable, Collection
= BidirectionalSlice<Self>
// FIXME(ABI)#93 (Recursive Protocol Constraints):
// FIXME(ABI)#94 (Associated Types with where clauses):
// This is dependent on both recursive protocol constraints AND associated
// types with where clauses.
// associatedtype SubSequence : BidirectionalCollection
/// A type that can represent the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices : _BidirectionalIndexable, Collection
= DefaultBidirectionalIndices<Self>
// FIXME(ABI)#95 (Recursive Protocol Constraints):
// FIXME(ABI)#96 (Associated Types with where clauses):
// This is dependent on both recursive protocol constraints AND associated
// types with where clauses.
// associatedtype Indices : BidirectionalCollection
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be non-uniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can cause an unexpected copy of the collection. To avoid the
/// unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
var indices: Indices { get }
// TODO: swift-3-indexing-model: tests.
/// The last element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let lastNumber = numbers.last {
/// print(lastNumber)
/// }
/// // Prints "50"
///
/// - Complexity: O(1)
var last: Iterator.Element? { get }
}
/// Default implementation for bidirectional collections.
extension _BidirectionalIndexable {
@inline(__always)
public func formIndex(before i: inout Index) {
i = index(before: i)
}
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
if n >= 0 {
return _advanceForward(i, by: n)
}
var i = i
for _ in stride(from: 0, to: n, by: -1) {
formIndex(before: &i)
}
return i
}
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
if n >= 0 {
return _advanceForward(i, by: n, limitedBy: limit)
}
var i = i
for _ in stride(from: 0, to: n, by: -1) {
if i == limit {
return nil
}
formIndex(before: &i)
}
return i
}
public func distance(from start: Index, to end: Index) -> IndexDistance {
var start = start
var count: IndexDistance = 0
if start < end {
while start != end {
count += 1 as IndexDistance
formIndex(after: &start)
}
}
else if start > end {
while start != end {
count -= 1 as IndexDistance
formIndex(before: &start)
}
}
return count
}
}
/// Supply the default "slicing" `subscript` for `BidirectionalCollection`
/// models that accept the default associated `SubSequence`,
/// `BidirectionalSlice<Self>`.
extension BidirectionalCollection where SubSequence == BidirectionalSlice<Self> {
public subscript(bounds: Range<Index>) -> BidirectionalSlice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return BidirectionalSlice(base: self, bounds: bounds)
}
}
extension BidirectionalCollection where SubSequence == Self {
/// Removes and returns the last element of the collection.
///
/// - Returns: The last element of the collection if the collection has one
/// or more elements; otherwise, `nil`.
///
/// - Complexity: O(1).
/// - SeeAlso: `removeLast()`
public mutating func popLast() -> Iterator.Element? {
guard !isEmpty else { return nil }
let element = last!
self = self[startIndex..<index(before: endIndex)]
return element
}
/// Removes and returns the last element of the collection.
///
/// The collection must not be empty.
///
/// - Returns: The last element of the collection.
///
/// - Complexity: O(1)
/// - SeeAlso: `popLast()`
@discardableResult
public mutating func removeLast() -> Iterator.Element {
let element = last!
self = self[startIndex..<index(before: endIndex)]
return element
}
/// Removes the given number of elements from the end of the collection.
///
/// - Parameter n: The number of elements to remove. `n` must be greater
/// than or equal to zero, and must be less than or equal to the number of
/// elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
public mutating func removeLast(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it contains")
self = self[startIndex..<index(endIndex, offsetBy: numericCast(-n))]
}
}
extension BidirectionalCollection {
/// Returns a subsequence containing all but the specified number of final
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in the
/// collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence that leaves off `n` elements from the end.
///
/// - Complexity: O(*n*), where *n* is the number of elements to drop.
public func dropLast(_ n: Int) -> SubSequence {
_precondition(
n >= 0, "Can't drop a negative number of elements from a collection")
let end = index(
endIndex,
offsetBy: numericCast(-n),
limitedBy: startIndex) ?? startIndex
return self[startIndex..<end]
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains the entire collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence terminating at the end of the collection with at
/// most `maxLength` elements.
///
/// - Complexity: O(*n*), where *n* is equal to `maxLength`.
public func suffix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a suffix of negative length from a collection")
let start = index(
endIndex,
offsetBy: numericCast(-maxLength),
limitedBy: startIndex) ?? startIndex
return self[start..<endIndex]
}
}
| 915945a12227c9db25b43cc706204738 | 35.480645 | 116 | 0.650279 | false | false | false | false |
JohnDuxbury/xcode | refs/heads/master | Fingers/Fingers/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// Fingers
//
// Created by JD on 09/05/2015.
// Copyright (c) 2015 JDuxbury.me. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var guessResult: UILabel!
@IBOutlet weak var guessEntry: UITextField!
@IBAction func guessButton(sender: AnyObject) {
var randomNumber = arc4random_uniform(6)
var guessInt = guessEntry.text.toInt()
guessResult.text=toString(randomNumber)
if guessInt != nil {
if Int(randomNumber) == guessInt
{
guessResult.text="Good Guess!"
} else
{
guessResult.text="Sorry - the correct number was \(randomNumber)!"
}
}else{
guessResult.text="Please enter a number between 1 - 5!"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 52bdcf03e1923f0f6626de871ecad89e | 21.375 | 82 | 0.557861 | false | false | false | false |
Mashape/httpsnippet | refs/heads/master | test/fixtures/output/swift/nsurlsession/jsonObj-null-value.swift | mit | 1 | import Foundation
let headers = ["content-type": "application/json"]
let parameters = ["foo": ] as [String : Any]
let postData = JSONSerialization.data(withJSONObject: parameters, options: [])
let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
| 80d0610347fd53c1736c281cccb36dbb | 32 | 116 | 0.667879 | false | false | false | false |
BrettRToomey/brett-xml | refs/heads/master | Sources/BML.swift | mit | 1 | import Core
import Node
public typealias XML = BML
public final class BML {
var _name: Bytes
var _value: Bytes?
var nameCache: String?
var valueCache: String?
public var name: String {
if let nameCache = nameCache {
return nameCache
} else {
let result = _name.fasterString
nameCache = result
return result
}
}
public var value: String? {
guard _value != nil else {
return nil
}
if let valueCache = valueCache {
return valueCache
} else {
let result = _value!.fasterString
valueCache = result
return result
}
}
public var attributes: [BML]
public var children: [BML]
public weak var parent: BML?
init(
name: Bytes,
value: Bytes? = nil,
attributes: [BML] = [],
children: [BML] = [],
parent: BML? = nil
) {
_name = name
_value = value
self.attributes = attributes
self.children = children
self.parent = parent
}
convenience init(
name: String,
value: String? = nil,
attributes: [BML] = [],
children: [BML] = [],
parent: BML? = nil
) {
self.init(
name: name.bytes,
value: value?.bytes,
attributes: attributes,
children: children,
parent: parent
)
}
}
extension BML {
func addChild(key: Bytes, value: Bytes) {
let sighting = BML(name: key, value: value, parent: self)
add(child: sighting)
}
func addAttribute(key: Bytes, value: Bytes) {
let sighting = BML(name: key, value: value, parent: self)
add(attribute: sighting)
}
func add(child: BML) {
child.parent = self
children.append(child)
}
func add(attribute: BML) {
attributes.append(attribute)
}
}
extension BML {
public func children(named name: String) -> [BML] {
let name = name.bytes
return children.filter {
$0._name == name
}
}
public func firstChild(named name: String) -> BML? {
let name = name.bytes
for child in children {
if child._name == name {
return child
}
}
return nil
}
public func attributes(named name: String) -> [BML] {
let name = name.bytes
return children.filter {
$0._name == name
}
}
public func firstAttribute(named name: String) -> BML? {
let name = name.bytes
for attribute in attributes {
if attribute._name == name {
return attribute
}
}
return nil
}
}
extension BML {
public subscript(_ name: String) -> BML? {
return firstChild(named: name)
}
}
extension BML {
/*func makeNode() -> Node {
// String
if let text = text?.fasterString, children.count == 0 {
return .string(text)
}
// Array
if children.count == 1, text == nil, children[0].value.count > 1 {
return .array(
children[0].value.map {
$0.makeNode()
}
)
}
// Object
var object = Node.object([:])
if let text = text?.fasterString {
object["text"] = .string(text)
}
children.forEach {
let subObject: Node
if $0.value.count == 1 {
subObject = $0.value[0].makeNode()
} else {
subObject = .array(
$0.value.map {
$0.makeNode()
}
)
}
object[$0.key.fasterString] = subObject
}
return object
}*/
}
| 8fdd0395a15b6680a823acbe7df50780 | 21.539326 | 74 | 0.472333 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Media/StockPhotos/StockPhotosDataLoader.swift | gpl-2.0 | 2 | /// Implementations of this protocol will be notified when data is loaded from the StockPhotosService
protocol StockPhotosDataLoaderDelegate: AnyObject {
func didLoad(media: [StockPhotosMedia], reset: Bool)
}
/// Uses the StockPhotosService to load stock photos, handling pagination
final class StockPhotosDataLoader {
private let service: StockPhotosService
private weak var delegate: StockPhotosDataLoaderDelegate?
private var request: StockPhotosSearchParams?
fileprivate enum State {
case loading
case idle
}
fileprivate var state: State = .idle
init(service: StockPhotosService, delegate: StockPhotosDataLoaderDelegate) {
self.service = service
self.delegate = delegate
}
func search(_ params: StockPhotosSearchParams) {
request = params
let isFirstPage = request?.pageable?.pageIndex == StockPhotosPageable.defaultPageIndex
state = .loading
DispatchQueue.main.async { [weak self] in
WPAnalytics.track(.stockMediaSearched)
self?.service.search(params: params) { resultsPage in
self?.state = .idle
self?.request = StockPhotosSearchParams(text: self?.request?.text, pageable: resultsPage.nextPageable())
if let content = resultsPage.content() {
self?.delegate?.didLoad(media: content, reset: isFirstPage)
}
}
}
}
func loadNextPage() {
// Bail out if there is another active request
guard state == .idle else {
return
}
// Bail out if we are not aware of the pagination status
guard let request = request else {
return
}
// Bail out if we do not expect more pages of data
guard request.pageable?.next() != nil else {
return
}
search(request)
}
}
| 8c04b9bb5b889a9e0b724c5d67d24caa | 31.525424 | 120 | 0.633663 | false | false | false | false |
clwm01/RCTools | refs/heads/master | RCToolsDemo/RCToolsDemo/AudioStreamViewController.swift | mit | 2 | //
// AudioStreamViewController.swift
//
//
// Created by Rex Tsao on 3/14/16.
//
//
import UIKit
class AudioStreamViewController: UIViewController {
private let adds = ["http://www.bu-chou-la.com/uploadfile/24Vi.mp3", "http://120.24.165.30/ShadoPan_A_Hero.mp3"]
private let titles = ["24Vi.mp3", "ShadoPan_A_Hero.mp3"]
private var queue: AFSoundQueue?
private lazy var items = [AFSoundItem]()
private var player: RTAudioPlayback?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.whiteColor()
let startButton = UIButton()
startButton.setTitle("start", forState: .Normal)
startButton.sizeToFit()
startButton.addTarget(self, action: #selector(AudioStreamViewController.start), forControlEvents: .TouchUpInside)
startButton.frame.origin = CGPointMake(10, 64)
startButton.setTitleColor(UIColor.orangeColor(), forState: .Normal)
self.view.addSubview(startButton)
let stopButton = UIButton()
stopButton.setTitle("pause", forState: .Normal)
stopButton.sizeToFit()
stopButton.addTarget(self, action: #selector(AudioStreamViewController.pause), forControlEvents: .TouchUpInside)
stopButton.frame.origin = CGPointMake(startButton.frame.origin.x + startButton.frame.width + 10, 64)
stopButton.setTitleColor(UIColor.orangeColor(), forState: .Normal)
self.view.addSubview(stopButton)
let tableView = UITableView(frame: CGRectMake(0, stopButton.frame.origin.y + stopButton.frame.height + 10, self.view.bounds.width, self.view.bounds.height - stopButton.frame.height - 10))
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "music")
self.view.addSubview(tableView)
// AFSoundManager
let item1 = AFSoundItem(streamingURL: NSURL(string: self.adds[0]))
let item2 = AFSoundItem(streamingURL: NSURL(string: self.adds[1]))
self.items.append(item1)
self.items.append(item2)
self.queue = AFSoundQueue(items: items)
// self.queue?.playCurrentItem()
self.queue?.listenFeedbackUpdatesWithBlock({
item in
RTPrint.shareInstance().prt("Item duration: \(item.duration) - time elapsed: \(item.timePlayed)")
}, andFinishedBlock: {
nextItem in
if nextItem != nil {
RTPrint.shareInstance().prt("Finished item, next one is \(nextItem.title)")
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.queue?.clearQueue()
}
func start() {
RTPrint.shareInstance().prt("[AudioStreamViewController:start] You touched the start button.")
self.queue?.playCurrentItem()
self.player?.restart()
}
func pause() {
self.queue?.pause()
self.player?.pause()
}
}
extension AudioStreamViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("music")! as UITableViewCell
cell.textLabel!.text = self.titles[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.queue?.playItem(self.items[indexPath.row])
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
}
| 976852156eff59499d3f6375a04442ea | 37.811321 | 195 | 0.663588 | false | false | false | false |
anzfactory/TwitterClientCLI | refs/heads/master | Sources/TwitterClientCore/TwitterClient.swift | mit | 1 | import AppKit
import Foundation
import Dispatch
import APIKit
import Swiftline
import Rainbow
public final class Client {
let oauth: TwitterOAuth = TwitterOAuth(
consumerKey: Keys.consumerKey,
consumerSecret: Keys.consumerSecret,
oauthToken: UserDefaults.standard.string(forKey: "oauthtoken"),
oauthTokenSecret: UserDefaults.standard.string(forKey: "oauthtokensecret")
)
public init() { }
}
extension Client {
public func auth() {
let request = RequestTokenType(oauth: self.oauth)
Session.send(request) { [weak self] result in
switch result {
case .success(let requestToken):
self?.oauth.update(by: requestToken)
NSWorkspace.shared.open(URL(string: TwitterOAuth.URLs.authorize(oauthToken: requestToken.oauthToken).string)!)
let pinCode = ask("Enter PIN")
self?.getAccessToken(pinCode: pinCode)
case .failure(let error):
print(error.localizedDescription.red)
exit(0)
}
}
dispatchMain()
}
public func logout() {
UserDefaults.standard.removeObject(forKey: "oauthtoken")
UserDefaults.standard.removeObject(forKey: "oauthtokensecret")
print("アクセストークンをクリアしました\nアプリ連携の解除は忘れずに行って下さい".blue)
}
public func tweet(_ message: String, replyId: Int, path: String) {
if message.isEmpty && path.isEmpty {
print("message and path is empty...".red)
return
}
self.getTweet(tweetId: replyId) { tweet in
var msg = message
if let tweet = tweet {
msg = "@\(tweet.user.screenName) \(message)"
}
self.uploadMedia(path: path, callback: { mediaId in
let request = TweetType(oauth: self.oauth, message: msg, replyId: replyId, mediaId: mediaId)
Session.send(request) { [weak self] result in
switch result {
case .success(let tweet):
print("-- done --".blue)
self?.output(items: [tweet])
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
})
}
dispatchMain()
}
public func retweet(_ tweetId: Int) {
let request = RetweetType(oauth: self.oauth, tweetId: tweetId)
Session.send(request) { [weak self] result in
switch result {
case .success(let tweet):
print("-- retweeted --".blue)
self?.output(items: [tweet])
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func unretweet(_ tweetId: Int) {
let request = UnRetweetType(oauth: self.oauth, tweetId: tweetId)
Session.send(request) { [weak self] result in
switch result {
case .success(let tweet):
print("-- unretweeted --".blue)
self?.output(items: [tweet])
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func favorites(count: Int = 30) {
let request = FavoritesType(oauth: self.oauth, count: count)
Session.send(request) { [weak self] result in
switch result {
case .success(let tweets):
self?.output(items: tweets.list)
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func favorite(_ tweetId: Int) {
let request = FavoriteType(oauth: self.oauth, tweetId: tweetId)
Session.send(request) { [weak self] result in
switch result {
case .success(let tweet):
print("-- favorited --".blue)
self?.output(items: [tweet])
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func unfavorite(_ tweetId: Int) {
let request = UnFavoriteType(oauth: self.oauth, tweetId: tweetId)
Session.send(request) { [weak self] result in
switch result {
case .success(let tweet):
print("-- unfavorited --".blue)
self?.output(items: [tweet])
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func love(_ tweetId: Int) {
let request = FavoriteType(oauth: self.oauth, tweetId: tweetId)
Session.send(request) {
switch $0 {
case .success(_):
let retweetRequest = RetweetType(oauth: self.oauth, tweetId: tweetId)
Session.send(retweetRequest) { [weak self] result in
switch result {
case .success(let tweet):
print("-- retweeted & favorited --".blue)
self?.output(items: [tweet])
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
case .failure(let error):
print(error.localizedDescription.red)
exit(0)
}
}
dispatchMain()
}
public func timeline(count: Int = 30, sinceId: Int = 0, maxId: Int = 0) {
var count = count
if count <= 0 {
print("invalid count...".red)
return
} else if count > 200 {
count = 200
}
let request = TimelineType(oauth: self.oauth, count: count, sinceId: sinceId, maxId: maxId)
Session.send(request) { [weak self] result in
switch result {
case .success(let tweets):
self?.output(items: tweets.list)
case.failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func userTimeline(_ screenName: String, count: Int = 30, sinceId: Int = 0, maxId: Int = 0) {
var count = count
if count <= 0 {
print("invalid count...".red)
return
} else if count > 200 {
count = 200
}
let request = UserTimelineType(oauth: self.oauth, screenName: screenName, count: count, sinceId: sinceId, maxId: maxId)
Session.send(request) { [weak self] result in
switch result {
case .success(let tweets):
self?.output(items: tweets.list)
case.failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func searchTweet(_ q: String, count: Int = 30, sinceId: Int, maxId: Int) {
var count = count
if count <= 0 {
print("invalid count...".red)
return
} else if count > 200 {
count = 200
}
let request = SearchTweetType(oauth: self.oauth, q: q, count: count, sinceId: sinceId, maxId: maxId)
Session.send(request) { [weak self] result in
switch result {
case .success(let tweets):
self?.output(items: tweets.list)
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func searchUser(_ q: String, count: Int = 30) {
var count = count
if count <= 0 {
print("invalid count...".red)
return
} else if count > 200 {
count = 200
}
let request = SearchUserType(oauth: self.oauth, q: q, count: count)
Session.send(request) { [weak self] result in
switch result {
case .success(let users):
self?.output(items: users.list)
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func follow(userId: Int, screenName: String) {
let request = FollowType(oauth: self.oauth, userId: userId, screenName: screenName)
Session.send(request) {
switch $0 {
case .success(let user):
print("follow: @\(user.screenName)(\(user.id))".blue)
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func unfollow(userId: Int, screenName: String) {
let request = UnFollowType(oauth: self.oauth, userId: userId, screenName: screenName)
Session.send(request) {
switch $0 {
case .success(let user):
print("unfollow: @\(user.screenName)(\(user.id))".blue)
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func me() {
let request = AccountSettingsType(oauth: self.oauth)
Session.send(request) { [weak self] result in
switch result {
case .success(let settings):
self?.output(items: [settings])
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
public func rateLimit() {
let request = RateLimitType(oauth: self.oauth)
Session.send(request) { [weak self] result in
switch result {
case .success(let rateLimit):
self?.output(items: [rateLimit])
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
dispatchMain()
}
}
extension Client {
fileprivate func getAccessToken(pinCode: String) {
let request = AccessTokenType(oauth: self.oauth, pinCode: pinCode)
Session.send(request) { [weak self] result in
switch result {
case .success(let accessToken):
UserDefaults.standard.set(accessToken.oauthToken, forKey: "oauthtoken")
UserDefaults.standard.set(accessToken.oauthTokenSecret, forKey: "oauthtokensecret")
self?.oauth.update(by: accessToken)
print("Hello \(accessToken.userName)".blue)
case .failure(let error):
print(error.localizedDescription.red)
}
exit(0)
}
}
fileprivate func uploadMedia(path: String, callback: @escaping (Int?) -> Void) {
if path.isEmpty {
callback(nil)
return
}
let request = MediaUploadType(oauth: self.oauth, url: URL(fileURLWithPath: path))
Session.send(request) {
switch $0 {
case .success(let media):
callback(media.id)
case .failure(_):
callback(nil)
}
}
}
fileprivate func getTweet(tweetId: Int, callback: @escaping (Tweet?) -> Void) {
if 0 >= tweetId {
callback(nil)
return
}
let request = ShowTweetType(oauth: self.oauth, tweetId: tweetId)
Session.send(request) {
switch $0 {
case .success(let tweet):
callback(tweet)
case .failure(let error):
print(error)
callback(nil)
}
}
}
fileprivate func output(items: [Outputable]) {
for item in items {
print(item.output())
print("")
}
}
}
| 3cc918243d1c960e369bce168f1ec818 | 31.471204 | 127 | 0.510158 | false | false | false | false |
huonw/swift | refs/heads/master | test/IRGen/class_metadata.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s -check-prefix=CHECK -check-prefix=CHECK-%target-ptrsize
class A {}
// CHECK: [[A_NAME:@.*]] = private constant [2 x i8] c"A\00"
// CHECK-LABEL: @"$S14class_metadata1ACMn" =
// Flags. -2147221424 == 0x8004_0050 == HasVTable | Reflectable | Unique | Class
// CHECK-SAME: i32 -2147221424,
// Parent.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadataMXM"
// Name.
// CHECK-SAME: i32 {{.*}} [[A_NAME]]
// Metadata access function.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadata1ACMa"
// Superclass.
// CHECK-SAME: i32 0,
// Field count.
// CHECK-SAME: i32 0,
// Field offset vector offset.
// CHECK-32-SAME: i32 14,
// CHECK-64-SAME: i32 11,
// V-table offset.
// CHECK-32-SAME: i32 13,
// CHECK-64-SAME: i32 10,
// V-table length.
// CHECK-SAME: i32 1,
// V-table entry #1: invocation function.
// CHECK-SAME: @"$S14class_metadata1ACACycfc"
// V-table entry #1: flags.
// CHECK-SAME: i32 1 } }>, section
class B : A {}
// CHECK: [[B_NAME:@.*]] = private constant [2 x i8] c"B\00"
// CHECK-LABEL: @"$S14class_metadata1BCMn" =
// Flags. 262224 == 0x0004_0050 == Reflectable | Unique | Class
// CHECK-SAME: i32 262224,
// Parent.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadataMXM"
// Name.
// CHECK-SAME: i32 {{.*}} [[B_NAME]]
// Metadata access function.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadata1BCMa"
// Superclass.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadata1ACMn"
// Field count.
// CHECK-SAME: i32 0,
// Field offset vector offset.
// CHECK-32-SAME: i32 14 }>, section
// CHECK-64-SAME: i32 11 }>, section
class C<T> : B {}
// CHECK: [[C_NAME:@.*]] = private constant [2 x i8] c"C\00"
// CHECK-LABEL: @"$S14class_metadata1CCMn" =
// Flags. 262352 == 0x0004_00d0 == Reflectable | Generic | Unique | Class
// CHECK-SAME: i32 262352,
// Parent.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadataMXM"
// Name.
// CHECK-SAME: i32 {{.*}} [[C_NAME]]
// Metadata access function.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadata1CCMa"
// Superclass.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadata1BCMn"
// Negative size in words.
// CHECK-SAME: i32 2,
// Positive size in words.
// CHECK-32-SAME: i32 15,
// CHECK-64-SAME: i32 12,
// Num immediate members.
// CHECK-32-SAME: i32 1,
// Field count.
// CHECK-SAME: i32 0,
// Field offset vector offset.
// CHECK-32-SAME: i32 15,
// CHECK-64-SAME: i32 12,
// Instantiation cache.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadata1CCMI"
// Instantiation pattern.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadata1CCMP"
// Generic parameter count.
// CHECK-SAME: i16 1,
// Generic requirement count.
// CHECK-SAME: i16 0,
// Key generic arguments count.
// CHECK-SAME: i16 1,
// Extra generic arguments count.
// CHECK-SAME: i16 0,
// Generic parameter descriptor #1: flags. -128 == 0x80 == Key
// CHECK-SAME: i8 -128,
/// Padding.
// CHECK-SAME: i8 0,
// CHECK-SAME: i8 0,
// CHECK-SAME: i8 0 }>, section
// CHECK-LABEL: @"$S14class_metadata1CCMP" =
// Instantiation function.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadata1CCMi"
// For stupid reasons, when we declare the superclass after the subclass,
// we end up using an indirect reference to the nominal type descriptor.
class D : E {}
// CHECK: [[D_NAME:@.*]] = private constant [2 x i8] c"D\00"
// CHECK-LABEL: @"$S14class_metadata1DCMn" =
// Flags. 268697680 == 0x1004_0050 == Reflectable | IndirectSuperclass | Unique | Class
// CHECK-SAME: i32 268697680,
// Parent.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadataMXM"
// Name.
// CHECK-SAME: i32 {{.*}} [[D_NAME]]
// Metadata access function.
// CHECK-SAME: i32 {{.*}} @"$S14class_metadata1DCMa"
// Superclass.
// CHECK-SAME: i32 {{.*}} @"got.$S14class_metadata1ECMn
// Field count.
// CHECK-SAME: i32 0,
// Field offset vector offset.
// CHECK-32-SAME: i32 14 }>, section
// CHECK-64-SAME: i32 11 }>, section
class E {}
| 604b98375e9f7de09db28a195ac31c7b | 31.01626 | 114 | 0.623667 | false | false | false | false |
premefeed/premefeed-ios | refs/heads/master | PremeFeed-iOS/PremeFeedAPI.swift | mit | 1 | //
// PremeFeedAPI.swift
// PremeFeed-iOS
//
// Created by Cryptoc1 on 12/20/15.
// Copyright © 2015 Cryptoc1. All rights reserved.
//
import Foundation
class PremeFeedAPI {
// Default api url (NOTE: no ending slash)
let apiURL: String = "https://premefeed.herokuapp.com/api/v1"
init() {
// Empty
}
/*
*
* The folloiwing functions make requests to the api endpoint on the heroku app, they're pretty straightfoward.
* Because NSURLSession is asynchronous, we have to use callbacks
*
*/
func getItemById(id: String, callback: (SupremeItem) -> Void) {
self.makeRequest(NSURL(string: "\(self.apiURL)/item/id?id=\(id)")!, callback: { (json) -> Void in
callback(SupremeItem(json: json))
return
})
}
func getItemByLink(link: String, callback: (SupremeItem) -> Void) {
self.makeRequest(NSURL(string: "\(self.apiURL)/item/link?link=\(link.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!)")!, callback: { (json) -> Void in
callback(SupremeItem(json: json))
return
})
}
func getItemsByTitle(title: String, callback: (Array<SupremeItem>) -> Void) {
self.makeRequest(NSURL(string: "\(self.apiURL)/items/title?title=\(title.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!)")!, callback: { (json) -> Void in
var ret = [SupremeItem]()
for (i, _) in json["items"].enumerate() {
ret.append(SupremeItem(json: json["items"][i]))
}
callback(ret)
return
})
}
func getItemsByAvailability(availability: String, callback: (Array<SupremeItem>) -> Void) {
self.makeRequest(NSURL(string: "\(self.apiURL)/items/availability?availability=\(availability.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()))")!, callback: { (json) -> Void in
var ret = [SupremeItem]()
for (i, _) in json["items"].enumerate() {
ret.append(SupremeItem(json: json["items"][i]))
}
callback(ret)
return
})
}
func getAllItems(callback: (Array<SupremeItem>) -> Void) {
self.makeRequest(NSURL(string: "\(self.apiURL)/items/all")!, callback: { (json) -> Void in
var ret = [SupremeItem]()
for (i, _) in json["items"].enumerate() {
ret.append(SupremeItem(json: json["items"][i]))
}
callback(ret)
})
}
private func makeRequest(url: NSURL, callback: (JSON) -> Void) {
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
callback(JSON(data: data!));
}
task.resume()
}
}
// Converts JSON to a native object
class SupremeItem {
var id: String?
var title: String?
var style: String?
var link: String?
var description: String?
var price: Int?
var images: Array<String>?
var image: String?
var availability: String?
var results: Bool
init(json: JSON) {
if (json.stringValue == "No Results") {
self.results = false
} else {
self.results = true
self.id = json["id"].stringValue
self.title = json["title"].stringValue
self.style = json["style"].stringValue
self.link = json["link"].stringValue
self.description = json["description"].stringValue
self.price = json["price"].intValue
self.images = [String]()
for (i, _) in json["images"].enumerate() {
self.images!.append(json["images"][i].stringValue)
}
self.image = json["image"].stringValue
self.availability = json["availability"].stringValue
}
}
} | b60770d1e1d4fb23c07ce1b21ac64648 | 33.605263 | 218 | 0.580629 | false | false | false | false |
saagarjha/iina | refs/heads/develop | iina/GuideWindowController.swift | gpl-3.0 | 1 | //
// GuideWindowController.swift
// iina
//
// Created by Collider LI on 26/8/2020.
// Copyright © 2020 lhc. All rights reserved.
//
import Cocoa
import WebKit
fileprivate let highlightsLink = "https://iina.io/highlights"
class GuideWindowController: NSWindowController {
override var windowNibName: NSNib.Name {
return NSNib.Name("GuideWindowController")
}
enum Page {
case highlights
}
private var page = 0
var highlightsWebView: WKWebView?
@IBOutlet weak var highlightsContainerView: NSView!
@IBOutlet weak var highlightsLoadingIndicator: NSProgressIndicator!
@IBOutlet weak var highlightsLoadingFailedBox: NSBox!
override func windowDidLoad() {
super.windowDidLoad()
}
func show(pages: [Page]) {
loadHighlightsPage()
showWindow(self)
}
private func loadHighlightsPage() {
window?.title = NSLocalizedString("guide.highlights", comment: "Highlights")
let webView = WKWebView()
highlightsWebView = webView
webView.isHidden = true
webView.translatesAutoresizingMaskIntoConstraints = false
webView.navigationDelegate = self
highlightsContainerView.addSubview(webView, positioned: .below, relativeTo: nil)
Utility.quickConstraints(["H:|-0-[v]-0-|", "V:|-0-[v]-0-|"], ["v": webView])
let (version, _) = Utility.iinaVersion()
webView.load(URLRequest(url: URL(string: "\(highlightsLink)/\(version.split(separator: "-").first!)/")!))
highlightsLoadingIndicator.startAnimation(nil)
}
@IBAction func continueBtnAction(_ sender: Any) {
window?.close()
}
@IBAction func visitIINAWebsite(_ sender: Any) {
NSWorkspace.shared.open(URL(string: AppData.websiteLink)!)
}
}
extension GuideWindowController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url {
if url.absoluteString.starts(with: "https://iina.io/highlights/") {
decisionHandler(.allow)
return
} else {
NSWorkspace.shared.open(url)
}
}
decisionHandler(.cancel)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
highlightsLoadingIndicator.stopAnimation(nil)
highlightsLoadingIndicator.isHidden = true
highlightsLoadingFailedBox.isHidden = false
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
highlightsLoadingIndicator.stopAnimation(nil)
highlightsLoadingIndicator.isHidden = true
highlightsLoadingFailedBox.isHidden = false
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
highlightsLoadingIndicator.stopAnimation(nil)
highlightsLoadingIndicator.isHidden = true
highlightsWebView?.isHidden = false
}
}
class GuideWindowButtonCell: NSButtonCell {
override func awakeFromNib() {
self.attributedTitle = NSAttributedString(
string: title,
attributes: [NSAttributedString.Key.foregroundColor: NSColor.white]
)
}
override func drawBezel(withFrame frame: NSRect, in controlView: NSView) {
NSGraphicsContext.saveGraphicsState()
let rectPath = NSBezierPath(
roundedRect: NSRect(x: 2, y: 2, width: frame.width - 4, height: frame.height - 4),
xRadius: 4, yRadius: 4
)
let shadow = NSShadow()
shadow.shadowOffset = NSSize(width: 0, height: 0)
shadow.shadowBlurRadius = 1
shadow.shadowColor = NSColor.black.withAlphaComponent(0.5)
shadow.set()
if isHighlighted {
NSColor.systemBlue.highlight(withLevel: 0.1)?.setFill()
} else {
NSColor.systemBlue.setFill()
}
rectPath.fill()
NSGraphicsContext.restoreGraphicsState()
}
}
| 6c164ee1f8f5d3d2bcea7b71c0ba547c | 29.766129 | 155 | 0.718742 | false | false | false | false |
u10int/Kinetic | refs/heads/master | Pod/Classes/Animation.swift | mit | 1 | //
// Animation.swift
// Kinetic
//
// Created by Nicholas Shipes on 12/31/15.
// Copyright © 2015 Urban10 Interactive, LLC. All rights reserved.
//
import UIKit
public class Animation: Animatable, TimeScalable, Repeatable, Reversable, Subscriber {
fileprivate static var counter: UInt32 = 0
public var hashValue: Int {
return Unmanaged.passUnretained(self).toOpaque().hashValue
}
public init() {
Animation.counter += 1
self.id = Animation.counter
self.updated.observe { [weak self] (animation) in
self?.onUpdate()
}
}
deinit {
kill()
}
// MARK: Animatable
public var state: AnimationState = .idle {
willSet {
guard newValue != state else { return }
if newValue == .running && (state == .completed || state == .cancelled) {
reset()
}
}
didSet {
guard oldValue != state else { return }
switch state {
case .pending:
if canSubscribe() {
Scheduler.shared.add(self)
}
break
case .running:
started.trigger(self)
// started.close(self)
case .idle:
break
case .cancelled:
kill()
cancelled.trigger(self)
break
case .completed:
// kill()
Scheduler.shared.remove(self)
completed.trigger(self)
// completed.close(self)
print("animation \(id) done")
break
}
}
}
public var duration: TimeInterval = 1.0 {
didSet {
if duration == 0 {
duration = 0.001
}
}
}
public var delay: TimeInterval = 0
public var progress: Double {
get {
return min(Double(elapsed / (delay + duration)), 1.0)
}
set {
seek(duration * TimeInterval(newValue))
}
}
public var totalProgress: Double {
get {
return Double(min(Float(totalTime / totalDuration), Float(1.0)))
}
set {
seek(totalDuration * TimeInterval(newValue))
}
}
private var hasPlayed = false
public var startTime: TimeInterval = 0
public var endTime: TimeInterval {
return startTime + totalDuration
}
public var totalDuration: TimeInterval {
return (duration * TimeInterval(repeatCount + 1)) + (repeatDelay * TimeInterval(repeatCount))
}
public var totalTime: TimeInterval {
return min(runningTime, totalDuration)
}
internal(set) public var elapsed: TimeInterval = 0
public var time: TimeInterval {
return (elapsed - delay)
}
internal var runningTime: TimeInterval = 0
internal(set) public var timingFunction: TimingFunction = Linear().timingFunction
internal(set) public var spring: Spring?
@discardableResult
public func duration(_ duration: TimeInterval) -> Self {
self.duration = duration
return self
}
@discardableResult
public func delay(_ delay: TimeInterval) -> Self {
self.delay = delay
return self
}
@discardableResult
public func ease(_ easing: EasingType) -> Self {
timingFunction = easing.timingFunction
return self
}
@discardableResult
public func spring(tension: Double, friction: Double = 3) -> Self {
spring = Spring(tension: tension, friction: friction)
return self
}
public func play() {
// if animation is currently paused, reset it since play() starts from the beginning
if hasPlayed && state == .idle {
stop()
} else if state == .completed {
reset()
}
if state != .running && state != .pending {
state = .pending
hasPlayed = true
}
}
public func stop() {
if state == .running || state == .pending || isPaused() {
state = .cancelled
} else {
reset()
}
}
public func pause() {
if state == .running || state == .pending {
state = .idle
}
}
public func resume() {
if state == .idle {
state = .running
}
}
@discardableResult
public func seek(_ offset: TimeInterval) -> Self {
guard offset != elapsed else { return self }
pause()
state = .idle
if (offset > 0 && offset < totalDuration) {
}
let time = delay + elapsedTimeFromSeekTime(offset)
// print("\(self).\(self.id).seek - offset: \(offset), time: \(time), elapsed: \(elapsed), duration: \(duration)")
render(time: time)
return self
}
@discardableResult
public func forward() -> Self {
direction = .forward
return self
}
@discardableResult
public func reverse() -> Self {
direction = .reversed
return self
}
public func restart(_ includeDelay: Bool = false) {
reset()
elapsed = includeDelay ? 0 : delay
play()
}
internal func reset() {
seek(0)
runningTime = 0
cycle = 0
progress = 0
state = .idle
direction = .forward
updated.trigger(self)
}
var started = Event<Animation>()
var updated = Event<Animation>()
var completed = Event<Animation>()
var cancelled = Event<Animation>()
var repeated = Event<Animation>()
// MARK: TimeScalable
public var timeScale: Double = 1.0
// MARK: Repeatable
private(set) public var cycle: Int = 0
private(set) public var repeatCount: Int = 0
private(set) public var repeatDelay: TimeInterval = 0.0
private(set) public var repeatForever: Bool = false
@discardableResult
public func repeatCount(_ count: Int) -> Self {
repeatCount = count
return self
}
@discardableResult
public func repeatDelay(_ delay: TimeInterval) -> Self {
repeatDelay = delay
return self
}
@discardableResult
public func forever() -> Self {
repeatForever = true
return self
}
// MARK: Reversable
public var direction: Direction = .forward
private(set) public var reverseOnComplete: Bool = false
@discardableResult
public func yoyo() -> Self {
reverseOnComplete = true
return self
}
// MARK: TimeRenderable
internal func render(time: TimeInterval, advance: TimeInterval = 0) {
elapsed = time
updated.trigger(self)
}
// MARK: - Subscriber
internal var id: UInt32 = 0
internal var updatesStateOnAdvance = true
internal func kill() {
reset()
Scheduler.shared.remove(self)
}
internal func advance(_ time: Double) {
guard shouldAdvance() else { return }
let end = delay + duration
let multiplier: TimeInterval = direction == .reversed ? -timeScale : timeScale
elapsed = max(0, min(elapsed + (time * multiplier), end))
runningTime += time
// if animation doesn't repeat forever, cap elapsed time to endTime
if !repeatForever {
elapsed = min(elapsed, (delay + endTime))
}
if state == .pending && elapsed >= delay {
state = .running
}
// print("\(self).advance - id: \(id), state: \(state), time: \(time), elapsed: \(elapsed), end: \(end), duration: \(duration), progress: \(progress), cycle: \(cycle)")
render(time: elapsed, advance: time)
}
internal func canSubscribe() -> Bool {
return true
}
internal func shouldAdvance() -> Bool {
return state == .pending || state == .running || !isPaused()
}
internal func isAnimationComplete() -> Bool {
return true
}
// MARK: Event Handlers
@discardableResult
public func on(_ event: Animation.EventType, observer: @escaping Event<Animation>.Observer) -> Self {
switch event {
case .started:
started.observe(observer)
case .updated:
updated.observe(observer)
case .completed:
completed.observe(observer)
case .repeated:
repeated.observe(observer)
case .cancelled:
cancelled.observe(observer)
}
return self
}
private func onUpdate() {
let end = delay + duration
let shouldRepeat = (repeatForever || (repeatCount > 0 && cycle < repeatCount))
if state == .running && ((direction == .forward && elapsed >= end) || (direction == .reversed && elapsed == 0)) && updatesStateOnAdvance {
if shouldRepeat {
print("\(self) completed - repeating, reverseOnComplete: \(reverseOnComplete), reversed: \(direction == .reversed), repeat count \(cycle) of \(repeatCount)")
cycle += 1
if reverseOnComplete {
direction = (direction == .forward) ? .reversed : .forward
} else {
// restart()
elapsed = 0
}
repeated.trigger(self)
} else {
if isAnimationComplete() && state == .running {
state = .completed
}
}
} else if state == .idle && elapsed >= end {
state = .completed
}
}
// MARK: Internal Methods
func isPaused() -> Bool {
return (state == .idle && Scheduler.shared.contains(self))
}
func elapsedTimeFromSeekTime(_ time: TimeInterval) -> TimeInterval {
var adjustedTime = time
var adjustedCycle = cycle
// seek time must be restricted to the duration of the timeline minus repeats and repeatDelays
// so if the provided time is greater than the timeline's duration, we need to adjust the seek time first
if adjustedTime > duration {
if repeatCount > 0 && fmod(adjustedTime, duration) != 0.0 {
// determine which repeat cycle the seek time will be in for the specified time
adjustedCycle = Int(adjustedTime / duration)
adjustedTime -= (duration * TimeInterval(adjustedCycle))
} else {
adjustedTime = duration
}
} else {
adjustedCycle = 0
}
// determine if we should reverse the direction of the timeline based on calculated adjustedCycle
let shouldReverse = adjustedCycle != cycle && reverseOnComplete
if shouldReverse {
if direction == .forward {
reverse()
} else {
forward()
}
}
// if direction is reversed, then adjusted time needs to start from end of animation duration instead of 0
if direction == .reversed {
adjustedTime = duration - adjustedTime
}
cycle = adjustedCycle
return adjustedTime
}
}
public func ==(lhs: Animation, rhs: Animation) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
extension Animation {
public enum EventType {
case started
case updated
case cancelled
case completed
case repeated
}
}
| 90ac84bfc6093e0317129efaa4a1f20d | 22.150121 | 169 | 0.665307 | false | false | false | false |
TonnyTao/Acornote | refs/heads/master | Acornote_iOS/Acornote/View/TextView.swift | apache-2.0 | 1 | //
// TextView.swift
// Acornote
//
// Created by Tonny on 09/11/2016.
// Copyright © 2016 Tonny&Sunm. All rights reserved.
//
import UIKit
class TextView: UITextView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
textContainerInset = .zero
textContainer.lineFragmentPadding = 0
}
override var textColor: UIColor? {
didSet {
if let old = attributedText?.string, let color = textColor {
let style:NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
style.lineSpacing = 2
let att = NSAttributedString(string: old, attributes: [.font : ItemTableViewCell.titleFont, .paragraphStyle:style, .foregroundColor: color])
attributedText = att
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count == 1 && touches.first?.tapCount == 1 {
superview?.touchesBegan(touches, with: event)
return
}
super.touchesBegan(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count == 1 && touches.first?.tapCount == 1 {
superview?.touchesEnded(touches, with: event)
return
}
super.touchesEnded(touches, with: event)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count == 1 && touches.first?.tapCount == 1 {
superview?.touchesMoved(touches, with: event)
return
}
super.touchesMoved(touches, with: event)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count == 1 && touches.first?.tapCount == 1 {
superview?.touchesCancelled(touches, with: event)
return
}
super.touchesCancelled(touches, with: event)
}
}
| 0c725ce02717db1088399265de3a91dc | 31.515625 | 156 | 0.590581 | false | false | false | false |
SteveKChiu/CoreDataMonk | refs/heads/master | CoreDataMonk/CollectionViewDataProvider.swift | mit | 1 | //
// https://github.com/SteveKChiu/CoreDataMonk
//
// Copyright 2015, Steve K. Chiu <[email protected]>
//
// The MIT License (http://www.opensource.org/licenses/mit-license.php)
//
// 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 CoreData
//---------------------------------------------------------------------------
private class CollectionViewDataBridge<EntityType: NSManagedObject>
: NSObject, UICollectionViewDataSource, NSFetchedResultsControllerDelegate {
weak var provider: CollectionViewDataProvider<EntityType>?
var pendingActions: [() -> Void] = []
var updatedIndexPaths: Set<IndexPath> = []
var shouldReloadData = false
var isFiltering = false
var semaphore: DispatchSemaphore
var collectionView: UICollectionView? {
return self.provider?.collectionView
}
init(provider: CollectionViewDataProvider<EntityType>) {
self.provider = provider
self.semaphore = DispatchSemaphore(value: 1)
}
@objc func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.provider?.numberOfSections() ?? 0
}
@objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.provider?.numberOfObjectsInSection(section) ?? 0
}
@objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let object = self.provider?.objectAtIndexPath(indexPath),
let cell = self.provider?.onGetCell?(object, indexPath) {
return cell
}
return UICollectionViewCell()
}
@objc func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if let view = self.provider?.onGetSupplementary?(kind, indexPath) {
return view
}
return UICollectionReusableView()
}
private func ensureIndexPath(_ indexPath: IndexPath) -> Bool {
if self.isFiltering || self.shouldReloadData {
return false
} else if self.updatedIndexPaths.contains(indexPath) {
self.updatedIndexPaths.removeAll()
self.pendingActions.removeAll()
self.shouldReloadData = true
return false
} else {
self.updatedIndexPaths.insert(indexPath)
return true
}
}
@objc func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.pendingActions.removeAll()
self.updatedIndexPaths.removeAll()
self.shouldReloadData = false
self.isFiltering = self.provider?.objectFilter != nil
}
@objc func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
if ensureIndexPath(newIndexPath!) {
self.pendingActions.append() {
[weak self] in
self?.collectionView?.insertItems(at: [ newIndexPath! ])
}
}
case .delete:
if ensureIndexPath(indexPath!) {
self.pendingActions.append() {
[weak self] in
self?.collectionView?.deleteItems(at: [ indexPath! ])
}
}
case .move:
if ensureIndexPath(indexPath!) && ensureIndexPath(newIndexPath!) {
self.pendingActions.append() {
[weak self] in
self?.collectionView?.moveItem(at: indexPath!, to: newIndexPath!)
}
}
case .update:
if ensureIndexPath(indexPath!) {
self.pendingActions.append() {
[weak self] in
self?.collectionView?.reloadItems(at: [ indexPath! ])
}
}
}
}
@objc func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
if self.isFiltering || self.shouldReloadData {
return
}
switch type {
case .insert:
self.pendingActions.append() {
[weak self] in
self?.collectionView?.insertSections(IndexSet(integer: sectionIndex))
self?.collectionView?.collectionViewLayout.invalidateLayout()
}
case .delete:
self.pendingActions.append() {
[weak self] in
self?.collectionView?.deleteSections(IndexSet(integer: sectionIndex))
self?.collectionView?.collectionViewLayout.invalidateLayout()
}
default:
break
}
}
@objc func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
if self.isFiltering {
self.provider?.filter()
self.provider?.onDataChanged?()
return
}
if self.shouldReloadData || self.collectionView?.window == nil {
self.pendingActions.removeAll()
self.updatedIndexPaths.removeAll()
self.collectionView?.reloadData()
self.provider?.onDataChanged?()
return
}
guard let collectionView = self.collectionView else {
return
}
// make sure batch update animation is not overlapped
let semaphore = self.semaphore
_ = semaphore.wait(timeout: DispatchTime.now() + Double(Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC))
self.updatedIndexPaths.removeAll()
collectionView.performBatchUpdates({
[weak self] in
if let actions = self?.pendingActions, !actions.isEmpty {
self?.pendingActions.removeAll()
for action in actions {
action()
}
}
}, completion: {
[weak self] _ in
self?.provider?.onDataChanged?()
semaphore.signal()
})
}
}
//---------------------------------------------------------------------------
open class CollectionViewDataProvider<EntityType: NSManagedObject> : ViewDataProvider<EntityType> {
public let context: CoreDataMainContext
private var bridge: CollectionViewDataBridge<EntityType>!
public typealias OnGetCell = (EntityType, IndexPath) -> UICollectionViewCell?
public typealias OnGetSupplementary = (String, IndexPath) -> UICollectionReusableView?
public typealias OnDataChanged = () -> Void
public var onGetCell: OnGetCell?
public var onGetSupplementary: OnGetSupplementary?
public var onDataChanged: OnDataChanged?
public weak var collectionView: UICollectionView? {
willSet {
if self.collectionView?.dataSource === self.bridge {
self.collectionView?.dataSource = nil
}
}
didSet {
self.collectionView?.dataSource = self.bridge
}
}
open override var fetchedResultsController: NSFetchedResultsController<EntityType>? {
get {
return super.fetchedResultsController
}
set {
super.fetchedResultsController?.delegate = nil
super.fetchedResultsController = newValue
newValue?.delegate = self.bridge
}
}
public init(context: CoreDataMainContext) {
self.context = context
super.init()
self.bridge = CollectionViewDataBridge<EntityType>(provider: self)
}
public func bind(_ collectionView: UICollectionView, onGetCell: @escaping OnGetCell) {
self.onGetCell = onGetCell
self.collectionView = collectionView
}
public func load(_ query: CoreDataQuery? = nil, orderBy: CoreDataOrderBy, sectionBy: CoreDataQueryKey? = nil, options: CoreDataQueryOptions? = nil) throws {
self.fetchedResultsController = try self.context.fetchResults(EntityType.self, query, orderBy: orderBy, sectionBy: sectionBy, options: options)
try reload()
}
open override func filter() {
super.filter()
self.collectionView?.reloadData()
}
}
| 106b07b5b097797b4e620f6b4a59b6ca | 37.278884 | 215 | 0.623335 | false | false | false | false |
Bing0/ThroughWall | refs/heads/master | ChiselLogViewer/CoreDataController.swift | gpl-3.0 | 1 | //
// CoreDataController.swift
// ChiselLogViewer
//
// Created by Bingo on 09/07/2017.
// Copyright © 2017 Wu Bin. All rights reserved.
//
import Cocoa
class CoreDataController: NSObject {
var databaseURL: URL?
init(withBaseURL url: URL) {
let databaseURL = url.appendingPathComponent(databaseFileName)
self.databaseURL = databaseURL
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ThroughWall")
if let _databaseURL = self.databaseURL {
container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: _databaseURL)]
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error)")
}
})
return container
}()
func getContext() -> NSManagedObjectContext {
return persistentContainer.viewContext
}
}
| f3721c247a0e7328a415fcabadb84865 | 40.185185 | 199 | 0.640737 | false | false | false | false |
hironytic/HNTask | refs/heads/master | HNTaskTests/HNTaskTests.swift | mit | 1 | //
// HNTaskTests.swift
//
// Copyright (c) 2014 Hironori Ichimiya <[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 XCTest
class HNTaskTests: XCTestCase {
struct MyError {
let message: String
}
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testContinuationShouldRun() {
let expectation = expectationWithDescription("finish task");
let task = HNTask.resolve(nil)
task.continueWith { context in
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testContinuationShouldRunWhenRejected() {
let expectation = expectationWithDescription("finish task");
let task = HNTask.reject(MyError(message: "error"))
task.continueWith { context in
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testResultShouldBePassed() {
let expectation = expectationWithDescription("finish task");
let task = HNTask.resolve(10)
task.continueWith { context in
if let value = context.result as? Int {
XCTAssertEqual(value, 10, "previous result should be passed.")
} else {
XCTFail("previous result should be Int.")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testReturnValueShouldBeResult() {
let expectation = expectationWithDescription("finish task");
let task = HNTask.resolve(nil)
task.continueWith { context in
return ("result", nil)
}.continueWith { context in
if let value = context.result as? String {
XCTAssertEqual(value, "result", "previous return value should be result.")
} else {
XCTFail("previous result should be String.")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testRejectShouldCauseError() {
let expectation = expectationWithDescription("finish task");
let task = HNTask.reject(MyError(message: "error"))
task.continueWith { context in
XCTAssertTrue(context.isError(), "error should be occured.")
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testErrorValueShouldBePassed() {
let expectation = expectationWithDescription("finish task");
let task = HNTask.reject(MyError(message: "error"))
task.continueWith { context in
if let error = context.error {
if let myError = error as? MyError {
XCTAssertEqual(myError.message, "error", "error value should be passed.")
} else {
XCTFail("error value should be type of MyError.")
}
} else {
XCTFail("error value should be exist.")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testThreadShouldSwitchedByExecutor() {
let myQueue = dispatch_queue_create("com.hironytic.hntasktests", nil)
class MyExecutor: HNExecutor {
let queue: dispatch_queue_t
init(queue: dispatch_queue_t) {
self.queue = queue
}
func execute(callback: () -> Void) {
dispatch_async(queue) {
callback()
}
}
}
let testThread = NSThread.currentThread()
let expectation = expectationWithDescription("finish task");
let task = HNTask.resolve(nil)
task.continueWith(MyExecutor(queue: myQueue)) { context in
XCTAssertFalse(testThread.isEqual(NSThread.currentThread()), "thread should be switched")
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testResolvedTask() {
let expectation = expectationWithDescription("finish task");
let task = HNTask.resolve(20)
XCTAssertTrue(task.isCompleted(), "task should be completed.")
task.continueWith { context in
if let value = context.result as? Int {
XCTAssertEqual(value, 20, "resolved value should be passed.")
} else {
XCTFail("resolved value should be Int.")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testRejectedTask() {
let expectation = expectationWithDescription("finish task");
let task = HNTask.reject(MyError(message: "rejected"))
XCTAssertTrue(task.isCompleted(), "task should be completed.")
task.continueWith { context in
XCTAssertTrue(context.isError(), "task should be in error state.")
if let error = context.error {
if let myError = error as? MyError {
XCTAssertEqual(myError.message, "rejected", "error message should be 'rejected'")
} else {
XCTFail("error value should be MyError.")
}
} else {
XCTFail("error value should be exist.")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testThenShouldRunWhenSucceeded() {
let expectation = expectationWithDescription("finish task");
HNTask.resolve(30).then { value in
if let intValue = value as? Int {
XCTAssertEqual(intValue, 30, "previous value should be passed.")
} else {
XCTFail("previous value should be Int.")
}
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testThenShouldNotRunWhenError() {
let expectation = expectationWithDescription("finish task");
var ran = false
HNTask.reject(MyError(message: "myError")).then { value in
ran = true
return nil
}.finally {
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
XCTAssertFalse(ran, "then closure should not run.")
}
func testTypeCheckThenShouldRunWhenSucceeded() {
let expectation = expectationWithDescription("finish task");
HNTask.resolve(30).then { (value: Int) in
XCTAssertEqual(value, 30, "previous value should be passed.")
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testTypeCheckThenShouldNotRunWhenError() {
let expectation = expectationWithDescription("finish task");
var ran = false
HNTask.reject(MyError(message: "myError")).then { (value: Int) in
ran = true
return nil
}.finally {
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
XCTAssertFalse(ran, "then closure should not run.")
}
func testTypeCheckThenShouldNotRunWhenTypeMismatch() {
let expectation = expectationWithDescription("finish task");
var ran = false
HNTask.resolve(40).then { (value: String) in
ran = true
return nil
}.finally {
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
XCTAssertFalse(ran, "then closure should not run.")
}
func testTypeCheckThenShouldMakeError() {
let expectation = expectationWithDescription("finish task");
HNTask.resolve(40).then { (value: String) in
return nil
}.catch { error in
if let typeError = error as? HNTaskTypeError {
if let errorValue = typeError.value as? Int {
XCTAssertEqual(errorValue, 40, "error value shoule be 40.")
} else {
XCTFail("error value shoule be Int")
}
} else {
XCTFail("error shoule be kind of HNTaskTypeError")
}
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testCatchShouldNotRunWhenSucceeded() {
let expectation = expectationWithDescription("finish task");
var ran = false
HNTask.resolve(30).catch { error in
ran = true
return nil
}.finally {
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
XCTAssertFalse(ran, "catch closure should not run.")
}
func testCatchShouldRunWhenError() {
let expectation = expectationWithDescription("finish task");
HNTask.reject(MyError(message: "myError")).catch { error in
if let myError = error as? MyError {
XCTAssertEqual(myError.message, "myError", "error message should be 'myError'")
} else {
XCTFail("error value should be MyError.")
}
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testCatchShouldConsumeError() {
let expectation = expectationWithDescription("finish task");
HNTask.reject(MyError(message: "myError")).catch { error in
return 100
}.continueWith { context in
XCTAssertFalse(context.isError(), "error should be consumed.")
if let intValue = context.result as? Int {
XCTAssertEqual(intValue, 100, "previous value should be passed.")
} else {
XCTFail("previous value should be Int.")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testFinallyShouldRunWhenSucceeded() {
let expectation = expectationWithDescription("finish task");
HNTask.resolve(30).finally {
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testFinallyShouldRunWhenFailed() {
let expectation = expectationWithDescription("finish task");
HNTask.reject(MyError(message: "myError")).finally {
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testFinallyShouldCompleteAfterReturnedTasksCompletion() {
let expectation = expectationWithDescription("finish task");
var v = 0
HNTask.resolve(30).finally {
return self.delayAsync(100) {
v = 100
}
}.then { value in
XCTAssertEqual(v, 100, "called after the task returnd from finally()")
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testFinallyShouldNotChangeResultValue() {
let expectation = expectationWithDescription("finish task");
HNTask.resolve(30).finally {
return nil
}.continueWith { context in
XCTAssertFalse(context.isError(), "error should not occured")
if let value = context.result as? Int {
XCTAssertEqual(value, 30, "result value should not change")
} else {
XCTFail("result value shoule be Int")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testFinallyShouldNotChangeErrorValue() {
let expectation = expectationWithDescription("finish task");
HNTask.reject(MyError(message: "error1")).finally {
return nil
}.continueWith { context in
XCTAssertTrue(context.isError(), "error should remain")
if let error = context.error as? MyError {
XCTAssertEqual(error.message, "error1", "error value should not change")
} else {
XCTFail("error value shoule be MyError")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testFinallyShouldNotChangeResultValueAfterReturnedTasksCompletion() {
let expectation = expectationWithDescription("finish task");
HNTask.resolve(30).finally {
return self.delayAsync(100) { }
}.continueWith { context in
XCTAssertFalse(context.isError(), "error should not occured")
if let value = context.result as? Int {
XCTAssertEqual(value, 30, "result value should not change")
} else {
XCTFail("result value shoule be Int")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testFinallyShouldNotChangeErrorValueAfterReturnedTasksCompletion() {
let expectation = expectationWithDescription("finish task");
HNTask.reject(MyError(message: "error1")).finally {
return self.delayAsync(100) { }
}.continueWith { context in
XCTAssertTrue(context.isError(), "error should remain")
if let error = context.error as? MyError {
XCTAssertEqual(error.message, "error1", "error value should not change")
} else {
XCTFail("error value shoule be MyError")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func makeStringAsync(str: String) -> HNTask {
let task = HNTask.resolve(str + "s")
return task
}
func testExecutionOrder() {
let expectation = expectationWithDescription("finish task");
HNTask.resolve("").then { value in
if let str = value as? String {
return str + "a"
} else {
return HNTask.reject(MyError(message: "error"))
}
}.then { value in
if var str = value as? String {
str += "b"
return self.makeStringAsync(str)
} else {
return HNTask.reject(MyError(message: "error"))
}
}.then { value in
if let str = value as? String {
return str + "c"
} else {
return HNTask.reject(MyError(message: "error"))
}
}.continueWith { context in
XCTAssertFalse(context.isError(), "error should not occured")
if let str = context.result as? String {
XCTAssertEqual(str, "absc", "check order")
} else {
XCTFail("result value should be String")
}
expectation.fulfill()
return (nil, nil)
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func delayAsync(milliseconds: Int, callback: () -> Void) -> HNTask {
let task = HNTask { (resolve, reject) in
let delta: Int64 = Int64(milliseconds) * Int64(NSEC_PER_MSEC)
let time = dispatch_time(DISPATCH_TIME_NOW, delta);
dispatch_after(time, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
callback()
resolve(milliseconds)
}
}
return task
}
func timeoutAsync(milliseconds: Int) -> HNTask {
let task = HNTask { (resolve, reject) in
let delta: Int64 = Int64(milliseconds) * Int64(NSEC_PER_MSEC)
let time = dispatch_time(DISPATCH_TIME_NOW, delta);
dispatch_after(time, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
reject(MyError(message: "timeout"))
}
}
return task
}
func testThenShouldBeCalledAfterAllTasksAreCompleted() {
let expectation = expectationWithDescription("finish task");
var value = 0
let task1 = delayAsync(100, callback:{ value += 100 })
let task2 = delayAsync(300, callback:{ value += 300 })
let task3 = delayAsync(200, callback:{ value += 200 })
HNTask.all([task1, task2, task3]).then { values in
XCTAssertEqual(value, 600, "all task shoule be completed")
if let results = values as? Array<Any?> {
let v1 = results[0] as Int
let v2 = results[1] as Int
let v3 = results[2] as Int
XCTAssertEqual(v1, 100, "task1 should return 100")
XCTAssertEqual(v2, 300, "task1 should return 300")
XCTAssertEqual(v3, 200, "task1 should return 200")
} else {
XCTFail("values should be a type of Array")
}
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testCatchAfterAllShouleBeCalledWhenTaskReturnsError() {
let expectation = expectationWithDescription("finish task");
var value = 0
let task1 = delayAsync(100, callback:{ value += 100 })
let task2 = timeoutAsync(150)
let task3 = delayAsync(200, callback:{ value += 200 })
HNTask.all([task1, task2, task3]).then { values in
return nil
}.catch { error in
if let err = error as? MyError {
XCTAssertEqual(err.message, "timeout")
} else {
XCTFail("error should be a type of MyError")
}
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testThenShouldBeCalledAfterOneTaskInRaceIsCompleted() {
let expectation = expectationWithDescription("finish task");
let task1 = delayAsync(100, callback:{ })
let task2 = delayAsync(700, callback:{ })
let task3 = delayAsync(500, callback:{ })
HNTask.race([task1, task2, task3]).then { value in
if let result = value as? Int {
XCTAssertEqual(result, 100, "first task should pass the result")
} else {
XCTFail("result should be a type of Int")
}
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testCatchAfterRaceShouleBeCalledWhenTaskReturnsError() {
let expectation = expectationWithDescription("finish task");
var value = 0
let task1 = delayAsync(500, callback:{ })
let task2 = timeoutAsync(150)
let task3 = delayAsync(700, callback:{ })
HNTask.race([task1, task2, task3]).then { values in
return nil
}.catch { error in
if let err = error as? MyError {
XCTAssertEqual(err.message, "timeout")
} else {
XCTFail("error should be a type of MyError")
}
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testThenShouldBeCalledAfterAllTasksAreSettled() {
let expectation = expectationWithDescription("finish task");
var value = 0
let task1 = delayAsync(100, callback:{ value += 100 })
let task2 = delayAsync(300, callback:{ value += 300 })
let task3 = delayAsync(200, callback:{ value += 200 })
HNTask.allSettled([task1, task2, task3]).then { values in
XCTAssertEqual(value, 600, "all task shoule be completed")
if let results = values as? Array<Any?> {
let v1 = results[0] as Int
let v2 = results[1] as Int
let v3 = results[2] as Int
XCTAssertEqual(v1, 100, "task1 should return 100")
XCTAssertEqual(v2, 300, "task1 should return 300")
XCTAssertEqual(v3, 200, "task1 should return 200")
} else {
XCTFail("values should be a type of Array")
}
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testThenShouldBeCalledAfterAllTasksAreSettledEvenIfOneOfThemIsRejected() {
let expectation = expectationWithDescription("finish task");
var value = 0
let task1 = delayAsync(100, callback:{ value += 100 })
let task2 = timeoutAsync(150)
let task3 = delayAsync(200, callback:{ value += 200 })
HNTask.allSettled([task1, task2, task3]).then { values in
XCTAssertTrue(task1.isCompleted(), "task1 should be completed")
XCTAssertTrue(task2.isCompleted(), "task2 should be completed")
XCTAssertTrue(task3.isCompleted(), "task3 should be completed")
if let results = values as? Array<Any?> {
let v1 = results[0] as Int
let v3 = results[2] as Int
XCTAssertEqual(v1, 100, "task1 should return 100")
XCTAssertEqual(v3, 200, "task1 should return 200")
if let v2 = results[1] as? MyError {
XCTAssertEqual(v2.message, "timeout", "task2 should be timeout.")
} else {
XCTFail("values[1] should be a type of MyError.")
}
} else {
XCTFail("values should be a type of Array.")
}
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
func testAsyncExecutorsRunAsync() {
let expectation = expectationWithDescription("finish task");
HNAsyncExecutor.sharedExecutor.runAsync {
return "ran"
}.then { value in
if let result = value as? String {
XCTAssertEqual(result, "ran", "return value should be passed.")
} else {
XCTFail("result should be a type of String")
}
expectation.fulfill()
return nil
}
waitForExpectationsWithTimeout(5.0, handler: nil)
}
}
| 15db04b5554f9bddf3defea404012040 | 37.284144 | 111 | 0.577152 | false | true | false | false |
apple/swift-nio-ssl | refs/heads/main | Sources/NIOSSL/String+unsafeUninitializedCapacity.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension String {
/// This is a backport of `String.init(unsafeUninitializedCapacity:initializingUTF8With:)`
/// that allows writing directly into an uninitialized String's backing memory.
///
/// As this API does not exist on older Apple platforms, we fake it out with a pointer and accept the extra copy.
init(
customUnsafeUninitializedCapacity capacity: Int,
initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer<UInt8>) throws -> Int
) rethrows {
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
try self.init(unsafeUninitializedCapacity: capacity, initializingUTF8With: initializer)
} else {
try self.init(backportUnsafeUninitializedCapacity: capacity, initializingUTF8With: initializer)
}
}
private init(
backportUnsafeUninitializedCapacity capacity: Int,
initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer<UInt8>) throws -> Int
) rethrows {
let buffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: capacity)
defer {
buffer.deallocate()
}
let initializedCount = try initializer(buffer)
precondition(initializedCount <= capacity, "Overran buffer in initializer!")
self = String(decoding: UnsafeMutableBufferPointer(start: buffer.baseAddress!, count: initializedCount), as: UTF8.self)
}
}
| d721e2a69e148cb8bbf1e02f62f52160 | 41.26087 | 127 | 0.644033 | false | false | false | false |
doctorn/hac-website | refs/heads/master | Sources/HaCWebsiteLib/Events/WorkshopEvent.swift | mit | 1 | import Foundation
struct WorkshopEvent : Event {
let title : String
let time : DateInterval
let tagLine : String
let eventDescription : Text
let color : String
let hypePeriod : DateInterval
let tags : [String]
let workshop : Workshop
let imageURL : String?
let location : Location?
let facebookEventID : String?
var shouldShowAsUpdate: Bool {
get {
return self.hypePeriod.contains(Date())
}
}
var postCardRepresentation : PostCard {
return PostCard(
title: self.title,
category: .workshop,
description: self.tagLine,
backgroundColor: self.color, //TODO
imageURL: self.imageURL
)
}
init(title: String, time: DateInterval, tagLine : String, description: Text, color: String,
hypePeriod: DateInterval, tags: [String], workshop: Workshop, imageURL: String? = nil,
location: Location? = nil, facebookEventID : String? = nil) {
self.title = title
self.time = time
self.tagLine = tagLine
self.eventDescription = description
self.color = color
self.hypePeriod = hypePeriod
self.tags = tags
self.workshop = workshop
self.imageURL = imageURL
self.location = location
self.facebookEventID = facebookEventID
}
}
| 0feb6b08ce747b03165bc9cf78aa36f0 | 28.652174 | 95 | 0.620968 | false | false | false | false |
vivint/Woody | refs/heads/master | Sources/Woody.swift | apache-2.0 | 1 | //
// Woody.swift
// Vivint.SmartHome
//
// Created by Kaden Wilkinson on 9/1/17.
// Copyright © 2017 Vivint.SmartHome. All rights reserved.
//
import Foundation
@objc public protocol WoodyDelegate: class {
@objc optional func verbose(_ msg: String, filepath: String, function: String, line: Int)
@objc optional func debug(_ msg: String, filepath: String, function: String, line: Int)
@objc optional func info(_ msg: String, filepath: String, function: String, line: Int)
@objc optional func warning(_ msg: String, filepath: String, function: String, line: Int)
@objc optional func error(_ msg: String, filepath: String, function: String, line: Int)
}
@objcMembers public class Woody: NSObject {
@objc public enum Level: Int {
case verbose
case debug
case info
case warning
case error
}
/// This should never be set by a framework
@objc public static var delegate: WoodyDelegate?
/// This is used when the delegate hasn't been set yet
/// Keep internal for now until we know API is stable
@objc static var defaultLogger: (String) -> Void = { message in
NSLog(message)
}
@objc(logVerbose:filepath:function:line:)
public static func verbose(_ message: String, filepath: String = #file, function: String = #function, line: Int = #line) {
guard let d = delegate else {
defaultLogger("[VERBOSE] \(filename(from: filepath)).\(function): \(line) - \(message)")
return
}
d.verbose?(message, filepath: filepath, function: function, line: line)
}
@objc(logDebug:filepath:function:line:)
public static func debug(_ message: String, filepath: String = #file, function: String = #function, line: Int = #line) {
guard let d = delegate else {
defaultLogger("[DEBUG] \(filename(from: filepath)).\(function): \(line) - \(message)")
return
}
d.debug?(message, filepath: filepath, function: function, line: line)
}
@objc(logInfo:filepath:function:line:)
public static func info(_ message: String, filepath: String = #file, function: String = #function, line: Int = #line) {
guard let d = delegate else {
defaultLogger("[INFO] \(filename(from: filepath)).\(function): \(line) - \(message)")
return
}
d.info?(message, filepath: filepath, function: function, line: line)
}
@objc(logWarning:filepath:function:line:)
public static func warning(_ message: String, filepath: String = #file, function: String = #function, line: Int = #line) {
guard let d = delegate else {
defaultLogger("[WARNING] \(filename(from: filepath)).\(function): \(line) - \(message)")
return
}
d.warning?(message, filepath: filepath, function: function, line: line)
}
@objc(logError:filepath:function:line:)
public static func error(_ message: String, filepath: String = #file, function: String = #function, line: Int = #line) {
guard let d = delegate else {
defaultLogger("[ERROR] \(filename(from: filepath)).\(function): \(line) - \(message)")
return
}
d.error?(message, filepath: filepath, function: function, line: line)
}
private static func filename(from path: String, extensionIncluded: Bool = false) -> String {
let filename = (path as NSString).lastPathComponent
if !extensionIncluded {
let fileNameComponents = filename.components(separatedBy: ".")
if let firstComponent = fileNameComponents.first {
return firstComponent
}
return filename
}
return filename
}
}
| 9a31efdd4e7b96ead1a59df20333f220 | 38.808511 | 126 | 0.627205 | false | false | false | false |
fengxinsen/ReadX | refs/heads/master | ReadX/BaseWindowController.swift | mit | 1 | //
// BaseWindowController.swift
// ReadX
//
// Created by video on 2017/2/24.
// Copyright © 2017年 Von. All rights reserved.
//
import Cocoa
class BaseWindowController: NSWindowController {
open var index = 0
override var windowNibName: String? {
return "BaseWindowController"
}
override func windowDidLoad() {
super.windowDidLoad()
}
}
extension BaseWindowController {
//隐藏zoomButton
func hiddenZoomButton() {
self.window?.standardWindowButton(.zoomButton)?.isHidden = true
}
func hiddenTitleVisibility() {
self.window?.titleVisibility = .hidden
}
func titleBackgroundColor(color: NSColor) {
let titleView = self.window?.standardWindowButton(.closeButton)?.superview
titleView?.backgroundColor = color
// titleView?.wantsLayer = true
// titleView?.layer?.backgroundColor = NSColor.brown.cgColor
}
func center() {
self.window?.center()
}
func mAppDelegate() -> AppDelegate {
return NSApplication.shared().delegate as! AppDelegate
}
}
| 9c4e6c24622605f92e4ece22428f993a | 21.66 | 82 | 0.634598 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS Tests/RequestPasswordViewControllerSnapshotTests.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import Wire
final class RequestPasswordControllerSnapshotTests: XCTestCase, CoreDataFixtureTestHelper {
var coreDataFixture: CoreDataFixture!
var sut: RequestPasswordController!
var fingerprint: Data!
override func setUp() {
super.setUp()
coreDataFixture = CoreDataFixture()
fingerprint = coreDataFixture.mockUserClient(fingerprintString: "102030405060708090a0b0c0d0e0f0708090102030405060708090").fingerprint!
}
override func tearDown() {
fingerprint = nil
sut = nil
coreDataFixture = nil
super.tearDown()
}
func testForRemoveDeviceContextPasswordEntered() {
sut = RequestPasswordController(context: .removeDevice, callback: {_ in })
sut.passwordTextField?.text = "12345678"
sut.passwordTextFieldChanged(sut.passwordTextField!)
verify(matching: sut.alertController)
}
func testForRemoveDeviceContext() {
sut = RequestPasswordController(context: .removeDevice, callback: {_ in })
verify(matching: sut.alertController)
}
}
| 82e92d808f106a2e5eb1af43d3b2bad2 | 30.614035 | 142 | 0.718091 | false | true | false | false |
gitkong/FLTableViewComponent | refs/heads/master | FLComponentDemo/FLComponentDemo/FLCollectionViewFlowLayout.swift | mit | 2 | //
// FLCollectionViewFlowLayout.swift
// FLComponentDemo
//
// Created by gitKong on 2017/5/18.
// Copyright © 2017年 gitKong. All rights reserved.
//
import UIKit
typealias LayoutAttributesArray = Array<UICollectionViewLayoutAttributes>?
typealias LayoutAttributesDict = Dictionary<FLIdentifierType , LayoutAttributesArray>?
@objc enum FLCollectionViewFlowLayoutStyle : NSInteger{
case System = 0// System style, Both ends of the same spacing, the middle spacing is not equal, alignment is center
case Custom = 1// Both ends of spacing is not equal, the middle spacing is equal, alignment is top
}
class FLCollectionViewFlowLayout: UICollectionViewFlowLayout {
weak var delegate : UICollectionViewDelegateFlowLayout?
private var sectionAttributes : Array<LayoutAttributesDict> = []
var flowLayoutStyle : FLCollectionViewFlowLayoutStyle?{
didSet {
// reset
verticalTotalItemMaxY = 0
}
}
var verticalTotalItemMaxY : CGFloat = 0
var sectionInsetArray : Array<UIEdgeInsets> = []
var minimumInteritemSpacingArray : Array<CGFloat> = []
var minimumLineSpacingArray : Array<CGFloat> = []
convenience init(with flowLayoutStyle : FLCollectionViewFlowLayoutStyle = .System) {
self.init()
self.flowLayoutStyle = flowLayoutStyle
}
override init() {
super.init()
self.scrollDirection = .vertical
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepare() {
super.prepare()
if flowLayoutStyle == .System {
return
}
guard self.collectionView != nil , let sections = self.collectionView?.numberOfSections , self.delegate != nil else {
return
}
sectionAttributes.removeAll()
var currentInset : UIEdgeInsets = sectionInsetArray[0]
var currentMinimumInteritemSpacing : CGFloat = minimumInteritemSpacingArray[0]
var currentMinimumLineSpacing : CGFloat = minimumLineSpacingArray[0]
var offsetX : CGFloat = currentInset.left
var nextOffsetX : CGFloat = currentInset.left
var offsetY : CGFloat = currentInset.top
var currentRowMaxItemHeight : CGFloat = 0
var lastHeaderAttributeSize : CGSize = CGSize.zero
var lastFooterAttributeSize : CGSize = CGSize.zero
for section in 0 ..< sections {
var itemAttributes : LayoutAttributesArray = []
var attributeDict : LayoutAttributesDict = [FLIdentifierType.Cell : itemAttributes]
if let items = self.collectionView?.numberOfItems(inSection: section) {
let headerAttributeSize : CGSize = (self.delegate?.collectionView!(self.collectionView!, layout: self, referenceSizeForHeaderInSection: section))!
let headerAttribute = UICollectionViewLayoutAttributes.init(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, with: IndexPath.init(item: 0, section: section))
headerAttribute.frame = CGRect.init(origin: CGPoint.init(x: 0, y: verticalTotalItemMaxY), size: headerAttributeSize)
verticalTotalItemMaxY = 0
let footerAttribute = UICollectionViewLayoutAttributes.init(forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, with: IndexPath.init(item: 0, section: section))
//print("----- section (\(section)) ------")
for item in 0 ..< items {
let indexPath = IndexPath.init(item: item, section: section)
let attribute = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
if let itemSize = self.delegate?.collectionView!(self.collectionView!, layout: self, sizeForItemAt: indexPath) {
nextOffsetX = nextOffsetX + currentMinimumInteritemSpacing + itemSize.width
if nextOffsetX > self.collectionView!.bounds.size.width{
offsetX = currentInset.left
nextOffsetX = currentInset.left + currentMinimumInteritemSpacing + itemSize.width
offsetY = offsetY + currentRowMaxItemHeight + currentMinimumLineSpacing
//print("max item height = \(currentRowMaxItemHeight)")
// next row , compare with last itemSize
currentRowMaxItemHeight = itemSize.height
}
else {
//print("compare : \(currentRowMaxItemHeight) - \(itemSize.height)")
currentRowMaxItemHeight = max(currentRowMaxItemHeight, itemSize.height)
offsetX = nextOffsetX - (currentMinimumInteritemSpacing + itemSize.width)
}
attribute.frame = CGRect.init(x: offsetX, y: offsetY + headerAttribute.frame.size.height, width: itemSize.width, height: itemSize.height)
if item == items - 1 {
//print("last attribute frame : \(attribute.frame)")
verticalTotalItemMaxY = currentRowMaxItemHeight + attribute.frame.origin.y + currentInset.bottom
lastHeaderAttributeSize = headerAttribute.frame.size
}
}
itemAttributes!.append(attribute)
}
if let footerAttributeSize = self.delegate?.collectionView!(self.collectionView!, layout: self, referenceSizeForFooterInSection: section) {
if footerAttributeSize.height != 0 , footerAttributeSize.width != 0 {
//print("section : \(section), footerHeight : \(footerAttributeSize.height), verticalTotalItemMaxY : \(verticalTotalItemMaxY)")
footerAttribute.frame = CGRect.init(origin: CGPoint.init(x: 0, y: verticalTotalItemMaxY), size: footerAttributeSize)
verticalTotalItemMaxY = verticalTotalItemMaxY + footerAttribute.frame.size.height
if headerAttributeSize.height != 0 , headerAttributeSize.width != 0 {
//print("footer and header exist at section-\(section)")
}
else {
//print("footer exist at section-\(section), but header not")
}
offsetY = verticalTotalItemMaxY - lastHeaderAttributeSize.height + headerAttribute.frame.size.height + currentMinimumLineSpacing
lastFooterAttributeSize = footerAttribute.frame.size
}
else {
//print("section : \(section), headerAttribute : \(headerAttribute.size) verticalTotalItemMaxY : \(verticalTotalItemMaxY)")
offsetY = verticalTotalItemMaxY - lastHeaderAttributeSize.height + headerAttribute.frame.size.height + currentMinimumLineSpacing
if headerAttributeSize.height != 0 , headerAttributeSize.width != 0 {
//print("header exist at section-\(section), but footer not")
}
else {
//print("header and footer NOT exist at section-\(section)")
offsetY = offsetY + currentMinimumLineSpacing
}
}
}
else {
offsetY = verticalTotalItemMaxY - lastHeaderAttributeSize.height + headerAttribute.frame.size.height + currentMinimumLineSpacing
}
// if current header and last footer exist , just need to add minimumLineSpacing once
if lastFooterAttributeSize.height == 0 , headerAttributeSize.height == 0 {
offsetY = offsetY - currentMinimumLineSpacing
}
// reset
// next section, you should subtract the last section minimumLineSpacing
offsetY = offsetY - currentMinimumLineSpacing
if section < sections - 1 {
currentInset = sectionInsetArray[section + 1]
currentMinimumInteritemSpacing = minimumInteritemSpacingArray[section + 1]
currentMinimumLineSpacing = minimumLineSpacingArray[section + 1]
}
// add currentInset.top for next section offsetY
offsetY = offsetY + currentInset.top
offsetX = currentInset.left
nextOffsetX = offsetX
currentRowMaxItemHeight = 0
lastHeaderAttributeSize = CGSize.zero
lastFooterAttributeSize = CGSize.zero
attributeDict = [FLIdentifierType.Header : [headerAttribute], FLIdentifierType.Cell : itemAttributes, FLIdentifierType.Footer : [footerAttribute]]
}
sectionAttributes.append(attributeDict)
}
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if flowLayoutStyle == .System {
return super.layoutAttributesForItem(at: indexPath)
}
guard let attributeDict = sectionAttributes[indexPath.section] else {
return nil
}
guard let itemAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Cell] else {
return nil
}
return itemAttributes?[indexPath.item]
}
override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if flowLayoutStyle == .System {
return super.layoutAttributesForSupplementaryView(ofKind: elementKind, at:indexPath)
}
guard let attributeDict = sectionAttributes[indexPath.section] else {
return nil
}
if elementKind == UICollectionElementKindSectionHeader {
guard let headerAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Header] else {
return nil
}
return headerAttributes?.first
}
else {
guard let footerAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Footer] else {
return nil
}
return footerAttributes?.first
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
if flowLayoutStyle == .System {
return super.layoutAttributesForElements(in: rect)
}
var totalAttributes : LayoutAttributesArray = []
for attributeDict in sectionAttributes {
if let attributeDict = attributeDict {
if let headerAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Header] {
totalAttributes = totalAttributes! + headerAttributes!
}
if let itemAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Cell] {
totalAttributes = totalAttributes! + itemAttributes!
}
if let footerAttributes : LayoutAttributesArray = attributeDict[FLIdentifierType.Footer] {
totalAttributes = totalAttributes! + footerAttributes!
}
}
}
return totalAttributes?.filter({ (attribute) -> Bool in
return CGRect.intersects(rect)(attribute.frame)
})
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
if flowLayoutStyle == .System {
return super.shouldInvalidateLayout(forBoundsChange: newBounds)
}
return false
}
override var collectionViewContentSize: CGSize {
if flowLayoutStyle == .System {
return super.collectionViewContentSize
}
if verticalTotalItemMaxY == 0 {
return CGSize.zero
}
return CGSize.init(width: (self.collectionView?.frame.size.width)!, height: verticalTotalItemMaxY)
}
}
| 8e9db163504e0137ef086e16919d682a | 46.360294 | 190 | 0.586555 | false | false | false | false |
Bunn/firefox-ios | refs/heads/master | Storage/Rust/RustLogins.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
@_exported import MozillaAppServices
private let log = Logger.syncLogger
public extension LoginRecord {
convenience init(credentials: URLCredential, protectionSpace: URLProtectionSpace) {
let hostname: String
if let _ = protectionSpace.`protocol` {
hostname = protectionSpace.urlString()
} else {
hostname = protectionSpace.host
}
let httpRealm = protectionSpace.realm
let username = credentials.user
let password = credentials.password
self.init(fromJSONDict: [
"hostname": hostname,
"httpRealm": httpRealm as Any,
"username": username ?? "",
"password": password ?? ""
])
}
var credentials: URLCredential {
return URLCredential(user: username ?? "", password: password, persistence: .forSession)
}
var protectionSpace: URLProtectionSpace {
return URLProtectionSpace.fromOrigin(hostname)
}
var hasMalformedHostname: Bool {
let hostnameURL = hostname.asURL
guard let _ = hostnameURL?.host else {
return true
}
return false
}
var isValid: Maybe<()> {
// Referenced from https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginManager.js?rev=f76692f0fcf8&mark=280-281#271
// Logins with empty hostnames are not valid.
if hostname.isEmpty {
return Maybe(failure: LoginRecordError(description: "Can't add a login with an empty hostname."))
}
// Logins with empty passwords are not valid.
if password.isEmpty {
return Maybe(failure: LoginRecordError(description: "Can't add a login with an empty password."))
}
// Logins with both a formSubmitURL and httpRealm are not valid.
if let _ = formSubmitURL, let _ = httpRealm {
return Maybe(failure: LoginRecordError(description: "Can't add a login with both a httpRealm and formSubmitURL."))
}
// Login must have at least a formSubmitURL or httpRealm.
if (formSubmitURL == nil) && (httpRealm == nil) {
return Maybe(failure: LoginRecordError(description: "Can't add a login without a httpRealm or formSubmitURL."))
}
// All good.
return Maybe(success: ())
}
}
public class LoginRecordError: MaybeErrorType {
public let description: String
public init(description: String) {
self.description = description
}
}
public class RustLogins {
let databasePath: String
let encryptionKey: String
let queue: DispatchQueue
let storage: LoginsStorage
fileprivate(set) var isOpen: Bool = false
private var didAttemptToMoveToBackup = false
public init(databasePath: String, encryptionKey: String) {
self.databasePath = databasePath
self.encryptionKey = encryptionKey
self.queue = DispatchQueue(label: "RustLogins queue: \(databasePath)", attributes: [])
self.storage = LoginsStorage(databasePath: databasePath)
}
private func open() -> NSError? {
do {
try storage.unlock(withEncryptionKey: encryptionKey)
isOpen = true
return nil
} catch let err as NSError {
if let loginsStoreError = err as? LoginsStoreError {
switch loginsStoreError {
// The encryption key is incorrect, or the `databasePath`
// specified is not a valid database. This is an unrecoverable
// state unless we can move the existing file to a backup
// location and start over.
case .invalidKey(let message):
log.error(message)
if !didAttemptToMoveToBackup {
RustShared.moveDatabaseFileToBackupLocation(databasePath: databasePath)
didAttemptToMoveToBackup = true
return open()
}
case .panic(let message):
Sentry.shared.sendWithStacktrace(message: "Panicked when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: message)
default:
Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: loginsStoreError.localizedDescription)
}
} else {
Sentry.shared.sendWithStacktrace(message: "Unknown error when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription)
}
return err
}
}
private func close() -> NSError? {
do {
try storage.lock()
isOpen = false
return nil
} catch let err as NSError {
Sentry.shared.sendWithStacktrace(message: "Unknown error when closing Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription)
return err
}
}
public func reopenIfClosed() -> NSError? {
var error: NSError?
queue.sync {
guard !isOpen else { return }
error = open()
}
return error
}
public func forceClose() -> NSError? {
var error: NSError?
do {
try storage.interrupt()
} catch let err as NSError {
error = err
Sentry.shared.sendWithStacktrace(message: "Error interrupting Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription)
}
queue.sync {
guard isOpen else { return }
error = close()
}
return error
}
public func sync(unlockInfo: SyncUnlockInfo) -> Success {
let deferred = Success()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
try self.storage.sync(unlockInfo: unlockInfo)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
if let loginsStoreError = err as? LoginsStoreError {
switch loginsStoreError {
case .panic(let message):
Sentry.shared.sendWithStacktrace(message: "Panicked when syncing Logins database", tag: SentryTag.rustLogins, severity: .error, description: message)
default:
Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when syncing Logins database", tag: SentryTag.rustLogins, severity: .error, description: loginsStoreError.localizedDescription)
}
}
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func get(id: String) -> Deferred<Maybe<LoginRecord?>> {
let deferred = Deferred<Maybe<LoginRecord?>>()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
let record = try self.storage.get(id: id)
deferred.fill(Maybe(success: record))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func searchLoginsWithQuery(_ query: String?) -> Deferred<Maybe<Cursor<LoginRecord>>> {
return list().bind({ result in
if let error = result.failureValue {
return deferMaybe(error)
}
guard let records = result.successValue else {
return deferMaybe(ArrayCursor(data: []))
}
guard let query = query?.lowercased(), !query.isEmpty else {
return deferMaybe(ArrayCursor(data: records))
}
let filteredRecords = records.filter({
$0.hostname.lowercased().contains(query) ||
($0.username?.lowercased() ?? "").contains(query)
})
return deferMaybe(ArrayCursor(data: filteredRecords))
})
}
public func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace, withUsername username: String? = nil) -> Deferred<Maybe<Cursor<LoginRecord>>> {
return list().bind({ result in
if let error = result.failureValue {
return deferMaybe(error)
}
guard let records = result.successValue else {
return deferMaybe(ArrayCursor(data: []))
}
let filteredRecords: [LoginRecord]
if let username = username {
filteredRecords = records.filter({
$0.username == username && (
$0.hostname == protectionSpace.urlString() ||
$0.hostname == protectionSpace.host
)
})
} else {
filteredRecords = records.filter({
$0.hostname == protectionSpace.urlString() ||
$0.hostname == protectionSpace.host
})
}
return deferMaybe(ArrayCursor(data: filteredRecords))
})
}
public func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
return list().bind({ result in
if let error = result.failureValue {
return deferMaybe(error)
}
return deferMaybe((result.successValue?.count ?? 0) > 0)
})
}
public func list() -> Deferred<Maybe<[LoginRecord]>> {
let deferred = Deferred<Maybe<[LoginRecord]>>()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
let records = try self.storage.list()
deferred.fill(Maybe(success: records))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func add(login: LoginRecord) -> Deferred<Maybe<String>> {
let deferred = Deferred<Maybe<String>>()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
let id = try self.storage.add(login: login)
deferred.fill(Maybe(success: id))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func use(login: LoginRecord) -> Success {
login.timesUsed += 1
login.timeLastUsed = Int64(Date.nowMicroseconds())
return update(login: login)
}
public func update(login: LoginRecord) -> Success {
let deferred = Success()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
try self.storage.update(login: login)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func delete(ids: [String]) -> Deferred<[Maybe<Bool>]> {
return all(ids.map({ delete(id: $0) }))
}
public func delete(id: String) -> Deferred<Maybe<Bool>> {
let deferred = Deferred<Maybe<Bool>>()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
let existed = try self.storage.delete(id: id)
deferred.fill(Maybe(success: existed))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func reset() -> Success {
let deferred = Success()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
try self.storage.reset()
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func wipeLocal() -> Success {
let deferred = Success()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
try self.storage.wipeLocal()
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
}
| 667ef6c58313f16438812ff47b9186f7 | 32.391101 | 222 | 0.563193 | false | false | false | false |
windaddict/ARFun | refs/heads/master | ARFun.playground/Pages/Waypoint.xcplaygroundpage/Contents.swift | mit | 1 | /*
* Copyright 2017 John M. P. Knox
* Licensed under the MIT License - see license file
*/
import UIKit
import ARKit
import PlaygroundSupport
import MapKit
/**
* A starting point for placing AR content at real world coordinates in Swift Playgrounds 2
* Note since location services don't work in Playgrounds, the user has to manually pick
* their starting location and the AR location on a map before starting. If the compass isn't
* calibrated, the AR content won't place accurately.
*/
class WaypointNavigator: NSObject{
let mapView = MKMapView()
let debugView = ARDebugView()
///0: no locations, 1: start location marked, 2: destination marked
var mapState = 0
var start: CLLocationCoordinate2D? = nil
var destination: CLLocationCoordinate2D? = nil
var arDisplay: WayPointDisplay?
override init(){
super.init()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped(gestureRecognizer:)))
mapView.addGestureRecognizer(tapGestureRecognizer)
debugView.translatesAutoresizingMaskIntoConstraints = false
//add the debug view
mapView.addSubview(debugView)
mapView.leadingAnchor.constraint(equalTo: debugView.leadingAnchor)
mapView.topAnchor.constraint(equalTo: debugView.topAnchor)
PlaygroundPage.current.liveView = mapView
}
@objc func viewTapped(gestureRecognizer: UITapGestureRecognizer){
let tapPoint = gestureRecognizer.location(in: mapView)
let tapLocation = mapView.convert(tapPoint, toCoordinateFrom: mapView)
debugView.log("tapped: \(tapLocation)")
switch mapState{
case 0: //wait for the user to tap their starting location
start = tapLocation
mapState = 1
case 1: //wait for the user to tap their destination
destination = tapLocation
mapState = 2
case 2: //calculate the distances between the start and destination, show the ar display
guard let start = start, let destination = destination else {
debugView.log("Error: either start or destination didn't exist")
return
}
let (distanceSouth, distanceEast) = distances(start: start, destination: destination)
let display = WayPointDisplay()
arDisplay = display
PlaygroundPage.current.liveView = display.view
display.distanceSouth = distanceSouth
display.distanceEast = distanceEast
mapState = 0 //return to initial state
default :
mapState = 0
debugView.log("Error: hit default case")
}
}
///an approximation that returns the number of meters south and east the destination is from the start
func distances(start: CLLocationCoordinate2D, destination: CLLocationCoordinate2D)->(Double, Double){
//east / longitude
let lonStart = CLLocation(latitude: start.latitude, longitude: start.longitude)
let lonDest = CLLocation(latitude: start.latitude, longitude: destination.longitude)
var distanceEast = lonStart.distance(from: lonDest)
let directionMultiplier = destination.longitude >= start.longitude ? 1.0 : -1.0
distanceEast = distanceEast * directionMultiplier
//south / latitude
let latDest = CLLocation(latitude: destination.latitude, longitude: start.longitude)
var distanceSouth = lonStart.distance(from: latDest)
let latMultiplier = destination.latitude >= start.latitude ? -1.0 : 1.0
distanceSouth = latMultiplier * distanceSouth
return (distanceSouth, distanceEast)
}
}
class WayPointDisplay: NSObject, ARSCNViewDelegate {
///the distance south of the world origin to place the waypoint
var distanceSouth: Double = 0.0
///the distance east of the world origin to place the waypoint
var distanceEast: Double = 0.0
///maps ARAnchors to SCNNodes
var nodeDict = [UUID:SCNNode]()
//mark: ARSCNViewDelegate
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
if let node = nodeDict[anchor.identifier] {
return node
}
return nil
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
DispatchQueue.main.async { [weak self] in
self?.debugView.log("updated node")
}
}
let arSessionConfig = ARWorldTrackingConfiguration()
let debugView = ARDebugView()
var view:ARSCNView? = nil
let scene = SCNScene()
let useScenekit = true
override init(){
super.init()
let frame = CGRect(x: 0.0, y: 0, width: 100, height: 100)
let arView = ARSCNView(frame: frame)
//configure the ARSCNView
arView.debugOptions = [
ARSCNDebugOptions.showWorldOrigin,
ARSCNDebugOptions.showFeaturePoints,
// SCNDebugOptions.showLightInfluences,
// SCNDebugOptions.showWireframe
]
arView.showsStatistics = true
arView.automaticallyUpdatesLighting = true
debugView.translatesAutoresizingMaskIntoConstraints = false
//add the debug view
arView.addSubview(debugView)
arView.leadingAnchor.constraint(equalTo: debugView.leadingAnchor)
arView.topAnchor.constraint(equalTo: debugView.topAnchor)
view = arView
arView.scene = scene
//setup session config
if !ARWorldTrackingConfiguration.isSupported { return }
arSessionConfig.planeDetection = .horizontal
arSessionConfig.worldAlignment = .gravityAndHeading //y-axis points UP, x points E (longitude), z points S (latitude)
arSessionConfig.isLightEstimationEnabled = true
arView.session.run(arSessionConfig, options: [.resetTracking, .removeExistingAnchors])
arView.delegate = self
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped(gestureRecognizer:)))
view?.addGestureRecognizer(gestureRecognizer)
}
let shouldAddAnchorsForNodes = true
func addNode(node: SCNNode, worldTransform: matrix_float4x4) {
let anchor = ARAnchor(transform: worldTransform)
let position = vectorFrom(transform: worldTransform)
node.position = position
node.rotation = SCNVector4(x: 1, y: 1, z: 0, w: 0)
nodeDict[anchor.identifier] = node
if shouldAddAnchorsForNodes {
view?.session.add(anchor: anchor)
} else {
scene.rootNode.addChildNode(node)
}
}
///adds a 200M high cylinder at worldTransform
func addAntenna(worldTransform: matrix_float4x4 = matrix_identity_float4x4) {
let height = 200 as Float
let cylinder = SCNCylinder(radius: 0.5, height: CGFloat(height))
cylinder.firstMaterial?.diffuse.contents = UIColor(red: 0.4, green: 0, blue: 0, alpha: 1)
cylinder.firstMaterial?.specular.contents = UIColor.white
//raise the cylinder so the base is positioned at the worldTransform
var transform = matrix_identity_float4x4
transform.columns.3.y = height / 2
let finalTransform = matrix_multiply(worldTransform, transform)
let cylinderNode = SCNNode(geometry:cylinder)
addNode(node: cylinderNode, worldTransform: finalTransform)
}
///when the user taps, add a waypoint antenna at distanceEast, distanceSouth from the origin
@objc func viewTapped(gestureRecognizer: UITapGestureRecognizer){
debugView.log("DE: \(distanceEast) DS: \(distanceSouth)")
var transform = matrix_identity_float4x4
transform.columns.3.x = Float(distanceEast)
transform.columns.3.z = Float(distanceSouth)
addAntenna(worldTransform: transform)
}
///convert a transform matrix_float4x4 to a SCNVector3
func vectorFrom(transform: matrix_float4x4) -> SCNVector3 {
return SCNVector3Make(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z)
}
}
let mapper = WaypointNavigator()
PlaygroundPage.current.needsIndefiniteExecution = true
| fd95d144dcb9fcc65decb3ba044dad82 | 40.954774 | 125 | 0.669421 | false | false | false | false |
szk-atmosphere/MartyJunior | refs/heads/master | MartyJunior/MJTableViewTopCell.swift | mit | 1 | //
// MJTableViewTopCell.swift
// MartyJunior
//
// Created by 鈴木大貴 on 2015/11/26.
// Copyright © 2015年 Taiki Suzuki. All rights reserved.
//
import UIKit
import MisterFusion
class MJTableViewTopCell: UITableViewCell {
static let ReuseIdentifier: String = "MJTableViewTopCell"
weak var mainContentView: MJContentView? {
didSet {
guard let mainContentView = mainContentView else { return }
contentView.addLayoutSubview(mainContentView, andConstraints:
mainContentView.top,
mainContentView.left,
mainContentView.right,
mainContentView.height |==| mainContentView.currentHeight
)
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
initialize()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func initialize() {
selectionStyle = .none
}
}
| 4d6fc27df902348936c247a23f96dedc | 26.1 | 74 | 0.639299 | false | false | false | false |
kaushaldeo/Olympics | refs/heads/master | Olympics/Views/KDRankingCell.swift | apache-2.0 | 1 | //
// KDRankingCell.swift
// Olympics
//
// Created by Kaushal Deo on 7/25/16.
// Copyright © 2016 Scorpion Inc. All rights reserved.
//
import UIKit
class KDRankingCell: UITableViewCell {
@IBOutlet weak var tableView: UITableView!
var competitors = [Competitor]() {
didSet {
self.tableView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// MARK: - Table view data source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.competitors.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Configure the cell...
let cell = tableView.dequeueReusableCellWithIdentifier("Rank", forIndexPath: indexPath) as! KDResultViewCell
let competitor = self.competitors[indexPath.row]
cell.nameLabel.text = competitor.name()
if let text = competitor.iconName() {
cell.iconView.image = UIImage(named: "Images/\(text).png")
}
cell.rankLabel.text = competitor.rank ?? "-"
if let string = competitor.resultValue {
cell.resultLabel.text = string
}
else if let unit = competitor.unit {
let status = unit.statusValue()
if status != "closed" && status != "progress" {
cell.resultLabel.text = competitor.unit?.startDate?.time()
}
else if let string = competitor.resultType {
cell.resultLabel.text = string == "irm" ? "DNF" : ""
}
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let competitor = self.competitors[indexPath.row]
var height = CGFloat(0)
let string = competitor.resultValue ?? ""
let width = string.size(UIFont.systemFontOfSize(14), width: (CGRectGetWidth(tableView.frame) - 80)).width + 80.0
if let text = competitor.name() {
height += text.size(UIFont.systemFontOfSize(14), width:CGRectGetWidth(tableView.frame) - width).height + 24
}
return height
}
}
| 69582111169e25e5bb7d979c8fd1f878 | 30.924051 | 124 | 0.603489 | false | false | false | false |
garygriswold/Bible.js | refs/heads/master | SafeBible2/SafeBible_ios/SafeBible/Adapters/BiblePageModel.swift | mit | 1 | //
// BiblePageModel.swift
// Settings
//
// Created by Gary Griswold on 10/25/18.
// Copyright © 2018 ShortSands. All rights reserved.
//
// Bible.objectKey contains codes that define String replacements
// %I := Id in last part of s3KeyPrefix
// %O := ordinal 1 is GEN, 70 is MAT, not zero filled
// %o := 3 char ordinal A01 is GEN, zero filled
// %B := USFM 3 char book code
// %b := 2 char book code
// %C := chapter number, not zero filled
// %c := chapter number, zero filled, 2 char, 3 Psalms
//
import AWS
import WebKit
struct BiblePageModel {
func loadPage(reference: Reference, webView: WKWebView, controller: UIViewController) {
self.getChapter(reference: reference, view: webView, complete: { html in
if html != nil {
let page = DynamicCSS.shared.wrapHTML(html: html!, reference: reference)
webView.loadHTMLString(page, baseURL: nil)
} else {
// Usually an error occurs because the book does not exist in this Bible
TOCBooksViewController.push(controller: controller)
}
})
}
func loadCompareVerseCell(reference: Reference, startVerse: Int, endVerse: Int,
cell: CompareVerseCell, table: UITableView, indexPath: IndexPath) {
self.getChapter(reference: reference, view: cell.contentView, complete: { html in
if html != nil {
cell.verse.text = self.parse(html: html!, reference: reference,
startVerse: startVerse, endVerse: endVerse)
table.reloadRows(at: [indexPath], with: .automatic)
}
})
}
/**
* I guess the correct way to pass back a string is to pass in a Writable Key Path, but I don't understand it.
*/
func loadLabel(reference: Reference, verse: Int, label: UILabel) {
self.getChapter(reference: reference, view: nil, complete: { html in
if html != nil {
var result = self.parse(html: html!, reference: reference, startVerse: verse, endVerse: verse)
result = result.replacingOccurrences(of: String(verse), with: "")
label.text = result.trimmingCharacters(in: .whitespacesAndNewlines)
}
})
}
/** Used by HTMLVerseParserTest */
func testParse(reference: Reference, lastVerse: Int, complete: @escaping () -> Void) {
self.getChapter(reference: reference, view: nil, complete: { html in
for verse in 1..<(lastVerse + 1) {
let result = self.parse(html: html!, reference: reference, startVerse: verse,
endVerse: verse)
if result.count < 5 {
print("PARSE ERROR \(reference):\(verse) |\(result)|")
}
}
complete()
})
}
private func parse(html: String, reference: Reference, startVerse: Int, endVerse: Int) -> String {
if reference.isDownloaded {
return BibleDB.shared.getBibleVerses(reference: reference, startVerse: startVerse,
endVerse: endVerse)
} else if reference.isShortsands {
let parser = HTMLVerseParserSS(html: html, startVerse: startVerse, endVerse: endVerse)
return parser.parseVerses()
} else {
let parser = HTMLVerseParserDBP(html: html, startVerse: startVerse, endVerse: endVerse)
return parser.parseVerses()
}
}
private func getChapter(reference: Reference, view: UIView?, complete: @escaping (_ data:String?) -> Void) {
let start = CFAbsoluteTimeGetCurrent()
let html = BibleDB.shared.getBiblePage(reference: reference)
if html == nil {
let progress = self.addProgressIndicator(view: view)
let s3Key = self.generateKey(reference: reference)
let s3 = (reference.isShortsands) ? AwsS3Manager.findSS() : AwsS3Manager.findDbp()
s3.downloadText(s3Bucket: reference.bible.textBucket, s3Key: s3Key, complete: { error, data in
self.removeProgressIndicator(indicator: progress)
if let err = error {
print("ERROR: \(err)")
complete(nil)
}
else if let data1 = data {
complete(data1)
print("AWS Load \(reference.toString())")
_ = BibleDB.shared.storeBiblePage(reference: reference, html: data1)
print("*** BiblePageModel.getChapter duration \((CFAbsoluteTimeGetCurrent() - start) * 1000) ms")
}
})
} else {
complete(html)
print("DB Load \(reference.toString())")
}
}
private func addProgressIndicator(view: UIView?) -> UIActivityIndicatorView? {
if view != nil {
let style: UIActivityIndicatorView.Style = AppFont.nightMode ? .white : .gray
let progress = UIActivityIndicatorView(style: style)
progress.frame = CGRect(x: 40, y: 40, width: 0, height: 0)
view!.addSubview(progress)
progress.startAnimating()
return progress
} else {
return nil
}
}
private func removeProgressIndicator(indicator: UIActivityIndicatorView?) {
if indicator != nil {
indicator!.stopAnimating()
indicator!.removeFromSuperview()
}
}
private func generateKey(reference: Reference) -> String {
var result = [String]()
var inItem = false
for char: Character in reference.s3TextTemplate {
if char == "%" {
inItem = true
} else if !inItem {
result.append(String(char))
} else {
inItem = false
switch char {
case "I": // Id is last part of s3KeyPrefix
let parts = reference.s3TextPrefix.split(separator: "/")
result.append(String(parts[parts.count - 1]))
case "O": // ordinal 1 is GEN, 70 is MAT, not zero filled
if let seq = bookMap[reference.bookId]?.seq {
result.append(seq)
}
case "o": // 3 char ordinal A01 is GEN, zero filled
if let seq3 = bookMap[reference.bookId]?.seq3 {
result.append(seq3)
}
case "B": // USFM 3 char book code
result.append(reference.bookId)
case "b": // 2 char book code
if let id2 = bookMap[reference.bookId]?.id2 {
result.append(id2)
}
case "C": // chapter number, not zero filled
if reference.chapter > 0 {
result.append(String(reference.chapter))
} else {
result.removeLast() // remove the underscore that would preceed chapter
}
case "d": // chapter number, 2 char zero filled, Psalms 3 char
var chapStr = String(reference.chapter)
if chapStr.count == 1 {
chapStr = "0" + chapStr
}
if chapStr.count == 2 && reference.bookId == "PSA" {
chapStr = "0" + chapStr
}
result.append(chapStr)
default:
print("ERROR: Unknown format char %\(char)")
}
}
}
return reference.s3TextPrefix + "/" + result.joined()
}
struct BookData {
let seq: String
let seq3: String
let id2: String
}
let bookMap: [String: BookData] = [
"FRT": BookData(seq: "0", seq3: "?", id2: "?"),
"GEN": BookData(seq: "2", seq3: "A01", id2: "GN"),
"EXO": BookData(seq: "3", seq3: "A02", id2: "EX"),
"LEV": BookData(seq: "4", seq3: "A03", id2: "LV"),
"NUM": BookData(seq: "5", seq3: "A04", id2: "NU"),
"DEU": BookData(seq: "6", seq3: "A05", id2: "DT"),
"JOS": BookData(seq: "7", seq3: "A06", id2: "JS"),
"JDG": BookData(seq: "8", seq3: "A07", id2: "JG"),
"RUT": BookData(seq: "9", seq3: "A08", id2: "RT"),
"1SA": BookData(seq: "10", seq3: "A09", id2: "S1"),
"2SA": BookData(seq: "11", seq3: "A10", id2: "S2"),
"1KI": BookData(seq: "12", seq3: "A11", id2: "K1"),
"2KI": BookData(seq: "13", seq3: "A12", id2: "K2"),
"1CH": BookData(seq: "14", seq3: "A13", id2: "R1"),
"2CH": BookData(seq: "15", seq3: "A14", id2: "R2"),
"EZR": BookData(seq: "16", seq3: "A15", id2: "ER"),
"NEH": BookData(seq: "17", seq3: "A16", id2: "NH"),
"EST": BookData(seq: "18", seq3: "A17", id2: "ET"),
"JOB": BookData(seq: "19", seq3: "A18", id2: "JB"),
"PSA": BookData(seq: "20", seq3: "A19", id2: "PS"),
"PRO": BookData(seq: "21", seq3: "A20", id2: "PR"),
"ECC": BookData(seq: "22", seq3: "A21", id2: "EC"),
"SNG": BookData(seq: "23", seq3: "A22", id2: "SS"),
"ISA": BookData(seq: "24", seq3: "A23", id2: "IS"),
"JER": BookData(seq: "25", seq3: "A24", id2: "JR"),
"LAM": BookData(seq: "26", seq3: "A25", id2: "LM"),
"EZK": BookData(seq: "27", seq3: "A26", id2: "EK"),
"DAN": BookData(seq: "28", seq3: "A27", id2: "DN"),
"HOS": BookData(seq: "29", seq3: "A28", id2: "HS"),
"JOL": BookData(seq: "30", seq3: "A29", id2: "JL"),
"AMO": BookData(seq: "31", seq3: "A30", id2: "AM"),
"OBA": BookData(seq: "32", seq3: "A31", id2: "OB"),
"JON": BookData(seq: "33", seq3: "A32", id2: "JH"),
"MIC": BookData(seq: "34", seq3: "A33", id2: "MC"),
"NAM": BookData(seq: "35", seq3: "A34", id2: "NM"),
"HAB": BookData(seq: "36", seq3: "A35", id2: "HK"),
"ZEP": BookData(seq: "37", seq3: "A36", id2: "ZP"),
"HAG": BookData(seq: "38", seq3: "A37", id2: "HG"),
"ZEC": BookData(seq: "39", seq3: "A38", id2: "ZC"),
"MAL": BookData(seq: "40", seq3: "A39", id2: "ML"),
"TOB": BookData(seq: "41", seq3: "?", id2: "?"),
"JDT": BookData(seq: "42", seq3: "?", id2: "?"),
"ESG": BookData(seq: "43", seq3: "?", id2: "?"),
"WIS": BookData(seq: "45", seq3: "?", id2: "?"),
"SIR": BookData(seq: "46", seq3: "?", id2: "?"),
"BAR": BookData(seq: "47", seq3: "?", id2: "?"),
"LJE": BookData(seq: "48", seq3: "?", id2: "?"),
"S3Y": BookData(seq: "49", seq3: "?", id2: "?"),
"SUS": BookData(seq: "50", seq3: "?", id2: "?"),
"BEL": BookData(seq: "51", seq3: "?", id2: "?"),
"1MA": BookData(seq: "52", seq3: "?", id2: "?"),
"2MA": BookData(seq: "53", seq3: "?", id2: "?"),
"1ES": BookData(seq: "54", seq3: "?", id2: "?"),
"MAN": BookData(seq: "55", seq3: "?", id2: "?"),
"3MA": BookData(seq: "57", seq3: "?", id2: "?"),
"4MA": BookData(seq: "59", seq3: "?", id2: "?"),
"MAT": BookData(seq: "70", seq3: "B01", id2: "MT"),
"MRK": BookData(seq: "71", seq3: "B02", id2: "MK"),
"LUK": BookData(seq: "72", seq3: "B03", id2: "LK"),
"JHN": BookData(seq: "73", seq3: "B04", id2: "JN"),
"ACT": BookData(seq: "74", seq3: "B05", id2: "AC"),
"ROM": BookData(seq: "75", seq3: "B06", id2: "RM"),
"1CO": BookData(seq: "76", seq3: "B07", id2: "C1"),
"2CO": BookData(seq: "77", seq3: "B08", id2: "C2"),
"GAL": BookData(seq: "78", seq3: "B09", id2: "GL"),
"EPH": BookData(seq: "79", seq3: "B10", id2: "EP"),
"PHP": BookData(seq: "80", seq3: "B11", id2: "PP"),
"COL": BookData(seq: "81", seq3: "B12", id2: "CL"),
"1TH": BookData(seq: "82", seq3: "B13", id2: "H1"),
"2TH": BookData(seq: "83", seq3: "B14", id2: "H2"),
"1TI": BookData(seq: "84", seq3: "B15", id2: "T1"),
"2TI": BookData(seq: "85", seq3: "B16", id2: "T2"),
"TIT": BookData(seq: "86", seq3: "B17", id2: "TT"),
"PHM": BookData(seq: "87", seq3: "B18", id2: "PM"),
"HEB": BookData(seq: "88", seq3: "B19", id2: "HB"),
"JAS": BookData(seq: "89", seq3: "B20", id2: "JM"),
"1PE": BookData(seq: "90", seq3: "B21", id2: "P1"),
"2PE": BookData(seq: "91", seq3: "B22", id2: "P2"),
"1JN": BookData(seq: "92", seq3: "B23", id2: "J1"),
"2JN": BookData(seq: "93", seq3: "B24", id2: "J2"),
"3JN": BookData(seq: "94", seq3: "B25", id2: "J3"),
"JUD": BookData(seq: "95", seq3: "B26", id2: "JD"),
"REV": BookData(seq: "96", seq3: "B27", id2: "RV"),
"BAK": BookData(seq: "97", seq3: "?", id2: "?"),
"GLO": BookData(seq: "106", seq3: "?", id2: "?")
]
}
| 8b67847252f463900986c4adbc6641b7 | 45.902527 | 117 | 0.504233 | false | false | false | false |
ZENTRALALEX/LeafEditor | refs/heads/master | Sources/App/main.swift | mit | 1 | import Vapor
import Foundation
let drop = Droplet()
var nodes = [Node(["one": "One", "two": "Two", "three": Node(["one": "One", "sub": "Two"])])]
drop.post("leaf/save") { request in
guard let leaf = request.data["leaf"]?.string else {
return try JSON(node: ["error": "Failed to find leaf string.",
"description": nil])
}
do {
try leaf.write(toFile: drop.resourcesDir + "/Views/written.leaf", atomically: false, encoding: String.Encoding.utf8)
} catch {
print("could not write leaf")
}
return try JSON(node: ["error": nil,
"description": "Successfully wrote .leaf file."])
}
drop.get { req in
do {
let directoryContents = try FileManager.default.contentsOfDirectory(atPath: drop.resourcesDir + "/Views/")
let node = try directoryContents.makeNode()
let editorContent = try drop.view.make("written").makeBytes()
let file = try String(contentsOfFile: drop.resourcesDir + "/Views/written.leaf", encoding: String.Encoding.utf8)
print(directoryContents);
return try drop.view.make("written", [
"messages": node,
"editorContent" : file
])
} catch {
print("failed to read leaf files or written.leaf")
}
return try drop.view.make("welcome", [
"message": Node([])
])
}
drop.resource("posts", PostController())
drop.run()
| f0ff13aad21ce7e7e9c2000026e3c3dd | 27.921569 | 124 | 0.581695 | false | false | false | false |
ianrahman/HackerRankChallenges | refs/heads/master | Swift/Data Structures/Arrays/dynamic-array.swift | mit | 1 | import Foundation
// define initial values
var lastAns = 0
let params = readLine()!.components(separatedBy: " ").map{ Int($0)! }
let sequencesCount = params[0]
let queriesCount = params[1]
var seqList = [[Int]]()
// create necessary number of empty sequences
for _ in 0..<sequencesCount {
seqList.append([Int]())
}
// define query types
enum QueryType: Int {
case type1 = 1, type2
}
// read each query
for _ in 0..<queriesCount {
// define temp values
let query = readLine()!.components(separatedBy: " ").map{ Int($0)! }
let x = query[1]
let y = query[2]
let xor = x ^ lastAns
let index = (x ^ lastAns) % sequencesCount
// perform query
if let type = QueryType(rawValue: query[0]) {
switch type {
case .type1:
seqList[index].append(y)
case .type2:
let size = seqList[index].count
let value = seqList[index][y % size]
lastAns = value
print(lastAns)
}
}
}
| e280a15e3c602cc584d569a1a8f2615e | 22.714286 | 72 | 0.591365 | false | false | false | false |
OneBestWay/EasyCode | refs/heads/master | Mah Income/Pods/Fakery/Source/Generators/Commerce.swift | mit | 3 | import Foundation
public final class Commerce: Generator {
public func color() -> String {
return generate("commerce.color")
}
public func department(maximum: Int = 3, fixedAmount: Bool = false) -> String {
let amount = fixedAmount ? maximum : 1 + Int(arc4random_uniform(UInt32(maximum)))
let fetchedCategories = categories(amount)
let count = fetchedCategories.count
var department = ""
if count > 1 {
department = merge(categories: fetchedCategories)
} else if count == 1 {
department = fetchedCategories[0]
}
return department
}
public func productName() -> String {
return generate("commerce.product_name.adjective") + " "
+ generate("commerce.product_name.material") + " "
+ generate("commerce.product_name.product")
}
public func price() -> Double {
let arc4randoMax:Double = 0x100000000
return floor(Double((Double(arc4random()) / arc4randoMax) * 100.0) * 100) / 100.0
}
// MARK: - Helpers
public func categories(_ amount: Int) -> [String] {
var categories: [String] = []
while categories.count < amount {
let category = generate("commerce.department")
if !categories.contains(category) {
categories.append(category)
}
}
return categories
}
public func merge(categories: [String]) -> String {
let separator = generate("separator")
let commaSeparated = categories[0..<categories.count - 1].joined(separator: ", ")
return commaSeparated + separator + categories.last!
}
}
| 660eed7d3e59e47fe733676196042f44 | 25.186441 | 85 | 0.654369 | false | false | false | false |
GongChengKuangShi/DYZB | refs/heads/master | DesignBox/Pods/Kingfisher/Sources/Image.swift | mit | 2 | //
// Image.swift
// Kingfisher
//
// Created by Wei Wang on 16/1/6.
//
// Copyright (c) 2017 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
private var imagesKey: Void?
private var durationKey: Void?
#else
import UIKit
import MobileCoreServices
private var imageSourceKey: Void?
#endif
private var animatedImageDataKey: Void?
import ImageIO
import CoreGraphics
#if !os(watchOS)
import Accelerate
import CoreImage
#endif
// MARK: - Image Properties
extension Kingfisher where Base: Image {
fileprivate(set) var animatedImageData: Data? {
get {
return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data
}
set {
objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
#if os(macOS)
var cgImage: CGImage? {
return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
}
var scale: CGFloat {
return 1.0
}
fileprivate(set) var images: [Image]? {
get {
return objc_getAssociatedObject(base, &imagesKey) as? [Image]
}
set {
objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate(set) var duration: TimeInterval {
get {
return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0
}
set {
objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var size: CGSize {
return base.representations.reduce(CGSize.zero, { size, rep in
return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh)))
})
}
#else
var cgImage: CGImage? {
return base.cgImage
}
var scale: CGFloat {
return base.scale
}
var images: [Image]? {
return base.images
}
var duration: TimeInterval {
return base.duration
}
fileprivate(set) var imageSource: ImageSource? {
get {
return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource
}
set {
objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var size: CGSize {
return base.size
}
#endif
}
// MARK: - Image Conversion
extension Kingfisher where Base: Image {
#if os(macOS)
static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
return Image(cgImage: cgImage, size: CGSize.zero)
}
/**
Normalize the image. This method does nothing in OS X.
- returns: The image itself.
*/
public var normalized: Image {
return base
}
static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? {
return nil
}
#else
static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
if let refImage = refImage {
return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation)
} else {
return Image(cgImage: cgImage, scale: scale, orientation: .up)
}
}
/**
Normalize the image. This method will try to redraw an image with orientation and scale considered.
- returns: The normalized image with orientation set to up and correct scale.
*/
public var normalized: Image {
// prevent animated image (GIF) lose it's images
guard images == nil else { return base }
// No need to do anything if already up
guard base.imageOrientation != .up else { return base }
return draw(cgImage: nil, to: size) {
base.draw(in: CGRect(origin: CGPoint.zero, size: size))
}
}
static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? {
return .animatedImage(with: images, duration: duration)
}
#endif
}
// MARK: - Image Representation
extension Kingfisher where Base: Image {
// MARK: - PNG
public func pngRepresentation() -> Data? {
#if os(macOS)
guard let cgimage = cgImage else {
return nil
}
let rep = NSBitmapImageRep(cgImage: cgimage)
return rep.representation(using: .PNG, properties: [:])
#else
return UIImagePNGRepresentation(base)
#endif
}
// MARK: - JPEG
public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
#if os(macOS)
guard let cgImage = cgImage else {
return nil
}
let rep = NSBitmapImageRep(cgImage: cgImage)
return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality])
#else
return UIImageJPEGRepresentation(base, compressionQuality)
#endif
}
// MARK: - GIF
public func gifRepresentation() -> Data? {
return animatedImageData
}
}
// MARK: - Create images from data
extension Kingfisher where Base: Image {
static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool, onlyFirstFrame: Bool = false) -> Image? {
func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? {
//Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
func frameDuration(from gifInfo: NSDictionary?) -> Double {
let gifDefaultFrameDuration = 0.100
guard let gifInfo = gifInfo else {
return gifDefaultFrameDuration
}
let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
let duration = unclampedDelayTime ?? delayTime
guard let frameDuration = duration else { return gifDefaultFrameDuration }
return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
}
let frameCount = CGImageSourceGetCount(imageSource)
var images = [Image]()
var gifDuration = 0.0
for i in 0 ..< frameCount {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
return nil
}
if frameCount == 1 {
// Single frame
gifDuration = Double.infinity
} else {
// Animated GIF
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else {
return nil
}
let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary
gifDuration += frameDuration(from: gifInfo)
}
images.append(Kingfisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil))
if onlyFirstFrame { break }
}
return (images, gifDuration)
}
// Start of kf.animatedImageWithGIFData
let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else {
return nil
}
#if os(macOS)
guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
return nil
}
let image: Image?
if onlyFirstFrame {
image = images.first
} else {
image = Image(data: data)
image?.kf.images = images
image?.kf.duration = gifDuration
}
image?.kf.animatedImageData = data
return image
#else
let image: Image?
if preloadAll || onlyFirstFrame {
guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil }
image = onlyFirstFrame ? images.first : Kingfisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration)
} else {
image = Image(data: data)
image?.kf.imageSource = ImageSource(ref: imageSource)
}
image?.kf.animatedImageData = data
return image
#endif
}
static func image(data: Data, scale: CGFloat, preloadAllAnimationData: Bool, onlyFirstFrame: Bool) -> Image? {
var image: Image?
#if os(macOS)
switch data.kf.imageFormat {
case .JPEG:
image = Image(data: data)
case .PNG:
image = Image(data: data)
case .GIF:
image = Kingfisher<Image>.animated(
with: data,
scale: scale,
duration: 0.0,
preloadAll: preloadAllAnimationData,
onlyFirstFrame: onlyFirstFrame)
case .unknown:
image = Image(data: data)
}
#else
switch data.kf.imageFormat {
case .JPEG:
image = Image(data: data, scale: scale)
case .PNG:
image = Image(data: data, scale: scale)
case .GIF:
image = Kingfisher<Image>.animated(
with: data,
scale: scale,
duration: 0.0,
preloadAll: preloadAllAnimationData,
onlyFirstFrame: onlyFirstFrame)
case .unknown:
image = Image(data: data, scale: scale)
}
#endif
return image
}
}
// MARK: - Image Transforming
extension Kingfisher where Base: Image {
// MARK: - Round Corner
/// Create a round corner image based on `self`.
///
/// - parameter radius: The round corner radius of creating image.
/// - parameter size: The target size of creating image.
/// - parameter corners: The target corners which will be applied rounding.
///
/// - returns: An image with round corner of `self`.
///
/// - Note: This method only works for CG-based image.
public func image(withRoundRadius radius: CGFloat,
fit size: CGSize,
roundingCorners corners: RectCorner = .all) -> Image
{
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
return base
}
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return draw(cgImage: cgImage, to: size) {
#if os(macOS)
let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius)
path.windingRule = .evenOddWindingRule
path.addClip()
base.draw(in: rect)
#else
guard let context = UIGraphicsGetCurrentContext() else {
assertionFailure("[Kingfisher] Failed to create CG context for image.")
return
}
let path = UIBezierPath(roundedRect: rect,
byRoundingCorners: corners.uiRectCorner,
cornerRadii: CGSize(width: radius, height: radius)).cgPath
context.addPath(path)
context.clip()
base.draw(in: rect)
#endif
}
}
#if os(iOS) || os(tvOS)
func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image {
switch contentMode {
case .scaleAspectFit:
return resize(to: size, for: .aspectFit)
case .scaleAspectFill:
return resize(to: size, for: .aspectFill)
default:
return resize(to: size)
}
}
#endif
// MARK: - Resize
/// Resize `self` to an image of new size.
///
/// - parameter size: The target size.
///
/// - returns: An image with new size.
///
/// - Note: This method only works for CG-based image.
public func resize(to size: CGSize) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Resize only works for CG-based image.")
return base
}
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return draw(cgImage: cgImage, to: size) {
#if os(macOS)
base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
#else
base.draw(in: rect)
#endif
}
}
/// Resize `self` to an image of new size, respecting the content mode.
///
/// - Parameters:
/// - size: The target size.
/// - contentMode: Content mode of output image should be.
/// - Returns: An image with new size.
public func resize(to size: CGSize, for contentMode: ContentMode) -> Image {
switch contentMode {
case .aspectFit:
let newSize = self.size.kf.constrained(size)
return resize(to: newSize)
case .aspectFill:
let newSize = self.size.kf.filling(size)
return resize(to: newSize)
default:
return resize(to: size)
}
}
public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Crop only works for CG-based image.")
return base
}
let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
assertionFailure("[Kingfisher] Cropping image failed.")
return base
}
return Kingfisher.image(cgImage: image, scale: scale, refImage: base)
}
// MARK: - Blur
/// Create an image with blur effect based on `self`.
///
/// - parameter radius: The blur radius should be used when creating blur effect.
///
/// - returns: An image with blur effect applied.
///
/// - Note: This method only works for CG-based image.
public func blurred(withRadius radius: CGFloat) -> Image {
#if os(watchOS)
return base
#else
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Blur only works for CG-based image.")
return base
}
// http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
// let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
// if d is odd, use three box-blurs of size 'd', centered on the output pixel.
let s = Float(max(radius, 2.0))
// We will do blur on a resized image (*0.5), so the blur radius could be half as well.
// Fix the slow compiling time for Swift 3.
// See https://github.com/onevcat/Kingfisher/issues/611
let pi2 = 2 * Float.pi
let sqrtPi2 = sqrt(pi2)
var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
if targetRadius.isEven {
targetRadius += 1
}
let iterations: Int
if radius < 0.5 {
iterations = 1
} else if radius < 1.5 {
iterations = 2
} else {
iterations = 3
}
let w = Int(size.width)
let h = Int(size.height)
let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
let data = context.data
let width = vImagePixelCount(context.width)
let height = vImagePixelCount(context.height)
let rowBytes = context.bytesPerRow
return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
}
guard let context = beginContext(size: size, scale: scale) else {
assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
return base
}
defer { endContext() }
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
var inBuffer = createEffectBuffer(context)
guard let outContext = beginContext(size: size, scale: scale) else {
assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
return base
}
defer { endContext() }
var outBuffer = createEffectBuffer(outContext)
for _ in 0 ..< iterations {
vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend))
(inBuffer, outBuffer) = (outBuffer, inBuffer)
}
#if os(macOS)
let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) }
#else
let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) }
#endif
guard let blurredImage = result else {
assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
return base
}
return blurredImage
#endif
}
// MARK: - Overlay
/// Create an image from `self` with a color overlay layer.
///
/// - parameter color: The color should be use to overlay.
/// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
///
/// - returns: An image with a color overlay applied.
///
/// - Note: This method only works for CG-based image.
public func overlaying(with color: Color, fraction: CGFloat) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
return base
}
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
return draw(cgImage: cgImage, to: rect.size) {
#if os(macOS)
base.draw(in: rect)
if fraction > 0 {
color.withAlphaComponent(1 - fraction).set()
NSRectFillUsingOperation(rect, .sourceAtop)
}
#else
color.set()
UIRectFill(rect)
base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
if fraction > 0 {
base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
}
#endif
}
}
// MARK: - Tint
/// Create an image from `self` with a color tint.
///
/// - parameter color: The color should be used to tint `self`
///
/// - returns: An image with a color tint applied.
public func tinted(with color: Color) -> Image {
#if os(watchOS)
return base
#else
return apply(.tint(color))
#endif
}
// MARK: - Color Control
/// Create an image from `self` with color control.
///
/// - parameter brightness: Brightness changing to image.
/// - parameter contrast: Contrast changing to image.
/// - parameter saturation: Saturation changing to image.
/// - parameter inputEV: InputEV changing to image.
///
/// - returns: An image with color control applied.
public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
#if os(watchOS)
return base
#else
return apply(.colorControl(brightness, contrast, saturation, inputEV))
#endif
}
}
// MARK: - Decode
extension Kingfisher where Base: Image {
var decoded: Image {
return decoded(scale: scale)
}
func decoded(scale: CGFloat) -> Image {
// prevent animated image (GIF) lose it's images
#if os(iOS)
if imageSource != nil { return base }
#else
if images != nil { return base }
#endif
guard let imageRef = self.cgImage else {
assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
return base
}
// Draw CGImage in a plain context with scale of 1.0.
guard let context = beginContext(size: CGSize(width: imageRef.width, height: imageRef.height), scale: 1.0) else {
assertionFailure("[Kingfisher] Decoding fails to create a valid context.")
return base
}
defer { endContext() }
let rect = CGRect(x: 0, y: 0, width: CGFloat(imageRef.width), height: CGFloat(imageRef.height))
context.draw(imageRef, in: rect)
let decompressedImageRef = context.makeImage()
return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base)
}
}
/// Reference the source image reference
class ImageSource {
var imageRef: CGImageSource?
init(ref: CGImageSource) {
self.imageRef = ref
}
}
// MARK: - Image format
private struct ImageHeaderData {
static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
static var JPEG_IF: [UInt8] = [0xFF]
static var GIF: [UInt8] = [0x47, 0x49, 0x46]
}
enum ImageFormat {
case unknown, PNG, JPEG, GIF
}
// MARK: - Misc Helpers
public struct DataProxy {
fileprivate let base: Data
init(proxy: Data) {
base = proxy
}
}
extension Data: KingfisherCompatible {
public typealias CompatibleType = DataProxy
public var kf: DataProxy {
return DataProxy(proxy: self)
}
}
extension DataProxy {
var imageFormat: ImageFormat {
var buffer = [UInt8](repeating: 0, count: 8)
(base as NSData).getBytes(&buffer, length: 8)
if buffer == ImageHeaderData.PNG {
return .PNG
} else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
buffer[2] == ImageHeaderData.JPEG_IF[0]
{
return .JPEG
} else if buffer[0] == ImageHeaderData.GIF[0] &&
buffer[1] == ImageHeaderData.GIF[1] &&
buffer[2] == ImageHeaderData.GIF[2]
{
return .GIF
}
return .unknown
}
}
public struct CGSizeProxy {
fileprivate let base: CGSize
init(proxy: CGSize) {
base = proxy
}
}
extension CGSize: KingfisherCompatible {
public typealias CompatibleType = CGSizeProxy
public var kf: CGSizeProxy {
return CGSizeProxy(proxy: self)
}
}
extension CGSizeProxy {
func constrained(_ size: CGSize) -> CGSize {
let aspectWidth = round(aspectRatio * size.height)
let aspectHeight = round(size.width / aspectRatio)
return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
}
func filling(_ size: CGSize) -> CGSize {
let aspectWidth = round(aspectRatio * size.height)
let aspectHeight = round(size.width / aspectRatio)
return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
}
private var aspectRatio: CGFloat {
return base.height == 0.0 ? 1.0 : base.width / base.height
}
func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect {
let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0),
y: anchor.y.clamped(to: 0.0...1.0))
let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width
let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height
let r = CGRect(x: x, y: y, width: size.width, height: size.height)
let ori = CGRect(origin: CGPoint.zero, size: base)
return ori.intersection(r)
}
}
extension CGRect {
func scaled(_ scale: CGFloat) -> CGRect {
return CGRect(x: origin.x * scale, y: origin.y * scale,
width: size.width * scale, height: size.height * scale)
}
}
extension Comparable {
func clamped(to limits: ClosedRange<Self>) -> Self {
return min(max(self, limits.lowerBound), limits.upperBound)
}
}
extension Kingfisher where Base: Image {
func beginContext(size: CGSize, scale: CGFloat) -> CGContext? {
#if os(macOS)
guard let rep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: cgImage?.bitsPerComponent ?? 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSCalibratedRGBColorSpace,
bytesPerRow: 0,
bitsPerPixel: 0) else
{
assertionFailure("[Kingfisher] Image representation cannot be created.")
return nil
}
rep.size = size
NSGraphicsContext.saveGraphicsState()
guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
assertionFailure("[Kingfisher] Image contenxt cannot be created.")
return nil
}
NSGraphicsContext.setCurrent(context)
return context.cgContext
#else
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
context?.scaleBy(x: 1.0, y: -1.0)
context?.translateBy(x: 0, y: -size.height)
return context
#endif
}
func endContext() {
#if os(macOS)
NSGraphicsContext.restoreGraphicsState()
#else
UIGraphicsEndImageContext()
#endif
}
func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
#if os(macOS)
guard let rep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: cgImage?.bitsPerComponent ?? 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSCalibratedRGBColorSpace,
bytesPerRow: 0,
bitsPerPixel: 0) else
{
assertionFailure("[Kingfisher] Image representation cannot be created.")
return base
}
rep.size = size
NSGraphicsContext.saveGraphicsState()
let context = NSGraphicsContext(bitmapImageRep: rep)
NSGraphicsContext.setCurrent(context)
draw()
NSGraphicsContext.restoreGraphicsState()
let outputImage = Image(size: size)
outputImage.addRepresentation(rep)
return outputImage
#else
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
draw()
return UIGraphicsGetImageFromCurrentImageContext() ?? base
#endif
}
#if os(macOS)
func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
let image = Image(cgImage: cgImage, size: base.size)
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return draw(cgImage: cgImage, to: self.size) {
image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
}
}
#endif
}
extension Float {
var isEven: Bool {
return truncatingRemainder(dividingBy: 2.0) == 0
}
}
#if os(macOS)
extension NSBezierPath {
convenience init(roundedRect rect: NSRect, topLeftRadius: CGFloat, topRightRadius: CGFloat,
bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat)
{
self.init()
let maxCorner = min(rect.width, rect.height) / 2
let radiusTopLeft = min(maxCorner, max(0, topLeftRadius))
let radiustopRight = min(maxCorner, max(0, topRightRadius))
let radiusbottomLeft = min(maxCorner, max(0, bottomLeftRadius))
let radiusbottomRight = min(maxCorner, max(0, bottomRightRadius))
guard !NSIsEmptyRect(rect) else {
return
}
let topLeft = NSMakePoint(NSMinX(rect), NSMaxY(rect));
let topRight = NSMakePoint(NSMaxX(rect), NSMaxY(rect));
let bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect));
move(to: NSMakePoint(NSMidX(rect), NSMaxY(rect)))
appendArc(from: topLeft, to: rect.origin, radius: radiusTopLeft)
appendArc(from: rect.origin, to: bottomRight, radius: radiusbottomLeft)
appendArc(from: bottomRight, to: topRight, radius: radiusbottomRight)
appendArc(from: topRight, to: topLeft, radius: radiustopRight)
close()
}
convenience init(roundedRect rect: NSRect, byRoundingCorners corners: RectCorner, radius: CGFloat) {
let radiusTopLeft = corners.contains(.topLeft) ? radius : 0
let radiusTopRight = corners.contains(.topRight) ? radius : 0
let radiusBottomLeft = corners.contains(.bottomLeft) ? radius : 0
let radiusBottomRight = corners.contains(.bottomRight) ? radius : 0
self.init(roundedRect: rect, topLeftRadius: radiusTopLeft, topRightRadius: radiusTopRight,
bottomLeftRadius: radiusBottomLeft, bottomRightRadius: radiusBottomRight)
}
}
#else
extension RectCorner {
var uiRectCorner: UIRectCorner {
var result: UIRectCorner = []
if self.contains(.topLeft) { result.insert(.topLeft) }
if self.contains(.topRight) { result.insert(.topRight) }
if self.contains(.bottomLeft) { result.insert(.bottomLeft) }
if self.contains(.bottomRight) { result.insert(.bottomRight) }
return result
}
}
#endif
// MARK: - Deprecated. Only for back compatibility.
extension Image {
/**
Normalize the image. This method does nothing in OS X.
- returns: The image itself.
*/
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.",
renamed: "kf.normalized")
public func kf_normalized() -> Image {
return kf.normalized
}
// MARK: - Round Corner
/// Create a round corner image based on `self`.
///
/// - parameter radius: The round corner radius of creating image.
/// - parameter size: The target size of creating image.
/// - parameter scale: The image scale of creating image.
///
/// - returns: An image with round corner of `self`.
///
/// - Note: This method only works for CG-based image.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.",
renamed: "kf.image")
public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
return kf.image(withRoundRadius: radius, fit: size)
}
// MARK: - Resize
/// Resize `self` to an image of new size.
///
/// - parameter size: The target size.
///
/// - returns: An image with new size.
///
/// - Note: This method only works for CG-based image.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.",
renamed: "kf.resize")
public func kf_resize(to size: CGSize) -> Image {
return kf.resize(to: size)
}
// MARK: - Blur
/// Create an image with blur effect based on `self`.
///
/// - parameter radius: The blur radius should be used when creating blue.
///
/// - returns: An image with blur effect applied.
///
/// - Note: This method only works for CG-based image.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.",
renamed: "kf.blurred")
public func kf_blurred(withRadius radius: CGFloat) -> Image {
return kf.blurred(withRadius: radius)
}
// MARK: - Overlay
/// Create an image from `self` with a color overlay layer.
///
/// - parameter color: The color should be use to overlay.
/// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
///
/// - returns: An image with a color overlay applied.
///
/// - Note: This method only works for CG-based image.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.",
renamed: "kf.overlaying")
public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image {
return kf.overlaying(with: color, fraction: fraction)
}
// MARK: - Tint
/// Create an image from `self` with a color tint.
///
/// - parameter color: The color should be used to tint `self`
///
/// - returns: An image with a color tint applied.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.",
renamed: "kf.tinted")
public func kf_tinted(with color: Color) -> Image {
return kf.tinted(with: color)
}
// MARK: - Color Control
/// Create an image from `self` with color control.
///
/// - parameter brightness: Brightness changing to image.
/// - parameter contrast: Contrast changing to image.
/// - parameter saturation: Saturation changing to image.
/// - parameter inputEV: InputEV changing to image.
///
/// - returns: An image with color control applied.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.",
renamed: "kf.adjusted")
public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
}
}
extension Kingfisher where Base: Image {
@available(*, deprecated,
message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)")
public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image {
return image(withRoundRadius: radius, fit: size)
}
}
| b9d07d75da5b83b51e1b1fc678434408 | 34.482297 | 158 | 0.582001 | false | false | false | false |
Wakup/Wakup-iOS-SDK | refs/heads/master | Wakup/AsyncLegacy.swift | mit | 1 | //
// AsyncLegacy.swift
//
// Created by Tobias DM on 15/07/14.
// Modifed by Joseph Lord
// Copyright (c) 2014 Human Friendly Ltd.
//
// OS X 10.9+ and iOS 7.0+
// Only use with ARC
//
// The MIT License (MIT)
// Copyright (c) 2014 Tobias Due Munk
//
// 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
// HACK: For Beta 5, 6
prefix func +(v: qos_class_t) -> Int {
return Int(v.rawValue)
}
private class GCD {
/* dispatch_get_queue() */
class final func mainQueue() -> DispatchQueue {
return DispatchQueue.main
// Could use return dispatch_get_global_queue(+qos_class_main(), 0)
}
class final func userInteractiveQueue() -> DispatchQueue {
//return dispatch_get_global_queue(+QOS_CLASS_USER_INTERACTIVE, 0)
return DispatchQueue.global(qos: DispatchQoS.userInteractive.qosClass)
}
class final func userInitiatedQueue() -> DispatchQueue {
//return dispatch_get_global_queue(+QOS_CLASS_USER_INITIATED, 0)
return DispatchQueue.global(qos: DispatchQoS.userInitiated.qosClass)
}
class final func defaultQueue() -> DispatchQueue {
return DispatchQueue.global(qos: DispatchQoS.default.qosClass)
}
class final func utilityQueue() -> DispatchQueue {
return DispatchQueue.global(qos: DispatchQoS.utility.qosClass)
}
class final func backgroundQueue() -> DispatchQueue {
return DispatchQueue.global(qos: DispatchQoS.background.qosClass)
}
}
open class Async {
//The block to be executed does not need to be retained in present code
//only the dispatch_group is needed in order to cancel it.
//private let block: dispatch_block_t
fileprivate let dgroup: DispatchGroup = DispatchGroup()
fileprivate var isCancelled = false
fileprivate init() {}
}
extension Async { // Static methods
/* dispatch_async() */
fileprivate class final func async(_ block: @escaping ()->(), inQueue queue: DispatchQueue) -> Async {
// Wrap block in a struct since dispatch_block_t can't be extended and to give it a group
let asyncBlock = Async()
// Add block to queue
queue.async(group: asyncBlock.dgroup, execute: asyncBlock.cancellable(block))
return asyncBlock
}
@discardableResult class final func main(_ block: @escaping ()->()) -> Async {
return Async.async(block, inQueue: GCD.mainQueue())
}
@discardableResult class final func userInteractive(_ block: @escaping ()->()) -> Async {
return Async.async(block, inQueue: GCD.userInteractiveQueue())
}
@discardableResult class final func userInitiated(_ block: @escaping ()->()) -> Async {
return Async.async(block, inQueue: GCD.userInitiatedQueue())
}
@discardableResult class final func default_(_ block: @escaping ()->()) -> Async {
return Async.async(block, inQueue: GCD.defaultQueue())
}
@discardableResult class final func utility(_ block: @escaping ()->()) -> Async {
return Async.async(block, inQueue: GCD.utilityQueue())
}
@discardableResult class final func background(_ block: @escaping ()->()) -> Async {
return Async.async(block, inQueue: GCD.backgroundQueue())
}
@discardableResult class final func customQueue(_ queue: DispatchQueue, block: @escaping ()->()) -> Async {
return Async.async(block, inQueue: queue)
}
/* dispatch_after() */
fileprivate class final func after(_ seconds: Double, block: @escaping ()->(), inQueue queue: DispatchQueue) -> Async {
let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC))
let time = DispatchTime.now() + Double(nanoSeconds) / Double(NSEC_PER_SEC)
return at(time, block: block, inQueue: queue)
}
fileprivate class final func at(_ time: DispatchTime, block: @escaping ()->(), inQueue queue: DispatchQueue) -> Async {
// See Async.async() for comments
let asyncBlock = Async()
asyncBlock.dgroup.enter()
queue.asyncAfter(deadline: time){
let cancellableBlock = asyncBlock.cancellable(block)
cancellableBlock() // Compiler crashed in Beta6 when I just did asyncBlock.cancellable(block)() directly.
asyncBlock.dgroup.leave()
}
return asyncBlock
}
@discardableResult class final func main(after: Double, block: @escaping ()->()) -> Async {
return Async.after(after, block: block, inQueue: GCD.mainQueue())
}
@discardableResult class final func userInteractive(after: Double, block: @escaping ()->()) -> Async {
return Async.after(after, block: block, inQueue: GCD.userInteractiveQueue())
}
@discardableResult class final func userInitiated(after: Double, block: @escaping ()->()) -> Async {
return Async.after(after, block: block, inQueue: GCD.userInitiatedQueue())
}
@discardableResult class final func default_(after: Double, block: @escaping ()->()) -> Async {
return Async.after(after, block: block, inQueue: GCD.defaultQueue())
}
@discardableResult class final func utility(after: Double, block: @escaping ()->()) -> Async {
return Async.after(after, block: block, inQueue: GCD.utilityQueue())
}
@discardableResult class final func background(after: Double, block: @escaping ()->()) -> Async {
return Async.after(after, block: block, inQueue: GCD.backgroundQueue())
}
@discardableResult class final func customQueue(after: Double, queue: DispatchQueue, block: @escaping ()->()) -> Async {
return Async.after(after, block: block, inQueue: queue)
}
}
extension Async { // Regualar methods matching static once
fileprivate final func chain(block chainingBlock: @escaping ()->(), runInQueue queue: DispatchQueue) -> Async {
// See Async.async() for comments
let asyncBlock = Async()
asyncBlock.dgroup.enter()
self.dgroup.notify(queue: queue) {
let cancellableChainingBlock = asyncBlock.cancellable(chainingBlock)
cancellableChainingBlock()
asyncBlock.dgroup.leave()
}
return asyncBlock
}
fileprivate final func cancellable(_ blockToWrap: @escaping ()->()) -> ()->() {
// Retains self in case it is cancelled and then released.
return {
if !self.isCancelled {
blockToWrap()
}
}
}
final func main(_ chainingBlock: @escaping ()->()) -> Async {
return chain(block: chainingBlock, runInQueue: GCD.mainQueue())
}
final func userInteractive(_ chainingBlock: @escaping ()->()) -> Async {
return chain(block: chainingBlock, runInQueue: GCD.userInteractiveQueue())
}
final func userInitiated(_ chainingBlock: @escaping ()->()) -> Async {
return chain(block: chainingBlock, runInQueue: GCD.userInitiatedQueue())
}
final func default_(_ chainingBlock: @escaping ()->()) -> Async {
return chain(block: chainingBlock, runInQueue: GCD.defaultQueue())
}
final func utility(_ chainingBlock: @escaping ()->()) -> Async {
return chain(block: chainingBlock, runInQueue: GCD.utilityQueue())
}
final func background(_ chainingBlock: @escaping ()->()) -> Async {
return chain(block: chainingBlock, runInQueue: GCD.backgroundQueue())
}
final func customQueue(_ queue: DispatchQueue, chainingBlock: @escaping ()->()) -> Async {
return chain(block: chainingBlock, runInQueue: queue)
}
/* dispatch_after() */
fileprivate final func after(_ seconds: Double, block chainingBlock: @escaping ()->(), runInQueue queue: DispatchQueue) -> Async {
let asyncBlock = Async()
self.dgroup.notify(queue: queue)
{
asyncBlock.dgroup.enter()
let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC))
let time = DispatchTime.now() + Double(nanoSeconds) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time) {
let cancellableChainingBlock = self.cancellable(chainingBlock)
cancellableChainingBlock()
asyncBlock.dgroup.leave()
}
}
// Wrap block in a struct since dispatch_block_t can't be extended
return asyncBlock
}
final func main(after: Double, block: @escaping ()->()) -> Async {
return self.after(after, block: block, runInQueue: GCD.mainQueue())
}
final func userInteractive(after: Double, block: @escaping ()->()) -> Async {
return self.after(after, block: block, runInQueue: GCD.userInteractiveQueue())
}
final func userInitiated(after: Double, block: @escaping ()->()) -> Async {
return self.after(after, block: block, runInQueue: GCD.userInitiatedQueue())
}
final func default_(after: Double, block: @escaping ()->()) -> Async {
return self.after(after, block: block, runInQueue: GCD.defaultQueue())
}
final func utility(after: Double, block: @escaping ()->()) -> Async {
return self.after(after, block: block, runInQueue: GCD.utilityQueue())
}
final func background(after: Double, block: @escaping ()->()) -> Async {
return self.after(after, block: block, runInQueue: GCD.backgroundQueue())
}
final func customQueue(after: Double, queue: DispatchQueue, block: @escaping ()->()) -> Async {
return self.after(after, block: block, runInQueue: queue)
}
/* cancel */
final func cancel() {
// I don't think that syncronisation is necessary. Any combination of multiple access
// should result in some boolean value and the cancel will only cancel
// if the execution has not yet started.
isCancelled = true
}
/* wait */
/// If optional parameter forSeconds is not provided, use DISPATCH_TIME_FOREVER
final func wait(_ seconds: Double = 0.0) {
if seconds != 0.0 {
let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC))
let time = DispatchTime.now() + Double(nanoSeconds) / Double(NSEC_PER_SEC)
_ = dgroup.wait(timeout: time)
} else {
_ = dgroup.wait(timeout: DispatchTime.distantFuture)
}
}
}
// Convenience
// extension qos_class_t {
//
// // Calculated property
// var description: String {
// get {
// switch +self {
// case +qos_class_main(): return "Main"
// case +QOS_CLASS_USER_INTERACTIVE: return "User Interactive"
// case +QOS_CLASS_USER_INITIATED: return "User Initiated"
// case +QOS_CLASS_DEFAULT: return "Default"
// case +QOS_CLASS_UTILITY: return "Utility"
// case +QOS_CLASS_BACKGROUND: return "Background"
// case +QOS_CLASS_UNSPECIFIED: return "Unspecified"
// default: return "Unknown"
// }
// }
// }
//}
| e5dbd3a9319d5fe9e45b702aefb620bb | 40.185567 | 134 | 0.644305 | false | false | false | false |
katsana/katsana-sdk-ios | refs/heads/master | Pods/Siesta/Source/Siesta/Support/Progress.swift | apache-2.0 | 1 | //
// Progress.swift
// Siesta
//
// Created by Paul on 2015/9/28.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
internal struct RequestProgressComputation: Progress
{
private var uploadProgress, downloadProgress: TaskProgress
private var connectLatency, responseLatency: WaitingProgress
private var overallProgress: MonotonicProgress
init(isGet: Bool)
{
uploadProgress = TaskProgress(estimatedTotal: 8192) // bytes
downloadProgress = TaskProgress(estimatedTotal: 65536)
connectLatency = WaitingProgress(estimatedTotal: 2.5) // seconds to reach 75%
responseLatency = WaitingProgress(estimatedTotal: 1.2)
overallProgress =
MonotonicProgress(
CompoundProgress(components:
(connectLatency, weight: 0.3),
(uploadProgress, weight: isGet ? 0 : 1),
(responseLatency, weight: 0.3),
(downloadProgress, weight: isGet ? 1 : 0.1)))
}
mutating func update(from metrics: RequestTransferMetrics)
{
updateByteCounts(from: metrics)
updateLatency(from: metrics)
}
mutating func updateByteCounts(from metrics: RequestTransferMetrics)
{
func optionalTotal(_ n: Int64?) -> Double?
{
if let n = n, n > 0
{ return Double(n) }
else
{ return nil }
}
overallProgress = overallProgress.heldConstant
{
uploadProgress.actualTotal = optionalTotal(metrics.requestBytesTotal)
downloadProgress.actualTotal = optionalTotal(metrics.responseBytesTotal)
}
uploadProgress.completed = Double(metrics.requestBytesSent)
downloadProgress.completed = Double(metrics.responseBytesReceived)
}
mutating func updateLatency(from metrics: RequestTransferMetrics)
{
let requestStarted = metrics.requestBytesSent > 0,
responseStarted = metrics.responseBytesReceived > 0,
requestSent = requestStarted && metrics.requestBytesSent == metrics.requestBytesTotal
if requestStarted || responseStarted
{
overallProgress = overallProgress.heldConstant
{ connectLatency.complete() }
}
else
{ connectLatency.tick() }
if responseStarted
{
overallProgress = overallProgress.heldConstant
{ responseLatency.complete() }
}
else if requestSent
{ responseLatency.tick() }
}
mutating func complete()
{ overallProgress.child = TaskProgress.completed }
var rawFractionDone: Double
{
return overallProgress.fractionDone
}
}
// MARK: Generic progress computation
// The code from here to the bottom is a good candidate for open-sourcing as a separate project.
/// Generic task that goes from 0 to 1.
internal protocol Progress
{
var rawFractionDone: Double { get }
}
extension Progress
{
var fractionDone: Double
{
let raw = rawFractionDone
return raw.isNaN ? raw : max(0, min(1, raw))
}
}
/// A task that has a known amount of homogenous work completed (e.g. bytes transferred).
private class TaskProgress: Progress
{
/// The amount of work done, in arbitrary units.
var completed: Double
/// The actual amount of work to do, if known. In same units as `completed`.
var actualTotal: Double?
/// The 75% point for an asymptotic curve. In same units as `completed`.
/// Ignored if actualTotal is present.
var estimatedTotal: Double
init(completed: Double = 0, estimatedTotal: Double)
{
self.completed = completed
self.estimatedTotal = estimatedTotal
}
init(completed: Double = 0, actualTotal: Double)
{
self.completed = completed
self.actualTotal = actualTotal
self.estimatedTotal = actualTotal
}
var rawFractionDone: Double
{
if let actualTotal = actualTotal
{ return completed / actualTotal }
else
{ return 1 - pow(2, -2 * completed / estimatedTotal) }
}
static var completed: TaskProgress
{ return TaskProgress(completed: 1, actualTotal: 1) }
static var unknown: TaskProgress
{ return TaskProgress(completed: 0, estimatedTotal: Double.nan) }
}
/// Several individual progress measurements combined into one.
private struct CompoundProgress: Progress
{
var components: [Component]
init(components: Component...)
{ self.components = components }
var rawFractionDone: Double
{
var total = 0.0, totalWeight = 0.0
for component in components
{
total += component.progress.fractionDone * component.weight
totalWeight += component.weight
}
return total / totalWeight
}
typealias Component = (progress: Progress, weight: Double)
}
/// Wraps a progress computation, holding the result constant during potentially unstable operations such as
/// changing the amount of estimated work remaining.
private struct MonotonicProgress: Progress
{
var child: Progress
private var adjustment: Double = 1
init(_ child: Progress)
{ self.child = child }
var rawFractionDone: Double
{ return (child.fractionDone - 1) * adjustment + 1 }
func heldConstant(withRespectTo changes: () -> Void) -> MonotonicProgress
{
let before = fractionDone
changes()
let afterRaw = child.fractionDone
var result = self
if afterRaw != 1
{ result.adjustment = (before - 1) / (afterRaw - 1) }
return result
}
}
/// Progress spent waiting for something that will take an unknown amount of time.
private class WaitingProgress: Progress
{
private var startTime: TimeInterval?
private var progress: TaskProgress
init(estimatedTotal: Double)
{ progress = TaskProgress(estimatedTotal: estimatedTotal) }
var rawFractionDone: Double
{ return progress.rawFractionDone }
func tick()
{
let now = Siesta.now()
if let startTime = startTime
{ progress.completed = now - startTime }
else
{ startTime = now }
}
func complete()
{
progress.completed = Double.infinity
}
}
| 540ba5cd31eae66d20a00f881e6b6cff | 28.180617 | 108 | 0.618659 | false | false | false | false |
santosli/100-Days-of-Swift-3 | refs/heads/master | Project 19/Project 19/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// Project 19
//
// Created by Santos on 23/11/2016.
// Copyright © 2016 santos. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var demoTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//add left and right navigation button
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil)
//init color
self.navigationItem.title = "New Entry"
self.navigationController?.navigationBar.barTintColor = UIColor(red:0.93, green:0.98, blue:0.96, alpha:1.00)
self.navigationController?.navigationBar.tintColor = UIColor(red:0.00, green:0.73, blue:0.58, alpha:1.00)
//add toolbar above keyboard
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
keyboardToolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
keyboardToolbar.setShadowImage(UIImage(), forToolbarPosition: .any)
let cameraButton = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: nil)
cameraButton.tintColor = UIColor(red:0.46, green:0.84, blue:0.74, alpha:1.00)
let locationButton = UIBarButtonItem.init(image: #imageLiteral(resourceName: "location"), style: .plain, target: nil, action: nil)
locationButton.tintColor = UIColor(red:0.46, green:0.84, blue:0.74, alpha:1.00)
keyboardToolbar.items = [cameraButton, locationButton]
demoTextView.inputAccessoryView = keyboardToolbar
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| d34ea9eadd8508db7459d27486ed842d | 37.45283 | 138 | 0.678606 | false | false | false | false |
getcircle/protobuf-swift | refs/heads/master | src/ProtocolBuffers/runtime-pb-swift/ExtensionRegistry.swift | apache-2.0 | 3 | // Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public typealias AnyClassType = GeneratedMessage.Type
public protocol ExtensionField
{
var fieldNumber:Int32 {get set}
var extendedClass:AnyClassType {get}
var wireType:WireFormat {get}
func writeValueIncludingTagToCodedOutputStream(value:Any, output:CodedOutputStream) throws
func computeSerializedSizeIncludingTag(value:Any) throws -> Int32
func writeDescriptionOf(value:Any, inout output:String, indent:String) throws
func mergeFromCodedInputStream(input:CodedInputStream, unknownFields:UnknownFieldSet.Builder, extensionRegistry:ExtensionRegistry, builder:ExtendableMessageBuilder, tag:Int32) throws
}
public class ExtensionRegistry
{
private var classMap:[String : [Int32 : ConcreateExtensionField]]
public init()
{
self.classMap = [:]
}
public init(classMap:[String : [Int32 : ConcreateExtensionField]])
{
self.classMap = classMap
}
public func getExtension(clName:AnyClassType, fieldNumber:Int32) -> ConcreateExtensionField? {
let extensionMap = classMap[clName.className()]
if extensionMap == nil
{
return nil
}
return extensionMap![fieldNumber]
}
public func addExtension(extensions:ConcreateExtensionField)
{
let extendedClass = extensions.extendedClass.className()
var extensionMap = classMap[extendedClass]
if extensionMap == nil
{
extensionMap = [Int32 : ConcreateExtensionField]()
}
extensionMap![extensions.fieldNumber] = extensions
classMap[extendedClass] = extensionMap
}
}
| 81f5138d7d837382e5b46b357cb96177 | 32.042254 | 186 | 0.704177 | false | false | false | false |
YevhenHerasymenko/SwiftGroup1 | refs/heads/master | FirstGetRequest/FirstGetRequest/Controllers/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// FirstGetRequest
//
// Created by Yevhen Herasymenko on 22/07/2016.
// Copyright © 2016 Yevhen Herasymenko. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var userAvatar: UIImageView!
var user: User? = nil {
didSet {
let operation = NSBlockOperation {
self.updateUI()
}
NSOperationQueue.mainQueue().addOperation(operation)
}
}
override func viewDidLoad() {
super.viewDidLoad()
NetworkManager.getUser {[weak self] (answer) in
switch answer {
case .Success(let user):
guard let strongSelf = self else { return }
strongSelf.user = user
case .Failure(let error):
print(error)
}
}
}
func updateUI() {
if let avatar = user?.avatarUrl,
let avatarUrl = NSURL(string: avatar),
let photoData = NSData(contentsOfURL: avatarUrl) {
let image = UIImage(data: photoData)
userAvatar.image = image
}
}
}
| 32140d58e3e4535cfcf308dd2801b5a0 | 24.888889 | 64 | 0.551931 | false | false | false | false |
sora0077/QiitaKit | refs/heads/master | QiitaKit/src/Endpoint/Tagging/CreateTagging.swift | mit | 1 | //
// CreateTagging.swift
// QiitaKit
//
// Created on 2015/06/08.
// Copyright (c) 2015年 林達也. All rights reserved.
//
import Foundation
import APIKit
import Result
/**
* 投稿にタグを追加します。Qiita:Teamでのみ有効です。
*/
public struct CreateTagging {
public let id: Item.Identifier
/// タグを特定するための一意な名前
/// example: qiita
///
public let name: String
///
/// example: ["0.0.1"]
///
public let versions: Array<String>
public init(id: Item.Identifier, name: String, versions: Array<String>) {
self.id = id
self.name = name
self.versions = versions
}
}
extension CreateTagging: QiitaRequestToken {
public typealias Response = Tagging
public typealias SerializedObject = [String: AnyObject]
public var method: HTTPMethod {
return .POST
}
public var path: String {
return "/api/v2/items/\(id)/taggings"
}
public var parameters: [String: AnyObject]? {
return [
"name": name,
"versions": versions
]
}
public var encoding: RequestEncoding {
return .JSON
}
}
public extension CreateTagging {
func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
return _Tagging(object)
}
}
| 88e28e3bc36f8fba690f5ab50d54cce6 | 18.925373 | 119 | 0.610487 | false | false | false | false |
codefellows/sea-b19-ios | refs/heads/master | Projects/FlappyBirdSwift/FlappyBirdSwift/GameScene.swift | gpl-2.0 | 1 | //
// GameScene.swift
// FlappyBirdSwift
//
// Created by Bradley Johnson on 9/1/14.
// Copyright (c) 2014 learnswift. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var flappy = SKSpriteNode(imageNamed: "flappy")
var pipes = [PipeNode]()
var firstAvailable : PipeNode!
var flappyIsDead = false
var deltaTime = 0.0
var nextPipeTime = 2.0
var previousTime = 0.0
var timeSinceLastPipe = 0.0
//categories
let flappyCategory = 0x1 << 0
let pipeCategory = 0x1 << 1
let bottomPipeLowerBounds = -300
let pipeHeight = 530
override func didMoveToView(view: SKView) {
/* Setup your scene here */
//creating our main character
//setup scrollingbackground
self.setupBackground()
println(self.frame)
self.physicsWorld.contactDelegate = self
//setup pipes list
self.setupPipes()
//setup flappy
self.flappy.position = CGPoint(x: 100, y: 300)
self.addChild(self.flappy)
//adding physics to flappy
self.flappy.physicsBody = SKPhysicsBody(rectangleOfSize: self.flappy.size)
self.flappy.physicsBody.dynamic = true
self.flappy.physicsBody.mass = 0.02
self.flappy.physicsBody.categoryBitMask = UInt32(self.flappyCategory)
self.flappy.physicsBody.contactTestBitMask = UInt32(self.pipeCategory)
self.flappy.physicsBody.collisionBitMask = 0
}
func setupPipes() {
for (var i = 0; i < 10;i++) {
//pipe setup
var pipeNode = PipeNode()
pipeNode.pipe.position = CGPointMake(1100, 0)
pipeNode.pipe.anchorPoint = CGPointZero
pipeNode.pipe.physicsBody = SKPhysicsBody(rectangleOfSize: pipeNode.pipe.size)
pipeNode.pipe.physicsBody.affectedByGravity = false
pipeNode.pipe.physicsBody.dynamic = false
pipeNode.pipe.physicsBody.categoryBitMask = UInt32(self.pipeCategory)
pipeNode.pipe.physicsBody.contactTestBitMask = UInt32(self.flappyCategory)
//pipeNode.pipe.hidden = true
self.addChild(pipeNode.pipe)
//insert pipe into array, assign next pointer for linked list
self.pipes.insert(pipeNode, atIndex: 0)
if self.pipes.count > 1 {
pipeNode.nextNode = self.pipes[1]
}
}
self.firstAvailable = self.pipes[0]
}
func fetchFirstAvailablePipe () -> PipeNode {
var firstPipe = self.firstAvailable
//replace current head with head's next
if self.firstAvailable.nextNode != nil {
self.firstAvailable = self.firstAvailable.nextNode
}
//firstPipe.pipe.hidden = false
return firstPipe
}
func doneWithPipe(pipeNode : PipeNode) {
//pipeNode.pipe.hidden = true
pipeNode.nextNode = self.firstAvailable
self.firstAvailable = pipeNode
println("done with pipe")
}
func setupBackground() {
//this creates 2 backgrounds
for (var i = 0; i < 2;i++) {
var bg = SKSpriteNode(imageNamed: "space.jpg")
var newI = CGFloat(i)
bg.anchorPoint = CGPointZero
bg.position = CGPointMake(newI * bg.size.width, 90)
bg.name = "background"
self.addChild(bg)
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
println("touches began")
if flappyIsDead == false {
self.flappy.physicsBody.velocity = CGVectorMake(0, 0)
self.flappy.physicsBody.applyImpulse(CGVectorMake(0, 7))
}
}
func movePipe(pipeNode : PipeNode, location : CGPoint){
var moveAction = SKAction.moveTo(location, duration: 3)
var completionAction = SKAction.runBlock({
self.doneWithPipe(pipeNode)
})
var sequence = SKAction.sequence([moveAction,completionAction])
pipeNode.pipe.runAction(sequence)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
//figuring our delta time, aka time since last update:
self.deltaTime = currentTime - self.previousTime
self.previousTime = currentTime
self.timeSinceLastPipe += self.deltaTime
if self.timeSinceLastPipe > self.nextPipeTime {
println("spawning pipe")
//generate random number between 0 and -300
var y = Int(arc4random_uniform(UInt32(300)))
var randomY = CGFloat(y * -1)
//its time to create a pipe
var pipeNode = self.fetchFirstAvailablePipe()
println("height of pipe : \(pipeNode.pipe.size.height)")
pipeNode.pipe.position = CGPointMake(1100, randomY)
//create location to tell pipe to move to with an action
var location = CGPointMake(-70, randomY)
self.movePipe(pipeNode, location: location)
// var topY = CGFloat(self.pipeHeight) + 450 + randomY
//// spawn top pipe
// var topPipe = self.fetchFirstAvailablePipe()
// var rotate = SKAction.rotateByAngle(CGFloat(M_PI), duration: 0.0)
// topPipe.pipe.runAction(rotate)
//
// topPipe.pipe.position = CGPointMake(1100, topY)
// var nextLocation = CGPointMake(-70, topY)
// self.movePipe(topPipe, location: nextLocation)
//
// reset timesincelastpipe to 0, since we just created a pipe
self.timeSinceLastPipe = 0
}
//enumerate through our background nodes
self.enumerateChildNodesWithName("background", usingBlock: { (node, stop) -> Void in
if let bg = node as? SKSpriteNode {
//move the background to the left
bg.position = CGPointMake(bg.position.x - 5, bg.position.y)
//if background is completely off screen to left, move it to the right so it can be scrolled back on screen
if bg.position.x <= bg.size.width * -1 {
bg.position = CGPointMake(bg.position.x + bg.size.width * 2, bg.position.y)
}
}
})
}
func didBeginContact(contact: SKPhysicsContact!) {
println("contact!")
self.flappyIsDead = true
var bird = contact.bodyB.node
var slightUp = CGPointMake(bird.position.x, bird.position.y + 20)
var moveUp = SKAction.moveTo(slightUp, duration: 0.1)
var drop = CGPointMake(bird.position.x, 0)
var moveDown = SKAction.moveTo(drop, duration: 0.5)
var sequence = SKAction.sequence([moveUp,moveDown])
bird.runAction(sequence)
}
}
| 015fe12f3d8c5f0ab392d6cadf02e074 | 32.251163 | 115 | 0.586096 | false | false | false | false |
mxcl/PromiseKit | refs/heads/v6 | Tests/JS-A+/JSUtils.swift | mit | 1 | //
// JSUtils.swift
// PMKJSA+Tests
//
// Created by Lois Di Qual on 3/2/18.
//
import Foundation
import JavaScriptCore
enum JSUtils {
class JSError: Error {
let reason: JSValue
init(reason: JSValue) {
self.reason = reason
}
}
static let sharedContext: JSContext = {
guard let context = JSContext() else {
fatalError("Couldn't create JS context")
}
return context
}()
static var undefined: JSValue {
guard let undefined = JSValue(undefinedIn: JSUtils.sharedContext) else {
fatalError("Couldn't create `undefined` value")
}
return undefined
}
static func typeError(message: String) -> JSValue {
let message = message.replacingOccurrences(of: "\"", with: "\\\"")
let script = "new TypeError(\"\(message)\")"
guard let result = sharedContext.evaluateScript(script) else {
fatalError("Couldn't create TypeError")
}
return result
}
// @warning: relies on lodash to be present
static func isFunction(value: JSValue) -> Bool {
guard let context = value.context else {
return false
}
guard let lodash = context.objectForKeyedSubscript("_") else {
fatalError("Couldn't get lodash in JS context")
}
guard let result = lodash.invokeMethod("isFunction", withArguments: [value]) else {
fatalError("Couldn't invoke _.isFunction")
}
return result.toBool()
}
// Calls a JS function using `Function.prototype.call` and throws any potential exception wrapped in a JSError
static func call(function: JSValue, arguments: [JSValue]) throws -> JSValue? {
let context = JSUtils.sharedContext
// Create a new exception handler that will store a potential exception
// thrown in the handler. Save the value of the old handler.
var caughtException: JSValue?
let savedExceptionHandler = context.exceptionHandler
context.exceptionHandler = { context, exception in
caughtException = exception
}
// Call the handler
let returnValue = function.invokeMethod("call", withArguments: arguments)
context.exceptionHandler = savedExceptionHandler
// If an exception was caught, throw it
if let exception = caughtException {
throw JSError(reason: exception)
}
return returnValue
}
static func printCurrentStackTrace() {
guard let exception = JSUtils.sharedContext.evaluateScript("new Error()") else {
return print("Couldn't get current stack trace")
}
printStackTrace(exception: exception, includeExceptionDescription: false)
}
static func printStackTrace(exception: JSValue, includeExceptionDescription: Bool) {
guard let lineNumber = exception.objectForKeyedSubscript("line"),
let column = exception.objectForKeyedSubscript("column"),
let message = exception.objectForKeyedSubscript("message"),
let stacktrace = exception.objectForKeyedSubscript("stack")?.toString() else {
return print("Couldn't print stack trace")
}
if includeExceptionDescription {
print("JS Exception at \(lineNumber):\(column): \(message)")
}
let lines = stacktrace.split(separator: "\n").map { "\t> \($0)" }.joined(separator: "\n")
print(lines)
}
}
#if !swift(>=3.2)
extension String {
func split(separator: Character, omittingEmptySubsequences: Bool = true) -> [String] {
return characters.split(separator: separator, omittingEmptySubsequences: omittingEmptySubsequences).map(String.init)
}
var first: Character? {
return characters.first
}
}
#endif
| 16d87ca5d537eccd627d97184c78f7c6 | 32.974138 | 124 | 0.618371 | false | false | false | false |
andreamazz/BubbleTransition | refs/heads/master | Source/BubbleTransition.swift | mit | 1 | //
// BubbleTransition.swift
// BubbleTransition
//
// Created by Andrea Mazzini on 04/04/15.
// Copyright (c) 2015-2018 Fancy Pixel. All rights reserved.
//
import UIKit
/**
A custom modal transition that presents and dismiss a controller with an expanding bubble effect.
- Prepare the transition:
```swift
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let controller = segue.destination
controller.transitioningDelegate = self
controller.modalPresentationStyle = .custom
}
```
- Implement UIViewControllerTransitioningDelegate:
```swift
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .present
transition.startingPoint = someButton.center
transition.bubbleColor = someButton.backgroundColor!
return transition
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .dismiss
transition.startingPoint = someButton.center
transition.bubbleColor = someButton.backgroundColor!
return transition
}
```
*/
open class BubbleTransition: NSObject {
/**
The point that originates the bubble. The bubble starts from this point
and shrinks to it on dismiss
*/
@objc open var startingPoint = CGPoint.zero {
didSet {
bubble.center = startingPoint
}
}
/**
The transition duration. The same value is used in both the Present or Dismiss actions
Defaults to `0.5`
*/
@objc open var duration = 0.5
/**
The transition direction. Possible values `.present`, `.dismiss` or `.pop`
Defaults to `.Present`
*/
@objc open var transitionMode: BubbleTransitionMode = .present
/**
The color of the bubble. Make sure that it matches the destination controller's background color.
*/
@objc open var bubbleColor: UIColor = .white
open fileprivate(set) var bubble = UIView()
/**
The possible directions of the transition.
- Present: For presenting a new modal controller
- Dismiss: For dismissing the current controller
- Pop: For a pop animation in a navigation controller
*/
@objc public enum BubbleTransitionMode: Int {
case present, dismiss, pop
}
}
/// The interactive swipe direction
///
/// - up: swipe up
/// - down: swipe down
public enum BubbleInteractiveTransitionSwipeDirection: CGFloat {
case up = -1
case down = 1
}
/**
Handles the interactive dismissal of the presented controller via swipe
- Prepare the interactive transaction:
```swift
let interactiveTransition = BubbleInteractiveTransition()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let controller = segue.destination
controller.transitioningDelegate = self
controller.modalPresentationStyle = .custom
interactiveTransition.attach(to: controller)
}
```
and implement the appropriate delegate method:
```swift
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactiveTransition
}
```
*/
open class BubbleInteractiveTransition: UIPercentDrivenInteractiveTransition {
fileprivate var interactionStarted = false
fileprivate var interactionShouldFinish = false
fileprivate var controller: UIViewController?
/// The threshold that grants the dismissal of the controller. Values from 0 to 1
open var interactionThreshold: CGFloat = 0.3
/// The swipe direction
open var swipeDirection: BubbleInteractiveTransitionSwipeDirection = .down
/// Attach the swipe gesture to a controller
///
/// - Parameter to: the target controller
open func attach(to: UIViewController) {
controller = to
controller?.view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(BubbleInteractiveTransition.handlePan(gesture:))))
if #available(iOS 10.0, *) {
wantsInteractiveStart = false
}
}
@objc func handlePan(gesture: UIPanGestureRecognizer) {
guard let controller = controller, let view = controller.view else { return }
let translation = gesture.translation(in: controller.view.superview)
let delta = swipeDirection.rawValue * (translation.y / view.bounds.height)
let movement = fmaxf(Float(delta), 0.0)
let percent = fminf(movement, 1.0)
let progress = CGFloat(percent)
switch gesture.state {
case .began:
interactionStarted = true
controller.dismiss(animated: true, completion: nil)
case .changed:
interactionShouldFinish = progress > interactionThreshold
update(progress)
case .cancelled:
interactionShouldFinish = false
fallthrough
case .ended:
interactionStarted = false
interactionShouldFinish ? finish() : cancel()
default:
break
}
}
}
extension BubbleTransition: UIViewControllerAnimatedTransitioning {
// MARK: - UIViewControllerAnimatedTransitioning
/**
Required by UIViewControllerAnimatedTransitioning
*/
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
/**
Required by UIViewControllerAnimatedTransitioning
*/
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let fromViewController = transitionContext.viewController(forKey: .from)
let toViewController = transitionContext.viewController(forKey: .to)
if transitionMode == .present {
fromViewController?.beginAppearanceTransition(false, animated: true)
if toViewController?.modalPresentationStyle == .custom {
toViewController?.beginAppearanceTransition(true, animated: true)
}
let presentedControllerView = transitionContext.view(forKey: .to)!
let originalCenter = presentedControllerView.center
let originalSize = presentedControllerView.frame.size
bubble = UIView()
bubble.frame = frameForBubble(originalCenter, size: originalSize, start: startingPoint)
bubble.layer.cornerRadius = bubble.frame.size.height / 2
bubble.center = startingPoint
bubble.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
bubble.backgroundColor = bubbleColor
containerView.addSubview(bubble)
presentedControllerView.center = startingPoint
presentedControllerView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
presentedControllerView.alpha = 0
containerView.addSubview(presentedControllerView)
UIView.animate(withDuration: duration, animations: {
self.bubble.transform = CGAffineTransform.identity
presentedControllerView.transform = CGAffineTransform.identity
presentedControllerView.alpha = 1
presentedControllerView.center = originalCenter
}, completion: { (_) in
transitionContext.completeTransition(true)
self.bubble.isHidden = true
if toViewController?.modalPresentationStyle == .custom {
toViewController?.endAppearanceTransition()
}
fromViewController?.endAppearanceTransition()
})
} else {
if fromViewController?.modalPresentationStyle == .custom {
fromViewController?.beginAppearanceTransition(false, animated: true)
}
toViewController?.beginAppearanceTransition(true, animated: true)
let key: UITransitionContextViewKey = (transitionMode == .pop) ? .to : .from
let returningControllerView = transitionContext.view(forKey: key)!
let originalCenter = returningControllerView.center
let originalSize = returningControllerView.frame.size
bubble.frame = frameForBubble(originalCenter, size: originalSize, start: startingPoint)
bubble.layer.cornerRadius = bubble.frame.size.height / 2
bubble.backgroundColor = bubbleColor
bubble.center = startingPoint
bubble.isHidden = false
UIView.animate(withDuration: duration, animations: {
self.bubble.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
returningControllerView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
returningControllerView.center = self.startingPoint
returningControllerView.alpha = 0
if self.transitionMode == .pop {
containerView.insertSubview(returningControllerView, belowSubview: returningControllerView)
containerView.insertSubview(self.bubble, belowSubview: returningControllerView)
}
}, completion: { (completed) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
if !transitionContext.transitionWasCancelled {
returningControllerView.center = originalCenter
returningControllerView.removeFromSuperview()
self.bubble.removeFromSuperview()
if fromViewController?.modalPresentationStyle == .custom {
fromViewController?.endAppearanceTransition()
}
toViewController?.endAppearanceTransition()
}
})
}
}
}
private extension BubbleTransition {
func frameForBubble(_ originalCenter: CGPoint, size originalSize: CGSize, start: CGPoint) -> CGRect {
let lengthX = fmax(start.x, originalSize.width - start.x)
let lengthY = fmax(start.y, originalSize.height - start.y)
let offset = sqrt(lengthX * lengthX + lengthY * lengthY) * 2
let size = CGSize(width: offset, height: offset)
return CGRect(origin: CGPoint.zero, size: size)
}
}
| be9b1fb686557413e4be0ad8f2635ca8 | 34.151625 | 169 | 0.723529 | false | false | false | false |
nielstj/GLChat | refs/heads/master | GLChat/Model/ChatObject.swift | mit | 1 | //
// ChatObject.swift
// GLChat
//
// Created by Daniel on 16/8/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import Foundation
import UIKit
public enum ChatObjectCellType: Int {
case incoming
case outgoing
case options
case information
}
public protocol ChatObjectType {
var id: String { get }
var type: ChatObjectCellType { get }
var sender: AvatarType { get }
var message: String { get }
var images: [UIImage]? { get }
var timestamp: Date { get }
}
public struct ChatObject: ChatObjectType {
public var id: String
public var type: ChatObjectCellType
public var sender: AvatarType
public var message: String
public var images : [UIImage]?
public var timestamp: Date
public init(id: String,
type: ChatObjectCellType,
sender: AvatarType,
message: String,
images: [UIImage]?,
timestamp: Date) {
self.id = id
self.type = type
self.sender = sender
self.message = message
self.images = images
self.timestamp = timestamp
}
}
| 359008be329a35c48094c288ec32f12d | 21.92 | 50 | 0.609948 | false | false | false | false |
apegroup/APEReactiveNetworking | refs/heads/master | Example/fastlane/SnapshotHelper.swift | mit | 1 | //
// SnapshotHelper.swift
//
//
// Created by Felix Krause on 10/8/15.
// Copyright © 2015 Felix Krause. All rights reserved.
//
import Foundation
import XCTest
var deviceLanguage = ""
@available(*, deprecated, message="use setupSnapshot: instead")
func setLanguage(app: XCUIApplication) {
setupSnapshot(app)
}
func setupSnapshot(app: XCUIApplication) {
Snapshot.setupSnapshot(app)
}
func snapshot(name: String, waitForLoadingIndicator: Bool = false) {
Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator)
}
class Snapshot: NSObject {
class func setupSnapshot(app: XCUIApplication) {
setLanguage(app)
setLaunchArguments(app)
}
class func setLanguage(app: XCUIApplication) {
let path = "/tmp/language.txt"
do {
let locale = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
deviceLanguage = locale.substringToIndex(locale.startIndex.advancedBy(2, limit:locale.endIndex))
app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))", "-AppleLocale", "\"\(locale)\"", "-ui_testing"]
} catch {
print("Couldn't detect/set language...")
}
}
class func setLaunchArguments(app: XCUIApplication) {
let path = "/tmp/snapshot-launch_arguments.txt"
app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES"]
do {
let launchArguments = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: [])
let matches = regex.matchesInString(launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count))
let results = matches.map { result -> String in
(launchArguments as NSString).substringWithRange(result.range)
}
app.launchArguments += results
} catch {
print("Couldn't detect/set launch_arguments...")
}
}
class func snapshot(name: String, waitForLoadingIndicator: Bool = false) {
if waitForLoadingIndicator {
waitForLoadingIndicatorToDisappear()
}
print("snapshot: \(name)") // more information about this, check out https://github.com/krausefx/snapshot
sleep(1) // Waiting for the animation to be finished (kind of)
XCUIDevice.sharedDevice().orientation = .Unknown
}
class func waitForLoadingIndicatorToDisappear() {
let query = XCUIApplication().statusBars.childrenMatchingType(.Other).elementBoundByIndex(1).childrenMatchingType(.Other)
while query.count > 4 {
sleep(1)
print("Number of Elements in Status Bar: \(query.count)... waiting for status bar to disappear")
}
}
}
// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperVersion [[1.0]]
| fb6d6d96f0d0502674211fdb600d69a6 | 33.333333 | 146 | 0.655842 | false | false | false | false |
PokeMapCommunity/PokeMap-iOS | refs/heads/master | PokeMap/Helpers/LocationHelper.swift | mit | 1 | //
// LocationHelper.swift
// PokeMap
//
// Created by Ivan Bruel on 20/07/16.
// Copyright © 2016 Faber Ventures. All rights reserved.
//
import UIKit
import CoreLocation
import RxCocoa
import RxOptional
import RxSwift
class LocationHelper {
static let sharedInstance = LocationHelper()
private lazy var locationManager: CLLocationManager = {
let locationManager = CLLocationManager()
locationManager.distanceFilter = 5
return locationManager
}()
private var disposeBag = DisposeBag()
private var notifiedPokemons = [Pokemon]()
func start() {
locationManager.startMonitoringSignificantLocationChanges()
locationManager.rx_didUpdateLocations
.map { $0.first }
.filterNil()
.flatMap { location in
LocationHelper.loadPokemons(location.coordinate.latitude,
longitude: location.coordinate.longitude).retry(2)
}
.filter { $0.count > 0 }
.subscribeNext { pokemons in
self.notifiedPokemons = self.notifiedPokemons.unique.filter { !$0.expired }
let watchlistedPokemons = pokemons.filter {
Globals.watchlist.contains(($0.pokemonId as NSNumber).stringValue) && !self.notifiedPokemons.contains($0)
}
self.notifiedPokemons = self.notifiedPokemons
.arrayByAppendingContentsOf(watchlistedPokemons)
.unique
guard watchlistedPokemons.count > 0 else {
return
}
self.notifyPokemons(watchlistedPokemons)
}.addDisposableTo(disposeBag)
}
func stop() {
locationManager.stopUpdatingLocation()
disposeBag = DisposeBag()
}
private func notifyPokemons(pokemons: [Pokemon]) {
if pokemons.count == 1 {
showNotification(pokemons[0])
} else {
//pokemons.forEach { showNotification($0) }
showNotification(pokemons.count)
}
}
private func showNotification(pokemon: Pokemon) {
let notification = UILocalNotification()
notification.alertBody =
"\(pokemon.name) is nearby for another \(pokemon.expirationTime.shortTimeAgoSinceNow())"
notification.fireDate = NSDate(timeIntervalSinceNow: 1)
notification.timeZone = NSTimeZone.defaultTimeZone()
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
private func showNotification(numberOfPokemon: Int) {
let notification = UILocalNotification()
notification.alertBody = "\(numberOfPokemon) Rare pokemons nearby!"
notification.fireDate = NSDate(timeIntervalSinceNow: 1)
notification.timeZone = NSTimeZone.defaultTimeZone()
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
private static func loadPokemons(latitude: Double, longitude: Double) -> Observable<[Pokemon]> {
return Network.request(API.Pokemons(latitude: latitude, longitude: longitude, jobId: nil))
.mapArray(Pokemon.self, key: "pokemon")
}
}
| d16a029511e571b7a0b1a3718464d83c | 31.055556 | 115 | 0.713345 | false | false | false | false |
blg-andreasbraun/Operations | refs/heads/development | Sources/Testing/TestProcedure.swift | mit | 2 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
import Foundation
import ProcedureKit
public struct TestError: Error, Equatable {
public static func == (lhs: TestError, rhs: TestError) -> Bool {
return lhs.uuid == rhs.uuid
}
public static func verify(errors: [Error], count: Int = 1, contains error: TestError) -> Bool {
return (errors.count == count) && errors.contains { ($0 as? TestError) ?? TestError() == error }
}
let uuid = UUID()
public init() { }
}
open class TestProcedure: Procedure, InputProcedure, OutputProcedure {
public let delay: TimeInterval
public let error: Error?
public let producedOperation: Operation?
public var input: Pending<Void> = pendingVoid
public var output: Pending<ProcedureResult<String>> = .ready(.success("Hello World"))
public private(set) var executedAt: CFAbsoluteTime = 0
public private(set) var didExecute = false
public private(set) var procedureWillFinishCalled = false
public private(set) var procedureDidFinishCalled = false
public private(set) var procedureWillCancelCalled = false
public private(set) var procedureDidCancelCalled = false
public init(name: String = "TestProcedure", delay: TimeInterval = 0.000_001, error: Error? = .none, produced: Operation? = .none) {
self.delay = delay
self.error = error
self.producedOperation = produced
super.init()
self.name = name
}
open override func execute() {
executedAt = CFAbsoluteTimeGetCurrent()
if let operation = producedOperation {
DispatchQueue.main.asyncAfter(deadline: .now() + (delay / 2.0)) {
try! self.produce(operation: operation) // swiftlint:disable:this force_try
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
self.didExecute = true
self.finish(withError: self.error)
}
}
open override func procedureWillCancel(withErrors: [Error]) {
procedureWillCancelCalled = true
}
open override func procedureDidCancel(withErrors: [Error]) {
procedureDidCancelCalled = true
}
open override func procedureWillFinish(withErrors: [Error]) {
procedureWillFinishCalled = true
}
open override func procedureDidFinish(withErrors: [Error]) {
procedureDidFinishCalled = true
}
}
| 8055655f586affd677a895837a0580f9 | 31.118421 | 135 | 0.661614 | false | true | false | false |
1457792186/JWSwift | refs/heads/develop | NBUStatProject/Pods/Charts/Source/Charts/Utils/Platform.swift | apache-2.0 | 9 | import Foundation
/** This file provides a thin abstraction layer atop of UIKit (iOS, tvOS) and Cocoa (OS X). The two APIs are very much
alike, and for the chart library's usage of the APIs it is often sufficient to typealias one to the other. The NSUI*
types are aliased to either their UI* implementation (on iOS) or their NS* implementation (on OS X). */
#if os(iOS) || os(tvOS)
import UIKit
public typealias NSUIFont = UIFont
public typealias NSUIColor = UIColor
public typealias NSUIEvent = UIEvent
public typealias NSUITouch = UITouch
public typealias NSUIImage = UIImage
public typealias NSUIScrollView = UIScrollView
public typealias NSUIGestureRecognizer = UIGestureRecognizer
public typealias NSUIGestureRecognizerState = UIGestureRecognizerState
public typealias NSUIGestureRecognizerDelegate = UIGestureRecognizerDelegate
public typealias NSUITapGestureRecognizer = UITapGestureRecognizer
public typealias NSUIPanGestureRecognizer = UIPanGestureRecognizer
#if !os(tvOS)
public typealias NSUIPinchGestureRecognizer = UIPinchGestureRecognizer
public typealias NSUIRotationGestureRecognizer = UIRotationGestureRecognizer
#endif
public typealias NSUIScreen = UIScreen
public typealias NSUIDisplayLink = CADisplayLink
extension NSUITapGestureRecognizer
{
@objc final func nsuiNumberOfTouches() -> Int
{
return numberOfTouches
}
@objc final var nsuiNumberOfTapsRequired: Int
{
get
{
return self.numberOfTapsRequired
}
set
{
self.numberOfTapsRequired = newValue
}
}
}
extension NSUIPanGestureRecognizer
{
@objc final func nsuiNumberOfTouches() -> Int
{
return numberOfTouches
}
@objc final func nsuiLocationOfTouch(_ touch: Int, inView: UIView?) -> CGPoint
{
return super.location(ofTouch: touch, in: inView)
}
}
#if !os(tvOS)
extension NSUIRotationGestureRecognizer
{
@objc final var nsuiRotation: CGFloat
{
get { return rotation }
set { rotation = newValue }
}
}
#endif
#if !os(tvOS)
extension NSUIPinchGestureRecognizer
{
@objc final var nsuiScale: CGFloat
{
get
{
return scale
}
set
{
scale = newValue
}
}
@objc final func nsuiLocationOfTouch(_ touch: Int, inView: UIView?) -> CGPoint
{
return super.location(ofTouch: touch, in: inView)
}
}
#endif
open class NSUIView: UIView
{
public final override func touchesBegan(_ touches: Set<NSUITouch>, with event: NSUIEvent?)
{
self.nsuiTouchesBegan(touches, withEvent: event)
}
public final override func touchesMoved(_ touches: Set<NSUITouch>, with event: NSUIEvent?)
{
self.nsuiTouchesMoved(touches, withEvent: event)
}
public final override func touchesEnded(_ touches: Set<NSUITouch>, with event: NSUIEvent?)
{
self.nsuiTouchesEnded(touches, withEvent: event)
}
public final override func touchesCancelled(_ touches: Set<NSUITouch>, with event: NSUIEvent?)
{
self.nsuiTouchesCancelled(touches, withEvent: event)
}
@objc open func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesBegan(touches, with: event!)
}
@objc open func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesMoved(touches, with: event!)
}
@objc open func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesEnded(touches, with: event!)
}
@objc open func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?)
{
super.touchesCancelled(touches!, with: event!)
}
@objc var nsuiLayer: CALayer?
{
return self.layer
}
}
extension UIView
{
@objc final var nsuiGestureRecognizers: [NSUIGestureRecognizer]?
{
return self.gestureRecognizers
}
}
extension UIScrollView
{
@objc var nsuiIsScrollEnabled: Bool
{
get { return isScrollEnabled }
set { isScrollEnabled = newValue }
}
}
extension UIScreen
{
@objc final var nsuiScale: CGFloat
{
return self.scale
}
}
func NSUIGraphicsGetCurrentContext() -> CGContext?
{
return UIGraphicsGetCurrentContext()
}
func NSUIGraphicsGetImageFromCurrentImageContext() -> NSUIImage!
{
return UIGraphicsGetImageFromCurrentImageContext()
}
func NSUIGraphicsPushContext(_ context: CGContext)
{
UIGraphicsPushContext(context)
}
func NSUIGraphicsPopContext()
{
UIGraphicsPopContext()
}
func NSUIGraphicsEndImageContext()
{
UIGraphicsEndImageContext()
}
func NSUIImagePNGRepresentation(_ image: NSUIImage) -> Data?
{
return UIImagePNGRepresentation(image)
}
func NSUIImageJPEGRepresentation(_ image: NSUIImage, _ quality: CGFloat = 0.8) -> Data?
{
return UIImageJPEGRepresentation(image, quality)
}
func NSUIMainScreen() -> NSUIScreen?
{
return NSUIScreen.main
}
func NSUIGraphicsBeginImageContextWithOptions(_ size: CGSize, _ opaque: Bool, _ scale: CGFloat)
{
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
}
#endif
#if os(OSX)
import Cocoa
import Quartz
public typealias NSUIFont = NSFont
public typealias NSUIColor = NSColor
public typealias NSUIEvent = NSEvent
public typealias NSUITouch = NSTouch
public typealias NSUIImage = NSImage
public typealias NSUIScrollView = NSScrollView
public typealias NSUIGestureRecognizer = NSGestureRecognizer
public typealias NSUIGestureRecognizerState = NSGestureRecognizer.State
public typealias NSUIGestureRecognizerDelegate = NSGestureRecognizerDelegate
public typealias NSUITapGestureRecognizer = NSClickGestureRecognizer
public typealias NSUIPanGestureRecognizer = NSPanGestureRecognizer
public typealias NSUIPinchGestureRecognizer = NSMagnificationGestureRecognizer
public typealias NSUIRotationGestureRecognizer = NSRotationGestureRecognizer
public typealias NSUIScreen = NSScreen
/** On OS X there is no CADisplayLink. Use a 60 fps timer to render the animations. */
public class NSUIDisplayLink
{
private var timer: Timer?
private var displayLink: CVDisplayLink?
private var _timestamp: CFTimeInterval = 0.0
private weak var _target: AnyObject?
private var _selector: Selector
public var timestamp: CFTimeInterval
{
return _timestamp
}
init(target: AnyObject, selector: Selector)
{
_target = target
_selector = selector
if CVDisplayLinkCreateWithActiveCGDisplays(&displayLink) == kCVReturnSuccess
{
CVDisplayLinkSetOutputCallback(displayLink!, { (displayLink, inNow, inOutputTime, flagsIn, flagsOut, userData) -> CVReturn in
let _self = unsafeBitCast(userData, to: NSUIDisplayLink.self)
_self._timestamp = CFAbsoluteTimeGetCurrent()
_self._target?.performSelector(onMainThread: _self._selector, with: _self, waitUntilDone: false)
return kCVReturnSuccess
}, Unmanaged.passUnretained(self).toOpaque())
}
else
{
timer = Timer(timeInterval: 1.0 / 60.0, target: target, selector: selector, userInfo: nil, repeats: true)
}
}
deinit
{
stop()
}
open func add(to runloop: RunLoop, forMode mode: RunLoopMode)
{
if displayLink != nil
{
CVDisplayLinkStart(displayLink!)
}
else if timer != nil
{
runloop.add(timer!, forMode: mode)
}
}
open func remove(from: RunLoop, forMode: RunLoopMode)
{
stop()
}
private func stop()
{
if displayLink != nil
{
CVDisplayLinkStop(displayLink!)
}
if timer != nil
{
timer?.invalidate()
}
}
}
/** The 'tap' gesture is mapped to clicks. */
extension NSUITapGestureRecognizer
{
final func nsuiNumberOfTouches() -> Int
{
return 1
}
final var nsuiNumberOfTapsRequired: Int
{
get
{
return self.numberOfClicksRequired
}
set
{
self.numberOfClicksRequired = newValue
}
}
}
extension NSUIPanGestureRecognizer
{
final func nsuiNumberOfTouches() -> Int
{
return 1
}
/// FIXME: Currently there are no more than 1 touch in OSX gestures, and not way to create custom touch gestures.
final func nsuiLocationOfTouch(_ touch: Int, inView: NSView?) -> NSPoint
{
return super.location(in: inView)
}
}
extension NSUIRotationGestureRecognizer
{
/// FIXME: Currently there are no velocities in OSX gestures, and not way to create custom touch gestures.
final var velocity: CGFloat
{
return 0.1
}
final var nsuiRotation: CGFloat
{
get { return -rotation }
set { rotation = -newValue }
}
}
extension NSUIPinchGestureRecognizer
{
final var nsuiScale: CGFloat
{
get
{
return magnification + 1.0
}
set
{
magnification = newValue - 1.0
}
}
/// FIXME: Currently there are no more than 1 touch in OSX gestures, and not way to create custom touch gestures.
final func nsuiLocationOfTouch(_ touch: Int, inView view: NSView?) -> NSPoint
{
return super.location(in: view)
}
}
extension NSView
{
final var nsuiGestureRecognizers: [NSGestureRecognizer]?
{
return self.gestureRecognizers
}
}
extension NSScrollView
{
var nsuiIsScrollEnabled: Bool
{
get { return scrollEnabled }
set { scrollEnabled = newValue }
}
}
open class NSUIView: NSView
{
public final override var isFlipped: Bool
{
return true
}
func setNeedsDisplay()
{
self.setNeedsDisplay(self.bounds)
}
public final override func touchesBegan(with event: NSEvent)
{
self.nsuiTouchesBegan(event.touches(matching: .any, in: self), withEvent: event)
}
public final override func touchesEnded(with event: NSEvent)
{
self.nsuiTouchesEnded(event.touches(matching: .any, in: self), withEvent: event)
}
public final override func touchesMoved(with event: NSEvent)
{
self.nsuiTouchesMoved(event.touches(matching: .any, in: self), withEvent: event)
}
open override func touchesCancelled(with event: NSEvent)
{
self.nsuiTouchesCancelled(event.touches(matching: .any, in: self), withEvent: event)
}
open func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesBegan(with: event!)
}
open func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesMoved(with: event!)
}
open func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
super.touchesEnded(with: event!)
}
open func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?)
{
super.touchesCancelled(with: event!)
}
open var backgroundColor: NSUIColor?
{
get
{
return self.layer?.backgroundColor == nil
? nil
: NSColor(cgColor: self.layer!.backgroundColor!)
}
set
{
self.wantsLayer = true
self.layer?.backgroundColor = newValue == nil ? nil : newValue!.cgColor
}
}
final var nsuiLayer: CALayer?
{
return self.layer
}
}
extension NSFont
{
var lineHeight: CGFloat
{
// Not sure if this is right, but it looks okay
return self.boundingRectForFont.size.height
}
}
extension NSScreen
{
final var nsuiScale: CGFloat
{
return self.backingScaleFactor
}
}
extension NSImage
{
var cgImage: CGImage?
{
return self.cgImage(forProposedRect: nil, context: nil, hints: nil)
}
}
extension NSTouch
{
/** Touch locations on OS X are relative to the trackpad, whereas on iOS they are actually *on* the view. */
func locationInView(view: NSView) -> NSPoint
{
let n = self.normalizedPosition
let b = view.bounds
return NSPoint(x: b.origin.x + b.size.width * n.x, y: b.origin.y + b.size.height * n.y)
}
}
extension NSScrollView
{
var scrollEnabled: Bool
{
get
{
return true
}
set
{
// FIXME: We can't disable scrolling it on OSX
}
}
}
func NSUIGraphicsGetCurrentContext() -> CGContext?
{
return NSGraphicsContext.current?.cgContext
}
func NSUIGraphicsPushContext(_ context: CGContext)
{
let cx = NSGraphicsContext(cgContext: context, flipped: true)
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = cx
}
func NSUIGraphicsPopContext()
{
NSGraphicsContext.restoreGraphicsState()
}
func NSUIImagePNGRepresentation(_ image: NSUIImage) -> Data?
{
image.lockFocus()
let rep = NSBitmapImageRep(focusedViewRect: NSMakeRect(0, 0, image.size.width, image.size.height))
image.unlockFocus()
return rep?.representation(using: .png, properties: [:])
}
func NSUIImageJPEGRepresentation(_ image: NSUIImage, _ quality: CGFloat = 0.9) -> Data?
{
image.lockFocus()
let rep = NSBitmapImageRep(focusedViewRect: NSMakeRect(0, 0, image.size.width, image.size.height))
image.unlockFocus()
return rep?.representation(using: .jpeg, properties: [NSBitmapImageRep.PropertyKey.compressionFactor: quality])
}
private var imageContextStack: [CGFloat] = []
func NSUIGraphicsBeginImageContextWithOptions(_ size: CGSize, _ opaque: Bool, _ scale: CGFloat)
{
var scale = scale
if scale == 0.0
{
scale = NSScreen.main?.backingScaleFactor ?? 1.0
}
let width = Int(size.width * scale)
let height = Int(size.height * scale)
if width > 0 && height > 0
{
imageContextStack.append(scale)
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 4*width, space: colorSpace, bitmapInfo: (opaque ? CGImageAlphaInfo.noneSkipFirst.rawValue : CGImageAlphaInfo.premultipliedFirst.rawValue))
else { return }
ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: CGFloat(height)))
ctx.scaleBy(x: scale, y: scale)
NSUIGraphicsPushContext(ctx)
}
}
func NSUIGraphicsGetImageFromCurrentImageContext() -> NSUIImage?
{
if !imageContextStack.isEmpty
{
guard let ctx = NSUIGraphicsGetCurrentContext()
else { return nil }
let scale = imageContextStack.last!
if let theCGImage = ctx.makeImage()
{
let size = CGSize(width: CGFloat(ctx.width) / scale, height: CGFloat(ctx.height) / scale)
let image = NSImage(cgImage: theCGImage, size: size)
return image
}
}
return nil
}
func NSUIGraphicsEndImageContext()
{
if imageContextStack.last != nil
{
imageContextStack.removeLast()
NSUIGraphicsPopContext()
}
}
func NSUIMainScreen() -> NSUIScreen?
{
return NSUIScreen.main
}
#endif
| eab3eae9edda819a0581cfd931e35d5f | 25.512235 | 243 | 0.626446 | false | false | false | false |
xwu/swift | refs/heads/master | test/Concurrency/Runtime/async_taskgroup_cancelAll_only_specific_group.swift | apache-2.0 | 1 | // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input always
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
import Dispatch
@available(SwiftStdlib 5.5, *)
func asyncEcho(_ value: Int) async -> Int {
value
}
/// Tests that only the specific group we cancelAll on is cancelled,
/// and not accidentally all tasks in all groups within the given parent task.
@available(SwiftStdlib 5.5, *)
func test_taskGroup_cancelAll_onlySpecificGroup() async {
async let g1: Int = withTaskGroup(of: Int.self) { group in
for i in 1...5 {
group.spawn {
await Task.sleep(1_000_000_000)
let c = Task.isCancelled
print("add: \(i) (cancelled: \(c))")
return i
}
}
var sum = 0
while let got = try! await group.next() {
print("next: \(got)")
sum += got
}
let c = Task.isCancelled
print("g1 task cancelled: \(c)")
let cc = group.isCancelled
print("g1 group cancelled: \(cc)")
return sum
}
// The cancellation os g2 should have no impact on g1
let g2: Int = try! await withTaskGroup(of: Int.self) { group in
for i in 1...3 {
group.spawn {
await Task.sleep(1_000_000_000)
let c = Task.isCancelled
print("g1 task \(i) (cancelled: \(c))")
return i
}
}
print("cancelAll")
group.cancelAll()
let c = Task.isCancelled
print("g2 task cancelled: \(c)")
let cc = group.isCancelled
print("g2 group cancelled: \(cc)")
return 0
}
let result1 = try! await g1
let result2 = try! await g2
// CHECK: g2 task cancelled: false
// CHECK: g2 group cancelled: true
// CHECK: g1 task cancelled: false
// CHECK: g1 group cancelled: false
print("g1: \(result1)") // CHECK: g1: 15
print("g2: \(result2)") // CHECK: g2: 0
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
await test_taskGroup_cancelAll_onlySpecificGroup()
}
}
| 6eb48a91e1845f21c8300c1767bd79c1 | 23.678161 | 150 | 0.630647 | false | false | false | false |
gtcode/GTMetronome | refs/heads/master | GTMetronome/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// GTMetronome
//
// Created by Paul Lowndes on 8/3/17.
// Copyright © 2017 Paul Lowndes. All rights reserved.
//
import UIKit
import CoreData
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// per: https://github.com/gtcode/Learning-AV-Foundation-Swift/blob/master/Chapter%202/AudioLooper/AudioLooper/AppDelegate.swift
let audioSession = AVAudioSession.sharedInstance()
do {
// https://developer.apple.com/documentation/avfoundation/avaudiosession/audio_session_categories
try audioSession.setCategory(
AVAudioSessionCategoryPlayback
, mode: AVAudioSessionModeDefault
, options: [
AVAudioSessionCategoryOptions.mixWithOthers
]
)
try audioSession.setActive(
true
)
} catch let error as NSError {
print("AVAudioSession configuration error: \(error.localizedDescription)")
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "GTMetronome")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 27ad96a8e81e533d48768fca3dbf2411 | 44.504587 | 281 | 0.726008 | false | false | false | false |
koogawa/iSensorSwift | refs/heads/master | iSensorSwift/Controller/BrightnessViewController.swift | mit | 1 | //
// BrightnessViewController.swift
// iSensorSwift
//
// Created by koogawa on 2016/03/21.
// Copyright © 2016 koogawa. All rights reserved.
//
import UIKit
class BrightnessViewController: UIViewController {
@IBOutlet weak var brightnessLabel: UILabel!
@IBOutlet weak var brightStepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
// Setup UIStepper
let screen = UIScreen.main
self.brightStepper.value = Double(screen.brightness)
self.updateBrightnessLabel()
// Observe screen brightness
NotificationCenter.default.addObserver(self,
selector: #selector(screenBrightnessDidChange(_:)),
name: NSNotification.Name.UIScreenBrightnessDidChange,
object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Finish observation
NotificationCenter.default.removeObserver(self,
name: NSNotification.Name.UIScreenBrightnessDidChange,
object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Internal methods
func updateBrightnessLabel() {
let screen = UIScreen.main
self.brightnessLabel.text = "".appendingFormat("%.2f", screen.brightness)
}
@objc func screenBrightnessDidChange(_ notification: Notification) {
if let screen = notification.object {
self.brightnessLabel.text = "".appendingFormat("%.2f", (screen as AnyObject).brightness)
}
}
// MARK: - Action methods
@IBAction func stepperDidTap(_ stepper: UIStepper) {
UIScreen.main.brightness = CGFloat(stepper.value)
self.updateBrightnessLabel()
}
}
| 09019a0cf5f70b6b0133a9ec79d450c3 | 30.984615 | 114 | 0.589707 | false | false | false | false |
q231950/appwatch | refs/heads/master | AppWatchLogic/AppWatchLogic/TimeWarehouses/TimeWarehouse.swift | mit | 1 | //
// TimeWarehouse.swift
// AppWatch
//
// Created by Martin Kim Dung-Pham on 16.08.15.
// Copyright © 2015 Martin Kim Dung-Pham. All rights reserved.
//
import Foundation
extension NSDate {
func endedWithinRange(from: NSDate, to: NSDate) -> Bool {
return (self.compare(to) == NSComparisonResult.OrderedAscending && self.compare(from) == NSComparisonResult.OrderedDescending) || self.compare(to) == NSComparisonResult.OrderedSame
}
func beganWithinRange(from: NSDate, to: NSDate) -> Bool {
return (self.compare(to) == NSComparisonResult.OrderedDescending && self.compare(from) == NSComparisonResult.OrderedAscending ) || self.compare(from) == NSComparisonResult.OrderedSame
}
}
protocol TimeWarehouse {
func timeBoxes(from: NSDate, to: NSDate, completion: ([TimeBox]?, NSError?) -> Void)
} | ff1f18de4f5be431b3c802f7cc0a7a2c | 35.478261 | 191 | 0.708831 | false | false | false | false |
Acidburn0zzz/firefox-ios | refs/heads/main | Client/Frontend/AuthenticationManager/RequirePasscodeIntervalViewController.swift | mpl-2.0 | 1 | /* 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
import SwiftKeychainWrapper
/// Screen presented to the user when selecting the time interval before requiring a passcode
class RequirePasscodeIntervalViewController: UITableViewController {
let intervalOptions: [PasscodeInterval] = [
.immediately,
.oneMinute,
.fiveMinutes,
.tenMinutes,
.fifteenMinutes,
.oneHour
]
fileprivate let BasicCheckmarkCell = "BasicCheckmarkCell"
fileprivate var authenticationInfo: AuthenticationKeychainInfo?
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = .AuthenticationRequirePasscode
tableView.accessibilityIdentifier = "AuthenticationManager.passcodeIntervalTableView"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: BasicCheckmarkCell)
tableView.backgroundColor = UIColor.theme.tableView.headerBackground
let headerFooterFrame = CGRect(width: self.view.frame.width, height: SettingsUX.TableViewHeaderFooterHeight)
let headerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame)
headerView.showBorder(for: .bottom, true)
let footerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame)
footerView.showBorder(for: .top, true)
tableView.tableHeaderView = headerView
tableView.tableFooterView = footerView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.authenticationInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo()
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: BasicCheckmarkCell, for: indexPath)
let option = intervalOptions[indexPath.row]
let intervalTitle = NSAttributedString.tableRowTitle(option.settingTitle, enabled: true)
cell.textLabel?.attributedText = intervalTitle
cell.accessoryType = authenticationInfo?.requiredPasscodeInterval == option ? .checkmark : .none
cell.backgroundColor = UIColor.theme.tableView.rowBackground
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return intervalOptions.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
authenticationInfo?.updateRequiredPasscodeInterval(intervalOptions[indexPath.row])
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo)
tableView.reloadData()
}
}
| 0648fcd1aaa0f6487c3864a8803c1b50 | 39.657895 | 116 | 0.733333 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | refs/heads/master | iOS/Venue/Views/MyLocationAnnotation.swift | epl-1.0 | 1 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/// Subclass of VenueMapAnnotation. Represents an annotation for the user's current location.
class MyLocationAnnotation: VenueMapAnnotation {
var userObject: User!
private let imageName = "your_location"
private var referencePoint = CGPoint()
init(user: User, location: CGPoint) {
self.userObject = user
let backgroundImage = UIImage(named: imageName)!
// Setup the frame for the button
referencePoint = location
let x = self.referencePoint.x - (backgroundImage.size.width / 2)
let y = self.referencePoint.y - (backgroundImage.size.height / 2)
super.init(frame: CGRect(x: x, y: y, width: backgroundImage.size.width, height: backgroundImage.size.height))
self.setBackgroundImage(backgroundImage, forState: UIControlState.Normal)
self.accessibilityIdentifier = self.userObject.name
self.accessibilityHint = "Current User"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func updateLocation(mapZoomScale: CGFloat) {
self.center.x = (self.referencePoint.x * mapZoomScale)
self.center.y = (self.referencePoint.y * mapZoomScale)
}
override func updateReferencePoint(newReferencePoint: CGPoint, mapZoomScale: CGFloat) {
self.referencePoint = newReferencePoint
self.updateLocation(mapZoomScale)
}
override func annotationSelected(mapZoomScale: CGFloat) {
// Nothing happens for this type of annotation
}
override func getReferencePoint() -> CGPoint {
return self.referencePoint
}
}
| d19f64163e0cbbe81c9a24032784c85e | 32.396226 | 117 | 0.681356 | false | false | false | false |
devxoul/URLNavigator | refs/heads/master | Tests/URLMatcherTests/URLConvertibleSpec.swift | mit | 1 | import Foundation
import Nimble
import Quick
import URLMatcher
final class URLConvertibleSpec: QuickSpec {
override func spec() {
describe("urlValue") {
it("returns an URL instance") {
let url = URL(string: "https://xoul.kr")!
expect(url.urlValue) == url
expect(url.absoluteString.urlValue) == url
}
it("returns an URL instance from unicode string") {
let urlString = "https://xoul.kr/한글"
expect(urlString.urlValue) == URL(string: "https://xoul.kr/%ED%95%9C%EA%B8%80")!
}
}
describe("urlStringValue") {
it("returns a URL string value") {
let url = URL(string: "https://xoul.kr")!
expect(url.urlStringValue) == url.absoluteString
expect(url.absoluteString.urlStringValue) == url.absoluteString
}
}
describe("queryParameters") {
context("when there is no query string") {
it("returns empty dictionary") {
let url = "https://xoul.kr"
expect(url.urlValue?.queryParameters) == [:]
expect(url.urlStringValue.queryParameters) == [:]
}
}
context("when there is an empty query string") {
it("returns empty dictionary") {
let url = "https://xoul.kr?"
expect(url.urlValue?.queryParameters) == [:]
expect(url.urlStringValue.queryParameters) == [:]
}
}
context("when there is a query string") {
let url = "https://xoul.kr?key=this%20is%20a%20value&greeting=hello+world!&int=12&int=34&url=https://foo/bar?hello=world"
it("has proper keys") {
expect(Set(url.urlValue!.queryParameters.keys)) == ["key", "greeting", "int", "url"]
expect(Set(url.urlStringValue.queryParameters.keys)) == ["key", "greeting", "int", "url"]
}
it("decodes a percent encoding") {
expect(url.urlValue?.queryParameters["key"]) == "this is a value"
expect(url.urlStringValue.queryParameters["key"]) == "this is a value"
}
it("doesn't convert + to whitespace") {
expect(url.urlValue?.queryParameters["greeting"]) == "hello+world!"
expect(url.urlStringValue.queryParameters["greeting"]) == "hello+world!"
}
it("takes last value from duplicated keys") {
expect(url.urlValue?.queryParameters["int"]) == "34"
expect(url.urlStringValue.queryParameters["int"]) == "34"
}
it("has an url") {
expect(url.urlValue?.queryParameters["url"]) == "https://foo/bar?hello=world"
}
}
}
describe("queryItems") {
context("when there is no query string") {
it("returns nil") {
let url = "https://xoul.kr"
expect(url.urlValue?.queryItems).to(beNil())
expect(url.urlStringValue.queryItems).to(beNil())
}
}
context("when there is an empty query string") {
it("returns an empty array") {
let url = "https://xoul.kr?"
expect(url.urlValue?.queryItems) == []
expect(url.urlStringValue.queryItems) == []
}
}
context("when there is a query string") {
let url = "https://xoul.kr?key=this%20is%20a%20value&greeting=hello+world!&int=12&int=34"
it("has exact number of items") {
expect(url.urlValue?.queryItems?.count) == 4
expect(url.urlStringValue.queryItems?.count) == 4
}
it("decodes a percent encoding") {
expect(url.urlValue?.queryItems?[0]) == URLQueryItem(name: "key", value: "this is a value")
expect(url.urlStringValue.queryItems?[0]) == URLQueryItem(name: "key", value: "this is a value")
}
it("doesn't convert + to whitespace") {
expect(url.urlValue?.queryItems?[1]) == URLQueryItem(name: "greeting", value: "hello+world!")
expect(url.urlStringValue.queryItems?[1]) == URLQueryItem(name: "greeting", value: "hello+world!")
}
it("takes all duplicated keys") {
expect(url.urlValue?.queryItems?[2]) == URLQueryItem(name: "int", value: "12")
expect(url.urlValue?.queryItems?[3]) == URLQueryItem(name: "int", value: "34")
expect(url.urlStringValue.queryItems?[2]) == URLQueryItem(name: "int", value: "12")
expect(url.urlStringValue.queryItems?[3]) == URLQueryItem(name: "int", value: "34")
}
}
}
}
}
| a44ebce4f359cf84c7a14885a3c95136 | 35.289256 | 129 | 0.58506 | false | false | false | false |
mahomealex/MASQLiteWrapper | refs/heads/master | MASQLiteWrapper/Source/SQObject.swift | mit | 2 | //
// Object.swift
//
//
// Created by alex on 25/04/2017.
// Copyright © 2017 alex. All rights reserved.
//
import Foundation
open class SQObject : NSObject {
required override public init() {
super.init()
}
func generalSchema() -> SQObjectSchema {
var properties:[SQProperty] = []
let mm = Mirror(reflecting: self)
let pk = self.primaryKey()
let ignoreKeys = self.ignoreKeys()
var primaryKeyIndex = 0
for (index, p) in mm.children.enumerated() {
let label = p.label!
if ignoreKeys.contains(label) {
continue
}
let vm = Mirror(reflecting: p.value)
let propertyType = vm.subjectType
var type:SQPropertyType = .String
let typeString = "\(propertyType)"
if typeString.contains("String") {
if typeString.contains("Optional") {
type = .OptionString
} else {
type = .String
}
} else if (typeString.contains("NSDate")) {
fatalError("property is nsdate")
} else if (typeString.contains("Int")) {
type = .Int64
} else if (typeString.contains("Bool")) {
type = .Bool
} else if (typeString.contains("Double") || typeString.contains("Float")) {
type = .Double
} else {
fatalError("property is undefined type")
}
if label == pk {
primaryKeyIndex = index
}
let pt = SQProperty(name: label, type: type, primary: primaryKeyIndex == index)
properties.append(pt)
}
return SQObjectSchema(className: "\(mm.subjectType)", properties: properties, primaryKeyIndex:primaryKeyIndex, cl:type(of: self))
}
func primaryKey() -> String {
return ""
}
func ignoreKeys() -> [String] {
return []
}
}
| b26c00763855cb5424725da4f14e8bba | 28.112676 | 137 | 0.506531 | false | false | false | false |
tlax/looper | refs/heads/master | looper/Model/Camera/Compress/MCameraCompressItemSlight.swift | mit | 1 | import UIKit
class MCameraCompressItemSlight:MCameraCompressItem
{
private let kPercent:Int = 50
private let kRemoveInterval:Int = 1
init()
{
let title:String = NSLocalizedString("MCameraCompressItemSlight_title", comment:"")
let color:UIColor = UIColor(red:0.5, green:0.7, blue:0, alpha:1)
super.init(title:title, percent:kPercent, color:color)
}
override func compress(record:MCameraRecord) -> MCameraRecord?
{
let removeRecord:MCameraRecord = removeInterItems(
record:record,
intervalRemove:kRemoveInterval)
return removeRecord
}
}
| 407db6d3bac5acdd88d73ec8c06b71e2 | 26.5 | 91 | 0.648485 | false | false | false | false |
cpageler93/RAML-Swift | refs/heads/master | Sources/DocumentationEntry.swift | mit | 1 | //
// RAML+DocumentationEntry.swift
// RAML
//
// Created by Christoph Pageler on 24.06.17.
//
import Foundation
import Yaml
import PathKit
public class DocumentationEntry: HasAnnotations {
public var title: String
public var content: String
public var annotations: [Annotation]?
public init(title: String, content: String) {
self.title = title
self.content = content
}
internal init() {
self.title = ""
self.content = ""
}
}
// MARK: Documentation Parsing
internal extension RAML {
internal func parseDocumentation(_ input: ParseInput) throws -> [DocumentationEntry]? {
guard let yaml = input.yaml else { return nil }
switch yaml {
case .array(let yamlArray):
return try parseDocumentation(array: yamlArray, parentFilePath: input.parentFilePath)
case .string(let yamlString):
let (yaml, path) = try parseDocumentationEntriesFromIncludeString(yamlString, parentFilePath: input.parentFilePath)
guard let documentationEntriesArray = yaml.array else {
throw RAMLError.ramlParsingError(.invalidInclude)
}
return try parseDocumentation(array: documentationEntriesArray, parentFilePath: path)
default: return nil
}
}
private func parseDocumentation(array: [Yaml], parentFilePath: Path?) throws -> [DocumentationEntry] {
var documentation: [DocumentationEntry] = []
for yamlDocumentationEntry in array {
guard let title = yamlDocumentationEntry["title"].string else {
throw RAMLError.ramlParsingError(.missingValueFor(key: "title"))
}
guard var content = yamlDocumentationEntry["content"].string else {
throw RAMLError.ramlParsingError(.missingValueFor(key: "content"))
}
if isInclude(content) {
try testInclude(content)
guard let parentFilePath = parentFilePath else {
throw RAMLError.ramlParsingError(.invalidInclude)
}
content = try contentFromIncludeString(content, parentFilePath: parentFilePath)
}
let documentationEntry = DocumentationEntry(title: title, content: content)
documentationEntry.annotations = try parseAnnotations(ParseInput(yamlDocumentationEntry, parentFilePath))
documentation.append(documentationEntry)
}
return documentation
}
private func parseDocumentationEntriesFromIncludeString(_ includeString: String, parentFilePath: Path?) throws -> (Yaml, Path) {
return try parseYamlFromIncludeString(includeString, parentFilePath: parentFilePath, permittedFragmentIdentifier: "DocumentationItem")
}
}
public protocol HasDocumentationEntries {
var documentation: [DocumentationEntry]? { get set }
}
public extension HasDocumentationEntries {
func documentationEntryWith(title: String) -> DocumentationEntry? {
for documentationEntry in documentation ?? [] {
if documentationEntry.title == title {
return documentationEntry
}
}
return nil
}
func hasDocumentationEntryWith(title: String) -> Bool {
return documentationEntryWith(title: title) != nil
}
}
// MARK: Default Values
public extension DocumentationEntry {
public convenience init(initWithDefaultsBasedOn documentationEntry: DocumentationEntry) {
self.init()
self.title = documentationEntry.title
self.content = documentationEntry.content
self.annotations = documentationEntry.annotations?.map { $0.applyDefaults() }
}
public func applyDefaults() -> DocumentationEntry {
return DocumentationEntry(initWithDefaultsBasedOn: self)
}
}
| 8c34baac5094bf9a47a6bcd7926fdc01 | 32.141667 | 142 | 0.646719 | false | false | false | false |
lennet/proNotes | refs/heads/master | app/proNotes/Document/DocumentInstance.swift | mit | 1 | //
// DocumentInstance.swift
// proNotes
//
// Created by Leo Thomas on 29/11/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
@objc
protocol DocumentInstanceDelegate: class {
@objc optional func currentPageDidChange(_ page: DocumentPage)
@objc optional func didAddPage(_ index: Int)
@objc optional func didUpdatePage(_ index: Int)
}
class DocumentInstance {
static let sharedInstance = DocumentInstance()
var delegates = Set<UIViewController>()
var undoManager: UndoManager? {
get {
let manager = PagesTableViewController.sharedInstance?.undoManager
manager?.levelsOfUndo = 5
return manager
}
}
weak var currentPage: DocumentPage? {
didSet {
if currentPage != nil && oldValue != currentPage {
informDelegateToUpdateCurrentPage(currentPage!)
}
}
}
var document: Document? {
didSet {
if document != nil {
if oldValue == nil {
currentPage = document?.pages.first
}
}
}
}
func didUpdatePage(_ index: Int) {
document?.updateChangeCount(.done)
informDelegateDidUpdatePage(index)
}
func save(_ completionHandler: ((Bool) -> Void)?) {
document?.save(to: document!.fileURL, for: .forOverwriting, completionHandler: completionHandler)
}
func flushUndoManager() {
undoManager?.removeAllActions()
NotificationCenter.default.post(name: NSNotification.Name.NSUndoManagerWillUndoChange, object: nil)
}
// MARK: - NSUndoManager
func registerUndoAction(_ object: Any?, pageIndex: Int, layerIndex: Int) {
(undoManager?.prepare(withInvocationTarget: self) as? DocumentInstance)?.undoAction(object, pageIndex: pageIndex, layerIndex: layerIndex)
}
func undoAction(_ object: Any?, pageIndex: Int, layerIndex: Int) {
if let pageView = PagesTableViewController.sharedInstance?.currentPageView {
if pageView.page?.index == pageIndex {
if let pageSubView = pageView[layerIndex] {
pageSubView.undoAction?(object)
return
}
}
}
// Swift 😍
document?[pageIndex]?[layerIndex]?.undoAction(object)
}
// MARK: - Delegate Handling
func addDelegate(_ delegate: DocumentInstanceDelegate) {
if let viewController = delegate as? UIViewController {
if !delegates.contains(viewController) {
delegates.insert(viewController)
}
}
}
func removeDelegate(_ delegate: DocumentInstanceDelegate) {
if let viewController = delegate as? UIViewController {
if delegates.contains(viewController) {
delegates.remove(viewController)
}
}
}
func removeAllDelegates() {
for case let delegate as DocumentInstanceDelegate in delegates {
removeDelegate(delegate)
}
}
func informDelegateToUpdateCurrentPage(_ page: DocumentPage) {
for case let delegate as DocumentInstanceDelegate in delegates {
delegate.currentPageDidChange?(page)
}
}
func informDelegateDidAddPage(_ index: Int) {
for case let delegate as DocumentInstanceDelegate in delegates {
delegate.didAddPage?(index)
}
}
func informDelegateDidUpdatePage(_ index: Int) {
for case let delegate as DocumentInstanceDelegate in delegates {
delegate.didUpdatePage?(index)
}
}
}
| 14e29c19480aae40609714f73e86387e | 28.285714 | 145 | 0.612466 | false | false | false | false |
KoalaTeaCode/KoalaTeaPlayer | refs/heads/master | KoalaTeaPlayer/Classes/YTView/YTViewControllerPresenters.swift | mit | 1 | //
// YTViewControllerPresenter.swift
// KoalaTeaPlayer
//
// Created by Craig Holliday on 12/6/17.
//
import UIKit
open class YTViewControllerPresenter: UIViewController {
var ytNavigationController: YTViewController? = nil
override open func viewDidLoad() {
super.viewDidLoad()
guard let navigationController = self.navigationController as? YTViewController else {
print("The navigation controller is not a YTViewController")
return
}
self.ytNavigationController = navigationController
self.ytNavigationController?.ytViewControllerDelegate = self
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
open func loadYTPlayerViewWith(assetName: String, videoURL: URL, artworkURL: URL? = nil, savedTime: Float = 0) {
guard let ytNavigationController = ytNavigationController else { return }
ytNavigationController.loadYTPlayerViewWith(assetName: assetName, videoURL: videoURL, artworkURL: artworkURL, savedTime: savedTime)
self.hideStatusBar()
}
open func showStatusBar() {
statusBarShouldBeHidden = false
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open func hideStatusBar() {
statusBarShouldBeHidden = true
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open var statusBarShouldBeHidden = false
override open var prefersStatusBarHidden: Bool {
return statusBarShouldBeHidden
}
override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
}
extension YTViewControllerPresenter: YTViewControllerDelegate {
public func didMinimize() {
showStatusBar()
}
public func didmaximize() {
hideStatusBar()
}
public func didSwipeAway() {
}
}
open class YTViewControllerTablePresenter: UITableViewController {
var ytNavigationController: YTViewController? = nil
override open func viewDidLoad() {
super.viewDidLoad()
guard let navigationController = self.navigationController as? YTViewController else {
print("The navigation controller is not a YTViewController")
return
}
self.ytNavigationController = navigationController
self.ytNavigationController?.ytViewControllerDelegate = self
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
open func loadYTPlayerViewWith(assetName: String, videoURL: URL, artworkURL: URL? = nil, savedTime: Float = 0) {
guard let ytNavigationController = ytNavigationController else { return }
ytNavigationController.loadYTPlayerViewWith(assetName: assetName, videoURL: videoURL, artworkURL: artworkURL, savedTime: savedTime)
self.hideStatusBar()
}
open func showStatusBar() {
statusBarShouldBeHidden = false
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open func hideStatusBar() {
statusBarShouldBeHidden = true
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open var statusBarShouldBeHidden = false
override open var prefersStatusBarHidden: Bool {
return statusBarShouldBeHidden
}
override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
}
extension YTViewControllerTablePresenter: YTViewControllerDelegate {
public func didMinimize() {
showStatusBar()
}
public func didmaximize() {
hideStatusBar()
}
public func didSwipeAway() {
}
}
open class YTViewControllerCollectionPresenter: UICollectionViewController {
var ytNavigationController: YTViewController? = nil
override open func viewDidLoad() {
super.viewDidLoad()
guard let navigationController = self.navigationController as? YTViewController else {
print("The navigation controller is not a YTViewController")
return
}
self.ytNavigationController = navigationController
self.ytNavigationController?.ytViewControllerDelegate = self
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
open func loadYTPlayerViewWith(assetName: String, videoURL: URL, artworkURL: URL? = nil, savedTime: Float = 0) {
guard let ytNavigationController = ytNavigationController else { return }
ytNavigationController.loadYTPlayerViewWith(assetName: assetName, videoURL: videoURL, artworkURL: artworkURL, savedTime: savedTime)
self.hideStatusBar()
}
open func showStatusBar() {
statusBarShouldBeHidden = false
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open func hideStatusBar() {
statusBarShouldBeHidden = true
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open var statusBarShouldBeHidden = false
override open var prefersStatusBarHidden: Bool {
return statusBarShouldBeHidden
}
override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
}
extension YTViewControllerCollectionPresenter: YTViewControllerDelegate {
public func didMinimize() {
showStatusBar()
}
public func didmaximize() {
hideStatusBar()
}
public func didSwipeAway() {
}
}
| b85ec26818013135c6120db62045f28a | 28.832512 | 139 | 0.670244 | false | false | false | false |
Dibel/androidtool-mac | refs/heads/master | AndroidTool/DeviceDiscoverer.swift | apache-2.0 | 1 | //
// DeviceDiscoverer.swift
// AndroidTool
//
// Created by Morten Just Petersen on 4/22/15.
// Copyright (c) 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
import AVFoundation
protocol DeviceDiscovererDelegate {
func devicesUpdated(deviceList:[Device])
}
class DeviceDiscoverer:NSObject, IOSDeviceDelegate {
var delegate : DeviceDiscovererDelegate!
var previousDevices = [Device]()
var updatingSuspended = false
var mainTimer : NSTimer!
var updateInterval:NSTimeInterval = 3
var iosDeviceHelper : IOSDeviceHelper!
var iosDevices = [Device]()
var androidDevices = [Device]()
func start(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: "suspend", name: "suspendAdb", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "unSuspend", name: "unSuspendAdb", object: nil)
mainTimer = NSTimer.scheduledTimerWithTimeInterval(updateInterval, target: self, selector: "pollDevices", userInfo: nil, repeats: false)
mainTimer.fire()
/// start IOSDeviceHelper by instantiating
iosDeviceHelper = IOSDeviceHelper(delegate: self)
iosDeviceHelper.startObservingIOSDevices()
}
func stop(){}
func getSerials(thenDoThis:(serials:[String]?, gotResults:Bool)->Void, finished:()->Void){
ShellTasker(scriptFile: "getSerials").run() { (output) -> Void in
let str = String(output)
if str.utf16.count < 2 {
thenDoThis(serials: nil, gotResults: false)
finished()
return
}
let serials = str.characters.split { $0 == ";" }.map { String($0) }
thenDoThis(serials: serials, gotResults:true)
finished()
}
}
func getDetailsForSerial(serial:String, complete:(details:[String:String])->Void){
ShellTasker(scriptFile: "getDetailsForSerial").run(arguments: ["\(serial)"], isUserScript: false) { (output) -> Void in
let detailsDict = self.getPropsFromString(output as String)
complete(details:detailsDict)
}
}
func pollDevices(){
var newDevices = [Device]()
if updatingSuspended { return }
print("+", terminator: "")
getSerials({ (serials, gotResults) -> Void in
if gotResults {
for serial in serials! {
self.getDetailsForSerial(serial, complete: { (details) -> Void in
let device = Device(properties: details, adbIdentifier:serial)
newDevices.append(device)
if serials!.count == newDevices.count {
self.newDeviceCollector(updateWithList: newDevices, forDeviceOS:.Android)
}
})
}
} else {
self.newDeviceCollector(updateWithList: newDevices, forDeviceOS:.Android)
}
}, finished: { () -> Void in
// not really doing anything here afterall
})
mainTimer = NSTimer.scheduledTimerWithTimeInterval(updateInterval, target: self, selector: "pollDevices", userInfo: nil, repeats: false)
}
func suspend(){
// some activites will break an open connection, an example is screen recording.
updatingSuspended = true
}
func unSuspend(){
updatingSuspended = false
}
func getPropsFromString(string:String) -> [String:String] {
let re = try! NSRegularExpression(pattern: "\\[(.+?)\\]: \\[(.+?)\\]", options: [])
let matches = re.matchesInString(string, options: [], range: NSRange(location: 0, length: string.utf16.count))
var propDict = [String:String]()
for match in matches {
let key = (string as NSString).substringWithRange(match.rangeAtIndex(1))
let value = (string as NSString).substringWithRange(match.rangeAtIndex(2))
propDict[key] = value
}
return propDict
}
func iosDeviceAttached(device:AVCaptureDevice){
// instantiate new Device, check if we know it, add to iosDevices[], tell deviceCollector about it
print("Found device \(device.localizedName)")
let newDevice = Device(avDevice: device)
var known = false
for d in iosDevices {
if d.uuid == newDevice.uuid {
print("wtf, already exists")
known = true
}
}
if !known {
iosDevices.append(newDevice)
newDeviceCollector(updateWithList: iosDevices, forDeviceOS: .Ios)
// tell deviceCollector to merge with Android device and fire an update
}
}
func newDeviceCollector(updateWithList deviceList: [Device], forDeviceOS:DeviceOS){
var allDevices = [Device]()
// merge lists
if forDeviceOS == .Android {
androidDevices = deviceList
}
if forDeviceOS == .Ios {
iosDevices = deviceList
}
allDevices = androidDevices + iosDevices
delegate.devicesUpdated(allDevices)
}
func iosDeviceDetached(device:AVCaptureDevice){
// find the lost device in iosDevices[], remove it, and tell newDeviceCollector about it
for index in 0...(iosDevices.count-1) {
if iosDevices[index].uuid == device.uniqueID {
print("removing \(device.localizedName)")
iosDevices.removeAtIndex(index)
newDeviceCollector(updateWithList: iosDevices, forDeviceOS: .Ios)
}
}
}
func iosDeviceDidStartPreparing(device:AVCaptureDevice){
// this happens when
}
func iosDeviceDidEndPreparing(){}
} | be78f9d699e77aeb1be83f948471c6e9 | 33.534884 | 144 | 0.592524 | false | false | false | false |
devcastid/iOS-Tutorials | refs/heads/master | Davcast-iOS/Pods/Material/Sources/Menu.swift | mit | 1 | /*
* Copyright (C) 2015 - 20spacing, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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 HOLDER 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 UIKit
public enum MenuDirection {
case Up
case Down
case Left
case Right
}
public class Menu {
/// A Boolean that indicates if the menu is open or not.
public private(set) var opened: Bool = false
/// The rectangular bounds that the menu animates.
public var origin: CGPoint {
didSet {
reloadLayout()
}
}
/// The space between views.
public var spacing: CGFloat {
didSet {
reloadLayout()
}
}
/// Enables the animations for the Menu.
public var enabled: Bool = true
/// The direction in which the animation opens the menu.
public var direction: MenuDirection = .Up {
didSet {
reloadLayout()
}
}
/// An Array of UIViews.
public var views: Array<UIView>? {
didSet {
reloadLayout()
}
}
/// Size of views, not including the first view.
public var itemViewSize: CGSize = CGSizeMake(48, 48)
/// An Optional base view size.
public var baseViewSize: CGSize?
/**
Initializer.
- Parameter origin: The origin position of the Menu.
- Parameter spacing: The spacing size between views.
*/
public init(origin: CGPoint, spacing: CGFloat = 16) {
self.origin = origin
self.spacing = spacing
}
/// Reload the view layout.
public func reloadLayout() {
opened = false
layoutButtons()
}
/**
Open the Menu component with animation options.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func open(duration duration: NSTimeInterval = 0.15, delay: NSTimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
if enabled {
disable()
switch direction {
case .Up:
openUpAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Down:
openDownAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Left:
openLeftAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Right:
openRightAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
}
}
}
/**
Close the Menu component with animation options.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func close(duration duration: NSTimeInterval = 0.15, delay: NSTimeInterval = 0, usingSpringWithDamping: CGFloat = 0.5, initialSpringVelocity: CGFloat = 0, options: UIViewAnimationOptions = [], animations: ((UIView) -> Void)? = nil, completion: ((UIView) -> Void)? = nil) {
if enabled {
disable()
switch direction {
case .Up:
closeUpAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Down:
closeDownAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Left:
closeLeftAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
case .Right:
closeRightAnimation(duration, delay: delay, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: completion)
}
}
}
/**
Open the Menu component with animation options in the Up direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
private func openUpAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
var base: UIView?
for var i: Int = 1, l: Int = v.count; i < l; ++i {
if nil == base {
base = v[0]
}
let view: UIView = v[i]
view.hidden = false
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 1
view.frame.origin.y = base!.frame.origin.y - CGFloat(i) * self.itemViewSize.height - CGFloat(i) * self.spacing
animations?(view)
}, completion: { [unowned self] _ in
completion?(view)
self.enable(view)
})
}
opened = true
}
}
/**
Close the Menu component with animation options in the Up direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func closeUpAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
for var i: Int = 1, l: Int = v.count; i < l; ++i {
let view: UIView = v[i]
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 0
view.frame.origin.y = self.origin.y
animations?(view)
}, completion: { [unowned self] _ in
view.hidden = true
completion?(view)
self.enable(view)
})
}
opened = false
}
}
/**
Open the Menu component with animation options in the Down direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
private func openDownAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
var base: UIView?
for var i: Int = 1, l: Int = v.count; i < l; ++i {
if nil == base {
base = v[0]
}
let view: UIView = v[i]
view.hidden = false
let h: CGFloat = nil == baseViewSize ? itemViewSize.height : baseViewSize!.height
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 1
view.frame.origin.y = base!.frame.origin.y + h + CGFloat(i - 1) * self.itemViewSize.height + CGFloat(i) * self.spacing
animations?(view)
}, completion: { [unowned self] _ in
completion?(view)
self.enable(view)
})
}
opened = true
}
}
/**
Close the Menu component with animation options in the Down direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func closeDownAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
for var i: Int = 1, l: Int = v.count; i < l; ++i {
let view: UIView = v[i]
let h: CGFloat = nil == baseViewSize ? itemViewSize.height : baseViewSize!.height
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 0
view.frame.origin.y = self.origin.y + h
animations?(view)
}, completion: { [unowned self] _ in
view.hidden = true
completion?(view)
self.enable(view)
})
}
opened = false
}
}
/**
Open the Menu component with animation options in the Left direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
private func openLeftAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
var base: UIView?
for var i: Int = 1, l: Int = v.count; i < l; ++i {
if nil == base {
base = v[0]
}
let view: UIView = v[i]
view.hidden = false
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 1
view.frame.origin.x = base!.frame.origin.x - CGFloat(i) * self.itemViewSize.width - CGFloat(i) * self.spacing
animations?(view)
}, completion: { [unowned self] _ in
completion?(view)
self.enable(view)
})
}
opened = true
}
}
/**
Close the Menu component with animation options in the Left direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func closeLeftAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
for var i: Int = 1, l: Int = v.count; i < l; ++i {
let view: UIView = v[i]
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 0
view.frame.origin.x = self.origin.x
animations?(view)
}, completion: { [unowned self] _ in
view.hidden = true
completion?(view)
self.enable(view)
})
}
opened = false
}
}
/**
Open the Menu component with animation options in the Right direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
private func openRightAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
var base: UIView?
for var i: Int = 1, l: Int = v.count; i < l; ++i {
if nil == base {
base = v[0]
}
let view: UIView = v[i]
view.hidden = false
let h: CGFloat = nil == baseViewSize ? itemViewSize.height : baseViewSize!.height
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 1
view.frame.origin.x = base!.frame.origin.x + h + CGFloat(i - 1) * self.itemViewSize.width + CGFloat(i) * self.spacing
animations?(view)
}, completion: { [unowned self] _ in
completion?(view)
self.enable(view)
})
}
opened = true
}
}
/**
Close the Menu component with animation options in the Right direction.
- Parameter duration: The time for each view's animation.
- Parameter delay: A delay time for each view's animation.
- Parameter usingSpringWithDamping: A damping ratio for the animation.
- Parameter initialSpringVelocity: The initial velocity for the animation.
- Parameter options: Options to pass to the animation.
- Parameter animations: An animation block to execute on each view's animation.
- Parameter completion: A completion block to execute on each view's animation.
*/
public func closeRightAnimation(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions, animations: ((UIView) -> Void)?, completion: ((UIView) -> Void)?) {
if let v: Array<UIView> = views {
for var i: Int = 1, l: Int = v.count; i < l; ++i {
let view: UIView = v[i]
let w: CGFloat = nil == baseViewSize ? itemViewSize.width : baseViewSize!.width
UIView.animateWithDuration(Double(i) * duration,
delay: delay,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
options: options,
animations: { [unowned self] in
view.alpha = 0
view.frame.origin.x = self.origin.x + w
animations?(view)
}, completion: { [unowned self] _ in
view.hidden = true
completion?(view)
self.enable(view)
})
}
opened = false
}
}
/// Layout the views.
private func layoutButtons() {
if let v: Array<UIView> = views {
let size: CGSize = nil == baseViewSize ? itemViewSize : baseViewSize!
for var i: Int = 0, l: Int = v.count; i < l; ++i {
let view: UIView = v[i]
if 0 == i {
view.frame.size = size
view.frame.origin = origin
view.layer.zPosition = 10000
} else {
view.alpha = 0
view.hidden = true
view.frame.size = itemViewSize
view.frame.origin.x = origin.x + (size.width - itemViewSize.width) / 2
view.frame.origin.y = origin.y + (size.height - itemViewSize.height) / 2
view.layer.zPosition = CGFloat(10000 - v.count - i)
}
}
}
}
/// Disable the Menu if views exist.
private func disable() {
if let v: Array<UIView> = views {
if 0 < v.count {
enabled = false
}
}
}
/**
Enable the Menu if the last view is equal to the passed in view.
- Parameter view: UIView that is passed in to compare.
*/
private func enable(view: UIView) {
if let v: Array<UIView> = views {
if view == v.last {
enabled = true
}
}
}
} | 2fb94fa6a4c55a2bc1ebb1f7dda193ae | 39.729339 | 280 | 0.714742 | false | false | false | false |
billdonner/sheetcheats9 | refs/heads/master | sc9/EditTilesViewController.swift | apache-2.0 | 1 | //
// EditTilesViewController.swift
//
// Created by william donner on 9/29/15.
import UIKit
class TileSequeArgs {
var name:String = "",key:String = "",bpm:String = "",
textColor:UIColor = Colors.tileTextColor(),
backColor:UIColor = Colors.tileColor()
}
final class EditingTileCell: UICollectionViewCell {
@IBOutlet var alphabetLabel: UILabel!
func configureCellFromTile(_ t:Tyle) {
let name = t.tyleTitle
self.backgroundColor = t.tyleBackColor
self.alphabetLabel.text = name
self.alphabetLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyleHeadline)
self.alphabetLabel.textColor = Corpus.findFast(name) ? t.tyleTextColor : Colors.gray
}
}
final class EditTilesViewController: UICollectionViewController , ModelData {
let formatter = DateFormatter() // create just once
func refresh() { // DOES NOT SAVE DATAMODEL
self.collectionView?.backgroundColor = Colors.mainColor()
self.view.backgroundColor = Colors.mainColor()
self.collectionView?.reloadData()
}
var addSectionBBI: UIBarButtonItem!
@IBAction func editSections() {
self.presentSectionEditor(self)
}
// total surrender to storyboards, everything is done thru performSegue and unwindtoVC
@IBAction func unwindToEditTilesViewController(_ segue: UIStoryboardSegue) {
// print("Unwound to EditTilesViewController")
}
@IBAction func finallyDone(_ sender: AnyObject) {
// self.removeLastSpecialElements() // clean this up on way out
self.unwindToSurface (self)
}
var currentTileIdx:IndexPath?
var observer1 : NSObjectProtocol? // emsure ots retained
deinit{
NotificationCenter.default.removeObserver(observer1!)
self.cleanupFontSizeAware(self)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .lightContent
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// self.navigationItem.leftBarButtonItem?.enabled =
if self.sectCount() == 0 {
formatter.dateStyle = .short
formatter.timeStyle = .medium
let sectitle = "autogenerated " + formatter.string(from: Date())
let ip = IndexPath(row:0, section:0)
self.makeHeaderAt(ip , labelled: sectitle)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = Colors.mainColor()
self.view.backgroundColor = Colors.mainColor()
self.setupFontSizeAware(self)
observer1 = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: kSurfaceUpdatedSignal), object: nil, queue: OperationQueue.main) { _ in
print ("Surface was updated, edittilesviewController reacting....")
self.refresh()
}
}
}
// MARK: - UICollectionViewDelegate
// these would be delegates but that is already done because using UICollectionViewController
extension EditTilesViewController {
//: UICollectionViewDelegate{
override func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let tyle = self.tileData(indexPath)
// prepare for seque here
let tsarg = TileSequeArgs()
// set all necessary fields
tsarg.name = tyle.tyleTitle
tsarg.key = tyle.tyleKey
tsarg.bpm = tyle.tyleBpm
tsarg.textColor = tyle.tyleTextColor
tsarg.backColor = tyle.tyleBackColor
self.storeIndexArgForSeque(indexPath)
self.storeTileArgForSeque(tsarg)
self.presentEditTile(self)
}
}
// MARK: - UICollectionViewDataSource
extension EditTilesViewController {
//: UICollectionViewDataSource {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.tileSectionCount()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.tileCountInSection(section)
}
override func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
//1
switch kind {
//2
case UICollectionElementKindSectionHeader:
//3
let headerView =
collectionView.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: "sectionheaderid",
for: indexPath)
as! TilesSectionHeaderView
headerView.headerLabel.text = self.sectHeader((indexPath as NSIndexPath).section)[SectionProperties.NameKey]
headerView.headerLabel.textColor = Colors.headerTextColor()
headerView.headerLabel.backgroundColor = Colors.headerColor()
headerView.headerLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyleHeadline)
headerView.tag = (indexPath as NSIndexPath).section
// add a tap gesture recognizer
let tgr = UITapGestureRecognizer(target: self,action:#selector(EditTilesViewController.headerTapped(_:)))
headerView.addGestureRecognizer(tgr)
return headerView
default:
//4
fatalError( "Unexpected element kind")
}
}
func headerTapped(_ tgr:UITapGestureRecognizer) {
let v = tgr.view
if v != nil {
let sec = v!.tag // numeric section number
let max = tileCountInSection(sec)
let indexPath = IndexPath(item:max,section:sec)
//Create the AlertController
let actionSheetController: UIAlertController = UIAlertController(title: "Actions For This Section \(sec) ?", message: "Can not be undone", preferredStyle: .actionSheet )
//
// //Create and add the Cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
// Just dismiss the action sheet
}
actionSheetController.addAction(cancelAction)
//Create and add first option action
actionSheetController.addAction(UIAlertAction(title: "New Tile", style: .default ) { action -> Void in
let _ = self.makeTileAt(indexPath,labelled:"\(sec) - \(max)")
self.refresh()
Globals.saveDataModel()
// self.unwindToMainMenu(self)
})
//Create and add first option action
actionSheetController.addAction(UIAlertAction(title: "Rename This Section", style: .default ) { action -> Void in
self.storeIntArgForSeque(sec)
self.presentSectionRenamor(self)
// self.unwindToMainMenu(self)
})
// We need to provide a popover sourceView when using it on iPad
actionSheetController.popoverPresentationController?.sourceView = tgr.view! as UIView
// Present the AlertController
self.present(actionSheetController, animated: true, completion: nil)
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 3
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EditingTileCellID", for: indexPath) as! EditingTileCell
// Configure the cell
cell.configureCellFromTile(self.tileData(indexPath))
return cell
}
override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath) {
//if sourceIndexPath.section != destinationIndexPath.section {
mswap2(sourceIndexPath, destinationIndexPath)
// }
// else {
// mswap(sourceIndexPath, destinationIndexPath)
// }
}
}
extension EditTilesViewController:SegueHelpers {
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
self.prepForSegue(segue , sender: sender)
if let uiv = segue.destinationViewController as? ThemePickerViewController {
uiv.modalPresentationStyle = .fullScreen
uiv.delegate = self
}
if let uiv = segue.destinationViewController as? SectionRenamorViewController {
uiv.modalPresentationStyle = .fullScreen
uiv.sectionNum = self.fetchIntArgForSegue()
}
if let uiv = segue.destinationViewController as? SectionsEditorViewController {
uiv.modalPresentationStyle = .fullScreen
uiv.delegate = self
}
if let uiv = segue.destinationViewController as?
TilePropertiesEditorViewController {
// record which cell we are sequeing away from even if we never tell the editor
self.currentTileIdx = self.fetchIndexArgForSegue()
uiv.modalPresentationStyle = .fullScreen
uiv.tileIncoming = self.fetchTileArgForSegue()
uiv.tileIdx = self.currentTileIdx
uiv.delegate = self
}
}
}
extension EditTilesViewController: FontSizeAware {
func refreshFontSizeAware(_ vc: TilesViewController) {
vc.collectionView?.reloadData()
}
}
extension EditTilesViewController:ThemePickerDelegate {
func themePickerReturningResults(_ data:NSArray) {
print ("In edittiles theme returned \(data)")
}
}
extension EditTilesViewController: ShowContentDelegate {
func userDidDismiss() {
print("user dismissed Content View Controller")
}
}
// only the editing version of this controller gets these extra elegates
extension EditTilesViewController:TilePropertiesEditorDelegate {
func deleteThisTile() {
if self.currentTileIdx != nil {
self.tileRemove(self.currentTileIdx!)
Globals.saveDataModel()
refresh()
}
}
func tileDidUpdate(name:String,key:String,bpm:String,textColor:UIColor, backColor:UIColor){
if self.currentTileIdx != nil {
let tyle = elementFor(self.currentTileIdx!)
tyle.tyleTitle = name
tyle.tyleBpm = bpm
tyle.tyleKey = key
tyle.tyleTextColor = textColor
tyle.tyleBackColor = backColor
setElementFor(self.currentTileIdx!, el: tyle)
if let cell = self.collectionView?.cellForItem(at: self.currentTileIdx!) as? EditingTileCell {
//
// print ("updating tile at \(self.currentTileIdx!) ")
//
// cell.alphabetLabel.text = name
// cell.alphabetLabel.backgroundColor = backColor
// cell.alphabetLabel.textColor = textColor
cell.configureCellFromTile(tyle)
}
Globals.saveDataModel()
refresh()
}
}
}
extension EditTilesViewController: SectionsEditorDelegate {
func makeNewSection(_ i:Int) {
formatter.dateStyle = .short
formatter.timeStyle = .medium
let sectitle = formatter.string(from: Date())
let ip = IndexPath(row:i, section:0)
self.makeHeaderAt(ip , labelled: sectitle)
Globals.saveDataModel()
refresh()
}
func deleteSection(_ i: Int) { // removes whole section without a trace
self.deleteSect(i)
Globals.saveDataModel()
refresh()
}
func moveSections(_ from:Int,to:Int) {
self.moveSects(from, to)
Globals.saveDataModel()
refresh()
}
}
/// all the IB things need to be above here in the final classes
| f2b11c4f306f62582d503a5e1d82f7ae | 36.201201 | 181 | 0.627704 | false | false | false | false |
Shivol/Swift-CS333 | refs/heads/master | assignments/task5/schedule/schedule/MasterViewController+DataLoaderDelegate.swift | mit | 2 | //
// MasterViewController+DataLoaderDelegate.swift
// schedule
//
// Created by Илья Лошкарёв on 30.03.17.
// Copyright © 2017 mmcs. All rights reserved.
//
import UIKit
extension MasterViewController: DataLoaderDelegate {
func dataLoader(_ dataLoader: DataLoader, didFinishLoadingWith data: Any?) {
switch dataLoader {
case is TimetableDataLoader:
guard let loadedTimetable = data as? Timetable else {
fatalError("unexpected data")
}
self.timetable = loadedTimetable
if self.currentWeek != nil {
self.timetable!.currentWeek = self.currentWeek!
}
if let activity = tableView.backgroundView as? UIActivityIndicatorView {
activity.removeFromSuperview()
activity.stopAnimating()
}
tableView.reloadData()
case is WeekDataLoader:
guard let loadedWeek = data as? AlternatingWeek else {
fatalError("unexpected data")
}
self.currentWeek = loadedWeek
if self.timetable != nil{
self.timetable!.currentWeek = loadedWeek
tableView.reloadData()
}
default:
fatalError("unexpected loader")
}
}
func dataLoader(_ dataLoader: DataLoader, didFinishLoadingWith error: NSError) {
let alert = UIAlertController(title: "Error", message: error.description, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true)
}
}
| bf31639e1c97950de54a8ad69d122494 | 31.226415 | 105 | 0.581967 | false | false | false | false |
limaoxuan/MXAlertView | refs/heads/master | MXAlertView/MXAlertView/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// MXAlertView
//
// Created by 李茂轩 on 15/2/6.
// Copyright (c) 2015年 lee. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var button : UIButton?
var mxAlertView : MXAlertView?
func initSubViews(){
mxAlertView = MXAlertView()
self.view.addSubview(mxAlertView!)
button = UIButton()
button?.setTitle("show/hidden", forState: UIControlState.Normal)
button?.backgroundColor = UIColor.blackColor()
button?.setTranslatesAutoresizingMaskIntoConstraints(false)
button?.addTarget(self, action: Selector("clickButton:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button!)
let viewDic = (["button":button!]) as NSDictionary
let locationH = "H:[button]"
let locationY = "V:|-50-[button(30)]"
setConstraintsWithStringHandVWithCurrentView(locationH, locationY, self.view, viewDic)
setLocationAccrodingWithSuperViewAndCurrentViewSetLayoutAttributeCenterX(self.view, button!, 200)
let s = Selector("clickButton:")
}
@objc func clickButton(obj:AnyObject!){
if mxAlertView?.isOpen == false {
mxAlertView?.showAlertAnimation()
}else if mxAlertView?.isOpen == true {
mxAlertView?.hiddenAlertAnimation()
}
}
override func viewDidLoad() {
super.viewDidLoad()
initSubViews()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 1e8b471596a400afdd7693c51449be55 | 20.222222 | 114 | 0.590052 | false | false | false | false |
knutigro/AppReviews | refs/heads/develop | AppReviews/StatusMenuController.swift | gpl-3.0 | 1 | //
// StatusMenu.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-04-16.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
import AppKit
class StatusMenuController: NSObject {
var statusItem: NSStatusItem!
var applications = [Application]()
var newReviews = [Int]()
var applicationArrayController: ApplicationArrayController!
private var kvoContext = 0
// MARK: - Init & teardown
deinit {
removeObserver(self, forKeyPath: "applications", context: &kvoContext)
}
override init() {
super.init()
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) // NSVariableStatusItemLength
statusItem.image = NSImage(named: "stausBarIcon")
statusItem.alternateImage = NSImage(named: "stausBarIcon")
statusItem.highlightMode = true
applicationArrayController = ApplicationArrayController(content: nil)
applicationArrayController.managedObjectContext = ReviewManager.managedObjectContext()
applicationArrayController.entityName = kEntityNameApplication
do {
try applicationArrayController.fetchWithRequest(nil, merge: true)
} catch let error as NSError {
print(error)
}
bind("applications", toObject: applicationArrayController, withKeyPath: "arrangedObjects", options: nil)
addObserver(self, forKeyPath: "applications", options: .New, context: &kvoContext)
_ = NSNotificationCenter.defaultCenter().addObserverForName(kDidUpdateApplicationNotification, object: nil, queue: nil) { notification in
}
_ = NSNotificationCenter.defaultCenter().addObserverForName(kDidUpdateApplicationSettingsNotification, object: nil, queue: nil) { [weak self] notification in
self?.updateMenu()
}
updateMenu()
}
// MARK: - Handling menu items
func updateMenu() {
let menu = NSMenu()
var newReviews = false
var idx = 1
for application in applications {
// application.addObserver(self, forKeyPath: "settings.newReviews", options: .New, context: &kvoContext)
var title = application.trackName
if application.settings.newReviews.integerValue > 0 {
newReviews = true
title = title + " (" + String(application.settings.newReviews.integerValue) + ")"
}
let shortKey = idx < 10 ? String(idx) : ""
let menuItem = NSMenuItem(title: title, action: Selector("openReviewsForApp:"), keyEquivalent: shortKey)
menuItem.representedObject = application
menuItem.target = self
menu.addItem(menuItem)
idx++
}
if (applications.count > 0) {
menu.addItem(NSMenuItem.separatorItem())
}
let menuItemApplications = NSMenuItem(title: NSLocalizedString("Add / Remove Applications", comment: "statusbar.menu.applications"), action: Selector("openApplications:"), keyEquivalent: "a")
let menuItemAbout = NSMenuItem(title: NSLocalizedString("About Appstore Reviews", comment: "statusbar.menu.about"), action: Selector("openAbout:"), keyEquivalent: "")
let menuItemProvidFeedback = NSMenuItem(title: NSLocalizedString("Provide Feedback...", comment: "statusbar.menu.feedback"), action: Selector("openFeedback:"), keyEquivalent: "")
let menuItemQuit = NSMenuItem(title: NSLocalizedString("Quit", comment: "statusbar.menu.quit"), action: Selector("quit:"), keyEquivalent: "q")
let menuItemLaunchAtStartup = NSMenuItem(title: NSLocalizedString("Launch at startup", comment: "statusbar.menu.startup"), action: Selector("launchAtStartUpToggle:"), keyEquivalent: "")
menuItemLaunchAtStartup.state = NSApplication.shouldLaunchAtStartup() ? NSOnState : NSOffState
menuItemApplications.target = self
menuItemAbout.target = self
menuItemQuit.target = self
menuItemProvidFeedback.target = self
menuItemLaunchAtStartup.target = self
menu.addItem(menuItemApplications)
menu.addItem(NSMenuItem.separatorItem())
menu.addItem(menuItemLaunchAtStartup)
menu.addItem(menuItemProvidFeedback)
menu.addItem(NSMenuItem.separatorItem())
menu.addItem(menuItemAbout)
menu.addItem(menuItemQuit)
statusItem.menu = menu;
if newReviews {
statusItem.image = NSImage(named: "stausBarIconHappy")
statusItem.alternateImage = NSImage(named: "stausBarIconHappy")
} else {
statusItem.image = NSImage(named: "stausBarIcon")
statusItem.alternateImage = NSImage(named: "stausBarIcon")
}
}
}
// MARK: - Actions
extension StatusMenuController {
func openReviewsForApp(sender: AnyObject?) {
if let menuItem = sender as? NSMenuItem {
if let application = menuItem.representedObject as? Application {
ReviewWindowController.show(application.objectID)
}
}
}
func openAbout(sender: AnyObject?) {
let appdelegate = NSApplication.sharedApplication().delegate as! AppDelegate
let windowController = appdelegate.aboutWindowController
windowController.showWindow(self)
NSApp.activateIgnoringOtherApps(true)
}
func openApplications(sender: AnyObject?) {
let appdelegate = NSApplication.sharedApplication().delegate as! AppDelegate
let windowController = appdelegate.applicationWindowController
windowController.showWindow(self)
NSApp.activateIgnoringOtherApps(true)
}
func openFeedback(sender: AnyObject?) {
NSWorkspace.sharedWorkspace().openURL(NSURL(string: "http://knutigro.github.io/apps/app-reviews/#Feedback")!)
}
func launchAtStartUpToggle(sender : AnyObject?) {
if let menu = sender as? NSMenuItem {
NSApplication.toggleShouldLaunchAtStartup()
menu.state = NSApplication.shouldLaunchAtStartup() ? NSOnState : NSOffState
}
}
func quit(sender: AnyObject?) {
NSApplication.sharedApplication().terminate(sender)
}
}
// MARK: - KVO
extension StatusMenuController {
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &kvoContext {
// print("observeValueForKeyPath: " + keyPath + "change: \(change)" )
// updateMenu()
}
else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
} | 34e3d55c48c441e3a798a86c91dc343a | 37.644068 | 199 | 0.655359 | false | false | false | false |
imzyf/99-projects-of-swift | refs/heads/master | 031-stopwatch/031-stopwatch/ViewController.swift | mit | 1 | //
// ViewController.swift
// 031-stopwatch
//
// Created by moma on 2018/3/28.
// Copyright © 2018年 yifans. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - UI components
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var lapTimerLabel: UILabel!
@IBOutlet weak var playPauseButton: UIButton!
@IBOutlet weak var lapRestButton: UIButton!
@IBOutlet weak var lapsTableView: UITableView!
// MARK: - Variables
fileprivate let mainStopwatch: Stopwatch = Stopwatch()
fileprivate let lapStopwatch: Stopwatch = Stopwatch()
fileprivate var isPlay: Bool = false
fileprivate var laps: [String] = []
let stepTimeInterval: CGFloat = 0.035
override func viewDidLoad() {
super.viewDidLoad()
// 闭包设置 button 样式
let initCircleButton: (UIButton) -> Void = { button in
button.layer.cornerRadius = 0.5 * button.bounds.size.width
}
initCircleButton(playPauseButton)
initCircleButton(lapRestButton)
playPauseButton.setTitle("Stop", for: .selected)
lapRestButton.isEnabled = false
}
@IBAction func playPauseTimer(_ sender: UIButton) {
if sender.isSelected {
// stop
mainStopwatch.timer.invalidate()
} else {
// start
lapRestButton.isEnabled = true
mainStopwatch.timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(self.stepTimeInterval), repeats: true) { (time) in
self.updateTimer(self.mainStopwatch, label: self.timerLabel)
}
sender.isSelected = !sender.isSelected
//
// Timer.scheduledTimer(timeInterval: 0.035, target: self, selector: Selector.updateMainTimer, userInfo: nil, repeats: true)
//
}
}
func updateTimer(_ stopwatch: Stopwatch, label: UILabel) {
stopwatch.counter = stopwatch.counter + stepTimeInterval
let minutes = Int(stopwatch.counter / 60)
let minuteText = minutes < 10 ? "0\(minutes)" : "\(minutes)"
let seconds = stopwatch.counter.truncatingRemainder(dividingBy: 60)
let secondeText = seconds < 10 ? String(format: "0%.2f", seconds) : String(format: "%.2f", seconds)
label.text = minuteText + ":" + secondeText
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return laps.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath)
// if let labelNum = cell.viewWithTag(11) as? UILabel {
// labelNum.text = "Lap \(laps.count - (indexPath as NSIndexPath).row)"
// }
// if let labelTimer = cell.viewWithTag(12) as? UILabel {
// labelTimer.text = laps[laps.count - (indexPath as NSIndexPath).row - 1]
// }
return cell
}
}
| 1f8d61e743aa10ccbc28af6ffd66015b | 31.69 | 139 | 0.609055 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | refs/heads/master | Source/DiscussionTestsDataFactory.swift | apache-2.0 | 5 | //
// DiscussionTestsDataFactory.swift
// edX
//
// Created by Saeed Bashir on 2/25/16.
// Copyright © 2016 edX. All rights reserved.
//
@testable import edX
import UIKit
import XCTest
class DiscussionTestsDataFactory: NSObject {
static let thread = DiscussionThread(
threadID: "123",
type: .Discussion,
courseId: "some-course",
topicId: "abc",
groupId: nil,
groupName: nil,
title: "Some Post",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: "Staff",
commentCount: 0,
commentListUrl: nil,
hasEndorsed: false,
pinned: false,
closed: false,
following: false,
flagged: false,
abuseFlagged: false,
voted: true,
voteCount: 4,
createdAt: NSDate.stableTestDate(),
updatedAt: NSDate.stableTestDate(),
editableFields: nil,
read: true,
unreadCommentCount: 0,
responseCount: 0,
hasProfileImage: false,
imageURL: nil)
static let unreadThread = DiscussionThread(
threadID: "123",
type: .Discussion,
courseId: "some-course",
topicId: "abc",
groupId: nil,
groupName: nil,
title: "Test Post",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: "Test User",
commentCount: 5,
commentListUrl: nil,
hasEndorsed: true,
pinned: true,
closed: false,
following: true,
flagged: false,
abuseFlagged: false,
voted: true,
voteCount: 4,
createdAt: NSDate.stableTestDate(),
updatedAt: NSDate.stableTestDate(),
editableFields: nil,
read: false,
unreadCommentCount: 4,
responseCount: 0,
hasProfileImage: false,
imageURL: nil)
static let unendorsedComment = DiscussionComment(
commentID: "123",
parentID: "123",
threadID: "345",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: nil,
voted: true,
voteCount: 10,
createdAt: NSDate.stableTestDate(),
updatedAt: nil,
endorsed: false,
endorsedBy: nil,
endorsedByLabel: nil,
endorsedAt: nil,
flagged: false,
abuseFlagged: false,
editableFields: nil,
childCount: 0,
hasProfileImage: false,
imageURL: nil)
static let unendorsedComment1 = DiscussionComment(
commentID: "124",
parentID: "124",
threadID: "345",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: nil,
voted: true,
voteCount: 10,
createdAt: NSDate.stableTestDate(),
updatedAt: nil,
endorsed: false,
endorsedBy: nil,
endorsedByLabel: nil,
endorsedAt: nil,
flagged: false,
abuseFlagged: false,
editableFields: nil,
childCount: 5,
hasProfileImage: false,
imageURL: nil)
static let endorsedComment = DiscussionComment(
commentID: "125",
parentID: "125",
threadID: "345",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: nil,
voted: false,
voteCount: 10,
createdAt: NSDate.stableTestDate(),
updatedAt: nil,
endorsed: true,
endorsedBy: "Test Person 2",
endorsedByLabel: nil,
endorsedAt: NSDate.stableTestDate(),
flagged: false,
abuseFlagged: false,
editableFields: nil,
childCount: 0,
hasProfileImage: false,
imageURL: nil)
static let endorsedComment1 = DiscussionComment(
commentID: "126",
parentID: nil,
threadID: "345",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: nil,
voted: true,
voteCount: 10,
createdAt: NSDate.stableTestDate(),
updatedAt: nil,
endorsed: false,
endorsedBy: nil,
endorsedByLabel: "Test Person 2",
endorsedAt: NSDate.stableTestDate(),
flagged: false,
abuseFlagged: false,
editableFields: nil,
childCount: 2,
hasProfileImage: false,
imageURL: nil)
static func unendorsedResponses()-> [DiscussionComment] {
return [unendorsedComment, unendorsedComment1]
}
static func endorsedResponses() -> [DiscussionComment] {
return [endorsedComment, endorsedComment1]
}
}
| 51269a3c28693d544bdb15b065b08857 | 29.017045 | 97 | 0.572781 | false | true | false | false |
kevintulod/CascadeKit-iOS | refs/heads/master | CascadeKit/CascadeKit/Cascade Controller/CascadeDividerView.swift | mit | 1 | //
// CascadeDividerView.swift
// CascadeKit
//
// Created by Kevin Tulod on 1/7/17.
// Copyright © 2017 Kevin Tulod. All rights reserved.
//
import UIKit
protocol CascadeDividerDelegate {
func divider(_ divider: CascadeDividerView, shouldTranslateToCenter center: CGPoint) -> Bool
func divider(_ divider: CascadeDividerView, didTranslateToCenter center: CGPoint)
}
/// Defines the behavior of the center divider between the master/detail views
class CascadeDividerView: UIView {
/// Sets the margin on either side of the divider that responds to touch
static let touchMargin = -CGFloat(10)
internal var lastCenter = CGPoint(x: 0, y: 0)
internal var delegate: CascadeDividerDelegate?
/// Overrides the point(inside:) function to allow the divider to respond to touches within `touchMargin` pixels on either side
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return bounds.insetBy(dx: CascadeDividerView.touchMargin, dy: 0).contains(point)
}
override func awakeFromNib() {
super.awakeFromNib()
lastCenter = center
setupPanGestures()
backgroundColor = .lightGray
}
/// Sets up the gesture recognizer for dragging
internal func setupPanGestures() {
let pan = UIPanGestureRecognizer(target: self, action: #selector(CascadeDividerView.detectPan(recognizer:)))
addGestureRecognizer(pan)
}
/// Responder for the UIPanGestureRecognizer that controls the dragging behavior of the divider
internal func detectPan(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .changed:
// Translate the center only by x
let translation = recognizer.translation(in: superview)
let newCenter = CGPoint(x: lastCenter.x + translation.x, y: lastCenter.y)
if let delegate = delegate, delegate.divider(self, shouldTranslateToCenter: newCenter) {
center = newCenter
delegate.divider(self, didTranslateToCenter: center)
}
case .ended:
lastCenter = center
default:
break
}
}
}
| 7b11816d5ad648d762dbf7536963735c | 32.188406 | 131 | 0.650655 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.