repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mspvirajpatel/SwiftyBase
|
SwiftyBase/Classes/Controller/SideMenu/SideMenuManager.swift
|
1
|
18213
|
//
// SideMenuManager.swift
// Pods
//
// Created by MacMini-2 on 30/08/17.
//
//
/* Example usage:
// Define the menus
SideMenuManager.menuLeftNavigationController = storyboard!.instantiateViewController(withIdentifier: "LeftMenuNavigationController") as? UISideMenuNavigationController
SideMenuManager.menuRightNavigationController = storyboard!.instantiateViewController(withIdentifier: "RightMenuNavigationController") as? UISideMenuNavigationController
// Enable gestures. The left and/or right menus must be set up above for these to work.
// Note that these continue to work on the Navigation Controller independent of the View Controller it displays!
SideMenuManager.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar)
SideMenuManager.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view)
*/
open class SideMenuManager: NSObject {
@objc public enum MenuPushStyle: Int {
case defaultBehavior,
popWhenPossible,
replace,
preserve,
preserveAndHideBackButton,
subMenu
}
@objc public enum MenuPresentMode: Int {
case menuSlideIn,
viewSlideOut,
viewSlideInOut,
menuDissolveIn
}
// Bounds which has been allocated for the app on the whole device screen
internal static var appScreenRect: CGRect {
let appWindowRect = UIApplication.shared.keyWindow?.bounds ?? UIWindow().bounds
return appWindowRect
}
/**
The push style of the menu.
There are six modes in MenuPushStyle:
- defaultBehavior: The view controller is pushed onto the stack.
- popWhenPossible: If a view controller already in the stack is of the same class as the pushed view controller, the stack is instead popped back to the existing view controller. This behavior can help users from getting lost in a deep navigation stack.
- preserve: If a view controller already in the stack is of the same class as the pushed view controller, the existing view controller is pushed to the end of the stack. This behavior is similar to a UITabBarController.
- preserveAndHideBackButton: Same as .preserve and back buttons are automatically hidden.
- replace: Any existing view controllers are released from the stack and replaced with the pushed view controller. Back buttons are automatically hidden. This behavior is ideal if view controllers require a lot of memory or their state doesn't need to be preserved..
- subMenu: Unlike all other behaviors that push using the menu's presentingViewController, this behavior pushes view controllers within the menu. Use this behavior if you want to display a sub menu.
*/
public static var menuPushStyle: MenuPushStyle = .defaultBehavior
/**
The presentation mode of the menu.
There are four modes in MenuPresentMode:
- menuSlideIn: Menu slides in over of the existing view.
- viewSlideOut: The existing view slides out to reveal the menu.
- viewSlideInOut: The existing view slides out while the menu slides in.
- menuDissolveIn: The menu dissolves in over the existing view controller.
*/
public static var menuPresentMode: MenuPresentMode = .viewSlideOut
/// Prevents the same view controller (or a view controller of the same class) from being pushed more than once. Defaults to true.
public static var menuAllowPushOfSameClassTwice = true
/// Width of the menu when presented on screen, showing the existing view controller in the remaining space. Default is 75% of the screen width.
public static var menuWidth: CGFloat = max(round(min((appScreenRect.width), (appScreenRect.height)) * 0.75), 240)
/// Duration of the animation when the menu is presented without gestures. Default is 0.35 seconds.
public static var menuAnimationPresentDuration: Double = 0.35
/// Duration of the animation when the menu is dismissed without gestures. Default is 0.35 seconds.
public static var menuAnimationDismissDuration: Double = 0.35
/// Duration of the remaining animation when the menu is partially dismissed with gestures. Default is 0.2 seconds.
public static var menuAnimationCompleteGestureDuration: Double = 0.20
/// Amount to fade the existing view controller when the menu is presented. Default is 0 for no fade. Set to 1 to fade completely.
public static var menuAnimationFadeStrength: CGFloat = 0
/// The amount to scale the existing view controller or the menu view controller depending on the `menuPresentMode`. Default is 1 for no scaling. Less than 1 will shrink, greater than 1 will grow.
public static var menuAnimationTransformScaleFactor: CGFloat = 1
/// The background color behind menu animations. Depending on the animation settings this may not be visible. If `menuFadeStatusBar` is true, this color is used to fade it. Default is black.
public static var menuAnimationBackgroundColor: UIColor?
/// The shadow opacity around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is 0.5 for 50% opacity.
public static var menuShadowOpacity: Float = 0.5
/// The shadow color around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is black.
public static var menuShadowColor = UIColor.black
/// The radius of the shadow around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is 5.
public static var menuShadowRadius: CGFloat = 5
/// Enable or disable interaction with the presenting view controller while the menu is displayed. Enabling may make it difficult to dismiss the menu or cause exceptions if the user tries to present and already presented menu. Default is false.
public static var menuPresentingViewControllerUserInteractionEnabled: Bool = false
/// The strength of the parallax effect on the existing view controller. Does not apply to `menuPresentMode` when set to `ViewSlideOut`. Default is 0.
public static var menuParallaxStrength: Int = 0
/// Draws the `menuAnimationBackgroundColor` behind the status bar. Default is true.
public static var menuFadeStatusBar = true
/// The animation options when a menu is displayed. Ignored when displayed with a gesture.
public static var menuAnimationOptions: UIView.AnimationOptions = .curveEaseInOut
/// The animation spring damping when a menu is displayed. Ignored when displayed with a gesture.
public static var menuAnimationUsingSpringWithDamping: CGFloat = 1
/// The animation initial spring velocity when a menu is displayed. Ignored when displayed with a gesture.
public static var menuAnimationInitialSpringVelocity: CGFloat = 1
/// -Warning: Deprecated. Use `menuPushStyle = .subMenu` instead.
@available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .subMenu` instead.")
public static var menuAllowSubmenus: Bool {
get {
return menuPushStyle == .subMenu
}
set {
if newValue {
menuPushStyle = .subMenu
}
}
}
/// -Warning: Deprecated. Use `menuPushStyle = .popWhenPossible` instead.
@available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .popWhenPossible` instead.")
public static var menuAllowPopIfPossible: Bool {
get {
return menuPushStyle == .popWhenPossible
}
set {
if newValue {
menuPushStyle = .popWhenPossible
}
}
}
/// -Warning: Deprecated. Use `menuPushStyle = .replace` instead.
@available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .replace` instead.")
public static var menuReplaceOnPush: Bool {
get {
return menuPushStyle == .replace
}
set {
if newValue {
menuPushStyle = .replace
}
}
}
/// -Warning: Deprecated. Use `menuAnimationTransformScaleFactor` instead.
@available(*, deprecated, renamed: "menuAnimationTransformScaleFactor")
public static var menuAnimationShrinkStrength: CGFloat {
get {
return menuAnimationTransformScaleFactor
}
set {
menuAnimationTransformScaleFactor = newValue
}
}
// prevent instantiation
fileprivate override init() { }
/**
The blur effect style of the menu if the menu's root view controller is a UITableViewController or UICollectionViewController.
- Note: If you want cells in a UITableViewController menu to show vibrancy, make them a subclass of UITableViewVibrantCell.
*/
public static var menuBlurEffectStyle: UIBlurEffect.Style? {
didSet {
if oldValue != menuBlurEffectStyle {
updateMenuBlurIfNecessary()
}
}
}
/// The left menu.
public static var menuLeftNavigationController: UISideMenuNavigationController? {
willSet {
if menuLeftNavigationController?.presentingViewController == nil {
removeMenuBlurForMenu(menuLeftNavigationController)
}
}
didSet {
guard oldValue?.presentingViewController == nil else {
print("SideMenu Warning: menuLeftNavigationController cannot be modified while it's presented.")
menuLeftNavigationController = oldValue
return
}
setupNavigationController(menuLeftNavigationController, leftSide: true)
}
}
/// The right menu.
public static var menuRightNavigationController: UISideMenuNavigationController? {
willSet {
if menuRightNavigationController?.presentingViewController == nil {
removeMenuBlurForMenu(menuRightNavigationController)
}
}
didSet {
guard oldValue?.presentingViewController == nil else {
print("SideMenu Warning: menuRightNavigationController cannot be modified while it's presented.")
menuRightNavigationController = oldValue
return
}
setupNavigationController(menuRightNavigationController, leftSide: false)
}
}
/// The left menu swipe to dismiss gesture.
public static weak var menuLeftSwipeToDismissGesture: UIPanGestureRecognizer? {
didSet {
oldValue?.view?.removeGestureRecognizer(oldValue!)
setupGesture(gesture: menuLeftSwipeToDismissGesture)
}
}
/// The right menu swipe to dismiss gesture.
public static weak var menuRightSwipeToDismissGesture: UIPanGestureRecognizer? {
didSet {
oldValue?.view?.removeGestureRecognizer(oldValue!)
setupGesture(gesture: menuRightSwipeToDismissGesture)
}
}
fileprivate class func setupGesture(gesture: UIPanGestureRecognizer?) {
guard let gesture = gesture else {
return
}
gesture.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handleHideMenuPan(_:)))
}
fileprivate class func setupNavigationController(_ forMenu: UISideMenuNavigationController?, leftSide: Bool) {
guard let forMenu = forMenu else {
return
}
if menuEnableSwipeGestures {
let exitPanGesture = UIPanGestureRecognizer()
forMenu.view.addGestureRecognizer(exitPanGesture)
if leftSide {
menuLeftSwipeToDismissGesture = exitPanGesture
} else {
menuRightSwipeToDismissGesture = exitPanGesture
}
}
forMenu.transitioningDelegate = SideMenuTransition.singleton
forMenu.modalPresentationStyle = .overFullScreen
forMenu.leftSide = leftSide
updateMenuBlurIfNecessary()
}
/// Enable or disable gestures that would swipe to dismiss the menu. Default is true.
public static var menuEnableSwipeGestures: Bool = true {
didSet {
menuLeftSwipeToDismissGesture?.view?.removeGestureRecognizer(menuLeftSwipeToDismissGesture!)
menuRightSwipeToDismissGesture?.view?.removeGestureRecognizer(menuRightSwipeToDismissGesture!)
setupNavigationController(menuLeftNavigationController, leftSide: true)
setupNavigationController(menuRightNavigationController, leftSide: false)
}
}
fileprivate class func updateMenuBlurIfNecessary() {
let menuBlurBlock = { (forMenu: UISideMenuNavigationController?) in
if let forMenu = forMenu {
setupMenuBlurForMenu(forMenu)
}
}
menuBlurBlock(menuLeftNavigationController)
menuBlurBlock(menuRightNavigationController)
}
fileprivate class func setupMenuBlurForMenu(_ forMenu: UISideMenuNavigationController?) {
removeMenuBlurForMenu(forMenu)
guard let forMenu = forMenu,
let menuBlurEffectStyle = menuBlurEffectStyle,
let view = forMenu.visibleViewController?.view
, !UIAccessibility.isReduceTransparencyEnabled else {
return
}
if forMenu.originalMenuBackgroundColor == nil {
forMenu.originalMenuBackgroundColor = view.backgroundColor
}
let blurEffect = UIBlurEffect(style: menuBlurEffectStyle)
let blurView = UIVisualEffectView(effect: blurEffect)
view.backgroundColor = UIColor.clear
if let tableViewController = forMenu.visibleViewController as? UITableViewController {
tableViewController.tableView.backgroundView = blurView
tableViewController.tableView.separatorEffect = UIVibrancyEffect(blurEffect: blurEffect)
tableViewController.tableView.reloadData()
} else {
blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
blurView.frame = view.bounds
view.insertSubview(blurView, at: 0)
}
}
fileprivate class func removeMenuBlurForMenu(_ forMenu: UISideMenuNavigationController?) {
guard let forMenu = forMenu,
let originalMenuBackgroundColor = forMenu.originalMenuBackgroundColor,
let view = forMenu.visibleViewController?.view else {
return
}
view.backgroundColor = originalMenuBackgroundColor
forMenu.originalMenuBackgroundColor = nil
if let tableViewController = forMenu.visibleViewController as? UITableViewController {
tableViewController.tableView.backgroundView = nil
tableViewController.tableView.separatorEffect = nil
tableViewController.tableView.reloadData()
} else if let blurView = view.subviews[0] as? UIVisualEffectView {
blurView.removeFromSuperview()
}
}
/**
Adds screen edge gestures to a view to present a menu.
- Parameter toView: The view to add gestures to.
- Parameter forMenu: The menu (left or right) you want to add a gesture for. If unspecified, gestures will be added for both sides.
- Returns: The array of screen edge gestures added to `toView`.
*/
@discardableResult open class func menuAddScreenEdgePanGesturesToPresent(toView: UIView, forMenu: UIRectEdge? = nil) -> [UIScreenEdgePanGestureRecognizer] {
var array = [UIScreenEdgePanGestureRecognizer]()
if forMenu != .right {
let leftScreenEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer()
leftScreenEdgeGestureRecognizer.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handlePresentMenuLeftScreenEdge(_:)))
leftScreenEdgeGestureRecognizer.edges = .left
leftScreenEdgeGestureRecognizer.cancelsTouchesInView = true
toView.addGestureRecognizer(leftScreenEdgeGestureRecognizer)
array.append(leftScreenEdgeGestureRecognizer)
if SideMenuManager.menuLeftNavigationController == nil {
print("SideMenu Warning: menuAddScreenEdgePanGesturesToPresent for the left side was called before menuLeftNavigationController has been defined. The gesture will not work without a menu.")
}
}
if forMenu != .left {
let rightScreenEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer()
rightScreenEdgeGestureRecognizer.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handlePresentMenuRightScreenEdge(_:)))
rightScreenEdgeGestureRecognizer.edges = .right
rightScreenEdgeGestureRecognizer.cancelsTouchesInView = true
toView.addGestureRecognizer(rightScreenEdgeGestureRecognizer)
array.append(rightScreenEdgeGestureRecognizer)
if SideMenuManager.menuRightNavigationController == nil {
print("SideMenu Warning: menuAddScreenEdgePanGesturesToPresent for the right side was called before menuRightNavigationController has been defined. The gesture will not work without a menu.")
}
}
return array
}
/**
Adds a pan edge gesture to a view to present menus.
- Parameter toView: The view to add a pan gesture to.
- Returns: The pan gesture added to `toView`.
*/
@discardableResult open class func menuAddPanGestureToPresent(toView: UIView) -> UIPanGestureRecognizer {
let panGestureRecognizer = UIPanGestureRecognizer()
panGestureRecognizer.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handlePresentMenuPan(_:)))
toView.addGestureRecognizer(panGestureRecognizer)
if SideMenuManager.menuLeftNavigationController ?? SideMenuManager.menuRightNavigationController == nil {
print("SideMenu Warning: menuAddPanGestureToPresent called before menuLeftNavigationController or menuRightNavigationController have been defined. Gestures will not work without a menu.")
}
return panGestureRecognizer
}
}
|
mit
|
a4728f2c4ed174f30a7ff68730eafa47
| 45.820051 | 271 | 0.70241 | 5.700469 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/selluv-ios/Classes/Base/Vender/TransitionAnimation/PageTransitionAnimation.swift
|
1
|
4652
|
//
// PageTransitionAnimation.swift
// TransitionTreasury
//
// Created by DianQK on 12/30/15.
// Copyright © 2016 TransitionTreasury. All rights reserved.
//
import UIKit
//import TransitionTreasury
/// Page Motion
public class PageTransitionAnimation: NSObject, TRViewControllerAnimatedTransitioning, TransitionInteractiveable {
public var transitionStatus: TransitionStatus
public var transitionContext: UIViewControllerContextTransitioning?
public var percentTransition: UIPercentDrivenInteractiveTransition?
public var completion: (() -> Void)?
public var cancelPop: Bool = false
public var interacting: Bool = false
private var transformBackup: CATransform3D?
private var shadowOpacityBackup: Float?
private var shadowOffsetBackup: CGSize?
private var shadowRadiusBackup: CGFloat?
private var shadowPathBackup: CGPath?
private lazy var maskView: UIView = {
let maskView = UIView(frame: UIScreen.main.bounds)
maskView.backgroundColor = UIColor.black
return maskView
}()
public init(status: TransitionStatus = .push) {
transitionStatus = status
super.init()
}
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.6
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
var fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
var toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
let containView = transitionContext.containerView
var startPositionX: CGFloat = UIScreen.main.bounds.width
var endPositionX: CGFloat = 0
var startOpacity: Float = 0
var endOpacity: Float = 0.3
transformBackup = transformBackup ?? fromVC?.view.layer.transform
var transform3D: CATransform3D = CATransform3DIdentity
transform3D.m34 = -1.0/500.0
if transitionStatus == .pop {
swap(&fromVC, &toVC)
swap(&startPositionX, &endPositionX)
swap(&startOpacity, &endOpacity)
} else {
transform3D = CATransform3DTranslate(transform3D, 0, 0, -35)
}
containView.addSubview(fromVC!.view)
containView.addSubview(toVC!.view)
fromVC?.view.addSubview(maskView)
maskView.layer.opacity = startOpacity
toVC?.view.layer.position.x = startPositionX + toVC!.view.layer.bounds.width / 2
shadowOpacityBackup = toVC?.view.layer.shadowOpacity
shadowOffsetBackup = toVC?.view.layer.shadowOffset
shadowRadiusBackup = toVC?.view.layer.shadowRadius
shadowPathBackup = toVC?.view.layer.shadowPath
toVC?.view.layer.shadowOpacity = 0.5
toVC?.view.layer.shadowOffset = CGSize(width: -3, height: 0)
toVC?.view.layer.shadowRadius = 5
toVC?.view.layer.shadowPath = CGPath(rect: toVC!.view.layer.bounds, transform: nil)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseInOut, animations: {
self.maskView.layer.opacity = endOpacity
fromVC?.view.layer.transform = transform3D
toVC?.view.layer.position.x = endPositionX + toVC!.view.layer.bounds.width / 2
}) { finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
if !self.cancelPop {
toVC?.view.layer.shadowOpacity = 0
if self.transitionStatus == .pop && finished && !self.cancelPop {
self.maskView.removeFromSuperview()
fromVC?.view.layer.transform = self.transformBackup ?? CATransform3DIdentity
}
if finished {
toVC?.view.layer.shadowOpacity = self.shadowOpacityBackup ?? 0
toVC?.view.layer.shadowOffset = self.shadowOffsetBackup ?? CGSize(width: 0, height: 0)
toVC?.view.layer.shadowRadius = self.shadowRadiusBackup ?? 0
toVC?.view.layer.shadowPath = self.shadowPathBackup ?? CGPath(rect: CGRect.zero, transform: nil)
self.completion?()
self.completion = nil
}
}
self.cancelPop = false
}
}
}
|
mit
|
529df4a6b02c25bab6fcc248e137e02c
| 40.900901 | 132 | 0.643303 | 5.339839 | false | false | false | false |
apple/swift-docc-symbolkit
|
Sources/SymbolKit/SymbolGraph/Symbol/Swift/Generics.swift
|
1
|
2284
|
/*
This source file is part of the Swift.org open source project
Copyright (c) 2021 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
extension SymbolGraph.Symbol.Swift {
/**
The generic signature of a declaration or type.
*/
public struct Generics: Mixin {
public static let mixinKey = "swiftGenerics"
enum CodingKeys: String, CodingKey {
case parameters
case constraints
}
/**
The generic parameters of a declaration.
For example, in the following generic function signature,
```swift
func foo<T>(_ thing: T) { ... }
```
`T` is a *generic parameter*.
*/
public var parameters: [GenericParameter]
/**
The generic constraints of a declaration.
For example, in the following generic function signature,
```swift
func foo<S>(_ s: S) where S: Sequence
```
There is a *conformance constraint* involving `S`.
*/
public var constraints: [GenericConstraint]
public init(parameters: [SymbolGraph.Symbol.Swift.GenericParameter], constraints: [SymbolGraph.Symbol.Swift.GenericConstraint]) {
self.parameters = parameters
self.constraints = constraints
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
parameters = try container.decodeIfPresent([GenericParameter].self, forKey: .parameters) ?? []
constraints = try container.decodeIfPresent([GenericConstraint].self, forKey: .constraints) ?? []
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if !parameters.isEmpty {
try container.encode(parameters, forKey: .parameters)
}
if !constraints.isEmpty {
try container.encode(constraints, forKey: .constraints)
}
}
}
}
|
apache-2.0
|
7f9ca9c6899099e3850241df0a4365e5
| 30.722222 | 137 | 0.617776 | 5.121076 | false | false | false | false |
ifeherva/HSTracker
|
HSTracker/Importers/Handlers/HearthstoneDecks.swift
|
1
|
2072
|
//
// HearthstoneDecks.swift
// HSTracker
//
// Created by Benjamin Michotte on 25/02/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import Kanna
import RegexUtil
struct HearthstoneDecks: HttpImporter {
static let classes = [
"Chaman": "shaman",
"Chasseur": "hunter",
"Démoniste": "warlock",
"Druide": "druid",
"Guerrier": "warrior",
"Mage": "mage",
"Paladin": "paladin",
"Prêtre": "priest",
"Voleur": "rogue"
]
var siteName: String {
return "Hearthstone-Decks"
}
var handleUrl: RegexPattern {
return "hearthstone-decks\\.com"
}
var preferHttps: Bool {
return false
}
func loadDeck(doc: HTMLDocument, url: String) -> (Deck, [Card])? {
guard let classNode = doc.at_xpath("//input[@id='classe_nom']"),
let clazz = classNode["value"],
let className = HearthstoneDecks.classes[clazz],
let playerClass = CardClass(rawValue: className.lowercased()) else {
logger.error("Class not found")
return nil
}
logger.verbose("Got class \(playerClass)")
guard let deckNode = doc.at_xpath("//div[@id='content']//h1"),
let deckName = deckNode.text else {
logger.error("Deck name not found")
return nil
}
logger.verbose("Got deck name \(deckName)")
let deck = Deck()
deck.playerClass = playerClass
deck.name = deckName
var cards: [Card] = []
for cardNode in doc.xpath("//table[contains(@class,'tabcartes')]//tbody//tr//a") {
if let qty = cardNode["nb_card"],
let cardId = cardNode["real_id"],
let count = Int(qty),
let card = Cards.by(cardId: cardId) {
card.count = count
logger.verbose("Got card \(card)")
cards.append(card)
}
}
return (deck, cards)
}
}
|
mit
|
93a6a06ccdbe44c48a2c4c87c05e88a4
| 26.959459 | 90 | 0.535524 | 4.072835 | false | false | false | false |
maxoll90/FSwift
|
ios8-example/FSwift-Sample/Pods/FSwift/FSwift/Concurrency/Stream.swift
|
2
|
7009
|
//
// Stream.swift
// FSwift
//
// Created by Kelton Person on 4/8/15.
// Copyright (c) 2015 Kelton. All rights reserved.
//
import Foundation
public final class Stream<T> {
private(set) var isOpen: Bool = true
private(set) var subscriptions:[Subscription<T>] = []
public init() {
}
/**
closes the stream,
note that all queued messages will be published, but no other messages can be published
*/
public func close() {
isOpen = false
}
/**
opens the stream, by default, a stream is open
*/
public func open() {
isOpen = true
}
private func synced(closure: () -> ()) {
objc_sync_enter(self)
closure()
objc_sync_exit(self)
}
/**
publishes a message to the sream
:param: v - the value to publish
:returns: the stream that received the publish request (self)
*/
public func publish(v: T) -> Stream<T> {
synced {
if self.isOpen {
var last = self.subscriptions.count - 1
while last >= 0 {
if self.subscriptions[last].shouldExecute {
self.subscriptions[last].handle(v)
}
else {
self.subscriptions[last].stream = nil
self.subscriptions[last].isCancelled = true
self.subscriptions.removeAtIndex(last)
}
last = last - 1
}
}
}
return self
}
func clean() {
synced {
if self.isOpen {
var last = self.subscriptions.count - 1
while last >= 0 {
if !self.subscriptions[last].shouldExecute {
self.subscriptions.removeAtIndex(last)
}
last = last - 1
}
}
}
}
/**
subscribes to the stream,
this subscription will not received queued publisheds, only new publisheds
:param: s - a stream subscription
:returns: the stream that received the subscription request (self)
*/
public func subscribe(s: Subscription<T>) -> Subscription<T> {
synced {
s.stream = self
self.subscriptions.append(s)
}
return s
}
/**
clears all subscriptions,
note that all queued messages will be published, but no other messages can be published
:returns: the stream that was cleared (self)
*/
public func clearSubscriptions() -> Stream<T> {
synced {
self.subscriptions = []
}
return self
}
}
/**
* Manages streams subscriptions
*/
public class Subscription<T> {
internal(set) var isCancelled = false
private let action:(T) -> Void
private let executionCheck:() -> Bool
private let callbackQueue: NSOperationQueue
var stream: Stream<T>?
public init(action: (T) -> Void, callbackQueue: NSOperationQueue = NSOperationQueue.mainQueue(), executionCheck: () -> Bool) {
self.action = action
self.callbackQueue = callbackQueue
self.executionCheck = executionCheck
}
func handle(v: T) {
let operation = NSBlockOperation {
self.action(v)
}
callbackQueue.addOperation(operation)
}
/**
Cancels the subscriptuon
*/
public func cancel() {
isCancelled = true
//break the link between the stream and the subscription
stream?.clean()
stream = nil
}
/// determines if the subscription will receive a notification
public var shouldExecute: Bool {
return !isCancelled && executionCheck()
}
}
public extension Stream {
/**
subscribes to the stream
:param: - x an object, if nil the subscription is cancelled
:param: - f the action to be executed on publish
:returns: the subscription
*/
public func subscribe(x: AnyObject?, f: T -> Void) -> Subscription<T> {
let subscription = Subscription<T>(action: f, callbackQueue: NSOperationQueue.mainQueue(), executionCheck: { x != nil })
return self.subscribe(subscription)
}
/**
subscribes to the stream
:param: - x function to be evaluated at publish time, if its produces a nil, the subscription is cancelled
:param: - f the action to be executed on publish
:returns: the stream that received the subscription request (self)
*/
public func subscribe(x: () -> AnyObject?, f: T -> Void) -> Subscription<T> {
let subscription = Subscription(action: f, callbackQueue: NSOperationQueue.mainQueue(), executionCheck: { x() != nil })
return self.subscribe(subscription)
}
/**
subscribes to the stream
:param: - x a boolean, if its false, the subscription is cancelled
:param: - f the action to be executed on publish
:returns: the subscription
*/
public func subscribe(x: Bool, f: T -> Void) -> Subscription<T> {
let subscription = Subscription<T>(action: f, callbackQueue: NSOperationQueue.mainQueue(), executionCheck: { x })
return self.subscribe(subscription)
}
/**
subscribes to the stream
:param: - x a function to be evaluated at publish time, if its produces a false, the subscription is cancelled
:param: - f the action to be executed on publish
:returns: the subscription request
*/
public func subscribe(x: () -> Bool, f: T -> Void) -> Subscription<T> {
let subscription = Subscription(action: f, callbackQueue: NSOperationQueue.mainQueue(), executionCheck: { x() })
return self.subscribe(subscription)
}
/**
subscribes to the stream, it will always receive a publish callback
:param: - f the action to be executed on publish
:returns: the subscription
*/
public func subscribe(f: T -> Void) -> Subscription<T> {
let subscription = Subscription(action: f, callbackQueue: NSOperationQueue.mainQueue(), executionCheck: { true })
return self.subscribe(subscription)
}
}
public extension Future {
public func pipeTo(stream: Stream<T>) {
self.signal.register { status in
switch status {
case TryStatus.Success:
stream.publish(self.finalVal)
case TryStatus.Failure(let err):
1 + 1 //do nothing
}
}
}
public func pipeTo(stream: Stream<Try<T>>) {
self.signal.register { status in
switch status {
case TryStatus.Success:
stream.publish(Try.Success(self.finalVal))
case TryStatus.Failure(let err):
stream.publish(Try.Failure(err))
}
}
}
}
|
mit
|
fa948a0210a5709a29fcfe4aa4d61020
| 26.594488 | 130 | 0.569696 | 4.794118 | false | false | false | false |
apple/swift
|
test/Parse/multiline_string.swift
|
7
|
2539
|
// RUN: %target-swift-frontend -dump-ast %s | %FileCheck %s
import Swift
// ===---------- Multiline --------===
_ = """
One
""Alpha""
"""
// CHECK: "One\n\"\"Alpha\"\""
_ = """
Two
Beta
"""
// CHECK: " Two\nBeta"
_ = """
Three
Gamma
"""
// CHECK: " Three\n Gamma"
_ = """
Four
Delta
"""
// CHECK: " Four\n Delta"
_ = """
Five\n
Epsilon
"""
// CHECK: "Five\n\n\nEpsilon"
_ = """
Six
Zeta
"""
// CHECK: "Six\nZeta\n"
_ = """
Seven
Eta\n
"""
// CHECK: "Seven\nEta\n"
_ = """
\"""
"\""
""\"
Iota
"""
// CHECK: "\"\"\"\n\"\"\"\n\"\"\"\nIota"
_ = """
\("Nine")
Kappa
"""
// CHECK: "\nKappa"
_ = """
first
second
third
"""
// CHECK: "first\n second\nthird"
_ = """
first
second
third
"""
// CHECK: "first\n\tsecond\nthird"
_ = """
\\
"""
// CHECK: "\\"
_ = """
\\
"""
// CHECK: "\\"
_ = """
ABC
"""
// CHECK: "\nABC"
_ = """
ABC
"""
// CHECK: "\nABC"
_ = """
ABC
"""
// CHECK: "\nABC"
// contains tabs
_ = """
Twelve
Nu
"""
// CHECK: "Twelve\nNu"
_ = """
newline \
elided
"""
// CHECK: "newline elided"
// contains trailing whitespace
_ = """
trailing \
\("""
substring1 \
\("""
substring2 \
substring3
""")
""") \
whitespace
"""
// CHECK: "trailing "
// CHECK: "substring1 "
// CHECK: "substring2 substring3"
// CHECK: " whitespace"
// contains trailing whitespace
_ = """
foo\
bar
"""
// CHECK: "foo\nbar"
// contains trailing whitespace
_ = """
foo\
bar
"""
// CHECK: "foo\nbar"
_ = """
foo \
bar
"""
// CHECK: "foo bar"
_ = """
ABC
"""
// CHECK: "\nABC"
_ = """
ABC
"""
// CHECK: "\nABC\n"
_ = """
"""
// CHECK: "\n"
_ = """
"""
// CHECK: ""
_ = """
"""
// CHECK: ""
_ = "\("""
\("a" + """
valid
""")
""") literal"
// CHECK: "a"
// CHECK: " valid"
// CHECK: " literal"
_ = "hello\("""
world
""")"
// CHECK: "hello"
// CHECK: "world"
_ = """
hello\("""
world
""")
abc
"""
// CHECK: "hello"
// CHECK: "world"
// CHECK: "\nabc"
_ = "hello\("""
"world'
""")abc"
// CHECK: "hello"
// CHECK: "\"world'"
// CHECK: "abc"
_ = """
welcome
\(
/*
')' or '"""' in comment.
"""
*/
"to\("""
Swift
""")"
// ) or """ in comment.
)
!
"""
// CHECK: "welcome\n"
// CHECK: "to"
// CHECK: "Swift"
// CHECK: "\n!"
|
apache-2.0
|
74d43709ac0d760907adb791d5853d54
| 9.668067 | 59 | 0.381252 | 2.81798 | false | false | false | false |
justwudi/WDImagePicker
|
Classes/WDImageCropView.swift
|
1
|
9663
|
//
// WDImageCropView.swift
// WDImagePicker
//
// Created by Wu Di on 27/8/15.
// Copyright (c) 2015 Wu Di. All rights reserved.
//
import UIKit
import QuartzCore
private class ScrollView: UIScrollView {
private override func layoutSubviews() {
super.layoutSubviews()
if let zoomView = self.delegate?.viewForZoomingInScrollView?(self) {
let boundsSize = self.bounds.size
var frameToCenter = zoomView.frame
// center horizontally
if frameToCenter.size.width < boundsSize.width {
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2
} else {
frameToCenter.origin.x = 0
}
// center vertically
if frameToCenter.size.height < boundsSize.height {
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2
} else {
frameToCenter.origin.y = 0
}
zoomView.frame = frameToCenter
}
}
}
internal class WDImageCropView: UIView, UIScrollViewDelegate {
var resizableCropArea = false
private var scrollView: UIScrollView!
private var imageView: UIImageView!
private var cropOverlayView: WDImageCropOverlayView!
private var xOffset: CGFloat!
private var yOffset: CGFloat!
private static func scaleRect(rect: CGRect, scale: CGFloat) -> CGRect {
return CGRectMake(
rect.origin.x * scale,
rect.origin.y * scale,
rect.size.width * scale,
rect.size.height * scale)
}
var imageToCrop: UIImage? {
get {
return self.imageView.image
}
set {
self.imageView.image = newValue
}
}
var cropSize: CGSize {
get {
return self.cropOverlayView.cropSize
}
set {
if let view = self.cropOverlayView {
view.cropSize = newValue
} else {
if self.resizableCropArea {
self.cropOverlayView = WDResizableCropOverlayView(frame: self.bounds,
initialContentSize: CGSizeMake(newValue.width, newValue.height))
} else {
self.cropOverlayView = WDImageCropOverlayView(frame: self.bounds)
}
self.cropOverlayView.cropSize = newValue
self.addSubview(self.cropOverlayView)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.userInteractionEnabled = true
self.backgroundColor = UIColor.blackColor()
self.scrollView = ScrollView(frame: frame)
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.delegate = self
self.scrollView.clipsToBounds = false
self.scrollView.decelerationRate = 0
self.scrollView.backgroundColor = UIColor.clearColor()
self.addSubview(self.scrollView)
self.imageView = UIImageView(frame: self.scrollView.frame)
self.imageView.contentMode = .ScaleAspectFit
self.imageView.backgroundColor = UIColor.blackColor()
self.scrollView.addSubview(self.imageView)
self.scrollView.minimumZoomScale =
CGRectGetWidth(self.scrollView.frame) / CGRectGetHeight(self.scrollView.frame)
self.scrollView.maximumZoomScale = 20
self.scrollView.setZoomScale(1.0, animated: false)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if !resizableCropArea {
return self.scrollView
}
let resizableCropView = cropOverlayView as! WDResizableCropOverlayView
let outerFrame = CGRectInset(resizableCropView.cropBorderView.frame, -10, -10)
if CGRectContainsPoint(outerFrame, point) {
if resizableCropView.cropBorderView.frame.size.width < 60 ||
resizableCropView.cropBorderView.frame.size.height < 60 {
return super.hitTest(point, withEvent: event)
}
let innerTouchFrame = CGRectInset(resizableCropView.cropBorderView.frame, 30, 30)
if CGRectContainsPoint(innerTouchFrame, point) {
return self.scrollView
}
let outBorderTouchFrame = CGRectInset(resizableCropView.cropBorderView.frame, -10, -10)
if CGRectContainsPoint(outBorderTouchFrame, point) {
return super.hitTest(point, withEvent: event)
}
return super.hitTest(point, withEvent: event)
}
return self.scrollView
}
override func layoutSubviews() {
super.layoutSubviews()
let size = self.cropSize;
let toolbarSize = CGFloat(UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 0 : 54)
self.xOffset = floor((CGRectGetWidth(self.bounds) - size.width) * 0.5)
self.yOffset = floor((CGRectGetHeight(self.bounds) - toolbarSize - size.height) * 0.5)
let height = self.imageToCrop!.size.height
let width = self.imageToCrop!.size.width
var factor: CGFloat = 0
var factoredHeight: CGFloat = 0
var factoredWidth: CGFloat = 0
if width > height {
factor = width / size.width
factoredWidth = size.width
factoredHeight = height / factor
} else {
factor = height / size.height
factoredWidth = width / factor
factoredHeight = size.height
}
self.cropOverlayView.frame = self.bounds
self.scrollView.frame = CGRectMake(xOffset, yOffset, size.width, size.height)
self.scrollView.contentSize = CGSizeMake(size.width, size.height)
self.imageView.frame = CGRectMake(0, floor((size.height - factoredHeight) * 0.5),
factoredWidth, factoredHeight)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.imageView
}
func croppedImage() -> UIImage {
// Calculate rect that needs to be cropped
var visibleRect = resizableCropArea ?
calcVisibleRectForResizeableCropArea() : calcVisibleRectForCropArea()
// transform visible rect to image orientation
let rectTransform = orientationTransformedRectOfImage(imageToCrop!)
visibleRect = CGRectApplyAffineTransform(visibleRect, rectTransform);
// finally crop image
let imageRef = CGImageCreateWithImageInRect(imageToCrop!.CGImage, visibleRect)
let result = UIImage(CGImage: imageRef!, scale: imageToCrop!.scale,
orientation: imageToCrop!.imageOrientation)
return result
}
private func calcVisibleRectForResizeableCropArea() -> CGRect {
let resizableView = cropOverlayView as! WDResizableCropOverlayView
// first of all, get the size scale by taking a look at the real image dimensions. Here it
// doesn't matter if you take the width or the hight of the image, because it will always
// be scaled in the exact same proportion of the real image
var sizeScale = self.imageView.image!.size.width / self.imageView.frame.size.width
sizeScale *= self.scrollView.zoomScale
// then get the postion of the cropping rect inside the image
var visibleRect = resizableView.contentView.convertRect(resizableView.contentView.bounds,
toView: imageView)
visibleRect = WDImageCropView.scaleRect(visibleRect, scale: sizeScale)
return visibleRect
}
private func calcVisibleRectForCropArea() -> CGRect {
// scaled width/height in regards of real width to crop width
let scaleWidth = imageToCrop!.size.width / cropSize.width
let scaleHeight = imageToCrop!.size.height / cropSize.height
var scale: CGFloat = 0
if cropSize.width == cropSize.height {
scale = max(scaleWidth, scaleHeight)
} else if cropSize.width > cropSize.height {
scale = imageToCrop!.size.width < imageToCrop!.size.height ?
max(scaleWidth, scaleHeight) :
min(scaleWidth, scaleHeight)
} else {
scale = imageToCrop!.size.width < imageToCrop!.size.height ?
min(scaleWidth, scaleHeight) :
max(scaleWidth, scaleHeight)
}
// extract visible rect from scrollview and scale it
var visibleRect = scrollView.convertRect(scrollView.bounds, toView:imageView)
visibleRect = WDImageCropView.scaleRect(visibleRect, scale: scale)
return visibleRect
}
private func orientationTransformedRectOfImage(image: UIImage) -> CGAffineTransform {
var rectTransform: CGAffineTransform!
switch image.imageOrientation {
case .Left:
rectTransform = CGAffineTransformTranslate(
CGAffineTransformMakeRotation(CGFloat(M_PI_2)), 0, -image.size.height)
case .Right:
rectTransform = CGAffineTransformTranslate(
CGAffineTransformMakeRotation(CGFloat(-M_PI_2)),-image.size.width, 0)
case .Down:
rectTransform = CGAffineTransformTranslate(
CGAffineTransformMakeRotation(CGFloat(-M_PI)),
-image.size.width, -image.size.height)
default:
rectTransform = CGAffineTransformIdentity
}
return CGAffineTransformScale(rectTransform, image.scale, image.scale)
}
}
|
mit
|
dd1968d82475cbe6d646682262865872
| 36.312741 | 99 | 0.636655 | 5.05387 | false | false | false | false |
pfvernon2/swiftlets
|
iOSX/iOS/UILabel+Utilities.swift
|
1
|
685
|
//
// UILabel+Utilities.swift
// swiftlets
//
// Created by Frank Vernon on 5/16/20.
// Copyright © 2020 Frank Vernon. All rights reserved.
//
import UIKit
///Tirivial protocol to allow views to hide themselves when unused in the UI
public protocol SelfHiding {
func hideIfEmpty()
}
extension UIImageView: SelfHiding {
public func hideIfEmpty() {
self.isHidden = self.image == nil
}
}
extension UILabel: SelfHiding {
public func hideIfEmpty() {
isHidden = text?.isEmpty ?? true
}
}
public extension UILabel {
func toUpper() {
text = text?.uppercased()
}
func toLower() {
text = text?.lowercased()
}
}
|
apache-2.0
|
0a70863fe26406f569e26fb6c53270a7
| 17.486486 | 76 | 0.634503 | 3.931034 | false | false | false | false |
ayushgoel/SAHistoryNavigationViewController
|
SAHistoryNavigationViewController/SAHistoryViewController.swift
|
1
|
5004
|
//
// SAHistoryViewController.swift
// SAHistoryNavigationViewController
//
// Created by 鈴木大貴 on 2015/03/26.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
import MisterFusion
protocol SAHistoryViewControllerDelegate: class {
func historyViewController(viewController: SAHistoryViewController, didSelectIndex index: Int)
}
class SAHistoryViewController: UIViewController {
//MARK: static constants
static private let LineSpace: CGFloat = 20.0
static private let ReuseIdentifier = "Cell"
//MARK: - Properties
weak var delegate: SAHistoryViewControllerDelegate?
weak var contentView: UIView?
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
var images: [UIImage]?
var currentIndex: Int = 0
private var selectedIndex: Int?
private var isFirstLayoutSubviews = true
//MARKL: - Initializers
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
deinit {
contentView?.removeFromSuperview()
contentView = nil
}
//MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let contentView = contentView {
view.addSubview(contentView)
view.addLayoutSubview(contentView, andConstraints:
contentView.Top,
contentView.Bottom,
contentView.Left,
contentView.Right
)
}
view.backgroundColor = contentView?.backgroundColor
let size = UIScreen.mainScreen().bounds.size
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.itemSize = size
layout.minimumInteritemSpacing = 0.0
layout.minimumLineSpacing = self.dynamicType.LineSpace
layout.sectionInset = UIEdgeInsets(top: 0.0, left: size.width, bottom: 0.0, right: size.width)
layout.scrollDirection = .Horizontal
}
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: self.dynamicType.ReuseIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .clearColor()
collectionView.showsHorizontalScrollIndicator = false
view.addLayoutSubview(collectionView, andConstraints:
collectionView.Top,
collectionView.Bottom,
collectionView.CenterX,
collectionView.Width |==| view.Width |*| 3
)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if isFirstLayoutSubviews {
scrollToIndex(currentIndex, animated: false)
isFirstLayoutSubviews = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: - Scroll handling
extension SAHistoryViewController {
private func scrollToIndex(index: Int, animated: Bool) {
collectionView.scrollToItemAtIndexPath(NSIndexPath(forRow: index, inSection: 0), atScrollPosition: .CenteredHorizontally, animated: animated)
}
func scrollToSelectedIndex(animated: Bool) {
guard let index = selectedIndex else { return }
scrollToIndex(index, animated: animated)
}
}
//MARK: - UICollectionViewDataSource
extension SAHistoryViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.dynamicType.ReuseIdentifier, forIndexPath: indexPath)
let subviews = cell.subviews
subviews.forEach {
if let view = $0 as? UIImageView {
view.removeFromSuperview()
}
}
let imageView = UIImageView(frame: cell.bounds)
imageView.image = images?[indexPath.row]
cell.addSubview(imageView)
return cell
}
}
//MARK: - UICollectionViewDelegate
extension SAHistoryViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.deselectItemAtIndexPath(indexPath, animated: false)
let index = indexPath.row
selectedIndex = index
delegate?.historyViewController(self, didSelectIndex:index)
}
}
|
mit
|
3123c26e7be33caee133403b8b106084
| 34.119718 | 149 | 0.680706 | 5.811189 | false | false | false | false |
AlphaJian/LarsonApp
|
LarsonApp/LarsonApp/Class/JobDetail/WorkOrderViews/Cell/InputWorkOrderCell.swift
|
1
|
1552
|
//
// InputWorkOrderCell.swift
// LarsonApp
//
// Created by Perry Z Chen on 11/11/16.
// Copyright © 2016 Jian Zhang. All rights reserved.
//
import UIKit
class InputWorkOrderCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var contentTextView: UITextView!
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var textViewHeightConstraint: NSLayoutConstraint!
var textViewUpdateBlock: ReturnBlock?
override func awakeFromNib() {
super.awakeFromNib()
self.contentTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0)
self.contentTextView.textContainer.lineFragmentPadding = 0
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func initUI(parameter: (String, String)) {
self.titleLabel.text = parameter.0
self.contentTextView.text = parameter.1
}
}
extension InputWorkOrderCell : UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
self.textViewUpdateBlock?(textView.text as AnyObject)
}
func textViewDidBeginEditing(_ textView: UITextView) {
self.bottomView.backgroundColor = .blue
self.titleLabel.textColor = .blue
}
func textViewDidEndEditing(_ textView: UITextView) {
self.bottomView.backgroundColor = .lightGray
self.titleLabel.textColor = .darkGray
}
}
|
apache-2.0
|
272dea041f8e53b9838d1bc5af5bc847
| 28.264151 | 78 | 0.689233 | 4.831776 | false | false | false | false |
mayongl/SpaceCannon
|
SpaceCannon/SpaceCannon/GameScene.swift
|
1
|
17000
|
//
// GameScene.swift
// SpaceCannon
//
// Created by Yonglin Ma on 2/15/17.
// Copyright © 2017 Sixlivesleft. All rights reserved.
//
import SpriteKit
import GameplayKit
import AVFoundation
func radiansToVector(radians : CGFloat) -> CGVector {
var vector = CGVector()
vector.dx = cos(radians)
vector.dy = sin(radians)
return vector
}
func randomInRange(low : CGFloat, high : CGFloat) -> CGFloat{
var value = CGFloat(arc4random_uniform(10000)) / CGFloat(10000)
value = value * (high - low) + low
return value
}
class GameScene: SKScene, SKPhysicsContactDelegate {
let SHOOT_SPEED : CGFloat = 2000.0
let HaloLowAngle : CGFloat = 200.0 * CGFloat.pi / 180.0
let HaloHighAngle : CGFloat = 340.0 * CGFloat.pi / 180.0
let HaloSpeed : CGFloat = 200.0
let haloCategory : UInt32 = 0x1 << 0
let ballCategory : UInt32 = 0x1 << 1
let edgeCategory : UInt32 = 0x1 << 2
let shieldCategory : UInt32 = 0x1 << 3
let lifeBarCategory : UInt32 = 0x1 << 4
let keyTopScore = "TopScore"
var ammo : Int = 5 {
didSet {
if (ammo >= 0 && ammo <= 5) {
ammoDisplay?.texture = SKTexture(imageNamed: String.init(format: "Ammo%d", ammo))
} else {
ammo = 5
}
}
}
var score : Int = 0 {
didSet {
scoreLabel?.text = String.init(format: "Score: %d", score)
}
}
var gamePaused : Bool = false {
willSet {
if !gameOver { //It would be late if this is put into didSet
pauseButton?.isHidden = newValue
resumeButton?.isHidden = !newValue
}
}
didSet {
if !gameOver {
if gamePaused {
// self.run(SKAction.sequence([//SKAction.wait(forDuration: 0.1),
// SKAction.run {self.view?.isPaused = true}
// ]))
self.run(SKAction.run {self.view?.isPaused = true}) //The s can't be called directly, otherwise there would be no time to show the resume button
} else {
self.view?.isPaused = false
}
}
}
}
var topScore = 0
var gameOver = true
var appDefaults : UserDefaults?
private var mainLayer : SKNode?
private var menuLayer : SKNode?
private var cannon : SKSpriteNode?
private var ammoDisplay : SKSpriteNode?
private var scoreLabel : SKLabelNode?
private var pauseButton : SKSpriteNode?
private var resumeButton : SKSpriteNode?
//private var explosion : SKEmitterNode?
private var didShoot = false
/*override init() {
appDefaults = UserDefaults.standard
super.init()
topScore = (userDefaults?.integer(forKey: keyTopScore))!
}*/
override func didMove(to view: SKView) {
self.physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)
self.physicsWorld.contactDelegate = self
//self.explosion = SKEmitterNode(fileNamed: "HaloExplosion.sks")
self.cannon = self.childNode(withName: "cannon") as? SKSpriteNode
self.ammoDisplay = self.childNode(withName: "ammoDisplay") as? SKSpriteNode
self.scoreLabel = self.childNode(withName: "scoreLabel") as? SKLabelNode
self.mainLayer = self.childNode(withName: "mainLayer")
self.menuLayer = self.childNode(withName: "menuLayer")
self.pauseButton = self.childNode(withName: "pause") as? SKSpriteNode
self.pauseButton?.isHidden = true
self.resumeButton = self.childNode(withName: "resume") as? SKSpriteNode
self.resumeButton?.isHidden = true
topScore = UserDefaults.standard.integer(forKey: keyTopScore)
// Add edges
let leftEdge = SKNode()
leftEdge.physicsBody = SKPhysicsBody(edgeFrom: CGPoint.zero, to: CGPoint(x: 0.0, y: self.size.height))
leftEdge.physicsBody?.categoryBitMask = edgeCategory
leftEdge.position = CGPoint(x: 0, y: 0)
self.addChild(leftEdge)
let rightEdge = SKNode()
rightEdge.physicsBody = SKPhysicsBody(edgeFrom: CGPoint.zero, to: CGPoint(x: 0.0, y: self.size.height))
rightEdge.physicsBody?.categoryBitMask = edgeCategory
rightEdge.position = CGPoint(x: self.size.width, y: 0.0)
self.addChild(rightEdge)
/*if let cannon = self.cannon {
cannon.run(SKAction.repeatForever(
SKAction.sequence([SKAction.rotate(byAngle: CGFloat.pi, duration: 2),
SKAction.rotate(byAngle: -CGFloat.pi, duration: 2)])
))
}*/
showMenu()
// Spawn halos
self.run(SKAction.repeatForever(SKAction.sequence([SKAction.wait(forDuration: 2, withRange: 1),
SKAction.perform(#selector(spawnHalo), onTarget: self)])))
// Restore ammo
self.run(SKAction.repeatForever(SKAction.sequence([SKAction.wait(forDuration: 1),
SKAction.run {self.ammo += 1}
])))
}
func newGame() {
mainLayer?.removeAllChildren()
menuLayer?.run(SKAction.scale(to: 0.0, duration: 0.5))
//menuLayer?.isHidden = true
gameOver = false
ammo = 5
score = 0
pauseButton?.isHidden = false
// Add shields
for i in 0...6 {
let shield = SKSpriteNode(imageNamed: "Block")
shield.name = "shield"
shield.position = CGPoint(x: 75 + 100*i, y: 150)
shield.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 42, height: 9))
shield.physicsBody?.categoryBitMask = shieldCategory
shield.physicsBody?.collisionBitMask = 0
shield.xScale = 2.0
shield.yScale = 2.0
mainLayer?.addChild(shield)
}
// Add life bar
let lifeBar = SKSpriteNode(imageNamed: "BlueBar")
lifeBar.position = CGPoint(x: self.size.width/2, y: 120)
lifeBar.size = CGSize(width: self.size.width, height: lifeBar.size.height)
lifeBar.xScale = 2.0
lifeBar.yScale = 2.0
lifeBar.physicsBody = SKPhysicsBody(edgeFrom: CGPoint(x: -lifeBar.size.width/2, y: 0), to: CGPoint(x: lifeBar.size.width/2, y: 0))
lifeBar.physicsBody?.categoryBitMask = lifeBarCategory
lifeBar.physicsBody?.collisionBitMask = 0
mainLayer?.addChild(lifeBar)
}
func spawnHalo() {
let halo = SKSpriteNode(imageNamed: "Halo")
halo.name = "halo"
halo.position = CGPoint(x: CGFloat(arc4random_uniform(UInt32(self.size.width-halo.size.width)))+halo.size.width, y: self.size.height)
halo.xScale = 2.0
halo.yScale = 2.0
halo.physicsBody = SKPhysicsBody(circleOfRadius: 32.0)
guard (halo.physicsBody != nil) else {return}
let direction = radiansToVector(radians: randomInRange(low: HaloLowAngle, high: HaloHighAngle))
halo.physicsBody?.velocity.dx = direction.dx * HaloSpeed
halo.physicsBody?.velocity.dy = direction.dy * HaloSpeed
halo.physicsBody?.restitution = 1.0
halo.physicsBody?.linearDamping = 0.0
halo.physicsBody?.friction = 0.0
halo.physicsBody?.categoryBitMask = haloCategory
halo.physicsBody?.collisionBitMask = edgeCategory
halo.physicsBody?.contactTestBitMask = ballCategory | shieldCategory | lifeBarCategory
mainLayer?.addChild(halo)
}
func shoot() {
guard self.ammo > 0 else {return}
guard let cannon = self.cannon else { return }
self.ammo -= 1
let ball = SKSpriteNode(imageNamed: "Ball")
ball.name = "ball"
ball.xScale = 2.0
ball.yScale = 2.0
let rotationVector = radiansToVector(radians: (cannon.zRotation))
ball.position = CGPoint(x: (cannon.position.x + cannon.size.width * 0.5 * rotationVector.dx),
y: (cannon.position.y + cannon.size.height * 0.5 * rotationVector.dy))
ball.physicsBody = SKPhysicsBody(circleOfRadius: 12.0)
ball.physicsBody?.velocity = CGVector(dx: rotationVector.dx * SHOOT_SPEED, dy: rotationVector.dy * SHOOT_SPEED)
ball.physicsBody?.restitution = 1.0
ball.physicsBody?.linearDamping = 0.0
ball.physicsBody?.friction = 0.0
ball.physicsBody?.categoryBitMask = ballCategory
ball.physicsBody?.collisionBitMask = edgeCategory
ball.physicsBody?.contactTestBitMask = edgeCategory
let trail = SKEmitterNode(fileNamed: "BallTrail")
trail?.targetNode = mainLayer
trail?.xScale = 2.0
trail?.yScale = 2.0
ball.addChild(trail!)
mainLayer?.addChild(ball)
self.run(SKAction.playSoundFileNamed("Laser.caf", waitForCompletion: false))
}
//MARK: Frame life cycle
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
override func didEvaluateActions() {
// code
}
override func didSimulatePhysics() {
if didShoot {
for i in 0..<1 {
self.run(SKAction.sequence([SKAction.wait(forDuration: 0.1 * Double(i)),
SKAction.perform(#selector(shoot), onTarget: self)]))
}
didShoot = false
}
// Clean up balls
mainLayer?.enumerateChildNodes(withName: "ball", using: { (node, stop) in
if !self.frame.contains(node.position) {
node.removeFromParent()
}
})
// Clean up halos
mainLayer?.enumerateChildNodes(withName: "halo", using: { (node, stop) in
if !self.frame.contains(node.position) {
node.removeFromParent()
}
})
}
override func didApplyConstraints() {
//<#code#>
}
override func didFinishUpdate() {
//<#code#>
}
//MARK: collision handling
func didBegin(_ contact: SKPhysicsContact) {
var firstBody : SKPhysicsBody?
var secondBody : SKPhysicsBody?
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if (firstBody?.categoryBitMask == haloCategory && secondBody?.categoryBitMask == ballCategory) {
self.addExplosion(position: (firstBody?.node?.position)!, name : "HaloExplosion")
self.run(SKAction.playSoundFileNamed("Explosion.caf", waitForCompletion: false))
self.score += 1
//firstBody?.node?.isHidden = !(firstBody?.node?.isHidden)!
firstBody?.categoryBitMask = 0
firstBody?.node?.removeFromParent()
secondBody?.node?.removeFromParent()
}
if (firstBody?.categoryBitMask == haloCategory && secondBody?.categoryBitMask == shieldCategory) {
self.addExplosion(position: (firstBody?.node?.position)!, name : "HaloExplosion")
self.run(SKAction.playSoundFileNamed("Explosion.caf", waitForCompletion: false))
firstBody?.node?.isHidden = true
firstBody?.categoryBitMask = 0
//firstBody?.node?.removeFromParent()
secondBody?.node?.removeFromParent()
}
if (firstBody?.categoryBitMask == haloCategory && secondBody?.categoryBitMask == lifeBarCategory) {
//self.addExplosion(position: (firstBody?.node?.position)!, name : "HaloExplosion")
self.addExplosion(position: (secondBody?.node?.position)!, name : "LifeBarExplosion")
self.run(SKAction.playSoundFileNamed("DeepExplosion.caf", waitForCompletion: false))
//firstBody?.node?.removeFromParent()
secondBody?.node?.removeFromParent()
endGame()
}
if (firstBody?.categoryBitMask == ballCategory && secondBody?.categoryBitMask == edgeCategory) {
self.run(SKAction.playSoundFileNamed("Bounce.caf", waitForCompletion: false))
}
}
func endGame() {
mainLayer?.enumerateChildNodes(withName: "halo", using: { (node, stop) in
self.addExplosion(position: node.position, name : "HaloExplosion")
node.removeFromParent()
})
mainLayer?.enumerateChildNodes(withName: "ball", using: { (node, stop) in
node.removeFromParent()
})
mainLayer?.enumerateChildNodes(withName: "shield", using: { (node, stop) in
node.removeFromParent()
})
if (score > topScore) {
topScore = score
UserDefaults.standard.set(topScore, forKey: keyTopScore)
}
gameOver = true
pauseButton?.isHidden = true
showMenu()
//self.run(SKAction.sequence([SKAction.wait(forDuration: 1.5),
// SKAction.perform(#selector(newGame), onTarget: self)]))
}
func showMenu() {
let scoreNode = menuLayer?.childNode(withName: "score") as? SKLabelNode
scoreNode?.text = String.init(format : "%d", self.score)
let topScoreNode = menuLayer?.childNode(withName: "topScore") as? SKLabelNode
topScoreNode?.text = String.init(format : "%d", self.topScore)
//menuLayer?.isHidden = false
menuLayer?.run(SKAction.scale(to: 1.0, duration: 0.5))
}
func addExplosion(position : CGPoint, name : String) {
guard let explosion = SKEmitterNode(fileNamed: name) else {return}
explosion.position = position
explosion.xScale = 2.0
explosion.yScale = 2.0
mainLayer?.addChild(explosion)
explosion.run(SKAction.sequence([SKAction.wait(forDuration: 1.5),
SKAction.removeFromParent()]))
}
//MARK: - Touch handling
// func touchDown(atPoint pos : CGPoint) {
// if let n = self.spinnyNode?.copy() as! SKShapeNode? {
// n.position = pos
// n.strokeColor = SKColor.green
// self.addChild(n)
// }
// }
//
// func touchMoved(toPoint pos : CGPoint) {
// if let n = self.spinnyNode?.copy() as! SKShapeNode? {
// n.position = pos
// n.strokeColor = SKColor.blue
// self.addChild(n)
// }
// }
//
// func touchUp(atPoint pos : CGPoint) {
// if let n = self.spinnyNode?.copy() as! SKShapeNode? {
// n.position = pos
// n.strokeColor = SKColor.red
// self.addChild(n)
// }
// }
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// if let label = self.label {
// label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut")
// }
if !gameOver && !(self.view?.isPaused)! {
for t in touches {
let nodes = self.nodes(at: t.location(in: self))
if nodes.count == 0 || nodes[0].name != "pause" {
didShoot = true
}
}
}
}
/*override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}*/
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
//for t in touches { self.touchUp(atPoint: t.location(in: self)) }
for t in touches {
if gameOver {
let nodes = menuLayer?.nodes(at: t.location(in: self).applying(CGAffineTransform(translationX: -((menuLayer?.position.x)!), y: -((menuLayer?.position.y)!))))
if (nodes?.count)! > 0 && nodes?[0].name == "play" {
self.newGame()
}
} else {
let nodes = self.nodes(at: t.location(in: self))
if (nodes.count > 0){
if nodes[0].name == "pause" {
gamePaused = true
} else if nodes[0].name == "resume" {
gamePaused = false
}
}
}
}
}
}
|
mit
|
16acf00aed96141f0cf6026d6690516b
| 35.794372 | 173 | 0.566563 | 4.53065 | false | false | false | false |
avito-tech/Marshroute
|
MarshrouteTests/Sources/Support/TransitionContextsCreator.swift
|
1
|
4144
|
import UIKit
@testable import Marshroute
final class TransitionContextsCreator
{
static func createCompletedTransitionContextFromPresentationTransitionContext(
sourceTransitionsHandler: AnimatingTransitionsHandler,
sourceViewController: UIViewController,
targetViewController: UIViewController,
navigationController: UINavigationController?,
targetTransitionsHandlerBox: CompletedTransitionTargetTransitionsHandlerBox)
-> CompletedTransitionContext
{
var pushAnimationLaunchingContext = PushAnimationLaunchingContext(
targetViewController: targetViewController,
animator: NavigationTransitionsAnimator()
)
pushAnimationLaunchingContext.sourceViewController = sourceViewController
pushAnimationLaunchingContext.navigationController = navigationController
let presentationAnimationLaunchingContextBox = PresentationAnimationLaunchingContextBox.push(
launchingContext: pushAnimationLaunchingContext
)
let sourceAnimationLaunchingContextBox: SourceAnimationLaunchingContextBox
= .presentation(launchingContextBox: presentationAnimationLaunchingContextBox)
navigationController?.pushViewController(targetViewController, animated: false)
return CompletedTransitionContext(
transitionId: TransitionIdGeneratorImpl().generateNewTransitionId(),
sourceTransitionsHandler: sourceTransitionsHandler,
targetViewController: targetViewController,
targetTransitionsHandlerBox: targetTransitionsHandlerBox,
storableParameters: nil,
sourceAnimationLaunchingContextBox: sourceAnimationLaunchingContextBox
)
}
static func createRegisteringCompletedTransitionContext(
sourceTransitionsHandler: AnimatingTransitionsHandler,
targetViewController: UIViewController,
targetTransitionsHandlerBox: CompletedTransitionTargetTransitionsHandlerBox)
-> CompletedTransitionContext
{
let sourceAnimationLaunchingContextBox: SourceAnimationLaunchingContextBox
= .resetting(launchingContextBox: .registering)
// let resettingAnimationLaunchingContextBox = ResettingAnimationLaunchingContextBox.settingNavigationRoot(
// launchingContext: <#T##SettingAnimationLaunchingContext#>)(
//
//
// sourceTransitionsHandler.launchResettingAnimation(
// launchingContextBox: &sourceAnimationLaunchingContextBox
// )
return CompletedTransitionContext(
transitionId: TransitionIdGeneratorImpl().generateNewTransitionId(),
sourceTransitionsHandler: sourceTransitionsHandler,
targetViewController: targetViewController,
targetTransitionsHandlerBox: targetTransitionsHandlerBox,
storableParameters: nil,
sourceAnimationLaunchingContextBox: sourceAnimationLaunchingContextBox
)
}
static func createPresentationTransitionContext() -> PresentationTransitionContext {
return PresentationTransitionContext(
pushingViewController: UIViewController(),
animator: NavigationTransitionsAnimator(),
transitionId: TransitionIdGeneratorImpl().generateNewTransitionId()
)
}
static func createRegisteringEndpointNavigationControllerTransitionContext() -> ResettingTransitionContext {
return ResettingTransitionContext(
registeringEndpointNavigationController: UINavigationController(), animatingTransitionsHandler: NavigationTransitionsHandlerImpl(
navigationController: UINavigationController(),
transitionsCoordinator: TransitionsCoordinatorImpl(
stackClientProvider: TransitionContextsStackClientProviderImpl(),
peekAndPopTransitionsCoordinator: PeekAndPopUtilityImpl()
)
),
transitionId: TransitionIdGeneratorImpl().generateNewTransitionId()
)
}
}
|
mit
|
bbeff690962333db813892971827cfcd
| 46.090909 | 141 | 0.730936 | 7.923518 | false | false | false | false |
sstanic/Shopfred
|
Shopfred/Shopfred/Data/DataStore.swift
|
1
|
11403
|
//
// DataStore.swift
// Shopfred
//
// Created by Sascha Stanic on 6/4/17.
// Copyright © 2017 Sascha Stanic. All rights reserved.
//
import Foundation
import CoreData
import Reachability
/**
The DataStore is the connecting class to the data layer
and to the external database.
- important: The class is shared as singleton and should
be accessed only by the *sharedInstance()* class function.
# Public Attributes
- stack: The core data stack
- dbConnector: The connection to the external database
- userStore: Access to all user management functionalities
- shoppingStore: Access to all shopping space management functionalities
*/
class DataStore {
// MARK: Public Attributes
let stack = CoreDataStack(modelName: "Shopfred")!
var dbConnector: DbConnector? = nil
var userStore: UserStore!
var shoppingStore: ShoppingStore!
public var DeviceIsOnline: Bool {
get {
print("check reachability:")
if self.reachability.connection != .none {
print("online.")
return true
}
else {
print("offline.")
return false
}
}
}
// MARK: Private Attributes
private var reachability: Reachability!
// MARK: - Initializer
init() {
self.reachability = Reachability()!
self.userStore = UserStore(dataStore: self)
self.shoppingStore = ShoppingStore(dataStore: self)
self.shoppingStore.setUserStore(store: self.userStore)
self.userStore.setShoppingStore(store: self.shoppingStore)
}
// MARK: - Shared Instance
class func sharedInstance() -> DataStore {
struct Singleton {
static let sharedInstance = DataStore()
}
return Singleton.sharedInstance
}
// MARK: - Public Functions / Initialize Database Connector
func initializeDbConnector(provider: DbProvider) {
self.dbConnector = DbConnector(provider: provider)
}
func stopSync() {
if let dbConnector = self.dbConnector {
dbConnector.stopSyncFromExternalDb()
}
else {
print("dbConnector not set, skipping stop sync.")
}
}
// MARK: - Load Model (Initial Model Setup, Dependent of User)
func loadModelAndInitializeShoppingSpace(completion: (_ success: Bool, _ error: Error?) -> Void) {
print("load model")
let request: NSFetchRequest = LocalData.fetchRequest()
//initialize localData object which contains a reference to the current shopping space and to the archive of shopping spaces
do {
let results = try self.stack.context.fetch(request)
if (results.count == 1) {
self.shoppingStore.localData = results[0]
}
else {
let userInfo = [NSLocalizedDescriptionKey : "Error occured in loadModel. More than 1 localData object found."]
print(userInfo)
completion(false, NSError(domain: "loadModel", code: 1, userInfo: userInfo))
}
}
catch {
let userInfo = [NSLocalizedDescriptionKey : "Error occured in loadModel."]
print(userInfo)
completion(false, NSError(domain: "loadModel", code: 1, userInfo: userInfo))
}
//check if there was a user logged in. If yes, check current shopping space if user is registered.
if let isLoggedIn = UserDefaults.standard.value(forKey: Constants.IsLoggedIn) as? Bool {
if isLoggedIn {
if let currentUserId = UserDefaults.standard.value(forKey: Constants.CurrentUser) as? String {
if self.shoppingStore.shoppingSpaceHasUser(withId: currentUserId) {
print("Current shopping space has registered user that is logged in. Perfect.")
}
else {
print("User seems to be logged in but is not registered in current shopping space. That's odd.")
print("Set user defaults to user-is-logged-off.")
UserDefaults.standard.setValue(false, forKey: Constants.IsLoggedIn)
if !self.shoppingStore.isShoppingSpaceNew(space: self.shoppingStore.shoppingSpace) {
print("Current shopping space is registered but no user logged in.")
print("Moving current shopping space to archive.")
self.shoppingStore.moveCurrentShoppingSpaceToArchive()
}
}
}
}
}
// try to get the archived shoppingspace without a registered user
if self.shoppingStore.shoppingSpace == nil {
self.shoppingStore.shoppingSpace = self.shoppingStore.getShoppingSpaceFromArchive(withUserId: Constants.UserNotSet)
}
// if finally no shoppingspace is found, create a new one
if self.shoppingStore.shoppingSpace == nil {
self.shoppingStore.createNewShoppingSpace(initialContextName: Constants.InitialContextName, user: nil)
}
completion(true, nil)
}
// MARK: - Public Functions / Save Context & Sync With Database
func saveContext(completion: @escaping (_ success: Bool, _ error: Error?) -> Void) {
print("save context (and sync with db)")
self.shoppingStore.shoppingSpace.lastChange = ISO8601DateFormatter().string(from: Date())
Utils.GlobalMainQueue.async {
if self.stack.context.hasChanges {
do {
try self.stack.context.save()
}
catch {
let userInfo = [NSLocalizedDescriptionKey : "Error occured in saveContext"]
print(userInfo)
print("error message: \(error)")
completion(false, NSError(domain: "saveContext", code: 1, userInfo: userInfo))
}
}
self.shoppingStore.syncShoppingSpaceWithDb()
completion(true, nil)
}
}
func saveContextWithoutSync(_ completion: @escaping (_ success: Bool, _ error: Error?) -> Void) {
print("save context without sync")
Utils.GlobalMainQueue.async {
if self.stack.context.hasChanges {
do {
try self.stack.context.save()
print("context saved without sync.")
}
catch {
let userInfo = [NSLocalizedDescriptionKey : "Error occured in saveContext"]
print(userInfo)
completion(false, NSError(domain: "saveContext", code: 1, userInfo: userInfo))
}
}
completion(true, nil)
}
}
func syncFromDb() {
print("sync from db")
guard self.dbConnector != nil else {
print("DbConnector not set. Skipping sync.")
return
}
let loggedIn = UserDefaults.standard.bool(forKey: Constants.IsLoggedIn)
if loggedIn {
if let shoppingSpace = self.shoppingStore.shoppingSpace {
self.dbConnector!.syncFromExternalDb(withId: shoppingSpace.id!)
}
else {
print("No shopping space found (nil) for sync from external DB!")
}
}
else {
print("User is not logged in, skipping sync from external DB.")
}
}
func negotiateSyncWithExternalDb() {
print("negotiate sync with external db")
guard self.dbConnector != nil else {
print("DbConnector not set. Skipping negotiation.")
return
}
if let shoppingSpaceId = self.shoppingStore.shoppingSpace.id {
self.dbConnector!.getLastSyncDateFromExternalDb(forShoppingSpaceId: shoppingSpaceId) { success, error, dbTimeStamp in
let localTimeStamp = self.shoppingStore.shoppingSpace.lastChange
// Compare local and db sync timestamp
let localDate = self.getDateFromString(dateString: localTimeStamp)
let dbDate = self.getDateFromString(dateString: dbTimeStamp)
print("local date: <\(String(describing: localDate))> -- db date: <\(String(describing: dbDate))>")
// never synced
if localDate == nil && dbDate == nil {
print("never ever synced. nothing to do, first sync will be started after saving context.")
return
}
var toDbFirst: Bool
if localDate == nil && dbDate != nil {
print("for some reason local date is not set, but db date is. sync from db first.")
toDbFirst = false
}
else {
if localDate != nil && dbDate == nil {
print("for some reason db date is not set, but local date is. sync to db first.")
toDbFirst = true
}
else {
if localDate! > dbDate! {
toDbFirst = true
}
else {
toDbFirst = false
}
}
}
if toDbFirst {
// sync local -> db first
print("sync to db first.")
self.shoppingStore.syncShoppingSpaceWithDb()
}
else {
// sync db -> local first
print("sync from db first.")
self.syncFromDb()
}
}
}
else {
print("Something's wrong. Tried to negotiate first sync but there is no shopping space id available.")
}
}
private func getDateFromString(dateString: String?) -> Date? {
if dateString == nil {
return nil
}
let dateFormatter = ISO8601DateFormatter()
return dateFormatter.date(from: dateString!)
}
}
|
mit
|
3662677e71a69af44a021daf2b352b80
| 32.934524 | 132 | 0.504911 | 5.823289 | false | false | false | false |
jalehman/todolist-mvvm
|
todolist-mvvm/Todo.swift
|
1
|
942
|
//
// Todo.swift
// todolist-mvvm
//
// Created by Josh Lehman on 11/6/15.
// Copyright © 2015 JL. All rights reserved.
//
import Foundation
struct Todo: Equatable {
// MARK: Properties
let id: Int
let note: String
let createdAt: NSDate
let dueDate: NSDate
let completed: Bool
// MARK: API
init(id: Int, note: String, completed: Bool, dueDate: NSDate, createdAt: NSDate = NSDate()) {
self.id = id
self.note = note
self.completed = completed
self.createdAt = createdAt
self.dueDate = dueDate
}
func markAs(completed: Bool) -> Todo {
return Todo(id: id, note: note, completed: completed, dueDate: dueDate, createdAt: createdAt)
}
}
func ==(lhs: Todo, rhs: Todo) -> Bool {
return lhs.id == rhs.id && lhs.note == rhs.note && lhs.createdAt == rhs.createdAt && lhs.completed == rhs.completed && lhs.dueDate == rhs.dueDate
}
|
mit
|
2d552f517d1dd3c19c718dc3af404a03
| 23.789474 | 149 | 0.608927 | 3.809717 | false | false | false | false |
zisko/swift
|
stdlib/public/SDK/ARKit/ARKit.swift
|
1
|
4957
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import ARKit
@available(iOS, introduced: 11.0)
extension ARCamera {
/**
A value describing the camera's tracking state.
*/
public enum TrackingState {
public enum Reason {
/** Tracking is limited due to initialization in progress. */
case initializing
/** Tracking is limited due to a excessive motion of the camera. */
case excessiveMotion
/** Tracking is limited due to a lack of features visible to the camera. */
case insufficientFeatures
/** Tracking is limited due to a relocalization in progress. */
@available(iOS, introduced: 11.3)
case relocalizing
}
/** Tracking is not available. */
case notAvailable
/** Tracking is limited. See tracking reason for details. */
case limited(Reason)
/** Tracking is normal. */
case normal
}
/**
The tracking state of the camera.
*/
public var trackingState: TrackingState {
switch __trackingState {
case .notAvailable: return .notAvailable
case .normal: return .normal
case .limited:
let reason: TrackingState.Reason
if #available(iOS 11.3, *) {
switch __trackingStateReason {
case .initializing: reason = .initializing
case .relocalizing: reason = .relocalizing
case .excessiveMotion: reason = .excessiveMotion
default: reason = .insufficientFeatures
}
}
else {
switch __trackingStateReason {
case .initializing: reason = .initializing
case .excessiveMotion: reason = .excessiveMotion
default: reason = .insufficientFeatures
}
}
return .limited(reason)
}
}
}
@available(iOS, introduced: 11.0)
extension ARPointCloud {
/**
The 3D points comprising the point cloud.
*/
@nonobjc public var points: [vector_float3] {
let buffer = UnsafeBufferPointer(start: __points, count: Int(__count))
return Array(buffer)
}
/**
The 3D point identifiers comprising the point cloud.
*/
@nonobjc public var identifiers: [UInt64] {
let buffer = UnsafeBufferPointer(start: __identifiers, count: Int(__count))
return Array(buffer)
}
}
@available(iOS, introduced: 11.0)
extension ARFaceGeometry {
/**
The mesh vertices of the geometry.
*/
@nonobjc public var vertices: [vector_float3] {
let buffer = UnsafeBufferPointer(start: __vertices, count: Int(__vertexCount))
return Array(buffer)
}
/**
The texture coordinates of the geometry.
*/
@nonobjc public var textureCoordinates: [vector_float2] {
let buffer = UnsafeBufferPointer(start: __textureCoordinates, count: Int(__textureCoordinateCount))
return Array(buffer)
}
/**
The triangle indices of the geometry.
*/
@nonobjc public var triangleIndices: [Int16] {
let buffer = UnsafeBufferPointer(start: __triangleIndices, count: Int(triangleCount * 3))
return Array(buffer)
}
}
@available(iOS, introduced: 11.3)
extension ARPlaneGeometry {
/**
The mesh vertices of the geometry.
*/
@nonobjc public var vertices: [vector_float3] {
let buffer = UnsafeBufferPointer(start: __vertices, count: Int(__vertexCount))
return Array(buffer)
}
/**
The texture coordinates of the geometry.
*/
@nonobjc public var textureCoordinates: [vector_float2] {
let buffer = UnsafeBufferPointer(start: __textureCoordinates, count: Int(__textureCoordinateCount))
return Array(buffer)
}
/**
The triangle indices of the geometry.
*/
@nonobjc public var triangleIndices: [Int16] {
let buffer = UnsafeBufferPointer(start: __triangleIndices, count: Int(triangleCount * 3))
return Array(buffer)
}
/**
The vertices of the geometry's outermost boundary.
*/
@nonobjc public var boundaryVertices: [vector_float3] {
let buffer = UnsafeBufferPointer(start: __boundaryVertices, count: Int(__boundaryVertexCount))
return Array(buffer)
}
}
|
apache-2.0
|
459577d81ffe9414b8420ed50ebef2bf
| 30.775641 | 107 | 0.584426 | 5.002018 | false | false | false | false |
zisko/swift
|
test/IRGen/generic_tuples.swift
|
1
|
8285
|
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s | %FileCheck %s
// Make sure that optimization passes don't choke on storage types for generic tuples
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -O %s
// REQUIRES: CPU=x86_64
// CHECK: [[TYPE:%swift.type]] = type {
// CHECK: [[OPAQUE:%swift.opaque]] = type opaque
// CHECK: [[TUPLE_TYPE:%swift.tuple_type]] = type { [[TYPE]], i64, i8*, [0 x %swift.tuple_element_type] }
// CHECK: %swift.tuple_element_type = type { [[TYPE]]*, i64 }
func dup<T>(_ x: T) -> (T, T) { var x = x; return (x,x) }
// CHECK: define hidden swiftcc void @"$S14generic_tuples3dupyx_xtxlF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
// CHECK: entry:
// Allocate a local variable for 'x'.
// CHECK: [[TYPE_ADDR:%.*]] = bitcast %swift.type* %T to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[TYPE_ADDR]], i64 -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[SIZE_WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9
// CHECK: [[SIZE_WITNESS:%.*]] = load i8*, i8** [[SIZE_WITNESS_ADDR]]
// CHECK: [[SIZE:%.*]] = ptrtoint i8* [[SIZE_WITNESS]]
// CHECK: [[X_ALLOCA:%.*]] = alloca i8, {{.*}} [[SIZE]], align 16
// CHECK: [[X_TMP:%.*]] = bitcast i8* [[X_ALLOCA]] to %swift.opaque*
// Debug info shadow copy.
// CHECK-NEXT: store i8* [[X_ALLOCA]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]], align 8
// CHECK-NEXT: [[INITIALIZE_WITH_COPY:%.*]] = bitcast i8* [[WITNESS]] to [[OPAQUE]]* ([[OPAQUE]]*, [[OPAQUE]]*, [[TYPE]]*)*
// CHECK-NEXT: [[X:%.*]] = call [[OPAQUE]]* [[INITIALIZE_WITH_COPY]]([[OPAQUE]]* noalias [[X_TMP]], [[OPAQUE]]* noalias {{.*}}, [[TYPE]]* %T)
// Copy 'x' into the first result.
// CHECK-NEXT: call [[OPAQUE]]* [[INITIALIZE_WITH_COPY]]([[OPAQUE]]* noalias %0, [[OPAQUE]]* noalias [[X_TMP]], [[TYPE]]* %T)
// Copy 'x' into the second element.
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]], align 8
// CHECK-NEXT: [[TAKE_FN:%.*]] = bitcast i8* [[WITNESS]] to [[OPAQUE]]* ([[OPAQUE]]*, [[OPAQUE]]*, [[TYPE]]*)*
// CHECK-NEXT: call [[OPAQUE]]* [[TAKE_FN]]([[OPAQUE]]* noalias %1, [[OPAQUE]]* noalias [[X_TMP]], [[TYPE]]* %T)
struct S {}
func callDup(_ s: S) { _ = dup(s) }
// CHECK-LABEL: define hidden swiftcc void @"$S14generic_tuples7callDupyyAA1SVF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: call swiftcc void @"$S14generic_tuples3dupyx_xtxlF"({{.*}} undef, {{.*}} undef, %swift.type* {{.*}} @"$S14generic_tuples1SVMf", {{.*}})
// CHECK-NEXT: ret void
class C {}
func dupC<T : C>(_ x: T) -> (T, T) { return (x, x) }
// CHECK-LABEL: define hidden swiftcc { %T14generic_tuples1CC*, %T14generic_tuples1CC* } @"$S14generic_tuples4dupCyx_xtxAA1CCRbzlF"(%T14generic_tuples1CC*, %swift.type* %T)
// CHECK-NEXT: entry:
// CHECK: [[REF:%.*]] = bitcast %T14generic_tuples1CC* %0 to %swift.refcounted*
// CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* returned [[REF]])
// CHECK-NEXT: [[TUP1:%.*]] = insertvalue { %T14generic_tuples1CC*, %T14generic_tuples1CC* } undef, %T14generic_tuples1CC* %0, 0
// CHECK-NEXT: [[TUP2:%.*]] = insertvalue { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUP1:%.*]], %T14generic_tuples1CC* %0, 1
// CHECK-NEXT: ret { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUP2]]
func callDupC(_ c: C) { _ = dupC(c) }
// CHECK-LABEL: define hidden swiftcc void @"$S14generic_tuples8callDupCyyAA1CCF"(%T14generic_tuples1CC*)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[REF:%.*]] = bitcast %T14generic_tuples1CC* %0 to %swift.refcounted*
// CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* returned [[REF]])
// CHECK-NEXT: [[METATYPE:%.*]] = call %swift.type* @"$S14generic_tuples1CCMa"()
// CHECK-NEXT: [[TUPLE:%.*]] = call swiftcc { %T14generic_tuples1CC*, %T14generic_tuples1CC* } @"$S14generic_tuples4dupCyx_xtxAA1CCRbzlF"(%T14generic_tuples1CC* %0, %swift.type* [[METATYPE]])
// CHECK-NEXT: [[LEFT:%.*]] = extractvalue { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUPLE]], 0
// CHECK-NEXT: [[RIGHT:%.*]] = extractvalue { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUPLE]], 1
// CHECK-NEXT: [[LEFT_CAST:%.*]] = bitcast %T14generic_tuples1CC* [[LEFT]] to %swift.refcounted*
// CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* returned [[LEFT_CAST]]
// CHECK-NEXT: [[RIGHT_CAST:%.*]] = bitcast %T14generic_tuples1CC* [[RIGHT]] to %swift.refcounted*
// CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* returned [[RIGHT_CAST]]
// CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%T14generic_tuples1CC*)*)(%T14generic_tuples1CC* [[LEFT]])
// CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%T14generic_tuples1CC*)*)(%T14generic_tuples1CC* [[RIGHT]])
// CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%T14generic_tuples1CC*)*)(%T14generic_tuples1CC* [[RIGHT]])
// CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%T14generic_tuples1CC*)*)(%T14generic_tuples1CC* [[LEFT]])
// CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%T14generic_tuples1CC*)*)(%T14generic_tuples1CC* %0)
// CHECK-NEXT: ret void
// CHECK: define hidden swiftcc i64 @"$S14generic_tuples4lumpySi_xxtxlF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
func lump<T>(_ x: T) -> (Int, T, T) { return (0,x,x) }
// CHECK: define hidden swiftcc { i64, i64 } @"$S14generic_tuples5lump2ySi_SixtxlF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
func lump2<T>(_ x: T) -> (Int, Int, T) { return (0,0,x) }
// CHECK: define hidden swiftcc void @"$S14generic_tuples5lump3yx_xxtxlF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
func lump3<T>(_ x: T) -> (T, T, T) { return (x,x,x) }
// CHECK: define hidden swiftcc i64 @"$S14generic_tuples5lump4yx_SixtxlF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
func lump4<T>(_ x: T) -> (T, Int, T) { return (x,0,x) }
// CHECK: define hidden swiftcc i64 @"$S14generic_tuples6unlumpyS2i_xxt_tlF"(i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
func unlump<T>(_ x: (Int, T, T)) -> Int { return x.0 }
// CHECK: define hidden swiftcc void @"$S14generic_tuples7unlump1yxSi_xxt_tlF"(%swift.opaque* noalias nocapture sret, i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
func unlump1<T>(_ x: (Int, T, T)) -> T { return x.1 }
// CHECK: define hidden swiftcc void @"$S14generic_tuples7unlump2yxx_Sixt_tlF"(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
func unlump2<T>(_ x: (T, Int, T)) -> T { return x.0 }
// CHECK: define hidden swiftcc i64 @"$S14generic_tuples7unlump3ySix_Sixt_tlF"(%swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
func unlump3<T>(_ x: (T, Int, T)) -> Int { return x.1 }
// CHECK: tuple_existentials
func tuple_existentials() {
// Empty tuple:
var a : Any = ()
// CHECK: store %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* @"$SytN", i32 0, i32 1),
// 2 element tuple
var t2 = (1,2.0)
a = t2
// CHECK: call %swift.type* @swift_getTupleTypeMetadata2({{.*}}@"$SSiN{{.*}}",{{.*}}@"$SSdN{{.*}}", i8* null, i8** null)
// 3 element tuple
var t3 = ((),(),())
a = t3
// CHECK: call %swift.type* @swift_getTupleTypeMetadata3({{.*}}@"$SytN{{.*}},{{.*}}@"$SytN{{.*}},{{.*}}@"$SytN{{.*}}, i8* null, i8** null)
// 4 element tuple
var t4 = (1,2,3,4)
a = t4
// CHECK: call %swift.type* @swift_getTupleTypeMetadata(i64 4, {{.*}}, i8* null, i8** null)
}
|
apache-2.0
|
f551afc593669bb04298355c258998cc
| 68.041667 | 226 | 0.649849 | 3.075353 | false | false | false | false |
corywilhite/SceneBuilder
|
SceneBuilder/Hue/BridgePermissionManager.swift
|
1
|
3270
|
//
// BridgePermissionManager.swift
// SceneBuilder
//
// Created by Cory Wilhite on 12/7/16.
// Copyright © 2016 Cory Wilhite. All rights reserved.
//
import Foundation
import BoltsSwift
import Alamofire
class BridgePermissionManager {
static let shared = BridgePermissionManager()
func startRequest(with configuration: Bridge.Info) -> Task<String>{
let usernameSource = TaskCompletionSource<String>()
Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { timer in
self.startRequest(with: configuration, timer: timer)
.continueOnSuccessWith(continuation: { usernameSource.set(result: $0) })
}
return usernameSource.task
}
var tries = 0
enum BridgePermissionError: Error {
case unexpectedResponse
case timeout
}
func startRequest(with configuration: Bridge.Info, timer: Timer) -> Task<String> {
let usernameSource = TaskCompletionSource<String>()
let url = "http://\(configuration.internalIpAddress)/api"
let sanitizedDeviceName = UIDevice.current.name.replacingOccurrences(of: " ", with: "#").lowercased().data(using: .ascii, allowLossyConversion: true)
.flatMap { String(data: $0, encoding: .utf8) }
.flatMap { $0.replacingOccurrences(of: "?", with: "") } ?? "default"
request(
url,
method: .post,
parameters: ["devicetype": "SceneBuilder.\(sanitizedDeviceName)"],
encoding: JSONEncoding.default,
headers: nil
)
.responseJSON { (response) in
print(response)
guard let rawResponse = response.result.value as? [[String: Any]],
let responseDictionary = rawResponse.first else {
print("unexpected response")
timer.invalidate()
usernameSource.set(error: BridgePermissionError.unexpectedResponse)
return
}
if let successDictionary = responseDictionary["success"] as? [String: Any],
let username = successDictionary["username"] as? String {
timer.invalidate()
usernameSource.set(result: username)
return
} else if let errorDictionary = responseDictionary["error"] as? [String: Any],
let errorDescription = errorDictionary["description"] as? String {
print(errorDescription)
if self.tries == 6 {
print("invalidating timer")
timer.invalidate()
usernameSource.set(error: BridgePermissionError.timeout)
}
} else {
print("didnt receive expected response type")
}
self.tries += 1
}
return usernameSource.task
}
}
|
mit
|
b2c8282e0a553ded699333a5e308be09
| 33.776596 | 157 | 0.520037 | 5.8375 | false | false | false | false |
oracle/Oracle_DB_Tools
|
examples/rest/xcode-iOS/ords_iPhone/ords_iPhone/EmpDetail.swift
|
1
|
2500
|
//
// empDetail.swift
// ords_iPhone
//
// Created by Brian Spendolini on 3/5/21.
//
import SwiftUI
import MapKit
import CoreLocation
struct EmpDetail: View {
func getLocation(from address: String, completion: @escaping (_ location: CLLocationCoordinate2D?)-> Void) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks,
let location = placemarks.first?.location?.coordinate else {
completion(nil)
return
}
completion(location)
}
}
@State var location: CLLocationCoordinate2D?
@State var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 30.16622932512246, longitude: -97.73921163282644), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
var name: String
var phone: String
var address: String
var city: String
var state: String
var zip: String
var body: some View {
VStack(alignment: .leading) {
Text(name)
.font(.title)
Text(phone)
.font(.subheadline)
Divider()
Text(address)
.font(.headline)
.lineLimit(50)
Text(city)
.font(.headline)
.lineLimit(50)
Text(state)
.font(.headline)
.lineLimit(50)
Text(zip)
.font(.headline)
.lineLimit(50)
Divider()
Map(coordinateRegion: $region)
}.padding().navigationBarTitle(Text(name), displayMode: .inline)
.onAppear {
self.getLocation(from: address + " " +
city + " " +
state + " " +
zip) { coordinates in
print(address + " " +
city + " " +
state + " " +
zip)
print(coordinates) // Print here
self.location = coordinates // Assign to a local variable for further processing
}
}
}
struct EmpDetail_Previews: PreviewProvider {
static var previews: some View {
EmpDetail(name: "name", phone: "phone", address: "address", city: "city", state: "state", zip: "zip")
}
}
}
|
mit
|
575db9137017eafafa9ed00bf72a7393
| 28.411765 | 200 | 0.5044 | 4.873294 | false | false | false | false |
kumabook/MusicFav
|
MusicFav/ChannelCategoryTableViewController.swift
|
1
|
9561
|
//
// ChannelCategoryTableViewController.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 7/11/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import UIKit
import ReactiveSwift
import SwiftyJSON
import FeedlyKit
import MusicFeeder
import MBProgressHUD
import YouTubeKit
class ChannelCategoryTableViewController: AddStreamTableViewController {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
enum Section: Int {
case subscriptions = 0
case guideCategory = 1
static let count = 2
var title: String? {
switch self {
case .subscriptions:
if YouTubeKit.APIClient.isLoggedIn {
return "Your subscriptions"
} else {
return nil
}
case .guideCategory:
return "Category"
}
}
var tableCellReuseIdentifier: String {
switch self {
case .subscriptions:
if YouTubeKit.APIClient.isLoggedIn {
return "Subscriptions"
} else {
return "Login"
}
case .guideCategory:
return "Category"
}
}
var cellHeight: CGFloat {
switch self {
case .subscriptions:
if YouTubeKit.APIClient.isLoggedIn {
return 100
} else {
return 60
}
case .guideCategory:
return 60
}
}
}
var observer: Disposable?
let channelLoader: ChannelLoader!
var indicator: UIActivityIndicatorView!
var reloadButton: UIButton!
init(subscriptionRepository: SubscriptionRepository, channelLoader: ChannelLoader) {
self.channelLoader = channelLoader
super.init(subscriptionRepository: subscriptionRepository)
}
required init(coder aDecoder: NSCoder) {
channelLoader = ChannelLoader()
super.init(coder: aDecoder)
}
override func getSubscribables() -> [FeedlyKit.Stream] {
if let indexPaths = tableView.indexPathsForSelectedRows {
return indexPaths.map { ChannelStream(channel: Channel(subscription: self.channelLoader.subscriptions[$0.item])) }
} else {
return []
}
}
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "StreamTableViewCell", bundle: Bundle.main)
tableView.register(nib, forCellReuseIdentifier: "Subscriptions")
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Login")
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Section.guideCategory.tableCellReuseIdentifier)
navigationItem.rightBarButtonItem = UIBarButtonItem(title:"Add".localize(),
style: UIBarButtonItemStyle.plain,
target: self,
action: #selector(ChannelCategoryTableViewController.add))
indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
indicator.bounds = CGRect(x: 0,
y: 0,
width: indicator.bounds.width,
height: indicator.bounds.height * 3)
indicator.hidesWhenStopped = true
indicator.stopAnimating()
reloadButton = UIButton()
reloadButton.setImage(UIImage(named: "network_error"), for: UIControlState())
reloadButton.setTitleColor(UIColor.black, for: UIControlState())
reloadButton.addTarget(self, action:#selector(ChannelCategoryTableViewController.refresh), for:UIControlEvents.touchUpInside)
reloadButton.setTitle("Sorry, network error occured.".localize(), for:UIControlState.normal)
reloadButton.frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 44);
tableView.allowsMultipleSelection = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateAddButton()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
observeChannelLoader()
channelLoader.fetchSubscriptions()
channelLoader.fetchCategories()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
observer?.dispose()
observer = nil
}
@objc func refresh() {
channelLoader.fetchCategories()
}
func observeChannelLoader() {
observer?.dispose()
observer = channelLoader.signal.observeResult({ result in
guard let event = result.value else { return }
switch event {
case .startLoading:
self.showIndicator()
case .completeLoading:
self.hideIndicator()
self.reloadData(true)
case .failToLoad:
self.showReloadButton()
}
})
reloadData(true)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if tableView.contentOffset.y >= tableView.contentSize.height - tableView.bounds.size.height {
refresh()
}
}
func showIndicator() {
self.tableView.tableFooterView = indicator
indicator?.startAnimating()
}
func hideIndicator() {
indicator?.stopAnimating()
self.tableView.tableFooterView = nil
}
func showReloadButton() {
self.tableView.tableFooterView = reloadButton
}
func hideReloadButton() {
self.tableView.tableFooterView = nil
}
func showYouTubeLoginViewController() {
if !YouTubeKit.APIClient.isLoggedIn {
YouTubeKit.APIClient.authorize()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return Section.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return Section(rawValue: section)?.title
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return Section(rawValue: indexPath.section)!.cellHeight
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .subscriptions:
if YouTubeKit.APIClient.isLoggedIn {
return channelLoader.subscriptions.count
} else {
return 1
}
case .guideCategory:
return channelLoader.categories.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = Section(rawValue: indexPath.section)!
switch section {
case .subscriptions:
if YouTubeKit.APIClient.isLoggedIn {
let cell = tableView.dequeueReusableCell(withIdentifier: section.tableCellReuseIdentifier, for: indexPath) as! StreamTableViewCell
setAccessoryView(cell, indexPath: indexPath)
let subscription = channelLoader.subscriptions[indexPath.item]
cell.titleLabel.text = subscription.title
if let url = URL(string: subscription.thumbnails["default"]!) {
cell.thumbImageView.sd_setImage(with: url)
}
cell.subtitle1Label.text = ""
cell.subtitle2Label.text = subscription.description
cell.subtitle2Label.numberOfLines = 2
cell.subtitle2Label.textAlignment = .left
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: section.tableCellReuseIdentifier, for: indexPath)
cell.textLabel?.text = "Connect with Your YouTube Account"
return cell
}
case .guideCategory:
let cell = tableView.dequeueReusableCell(withIdentifier: section.tableCellReuseIdentifier, for: indexPath)
let category = channelLoader.categories[indexPath.item]
cell.textLabel?.text = category.title
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch Section(rawValue: indexPath.section)! {
case .subscriptions:
if YouTubeKit.APIClient.isLoggedIn {
super.tableView(tableView, didSelectRowAt: indexPath)
} else {
showYouTubeLoginViewController()
}
case .guideCategory:
let vc = ChannelTableViewController(subscriptionRepository: subscriptionRepository,
channelLoader: channelLoader,
type: .category(channelLoader.categories[indexPath.item]))
navigationController?.pushViewController(vc, animated: true)
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
|
mit
|
71d7773cef67ca20664ec2db18fec2a7
| 35.773077 | 146 | 0.600774 | 5.801578 | false | false | false | false |
jeffreybergier/WaterMe2
|
WaterMe/WaterMe/ReminderVesselMain/PhotoEmojiPicker/EmojiPickerCollectionViewCell.swift
|
1
|
2318
|
//
// EmojiPickerCollectionViewCell.swift
// WaterMe
//
// Created by Jeffrey Bergier on 6/3/17.
// Copyright © 2017 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe 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.
//
// WaterMe 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 WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
class EmojiPickerCollectionViewCell: UICollectionViewCell {
static let reuseID = "EmojiPickerCollectionViewCell"
class var nib: UINib { return UINib(nibName: self.reuseID, bundle: Bundle(for: self.self)) }
@IBOutlet private weak var emojiLabel: UILabel?
private var emojiString: String?
override func awakeFromNib() {
super.awakeFromNib()
self.prepareForReuse()
}
func configure(withEmojiString emojiString: String) {
let accessibility = self.traitCollection.preferredContentSizeCategory.isAccessibilityCategory
self.emojiString = emojiString
self.emojiLabel?.attributedText = NSAttributedString(string: emojiString,
font: .emojiLarge(accessibilityFontSizeEnabled: accessibility))
}
func updateLayout() {
guard let emojiString = self.emojiString else { return }
self.configure(withEmojiString: emojiString)
}
override func didMoveToWindow() {
super.didMoveToWindow()
self.updateLayout()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.updateLayout()
}
override func prepareForReuse() {
super.prepareForReuse()
self.emojiString = nil
self.emojiLabel?.attributedText = nil
}
}
|
gpl-3.0
|
4de87566bdaadf7656fa26fc7b093adb
| 33.58209 | 124 | 0.693569 | 4.982796 | false | false | false | false |
lorentey/swift
|
test/attr/attributes.swift
|
12
|
12782
|
// RUN: %target-typecheck-verify-swift -enable-objc-interop
@unknown func f0() {} // expected-error{{unknown attribute 'unknown'}}
@unknown(x,y) func f1() {} // expected-error{{unknown attribute 'unknown'}}
enum binary {
case Zero
case One
init() { self = .Zero }
}
func f5(x: inout binary) {}
//===---
//===--- IB attributes
//===---
@IBDesignable
class IBDesignableClassTy {
@IBDesignable func foo() {} // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{3-17=}}
}
@IBDesignable // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{1-15=}}
struct IBDesignableStructTy {}
@IBDesignable // expected-error {{'@IBDesignable' attribute cannot be applied to this declaration}} {{1-15=}}
protocol IBDesignableProtTy {}
@IBDesignable // expected-error {{@IBDesignable can only be applied to classes and extensions of classes}} {{1-15=}}
extension IBDesignableStructTy {}
class IBDesignableClassExtensionTy {}
@IBDesignable // okay
extension IBDesignableClassExtensionTy {}
class Inspect {
@IBInspectable var value : Int = 0 // okay
@GKInspectable var value2: Int = 0 // okay
@IBInspectable func foo() {} // expected-error {{@IBInspectable may only be used on 'var' declarations}} {{3-18=}}
@GKInspectable func foo2() {} // expected-error {{@GKInspectable may only be used on 'var' declarations}} {{3-18=}}
@IBInspectable class var cval: Int { return 0 } // expected-error {{only instance properties can be declared @IBInspectable}} {{3-18=}}
@GKInspectable class var cval2: Int { return 0 } // expected-error {{only instance properties can be declared @GKInspectable}} {{3-18=}}
}
@IBInspectable var ibinspectable_global : Int // expected-error {{only instance properties can be declared @IBInspectable}} {{1-16=}}
@GKInspectable var gkinspectable_global : Int // expected-error {{only instance properties can be declared @GKInspectable}} {{1-16=}}
func foo(x: @convention(block) Int) {} // expected-error {{@convention attribute only applies to function types}}
func foo(x: @convention(block) (Int) -> Int) {}
@_transparent
func zim() {}
@_transparent
func zung<T>(_: T) {}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to stored properties}} {{1-15=}}
var zippity : Int
func zoom(x: @_transparent () -> ()) { } // expected-error{{attribute can only be applied to declarations, not types}} {{1-1=@_transparent }} {{14-28=}}
protocol ProtoWithTransparent {
@_transparent// expected-error{{'@_transparent' attribute is not supported on declarations within protocols}} {{3-16=}}
func transInProto()
}
class TestTranspClass : ProtoWithTransparent {
@_transparent // expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}}
init () {}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{3-17=}}
deinit {}
@_transparent // expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}}
class func transStatic() {}
@_transparent// expected-error{{'@_transparent' attribute is not supported on declarations within classes}} {{3-16=}}
func transInProto() {}
}
struct TestTranspStruct : ProtoWithTransparent{
@_transparent
init () {}
@_transparent
init <T> (x : T) { }
@_transparent
static func transStatic() {}
@_transparent
func transInProto() {}
}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}}
struct CannotHaveTransparentStruct {
func m1() {}
}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}}
extension TestTranspClass {
func tr1() {}
}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}}
extension TestTranspStruct {
func tr1() {}
}
@_transparent // expected-error{{'@_transparent' attribute cannot be applied to this declaration}} {{1-15=}}
extension binary {
func tr1() {}
}
class transparentOnClassVar {
@_transparent var max: Int { return 0xFF }; // expected-error {{'@_transparent' attribute is not supported on declarations within classes}} {{3-17=}}
func blah () {
var _: Int = max
}
};
class transparentOnClassVar2 {
var max: Int {
@_transparent // expected-error {{'@_transparent' attribute is not supported on declarations within classes}} {{5-19=}}
get {
return 0xFF
}
}
func blah () {
var _: Int = max
}
};
@thin // expected-error {{attribute can only be applied to types, not declarations}}
func testThinDecl() -> () {}
protocol Class : class {}
protocol NonClass {}
@objc
class Ty0 : Class, NonClass {
init() { }
}
// Attributes that should be reported by parser as unknown
// See rdar://19533915
@__setterAccess struct S__accessibility {} // expected-error{{unknown attribute '__setterAccess'}}
@__raw_doc_comment struct S__raw_doc_comment {} // expected-error{{unknown attribute '__raw_doc_comment'}}
@__objc_bridged struct S__objc_bridged {} // expected-error{{unknown attribute '__objc_bridged'}}
weak
var weak0 : Ty0?
weak
var weak0x : Ty0?
weak unowned var weak1 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
weak weak var weak2 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
unowned var weak3 : Ty0
unowned var weak3a : Ty0
unowned(safe) var weak3b : Ty0
unowned(unsafe) var weak3c : Ty0
unowned unowned var weak4 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
unowned weak var weak5 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
weak
var weak6 : Int? // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
unowned
var weak7 : Int // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'Int'}}
weak
var weak8 : Class? = Ty0()
// expected-warning@-1 {{instance will be immediately deallocated because variable 'weak8' is 'weak'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'weak8' declared here}}
unowned var weak9 : Class = Ty0()
// expected-warning@-1 {{instance will be immediately deallocated because variable 'weak9' is 'unowned'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'weak9' declared here}}
weak
var weak10 : NonClass? = Ty0() // expected-error {{'weak' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak11 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak12 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak13 : NonClass = Ty0() // expected-error {{'unowned' must not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
weak
var weak14 : Ty0 // expected-error {{'weak' variable should have optional type 'Ty0?'}}
weak
var weak15 : Class // expected-error {{'weak' variable should have optional type 'Class?'}}
weak var weak16 : Class!
@weak var weak17 : Class? // expected-error {{'weak' is a declaration modifier, not an attribute}} {{1-2=}}
@_exported var exportVar: Int // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
@_exported func exportFunc() {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
@_exported struct ExportStruct {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
// Function result type attributes.
var func_result_type_attr : () -> @xyz Int // expected-error {{unknown attribute 'xyz'}}
func func_result_attr() -> @xyz Int { // expected-error {{unknown attribute 'xyz'}}
return 4
}
func func_with_unknown_attr1(@unknown(*) x: Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr2(x: @unknown(_) Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr3(x: @unknown(Int) -> Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr4(x: @unknown(Int) throws -> Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr5(x: @unknown (x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr6(x: @unknown(x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}} expected-error {{expected parameter type following ':'}}
func func_with_unknown_attr7(x: @unknown (Int) () -> Int) {} // expected-error {{unknown attribute 'unknown'}} expected-error {{expected ',' separator}} {{47-47=,}} expected-error {{unnamed parameters must be written with the empty name '_'}} {{48-48=_: }}
func func_type_attribute_with_space(x: @convention (c) () -> Int) {} // OK. Known attributes can have space before its paren.
// @thin and @pseudogeneric are not supported except in SIL.
var thinFunc : @thin () -> () // expected-error {{unknown attribute 'thin'}}
var pseudoGenericFunc : @pseudogeneric () -> () // expected-error {{unknown attribute 'pseudogeneric'}}
@inline(never) func nolineFunc() {}
@inline(never) var noinlineVar : Int { return 0 }
@inline(never) class FooClass { // expected-error {{'@inline(never)' attribute cannot be applied to this declaration}} {{1-16=}}
}
@inline(__always) func AlwaysInlineFunc() {}
@inline(__always) var alwaysInlineVar : Int { return 0 }
@inline(__always) class FooClass2 { // expected-error {{'@inline(__always)' attribute cannot be applied to this declaration}} {{1-19=}}
}
@_optimize(speed) func OspeedFunc() {}
@_optimize(speed) var OpeedVar : Int // expected-error {{'@_optimize(speed)' attribute cannot be applied to stored properties}} {{1-19=}}
@_optimize(speed) class OspeedClass { // expected-error {{'@_optimize(speed)' attribute cannot be applied to this declaration}} {{1-19=}}
}
class A {
@inline(never) init(a : Int) {}
var b : Int {
@inline(never) get {
return 42
}
@inline(never) set {
}
}
}
class B {
@inline(__always) init(a : Int) {}
var b : Int {
@inline(__always) get {
return 42
}
@inline(__always) set {
}
}
}
class C {
@_optimize(speed) init(a : Int) {}
var b : Int {
@_optimize(none) get {
return 42
}
@_optimize(size) set {
}
}
@_optimize(size) var c : Int // expected-error {{'@_optimize(size)' attribute cannot be applied to stored properties}}
}
class HasStorage {
@_hasStorage var x : Int = 42 // ok, _hasStorage is allowed here
}
@_show_in_interface protocol _underscored {}
@_show_in_interface class _notapplicable {} // expected-error {{may only be used on 'protocol' declarations}}
// Error recovery after one invalid attribute
@_invalid_attribute_ // expected-error {{unknown attribute '_invalid_attribute_'}}
@inline(__always)
public func sillyFunction() {}
// rdar://problem/45732251: unowned/unowned(unsafe) optional lets are permitted
func unownedOptionals(x: C) {
unowned let y: C? = x
unowned(unsafe) let y2: C? = x
_ = y
_ = y2
}
// @_nonEphemeral attribute
struct S1<T> {
func foo(@_nonEphemeral _ x: String) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}}
func bar(@_nonEphemeral _ x: T) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}}
func baz<U>(@_nonEphemeral _ x: U) {} // expected-error {{@_nonEphemeral attribute only applies to pointer types}}
func qux(@_nonEphemeral _ x: UnsafeMutableRawPointer) {}
func quux(@_nonEphemeral _ x: UnsafeMutablePointer<Int>?) {}
}
@_nonEphemeral struct S2 {} // expected-error {{@_nonEphemeral may only be used on 'parameter' declarations}}
protocol P {}
extension P {
// Allow @_nonEphemeral on the protocol Self type, as the protocol could be adopted by a pointer type.
func foo(@_nonEphemeral _ x: Self) {}
func bar(@_nonEphemeral _ x: Self?) {}
}
enum E1 {
case str(@_nonEphemeral _: String) // expected-error {{expected parameter name followed by ':'}}
case ptr(@_nonEphemeral _: UnsafeMutableRawPointer) // expected-error {{expected parameter name followed by ':'}}
func foo() -> @_nonEphemeral UnsafeMutableRawPointer? { return nil } // expected-error {{attribute can only be applied to declarations, not types}}
}
|
apache-2.0
|
e16dba5392504bbab46ff458d2c4eeb5
| 39.967949 | 256 | 0.695431 | 3.94628 | false | false | false | false |
yujinjcho/movie_recommendations
|
ios_ui/Pods/Nimble/Sources/Nimble/Matchers/AsyncMatcherWrapper.swift
|
69
|
11154
|
import Foundation
/// If you are running on a slower machine, it could be useful to increase the default timeout value
/// or slow down poll interval. Default timeout interval is 1, and poll interval is 0.01.
public struct AsyncDefaults {
public static var Timeout: TimeInterval = 1
public static var PollInterval: TimeInterval = 0.01
}
private func async<T>(style: ExpectationStyle, predicate: Predicate<T>, timeout: TimeInterval, poll: TimeInterval, fnName: String) -> Predicate<T> {
return Predicate { actualExpression in
let uncachedExpression = actualExpression.withoutCaching()
let fnName = "expect(...).\(fnName)(...)"
var lastPredicateResult: PredicateResult?
let result = pollBlock(
pollInterval: poll,
timeoutInterval: timeout,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: fnName) {
lastPredicateResult = try predicate.satisfies(uncachedExpression)
return lastPredicateResult!.toBoolean(expectation: style)
}
switch result {
case .completed: return lastPredicateResult!
case .timedOut: return PredicateResult(status: .fail, message: lastPredicateResult!.message)
case let .errorThrown(error):
return PredicateResult(status: .fail, message: .fail("unexpected error thrown: <\(error)>"))
case let .raisedException(exception):
return PredicateResult(status: .fail, message: .fail("unexpected exception raised: \(exception)"))
case .blockedRunLoop:
// swiftlint:disable:next line_length
return PredicateResult(status: .fail, message: lastPredicateResult!.message.appended(message: " (timed out, but main thread was unresponsive)."))
case .incomplete:
internalError("Reached .incomplete state for toEventually(...).")
}
}
}
// Deprecated
internal struct AsyncMatcherWrapper<T, U>: Matcher
where U: Matcher, U.ValueType == T {
let fullMatcher: U
let timeoutInterval: TimeInterval
let pollInterval: TimeInterval
init(fullMatcher: U, timeoutInterval: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval) {
self.fullMatcher = fullMatcher
self.timeoutInterval = timeoutInterval
self.pollInterval = pollInterval
}
func matches(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let fnName = "expect(...).toEventually(...)"
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: fnName) {
try self.fullMatcher.matches(uncachedExpression, failureMessage: failureMessage)
}
switch result {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.stringValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.stringValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventually(...).")
}
}
func doesNotMatch(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: "expect(...).toEventuallyNot(...)") {
try self.fullMatcher.doesNotMatch(uncachedExpression, failureMessage: failureMessage)
}
switch result {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.stringValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.stringValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventuallyNot(...).")
}
}
}
private let toEventuallyRequiresClosureError = FailureMessage(
// swiftlint:disable:next line_length
stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function"
)
extension Expectation {
/// Tests the actual value using a matcher to match by checking continuously
/// at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventually(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) {
nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue)
let (pass, msg) = execute(
expression,
.toMatch,
async(style: .toMatch, predicate: predicate, timeout: timeout, poll: pollInterval, fnName: "toEventually"),
to: "to eventually",
description: description,
captureExceptions: false
)
verify(pass, msg)
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventuallyNot(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) {
nimblePrecondition(expression.isClosure, "NimbleInternalError", toEventuallyRequiresClosureError.stringValue)
let (pass, msg) = execute(
expression,
.toNotMatch,
async(
style: .toNotMatch,
predicate: predicate,
timeout: timeout,
poll: pollInterval,
fnName: "toEventuallyNot"
),
to: "to eventually not",
description: description,
captureExceptions: false
)
verify(pass, msg)
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// Alias of toEventuallyNot()
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toNotEventually(_ predicate: Predicate<T>, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil) {
return toEventuallyNot(predicate, timeout: timeout, pollInterval: pollInterval, description: description)
}
}
// Deprecated
extension Expectation {
/// Tests the actual value using a matcher to match by checking continuously
/// at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T {
if expression.isClosure {
let (pass, msg) = expressionMatches(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
to: "to eventually",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventuallyNot<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T {
if expression.isClosure {
let (pass, msg) = expressionDoesNotMatch(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
toNot: "to eventually not",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// Alias of toEventuallyNot()
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toNotEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T {
return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description)
}
}
|
mit
|
216c4401d8d342cb123f6c4380955c14
| 46.262712 | 209 | 0.656715 | 5.607843 | false | false | false | false |
rene-dohan/CS-IOS
|
Renetik/Renetik/Classes/Core/Protocols/CSAny.swift
|
1
|
3375
|
//
// Created by Rene Dohan on 12/16/19.
//
import Foundation
public protocol CSAnyProtocol {
}
public extension CSAnyProtocol {
public static func cast(_ object: Any) -> Self { object as! Self }
public var notNil: Bool { true }
public var isSet: Bool { true }
public var isNil: Bool { false }
@discardableResult
public func also(_ function: (Self) -> Void) -> Self {
function(self)
return self
}
@discardableResult
public func then(_ function: (Self) -> Void) {
function(self)
}
@discardableResult
public func invoke(_ function: Func) -> Self {
function()
return self
}
@discardableResult
public func invoke(from: Int, until: Int, function: (Int) -> Void) -> Self {
from.until(until, function)
return self
}
@discardableResult
public func run(_ function: Func) -> Void {
function()
}
// let in Kotlin
public func get<ReturnType>(_ function: (Self) -> ReturnType) -> ReturnType { function(self) }
public var asString: String {
(self as? CSNameProtocol)?.name ??
(self as? CustomStringConvertible)?.description ?? "\(self)"
}
public var asInt: Int {
let value = asString
return value.isEmpty ? 0 : value.intValue
}
public var asDouble: Double {
let value = asString
return value.isEmpty ? 0 : value.doubleValue
}
public func cast<T>() -> T { self as! T }
public func castOrNil<T>() -> T? { self as? T }
func isTrue(predicate: (Self) -> Bool) -> Bool { predicate(self) }
func isFalse(predicate: (Self) -> Bool) -> Bool { !predicate(self) }
}
public extension CSAnyProtocol where Self: AnyObject {
var hashString: String { String(UInt(bitPattern: ObjectIdentifier(self))) }
}
public extension CSAnyProtocol where Self: NSObject {
public func equals(any objects: NSObject...) -> Bool {
if objects.contains(self) { return true }; return false
}
}
public extension CSAnyProtocol where Self: Equatable {
public func equals(any objects: Self...) -> Bool { objects.contains { $0 == self } }
public func isAny(_ objects: Self...) -> Bool { objects.contains { $0 == self } }
public func equals(_ object: Self) -> Bool { object == self }
}
public extension CSAnyProtocol where Self: Equatable, Self: AnyObject {
public static func ==(lhs: Self, rhs: Self) -> Bool { lhs === rhs }
}
public extension CSAnyProtocol where Self: CustomStringConvertible {
public var description: String { "\(type(of: self))" }
}
public extension CSAnyProtocol where Self: CustomStringConvertible, Self: CSNameProtocol {
public var description: String { name }
}
extension IndexPath: CSAnyProtocol {}
extension NSObject: CSAnyProtocol {}
extension Bool: CSAnyProtocol {}
extension String: CSAnyProtocol {}
extension Int: CSAnyProtocol {}
extension Float: CSAnyProtocol {}
extension Double: CSAnyProtocol {}
extension CGFloat: CSAnyProtocol {}
extension Array: CSAnyProtocol {}
extension Dictionary: CSAnyProtocol {}
extension Date: CSAnyProtocol {}
//public extension Optional where Wrapped: CSAnyProtocol {
// public var asString: String {
// (self as? CSNameProtocol)?.name ??
// (self as? CustomStringConvertible)?.description ?? "\(self)"
// }
//}
|
mit
|
ec25d2bf43f2b6d69e386828b05da4a3
| 24.383459 | 98 | 0.646222 | 4.166667 | false | false | false | false |
mozilla-mobile/firefox-ios
|
Shared/Extensions/HexExtensions.swift
|
2
|
2494
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
extension String {
public var hexDecodedData: Data {
// Convert to a CString and make sure it has an even number of characters (terminating 0 is included, so we
// check for uneven!)
guard let cString = self.cString(using: .ascii), (cString.count % 2) == 1 else {
return Data()
}
var result = Data(capacity: (cString.count - 1) / 2)
for i in stride(from: 0, to: (cString.count - 1), by: 2) {
guard let l = hexCharToByte(cString[i]), let r = hexCharToByte(cString[i+1]) else {
return Data()
}
var value: UInt8 = (l << 4) | r
result.append(&value, count: MemoryLayout.size(ofValue: value))
}
return result
}
private func hexCharToByte(_ c: CChar) -> UInt8? {
if c >= 48 && c <= 57 { // 0 - 9
return UInt8(c - 48)
}
if c >= 97 && c <= 102 { // a - f
return UInt8(10) + UInt8(c - 97)
}
if c >= 65 && c <= 70 { // A - F
return UInt8(10) + UInt8(c - 65)
}
return nil
}
}
private let HexDigits: [String] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
extension Data {
public var hexEncodedString: String {
var result = String()
result.reserveCapacity(count * 2)
withUnsafeBytes { (p: UnsafeRawBufferPointer) in
for i in 0..<count {
result.append(HexDigits[Int((p[i] & 0xf0) >> 4)])
result.append(HexDigits[Int(p[i] & 0x0f)])
}
}
return String(result)
}
public static func randomOfLength(_ length: UInt) -> Data? {
let length = Int(length)
var data = Data(count: length)
var result: Int32 = 0
data.withUnsafeMutableBytes { (p: UnsafeMutableRawBufferPointer) in
guard let p = p.bindMemory(to: UInt8.self).baseAddress else {
result = -1
return
}
result = SecRandomCopyBytes(kSecRandomDefault, length, p)
}
return result == 0 ? data : nil
}
}
extension Data {
public var base64EncodedString: String {
return self.base64EncodedString(options: [])
}
}
|
mpl-2.0
|
0c219abc63fffd71971202167e1a03b4
| 32.253333 | 115 | 0.536488 | 3.836923 | false | false | false | false |
XSega/Words
|
Words/WordsAPIDataManager.swift
|
1
|
1526
|
//
// WordsAPIDataManager.swift
// Words
//
// Created by Sergey Ilyushin on 10/08/2017.
// Copyright © 2017 Sergey Ilyushin. All rights reserved.
//
import Foundation
protocol IWordsAPIDataManager: class {
func requestUserWords(email: String, token: String, completionHandler: (([UserWord]) -> Void)?, errorHandler: ((Error) -> Void)?)
}
class WordsAPIDataManager: IWordsAPIDataManager {
// MARK:- Public vars
var api: IWordsAPI!
init(api: IWordsAPI) {
self.api = api
}
func requestUserWords(email: String, token: String, completionHandler: (([UserWord]) -> Void)?, errorHandler: ((Error) -> Void)?) {
let succesHandler = {[unowned self](apiWords: [APIUserWord]) in
let words = self.userWordFromAPI(apiWords: apiWords)
completionHandler?(words)
}
let wrongHandler = {(error: Error) in
print(error.localizedDescription)
errorHandler?(error)
}
api.requestUserWords(email: email, token: token, completionHandler: succesHandler, errorHandler: wrongHandler)
}
// MARK:- Load meaning from Skyeng user words
fileprivate func userWordFromAPI(apiWords: [APIUserWord]) -> [UserWord] {
var words = [UserWord]()
for apiWord in apiWords {
let progress = (1 - apiWord.progress) * 10
let word = UserWord(identifier: apiWord.identifier, progress: Int(progress))
words.append(word)
}
return words
}
}
|
mit
|
d1bcebd3e32d922f02d4bd7ff6ab80cb
| 31.446809 | 135 | 0.630164 | 4.247911 | false | false | false | false |
wokalski/Diff.swift
|
Sources/LinkedList.swift
|
3
|
2058
|
class LinkedList<T> {
let next: LinkedList?
let value: T
init(next: LinkedList?, value: T) {
self.next = next
self.value = value
}
init?(array: [T]) {
let reversed = array.reversed()
guard let first = array.first else {
return nil
}
var tailLinkedList: LinkedList?
for i in 0 ..< reversed.count - 1 {
tailLinkedList = LinkedList(next: tailLinkedList, value: reversed.itemOnStartIndex(advancedBy: i))
}
self.next = tailLinkedList
self.value = first
}
func array() -> Array<T> {
if let next = next {
return [value] + next.array()
}
return [value]
}
}
class DoublyLinkedList<T> {
let next: DoublyLinkedList?
private(set) weak var previous: DoublyLinkedList?
var head: DoublyLinkedList {
guard let previous = previous else {
return self
}
return previous.head
}
var value: T
init(next: DoublyLinkedList?, value: T) {
self.value = value
self.next = next
self.next?.previous = self
}
init?(array: [T]) {
let reversed = array.reversed()
guard let first = array.first else {
return nil
}
var tailDoublyLinkedList: DoublyLinkedList?
for i in 0 ..< reversed.count - 1 {
let nextTail = DoublyLinkedList(next: tailDoublyLinkedList, value: reversed.itemOnStartIndex(advancedBy: i))
tailDoublyLinkedList?.previous = nextTail
tailDoublyLinkedList = nextTail
}
self.value = first
self.next = tailDoublyLinkedList
self.next?.previous = self
}
convenience init?(linkedList: LinkedList<T>?) {
guard let linkedList = linkedList else {
return nil
}
self.init(array: linkedList.array())
}
func array() -> Array<T> {
if let next = next {
return [value] + next.array()
}
return [value]
}
}
|
mit
|
d6f1247fc5644a27d4571a404ffb84d2
| 23.211765 | 120 | 0.557823 | 4.38806 | false | false | false | false |
aschwaighofer/swift
|
stdlib/public/core/DiscontiguousSlice.swift
|
2
|
6786
|
//===--- DiscontiguousSlice.swift -----------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection wrapper that provides access to the elements of a collection,
/// indexed by a set of indices.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
@frozen
public struct DiscontiguousSlice<Base: Collection> {
/// The collection that the indexed collection wraps.
public var base: Base
/// The set of subranges that are available through this discontiguous slice.
public var subranges: RangeSet<Base.Index>
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension DiscontiguousSlice {
/// A position in an `DiscontiguousSlice`.
@frozen
public struct Index: Comparable {
/// The index of the range that contains `base`.
internal var _rangeOffset: Int
/// The position of this index in the base collection.
public var base: Base.Index
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.base < rhs.base
}
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension DiscontiguousSlice.Index: Hashable where Base.Index: Hashable {}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension DiscontiguousSlice: Collection {
public typealias SubSequence = Self
public var startIndex: Index {
subranges.isEmpty
? endIndex
: Index(_rangeOffset: 0, base: subranges._ranges[0].lowerBound)
}
public var endIndex: Index {
Index(_rangeOffset: subranges._ranges.endIndex, base: base.endIndex)
}
public func index(after i: Index) -> Index {
let nextIndex = base.index(after: i.base)
if subranges._ranges[i._rangeOffset].contains(nextIndex) {
return Index(_rangeOffset: i._rangeOffset, base: nextIndex)
}
let nextOffset = i._rangeOffset + 1
if nextOffset < subranges._ranges.endIndex {
return Index(
_rangeOffset: nextOffset,
base: subranges._ranges[nextOffset].lowerBound)
} else {
return endIndex
}
}
public subscript(i: Index) -> Base.Element {
base[i.base]
}
public subscript(bounds: Range<Index>) -> DiscontiguousSlice<Base> {
let baseBounds = bounds.lowerBound.base ..< bounds.upperBound.base
let subset = subranges.intersection(RangeSet(baseBounds))
return DiscontiguousSlice<Base>(base: base, subranges: subset)
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension DiscontiguousSlice {
public var count: Int {
var c = 0
for range in subranges._ranges {
c += base.distance(from: range.lowerBound, to: range.upperBound)
}
return c
}
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
var result: ContiguousArray<Element> = []
for range in subranges._ranges {
result.append(contentsOf: base[range])
}
return result
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension DiscontiguousSlice: BidirectionalCollection
where Base: BidirectionalCollection
{
public func index(before i: Index) -> Index {
_precondition(i != startIndex, "Can't move index before startIndex")
if i == endIndex || i.base == subranges._ranges[i._rangeOffset].lowerBound {
let offset = i._rangeOffset - 1
return Index(
_rangeOffset: offset,
base: base.index(before: subranges._ranges[offset].upperBound))
}
return Index(
_rangeOffset: i._rangeOffset,
base: base.index(before: i.base))
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension DiscontiguousSlice: MutableCollection where Base: MutableCollection {
public subscript(i: Index) -> Base.Element {
get {
base[i.base]
}
set {
base[i.base] = newValue
}
}
}
// MARK: Subscripts
extension Collection {
/// Accesses a view of this collection with the elements at the given
/// indices.
///
/// - Parameter subranges: The indices of the elements to retrieve from this
/// collection.
/// - Returns: A collection of the elements at the positions in `subranges`.
///
/// - Complexity: O(1)
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public subscript(subranges: RangeSet<Index>) -> DiscontiguousSlice<Self> {
DiscontiguousSlice(base: self, subranges: subranges)
}
}
extension MutableCollection {
/// Accesses a mutable view of this collection with the elements at the
/// given indices.
///
/// - Parameter subranges: The ranges of the elements to retrieve from this
/// collection.
/// - Returns: A collection of the elements at the positions in `subranges`.
///
/// - Complexity: O(1) to access the elements, O(*m*) to mutate the
/// elements at the positions in `subranges`, where *m* is the number of
/// elements indicated by `subranges`.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public subscript(subranges: RangeSet<Index>) -> DiscontiguousSlice<Self> {
get {
DiscontiguousSlice(base: self, subranges: subranges)
}
set {
for i in newValue.indices {
self[i.base] = newValue[i]
}
}
}
}
extension Collection {
/// Returns a collection of the elements in this collection that are not
/// represented by the given range set.
///
/// For example, this code sample finds the indices of all the vowel
/// characters in the string, and then retrieves a collection that omits
/// those characters.
///
/// let str = "The rain in Spain stays mainly in the plain."
/// let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
/// let vowelIndices = str.subranges(where: { vowels.contains($0) })
///
/// let disemvoweled = str.removingSubranges(vowelIndices)
/// print(String(disemvoweled))
/// // Prints "Th rn n Spn stys mnly n th pln."
///
/// - Parameter subranges: A range set representing the indices of the
/// elements to remove.
/// - Returns: A collection of the elements that are not in `subranges`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
public func removingSubranges(
_ subranges: RangeSet<Index>
) -> DiscontiguousSlice<Self> {
let inversion = subranges._inverted(within: self)
return self[inversion]
}
}
|
apache-2.0
|
57bca6acf9412a855c3e350ed2da4ee5
| 31.941748 | 80 | 0.662688 | 4.254545 | false | false | false | false |
emlai/LLVM.swift
|
Sources/Instruction.swift
|
1
|
4020
|
//
// Created by Ben Cochran on 11/13/15.
// Copyright © 2015 Ben Cochran. All rights reserved.
//
import LLVM_C
public protocol InstructionType : UserType {
var parent: BasicBlock { get }
var nextInstruction: InstructionType? { get }
var previousInstruction: InstructionType? { get }
var opCode: LLVMOpcode { get }
func eraseFromParent()
}
public extension InstructionType {
public var parent: BasicBlock {
return BasicBlock(ref: LLVMGetInstructionParent(ref))
}
public var nextInstruction: InstructionType? {
return AnyInstruction(maybeRef: LLVMGetNextInstruction(ref))
}
public var previousInstruction: InstructionType? {
return AnyInstruction(maybeRef: LLVMGetPreviousInstruction(ref))
}
public var opCode: LLVMOpcode {
return LLVMGetInstructionOpcode(ref)
}
public func eraseFromParent() {
LLVMInstructionEraseFromParent(ref)
}
}
public struct AnyInstruction : InstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public protocol TerminatorInstructionType : InstructionType { }
public struct AnyTerminatorInstruction : TerminatorInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public struct ReturnInstruction : TerminatorInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public struct BranchInstruction : TerminatorInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public struct SwitchInstruction : TerminatorInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
func addCase(_ on: ConstantType, destination: BasicBlock) {
LLVMAddCase(ref, on.ref, destination.ref)
}
}
public struct IndirectBranchInstruction : TerminatorInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
public func addDestination(_ destination: BasicBlock) {
LLVMAddDestination(ref, destination.ref)
}
}
public struct ResumeInstruction : TerminatorInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public struct InvokeInstruction : TerminatorInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public struct UnreachableInstruction : TerminatorInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public struct CallInstruction : InstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public struct StoreInstruction : InstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public protocol UnaryInstructionType : InstructionType { }
public struct AllocaInstruction : UnaryInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public struct LoadInstruction : UnaryInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public struct VAArgInstruction : UnaryInstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
}
public struct PHINode : InstructionType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
public func addIncoming(_ value: ValueType, from basicBlock: BasicBlock) {
var valueRef = Optional.some(value.ref)
var basicBlockRef = Optional.some(basicBlock.ref)
LLVMAddIncoming(ref, &valueRef, &basicBlockRef, 1)
}
}
|
mit
|
b353887e773ca892d3ccaed9c2edbe05
| 23.065868 | 78 | 0.681015 | 4.226078 | false | false | false | false |
JGiola/swift
|
benchmark/single-source/LuhnAlgoLazy.swift
|
7
|
6406
|
// LuhnAlgoLazy benchmark
//
// Description: Performs a Luhn checksum lazily
// Source: https://gist.github.com/airspeedswift/e584239d7658b317f59a
import TestsUtils
public let benchmarks = [
BenchmarkInfo(
name: "LuhnAlgoLazy",
runFunction: run_LuhnAlgoLazy,
tags: [.algorithm]
),
]
@inline(never)
public func run_LuhnAlgoLazy(_ n: Int) {
let resultRef = true
var result = false
for _ in 1...100*n {
result = lazychecksum(ccnum)
if result != resultRef {
break
}
}
check(result == resultRef)
}
// Another version of the Luhn algorithm, similar to the one found here:
// https://gist.github.com/airspeedswift/b349c256e90da746b852
//
// This time, trying to keep two versions, one eager one lazy,
// as similar as possible. Only adding "lazy" to the start of
// the expression to switch between the two.
//
// Much of the same code as the previous version at the top,
// Skip down to line 110 for the different par
// mapSome is my Swift version of Haskell's mapMaybe, which
// is a map that takes a transform function that returns an
// optional, and returns a collection of only those values
// that weren't nil
// first we need a lazy view that holds the original
// sequence and the transform function
struct MapSomeSequenceView<Base: Sequence, T> {
fileprivate let _base: Base
fileprivate let _transform: (Base.Element) -> T?
}
// extend it to implement Sequence
extension MapSomeSequenceView: Sequence {
typealias Iterator = AnyIterator<T>
func makeIterator() -> Iterator {
var g = _base.makeIterator()
// AnyIterator is a helper that takes a
// closure and calls it to generate each
// element
return AnyIterator {
while let element = g.next() {
if let some = self._transform(element) {
return some
}
}
return nil
}
}
}
// now extend a lazy collection to return that view
// from a call to mapSome. In practice, when doing this,
// you should do it for all the lazy wrappers
// (i.e. random-access, forward and sequence)
extension LazyCollectionProtocol {
// I might be missing a trick with this super-ugly return type, is there a
// better way?
func mapSome<U>(
_ transform: @escaping (Elements.Element) -> U?
) -> LazySequence<MapSomeSequenceView<Elements, U>> {
return MapSomeSequenceView(_base: elements, _transform: transform).lazy
}
}
// curried function - call with 1 argument to get a function
// that tells you if i is a multiple of a given number
// e.g.
// let isEven = isMultipleOf(2)
// isEven(4) // true
func isMultipleOf<T: FixedWidthInteger>(_ of: T)->(T)->Bool {
return { $0 % of == 0 }
}
// extend LazySequence to map only every nth element, with all
// other elements untransformed.
extension LazySequenceProtocol {
func mapEveryN(
_ n: Int,
_ transform: @escaping (Element) -> Element
) -> LazyMapSequence<EnumeratedSequence<Self>, Element> {
let isNth = isMultipleOf(n)
func transform2(
_ pair: EnumeratedSequence<Self>.Element
) -> Element {
return isNth(pair.0 + 1) ? transform(pair.1) : pair.1
}
return self.enumerated().lazy.map(transform2)
}
}
infix operator |> : PipeRightPrecedence
precedencegroup PipeRightPrecedence {
associativity: left
}
func |><T,U>(t: T, f: (T)->U) -> U {
return f(t)
}
infix operator • : DotPrecedence
precedencegroup DotPrecedence {
associativity: left
}
func • <T, U, V> (g: @escaping (U) -> V, f: @escaping (T) -> U) -> (T) -> V {
return { x in g(f(x)) }
}
// function to free a method from the shackles
// of it's owner
func freeMemberFunc<T,U>(_ f: @escaping (T)->()->U)->(T)->U {
return { (t: T)->U in f(t)() }
}
extension String {
func toInt() -> Int? { return Int(self) }
}
// stringToInt can now be pipelined or composed
let stringToInt = freeMemberFunc(String.toInt)
// if only Character also had a toInt method
let charToString = { (c: Character) -> String in String(c) }
let charToInt = stringToInt • charToString
func sum<S: Sequence>(_ nums: S)->S.Element where S.Element: FixedWidthInteger {
return nums.reduce(0,+)
}
func reverse<C: LazyCollectionProtocol>(
_ source: C
) -> LazyCollection<ReversedCollection<C.Elements>> {
return source.elements.reversed().lazy
}
func map<S: LazySequenceProtocol, U>(
_ source: S, _ transform: @escaping (S.Elements.Element)->U
) -> LazyMapSequence<S.Elements,U> {
return source.map(transform)
}
func mapSome<C: LazyCollectionProtocol, U>(
_ source: C,
_ transform: @escaping (C.Elements.Element)->U?
) -> LazySequence<MapSomeSequenceView<C.Elements, U>> {
return source.mapSome(transform)
}
func mapEveryN<S: LazySequenceProtocol>(
_ source: S, _ n: Int,
_ transform: @escaping (S.Element)->S.Element
) -> LazyMapSequence<EnumeratedSequence<S>, S.Element> {
return source.mapEveryN(n, transform)
}
// Non-lazy version of mapSome:
func mapSome<S: Sequence, C: RangeReplaceableCollection>(
_ source: S,
_ transform: @escaping (S.Element)->C.Element?
) -> C {
var result = C()
for x in source {
if let y = transform(x) {
result.append(y)
}
}
return result
}
// Specialized default version of mapSome that returns an array, to avoid
// forcing the user having to specify:
func mapSome<S: Sequence,U>(
_ source: S,
_ transform: @escaping (S.Element
)->U?)->[U] {
// just calls the more generalized version
return mapSome(source, transform)
}
// Non-lazy version of mapEveryN:
func mapEveryN<S: Sequence>(
_ source: S, _ n: Int,
_ transform: @escaping (S.Element) -> S.Element
) -> [S.Element] {
let isNth = isMultipleOf(n)
return source.enumerated().map {
(pair: (index: Int, elem: S.Element)) in
isNth(pair.index+1)
? transform(pair.elem)
: pair.elem
}
}
let double = { $0*2 }
let combineDoubleDigits = {
(10...18).contains($0) ? $0-9 : $0
}
// first, the lazy version of checksum calculation
let lazychecksum = { (ccnum: String) -> Bool in
ccnum.lazy
|> reverse
|> { mapSome($0, charToInt) }
|> { mapEveryN($0, 2, double) }
|> { map($0, combineDoubleDigits) }
|> sum
|> isMultipleOf(10)
}
let ccnum = "4012 8888 8888 1881"
|
apache-2.0
|
e442a8f1e7c6b018da76bec8b90bda2a
| 26.467811 | 80 | 0.648594 | 3.613778 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/MimeTypes.swift
|
1
|
2967
|
//
// MimeTypes.swift
// Telegram-Mac
//
// Created by keepcoder on 19/10/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
import TGUIKit
fileprivate var mimestore:[String:String] = [:]
fileprivate var extensionstore:[String:String] = [:]
func initializeMimeStore() {
assertOnMainThread()
if mimestore.isEmpty && extensionstore.isEmpty {
let path = Bundle.main.path(forResource: "mime-types", ofType: "txt")
let content = try? String(contentsOfFile: path ?? "")
let mimes = content?.components(separatedBy: CharacterSet.newlines)
if let mimes = mimes {
for mime in mimes {
let single = mime.components(separatedBy: ":")
if single.count == 2 {
extensionstore[single[0]] = single[1]
mimestore[single[1]] = single[0]
}
}
}
}
}
func resourceType(mimeType:String? = nil, orExt:String? = nil) -> Signal<String?, NoError> {
assert(mimeType != nil || orExt != nil)
assert((mimeType != nil && orExt == nil) || (mimeType == nil && orExt != nil))
return Signal<String?, NoError> { (subscriber) -> Disposable in
initializeMimeStore()
var result:String?
if let mimeType = mimeType {
result = mimestore[mimeType]
} else if let orExt = orExt {
result = extensionstore[orExt.lowercased()]
}
subscriber.putNext(result)
subscriber.putCompletion()
return EmptyDisposable
} |> runOn(Queue.mainQueue())
}
func MIMEType(_ path: String, isExt: Bool = false) -> String {
let fileExtension = isExt ? path.lowercased() : path.nsstring.pathExtension.lowercased()
if !fileExtension.isEmpty {
if let ext = extensionstore[fileExtension] {
return ext
} else {
if !fileExtension.isEmpty {
let UTIRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension as CFString, nil)
let UTI = UTIRef?.takeRetainedValue()
if let UTI = UTI {
let MIMETypeRef = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType)
if MIMETypeRef != nil
{
let MIMEType = MIMETypeRef?.takeRetainedValue()
return MIMEType as String? ?? "application/octet-stream"
}
}
}
return "application/octet-stream"
}
} else {
return !isExt && path.isDirectory ? "application/zip" : "application/octet-stream"
}
}
func fileExt(_ mimeType: String) -> String? {
if let ext = mimestore[mimeType] {
return ext
}
return nil
}
let voiceMime = "audio/ogg"
let musicMime = "audio/mp3"
|
gpl-2.0
|
c3b1dfbe82431852db3aaf94b8b7fa54
| 29.895833 | 128 | 0.566082 | 4.72293 | false | false | false | false |
ninjz/async-swift
|
Async.swift
|
1
|
2084
|
//
// Async.swift
// Async
//
// Created by Fabio Poloni on 01.10.14.
//
//
import Foundation
struct Async {
static func each<ArrayType, ErrorType>(arr: [ArrayType], iterator: (item: ArrayType, asyncCallback: (error: ErrorType?) -> Void) -> Void, finished: (error: ErrorType?) -> Void) {
var isFinishedCalled = false
var finishedOnce = { (error: ErrorType?) -> Void in
if !isFinishedCalled {
isFinishedCalled = true
finished(error: error)
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
var done = 0
for item in arr {
iterator(item: item) { (error) -> Void in
if error != nil {
finishedOnce(error)
} else if (++done >= arr.count) {
finishedOnce(nil)
}
}
}
}
}
static func eachSeries<ArrayType, ErrorType>(var arr: [ArrayType], iterator: (item: ArrayType, asyncCallback: (error: ErrorType?) -> Void) -> Void, finished: (error: ErrorType?) -> Void) {
var isFinishedCalled = false
var finishedOnce = { (error: ErrorType?) -> Void in
if !isFinishedCalled {
isFinishedCalled = true
finished(error: error)
}
}
var next: (() -> Void)?
next = { () -> Void in
if arr.count > 0 {
let item = arr.removeAtIndex(0)
iterator(item: item) { (error) -> Void in
if error != nil {
finishedOnce(error)
} else {
next!()
}
}
} else {
finishedOnce(nil)
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
next!()
}
}
}
|
mit
|
ac715b126058dcd13479ccdb5c89991c
| 30.104478 | 192 | 0.455374 | 4.779817 | false | false | false | false |
catloafsoft/AudioKit
|
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Parametric Equalizer.xcplaygroundpage/Contents.swift
|
1
|
1140
|
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Parametric Equalizer
//: #### A parametric equalizer can be used to raise or lower specific frequencies or frequency bands. Live sound engineers often use parametric equalizers during a concert in order to keep feedback from occuring, as they allow much more precise control over the frequency spectrum than other types of equalizers. Acoustic engineers will also use them to tune a room. This node may be useful if you're building an app to do audio analysis.
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("mixloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
var parametricEQ = AKParametricEQ(player)
//: Set the parameters of the parametric equalizer here
parametricEQ.centerFrequency = 1000 // Hz
parametricEQ.q = 1 // Hz
parametricEQ.gain = 10 // dB
AudioKit.output = parametricEQ
AudioKit.start()
player.play()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
|
mit
|
d82903d789e3edd7d7993bfb2ae3d158
| 39.714286 | 439 | 0.75614 | 4.222222 | false | false | false | false |
dataich/TypetalkSwift
|
TypetalkSwift/Requests/PutBookmarks.swift
|
1
|
880
|
//
// PutBookmarks.swift
// TypetalkSwift
//
// Created by Taichiro Yoshida on 2017/10/15.
// Copyright © 2017 Nulab Inc. All rights reserved.
//
import Alamofire
// sourcery: AutoInit
public struct PutBookmarks: Request {
public let topicId: Int
public let postId: Int?
public typealias Response = PutBookmarksResponse
public var method: HTTPMethod {
return .put
}
public var path: String {
return "/bookmarks"
}
public var parameters: Parameters? {
var parameters: Parameters = [:]
parameters["topicId"] = self.topicId
parameters["postId"] = self.postId
return parameters
}
// sourcery:inline:auto:PutBookmarks.AutoInit
public init(topicId: Int, postId: Int?) {
self.topicId = topicId
self.postId = postId
}
// sourcery:end
}
public struct PutBookmarksResponse: Codable {
public let unread: Unread
}
|
mit
|
94d0f950362187d5474f2434cabcf9fd
| 19.928571 | 52 | 0.68942 | 4.03211 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureKYC/Sources/FeatureKYCUI/MobileNumber/KYCVerifyPhoneNumberPresenter.swift
|
1
|
3280
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Localization
import PhoneNumberKit
import PlatformKit
import RxSwift
import ToolKit
protocol KYCVerifyPhoneNumberView: AnyObject {
func showLoadingView(with text: String)
func startVerificationSuccess()
func showError(message: String)
func hideLoadingView()
}
protocol KYCConfirmPhoneNumberView: KYCVerifyPhoneNumberView {
func confirmCodeSuccess()
}
class KYCVerifyPhoneNumberPresenter {
private let interactor: KYCVerifyPhoneNumberInteractor
private weak var view: KYCVerifyPhoneNumberView?
private var disposable: Disposable?
private let subscriptionScheduler: SerialDispatchQueueScheduler
deinit {
disposable?.dispose()
}
init(
subscriptionScheduler: SerialDispatchQueueScheduler = MainScheduler.asyncInstance,
view: KYCVerifyPhoneNumberView,
interactor: KYCVerifyPhoneNumberInteractor = KYCVerifyPhoneNumberInteractor()
) {
self.subscriptionScheduler = subscriptionScheduler
self.view = view
self.interactor = interactor
}
// MARK: - Public
func startVerification(number: String) {
view?.showLoadingView(with: LocalizationConstants.loading)
disposable = interactor.startVerification(number: number)
.subscribe(on: subscriptionScheduler)
.observe(on: MainScheduler.instance)
.subscribe(onCompleted: { [unowned self] in
self.handleStartVerificationCodeSuccess()
}, onError: { [unowned self] error in
self.handleStartVerificationError(error)
})
}
func verifyNumber(with code: String) {
view?.showLoadingView(with: LocalizationConstants.loading)
disposable = interactor.verifyNumber(with: code)
.subscribe(on: subscriptionScheduler)
.observe(on: MainScheduler.instance)
.subscribe(onCompleted: { [unowned self] in
self.handleVerifyCodeSuccess()
}, onError: { [unowned self] error in
self.handleVerifyNumberError(error)
})
}
// MARK: - Private
private func handleVerifyCodeSuccess() {
view?.hideLoadingView()
if let confirmView = view as? KYCConfirmPhoneNumberView {
confirmView.confirmCodeSuccess()
}
}
private func handleStartVerificationCodeSuccess() {
view?.hideLoadingView()
view?.startVerificationSuccess()
}
private func handleStartVerificationError(_ error: Error) {
Logger.shared.error("Could not start mobile verification process. Error: \(error)")
view?.hideLoadingView()
if let phoneNumberError = error as? PhoneNumberError {
view?.showError(message: phoneNumberError.errorDescription ?? LocalizationConstants.KYC.invalidPhoneNumber)
} else {
view?.showError(message: LocalizationConstants.KYC.invalidPhoneNumber)
}
}
private func handleVerifyNumberError(_ error: Error) {
Logger.shared.error("Could not complete mobile verification. Error: \(error)")
view?.hideLoadingView()
view?.showError(message: LocalizationConstants.KYC.failedToConfirmNumber)
}
}
|
lgpl-3.0
|
430820006fc34a3ed5c068700f06e1b2
| 31.79 | 119 | 0.685575 | 5.280193 | false | false | false | false |
zhugejunwei/LeetCode
|
369. Plus One Linked List.swift
|
1
|
2153
|
import Darwin
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
// using an Array, 53 ms
func plusOne(head: ListNode?) -> ListNode? {
var node = head
var t = [node?.val]
while node?.next != nil {
node = node?.next
t.append(node?.val)
}
var i = t.count - 1
while i >= 0 {
if t[i] < 9 {
t[i]! += 1
break
}else {
t[i] = 0
}
i -= 1
}
if t[0] == 0 {
var res = Array(count: t.count + 1, repeatedValue: 0)
res[0] = 1
var n = ListNode(1)
let headNode = n
n.next = head
n = n.next!
n.val = 0
while n.next != nil {
n = n.next!
n.val = 0
}
return headNode
}else {
var n = head
var k = 0
n?.val = t[k]!
while n?.next != nil {
k += 1
n = n?.next
n?.val = t[k]!
}
}
return head
}
// recursion, 44 ms
func plusOne(head: ListNode?) -> ListNode? {
var head = head
if helper(head) == 1 {
let tmp = head
let preHead = ListNode(1)
preHead.next = tmp
head = preHead
}
return head
}
func helper(head: ListNode?) -> Int {
let cur = head
if cur?.next == nil {
cur?.val += 1
}else {
cur?.val += helper(head?.next)
}
if cur!.val >= 10 {
cur!.val -= 10
return 1
}
return 0
}
// last 9s -> 0s, last !9 -> +1, all 9s -> 1 + 0...0, using two nodes to find and record the last 9, using dummy node to store the first node, 48 ms
func plusOne(head: ListNode?) -> ListNode? {
let dummy = ListNode(0)
dummy.next = head
var i = dummy
var j = dummy
while j.next != nil {
j = j.next!
if j.val != 9 {
i = j
}
}
i.val += 1
while i.next != nil {
i = i.next!
i.val = 0
}
if dummy.val == 0 {
return dummy.next
}else {
return dummy
}
}
|
mit
|
61685829b1553858fcae30248873cb0c
| 18.572727 | 148 | 0.445425 | 3.461415 | false | false | false | false |
googlemaps/ios-on-demand-rides-deliveries-samples
|
swift/consumer_swiftui/App/Utils/Style.swift
|
1
|
1780
|
/*
* Copyright 2022 Google LLC. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import Foundation
import SwiftUI
/// Constants that can be used in the sample app.
enum Style {
/// The length for the element frame width.
static let frameWidth = UIScreen.main.bounds.width * 0.8
/// Medium height for the element frame.
static let mediumFrameHeight = 35.0
/// Font size for small content.
static let smallFontSize = 14.0
/// Font size for medium content.
static let mediumFontSize = 18.0
/// Light color for static text.
static let textColor = Color(red: 117 / 255, green: 117 / 255, blue: 117 / 255)
/// Color for default state in buttons
static let buttonBackgroundColor = Color(red: 113 / 255, green: 131 / 255, blue: 148 / 255)
/// Color for normal traffic speed type.
static let trafficPolylineSpeedTypeNormalColor = UIColor(
red: 44 / 255, green: 153 / 255, blue: 255 / 255, alpha: 1)
/// Color for slow traffic speed type.
static let trafficPolylineSpeedTypeSlowColor = UIColor.yellow
/// Color for traffic jam speed type.
static let trafficPolylineSpeedTypeTrafficJamColor = UIColor.red
/// Color for no-data speed type.
static let trafficPolylineSpeedTypeNoDataColor = UIColor.gray
}
|
apache-2.0
|
ac88278758220c086448739cd7a878ad
| 33.230769 | 93 | 0.726966 | 4.168618 | false | false | false | false |
apple/swift
|
test/SILOptimizer/exclusivity_static_diagnostics.swift
|
2
|
25834
|
// RUN: %target-swift-frontend -enforce-exclusivity=checked -swift-version 4 -emit-sil -primary-file %s -o /dev/null -verify
// RUN: %target-swift-frontend -enforce-exclusivity=checked -swift-version 4 -emit-sil -primary-file %s -o /dev/null -verify
import Swift
func takesTwoInouts<T>(_ p1: inout T, _ p2: inout T) { }
func simpleInoutDiagnostic() {
var i = 7
// FIXME: This diagnostic should be removed if static enforcement is
// turned on by default.
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&i, &i)
}
func inoutOnInoutParameter(p: inout Int) {
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'p', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&p, &p)
}
func swapNoSuppression(_ i: Int, _ j: Int) {
var a: [Int] = [1, 2, 3]
// expected-error@+2{{overlapping accesses to 'a', but modification requires exclusive access; consider calling MutableCollection.swapAt(_:_:)}}
// expected-note@+1{{conflicting access is here}}
swap(&a[i], &a[j])
}
class SomeClass { }
struct StructWithMutatingMethodThatTakesSelfInout {
var f = SomeClass()
mutating func mutate(_ other: inout StructWithMutatingMethodThatTakesSelfInout) { }
mutating func mutate(_ other: inout SomeClass) { }
mutating func callMutatingMethodThatTakesSelfInout() {
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
mutate(&self)
}
mutating func callMutatingMethodThatTakesSelfStoredPropInout() {
// expected-error@+2{{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
mutate(&self.f)
}
}
var globalStruct1 = StructWithMutatingMethodThatTakesSelfInout()
func callMutatingMethodThatTakesGlobalStoredPropInout() {
// expected-error@+2{{overlapping accesses to 'globalStruct1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
globalStruct1.mutate(&globalStruct1.f)
}
class ClassWithFinalStoredProp {
final var s1: StructWithMutatingMethodThatTakesSelfInout = StructWithMutatingMethodThatTakesSelfInout()
final var s2: StructWithMutatingMethodThatTakesSelfInout = StructWithMutatingMethodThatTakesSelfInout()
final var i = 7
func callMutatingMethodThatTakesClassStoredPropInout() {
s1.mutate(&s2.f) // no-warning
// expected-error@+2{{overlapping accesses to 's1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
s1.mutate(&s1.f)
let local1 = self
// expected-error@+2{{overlapping accesses to 's1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
local1.s1.mutate(&local1.s1.f)
}
}
func violationWithGenericType<T>(_ p: T) {
var local = p
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&local, &local)
}
// Helper.
struct StructWithTwoStoredProp {
var f1: Int = 7
var f2: Int = 8
}
// Take an unsafe pointer to a stored property while accessing another stored property.
func violationWithUnsafePointer(_ s: inout StructWithTwoStoredProp) {
withUnsafePointer(to: &s.f1) { (ptr) in
// expected-error@-1 {{overlapping accesses to 's.f1', but modification requires exclusive access; consider copying to a local variable}}
_ = s.f1
// expected-note@-1 {{conflicting access is here}}
}
// Statically treat accesses to separate stored properties in structs as
// accessing separate storage.
withUnsafePointer(to: &s.f1) { (ptr) in // no-error
_ = s.f2
}
}
// Tests for Fix-Its to replace swap(&collection[a], &collection[b]) with
// collection.swapAt(a, b)
struct StructWithField {
var f = 12
}
struct StructWithFixits {
var arrayProp: [Int] = [1, 2, 3]
var dictionaryProp: [Int : Int] = [0 : 10, 1 : 11]
mutating
func shouldHaveFixIts<T>(_ i: Int, _ j: Int, _ param: T, _ paramIndex: T.Index) where T : MutableCollection {
var array1 = [1, 2, 3]
// expected-error@+2{{overlapping accesses}}{{5-41=array1.swapAt(i + 5, j - 2)}}
// expected-note@+1{{conflicting access is here}}
swap(&array1[i + 5], &array1[j - 2])
// expected-error@+2{{overlapping accesses}}{{5-49=self.arrayProp.swapAt(i, j)}}
// expected-note@+1{{conflicting access is here}}
swap(&self.arrayProp[i], &self.arrayProp[j])
var localOfGenericType = param
// expected-error@+2{{overlapping accesses}}{{5-75=localOfGenericType.swapAt(paramIndex, paramIndex)}}
// expected-note@+1{{conflicting access is here}}
swap(&localOfGenericType[paramIndex], &localOfGenericType[paramIndex])
// expected-error@+2{{overlapping accesses}}{{5-39=array1.swapAt(i, j)}}
// expected-note@+1{{conflicting access is here}}
Swift.swap(&array1[i], &array1[j]) // no-crash
}
mutating
func shouldHaveNoFixIts(_ i: Int, _ j: Int) {
var s = StructWithField()
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&s.f, &s.f)
var array1 = [1, 2, 3]
var array2 = [1, 2, 3]
// Swapping between different arrays should cannot have the
// Fix-It.
swap(&array1[i], &array2[j]) // no-warning no-fixit
swap(&array1[i], &self.arrayProp[j]) // no-warning no-fixit
// Dictionaries aren't MutableCollections so don't support swapAt().
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&dictionaryProp[i], &dictionaryProp[j])
// We could safely Fix-It this but don't now because the left and
// right bases are not textually identical.
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&self.arrayProp[i], &arrayProp[j])
// We could safely Fix-It this but we're not that heroic.
// We don't suppress when swap() is used as a value
let mySwap: (inout Int, inout Int) -> () = swap
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
mySwap(&array1[i], &array1[j])
func myOtherSwap<T>(_ a: inout T, _ b: inout T) {
swap(&a, &b) // no-warning
}
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
mySwap(&array1[i], &array1[j])
}
}
func takesInoutAndNoEscapeClosure<T>(_ p: inout T, _ c: () -> ()) { }
func callsTakesInoutAndNoEscapeClosure() {
var local = 5
takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local = 8 // expected-note {{conflicting access is here}}
}
}
func inoutReadWriteInout(x: inout Int) {
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesInoutAndNoEscapeClosure(&x, { _ = x })
}
func inoutWriteWriteInout(x: inout Int) {
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesInoutAndNoEscapeClosure(&x, { x = 42 })
}
func callsTakesInoutAndNoEscapeClosureWithRead() {
var local = 5
takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
_ = local // expected-note {{conflicting access is here}}
}
}
func takesInoutAndNoEscapeClosureThatThrows<T>(_ p: inout T, _ c: () throws -> ()) { }
func callsTakesInoutAndNoEscapeClosureThatThrowsWithNonThrowingClosure() {
var local = 5
takesInoutAndNoEscapeClosureThatThrows(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local = 8 // expected-note {{conflicting access is here}}
}
}
func takesInoutAndNoEscapeClosureAndThrows<T>(_ p: inout T, _ c: () -> ()) throws { }
func callsTakesInoutAndNoEscapeClosureAndThrows() {
var local = 5
try! takesInoutAndNoEscapeClosureAndThrows(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local = 8 // expected-note {{conflicting access is here}}
}
}
func takesTwoNoEscapeClosures(_ c1: () -> (), _ c2: () -> ()) { }
func callsTakesTwoNoEscapeClosures() {
var local = 7
takesTwoNoEscapeClosures({local = 8}, {local = 9}) // no-error
_ = local
}
func takesInoutAndEscapingClosure<T>(_ p: inout T, _ c: @escaping () -> ()) { }
func callsTakesInoutAndEscapingClosure() {
var local = 5
takesInoutAndEscapingClosure(&local) { // no-error
local = 8
}
}
func callsClosureLiteralImmediately() {
var i = 7;
// Closure literals that are called immediately are considered nonescaping
_ = ({ (p: inout Int) in
i
// expected-note@-1 {{conflicting access is here}}
}
)(&i)
// expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
}
func callsStoredClosureLiteral() {
var i = 7;
let c = { (p: inout Int) in i}
// Closure literals that are stored and later called are treated as escaping
// We don't expect a static exclusivity diagnostic here, but the issue
// will be caught at run time
_ = c(&i) // no-error
}
// Calling this with an inout expression for the first parameter performs a
// read access for the duration of a call
func takesUnsafePointerAndNoEscapeClosure<T>(_ p: UnsafePointer<T>, _ c: () -> ()) { }
// Calling this with an inout expression for the first parameter performs a
// modify access for the duration of a call
func takesUnsafeMutablePointerAndNoEscapeClosure<T>(_ p: UnsafeMutablePointer<T>, _ c: () -> ()) { }
func callsTakesUnsafePointerAndNoEscapeClosure() {
var local = 1
takesUnsafePointerAndNoEscapeClosure(&local) { // expected-note {{conflicting access is here}}
local = 2 // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
}
}
func callsTakesUnsafePointerAndNoEscapeClosureThatReads() {
var local = 1
// Overlapping reads
takesUnsafePointerAndNoEscapeClosure(&local) {
_ = local // no-error
}
}
func callsTakesUnsafeMutablePointerAndNoEscapeClosureThatReads() {
var local = 1
// Overlapping modify and read
takesUnsafeMutablePointerAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
_ = local // expected-note {{conflicting access is here}}
}
}
func takesThrowingAutoClosureReturningGeneric<T: Equatable>(_ : @autoclosure () throws -> T) { }
func takesInoutAndClosure<T>(_: inout T, _ : () -> ()) { }
func callsTakesThrowingAutoClosureReturningGeneric() {
var i = 0
takesInoutAndClosure(&i) { // expected-error {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
takesThrowingAutoClosureReturningGeneric(i) // expected-note {{conflicting access is here}}
}
}
struct StructWithMutatingMethodThatTakesAutoclosure {
var f = 2
mutating func takesAutoclosure(_ p: @autoclosure () throws -> ()) rethrows { }
}
func conflictOnSubPathInNoEscapeAutoclosure() {
var s = StructWithMutatingMethodThatTakesAutoclosure()
s.takesAutoclosure(s.f = 2)
// expected-error@-1 {{overlapping accesses to 's', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2 {{conflicting access is here}}
}
func conflictOnWholeInNoEscapeAutoclosure() {
var s = StructWithMutatingMethodThatTakesAutoclosure()
takesInoutAndNoEscapeClosure(&s.f) {
// expected-error@-1 {{overlapping accesses to 's.f', but modification requires exclusive access; consider copying to a local variable}}
s = StructWithMutatingMethodThatTakesAutoclosure()
// expected-note@-1 {{conflicting access is here}}
}
}
struct ParameterizedStruct<T> {
mutating func takesFunctionWithGenericReturnType(_ f: (Int) -> T) {}
}
func testReabstractionThunk(p1: inout ParameterizedStruct<Int>,
p2: inout ParameterizedStruct<Int>) {
// Since takesFunctionWithGenericReturnType() takes a closure with a generic
// return type it expects the value to be returned @out. But the closure
// here has an 'Int' return type, so the compiler uses a reabstraction thunk
// to pass the closure to the method.
// This tests that we still detect access violations for closures passed
// using a reabstraction thunk.
p1.takesFunctionWithGenericReturnType { _ in
// expected-error@-1 {{overlapping accesses to 'p1', but modification requires exclusive access; consider copying to a local variable}}
p2 = p1
// expected-note@-1 {{conflicting access is here}}
return 3
}
}
func takesNoEscapeBlockClosure
(
_ p: inout Int, _ c: @convention(block) () -> ()
) { }
func takesEscapingBlockClosure
(
_ p: inout Int, _ c: @escaping @convention(block) () -> ()
) { }
func testCallNoEscapeBlockClosure() {
var i = 7
takesNoEscapeBlockClosure(&i) {
// expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
i = 7
// expected-note@-1 {{conflicting access is here}}
}
}
func testCallNoEscapeBlockClosureRead() {
var i = 7
takesNoEscapeBlockClosure(&i) {
// expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
_ = i
// expected-note@-1 {{conflicting access is here}}
}
}
func testCallEscapingBlockClosure() {
var i = 7
takesEscapingBlockClosure(&i) { // no-warning
i = 7
}
}
func testCallNonEscapingWithEscapedBlock() {
var i = 7
let someBlock : @convention(block) () -> () = {
i = 8
}
takesNoEscapeBlockClosure(&i, someBlock) // no-warning
}
func takesInoutAndClosureWithGenericArg<T>(_ p: inout Int, _ c: (T) -> Int) { }
func callsTakesInoutAndClosureWithGenericArg() {
var i = 7
takesInoutAndClosureWithGenericArg(&i) { (p: Int) in
// expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
return i + p
// expected-note@-1 {{conflicting access is here}}
}
}
func takesInoutAndClosureTakingNonOptional(_ p: inout Int, _ c: (Int) -> ()) { }
func callsTakesInoutAndClosureTakingNonOptionalWithClosureTakingOptional() {
var i = 7
// Test for the thunk converting an (Int?) -> () to an (Int) -> ()
takesInoutAndClosureTakingNonOptional(&i) { (p: Int?) in
// expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
i = 8
// expected-note@-1 {{conflicting access is here}}
}
}
// Helper.
func doOne(_ f: () -> ()) {
f()
}
func noEscapeBlock() {
var x = 3
doOne {
// expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesInoutAndNoEscapeClosure(&x, { _ = x })
}
}
func inoutSeparateStructStoredProperties() {
var s = StructWithTwoStoredProp()
takesTwoInouts(&s.f1, &s.f2) // no-error
}
func inoutSameStoredProperty() {
var s = StructWithTwoStoredProp()
takesTwoInouts(&s.f1, &s.f1)
// expected-error@-1{{overlapping accesses to 's.f1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSeparateTupleElements() {
var t = (1, 4)
takesTwoInouts(&t.0, &t.1) // no-error
}
func inoutSameTupleElement() {
var t = (1, 4)
takesTwoInouts(&t.0, &t.0)
// expected-error@-1{{overlapping accesses to 't.0', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSameTupleNamedElement() {
var t = (name1: 1, name2: 4)
takesTwoInouts(&t.name2, &t.name2)
// expected-error@-1{{overlapping accesses to 't.name2', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSamePropertyInSameTuple() {
var t = (name1: 1, name2: StructWithTwoStoredProp())
takesTwoInouts(&t.name2.f1, &t.name2.f1)
// expected-error@-1{{overlapping accesses to 't.name2.f1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
// Noescape closures and separate stored structs
func callsTakesInoutAndNoEscapeClosureNoWarningOnSeparateStored() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) {
local.f2 = 8 // no-error
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnSameStoredProp() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
local.f1 = 8 // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnAggregateAndStoredProp() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local.f1 = 8 // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndAggregate() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndBothPropertyAndAggregate() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
local.f1 = 8
// We want the diagnostic on the access for the aggregate and not the projection.
local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndBothAggregateAndProperty() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
// We want the diagnostic on the access for the aggregate and not the projection.
local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}}
local.f1 = 8
}
}
struct MyStruct<T> {
var prop = 7
mutating func inoutBoundGenericStruct() {
takesTwoInouts(&prop, &prop)
// expected-error@-1{{overlapping accesses to 'self.prop', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
}
func testForLoopCausesReadAccess() {
var a: [Int] = [1]
takesInoutAndNoEscapeClosure(&a) { // expected-error {{overlapping accesses to 'a', but modification requires exclusive access; consider copying to a local variable}}
for _ in a { // expected-note {{conflicting access is here}}
}
}
}
func testKeyPathStructField() {
let getF = \StructWithField.f
var local = StructWithField()
takesInoutAndNoEscapeClosure(&local[keyPath: getF]) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local.f = 17 // expected-note {{conflicting access is here}}
}
}
func testKeyPathWithClassFinalStoredProperty() {
let getI = \ClassWithFinalStoredProp.i
let local = ClassWithFinalStoredProp()
// Ideally we would diagnose statically here, but it is not required by the
// model.
takesTwoInouts(&local[keyPath: getI], &local[keyPath: getI])
}
func takesInoutAndOptionalClosure(_: inout Int, _ f: (()->())?) {
f!()
}
// An optional closure is not considered @noescape:
// This violation will only be caught dynamically.
//
// apply %takesInoutAndOptionalClosure(%closure)
// : $@convention(thin) (@inout Int, @owned Optional<@callee_guaranteed () -> ()>) -> ()
func testOptionalClosure() {
var x = 0
takesInoutAndOptionalClosure(&x) { x += 1 }
}
func takesInoutAndOptionalBlock(_: inout Int, _ f: (@convention(block) ()->())?) {
f!()
}
// An optional block is not be considered @noescape.
// This violation will only be caught dynamically.
func testOptionalBlock() {
var x = 0
takesInoutAndOptionalBlock(&x) { x += 1 }
}
// Diagnost a conflict on a noescape closure that is conditionally passed as a function argument.
//
// <rdar://problem/42560459> [Exclusivity] Failure to statically diagnose a conflict when passing conditional noescape closures.
struct S {
var x: Int
mutating func takeNoescapeClosure(_ f: ()->()) { f() }
mutating func testNoescapePartialApplyPhiUse(z : Bool) {
func f1() {
x = 1 // expected-note {{conflicting access is here}}
}
func f2() {
x = 1 // expected-note {{conflicting access is here}}
}
takeNoescapeClosure(z ? f1 : f2)
// expected-error@-1 2 {{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}}
}
}
func doit(x: inout Int, _ fn: () -> ()) {}
func nestedConflict(x: inout Int) {
doit(x: &x, x == 0 ? { x = 1 } : { x = 2})
// expected-error@-1 2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2 2{{conflicting access is here}}
}
// Avoid diagnosing a conflict on disjoint struct properties when one is a `let`.
// This requires an address projection before loading the `let` property.
//
// rdar://problem/35561050
// https://github.com/apple/swift/issues/52547
// [Exclusivity] SILGen loads entire struct when reading captured 'let'
// stored property
struct DisjointLetMember {
var dummy: AnyObject // Make this a nontrivial struct because the SIL is more involved.
mutating func get(makeValue: ()->Int) -> Int {
return makeValue()
}
}
class IntWrapper {
var x = 0
}
struct DisjointLet {
let a = 2 // Using a `let` forces a full load.
let b: IntWrapper
var cache: DisjointLetMember
init(b: IntWrapper) {
self.b = b
self.cache = DisjointLetMember(dummy: b)
}
mutating func testDisjointLet() -> Int {
// Access to inout `self` for member .cache`.
return cache.get {
// Access to captured `self` for member .cache`.
a + b.x
}
}
}
// -----------------------------------------------------------------------------
// coroutineWithClosureArg: AccessedSummaryAnalysis must consider
// begin_apply a valid user of partial_apply.
//
// Test that this does not assert in hasExpectedUsesOfNoEscapePartialApply.
//
// This test needs two closures, one to capture the variable, another
// to recapture the variable, so AccessSummary is forced to process
// the closure.
func coroutineWithClosureArg(i: Int, x: inout Int, d: inout Dictionary<Int, Int>) {
{ d[i, default: x] = 0 }()
}
// -----------------------------------------------------------------------------
//
struct TestConflictInCoroutineClosureArg {
static let defaultKey = 0
var dictionary = [defaultKey:0]
mutating func incrementValue(at key: Int) {
dictionary[key, default:
dictionary[TestConflictInCoroutineClosureArg.defaultKey]!] += 1
// expected-error@-2 {{overlapping accesses to 'self.dictionary', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2 {{conflicting access is here}}
}
}
// Check that AccessSummaryAnalysis does not crash with this:
struct TestStruct {
var x = 7
mutating func b() {
func c() {}
func d() {
x // expected-warning {{property is accessed but result is unused}}
}
withoutActuallyEscaping(c) { e in
withoutActuallyEscaping(d) { e in
}
}
}
}
|
apache-2.0
|
6484f8aed4c4a17a75aa7974969c23c1
| 36.011461 | 191 | 0.705543 | 4.204753 | false | false | false | false |
JKapanke/betterthings
|
WorldTraveler/DiceRollViewController.swift
|
1
|
3168
|
//
// DiceRollViewController.swift
// WorldTraveler
//
// Created by Jason Kapanke on 12/2/14.
// Copyright (c) 2014 Better Things. All rights reserved.
//
import UIKit
class DiceRollViewController: UIViewController
{
@IBOutlet weak var rollButton: UIButton!
@IBOutlet weak var secondDieImage: UIImageView!
@IBOutlet weak var firstDieImage: UIImageView!
var countryRolled = Country()
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//send them to the next view with the selected country by passing the country name as part of the seque
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
//the segue must be named as noted in the operator
if (segue.identifier == "toCountrySegue")
{
var cvc = segue.destinationViewController as CountryViewController;
cvc.typeOfCountry = countryRolled
/*
cvc.dynamicLabel.text = countryRolled.getCountryName()
cvc.dynamicMap = countryRolled.getMapImage()
cvc.activityOneLabel.text = countryRolled.getFirstActivity().getActivityName()
cvc.activityTwoLabel.text = countryRolled.getSecondActivity().getActivityName()
cvc.activityThreeLabel.text = countryRolled.getThirdActivity().getActivityName()
*/
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func rollButtonAction(sender: UIButton)
{
let firstDie = Dice()
let secondDie = Dice()
//initiate rolling die sound
firstDie.playRollingDiceSound()
//sleep for 2 seconds to allow the shaking and rolling of die to complete
sleep(2)
var firstDieValue = firstDie.rollDice()
var secondDieValue = secondDie.rollDice()
var dieTotal = firstDieValue + secondDieValue
firstDieImage.image = UIImage(named: "dice\(firstDieValue).png")
secondDieImage.image = UIImage(named: "dice\(secondDieValue).png")
println("you rolled a \(dieTotal)!")
//Call the function which returns a country to the value
countryRolled = determineCountryBasedOnRoll(dieTotal)
println("Country to visit: \(countryRolled.getCountryName())")
}
func determineCountryBasedOnRoll(dieValue: Int) -> Country {
var determinedCountry = Country()
switch dieValue
{
case 0...4:
determinedCountry = Canada()
case 5...6:
determinedCountry = Brazil()
case 7...8:
determinedCountry = India()
case 9...10:
determinedCountry = Australia()
case 11...12:
determinedCountry = China()
default:
determinedCountry = Country()
}
return determinedCountry
}
}
|
mit
|
2767450f41eabae7ff8a8ef40a8981dd
| 30.366337 | 107 | 0.607323 | 4.965517 | false | false | false | false |
See-Ku/SK4Toolkit
|
SK4ToolkitTests/StringExtensionTests.swift
|
1
|
3401
|
//
// StringExtensionTests.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/03/30.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import XCTest
import SK4Toolkit
class StringExtensionTests: XCTestCase {
func testString() {
let base = "12345678"
// /////////////////////////////////////////////////////////////
// sk4SubstringToIndex
// 先頭から4文字を取得
XCTAssert(base.sk4SubstringToIndex(4) == "1234")
// 先頭から0文字を取得 = ""
XCTAssert(base.sk4SubstringToIndex(0) == "")
// 文字列の長さを超えた場合、全体を返す
XCTAssert(base.sk4SubstringToIndex(12) == "12345678")
// 先頭より前を指定された場合、""を返す
XCTAssert(base.sk4SubstringToIndex(-4) == "")
// /////////////////////////////////////////////////////////////
// sk4SubstringFromIndex
// 4文字目以降を取得
XCTAssert(base.sk4SubstringFromIndex(4) == "5678")
// 0文字目以降をを取得
XCTAssert(base.sk4SubstringFromIndex(0) == "12345678")
// 文字列の長さを超えた場合""を返す
XCTAssert(base.sk4SubstringFromIndex(12) == "")
// 先頭より前を指定された場合、全体を返す
XCTAssert(base.sk4SubstringFromIndex(-4) == "12345678")
// /////////////////////////////////////////////////////////////
// sk4SubstringWithRange
// 2文字目から6文字目までを取得
XCTAssert(base.sk4SubstringWithRange(start: 2, end: 6) == "3456")
// 0文字目から4文字目までを取得
XCTAssert(base.sk4SubstringWithRange(start: 0, end: 4) == "1234")
// 4文字目から8文字目までを取得
XCTAssert(base.sk4SubstringWithRange(start: 4, end: 8) == "5678")
// 範囲外の指定は範囲内に丸める
XCTAssert(base.sk4SubstringWithRange(start: -2, end: 3) == "123")
XCTAssert(base.sk4SubstringWithRange(start: 5, end: 12) == "678")
XCTAssert(base.sk4SubstringWithRange(start: -3, end: 15) == "12345678")
// Rangeでの指定も可能
XCTAssert(base.sk4SubstringWithRange(1 ..< 4) == "234")
// /////////////////////////////////////////////////////////////
// sk4TrimSpace
// 文字列の前後から空白文字を取り除く
XCTAssert(" abc def\n ".sk4TrimSpace() == "abc def\n")
// 文字列の前後から空白文字と改行を取り除く
XCTAssert(" abc def\n ".sk4TrimSpaceNL() == "abc def")
// 全角空白も対応
XCTAssert(" どうかな? ".sk4TrimSpaceNL() == "どうかな?")
// 何も残らない場合は""になる
XCTAssert(" \n \n ".sk4TrimSpaceNL() == "")
XCTAssert("".sk4TrimSpaceNL() == "")
}
func testConvert() {
let str = "1234"
// utf8エンコードでNSDataに変換
if let data = str.sk4ToNSData() {
// println(data1)
XCTAssert(data.description == "<31323334>")
} else {
XCTFail("Fail")
}
// Base64をデコードしてNSDataに変換
if let data = str.sk4Base64Decode() {
// println(data2)
XCTAssert(data.description == "<d76df8>")
} else {
XCTFail("Fail")
}
let empty = ""
// utf8エンコードでNSDataに変換
if let data = empty.sk4ToNSData() {
XCTAssert(data.length == 0)
} else {
XCTFail("Fail")
}
// Base64をデコードしてNSDataに変換
if let data = empty.sk4Base64Decode() {
XCTAssert(data.length == 0)
} else {
XCTFail("Fail")
}
}
}
// eof
|
mit
|
0324ce3ec2f26e8ca01175c33dd32072
| 22.04878 | 73 | 0.595767 | 2.755102 | false | false | false | false |
gdollardollar/GMHud
|
Example/InputViewController.swift
|
1
|
1035
|
//
// InputViewController.swift
// GMHud
//
// Created by Guillaume on 11/22/16.
// Copyright © 2016 gdollardollar. All rights reserved.
//
import UIKit
import GMHud
class InputViewController: Hud {
override func animateDisplay() {
let c = view.backgroundColor
view.backgroundColor = .clear
content!.transform.ty = content!.bounds.height
UIView.animate(withDuration: 0.3, delay: 0, options: [], animations: {
self.view.backgroundColor = c
self.content!.transform.ty = 0
}, completion: nil)
}
override func animateDismiss(completion: @escaping (Bool) -> ()) {
UIView.animate(withDuration: 0.3, delay: 0, options: [], animations: {
self.view.backgroundColor = .clear
self.content!.transform.ty = self.content!.bounds.height
}, completion: completion)
}
override func coverTapShouldBegin(tap: UITapGestureRecognizer) -> Bool {
return true
}
}
|
mit
|
e2da20e49e7e0e767a4b2577a01c7789
| 25.512821 | 78 | 0.60735 | 4.4 | false | false | false | false |
chetca/Android_to_iOs
|
memuDemo/DatsansSC/DatsansTableViewController.swift
|
1
|
2273
|
//
// DatsansTableViewController.swift
// memuDemo
//
// Created by Dugar Badagarov on 30/08/2017.
// Copyright © 2017 Parth Changela. All rights reserved.
//
import UIKit
class DatsansTableViewController: UITableViewController {
@IBOutlet var btnMenuButton: UIBarButtonItem!
var paramDict:[String:[String]] = Dictionary()
override func viewDidLoad() {
super.viewDidLoad()
if revealViewController() != nil {
btnMenuButton.target = revealViewController()
btnMenuButton.action = #selector(SWRevealViewController.revealToggle(_:))
paramDict = JSONTaker.shared.loadData(API: "dat", paramNames: ["title", "text"])
//loadAstrologicalData(baseURL: "file:///Users/dugar/Downloads/feed.json")
//print (paramDict)
tableView.contentInset = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
}
tableView.allowsSelection = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (paramDict["title"]?.count)!
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if !(cell != nil) {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell") //if cell is nil, get pointer to new one
}
cell?.textLabel?.font = UIFont(name: "Helvetica", size: 13)
if (indexPath.row >= 0 && indexPath.row <= 6) {
cell?.textLabel?.setHTML(html: String((self.paramDict["title"]?[indexPath.row])! + "\n" + (self.paramDict["text"]?[indexPath.row])!))
cell?.textLabel?.numberOfLines = 0
}
return cell!
}
}
|
mit
|
b91a22c2985826c4e28c36253d4c2907
| 35.063492 | 145 | 0.581866 | 5.235023 | false | false | false | false |
ikesyo/Rex
|
Source/UIKit/UILabel.swift
|
1
|
1067
|
//
// UILabel.swift
// Rex
//
// Created by Neil Pankey on 6/19/15.
// Copyright (c) 2015 Neil Pankey. All rights reserved.
//
import ReactiveCocoa
import UIKit
extension UILabel {
/// Wraps a label's `text` value in a bindable property.
public var rex_text: MutableProperty<String?> {
return associatedProperty(self, key: &attributedTextKey, initial: { $0.text }, setter: { $0.text = $1 })
}
/// Wraps a label's `attributedText` value in a bindable property.
public var rex_attributedText: MutableProperty<NSAttributedString?> {
return associatedProperty(self, key: &attributedTextKey, initial: { $0.attributedText }, setter: { $0.attributedText = $1 })
}
/// Wraps a label's `textColor` value in a bindable property.
public var rex_textColor: MutableProperty<UIColor> {
return associatedProperty(self, key: &textColorKey, initial: { $0.textColor }, setter: { $0.textColor = $1 })
}
}
private var textKey: UInt8 = 0
private var attributedTextKey: UInt8 = 0
private var textColorKey: UInt8 = 0
|
mit
|
6e3e3db1ef40bbef002bd37f21f7b265
| 33.419355 | 132 | 0.68135 | 3.865942 | false | false | false | false |
UniqHu/Youber
|
Youber/Youber/View/ActionController/ActionControllerSettings.swift
|
1
|
9975
|
// ActionControllerSettings.swiftg
// XLActionController ( https://github.com/xmartlabs/XLActionController )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public struct ActionControllerSettings {
/** Struct that contains properties to configure the actions controller's behavior */
public struct Behavior {
/**
* A Boolean value that determines whether the action controller must be dismissed when the user taps the
* background view. Its default value is `true`.
*/
public var hideOnTap = true
/**
* A Boolean value that determines whether the action controller must be dismissed when the user scroll down
* the collection view. Its default value is `true`.
*
* @discussion If `scrollEnabled` value is `false`, this property is discarded and the action controller won't
* be dismissed if the user scrolls down the collection view.
*/
public var hideOnScrollDown = true
/**
* A Boolean value that determines whether the collectionView's scroll is enabled. Its default value is `false`
*/
public var scrollEnabled = false
/**
* A Boolean value that controls whether the collection view scroll bounces past the edge of content and back
* again. Its default value is `false`
*/
public var bounces = false
/**
* A Boolean value that determines whether if the collection view layout will use UIDynamics to animate its
* items. Its default value is `false`
*/
public var useDynamics = false
}
/** Struct that contains properties to configure the cancel view */
public struct CancelViewStyle {
/**
* A Boolean value that determines whether cancel view is shown. Its default value is `false`. Its default
* value is `false`.
*/
public var showCancel = false
/**
* The cancel view's title. Its default value is "Cancel".
*/
public var title: String? = "Cancel"
/**
* The cancel view's height. Its default value is `60`.
*/
public var height = CGFloat(60.0)
/**
* The cancel view's background color. Its default value is `UIColor.blackColor().colorWithAlphaComponent(0.8)`.
*/
public var backgroundColor = UIColor.black.withAlphaComponent(0.8)
/**
* A Boolean value that determines whether the collection view can be partially covered by the
* cancel view when it is pulled down. Its default value is `true`
*/
public var hideCollectionViewBehindCancelView = true
}
/** Struct that contains properties to configure the collection view's style */
public struct CollectionViewStyle {
/**
* A float that determines the margins between the collection view and the container view's margins.
* Its default value is `0`
*/
public var lateralMargin: CGFloat = 0
/**
* A float that determines the cells' height when using UIDynamics to animate items. Its default value is `50`.
*/
public var cellHeightWhenDynamicsIsUsed: CGFloat = 50
}
/** Struct that contains properties to configure the animation when presenting the action controller */
public struct PresentAnimationStyle {
/**
* A float value that is used as damping for the animation block. Its default value is `1.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var damping = CGFloat(1.0)
/**
* A float value that is used as delay for the animation block. Its default value is `0.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var delay = TimeInterval(0.0)
/**
* A float value that determines the animation duration. Its default value is `0.7`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var duration = TimeInterval(0.7)
/**
* A float value that is used as `springVelocity` for the animation block. Its default value is `0.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var springVelocity = CGFloat(0.0)
/**
* A mask of options indicating how you want to perform the animations. Its default value is `UIViewAnimationOptions.CurveEaseOut`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var options = UIViewAnimationOptions.curveEaseOut
}
/** Struct that contains properties to configure the animation when dismissing the action controller */
public struct DismissAnimationStyle {
/**
* A float value that is used as damping for the animation block. Its default value is `1.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var damping = CGFloat(1.0)
/**
* A float value that is used as delay for the animation block. Its default value is `0.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var delay = TimeInterval(0.0)
/**
* A float value that determines the animation duration. Its default value is `0.7`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var duration = TimeInterval(0.7)
/**
* A float value that is used as `springVelocity` for the animation block. Its default value is `0.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var springVelocity = CGFloat(0.0)
/**
* A mask of options indicating how you want to perform the animations. Its default value is `UIViewAnimationOptions.CurveEaseIn`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var options = UIViewAnimationOptions.curveEaseIn
/**
* A float value that makes the action controller's to be animated until the bottomof the screen plus this value.
*/
public var offset = CGFloat(0)
}
/** Struct that contains all properties related to presentation & dismissal animations */
public struct AnimationStyle {
/**
* A size value that is used to scale the presenting view controller when the action controller is being
* presented. If `nil` is set, then the presenting view controller won't be scaled. Its default value is
* `(0.9, 0.9)`.
*/
public var scale: CGSize? = CGSize(width: 0.9, height: 0.9)
/** Stores presentation animation properties */
public var present = PresentAnimationStyle()
/** Stores dismissal animation properties */
public var dismiss = DismissAnimationStyle()
}
/** Struct that contains properties related to the status bar's appearance */
public struct StatusBarStyle {
/**
* A Boolean value that determines whether the status bar should be visible or hidden when the action controller
* is visible. Its default value is `true`.
*/
public var showStatusBar = true
/**
* A value that determines the style of the device’s status bar when the action controller is visible. Its
* default value is `UIStatusBarStyle.LightContent`.
*/
public var style = UIStatusBarStyle.lightContent
}
/** Stores the behavior's properties values */
public var behavior = Behavior()
/** Stores the cancel view's properties values */
public var cancelView = CancelViewStyle()
/** Stores the collection view's properties values */
public var collectionView = CollectionViewStyle()
/** Stores the animations' properties values */
public var animation = AnimationStyle()
/** Stores the status bar's properties values */
public var statusBar = StatusBarStyle()
/**
* Create the default settings
* @return The default value for settings
*/
public static func defaultSettings() -> ActionControllerSettings {
return ActionControllerSettings()
}
}
|
mit
|
04f318bc1e33bd1c3754e5b0576da50b
| 47.178744 | 140 | 0.668505 | 5.271142 | false | false | false | false |
ngageoint/mage-ios
|
Mage/CoreData/Observation.swift
|
1
|
64133
|
//
// Observation.m
// mage-ios-sdk
//
// Created by William Newman on 4/13/16.
// Copyright © 2016 National Geospatial-Intelligence Agency. All rights reserved.
//
import Foundation
import CoreData
import sf_ios
import UIKit
import MagicalRecord
import geopackage_ios
enum State: Int, CustomStringConvertible {
case Archive, Active
var description: String {
switch self {
case .Archive:
return "archive"
case .Active:
return "active"
}
}
}
@objc public class Observation: NSManagedObject, Navigable {
var orderedAttachments: [Attachment]? {
get {
var observationForms: [[String: Any]] = []
if let properties = self.properties as? [String: Any] {
if (properties.keys.contains("forms")) {
observationForms = properties["forms"] as! [[String: Any]];
}
}
return attachments?.sorted(by: { first, second in
// return true if first comes before second, false otherwise
if first.observationFormId == second.observationFormId {
// if they are in the same form, sort on field
if first.fieldName == second.fieldName {
// if they are the same field return the order comparison unless they are both zero, then return the lat modified comparison
let firstOrder = first.order?.intValue ?? 0
let secondOrder = second.order?.intValue ?? 0
return (firstOrder != secondOrder) ? (firstOrder < secondOrder) : (first.lastModified ?? Date()) < (second.lastModified ?? Date())
} else {
// return the first field
let form = observationForms.first { form in
return form[FormKey.id.key] as? String == first.observationFormId
}
let firstFieldIndex = (form?[FormKey.fields.key] as? [[String: Any]])?.firstIndex { form in
return form[FieldKey.name.key] as? String == first.fieldName
} ?? 0
let secondFieldIndex = (form?[FormKey.fields.key] as? [[String: Any]])?.firstIndex { form in
return form[FieldKey.name.key] as? String == second.fieldName
} ?? 0
return firstFieldIndex < secondFieldIndex
}
} else {
// different forms, sort on form order
let firstFormIndex = observationForms.firstIndex { form in
return form[FormKey.id.key] as? String == first.observationFormId
} ?? 0
let secondFormIndex = observationForms.firstIndex { form in
return form[FormKey.id.key] as? String == second.observationFormId
} ?? 0
return firstFormIndex < secondFormIndex
}
})
}
}
var coordinate: CLLocationCoordinate2D {
get {
return location?.coordinate ?? CLLocationCoordinate2D(latitude: 0, longitude: 0)
}
}
public func viewRegion(mapView: MKMapView) -> MKCoordinateRegion {
if let geometry = self.geometry {
var latitudeMeters = 2500.0
var longitudeMeters = 2500.0
if geometry is SFPoint {
if let properties = properties, let accuracy = properties[ObservationKey.accuracy.key] as? Double {
latitudeMeters = accuracy * 2.5
longitudeMeters = accuracy * 2.5
}
} else {
let envelope = SFGeometryEnvelopeBuilder.buildEnvelope(with: geometry)
let boundingBox = GPKGBoundingBox(envelope: envelope)
if let size = boundingBox?.sizeInMeters() {
latitudeMeters = size.height + (2 * (size.height * 0.1))
longitudeMeters = size.width + (2 * (size.width * 0.1))
}
}
if let centroid = geometry.centroid() {
return MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: centroid.y.doubleValue, longitude: centroid.x.doubleValue), latitudinalMeters: latitudeMeters, longitudinalMeters: longitudeMeters)
}
}
return MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 0, longitude: 0), latitudinalMeters: 50000, longitudinalMeters: 50000)
}
static func fetchedResultsController(_ observation: Observation, delegate: NSFetchedResultsControllerDelegate) -> NSFetchedResultsController<Observation>? {
let fetchRequest = Observation.fetchRequest()
if let remoteId = observation.remoteId {
fetchRequest.predicate = NSPredicate(format: "remoteId = %@", remoteId)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)]
} else {
fetchRequest.predicate = NSPredicate(format: "self = %@", observation)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)]
}
let observationFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: NSManagedObjectContext.mr_default(), sectionNameKeyPath: nil, cacheName: nil)
observationFetchedResultsController.delegate = delegate
do {
try observationFetchedResultsController.performFetch()
} catch {
let fetchError = error as NSError
print("Unable to Perform Fetch Request")
print("\(fetchError), \(fetchError.localizedDescription)")
}
return observationFetchedResultsController
}
@objc public static func operationToPullInitialObservations(success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? {
return Observation.operationToPullObservations(initial: true, success: success, failure: failure);
}
@objc public static func operationToPullObservations(success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? {
return Observation.operationToPullObservations(initial: false, success: success, failure: failure);
}
static func operationToPullObservations(initial: Bool, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? {
guard let currentEventId = Server.currentEventId(), let baseURL = MageServer.baseURL() else {
return nil;
}
let url = "\(baseURL.absoluteURL)/api/events/\(currentEventId)/observations";
print("Fetching observations from event \(currentEventId)");
var parameters: [AnyHashable : Any] = [
// does this work on the server?
"sort" : "lastModified+DESC"
]
if let lastObservationDate = Observation.fetchLastObservationDate(context: NSManagedObjectContext.mr_default()) {
parameters["startDate"] = ISO8601DateFormatter.string(from: lastObservationDate, timeZone: TimeZone(secondsFromGMT: 0)!, formatOptions: [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone])
}
let manager = MageSessionManager.shared();
let methodStart = Date()
NSLog("TIMING Fetching Observations for event \(currentEventId) @ \(methodStart)")
let task = manager?.get_TASK(url, parameters: parameters, progress: nil, success: { task, responseObject in
NSLog("TIMING Fetched Observations for event \(currentEventId). Elapsed: \(methodStart.timeIntervalSinceNow) seconds")
guard let features = responseObject as? [[AnyHashable : Any]] else {
success?(task, nil);
return;
}
print("Fetched \(features.count) observations from the server, saving");
if features.count == 0 {
success?(task, responseObject)
return;
}
let saveStart = Date()
NSLog("TIMING Saving Observations for event \(currentEventId) @ \(saveStart)")
let rootSavingContext = NSManagedObjectContext.mr_rootSaving();
let localContext = NSManagedObjectContext.mr_context(withParent: rootSavingContext);
localContext.perform {
NSLog("TIMING There are \(features.count) features to save, chunking into groups of 250")
localContext.mr_setWorkingName(#function)
var chunks = features.chunked(into: 250);
var newObservationCount = 0;
var observationToNotifyAbout: Observation?;
var eventFormDictionary: [NSNumber: [[String: AnyHashable]]] = [:]
if let event = Event.getEvent(eventId: currentEventId, context: localContext), let eventForms = event.forms {
for eventForm in eventForms {
if let formId = eventForm.formId, let json = eventForm.json?.json {
eventFormDictionary[formId] = json[FormKey.fields.key] as? [[String: AnyHashable]]
}
}
}
localContext.reset();
NSLog("TIMING we have \(chunks.count) groups to save")
while (chunks.count > 0) {
autoreleasepool {
guard let features = chunks.last else {
return;
}
chunks.removeLast();
let createObservationsDate = Date()
NSLog("TIMING creating \(features.count) observations for chunk \(chunks.count)")
for observation in features {
if let newObservation = Observation.create(feature: observation, eventForms: eventFormDictionary, context: localContext) {
newObservationCount = newObservationCount + 1;
if (!initial) {
observationToNotifyAbout = newObservation;
}
}
}
NSLog("TIMING created \(features.count) observations for chunk \(chunks.count) Elapsed: \(createObservationsDate.timeIntervalSinceNow) seconds")
}
// only save once per chunk
let localSaveDate = Date()
do {
NSLog("TIMING saving \(features.count) observations on local context")
try localContext.save()
} catch {
print("Error saving observations: \(error)")
}
NSLog("TIMING saved \(features.count) observations on local context. Elapsed \(localSaveDate.timeIntervalSinceNow) seconds")
rootSavingContext.perform {
let rootSaveDate = Date()
do {
NSLog("TIMING saving \(features.count) observations on root context")
try rootSavingContext.save()
} catch {
print("Error saving observations: \(error)")
}
NSLog("TIMING saved \(features.count) observations on root context. Elapsed \(rootSaveDate.timeIntervalSinceNow) seconds")
}
localContext.reset();
NSLog("TIMING reset the local context for chunk \(chunks.count)")
NSLog("Saved chunk \(chunks.count)")
}
NSLog("Received \(newObservationCount) new observations and send bulk is \(initial)")
if ((initial && newObservationCount > 0) || newObservationCount > 1) {
NotificationRequester.sendBulkNotificationCount(UInt(newObservationCount), in: Event.getCurrentEvent(context: localContext));
} else if let observationToNotifyAbout = observationToNotifyAbout {
NotificationRequester.observationPulled(observationToNotifyAbout);
}
NSLog("TIMING Saved Observations for event \(currentEventId). Elapsed: \(saveStart.timeIntervalSinceNow) seconds")
DispatchQueue.main.async {
success?(task, responseObject);
}
}
}, failure: { task, error in
print("Error \(error)")
failure?(task, error);
})
return task;
}
@objc public static func operationToPushObservation(observation: Observation, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error?) -> Void)?) -> URLSessionDataTask? {
let archived = (observation.state?.intValue ?? 0) == State.Archive.rawValue
if observation.remoteId != nil {
if (archived) {
return Observation.operationToDelete(observation: observation, success: success, failure: failure);
} else {
return Observation.operationToUpdate(observation: observation, success: success, failure: failure);
}
} else {
return Observation.operationToCreate(observation: observation, success: success, failure: failure);
}
}
@objc public static func operationToPushFavorite(favorite: ObservationFavorite, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? {
guard let eventId = favorite.observation?.eventId, let observationRemoteId = favorite.observation?.remoteId, let baseURL = MageServer.baseURL() else {
return nil;
}
let url = "\(baseURL.absoluteURL)/api/events/\(eventId)/observations/\(observationRemoteId)/favorite";
NSLog("Trying to push favorite to server \(url)")
let manager = MageSessionManager.shared();
if (!favorite.favorite) {
return manager?.delete_TASK(url, parameters: nil, success: success, failure: failure);
} else {
return manager?.put_TASK(url, parameters: nil, success: success, failure: failure);
}
}
@objc public static func operationToPushImportant(important: ObservationImportant, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? {
guard let eventId = important.observation?.eventId, let observationRemoteId = important.observation?.remoteId, let baseURL = MageServer.baseURL() else {
return nil;
}
let url = "\(baseURL.absoluteURL)/api/events/\(eventId)/observations/\(observationRemoteId)/important";
NSLog("Trying to push favorite to server \(url)")
let manager = MageSessionManager.shared();
if (important.important) {
let parameters: [String : String?] = [
ObservationImportantKey.description.key : important.reason
]
return manager?.put_TASK(url, parameters: parameters, success: success, failure: failure);
} else {
return manager?.delete_TASK(url, parameters: nil, success: success, failure: failure);
}
}
static func operationToDelete(observation: Observation, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error?) -> Void)?) -> URLSessionDataTask? {
NSLog("Trying to delete observation \(observation.url ?? "no url")");
let deleteMethod = MAGERoutes.observation().deleteRoute(observation);
let manager = MageSessionManager.shared();
return manager?.post_TASK(deleteMethod.route, parameters: deleteMethod.parameters, progress: nil, success: { task, responseObject in
// if the delete worked, remove the observation from the database on the phone
MagicalRecord.save { context in
observation.mr_deleteEntity(in: context);
} completion: { contextDidSave, error in
// TODO: why are we calling failure here?
// I think because the ObservationPushService is going to try to parse the response and update the observation which we do not want
failure?(task, nil);
}
}, failure: { task, error in
NSLog("Failure to delete")
let error = error as NSError
if let data = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? Data {
let errorString = String(data: data, encoding: .utf8);
NSLog("Error deleting observation \(errorString ?? "unknown error")");
if let response = task?.response as? HTTPURLResponse {
if (response.statusCode == 404) {
// Observation does not exist on the server, delete it
MagicalRecord.save { context in
observation.mr_deleteEntity(in: context);
} completion: { contextDidSave, error in
// TODO: why are we calling failure here?
// I think because the ObservationPushService is going to try to parse the response and update the observation which we do not want
failure?(task, nil);
}
}
} else {
failure?(task, error);
}
} else {
failure?(task, error);
}
});
}
static func operationToUpdate(observation: Observation, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? {
NSLog("Trying to update observation \(observation.url ?? "unknown url")")
let manager = MageSessionManager.shared();
guard let context = observation.managedObjectContext, let event = Event.getCurrentEvent(context:context) else {
return nil;
}
if (MageServer.isServerVersion5) {
if let observationUrl = observation.url {
return manager?.put_TASK(observationUrl, parameters: observation.createJsonToSubmit(event:event), success: success, failure: failure);
}
} else { //} if MageServer.isServerVersion6_0() {
if let observationUrl = observation.url {
return manager?.put_TASK(observationUrl, parameters: observation.createJsonToSubmit(event:event), success: success, failure: failure);
}
}
// else {
// // TODO: 6.1 and above
// if let observationUrl = observation.url {
// return manager?.patch_TASK(observationUrl, parameters: observation.createJsonToSubmit(event:event), success: success, failure: failure);
// }
// }
return nil;
}
static func operationToCreate(observation: Observation, success: ((URLSessionDataTask,Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> URLSessionDataTask? {
let create = MAGERoutes.observation().createId(observation);
NSLog("Trying to create observation %@", create.route);
let manager = MageSessionManager.shared();
let task = manager?.post_TASK(create.route, parameters: nil, progress: nil, success: { task, response in
NSLog("Successfully created location for observation resource");
guard let response = response as? [AnyHashable : Any], let observationUrl = response[ObservationKey.url.key] as? String, let remoteId = response[ObservationKey.id.key] as? String else {
return;
}
MagicalRecord.save { context in
guard let localObservation = observation.mr_(in: context) else {
return;
}
localObservation.remoteId = remoteId
localObservation.url = observationUrl;
} completion: { contextDidSave, error in
if !contextDidSave {
NSLog("Failed to save observation to DB after getting an ID")
}
guard let context = observation.managedObjectContext, let event = Event.getCurrentEvent(context: context) else {
return;
}
let putTask = manager?.put_TASK(observationUrl, parameters: observation.createJsonToSubmit(event:event), success: { task, response in
print("successfully submitted observation")
success?(task, response);
}, failure: { task, error in
print("failure");
});
manager?.addTask(putTask);
}
}, failure: failure)
return task;
}
func fieldNameToField(formId: NSNumber, name: String) -> [AnyHashable : Any]? {
if let managedObjectContext = managedObjectContext, let form : Form = Form.mr_findFirst(byAttribute: "formId", withValue: formId, in: managedObjectContext) {
return form.getFieldByName(name: name)
}
return nil
}
func createJsonToSubmit(event: Event) -> [AnyHashable : Any] {
var observationJson: [AnyHashable : Any] = [:]
if let remoteId = self.remoteId {
observationJson[ObservationKey.id.key] = remoteId;
}
if let userId = self.userId {
observationJson[ObservationKey.userId.key] = userId;
}
if let deviceId = self.deviceId {
observationJson[ObservationKey.deviceId.key] = deviceId;
}
if let url = self.url {
observationJson[ObservationKey.url.key] = url;
}
observationJson[ObservationKey.type.key] = "Feature";
let state = self.state?.intValue ?? State.Active.rawValue
observationJson[ObservationKey.state.key] = ["name":(State(rawValue: state) ?? .Active).description]
if let geometry = self.geometry {
observationJson[ObservationKey.geometry.key] = GeometrySerializer.serializeGeometry(geometry);
}
if let timestamp = self.timestamp {
observationJson[ObservationKey.timestamp.key] = ISO8601DateFormatter.string(from: timestamp, timeZone: TimeZone(secondsFromGMT: 0)!, formatOptions: [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone]);
}
var jsonProperties : [AnyHashable : Any] = self.properties ?? [:]
var attachmentsToDelete : [String: [String : [Attachment]]] = [:]
if (!MageServer.isServerVersion5) {
// check for attachments marked for deletion and be sure to add them to the form properties
if let attachments = attachments {
for case let attachment in attachments where attachment.markedForDeletion {
var attachmentsPerForm: [String : [Attachment]] = [:]
if let observationFormId = attachment.observationFormId, let currentAttachmentsPerForm = attachmentsToDelete[observationFormId] {
attachmentsPerForm = currentAttachmentsPerForm;
}
var attachmentsInField: [Attachment] = [];
if let fieldName = attachment.fieldName, let currentAttachmentsInField = attachmentsPerForm[fieldName] {
attachmentsInField = currentAttachmentsInField;
}
attachmentsInField.append(attachment);
if let fieldName = attachment.fieldName, let observationFormId = attachment.observationFormId {
attachmentsPerForm[fieldName] = attachmentsInField;
attachmentsToDelete[observationFormId] = attachmentsPerForm
}
}
}
}
let forms = jsonProperties[ObservationKey.forms.key] as? [[String: Any]]
var formArray: [Any] = [];
if let forms = forms {
for form in forms {
var formProperties: [String: Any] = form;
for (key, value) in form {
if let formId = form[FormKey.formId.key] as? NSNumber {
if let field = self.fieldNameToField(formId: formId, name:key) {
if let fieldType = field[FieldKey.type.key] as? String, fieldType == FieldType.geometry.key {
if let fieldGeometry = value as? SFGeometry {
formProperties[key] = GeometrySerializer.serializeGeometry(fieldGeometry);
}
} else if let fieldType = field[FieldKey.type.key] as? String, fieldType == FieldType.attachment.key {
// filter out the unsent attachemnts which are marked for deletion
var newAttachments:[[AnyHashable:Any]] = []
if let currentAttachments = formProperties[key] as? [[AnyHashable:Any]] {
for attachment in currentAttachments {
if let markedForDeletion = attachment[AttachmentKey.markedForDeletion.key] as? Int, markedForDeletion == 1 {
//skip it
} else {
newAttachments.append(attachment)
}
}
formProperties[key] = newAttachments
}
}
}
}
}
// check for deleted attachments and add them to the proper field
if let formId = form[FormKey.id.key] as? String, let attachmentsToDeleteForForm = attachmentsToDelete[formId] {
for (field, attachmentsToDeleteForField) in attachmentsToDeleteForForm {
var newAttachments: [[AnyHashable : Any]] = [];
if let value = form[field] as? [[AnyHashable : Any]] {
newAttachments = value;
}
for a in attachmentsToDeleteForField {
if let remoteId = a.remoteId {
newAttachments.append([
AttachmentKey.id.key: remoteId,
AttachmentKey.action.key: "delete"
])
}
}
formProperties[field] = newAttachments;
}
}
formArray.append(formProperties);
}
}
jsonProperties[ObservationKey.forms.key] = formArray;
observationJson[ObservationKey.properties.key] = jsonProperties;
return observationJson;
}
@objc public static func fetchLastObservationDate(context: NSManagedObjectContext) -> Date? {
let user = User.fetchCurrentUser(context: context);
if let userRemoteId = user?.remoteId, let currentEventId = Server.currentEventId() {
let observation = Observation.mr_findFirst(with: NSPredicate(format: "\(ObservationKey.eventId.key) == %@ AND user.\(UserKey.remoteId.key) != %@", currentEventId, userRemoteId), sortedBy: ObservationKey.lastModified.key, ascending: false, in:context);
return observation?.lastModified;
}
return nil;
}
@discardableResult
@objc public static func create(geometry: SFGeometry?, date: Date? = nil, accuracy: CLLocationAccuracy, provider: String?, delta: Double, context: NSManagedObjectContext) -> Observation {
var observationDate = date ?? Date();
observationDate = Calendar.current.date(bySetting: .second, value: 0, of: observationDate)!
observationDate = Calendar.current.date(bySetting: .nanosecond, value: 0, of: observationDate)!
let observation = Observation.mr_createEntity(in: context)!;
observation.timestamp = observationDate;
var properties: [AnyHashable : Any] = [:];
properties[ObservationKey.timestamp.key] = ISO8601DateFormatter.string(from: observationDate, timeZone: TimeZone(secondsFromGMT: 0)!, formatOptions: [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone])
if let geometry = geometry, let provider = provider {
properties[ObservationKey.provider.key] = provider;
if (provider != "manual") {
properties[ObservationKey.accuracy.key] = accuracy;
properties[ObservationKey.delta.key] = delta;
}
observation.geometry = geometry;
}
properties[ObservationKey.forms.key] = [];
observation.properties = properties;
observation.user = User.fetchCurrentUser(context: context);
observation.dirty = false;
observation.state = NSNumber(value: State.Active.rawValue)
observation.eventId = Server.currentEventId();
return observation;
}
static func idFromJson(json: [AnyHashable : Any]) -> String? {
return json[ObservationKey.id.key] as? String
}
static func stateFromJson(json: [AnyHashable : Any]) -> State {
if let stateJson = json[ObservationKey.state.key] as? [AnyHashable : Any], let stateName = stateJson["name"] as? String {
if stateName == State.Archive.description {
return State.Archive
} else {
return State.Active;
}
}
return State.Active;
}
@discardableResult
@objc public static func create(feature: [AnyHashable : Any], eventForms: [NSNumber: [[String: AnyHashable]]]? = nil, context:NSManagedObjectContext) -> Observation? {
var newObservation: Observation? = nil;
let remoteId = Observation.idFromJson(json: feature);
let state = Observation.stateFromJson(json: feature);
// NSLog("TIMING create the observation \(remoteId)")
if let remoteId = remoteId, let existingObservation = Observation.mr_findFirst(byAttribute: ObservationKey.remoteId.key, withValue: remoteId, in: context) {
// if the observation is archived, delete it
if state == .Archive {
NSLog("Deleting archived observation with id: %@", remoteId);
existingObservation.mr_deleteEntity(in: context);
} else if !existingObservation.isDirty {
// if the observation is not dirty, and has been updated, update it
if let lastModified = feature[ObservationKey.lastModified.key] as? String {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone];
formatter.timeZone = TimeZone(secondsFromGMT: 0)!;
let lastModifiedDate = formatter.date(from: lastModified) ?? Date();
if lastModifiedDate == existingObservation.lastModified {
// If the last modified date for this observation has not changed no need to update.
return newObservation
}
}
existingObservation.populate(json: feature, eventForms: eventForms);
if let userId = existingObservation.userId {
if let user = User.mr_findFirst(byAttribute: ObservationKey.remoteId.key, withValue: userId, in: context) {
existingObservation.user = user
if user.lastUpdated == nil {
// new user, go fetch
let manager = MageSessionManager.shared();
let fetchUserTask = User.operationToFetchUser(userId: userId) { task, response in
NSLog("Fetched user \(userId) successfully.")
} failure: { task, error in
NSLog("Failed to fetch user \(userId) error \(error)")
}
manager?.addTask(fetchUserTask)
}
} else {
// new user, go fetch
let manager = MageSessionManager.shared();
let fetchUserTask = User.operationToFetchUser(userId: userId) { task, response in
NSLog("Fetched user \(userId) successfully.")
existingObservation.user = User.mr_findFirst(byAttribute: ObservationKey.remoteId.key, withValue: userId, in: context)
} failure: { task, error in
NSLog("Failed to fetch user \(userId) error \(error)")
}
manager?.addTask(fetchUserTask)
}
}
if let importantJson = feature[ObservationKey.important.key] as? [String : Any] {
if let important = ObservationImportant.important(json: importantJson, context: context) {
important.observation = existingObservation;
existingObservation.observationImportant = important;
}
} else if let existingObservationImportant = existingObservation.observationImportant {
existingObservationImportant.mr_deleteEntity(in: context);
existingObservation.observationImportant = nil;
}
let favoritesMap = existingObservation.favoritesMap;
let favoriteUserIds = (feature[ObservationKey.favoriteUserIds.key] as? [String]) ?? []
for favoriteUserId in favoriteUserIds {
if favoritesMap[favoriteUserId] == nil {
if let favorite = ObservationFavorite.favorite(userId: favoriteUserId, context: context) {
favorite.observation = existingObservation;
existingObservation.addToFavorites(favorite);
}
}
}
for (userId, favorite) in favoritesMap {
if !favoriteUserIds.contains(userId) {
favorite.mr_deleteEntity(in: context);
existingObservation.removeFromFavorites(favorite);
}
}
if let attachmentsJson = feature[ObservationKey.attachments.key] as? [[AnyHashable : Any]] {
for (index, attachmentJson) in attachmentsJson.enumerated() {
var attachmentFound = false;
if let remoteId = attachmentJson[AttachmentKey.id.key] as? String, let attachments = existingObservation.attachments {
for attachment in attachments {
if remoteId == attachment.remoteId {
attachment.contentType = attachmentJson[AttachmentKey.contentType.key] as? String
attachment.name = attachmentJson[AttachmentKey.name.key] as? String
attachment.size = attachmentJson[AttachmentKey.size.key] as? NSNumber
attachment.url = attachmentJson[AttachmentKey.url.key] as? String
attachment.remotePath = attachmentJson[AttachmentKey.remotePath.key] as? String
attachment.observation = existingObservation;
attachment.order = NSNumber(value: index)
attachmentFound = true;
break;
}
}
}
if !attachmentFound {
if let attachment = Attachment.attachment(json: attachmentJson, order: index, context: context) {
existingObservation.addToAttachments(attachment);
}
}
}
}
}
} else {
if state != .Archive {
// if the observation doesn't exist, insert it
if let observation = Observation.mr_createEntity(in: context) {
observation.populate(json: feature, eventForms: eventForms);
if let userId = observation.userId {
if let user = User.mr_findFirst(byAttribute: UserKey.remoteId.key, withValue: userId, in: context) {
observation.user = user
// this could happen if we pulled the teams and know this user belongs on a team
// but did not pull the user information because the bulk user pull failed
if user.lastUpdated == nil {
// new user, go fetch
let manager = MageSessionManager.shared();
let fetchUserTask = User.operationToFetchUser(userId: userId) { task, response in
NSLog("Fetched user \(userId) successfully.")
} failure: { task, error in
NSLog("Failed to fetch user \(userId) error \(error)")
}
manager?.addTask(fetchUserTask)
}
} else {
// new user, go fetch
let manager = MageSessionManager.shared();
let fetchUserTask = User.operationToFetchUser(userId: userId) { task, response in
NSLog("Fetched user \(userId) successfully.")
observation.user = User.mr_findFirst(byAttribute: ObservationKey.remoteId.key, withValue: userId, in: context)
} failure: { task, error in
NSLog("Failed to fetch user \(userId) error \(error)")
}
manager?.addTask(fetchUserTask)
}
}
if let importantJson = feature[ObservationKey.important.key] as? [String : Any] {
if let important = ObservationImportant.important(json: importantJson, context: context) {
important.observation = observation;
observation.observationImportant = important;
}
}
if let favoriteUserIds = feature[ObservationKey.favoriteUserIds.key] as? [String] {
for favoriteUserId in favoriteUserIds {
if let favorite = ObservationFavorite.favorite(userId: favoriteUserId, context: context) {
favorite.observation = observation;
observation.addToFavorites(favorite);
}
}
}
if let attachmentsJson = feature[ObservationKey.attachments.key] as? [[AnyHashable : Any]] {
for (index, attachmentJson) in attachmentsJson.enumerated() {
if let attachment = Attachment.attachment(json: attachmentJson, order: index, context: context) {
observation.addToAttachments(attachment);
}
}
}
newObservation = observation;
}
}
}
return newObservation;
}
@objc public static func isRectangle(points: [SFPoint]) -> Bool {
let size = points.count
if size == 4 || size == 5 {
let point1 = points[0]
let lastPoint = points[size - 1]
let closed: Bool = point1.x == lastPoint.x && point1.y == lastPoint.y;
if ((closed && size == 5) || (!closed && size == 4)) {
let point2 = points[1]
let point3 = points[2]
let point4 = points[3]
if ((point1.x == point2.x) && (point2.y == point3.y)) {
if ((point1.y == point4.y) && (point3.x == point4.x)) {
return true;
}
} else if ((point1.y == point2.y) && (point2.x == point3.x)) {
if ((point1.x == point4.x) && (point3.y == point4.y)) {
return true;
}
}
}
}
return false;
}
@discardableResult
@objc public func populate(json: [AnyHashable : Any], eventForms: [NSNumber: [[String: AnyHashable]]]? = nil) -> Observation {
self.eventId = json[ObservationKey.eventId.key] as? NSNumber
self.remoteId = Observation.idFromJson(json: json);
self.userId = json[ObservationKey.userId.key] as? String
self.deviceId = json[ObservationKey.deviceId.key] as? String
self.dirty = false
if let properties = json[ObservationKey.properties.key] as? [String : Any] {
self.properties = self.generateProperties(propertyJson: properties, eventForms: eventForms);
}
if let lastModified = json[ObservationKey.lastModified.key] as? String {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone];
formatter.timeZone = TimeZone(secondsFromGMT: 0)!;
self.lastModified = formatter.date(from: lastModified);
}
if let timestamp = self.properties?[ObservationKey.timestamp.key] as? String {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone];
formatter.timeZone = TimeZone(secondsFromGMT: 0)!;
self.timestamp = formatter.date(from: timestamp);
}
self.url = json[ObservationKey.url.key] as? String
let state = Observation.stateFromJson(json: json);
self.state = NSNumber(value: state.rawValue)
self.geometry = GeometryDeserializer.parseGeometry(json: json[ObservationKey.geometry.key] as? [AnyHashable : Any])
return self;
}
func generateProperties(propertyJson: [String : Any], eventForms: [NSNumber: [[String: AnyHashable]]]? = nil) -> [AnyHashable : Any] {
var parsedProperties: [String : Any] = [:]
if self.event == nil {
return parsedProperties;
}
for (key, value) in propertyJson {
if key == ObservationKey.forms.key {
var forms:[[String : Any]] = []
if let formsProperties = value as? [[String : Any]] {
for formProperties in formsProperties {
var parsedFormProperties:[String:Any] = formProperties;
if let formId = formProperties[EventKey.formId.key] as? NSNumber {
var formFields: [[String: AnyHashable]]? = nil
if let eventForms = eventForms {
formFields = eventForms[formId]
} else if let managedObjectContext = managedObjectContext, let fetchedForm : Form = Form.mr_findFirst(byAttribute: "formId", withValue: formId, in: managedObjectContext) {
formFields = fetchedForm.json?.json?[FormKey.fields.key] as? [[String: AnyHashable]]
}
if let formFields = formFields {
for (formKey, value) in formProperties {
if let field = Form.getFieldByNameFromJSONFields(json: formFields, name: formKey) {
if let type = field[FieldKey.type.key] as? String, type == FieldType.geometry.key {
if let value = value as? [String: Any] {
let geometry = GeometryDeserializer.parseGeometry(json: value)
parsedFormProperties[formKey] = geometry;
}
}
}
}
}
forms.append(parsedFormProperties);
}
}
}
parsedProperties[ObservationKey.forms.key] = forms;
} else {
parsedProperties[key] = value;
}
}
return parsedProperties;
}
@objc public func addTransientAttachment(attachment: Attachment) {
self.transientAttachments.append(attachment);
}
@objc public var transientAttachments: [Attachment] = [];
@objc public var geometry: SFGeometry? {
get {
if let geometryData = self.geometryData {
return SFGeometryUtils.decodeGeometry(geometryData);
}
return nil
}
set {
if let newValue = newValue {
self.geometryData = SFGeometryUtils.encode(newValue);
} else {
self.geometryData = nil
}
}
}
@objc public var location: CLLocation? {
get {
if let geometry = geometry, let centroid = SFGeometryUtils.centroid(of: geometry) {
return CLLocation(latitude: centroid.y.doubleValue, longitude: centroid.x.doubleValue);
}
return CLLocation(latitude: 0, longitude: 0);
}
}
@objc public var isDirty: Bool {
get {
return self.dirty
}
}
@objc public var isImportant: Bool {
get {
if let observationImportant = self.observationImportant, observationImportant.important {
return true;
}
return false;
}
}
@objc public var isDeletableByCurrentUser: Bool {
get {
guard let managedObjectContext = self.managedObjectContext,
let currentUser = User.fetchCurrentUser(context: managedObjectContext),
let event = self.event else {
return false;
}
// if the user has update on the event
if let userRemoteId = currentUser.remoteId,
let acl = event.acl,
let userAcl = acl[userRemoteId] as? [String : Any],
let userPermissions = userAcl[PermissionsKey.permissions.key] as? [String] {
if (userPermissions.contains(PermissionsKey.update.key)) {
return true;
}
}
// if the user has DELETE_OBSERVATION permission
if let role = currentUser.role, let rolePermissions = role.permissions {
if rolePermissions.contains(PermissionsKey.DELETE_OBSERVATION.key) {
return true;
}
}
// If the observation was created by this user
if let userRemoteId = currentUser.remoteId, let user = self.user {
if userRemoteId == user.remoteId {
return true;
}
}
return false;
}
}
@objc public var currentUserCanUpdateImportant: Bool {
get {
guard let managedObjectContext = self.managedObjectContext,
let currentUser = User.fetchCurrentUser(context: managedObjectContext),
let event = self.event else {
return false;
}
// if the user has update on the event
if let userRemoteId = currentUser.remoteId,
let acl = event.acl,
let userAcl = acl[userRemoteId] as? [String : Any],
let userPermissions = userAcl[PermissionsKey.permissions.key] as? [String] {
if (userPermissions.contains(PermissionsKey.update.key)) {
return true;
}
}
// if the user has UPDATE_EVENT permission
if let role = currentUser.role, let rolePermissions = role.permissions {
if rolePermissions.contains(PermissionsKey.UPDATE_EVENT.key) {
return true;
}
}
return false;
}
}
var event : Event? {
get {
if let eventId = self.eventId, let managedObjectContext = self.managedObjectContext {
return Event.getEvent(eventId: eventId, context: managedObjectContext)
}
return nil;
}
}
@objc public var hasValidationError: Bool {
get {
if let error = self.error {
return error[ObservationPushService.ObservationErrorStatusCode] != nil
}
return false;
}
}
@objc public var errorMessage: String {
get {
if let error = self.error {
if let errorMessage = error[ObservationPushService.ObservationErrorMessage] as? String {
return errorMessage
} else if let errorMessage = error[ObservationPushService.ObservationErrorDescription] as? String {
return errorMessage
}
}
return "";
}
}
@objc public var formsToBeDeleted: NSMutableIndexSet = NSMutableIndexSet()
@objc public func clearFormsToBeDeleted() {
formsToBeDeleted = NSMutableIndexSet()
}
@objc public func addFormToBeDeleted(formIndex: Int) {
self.formsToBeDeleted.add(formIndex);
}
@objc public func removeFormToBeDeleted(formIndex: Int) {
self.formsToBeDeleted.remove(formIndex);
}
@objc public var primaryObservationForm: [AnyHashable : Any]? {
get {
if let properties = self.properties, let forms = properties[ObservationKey.forms.key] as? [[AnyHashable:Any]] {
for (index, form) in forms.enumerated() {
// here we can ignore forms which will be deleted
if !self.formsToBeDeleted.contains(index) {
return form;
}
}
}
return nil
}
}
@objc public var primaryEventForm: Form? {
get {
if let primaryObservationForm = primaryObservationForm, let formId = primaryObservationForm[EventKey.formId.key] as? NSNumber {
return Form.mr_findFirst(byAttribute: "formId", withValue: formId, in: managedObjectContext ?? NSManagedObjectContext.mr_default())
}
return nil;
}
}
@objc public var primaryField: String? {
get {
if let primaryEventForm = primaryEventForm {
return primaryEventForm.primaryMapField?[FieldKey.name.key] as? String
}
return nil
}
}
@objc public var secondaryField: String? {
get {
if let primaryEventForm = primaryEventForm {
return primaryEventForm.secondaryMapField?[FieldKey.name.key] as? String
}
return nil
}
}
@objc public var primaryFieldText: String? {
get {
if let primaryField = primaryEventForm?.primaryMapField, let observationForms = self.properties?[ObservationKey.forms.key] as? [[AnyHashable : Any]], let primaryFieldName = primaryField[FieldKey.name.key] as? String, observationForms.count > 0 {
let value = self.primaryObservationForm?[primaryFieldName]
return Observation.fieldValueText(value: value, field: primaryField)
}
return nil;
}
}
@objc public var secondaryFieldText: String? {
get {
if let variantField = primaryEventForm?.secondaryMapField, let observationForms = self.properties?[ObservationKey.forms.key] as? [[AnyHashable : Any]], let variantFieldName = variantField[FieldKey.name.key] as? String, observationForms.count > 0 {
let value = self.primaryObservationForm?[variantFieldName]
return Observation.fieldValueText(value: value, field: variantField)
}
return nil;
}
}
@objc public var primaryFeedFieldText: String? {
get {
if let primaryFeedField = primaryEventForm?.primaryFeedField, let observationForms = self.properties?[ObservationKey.forms.key] as? [[AnyHashable : Any]], let primaryFeedFieldName = primaryFeedField[FieldKey.name.key] as? String, observationForms.count > 0 {
let value = primaryObservationForm?[primaryFeedFieldName]
return Observation.fieldValueText(value: value, field: primaryFeedField)
}
return nil;
}
}
@objc public var secondaryFeedFieldText: String? {
get {
if let secondaryFeedField = primaryEventForm?.secondaryFeedField, let observationForms = self.properties?[ObservationKey.forms.key] as? [[AnyHashable : Any]], let secondaryFeedFieldName = secondaryFeedField[FieldKey.name.key] as? String, observationForms.count > 0 {
let value = self.primaryObservationForm?[secondaryFeedFieldName]
return Observation.fieldValueText(value: value, field: secondaryFeedField)
}
return nil;
}
}
@objc public static func fieldValueText(value: Any?, field: [AnyHashable : Any]) -> String {
guard let value = value, let type = field[FieldKey.type.key] as? String else {
return "";
}
if type == FieldType.geometry.key {
var geometry: SFGeometry?;
if let valueDictionary = value as? [AnyHashable : Any] {
geometry = GeometryDeserializer.parseGeometry(json: valueDictionary);
} else {
geometry = value as? SFGeometry
}
if let geometry = geometry, let centroid = SFGeometryUtils.centroid(of: geometry) {
return "\(String(format: "%.6f", centroid.y.doubleValue)), \(String(format: "%.6f", centroid.x.doubleValue))"
}
} else if type == FieldType.date.key {
if let value = value as? String {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withDashSeparatorInDate, .withFullDate, .withFractionalSeconds, .withTime, .withColonSeparatorInTime, .withTimeZone];
formatter.timeZone = TimeZone(secondsFromGMT: 0)!;
let date = formatter.date(from: value);
return (date as NSDate?)?.formattedDisplay() ?? "";
}
} else if type == FieldType.checkbox.key {
if let value = value as? Bool {
if value {
return "YES"
} else {
return "NO"
}
} else if let value = value as? NSNumber {
if value == 1 {
return "YES"
} else {
return "NO"
}
}
} else if type == FieldType.numberfield.key {
return String(describing:value);
} else if type == FieldType.multiselectdropdown.key {
if let value = value as? [String] {
return value.joined(separator: ", ")
}
} else if (type == FieldType.textfield.key ||
type == FieldType.textarea.key ||
type == FieldType.email.key ||
type == FieldType.password.key ||
type == FieldType.radio.key ||
type == FieldType.dropdown.key) {
if let value = value as? String {
return value;
}
}
return "";
}
@objc public func toggleFavorite(completion:((Bool,Error?) -> Void)?) {
MagicalRecord.save({ [weak self] localContext in
if let localObservation = self?.mr_(in: localContext),
let user = User.fetchCurrentUser(context: localContext),
let userRemoteId = user.remoteId {
if let favorite = localObservation.favoritesMap[userRemoteId], favorite.favorite {
// toggle off
favorite.dirty = true;
favorite.favorite = false
} else {
// toggle on
if let favorite = localObservation.favoritesMap[userRemoteId] {
favorite.dirty = true;
favorite.favorite = true
favorite.userId = userRemoteId
} else {
if let favorite = ObservationFavorite.mr_createEntity(in: localContext) {
localObservation.addToFavorites(favorite);
favorite.observation = localObservation;
favorite.dirty = true;
favorite.favorite = true
favorite.userId = userRemoteId
}
}
}
}
}, completion: completion)
}
@objc public var favoritesMap: [String : ObservationFavorite] {
get {
var favoritesMap: [String:ObservationFavorite] = [:]
if let favorites = self.favorites {
for favorite in favorites {
if let userId = favorite.userId {
favoritesMap[userId] = favorite
}
}
}
return favoritesMap
}
}
@objc public func flagImportant(description: String, completion:((Bool,Error?) -> Void)?) {
if !self.currentUserCanUpdateImportant {
completion?(false, nil);
return;
}
MagicalRecord.save({ [weak self] localContext in
if let localObservation = self?.mr_(in: localContext),
let user = User.fetchCurrentUser(context: localContext),
let userRemoteId = user.remoteId {
if let important = self?.observationImportant {
important.dirty = true;
important.important = true;
important.userId = userRemoteId;
important.reason = description
// this will get overridden by the server, but let's set an initial value so the UI has something to display
important.timestamp = Date();
} else {
if let important = ObservationImportant.mr_createEntity(in: localContext) {
important.observation = localObservation
localObservation.observationImportant = important;
important.dirty = true;
important.important = true;
important.userId = userRemoteId;
important.reason = description
// this will get overridden by the server, but let's set an initial value so the UI has something to display
important.timestamp = Date();
}
}
}
}, completion: completion)
}
@objc public func removeImportant(completion:((Bool,Error?) -> Void)?) {
if !self.currentUserCanUpdateImportant {
completion?(false, nil);
return;
}
MagicalRecord.save({ [weak self] localContext in
if let localObservation = self?.mr_(in: localContext),
let user = User.fetchCurrentUser(context: localContext),
let userRemoteId = user.remoteId {
if let important = self?.observationImportant {
important.dirty = true;
important.important = false;
important.userId = userRemoteId;
important.reason = nil
// this will get overridden by the server, but let's set an initial value so the UI has something to display
important.timestamp = Date();
} else {
if let important = ObservationImportant.mr_createEntity(in: localContext) {
important.observation = localObservation
localObservation.observationImportant = important;
important.dirty = true;
important.important = false;
important.userId = userRemoteId;
important.reason = nil
// this will get overridden by the server, but let's set an initial value so the UI has something to display
important.timestamp = Date();
}
}
}
}, completion: completion)
}
@objc public func delete(completion:((Bool,Error?) -> Void)?) {
if !self.isDeletableByCurrentUser {
completion?(false, nil);
return;
}
if self.remoteId != nil {
self.state = NSNumber(value: State.Archive.rawValue)
self.dirty = true
self.managedObjectContext?.mr_saveToPersistentStore(completion: completion)
} else {
MagicalRecord.save({ [weak self] localContext in
self?.mr_deleteEntity(in: localContext);
}, completion: completion)
}
}
}
|
apache-2.0
|
f732586b385e191fdc0f420386368514
| 48.98597 | 280 | 0.545609 | 5.605454 | false | false | false | false |
telip007/ChatFire
|
Pods/SwiftMessages/SwiftMessages/BaseView.swift
|
2
|
6176
|
//
// BaseView.swift
// SwiftMessages
//
// Created by Timothy Moose on 8/17/16.
// Copyright © 2016 SwiftKick Mobile LLC. All rights reserved.
//
import UIKit
/*
The `BaseView` class is a reusable message view base class that implements some
of the optional SwiftMessages protocols and provides some convenience functions
and a configurable tap handler. Message views do not need to inherit from `BaseVew`.
*/
public class BaseView: UIView, BackgroundViewable, MarginAdjustable {
/*
MARK: - IB outlets
*/
/**
Fulfills the `BackgroundViewable` protocol and is the target for
the optional `tapHandler` block. Defaults to `self`.
*/
@IBOutlet public var backgroundView: UIView! {
didSet {
if let old = oldValue {
old.removeGestureRecognizer(tapRecognizer)
}
installTapRecognizer()
}
}
// The `contentView` property was removed because it no longer had any functionality
// in the framework. This is a minor backwards incompatible change. If you've copied
// one of the included nib files from a previous release, you may get a key-value
// coding runtime error related to contentView, in which case you can subclass the
// view and add a `contentView` property or you can remove the outlet connection in
// Interface Builder.
// @IBOutlet public var contentView: UIView!
/*
MARK: - Initialization
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundView = self
}
public override init(frame: CGRect) {
super.init(frame: frame)
backgroundView = self
}
public override func awakeFromNib() {
layoutMargins = UIEdgeInsetsZero
}
/*
MARK: - Installing content
*/
/**
A convenience function for installing a content view as a subview of `backgroundView`
and pinning the edges to `backgroundView` with the specified `insets`.
- Parameter contentView: The view to be installed into the background view
and assigned to the `contentView` property.
- Parameter insets: The amount to inset the content view from the background view.
Default is zero inset.
*/
public func installContentView(contentView: UIView, insets: UIEdgeInsets = UIEdgeInsetsZero) {
contentView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.addSubview(contentView)
let top = NSLayoutConstraint(item: contentView, attribute: .Top, relatedBy: .Equal, toItem: backgroundView, attribute: .TopMargin, multiplier: 1.0, constant: insets.top)
let left = NSLayoutConstraint(item: contentView, attribute: .Left, relatedBy: .Equal, toItem: backgroundView, attribute: .LeftMargin, multiplier: 1.0, constant: insets.left)
let bottom = NSLayoutConstraint(item: contentView, attribute: .Bottom, relatedBy: .Equal, toItem: backgroundView, attribute: .BottomMargin, multiplier: 1.0, constant: -insets.bottom)
let right = NSLayoutConstraint(item: contentView, attribute: .Right, relatedBy: .Equal, toItem: backgroundView, attribute: .RightMargin, multiplier: 1.0, constant: -insets.right)
backgroundView.addConstraints([top, left, bottom, right])
}
/*
MARK: - Tap handler
*/
/**
An optional tap handler that will be called when the `backgroundView` is tapped.
*/
public var tapHandler: ((view: BaseView) -> Void)? {
didSet {
installTapRecognizer()
}
}
private lazy var tapRecognizer: UITapGestureRecognizer = {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MessageView.tapped))
return tapRecognizer
}()
func tapped() {
tapHandler?(view: self)
}
private func installTapRecognizer() {
guard let backgroundView = backgroundView else { return }
backgroundView.removeGestureRecognizer(tapRecognizer)
if tapHandler != nil {
// Only install the tap recognizer if there is a tap handler,
// which makes it slightly nicer if one wants to install
// a custom gesture recognizer.
backgroundView.addGestureRecognizer(tapRecognizer)
}
}
/*
MARK: - MarginAdjustable
These properties fulfill the `MarginAdjustable` protocol and are exposed
as `@IBInspectables` so that they can be adjusted directly in nib files
(see MessageView.nib).
*/
@IBInspectable public var bounceAnimationOffset: CGFloat = 5.0
@IBInspectable public var statusBarOffset: CGFloat = 20.0
/*
MARK: - Setting preferred height
*/
/**
An optional value that sets the message view's intrinsic content height.
This can be used as a way to specify a fixed height for the message view.
Note that this height is not guaranteed depending on anyt Auto Layout
constraints used within the message view.
*/
public var preferredHeight: CGFloat? {
didSet {
setNeedsLayout()
}
}
public override func intrinsicContentSize() -> CGSize {
if let preferredHeight = preferredHeight {
return CGSizeMake(UIViewNoIntrinsicMetric, preferredHeight)
}
return super.intrinsicContentSize()
}
}
/*
MARK: - Theming
*/
extension BaseView {
/// A convenience function to configure a default drop shadow effect.
public func configureDropShadow() {
let layer = backgroundView.layer
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
layer.shadowRadius = 6.0
layer.shadowOpacity = 0.4
layer.masksToBounds = false
updateShadowPath()
}
private func updateShadowPath() {
layer.shadowPath = UIBezierPath(roundedRect: layer.bounds, cornerRadius: layer.cornerRadius).CGPath
}
public override func layoutSubviews() {
super.layoutSubviews()
updateShadowPath()
}
}
|
apache-2.0
|
43cb48d195e90add8022c2e6392f4c86
| 33.497207 | 190 | 0.662672 | 5.189076 | false | false | false | false |
lexrus/LexNightmare
|
LexNightmare/GameViewController.swift
|
1
|
3079
|
//
// GameViewController.swift
// LexNightmare
//
// Created by Lex Tang on 3/12/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
import SpriteKit
import GameKit
class GameViewController: UIViewController, GameSceneDelegate, GKGameCenterControllerDelegate {
@IBOutlet weak var sleepButton: UIButton!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var leaderboardButton: UIButton!
@IBOutlet weak var muteButton: UIButton!
@IBOutlet weak var skView: SKView!
@IBOutlet weak var controlPanel: UIView!
@IBOutlet weak var scoreLabel: UILabel!
var _leaderboardID = ""
var _gameCenterEnabled = false
var _currentScore: UInt64 = 0
lazy var scene: GameScene = {
let s = GameScene()
s.gameDelegate = self
return s
}()
override func viewDidLoad() {
super.viewDidLoad()
authenticateLocalPlayer()
skView.ignoresSiblingOrder = true
skView.presentScene(scene)
controlPanel.alpha = 0
muteButton.selected = GameDefaults.sharedDefaults.mute
leaderboardButton.titleLabel!.text = NSLocalizedString("Leaderboard", comment: "Game Center Leaderboard")
sleepButton.titleLabel!.text = NSLocalizedString("Sleep", comment: "Sleep again button")
shareButton.titleLabel!.text = NSLocalizedString("Share", comment: "Share button title")
muteButton.titleLabel!.text = NSLocalizedString("Mute", comment: "Mute button title")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
scene.size = skView.bounds.size
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func prefersStatusBarHidden() -> Bool {
return true
}
@IBAction func restart(sender: UIButton) {
controlPanel.alpha = 0
removeSnapshot()
scene.restart()
}
@IBAction func didTapMuteButton(sender: UIButton) {
sender.selected = !sender.selected
GameDefaults.sharedDefaults.mute = sender.selected
}
func gameDidOver(score: Int64) {
_currentScore = UInt64(score)
scoreLabel.text = "\(score)'"
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.8 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.clearWithSnapshot()
UIView.animateWithDuration(0.4) {
self.controlPanel.alpha = 1.0
}
}
reportScore(Int64(score))
}
@IBAction func showLeaderboard(sender: UIButton) {
showLeaderboardAndAchievements(true)
}
}
|
mit
|
01284c280ebd976e05a8e95660f9684f
| 28.893204 | 113 | 0.636246 | 4.958132 | false | false | false | false |
Harry-L/5-3-1
|
ios-charts-master/Charts/Classes/Renderers/ScatterChartRenderer.swift
|
3
|
11091
|
//
// ScatterChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class ScatterChartRenderer: LineScatterCandleRadarChartRenderer
{
public weak var dataProvider: ScatterChartDataProvider?
public init(dataProvider: ScatterChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
public override func drawData(context context: CGContext)
{
guard let scatterData = dataProvider?.scatterData else { return }
for (var i = 0; i < scatterData.dataSetCount; i++)
{
guard let set = scatterData.getDataSetByIndex(i) else { continue }
if set.isVisible
{
if !(set is IScatterChartDataSet)
{
fatalError("Datasets for ScatterChartRenderer must conform to IScatterChartDataSet")
}
drawDataSet(context: context, dataSet: set as! IScatterChartDataSet)
}
}
}
private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint())
public func drawDataSet(context context: CGContext, dataSet: IScatterChartDataSet)
{
guard let
dataProvider = dataProvider,
animator = animator
else { return }
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let phaseY = animator.phaseY
let entryCount = dataSet.entryCount
let shapeSize = dataSet.scatterShapeSize
let shapeHalf = shapeSize / 2.0
var point = CGPoint()
let valueToPixelMatrix = trans.valueToPixelMatrix
let shape = dataSet.scatterShape
CGContextSaveGState(context)
for (var j = 0, count = Int(min(ceil(CGFloat(entryCount) * animator.phaseX), CGFloat(entryCount))); j < count; j++)
{
guard let e = dataSet.entryForIndex(j) else { continue }
point.x = CGFloat(e.xIndex)
point.y = CGFloat(e.value) * phaseY
point = CGPointApplyAffineTransform(point, valueToPixelMatrix);
if (!viewPortHandler.isInBoundsRight(point.x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(point.x) || !viewPortHandler.isInBoundsY(point.y))
{
continue
}
if (shape == .Square)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
var rect = CGRect()
rect.origin.x = point.x - shapeHalf
rect.origin.y = point.y - shapeHalf
rect.size.width = shapeSize
rect.size.height = shapeSize
CGContextFillRect(context, rect)
}
else if (shape == .Circle)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
var rect = CGRect()
rect.origin.x = point.x - shapeHalf
rect.origin.y = point.y - shapeHalf
rect.size.width = shapeSize
rect.size.height = shapeSize
CGContextFillEllipseInRect(context, rect)
}
else if (shape == .Cross)
{
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor)
_lineSegments[0].x = point.x - shapeHalf
_lineSegments[0].y = point.y
_lineSegments[1].x = point.x + shapeHalf
_lineSegments[1].y = point.y
CGContextStrokeLineSegments(context, _lineSegments, 2)
_lineSegments[0].x = point.x
_lineSegments[0].y = point.y - shapeHalf
_lineSegments[1].x = point.x
_lineSegments[1].y = point.y + shapeHalf
CGContextStrokeLineSegments(context, _lineSegments, 2)
}
else if (shape == .Triangle)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
// create a triangle path
CGContextBeginPath(context)
CGContextMoveToPoint(context, point.x, point.y - shapeHalf)
CGContextAddLineToPoint(context, point.x + shapeHalf, point.y + shapeHalf)
CGContextAddLineToPoint(context, point.x - shapeHalf, point.y + shapeHalf)
CGContextClosePath(context)
CGContextFillPath(context)
}
else if (shape == .Custom)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
let customShape = dataSet.customScatterShape
if customShape == nil
{
return
}
// transform the provided custom path
CGContextSaveGState(context)
CGContextTranslateCTM(context, point.x, point.y)
CGContextBeginPath(context)
CGContextAddPath(context, customShape)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
}
CGContextRestoreGState(context)
}
public override func drawValues(context context: CGContext)
{
guard let
dataProvider = dataProvider,
scatterData = dataProvider.scatterData,
animator = animator
else { return }
// if values are drawn
if (scatterData.yValCount < Int(ceil(CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX)))
{
guard let dataSets = scatterData.dataSets as? [IScatterChartDataSet] else { return }
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var pt = CGPoint()
for (var i = 0; i < scatterData.dataSetCount; i++)
{
let dataSet = dataSets[i]
if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0
{
continue
}
let valueFont = dataSet.valueFont
let valueTextColor = dataSet.valueTextColor
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let entryCount = dataSet.entryCount
let shapeSize = dataSet.scatterShapeSize
let lineHeight = valueFont.lineHeight
for (var j = 0, count = Int(ceil(CGFloat(entryCount) * phaseX)); j < count; j++)
{
guard let e = dataSet.entryForIndex(j) else { break }
pt.x = CGFloat(e.xIndex)
pt.y = CGFloat(e.value) * phaseY
pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
// make sure the lines don't do shitty things outside bounds
if ((!viewPortHandler.isInBoundsLeft(pt.x)
|| !viewPortHandler.isInBoundsY(pt.y)))
{
continue
}
let text = formatter.stringFromNumber(e.value)
ChartUtils.drawText(
context: context,
text: text!,
point: CGPoint(
x: pt.x,
y: pt.y - shapeSize - lineHeight),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor])
}
}
}
}
public override func drawExtras(context context: CGContext)
{
}
private var _highlightPointBuffer = CGPoint()
public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight])
{
guard let
dataProvider = dataProvider,
scatterData = dataProvider.scatterData,
animator = animator
else { return }
let chartXMax = dataProvider.chartXMax
CGContextSaveGState(context)
for (var i = 0; i < indices.count; i++)
{
guard let set = scatterData.getDataSetByIndex(indices[i].dataSetIndex) as? IScatterChartDataSet else { continue }
if !set.isHighlightEnabled
{
continue
}
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor)
CGContextSetLineWidth(context, set.highlightLineWidth)
if (set.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let xIndex = indices[i].xIndex; // get the x-position
if (CGFloat(xIndex) > CGFloat(chartXMax) * animator.phaseX)
{
continue
}
let yVal = set.yValForXIndex(xIndex)
if (yVal.isNaN)
{
continue
}
let y = CGFloat(yVal) * animator.phaseY; // get the y-position
_highlightPointBuffer.x = CGFloat(xIndex)
_highlightPointBuffer.y = y
let trans = dataProvider.getTransformer(set.axisDependency)
trans.pointValueToPixel(&_highlightPointBuffer)
// draw the lines
drawHighlightLines(context: context, point: _highlightPointBuffer, set: set)
}
CGContextRestoreGState(context)
}
}
|
mit
|
cbb165dc376ed2ef7f768d5ea405f4c4
| 34.89644 | 141 | 0.517266 | 6.244932 | false | false | false | false |
lukejmann/FBLA2017
|
Pods/Presentr/Presentr/Presentr.swift
|
1
|
10167
|
//
// Presentr.swift
// Presentr
//
// Created by Daniel Lozano on 5/10/16.
// Copyright © 2016 Icalia Labs. All rights reserved.
//
import Foundation
import UIKit
struct PresentrConstants {
struct Values {
static let defaultSideMargin: Float = 30.0
static let defaultHeightPercentage: Float = 0.66
}
struct Strings {
static let alertTitle = "Alert"
static let alertBody = "This is an alert."
}
}
public enum DismissSwipeDirection {
case `default`
case bottom
case top
}
// MARK: - PresentrDelegate
/**
The 'PresentrDelegate' protocol defines methods that you use to respond to changes from the 'PresentrController'. All of the methods of this protocol are optional.
*/
@objc public protocol PresentrDelegate {
/**
Asks the delegate if it should dismiss the presented controller on the tap of the outer chrome view.
Use this method to validate requirments or finish tasks before the dismissal of the presented controller.
After things are wrapped up and verified it may be good to dismiss the presented controller automatically so the user does't have to close it again.
- parameter keyboardShowing: Whether or not the keyboard is currently being shown by the presented view.
- returns: False if the dismissal should be prevented, otherwise, true if the dimissal should occur.
*/
@objc optional func presentrShouldDismiss(keyboardShowing: Bool) -> Bool
}
/// Main Presentr class. This is the point of entry for using the framework.
public class Presentr: NSObject {
/// This must be set during initialization, but can be changed to reuse a Presentr object.
public var presentationType: PresentationType
/// The type of transition animation to be used to present the view controller. This is optional, if not provided the default for each presentation type will be used.
public var transitionType: TransitionType?
/// The type of transition animation to be used to dismiss the view controller. This is optional, if not provided transitionType or default value will be used.
public var dismissTransitionType: TransitionType?
/// Should the presented controller have rounded corners. Each presentation type has its own default if nil.
public var roundCorners: Bool?
/// Radius of rounded corners for presented controller if roundCorners is true. Default is 4.
public var cornerRadius: CGFloat = 4
/// Shadow settings for presented controller.
public var dropShadow: PresentrShadow?
/// Should the presented controller dismiss on background tap. Default is true.
public var dismissOnTap = true
/// Should the presented controller dismiss on Swipe inside the presented view controller. Default is false.
public var dismissOnSwipe = false
/// If dismissOnSwipe is true, the direction for the swipe. Default depends on presentation type.
public var dismissOnSwipeDirection: DismissSwipeDirection = .default
/// Should the presented controller use animation when dismiss on background tap or swipe. Default is true.
public var dismissAnimated = true
/// Color of the background. Default is Black.
public var backgroundColor = UIColor.black
/// Opacity of the background. Default is 0.7.
public var backgroundOpacity: Float = 0.7
/// Should the presented controller blur the background. Default is false.
public var blurBackground = false
/// The type of blur to be applied to the background. Ignored if blurBackground is set to false. Default is Dark.
public var blurStyle: UIBlurEffectStyle = .dark
/// A custom background view to be added on top of the regular background view.
public var customBackgroundView: UIView?
/// How the presented view controller should respond to keyboard presentation.
public var keyboardTranslationType: KeyboardTranslationType = .none
/// When a ViewController for context is set this handles what happens to a tap when it is outside the context. True will ignore tap and pass the tap to the background controller, false will handle the tap and dismiss the presented controller. Default is false.
public var shouldIgnoreTapOutsideContext = false
/// Uses the ViewController's frame as context for the presentation. Imitates UIModalPresentation.currentContext
public weak var viewControllerForContext: UIViewController? {
didSet {
guard let viewController = viewControllerForContext, let view = viewController.view else {
contextFrameForPresentation = nil
return
}
let correctedOrigin = view.convert(view.frame.origin, to: nil) // Correct origin in relation to UIWindow
contextFrameForPresentation = CGRect(x: correctedOrigin.x, y: correctedOrigin.y, width: view.bounds.width, height: view.bounds.height)
}
}
fileprivate var contextFrameForPresentation: CGRect?
// MARK: Init
public init(presentationType: PresentationType) {
self.presentationType = presentationType
}
// MARK: Class Helper Methods
/**
Public helper class method for creating and configuring an instance of the 'AlertViewController'
- parameter title: Title to be used in the Alert View Controller.
- parameter body: Body of the message to be displayed in the Alert View Controller.
- returns: Returns a configured instance of 'AlertViewController'
*/
public static func alertViewController(title: String = PresentrConstants.Strings.alertTitle, body: String = PresentrConstants.Strings.alertBody) -> AlertViewController {
let alertController = AlertViewController()
alertController.titleText = title
alertController.bodyText = body
return alertController
}
// MARK: Private Methods
/**
Private method for presenting a view controller, using the custom presentation. Called from the UIViewController extension.
- parameter presentingVC: The view controller which is doing the presenting.
- parameter presentedVC: The view controller to be presented.
- parameter animated: Animation boolean.
- parameter completion: Completion block.
*/
fileprivate func presentViewController(presentingViewController presentingVC: UIViewController, presentedViewController presentedVC: UIViewController, animated: Bool, completion: (() -> Void)?) {
presentedVC.transitioningDelegate = self
presentedVC.modalPresentationStyle = .custom
presentingVC.present(presentedVC, animated: animated, completion: completion)
}
fileprivate var transitionForPresent: TransitionType {
return transitionType ?? presentationType.defaultTransitionType()
}
fileprivate var transitionForDismiss: TransitionType {
return dismissTransitionType ?? transitionType ?? presentationType.defaultTransitionType()
}
}
// MARK: - UIViewControllerTransitioningDelegate
extension Presentr: UIViewControllerTransitioningDelegate {
public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return presentationController(presented, presenting: presenting)
}
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return transitionForPresent.animation()
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return transitionForDismiss.animation()
}
// MARK: - Private Helper's
fileprivate func presentationController(_ presented: UIViewController, presenting: UIViewController?) -> PresentrController {
return PresentrController(presentedViewController: presented,
presentingViewController: presenting,
presentationType: presentationType,
roundCorners: roundCorners,
cornerRadius: cornerRadius,
dropShadow: dropShadow,
dismissOnTap: dismissOnTap,
dismissOnSwipe: dismissOnSwipe,
dismissOnSwipeDirection: dismissOnSwipeDirection,
backgroundColor: backgroundColor,
backgroundOpacity: backgroundOpacity,
blurBackground: blurBackground,
blurStyle: blurStyle,
customBackgroundView: customBackgroundView,
keyboardTranslationType: keyboardTranslationType,
dismissAnimated: dismissAnimated,
contextFrameForPresentation: contextFrameForPresentation,
shouldIgnoreTapOutsideContext: shouldIgnoreTapOutsideContext)
}
}
// MARK: - UIViewController extension to provide customPresentViewController(_:viewController:animated:completion:) method
public extension UIViewController {
/// Present a view controller with a custom presentation provided by the Presentr object.
///
/// - Parameters:
/// - presentr: Presentr object used for custom presentation.
/// - viewController: The view controller to be presented.
/// - animated: Animation setting for the presentation.
/// - completion: Completion handler.
func customPresentViewController(_ presentr: Presentr, viewController: UIViewController, animated: Bool, completion: (() -> Void)?) {
presentr.presentViewController(presentingViewController: self,
presentedViewController: viewController,
animated: animated,
completion: completion)
}
}
|
mit
|
90603d91ee8942c4dd2ebac810489527
| 43.982301 | 265 | 0.697226 | 5.927697 | false | false | false | false |
Bootstragram/Martinet
|
Example/Martinet/DemoAsyncDownloadsPresenter.swift
|
1
|
2672
|
//
// DemoAsyncDownloadsPresenter.swift
// Martinet
//
// Created by Mickaël Floc'hlay on 27/02/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import Martinet
class LargerItemsTableViewController: ItemsTableViewController<String, UITableViewCell> {
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
class DemoAsyncDownloadsPresenter {
var viewController: LargerItemsTableViewController?
var items = [
"5",
"10",
"15",
"20",
"25",
"30",
"35",
"40",
"45",
"50",
"55",
"60",
"65",
"70",
"75",
"80",
"85",
"90",
"95",
"100",
"105",
"110",
"115",
"120",
"125",
"130",
"135",
"140",
"145",
"150",
"155",
"160",
"165",
"170",
"175",
"180",
"185",
"190",
"195",
"200",
]
init() {
viewController = LargerItemsTableViewController(items: items, configure: { cell, item in
if let myURL = URL(string: "https://placehold.it/\(item)x100") {
cell.layer.setValue(myURL, forKey: "myURL")
cell.textLabel?.text = myURL.absoluteString
let hueVal = Double(item) ?? 200.0
let hueValFloat = CGFloat(hueVal / 200.0)
cell.backgroundColor = UIColor(hue: hueValFloat, saturation: 0.7, brightness: 0.7, alpha: 1.0)
cell.imageView?.image = nil // Comment to activate "blinking"
// Download image from URL asynchronously
URLSession.shared.dataTask(with: myURL) { data, response, error in
guard let fetchedData = data, error == nil else {
debugPrint("Error")
return
}
DispatchQueue.main.async() { () -> Void in
let myCachedURL = cell.layer.value(forKey: "myURL") as? URL
if myCachedURL == myURL { // If cell url still matches downloaded image url, set to imageView. Otherwise discard (or cache)
cell.imageView?.image = UIImage(data: fetchedData)
cell.setNeedsLayout()
} else {
debugPrint("\(myCachedURL) != \(myURL)")
}
}
}.resume()
}
})
}
}
|
mit
|
09ec329f9c189b3bf6e13079c1c97b6d
| 27.105263 | 147 | 0.470412 | 4.587629 | false | false | false | false |
allevato/SwiftCGI
|
Sources/SwiftCGI/FileOutputStream.swift
|
1
|
2723
|
// Copyright 2015 Tony Allevato
//
// 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
/// An output stream that writes content to a file or file descriptor.
public class FileOutputStream: OutputStream {
/// The file handle associated with the stream.
private let fileHandle: NSFileHandle!
/// Creates a new output stream that writes to the given file descriptor.
///
/// When using this initializer, the returned stream will *not* be closed automatically if it is
/// open when the stream is deallocated.
///
/// - Parameter fileDescriptor: The POSIX file descriptor to which the stream will write.
public init(fileDescriptor: Int32) {
fileHandle = NSFileHandle(fileDescriptor: fileDescriptor, closeOnDealloc: false)
}
/// Creates a new output stream that writes to the file at the given path.
///
/// When using this initializer, the returned stream *will* be closed automatically if it is open
/// when the stream is deallocated.
///
/// This initializer will fail if the file could not be opened.
///
/// - Parameter path: The path to the file that should be opened.
public init?(path: String) {
fileHandle = NSFileHandle(forWritingAtPath: path)
if fileHandle == nil {
return nil
}
}
public func write(buffer: [UInt8], offset: Int, count: Int) throws {
buffer.withUnsafeBufferPointer { buffer in
let source = buffer.baseAddress.advancedBy(offset)
let data = NSData(
bytesNoCopy: UnsafeMutablePointer<Void>(source), length: count, freeWhenDone: false)
// TODO: Detect errors other than EOF and throw them.
fileHandle.writeData(data)
}
}
public func seek(offset: Int, origin: SeekOrigin) throws -> Int {
switch origin {
case .Begin:
fileHandle.seekToFileOffset(UInt64(offset))
case .Current:
fileHandle.seekToFileOffset(fileHandle.offsetInFile + UInt64(offset))
case .End:
fileHandle.seekToEndOfFile()
fileHandle.seekToFileOffset(fileHandle.offsetInFile + UInt64(offset))
}
return Int(fileHandle.offsetInFile)
}
public func close() {
fileHandle.closeFile()
}
public func flush() {
fileHandle.synchronizeFile()
}
}
|
apache-2.0
|
dd2adc70933ff2d3b570e3d9a91631c0
| 33.468354 | 99 | 0.710613 | 4.599662 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Views/Maps Tab/Map/Map Annotation/CalloutBalloon.swift
|
1
|
8276
|
//
// CalloutBalloon.swift
// MEGameTracker
//
// Created by Emily Ivie on 3/9/17.
// Copyright © 2017 Emily Ivie. All rights reserved.
//
import UIKit
public struct CalloutBalloon {
public enum TailDirection { case up, down, right, left }
weak var baseLayer: CALayer?
weak var visibleWrapper: UIView?
weak var sizeWrapper: UIView?
let tailDirection: TailDirection
let tailLength: CGFloat
let tailWidth: CGFloat
let borderWidth: CGFloat
var cornerRadius: CGFloat
let borderColor: UIColor
let backgroundColor: UIColor
var innerLayer: CAShapeLayer?
var outerLayer: CAShapeLayer?
public init(
baseLayer: CALayer?,
visibleWrapper: UIView?,
sizeWrapper: UIView?,
tailDirection: TailDirection = .up,
tailLength: CGFloat = 20.0,
tailWidth: CGFloat = 10.0,
borderWidth: CGFloat = 1.0,
cornerRadius: CGFloat = 5.0,
borderColor: UIColor = .placeholderText,
backgroundColor: UIColor = UIColor(named: "secondaryBackground")!
) {
self.baseLayer = baseLayer
self.visibleWrapper = visibleWrapper
self.sizeWrapper = sizeWrapper
self.tailDirection = tailDirection
self.tailLength = tailLength
self.tailWidth = tailWidth
self.borderWidth = borderWidth
self.cornerRadius = cornerRadius
self.borderColor = borderColor
self.backgroundColor = backgroundColor
}
public mutating func render() {
createLayers()
positionLayers()
drawLayers()
}
private mutating func createLayers() {
guard let sizeWrapper = self.sizeWrapper else { return }
// add necessary layers
innerLayer = CAShapeLayer()
outerLayer = CAShapeLayer()
let bounds = sizeWrapper.bounds
innerLayer?.frame = bounds
outerLayer?.frame = bounds
}
private func positionLayers() {
guard let sizeWrapper = self.sizeWrapper else { return }
// now offset for arrow (otherwise its border color gets clipped off)
let x = sizeWrapper.frame.origin.x
let y = sizeWrapper.frame.origin.y
outerLayer?.frame.origin.x = x
outerLayer?.frame.origin.y = y
innerLayer?.frame.origin.x = x
innerLayer?.frame.origin.y = y
}
private func drawLayers() {
let outerPath = UIBezierPath()
let innerPath = UIBezierPath()
drawBalloon(outerPath: outerPath, innerPath: innerPath)
innerLayer?.path = innerPath.cgPath
visibleWrapper?.layer.backgroundColor = backgroundColor.cgColor
visibleWrapper?.layer.mask = innerLayer
outerLayer?.path = outerPath.cgPath
baseLayer?.backgroundColor = borderColor.cgColor
baseLayer?.mask = outerLayer
}
// swiftlint:disable function_body_length
private func drawBalloon(outerPath: UIBezierPath, innerPath: UIBezierPath) {
guard let sizeWrapper = self.sizeWrapper else { return }
let bounds = sizeWrapper.bounds
outerPath.move(to: CGPoint(x: cornerRadius, y: 0))
innerPath.move(to: CGPoint(x: cornerRadius + borderWidth, y: 0 + borderWidth))
if tailDirection == .up {
drawTail(outerPath: outerPath, innerPath: innerPath)
}
let topRight = CGPoint(x: bounds.width, y: 0)
let topRight1 = CGPoint(x: bounds.width - cornerRadius, y: 0)
let topRight2 = CGPoint(x: bounds.width, y: cornerRadius)
let topRightInner = CGPoint(x: bounds.width - (borderWidth / 2), y: 0 + (borderWidth / 2))
let topRightInner1 = CGPoint(x: (bounds.width - cornerRadius) - borderWidth, y: 0 + borderWidth)
let topRightInner2 = CGPoint(x: bounds.width - borderWidth, y: cornerRadius + borderWidth)
outerPath.addLine(to: topRight1)
innerPath.addLine(to: topRightInner1)
outerPath.addQuadCurve(to: topRight2, controlPoint: topRight)
innerPath.addQuadCurve(to: topRightInner2, controlPoint: topRightInner)
if tailDirection == .right {
drawTail(outerPath: outerPath, innerPath: innerPath)
}
let bottomRight = CGPoint(x: bounds.width, y: bounds.height)
let bottomRight1 = CGPoint(x: bounds.width, y: bounds.height - cornerRadius)
let bottomRight2 = CGPoint(x: bounds.width - cornerRadius, y: bounds.height)
let bottomRightInner = CGPoint(x: bounds.width - (borderWidth / 2), y: bounds.height - (borderWidth / 2))
let bottomRightInner1 = CGPoint(x: bounds.width - borderWidth, y: bounds.height - cornerRadius - borderWidth)
let bottomRightInner2 = CGPoint(x: bounds.width - cornerRadius - borderWidth, y: bounds.height - borderWidth)
outerPath.addLine(to: bottomRight1)
innerPath.addLine(to: bottomRightInner1)
outerPath.addQuadCurve(to: bottomRight2, controlPoint: bottomRight)
innerPath.addQuadCurve(to: bottomRightInner2, controlPoint: bottomRightInner)
if tailDirection == .down {
drawTail(outerPath: outerPath, innerPath: innerPath)
}
let bottomLeft = CGPoint(x: 0, y: bounds.height)
let bottomLeft1 = CGPoint(x: cornerRadius, y: bounds.height)
let bottomLeft2 = CGPoint(x: 0, y: bounds.height - cornerRadius)
let bottomLeftInner = CGPoint(x: 0 + (borderWidth / 2), y: bounds.height - (borderWidth / 2))
let bottomLeftInner1 = CGPoint(x: cornerRadius + borderWidth, y: bounds.height - borderWidth)
let bottomLeftInner2 = CGPoint(x: 0 + borderWidth, y: bounds.height - cornerRadius - borderWidth)
outerPath.addLine(to: bottomLeft1)
innerPath.addLine(to: bottomLeftInner1)
outerPath.addQuadCurve(to: bottomLeft2, controlPoint: bottomLeft)
innerPath.addQuadCurve(to: bottomLeftInner2, controlPoint: bottomLeftInner)
if tailDirection == .left {
drawTail(outerPath: outerPath, innerPath: innerPath)
}
let topLeft = CGPoint(x: 0, y: 0)
let topLeft1 = CGPoint(x: 0, y: cornerRadius)
let topLeft2 = CGPoint(x: cornerRadius, y: 0)
let topLeftInner = CGPoint(x: 0 + (borderWidth / 2), y: 0 + (borderWidth / 2))
let topLeftInner1 = CGPoint(x: 0 + borderWidth, y: cornerRadius + borderWidth)
let topLeftInner2 = CGPoint(x: cornerRadius + borderWidth, y: 0 + borderWidth)
outerPath.addLine(to: topLeft1)
innerPath.addLine(to: topLeftInner1)
outerPath.addQuadCurve(to: topLeft2, controlPoint: topLeft)
innerPath.addQuadCurve(to: topLeftInner2, controlPoint: topLeftInner)
outerPath.close()
innerPath.close()
}
// swiftlint:enable function_body_length
// swiftlint:disable function_body_length
private func drawTail(outerPath: UIBezierPath, innerPath: UIBezierPath) {
guard let sizeWrapper = self.sizeWrapper else { return }
let bounds = sizeWrapper.bounds
let tailInnerWidth = tailWidth - (borderWidth * 2)
var lineBreak = CGPoint(x: (bounds.width - tailWidth) / 2, y: (bounds.height - tailWidth) / 2)
var lineBreakInner = CGPoint(
x: (bounds.width - tailInnerWidth) / 2,
y: (bounds.height - tailInnerWidth) / 2
)
var tailPoint = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
var tailPointInner = CGPoint(x: tailPoint.x, y: tailPoint.y)
switch tailDirection {
case .up:
lineBreak.y = 0 // top side
lineBreakInner.y = lineBreak.y + borderWidth
tailPoint.y = lineBreak.y - tailLength // above top
tailPointInner.y = tailPoint.y + (borderWidth * 2)
case .right:
lineBreak.x = bounds.width // right side
lineBreakInner.x = lineBreak.x - borderWidth
tailPoint.x = lineBreak.x + tailLength // right of right
tailPointInner.x = tailPoint.x - (borderWidth * 2)
case .down:
lineBreak.x += tailWidth
lineBreak.y = bounds.height // bottom side
lineBreakInner.x += tailInnerWidth
lineBreakInner.y = lineBreak.y - borderWidth
tailPoint.y = lineBreak.y + tailLength // below bottom
tailPointInner.y = tailPoint.y - (borderWidth * 2)
case .left:
lineBreak.y += tailWidth
lineBreak.x = 0 // left side
lineBreakInner.y += tailInnerWidth
lineBreakInner.x = lineBreak.x + borderWidth
tailPoint.x = lineBreak.x - tailLength // left of left
tailPointInner.x = tailPoint.x + (borderWidth * 2)
}
outerPath.addLine(to: lineBreak)
innerPath.addLine(to: lineBreakInner)
outerPath.addLine(to: tailPoint)
innerPath.addLine(to: tailPointInner)
if tailDirection == .up || tailDirection == .down {
lineBreak.x += tailWidth * (tailDirection == .up ? 1 : -1)
lineBreakInner.x += tailInnerWidth * (tailDirection == .up ? 1 : -1)
} else {
lineBreak.y += tailWidth * (tailDirection == .right ? 1 : -1)
lineBreakInner.y += tailInnerWidth * (tailDirection == .right ? 1 : -1)
}
outerPath.addLine(to: lineBreak)
innerPath.addLine(to: lineBreakInner)
}
// swiftlint:enable function_body_length
}
|
mit
|
04b96742c7929cd6fb40d883a5d51716
| 37.488372 | 111 | 0.728218 | 3.533305 | false | false | false | false |
abreis/swift-gissumo
|
scripts/parsers/singles/averageCoverageDistribution.swift
|
1
|
6036
|
/* This script expects a set of 'cityCoverageEvolution' stat files.
* It aggregates all metrics and reports mean values and sample counts
* for each. Standard deviation is left out due to the computational
* complexity required when large numbers of samples are present.
*
* If a time value is provided as the second argument, only samples that
* occur after that time are recorded.
*/
import Foundation
/*** MEASUREMENT SWIFT3 ***/
// A measurement object: load data into 'samples' and all metrics are obtained as computed properties
struct Measurement {
var samples = [Double]()
mutating func add(_ point: Double) { samples.append(point) }
var count: Double { return Double(samples.count) }
var sum: Double { return samples.reduce(0,+) }
var mean: Double { return sum/count }
var min: Double { return samples.min()! }
var max: Double { return samples.max()! }
// This returns the maximum likelihood estimator(over N), not the minimum variance unbiased estimator (over N-1)
var variance: Double { return samples.reduce(0,{$0 + pow($1-mean,2)} )/count }
var stdev: Double { return sqrt(variance) }
// Specify the desired confidence level (1-significance) before requesting the intervals
// func confidenceIntervals(confidence: Double) -> Double {}
//var confidence: Double = 0.90
//var confidenceInterval: Double { return 0.0 }
}
/*** ***/
guard 2...3 ~= CommandLine.arguments.count else {
print("usage: \(CommandLine.arguments[0]) [list of data files] [minimum time]")
exit(EXIT_FAILURE)
}
// Load minimum sample time
var minTime: Double = 0.0
if CommandLine.arguments.count == 3 {
guard let inMinTime = Double(CommandLine.arguments[2]) else {
print("Error: Invalid minimum time specified.")
exit(EXIT_FAILURE)
}
minTime = inMinTime
}
var statFiles: String
do {
let statFilesURL = NSURL.fileURL(withPath: CommandLine.arguments[1])
_ = try statFilesURL.checkResourceIsReachable()
statFiles = try String(contentsOf: statFilesURL, encoding: String.Encoding.utf8)
} catch {
print(error)
exit(EXIT_FAILURE)
}
/// Process statistics files
struct DataMeasurements {
var numCovered = Measurement()
var percentCovered = Measurement()
var meanSig = Measurement()
var stdevSig = Measurement()
var sig0cells = Measurement()
var sig1cells = Measurement()
var sig2cells = Measurement()
var sig3cells = Measurement()
var sig4cells = Measurement()
var sig5cells = Measurement()
}
var dataMeasurements = DataMeasurements()
for statFile in statFiles.components(separatedBy: .newlines).filter({!$0.isEmpty}) {
// 1. Open and read the statFile into a string
var statFileData: String
do {
let statFileURL = NSURL.fileURL(withPath: statFile)
_ = try statFileURL.checkResourceIsReachable()
statFileData = try String(contentsOf: statFileURL, encoding: String.Encoding.utf8)
} catch {
print(error)
exit(EXIT_FAILURE)
}
// 2. Break the stat file into lines
var statFileLines: [String] = statFileData.components(separatedBy: .newlines).filter({!$0.isEmpty})
// 3. Drop the first line (header)
statFileLines.removeFirst()
// 4. Run through the statFile lines
statFileLoop: for statFileLine in statFileLines {
// Split each line by tabs
let statFileLineColumns = statFileLine.components(separatedBy: "\t").filter({!$0.isEmpty})
// 0 1 2 3 4 5 6 7 8 9 10
// time #covered %covered meanSig stdevSig 0cells 1cells 2cells 3cells 4cells 5cells
guard let intime = Double(statFileLineColumns[0]) else {
print("ERROR: Can't interpret input time.")
exit(EXIT_FAILURE)
}
if(intime > minTime) {
guard let inccov = UInt(statFileLineColumns[1]),
let inpercov = Double(statFileLineColumns[2]),
let inmeansig = Double(statFileLineColumns[3]),
let instdevsig = Double(statFileLineColumns[4]),
let in0cell = UInt(statFileLineColumns[5]),
let in1cell = UInt(statFileLineColumns[6]),
let in2cell = UInt(statFileLineColumns[7]),
let in3cell = UInt(statFileLineColumns[8]),
let in4cell = UInt(statFileLineColumns[9]),
let in5cell = UInt(statFileLineColumns[10])
else {
print("ERROR: Can't interpret input data.")
exit(EXIT_FAILURE)
}
dataMeasurements.numCovered.add(Double(inccov))
dataMeasurements.percentCovered.add(inpercov)
dataMeasurements.meanSig.add(inmeansig)
dataMeasurements.stdevSig.add(instdevsig)
dataMeasurements.sig0cells.add(Double(in0cell))
dataMeasurements.sig1cells.add(Double(in1cell))
dataMeasurements.sig2cells.add(Double(in2cell))
dataMeasurements.sig3cells.add(Double(in3cell))
dataMeasurements.sig4cells.add(Double(in4cell))
dataMeasurements.sig5cells.add(Double(in5cell))
}
}
}
print("metric", "numCovered", "percentCovered", "meanSig", "stdevSig", "0cells", "1cells", "2cells", "3cells", "4cells", "5cells", separator: "\t", terminator: "\n")
print("mean", dataMeasurements.numCovered.mean, dataMeasurements.percentCovered.mean, dataMeasurements.meanSig.mean, dataMeasurements.stdevSig.mean, dataMeasurements.sig0cells.mean, dataMeasurements.sig1cells.mean, dataMeasurements.sig2cells.mean, dataMeasurements.sig3cells.mean, dataMeasurements.sig4cells.mean, dataMeasurements.sig5cells.mean, separator: "\t", terminator: "\n")
//print("stdev", dataMeasurements.numCovered.stdev, dataMeasurements.percentCovered.stdev, dataMeasurements.meanSig.stdev, dataMeasurements.stdevSig.stdev, dataMeasurements.sig0cells.stdev, dataMeasurements.sig1cells.stdev, dataMeasurements.sig2cells.stdev, dataMeasurements.sig3cells.stdev, dataMeasurements.sig4cells.stdev, dataMeasurements.sig5cells.stdev, separator: "\t", terminator: "\n")
print("count", dataMeasurements.numCovered.count, dataMeasurements.percentCovered.count, dataMeasurements.meanSig.count, dataMeasurements.stdevSig.count, dataMeasurements.sig0cells.count, dataMeasurements.sig1cells.count, dataMeasurements.sig2cells.count, dataMeasurements.sig3cells.count, dataMeasurements.sig4cells.count, dataMeasurements.sig5cells.count, separator: "\t", terminator: "\n")
|
mit
|
70e1aa703618933ceb159a59330d550c
| 39.24 | 394 | 0.747018 | 3.437358 | false | false | false | false |
Arcovv/CleanArchitectureRxSwift
|
Network/Entries/Address+Mapping.swift
|
1
|
502
|
//
// Address+Mapping.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 10.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import Domain
import ObjectMapper
extension Address: ImmutableMappable {
// JSON -> Object
public init(map: Map) throws {
city = try map.value("city")
geo = try map.value("geo")
street = try map.value("street")
suite = try map.value("suite")
zipcode = try map.value("zipcode")
}
}
|
mit
|
20fb9fb62ee36f31eefe0546c359fcf4
| 21.772727 | 51 | 0.62475 | 3.853846 | false | false | false | false |
nagyistoce/edx-app-ios
|
Source/DiscussionAPI.swift
|
1
|
10782
|
//
// DiscussionAPI.swift
// edX
//
// Created by Tang, Jeff on 6/26/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
public enum DiscussionPostsFilter {
case AllPosts
case Unread
case Unanswered
private var apiRepresentation : String? {
switch self {
case AllPosts: return nil // default
case Unread: return "unread"
case Unanswered: return "unanswered"
}
}
}
public enum DiscussionPostsSort {
case RecentActivity
case LastActivityAt
case VoteCount
private var apiRepresentation : String? {
switch self {
case RecentActivity: return nil // default
case LastActivityAt: return "last_activity_at"
case VoteCount: return "vote_count"
}
}
}
public class DiscussionAPI {
static func createNewThread(newThread: DiscussionNewThread) -> NetworkRequest<DiscussionThread> {
let json = JSON([
"course_id" : newThread.courseID,
"topic_id" : newThread.topicID,
"type" : newThread.type,
"title" : newThread.title,
"raw_body" : newThread.rawBody,
])
return NetworkRequest(
method : HTTPMethod.POST,
path : "/api/discussion/v1/threads/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
deserializer : {(response, data) -> Result<DiscussionThread> in
return Result(jsonData : data, error : NSError.oex_unknownError()) {
return DiscussionThread(json: $0)
}
})
}
// when parent id is nil, counts as a new post
static func createNewComment(threadID : String, text : String, parentID : String? = nil) -> NetworkRequest<DiscussionComment> {
var json = JSON([
"thread_id" : threadID,
"raw_body" : text,
])
if let parentID = parentID {
json["parent_id"] = JSON(parentID)
}
return NetworkRequest(
method : HTTPMethod.POST,
path : "/api/discussion/v1/comments/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
deserializer : {(response, data) -> Result<DiscussionComment> in
return Result(jsonData : data, error : NSError.oex_unknownError()) {
return DiscussionComment(json: $0)
}
})
}
// User can only vote on post and response not on comment.
// thread is the same as post
static func voteThread(voted: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["voted" : !voted])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
deserializer : {(response, data) -> Result<DiscussionThread> in
return Result(jsonData : data, error : NSError.oex_unknownError()) {
return DiscussionThread(json: $0)
}
})
}
static func voteResponse(voted: Bool, responseID: String) -> NetworkRequest<DiscussionComment> {
let json = JSON(["voted" : !voted])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/comments/\(responseID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
deserializer : {(response, data) -> Result<DiscussionComment> in
return Result(jsonData : data, error : NSError.oex_unknownError()) {
return DiscussionComment(json: $0)
}
})
}
// User can flag (report) on post, response, or comment
static func flagThread(flagged: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["flagged" : flagged])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
deserializer : {(response, data) -> Result<DiscussionThread> in
return Result(jsonData : data, error : NSError.oex_unknownError()) {
return DiscussionThread(json: $0)
}
})
}
static func flagComment(flagged: Bool, commentID: String) -> NetworkRequest<DiscussionComment> {
let json = JSON(["flagged" : flagged])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/comments/\(commentID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
deserializer : {(response, data) -> Result<DiscussionComment> in
return Result(jsonData : data, error : NSError.oex_unknownError()) {
return DiscussionComment(json: $0)
}
})
}
// User can only follow original post, not response or comment.
static func followThread(following: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
var json = JSON(["following" : !following])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
deserializer : {(response, data) -> Result<DiscussionThread> in
return Result(jsonData : data, error : NSError.oex_unknownError()) {
return DiscussionThread(json: $0)
}
})
}
static func markThreadAsRead(read: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["read" : read])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
deserializer : {(response, data) -> Result<DiscussionThread> in
return Result(jsonData : data, error : NSError.oex_unknownError()) {
return DiscussionThread(json: $0)
}
})
}
static func getThreads(#courseID: String, topicID: String, filter: DiscussionPostsFilter, orderBy: DiscussionPostsSort) -> NetworkRequest<[DiscussionThread]> {
var query = ["course_id" : JSON(courseID), "topic_id": JSON(topicID)]
if let view = filter.apiRepresentation {
query["view"] = JSON(view)
}
if let order = orderBy.apiRepresentation {
query["order_by"] = JSON(order)
}
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/threads/",
query: query,
requiresAuth : true,
deserializer : {(response, data) -> Result<[DiscussionThread]> in
return Result(jsonData : data, error : NSError.oex_unknownError(), constructor: {
var result: [DiscussionThread] = []
if let threads = $0["results"].array {
for json in threads {
if let discussionThread = DiscussionThread(json: json) {
result.append(discussionThread)
}
}
}
return result
})
})
}
static func searchThreads(#courseID: String, searchText: String) -> NetworkRequest<[DiscussionThread]> {
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/threads/",
query: ["course_id" : JSON(courseID), "text_search": JSON(searchText)],
requiresAuth : true,
deserializer : {(response, data) -> Result<[DiscussionThread]> in
return Result(jsonData : data, error : NSError.oex_unknownError(), constructor: {
var result: [DiscussionThread] = []
if let threads = $0["results"].array {
for json in threads {
if let discussionThread = DiscussionThread(json: json) {
result.append(discussionThread)
}
}
}
return result
})
})
}
static func getResponses(threadID: String) -> NetworkRequest<[DiscussionComment]> {
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/comments/", // responses are treated similarly as comments
query: ["page_size" : 20, "thread_id": JSON(threadID)],
requiresAuth : true,
deserializer : {(response, data) -> Result<[DiscussionComment]> in
return Result(jsonData : data, error : NSError.oex_unknownError()) {
var result: [DiscussionComment] = []
if let threads = $0["results"].array {
for json in threads {
if let discussionComment = DiscussionComment(json: json) {
result.append(discussionComment)
}
}
}
return result
}
})
}
static func getCourseTopics(courseID: String) -> NetworkRequest<[DiscussionTopic]> {
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/course_topics/\(courseID)",
requiresAuth : true,
deserializer : {(response, data) -> Result<[DiscussionTopic]> in
return Result(jsonData : data, error : NSError.oex_unknownError()) {
var result: [DiscussionTopic] = []
let topics = ["courseware_topics", "non_courseware_topics"]
for topic in topics {
if let results = $0[topic].array {
for json in results {
if let topic = DiscussionTopic(json: json) {
result.append(topic)
}
}
}
}
return result
}
})
}
}
|
apache-2.0
|
6359e45d198ee05b1dfd6d717fb4bd47
| 39.537594 | 163 | 0.526247 | 5.348214 | false | false | false | false |
kingiol/KDCycleBannerView-Swift
|
KDCycleBannerView/KDCycleBannerView.swift
|
1
|
11067
|
//
// KDCycleBannerView.swift
// KDCycleBannerView-Swift
//
// Created by Kingiol on 14-6-14.
// Copyright (c) 2014年 Kingiol. All rights reserved.
//
import UIKit
@objc protocol KDCycleBannerViewDatasource: NSObjectProtocol {
func numberOfKDCycleBannerView(bannerView: KDCycleBannerView) -> Array<AnyObject>;
func contentModeForImageIndex(index: Int) -> UIViewContentMode
@optional func placeHolderImageOfZeroBanerView() -> UIImage
@optional func placeHolderImageOfBannerView(bannerView: KDCycleBannerView, atIndex: Int) -> UIImage
}
@objc protocol KDCycleBannerViewDelegate: NSObjectProtocol {
@optional func cycleBannerView(bannerView: KDCycleBannerView, didScrollToIndex index: Int)
@optional func cycleBannerView(bannerView: KDCycleBannerView, didSelectedAtIndex index: Int)
}
class KDCycleBannerView: UIView, UIScrollViewDelegate, UIGestureRecognizerDelegate {
@IBOutlet var datasource: KDCycleBannerViewDatasource!
@IBOutlet var delegate: KDCycleBannerViewDelegate?
var continuous: Bool = false // if YES, then bannerview will show like a carousel, default is NO
var autoPlayTimeInterval: Int = 0 // if autoPlayTimeInterval more than 0, the bannerView will autoplay with autoPlayTimeInterval value space, default is 0
var scrollView: UIScrollView = UIScrollView()
var scrollViewBounces: Bool = true
var pageControl: UIPageControl = UIPageControl()
var datasourceImages: Array<AnyObject> = Array()
var currentSelectedPage: Int = 0
var completeBlock: (() -> ())?
var autoPlayDelay: dispatch_time_t {
let delay = Double(autoPlayTimeInterval) * Double(NSEC_PER_SEC)
return dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
}
init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
}
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
func reloadDataWithCompleteBlock(block: () -> ()) {
completeBlock = block
setNeedsLayout()
}
func setCurrentPage(currentPage: Int, animated: Bool) {
let page = min(datasourceImages.count - 1, max(0, currentPage))
setSwitchPage(page, animated: animated, withUserInterface: true)
}
override func layoutSubviews() {
super.layoutSubviews()
loadData()
// progress autoPlayTimeInterval
struct DISPATCH_ONE_STRUCT {
static var token: dispatch_once_t = 0
}
dispatch_once(&DISPATCH_ONE_STRUCT.token) {
if self.autoPlayTimeInterval > 0 && self.continuous && self.datasourceImages.count > 3 {
println("OKKKK");
dispatch_after(self.autoPlayDelay, dispatch_get_main_queue(), self.autoSwitchBanner)
}
}
}
override func didMoveToSuperview() {
initialize()
completeBlock?()
}
func initialize() {
clipsToBounds = true
initializeScrollView()
initializePageControl()
}
func initializeScrollView() {
scrollView = UIScrollView(frame: CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)));
scrollView.delegate = self
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.autoresizingMask = autoresizingMask
self.addSubview(scrollView)
}
func initializePageControl() {
var pageControlFrame: CGRect = CGRect(x: 0, y: 0, width: CGRectGetWidth(scrollView.frame), height: 30)
pageControl = UIPageControl(frame: pageControlFrame)
pageControl.center = CGPoint(x: CGRectGetWidth(scrollView.frame) * 0.5, y: CGRectGetHeight(scrollView.frame) - 12)
pageControl.userInteractionEnabled = false
self.addSubview(pageControl)
}
func loadData() {
datasourceImages = datasource.numberOfKDCycleBannerView(self)
if datasourceImages.count == 0 {
//显示默认页,无数据页面
if let image = datasource.placeHolderImageOfZeroBanerView?() {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: CGRectGetWidth(scrollView.frame), height: CGRectGetHeight(scrollView.frame)))
imageView.clipsToBounds = true
imageView.contentMode = .ScaleAspectFill
imageView.backgroundColor = UIColor.clearColor()
imageView.image = image
scrollView.addSubview(imageView)
}
return
}
pageControl.numberOfPages = datasourceImages.count
pageControl.currentPage = 0
if continuous && datasourceImages.count > 1 {
datasourceImages.insert(datasourceImages[datasourceImages.count - 1], atIndex: 0)
datasourceImages.append(datasourceImages[1])
}
let contentWidth = CGRectGetWidth(scrollView.frame)
let contentHeight = CGRectGetHeight(scrollView.frame)
scrollView.contentSize = CGSize(width: contentWidth * CGFloat(datasourceImages.count), height: contentHeight)
for (index, obj: AnyObject) in enumerate(datasourceImages) {
let imgRect = CGRectMake(contentWidth * CGFloat(index), 0, contentWidth, contentHeight)
let imageView = UIImageView(frame: imgRect)
imageView.backgroundColor = UIColor.clearColor()
imageView.clipsToBounds = true
imageView.contentMode = datasource.contentModeForImageIndex(index)
if obj is UIImage {
imageView.image = obj as UIImage
}else if obj is String || obj is NSURL {
let activityIndicatorView = UIActivityIndicatorView()
activityIndicatorView.center = CGPointMake(CGRectGetWidth(scrollView.frame) * 0.5, CGRectGetHeight(scrollView.frame) * 0.5)
activityIndicatorView.tag = 100
activityIndicatorView.activityIndicatorViewStyle = .WhiteLarge
activityIndicatorView.startAnimating()
imageView.addSubview(activityIndicatorView)
imageView.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old, context: nil)
if let placeHolderImage = datasource.placeHolderImageOfBannerView?(self, atIndex: index) {
imageView.setImageWithURL(obj is String ? NSURL(string: obj as String) : obj as NSURL, placeholderImage: placeHolderImage)
}else {
imageView.setImageWithURL(obj is String ? NSURL(string: obj as String) : obj as NSURL)
}
}
scrollView.addSubview(imageView)
}
if continuous && datasourceImages.count > 1 {
scrollView.contentOffset = CGPointMake(CGRectGetWidth(scrollView.frame), 0)
}
// single tap gesture recognizer
let tapGestureRecognize = UITapGestureRecognizer(target: self, action: Selector("singleTapGestureRecognizer:")) // designated initializer)
tapGestureRecognize.delegate = self
tapGestureRecognize.numberOfTapsRequired = 1
scrollView.addGestureRecognizer(tapGestureRecognize)
}
func moveToTargetPosition(targetX: CGFloat, withAnimated animated: Bool) {
scrollView.setContentOffset(CGPointMake(targetX, 0), animated: animated)
}
func setSwitchPage(switchPage: Int, animated: Bool, withUserInterface userInterface: Bool) {
var page = -1
if userInterface {
page = switchPage
}else {
currentSelectedPage++
page = currentSelectedPage % (continuous ? datasourceImages.count - 1 : datasourceImages.count)
}
if continuous {
if datasourceImages.count > 1 {
if page >= datasourceImages.count - 2 {
page = datasourceImages.count - 3
currentSelectedPage = 0
moveToTargetPosition(CGRectGetWidth(scrollView.frame) * CGFloat(page + 2), withAnimated: animated)
}else {
moveToTargetPosition(CGRectGetWidth(scrollView.frame) * CGFloat(page + 1), withAnimated: animated)
}
}else {
moveToTargetPosition(0, withAnimated: animated)
}
}else {
moveToTargetPosition(CGRectGetWidth(scrollView.frame) * CGFloat(page), withAnimated: animated)
}
scrollViewDidScroll(scrollView)
}
func autoSwitchBanner() {
NSObject.cancelPreviousPerformRequestsWithTarget(self)
setSwitchPage(-1, animated: true, withUserInterface: false)
dispatch_after(autoPlayDelay, dispatch_get_main_queue(), autoSwitchBanner)
}
//pragma mark - KVO
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: NSDictionary!, context: CMutableVoidPointer)
{
if keyPath == "image" {
let imageView = object as UIImageView
let activityIndicatorView: UIActivityIndicatorView = imageView.viewWithTag(100) as UIActivityIndicatorView
activityIndicatorView.removeFromSuperview()
imageView.removeObserver(self, forKeyPath: "image")
}
}
//pragma mark - UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView!) {
var targetX: CGFloat = scrollView.contentOffset.x
var item_width = CGRectGetWidth(scrollView.frame)
if continuous && datasourceImages.count >= 3 {
if targetX >= item_width * CGFloat(datasourceImages.count - 1) {
targetX = item_width
scrollView.contentOffset = CGPointMake(targetX, 0)
}else if targetX <= 0 {
targetX = item_width * CGFloat(datasourceImages.count - 2)
scrollView.contentOffset = CGPointMake(targetX, 0)
}
}
var page: Int = Int(scrollView.contentOffset.x + item_width * 0.5) / Int(item_width)
if continuous && datasourceImages.count > 1 {
page--
if page >= pageControl.numberOfPages {
page = 0
}else if (page < 0) {
page = pageControl.numberOfPages - 1
}
}
currentSelectedPage = page
if page != pageControl.currentPage {
delegate?.cycleBannerView?(self, didScrollToIndex: page)
}
pageControl.currentPage = page
}
func singleTapGestureRecognizer(tapGesture: UITapGestureRecognizer) {
let page = Int(scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame))
delegate?.cycleBannerView?(self, didSelectedAtIndex: page)
}
}
|
mit
|
248fdf63a46a2d5d94ddaa805b8bdf6f
| 39.450549 | 158 | 0.638323 | 5.466832 | false | false | false | false |
MukeshKumarS/Swift
|
test/Prototypes/FloatingPoint.swift
|
1
|
48234
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %S/../../utils/line-directive %s -- %target-build-swift -parse-stdlib %s -o %t/a.out
// RUN: %S/../../utils/line-directive %s -- %target-run %t/a.out
// REQUIRES: executable_test
import Swift
// TODO: These should probably subsumed into UnsignedIntegerType or
// another integer protocol. Dave has already done some work here.
public protocol FloatingPointRepresentationType : UnsignedIntegerType {
var leadingZeros: UInt { get }
func <<(left: Self, right: Self) -> Self
func >>(left: Self, right: Self) -> Self
init(_ value: UInt)
}
extension UInt64 : FloatingPointRepresentationType {
public var leadingZeros: UInt {
return UInt(_countLeadingZeros(Int64(bitPattern: self)))
}
}
extension UInt32 : FloatingPointRepresentationType {
public var leadingZeros: UInt {
return UInt64(self).leadingZeros - 32
}
}
// Ewwww? <rdar://problem/20060017>
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
public protocol FloatingPointType : Comparable, SignedNumberType,
IntegerLiteralConvertible,
FloatLiteralConvertible {
/// An unsigned integer type large enough to hold the significand field.
typealias SignificandBits: FloatingPointRepresentationType
/// Positive infinity.
///
/// Compares greater than all finite numbers.
static var infinity: Self { get }
/// Quiet NaN.
///
/// Compares not equal to every value, including itself. Most operations
/// with a `NaN` operand will produce a `NaN` result.
static var NaN: Self { get }
/// NaN with specified `payload`.
///
/// Compares not equal to every value, including itself. Most operations
/// with a `NaN` operand will produce a `NaN` result.
static func NaN(payload bits: SignificandBits, signaling: Bool) -> Self
/// The greatest finite value.
///
/// Compares greater than or equal to all finite numbers, but less than
/// infinity.
static var greatestFiniteMagnitude: Self { get }
// Note -- rationale for "ulp" instead of "epsilon":
// We do not use that name because it is ambiguous at best and misleading
// at worst:
//
// - Historically several definitions of "machine epsilon" have commonly
// been used, which differ by up to a factor of two or so. By contrast
// "ulp" is a term with a specific unambiguous definition.
//
// - Some languages have used "epsilon" to refer to wildly different values,
// such as `leastMagnitude`.
//
// - Inexperienced users often believe that "epsilon" should be used as a
// tolerance for floating-point comparisons, because of the name. It is
// nearly always the wrong value to use for this purpose.
/// The unit in the last place of 1.0.
///
/// This is the weight of the least significant bit of the significand of 1.0,
/// or the positive difference between 1.0 and the next greater representable
/// number.
///
/// This value (or a similar value) is often called "epsilon", "machine
/// epsilon", or "macheps" in other languages.
static var ulp: Self { get }
/// The least positive normal value.
///
/// Compares less than or equal to all positive normal numbers. There may
/// be smaller positive numbers, but they are "subnormal", meaning that
/// they are represented with less precision than normal numbers.
static var leastNormalMagnitude: Self { get }
/// The least positive value.
///
/// Compares less than or equal to all positive numbers, but greater than
/// zero. If the target supports subnormal values, this is smaller than
/// `leastNormalMagnitude`; otherwise (as on armv7), they are equal.
static var leastMagnitude: Self { get }
/// The `signbit`. True for negative numbers, false for positive.
///
/// This is simply the high-order bit in the encoding of `self`, regardless
/// of the encoded value. This *is not* the same thing as `self < 0`.
/// In particular:
///
/// - If `x` is `-0.0`, then `x.signbit` is `true`, but `x < 0` is `false`.
/// - If `x` is `NaN`, then `x.signbit` could be either `true` or `false`,
/// (the signbit of `NaN` is unspecified) but `x < 0` is `false`.
///
/// Implements the IEEE-754 `isSignMinus` operation.
var signbit: Bool { get }
/// The mathematical `exponent`.
///
/// If `x` is a normal floating-point number, then `exponent` is simply the
/// raw encoded exponent interpreted as a signed integer with the exponent
/// bias removed.
///
/// For subnormal numbers, `exponent` is computed as though the exponent
/// range of `Self` were unbounded. In particular, `x.exponent` will
/// be smaller than the minimum normal exponent that can be encoded.
///
/// Other edge cases:
///
/// - If `x` is zero, then `x.exponent` is `Int.min`.
/// - If `x` is +/-infinity or NaN, then `x.exponent` is `Int.max`
///
/// Implements the IEEE-754 `logB` operation.
var exponent: Int { get }
/// The mathematical `significand` (sometimes erroneously called the "mantissa").
///
/// `significand` is computed as though the exponent range of `Self` were
/// unbounded; if `x` is a finite non-zero number, then `x.significand` is
/// in the range `[1,2)`.
///
/// For other values of `x`, `x.significand` is defined as follows:
///
/// - If `x` is zero, then `x.significand` is 0.0.
/// - If `x` is infinity, then `x.signficand` is 1.0.
/// - If `x` is NaN, then `x.significand` is NaN.
///
/// For all floating-point `x`, if we define y by:
///
/// let y = Self(signbit: x.signbit, exponent: x.exponent,
/// significand: x.significand)
///
/// then `y` is equivalent to `x`, meaning that `y` is `x` canonicalized.
/// For types that do not have non-canonical encodings, this implies that
/// `y` has the same encoding as `x`. Note that this is a stronger
/// statement than `x == y`, as it implies that both the sign of zero and
/// the payload of NaN are preserved.
var significand: Self { get }
/// Combines a signbit, exponent, and signficand to produce a floating-point
/// datum.
///
/// In common usage, `significand` will generally be a number in the range
/// `[1,2)`, but this is not required; the initializer supports any valid
/// floating-point datum. The result is:
///
/// `(-1)^signbit * signficand * 2^exponent`
///
/// (where ^ denotes the mathematical operation of exponentiation) computed
/// as if by a single correctly-rounded floating-point operation. If this
/// value is outside the representable range of the type, overflow or
/// underflow will occur, and zero, a subnormal value, or infinity will be
/// returned, as with any basic operation. Other edge cases:
///
/// - If `significand` is zero or infinite, the result is zero or infinite,
/// regardless of the value of `exponent`.
/// - If `significand` is NaN, the result is NaN.
///
/// Note that for any floating-point datum `x` the result of
///
/// `Self(signbit: x.signbit,
/// exponent: x.exponent,
/// significand: x.significand)`
///
/// is "the same" as `x` (if `x` is NaN, then this result is also `NaN`, but
/// it might be a different NaN).
///
/// Because of these properties, this initializer also implements the
/// IEEE-754 `scaleB` operation.
init(signbit: Bool, exponent: Int, significand: Self)
/// The unit in the last place of `self`.
///
/// This is the value of the least significant bit in the significand of
/// `self`. For most numbers `x`, this is the difference between `x` and
/// the next greater (in magnitude) representable number. There are some
/// edge cases to be aware of:
///
/// - `greatestFiniteMagnitude.ulp` is a finite number, even though
/// the next greater respresentable value is `infinity`.
/// - `x.ulp` is `NaN` if `x` is not a finite number.
/// - If `x` is very small in magnitude, then `x.ulp` may be a subnormal
/// number. On targets that do not support subnormals, `x.ulp` may be
/// flushed to zero.
var ulp: Self { get }
// TODO: IEEE-754 requires the following operations for every FP type.
// They need bindings (names) for Swift. Some of them map to existing
// C library functions, so the default choice would be to use the C
// names, but we should consider if other names would be more appropriate
// for Swift.
//
// For now I have simply used the IEEE-754 names to track them.
//
// The C bindings for these operations are:
// roundToIntegralTiesToEven roundeven (n1778)
// roundToIntegralTiesAway round (c99)
// roundToIntegralTowardZero trunc (c99)
// roundToIntegralTowardPositive ceil (c90)
// roundToIntegralTowardNegative floor (c90)
//
// Also TBD: should these only be available as free functions?
/// Rounds `self` to nearest integral value, with halfway cases rounded
/// to the even integer.
func roundToIntegralTiesToEven() -> Self
/// Rounds `self` to the nearest integral value, with halfway cases rounded
/// away from zero.
func roundToIntegralTiesToAway() -> Self
/// Rounds `self` to an integral value towards zero.
func roundToIntegralTowardZero() -> Self
/// Rounds `self` to an integral value toward positive infinity.
func roundToIntegralTowardPositive() -> Self
/// Rounds `self` to an integral value toward negative infinity.
func roundToIntegralTowardNegative() -> Self
// TODO: roundToIntegralExact requires a notion of flags and of
// rounding modes, which require language design.
// TODO: should nextUp and nextDown be computed properties or funcs?
// For me, these sit right on the edge in terms of what makes sense.
/// The least `Self` that compares greater than `self`.
///
/// - If `x` is `-infinity`, then `x.nextUp` is `-greatestMagnitude`.
/// - If `x` is `-leastMagnitude`, then `x.nextUp` is `-0.0`.
/// - If `x` is zero, then `x.nextUp` is `leastMagnitude`.
/// - If `x` is `greatestMagnitude`, then `x.nextUp` is `infinity`.
/// - If `x` is `infinity` or `NaN`, then `x.nextUp` is `x`.
var nextUp: Self { get }
/// The greatest `Self` that compares less than `self`.
///
/// `x.nextDown` is equivalent to `-(-x).nextUp`
var nextDown: Self { get }
// TODO: IEEE-754 defines the following semantics for remainder(x, y).
//
// This operation differs from what is currently provided by the %
// operator, which implements fmod, not remainder. The difference is
// that fmod is the remainder of truncating division (the sign matches
// that of x and the magnitude is in [0, y)), whereas remainder is what
// results from round-to-nearest division (it lies in [y/2, y/2]).
//
// I would prefer that % implement the remainder operation, but this is
// a fairly significant change to the language that needs discussion.
// Both operations should be probably be available, anyway.
/// Remainder of `x` divided by `y`.
///
/// `remainder(x,y)` is defined for finite `x` and `y` by the mathematical
/// relation `r = x - yn`, where `n` is the integer nearest to the exact
/// number (*not* the floating-point value) `x/y`. If `x/y` is exactly
/// halfway between two integers, `n` is even. `remainder` is always
/// exact, and therefore is not affected by the rounding mode.
///
/// If `remainder(x,y)` is zero, it has the same sign as `x`. If `y` is
/// infinite, then `remainder(x,y)` is `x`.
static func remainder(x: Self, _ y: Self) -> Self
// TODO: The IEEE-754 "minNumber" and "maxNumber" operations should
// probably be provided by the min and max generic free functions, but
// there is some question of how best to do that. As an initial
// binding, they are provided as static functions.
//
// We will end up naming the static functions something else
// (if we keep them at all) to avoid confusion with Int.min, etc.
/// The minimum of `x` and `y`.
///
/// Returns `x` if `x < y`, `y` if `y < x`, and whichever of `x` or `y`
/// is a number if the other is NaN. The result is NaN only if both
/// arguments are NaN.
static func min(x: Self, _ y: Self) -> Self
/// The maximum of `x` and `y`.
///
/// Returns `x` if `x > y`, `y` if `y > x`, and whichever of `x` or `y`
/// is a number if the other is NaN. The result is NaN only if both
/// arguments are NaN.
static func max(x: Self, _ y: Self) -> Self
// Note: IEEE-754 calls these "minNumMag" and "maxNumMag". C (n1778)
// uses "fminmag" and "fmaxmag". Neither of these strike me as very
// good names. I prefer minMagnitude and maxMagnitude, which are
// clear without being too wordy.
/// Whichever of `x` or `y` has lesser magnitude.
///
/// Returns `x` if `|x| < |y|`, `y` if `|y| < |x|`, and whichever of
/// `x` or `y` is a number if the other is NaN. The result is NaN
/// only if both arguments are NaN.
static func minMagnitude(left: Self, _ right: Self) -> Self
/// Whichever of `x` or `y` has greater magnitude.
///
/// Returns `x` if `|x| > |y|`, `y` if `|y| > |x|`, and whichever of
/// `x` or `y` is a number if the other is NaN. The result is NaN
/// only if both arguments are NaN.
static func maxMagnitude(left: Self, _ right: Self) -> Self
func +(x: Self, y: Self) -> Self
func -(x: Self, y: Self) -> Self
func *(x: Self, y: Self) -> Self
func /(x: Self, y: Self) -> Self
// Implementation details of formatOf operations.
static func _addStickyRounding(x: Self, _ y: Self) -> Self
static func _mulStickyRounding(x: Self, _ y: Self) -> Self
static func _divStickyRounding(x: Self, _ y: Self) -> Self
static func _sqrtStickyRounding(x: Self) -> Self
static func _mulAddStickyRounding(x: Self, _ y: Self, _ z: Self) -> Self
// TODO: do we actually want to provide remainder as an operator? It's
// definitely not obvious to me that we should, but we have until now.
// See further discussion with func remainder(x,y) above.
func %(x: Self, y: Self) -> Self
// Conversions from all integer types.
init(_ value: Int8)
init(_ value: Int16)
init(_ value: Int32)
init(_ value: Int64)
init(_ value: Int)
init(_ value: UInt8)
init(_ value: UInt16)
init(_ value: UInt32)
init(_ value: UInt64)
init(_ value: UInt)
init(_ value: SignificandBits)
// Conversions from all floating-point types.
init(_ value: Float)
init(_ value: Double)
#if arch(i386) || arch(x86_64)
init(_ value: Float80)
#endif
// TODO: where do conversions to/from string live? IEEE-754 requires
// conversions to/from decimal character and hexadecimal character
// sequences.
/// Implements the IEEE-754 copy operation.
prefix func +(value: Self) -> Self
// IEEE-754 negate operation is prefix `-`, provided by SignedNumberType.
// TODO: ensure that the optimizer is able to produce a simple xor for -.
// IEEE-754 abs operation is the free function abs( ), provided by
// SignedNumberType. TODO: ensure that the optimizer is able to produce
// a simple and or bic for abs( ).
// TODO: should this be the free function copysign(x, y) instead, a la C?
/// Returns datum with magnitude of `self` and sign of `from`.
///
/// Implements the IEEE-754 copysign operation.
func copysign(from: Self) -> Self
// TODO: "signaling/quiet" comparison predicates if/when we have a model for
// floating-point flags and exceptions in Swift.
/// The floating point "class" of this datum.
///
/// Implements the IEEE-754 `class` operation.
var floatingPointClass: FloatingPointClassification { get }
/// True if and only if `self` is zero.
var isZero: Bool { get }
/// True if and only if `self` is subnormal.
///
/// A subnormal number does not use the full precision available to normal
/// numbers of the same format. Zero is not a subnormal number.
var isSubnormal: Bool { get }
/// True if and only if `self` is normal.
///
/// A normal number uses the full precision available in the format. Zero
/// is not a normal number.
var isNormal: Bool { get }
/// True if and only if `self` is finite.
///
/// If `x.isFinite` is `true`, then one of `x.isZero`, `x.isSubnormal`, or
/// `x.isNormal` is also `true`, and `x.isInfinite` and `x.isNaN` are
/// `false`.
var isFinite: Bool { get }
/// True if and only if `self` is infinite.
///
/// Note that `isFinite` and `isInfinite` do not form a dichotomy, because
/// they are not total. If `x` is `NaN`, then both properties are `false`.
var isInfinite: Bool { get }
/// True if and only if `self` is NaN ("not a number").
var isNaN: Bool { get }
/// True if and only if `self` is a signaling NaN.
var isSignaling: Bool { get }
/// True if and only if `self` is canonical.
///
/// Every floating-point datum of type Float or Double is canonical, but
/// non-canonical values of type Float80 exist. These are known as
/// "pseudo-denormal", "unnormal", "pseudo-infinity", and "pseudo-nan".
/// (https://en.wikipedia.org/wiki/Extended_precision#x86_Extended_Precision_Format)
var isCanonical: Bool { get }
/// A total order relation on all values of type Self (including NaN).
func totalOrder(other: Self) -> Bool
/// A total order relation that compares magnitudes.
func totalOrderMagnitude(other: Self) -> Bool
// Note: this operation is *not* required by IEEE-754, but it is an oft-
// requested feature. TBD: should +0 and -0 be equivalent? Substitution
// property of equality says no.
//
// More adventurous (probably crazy) thought: we *could* make this (or
// something like it) the default behavior of the == operator, and make
// IEEE-754 equality be the function. IEEE-754 merely dictates that
// certain operations be available, not what their bindings in a
// language actually are. Their are two problems with this:
//
// - it violates the hell out of the principle of least surprise,
// given that programmers have been conditioned by years of using
// other languages.
//
// - it would introduce a gratuitous minor inefficiency to most
// code on the hardware we have today, where IEEE-754 equality is
// generally a single test, and "equivalent" is not.
//
// Still, I want to at least make note of the possibility.
/// An equivalence relation on all values of type Self (including NaN).
///
/// Unlike `==`, this relation is a formal equivalence relation. In
/// particular, it is reflexive. All NaNs compare equal to each other
/// under this relation.
func equivalent(other: Self) -> Bool
}
// Features of FloatingPointType that can be implemented without any
// dependence on the internals of the type.
extension FloatingPointType {
public static var NaN: Self { return NaN(payload: 0, signaling: false) }
public static var ulp: Self { return Self(1).ulp }
public func roundToIntegralTiesToEven() -> Self {
fatalError("TODO once roundeven functions are provided in math.h")
}
public static func minMagnitude(left: Self, _ right: Self) -> Self {
fatalError("TODO once fminmag functions are available in libm")
}
public static func maxMagnitude(left: Self, _ right: Self) -> Self {
fatalError("TODO once fmaxmag functions are available in libm")
}
public static func _addStickyRounding(x: Self, _ y: Self) -> Self {
fatalError("TODO: Unimplemented")
}
public static func _mulStickyRounding(x: Self, _ y: Self) -> Self {
fatalError("TODO: Unimplemented")
}
public static func _divStickyRounding(x: Self, _ y: Self) -> Self {
fatalError("TODO: Unimplemented")
}
public static func _sqrtStickyRounding(x: Self) -> Self {
fatalError("TODO: Unimplemented")
}
public static func _mulAddStickyRounding(x: Self, _ y: Self, _ z: Self) -> Self {
fatalError("TODO: Unimplemented")
}
public var floatingPointClass: FloatingPointClassification {
if isSignaling { return .SignalingNaN }
if isNaN { return .QuietNaN }
if isInfinite { return signbit ? .NegativeInfinity : .PositiveInfinity }
if isNormal { return signbit ? .NegativeNormal : .PositiveNormal }
if isSubnormal { return signbit ? .NegativeSubnormal : .PositiveSubnormal }
return signbit ? .NegativeZero : .PositiveZero
}
public func totalOrderMagnitude(other: Self) -> Bool {
return abs(self).totalOrder(abs(other))
}
public func equivalent(other: Self) -> Bool {
if self.isNaN && other.isNaN { return true }
if self.isZero && other.isZero { return self.signbit == other.signbit }
return self == other
}
}
public protocol BinaryFloatingPointType: FloatingPointType {
/// Values that parametrize the type:
static var _exponentBitCount: UInt { get }
static var _fractionalBitCount: UInt { get }
/// The raw encoding of the exponent field of the floating-point datum.
var exponentBitPattern: UInt { get }
/// The raw encoding of the significand field of the floating-point datum.
var significandBitPattern: SignificandBits { get }
/// The least-magnitude member of the binade of `self`.
///
/// If `x` is `+/-signficand * 2^exponent`, then `x.binade` is
/// `+/- 2^exponent`; i.e. the floating point number with the same sign
/// and exponent, but a significand of 1.0.
var binade: Self { get }
/// Combines a signbit, exponent and signficand bit patterns to produce a
/// floating-point datum. No error-checking is performed by this function;
/// the bit patterns are simply concatenated to produce the floating-point
/// encoding of the result.
init(signbit: Bool,
exponentBitPattern: UInt,
significandBitPattern: SignificandBits)
init<T: BinaryFloatingPointType>(_ other: T)
// TODO: IEEE-754 requires that the six basic operations (add, subtract,
// multiply, divide, square root, and FMA) be provided from all source
// formats to all destination formats, with a single rounding. In order
// to satisfy this requirement (which I believe we should), we'll need
// something like the following.
//
// fusedMultiplyAdd needs naming attention for Swift. The C name
// fma(x,y,z) might be too terse for the Swift standard library, but
// fusedMultiplyAdd is awfully verbose. mulAdd(x, y, z), perhaps?
// Or we could go full Obj-C style and do mul(_:, _:, add:), I suppose.
//
// While `sqrt` and `fma` have traditionally been part of the
// math library in C-derived languages, they rightfully belong as part
// of the base FloatingPointType protocol in Swift, because they are
// IEEE-754 required operations, like + or *.
/// The sum of `x` and `y`, correctly rounded to `Self`.
static func add<X: BinaryFloatingPointType, Y: BinaryFloatingPointType>(x: X, _ y: Y) -> Self
/// The difference of `x` and `y`, correctly rounded to `Self`.
static func sub<X: BinaryFloatingPointType, Y: BinaryFloatingPointType>(x: X, _ y: Y) -> Self
/// The product of `x` and `y`, correctly rounded to `Self`.
static func mul<X: BinaryFloatingPointType, Y: BinaryFloatingPointType>(x: X, _ y: Y) -> Self
/// The quotient of `x` and `y`, correctly rounded to `Self`.
static func div<X: BinaryFloatingPointType, Y: BinaryFloatingPointType>(x: X, _ y: Y) -> Self
/// The square root of `x`, correctly rounded to `Self`.
static func sqrt<X: BinaryFloatingPointType>(x: X) -> Self
/// (x*y) + z correctly rounded to `Self`.
static func mulAdd<X: BinaryFloatingPointType, Y: BinaryFloatingPointType, Z: BinaryFloatingPointType>(x: X, _ y: Y, _ z: Z) -> Self
}
extension BinaryFloatingPointType {
static var _exponentBias: UInt {
return Self._infinityExponent >> 1
}
static var _infinityExponent: UInt {
return 1 << _exponentBitCount - 1
}
static var _integralBitMask: SignificandBits {
return 1 << SignificandBits(UIntMax(_fractionalBitCount))
}
static var _fractionalBitMask: SignificandBits {
return _integralBitMask - 1
}
static var _quietBitMask: SignificandBits {
return _integralBitMask >> 1
}
static var _payloadBitMask: SignificandBits {
return _quietBitMask - 1
}
public static var infinity: Self {
return Self(signbit: false,
exponentBitPattern:_infinityExponent,
significandBitPattern: 0)
}
public static func NaN(payload bits: SignificandBits, signaling: Bool) -> Self {
var significand = bits & _payloadBitMask
if signaling {
// Ensure at least one bit is set in payload, otherwise we will get
// an infinity instead of NaN.
if significand == 0 {
significand = _quietBitMask >> 1
}
} else {
significand = significand | _quietBitMask
}
return Self(signbit: false,
exponentBitPattern: _infinityExponent,
significandBitPattern: significand)
}
public static var greatestFiniteMagnitude: Self {
return Self(signbit: false,
exponentBitPattern: _infinityExponent - 1,
significandBitPattern: _fractionalBitMask)
}
public static var leastNormalMagnitude: Self {
return Self(signbit: false, exponentBitPattern: 1, significandBitPattern: 0)
}
public static var leastMagnitude: Self {
#if arch(arm)
return .leastNormalMagnitude
#else
return Self(signbit: false, exponentBitPattern: 0, significandBitPattern: 1)
#endif
}
public var exponent: Int {
if !isFinite { return .max }
let provisional = Int(exponentBitPattern) - Int(Self._exponentBias)
if isNormal { return provisional }
if isZero { return .min }
let shift = significandBitPattern.leadingZeros - Self._fractionalBitMask.leadingZeros
return provisional - Int(shift)
}
public var significand: Self {
if isNaN { return self }
if isNormal {
return Self(Self._integralBitMask | significandBitPattern) * Self.ulp
}
if isZero { return 0 }
let shift = 1 + significandBitPattern.leadingZeros - Self._fractionalBitMask.leadingZeros
return Self(significandBitPattern << SignificandBits(shift)) * Self.ulp
}
public init(signbit: Bool, exponent: Int, significand: Self) {
var result = significand
if signbit { result = -result }
if significand.isFinite && !significand.isZero {
var clamped = exponent
if clamped < Self.leastNormalMagnitude.exponent {
clamped = max(clamped, 3*Self.leastNormalMagnitude.exponent)
while clamped < Self.leastNormalMagnitude.exponent {
result = result * Self.leastNormalMagnitude
clamped += Self.leastNormalMagnitude.exponent
}
}
else if clamped > Self.greatestFiniteMagnitude.exponent {
clamped = min(clamped, 3*Self.greatestFiniteMagnitude.exponent)
while clamped > Self.greatestFiniteMagnitude.exponent {
result = result * Self.greatestFiniteMagnitude.binade
clamped -= Self.greatestFiniteMagnitude.exponent
}
}
let scale = Self(signbit: false,
exponentBitPattern: UInt(Int(Self._exponentBias) + clamped),
significandBitPattern: Self._integralBitMask)
result = result * scale
}
self = result
}
public var ulp: Self {
if !isFinite { return .NaN }
if exponentBitPattern > Self._fractionalBitCount {
// ulp is normal, so we directly manifest its exponent and use a
// significand of 1.
let ulpExponent = exponentBitPattern - Self._fractionalBitCount
return Self(signbit: false, exponentBitPattern: ulpExponent, significandBitPattern: 0)
}
if exponentBitPattern >= 1 {
// self is normal, but ulp is subnormal; we need to compute a shift
// to apply to the significand.
let ulpShift = SignificandBits(exponentBitPattern - 1)
return Self(signbit: false, exponentBitPattern: 0, significandBitPattern: 1 << ulpShift)
}
return Self(signbit:false, exponentBitPattern:0, significandBitPattern:1)
}
public var nextUp: Self {
if isNaN { return self }
if signbit {
if significandBitPattern == 0 {
if exponentBitPattern == 0 { return Self.leastMagnitude }
return Self(signbit: true,
exponentBitPattern: exponentBitPattern - 1,
significandBitPattern: Self._fractionalBitMask)
}
return Self(signbit: true,
exponentBitPattern: exponentBitPattern,
significandBitPattern: significandBitPattern - 1)
}
if isInfinite { return self }
if significandBitPattern == Self._fractionalBitMask {
return Self(signbit: false,
exponentBitPattern: exponentBitPattern + 1,
significandBitPattern: 0)
}
return Self(signbit: false,
exponentBitPattern: exponentBitPattern,
significandBitPattern: significandBitPattern + 1)
}
public var nextDown: Self { return -(-self).nextUp }
public var binade: Self {
if !isFinite { return .NaN }
if isNormal {
return Self(signbit: false, exponentBitPattern: exponentBitPattern,
significandBitPattern: Self._integralBitMask)
}
if isZero { return 0 }
let shift = significandBitPattern.leadingZeros - Self._integralBitMask.leadingZeros
let significand = Self._integralBitMask >> SignificandBits(shift)
return Self(signbit: false, exponentBitPattern: 0,
significandBitPattern: significand)
}
public static func add<X: BinaryFloatingPointType, Y: BinaryFloatingPointType>(x: X, _ y: Y) -> Self {
if X._fractionalBitCount < Y._fractionalBitCount { return add(y, x) }
if X._fractionalBitCount <= Self._fractionalBitCount { return Self(x) + Self(y) }
return Self(X._addStickyRounding(x, X(y)))
}
public static func sub<X: BinaryFloatingPointType, Y: BinaryFloatingPointType>(x: X, _ y: Y) -> Self {
return Self.add(x, -y)
}
public static func mul<X: BinaryFloatingPointType, Y: BinaryFloatingPointType>(x: X, _ y: Y) -> Self {
if X._fractionalBitCount < Y._fractionalBitCount { return mul(y, x) }
if X._fractionalBitCount <= Self._fractionalBitCount { return Self(x) * Self(y) }
return Self(X._mulStickyRounding(x, X(y)))
}
public static func div<X: BinaryFloatingPointType, Y: BinaryFloatingPointType>(x: X, _ y: Y) -> Self {
if X._fractionalBitCount <= Self._fractionalBitCount &&
Y._fractionalBitCount <= Self._fractionalBitCount { return Self(x) / Self(y) }
if X._fractionalBitCount < Y._fractionalBitCount { return Self(Y._divStickyRounding(Y(x), y)) }
return Self(X._divStickyRounding(x, X(y)))
}
public static func sqrt<X: BinaryFloatingPointType>(x: X) -> Self {
if X._fractionalBitCount <= Self._fractionalBitCount { return sqrt(Self(x)) }
return Self(X._sqrtStickyRounding(x))
}
public static func mulAdd<X: BinaryFloatingPointType, Y: BinaryFloatingPointType, Z: BinaryFloatingPointType>(x: X, _ y: Y, _ z: Z) -> Self {
if X._fractionalBitCount < Y._fractionalBitCount { return mulAdd(y, x, z) }
if X._fractionalBitCount <= Self._fractionalBitCount &&
Z._fractionalBitCount <= Self._fractionalBitCount { return mulAdd(Self(x), Self(y), Self(z)) }
if X._fractionalBitCount < Z._fractionalBitCount { return Self(Z._mulAddStickyRounding(Z(x), Z(y), z)) }
return Self(X._mulAddStickyRounding(x, X(y), X(z)))
}
public var absoluteValue: Self {
return Self(signbit: false, exponentBitPattern: exponentBitPattern,
significandBitPattern: significandBitPattern)
}
public func copysign(from: Self) -> Self {
return Self(signbit: from.signbit, exponentBitPattern: exponentBitPattern,
significandBitPattern: significandBitPattern)
}
public var isZero: Bool {
return exponentBitPattern == 0 && significandBitPattern == 0
}
public var isSubnormal: Bool {
return exponentBitPattern == 0 && significandBitPattern != 0
}
public var isNormal: Bool {
return exponentBitPattern > 0 && isFinite
}
public var isFinite: Bool {
return exponentBitPattern < Self._infinityExponent
}
public var isInfinite: Bool {
return exponentBitPattern == Self._infinityExponent &&
significandBitPattern == Self._integralBitMask
}
public var isNaN: Bool {
return exponentBitPattern == Self._infinityExponent && !isInfinite
}
public var isSignaling: Bool {
return isNaN && (significandBitPattern & Self._quietBitMask == 0)
}
public var isCanonical: Bool { return true }
public func totalOrder(other: Self) -> Bool {
// Every negative-signed value (even NaN) is less than every positive-
// signed value, so if the signs do not match, we simply return the
// signbit of self.
if signbit != other.signbit { return signbit }
// Signbits match; look at exponents.
if exponentBitPattern > other.exponentBitPattern { return signbit }
if exponentBitPattern < other.exponentBitPattern { return !signbit }
// Signs and exponents match, look at significands.
if significandBitPattern > other.significandBitPattern { return signbit }
if significandBitPattern < other.significandBitPattern { return !signbit }
return true
}
}
public protocol FloatingPointInterchangeType: FloatingPointType {
/// An unsigned integer type used to represent floating-point encodings.
typealias BitPattern: FloatingPointRepresentationType
/// Interpret `encoding` as a little-endian encoding of `Self`.
init(littleEndian encoding: BitPattern)
/// Interpret `encoding` as a big-endian encoding of `Self`.
init(bigEndian encoding: BitPattern)
/// Get the little-endian encoding of `self` as an integer.
var littleEndian: BitPattern { get }
/// Get the big-endian encoding of `self` as an integer.
var bigEndian: BitPattern { get }
}
extension FloatingPointInterchangeType {
public init(littleEndian encoding: BitPattern) {
#if arch(i386) || arch(x86_64) || arch(arm) || arch(arm64)
self = unsafeBitCast(encoding, Self.self)
#else
_UnsupportedArchitectureError()
#endif
}
public init(bigEndian encoding: BitPattern) {
fatalError("TODO: with low-level generic integer type support for bswap.")
}
public var littleEndian: BitPattern {
#if arch(i386) || arch(x86_64) || arch(arm) || arch(arm64)
return unsafeBitCast(self, BitPattern.self)
#else
_UnsupportedArchitectureError()
#endif
}
public var bigEndian: BitPattern {
fatalError("TODO: with low-level generic integer type support for bswap.")
}
}
extension Float : BinaryFloatingPointType, FloatingPointInterchangeType {
var _representation: UInt32 { return unsafeBitCast(self, UInt32.self) }
public typealias SignificandBits = UInt32
public typealias BitPattern = UInt32
public static var _fractionalBitCount: UInt { return 23 }
public static var _exponentBitCount: UInt { return 8 }
public var signbit: Bool { return _representation >> 31 == 1 }
public var exponentBitPattern: UInt { return UInt(_representation >> 23) & 0xff }
public var significandBitPattern: SignificandBits { return _representation & Float._fractionalBitMask }
public init(signbit: Bool, exponentBitPattern: UInt, significandBitPattern: SignificandBits) {
let sign = SignificandBits(signbit ? 1 : 0) << 31
let exponent = SignificandBits(exponentBitPattern) << 23
let _representation = sign | exponent | significandBitPattern
self = unsafeBitCast(_representation, Float.self)
}
public init<T: BinaryFloatingPointType>(_ other: T) {
// rdar://16980851 #if does not work with 'switch'
#if arch(i386) || arch(x86_64)
switch other {
case let f as Float:
self = f
case let d as Double:
self = Float(d)
case let ld as Float80:
self = Float(ld)
default:
fatalError()
}
#else
switch other {
case let f as Float:
self = f
case let d as Double:
self = Float(d)
default:
fatalError()
}
#endif
}
public func roundToIntegralTiesToAway() -> Float { return roundf(self) }
public func roundToIntegralTowardZero() -> Float { return truncf(self) }
public func roundToIntegralTowardPositive() -> Float { return ceilf(self) }
public func roundToIntegralTowardNegative() -> Float { return floorf(self) }
public static func remainder(left: Float, _ right: Float) -> Float { return remainderf(left, right) }
public static func min(left: Float, _ right: Float) -> Float { return fminf(left, right) }
public static func max(left: Float, _ right: Float) -> Float { return fmaxf(left, right) }
public static func sqrt(x: Float) -> Float { return sqrtf(x) }
}
extension Double : BinaryFloatingPointType {
var _representation: UInt64 { return unsafeBitCast(self, UInt64.self) }
public typealias SignificandBits = UInt64
public static var _fractionalBitCount: UInt { return 52 }
public static var _exponentBitCount: UInt { return 11 }
public var signbit: Bool { return _representation >> 63 == 1 }
public var exponentBitPattern: UInt { return UInt(_representation >> 52) & 0x7ff }
public var significandBitPattern: SignificandBits { return _representation & Double._fractionalBitMask }
public init(signbit: Bool, exponentBitPattern: UInt, significandBitPattern: SignificandBits) {
let sign = SignificandBits(signbit ? 1 : 0) << 63
let exponent = SignificandBits(exponentBitPattern) << 52
let _representation = sign | exponent | significandBitPattern
self = unsafeBitCast(_representation, Double.self)
}
public init<T: BinaryFloatingPointType>(_ other: T) {
// rdar://16980851 #if does not work with 'switch' cases
#if arch(i386) || arch(x86_64)
switch other {
case let f as Float:
self = Double(f)
case let d as Double:
self = d
case let ld as Float80:
self = Double(ld)
default:
fatalError()
}
#else
switch other {
case let f as Float:
self = Double(f)
case let d as Double:
self = d
default:
fatalError()
}
#endif
}
public func roundToIntegralTiesToAway() -> Double { return round(self) }
public func roundToIntegralTowardZero() -> Double { return trunc(self) }
public func roundToIntegralTowardPositive() -> Double { return ceil(self) }
public func roundToIntegralTowardNegative() -> Double { return floor(self) }
public static func remainder(left: Double, _ right: Double) -> Double { return remainder(left, right) }
public static func min(left: Double, _ right: Double) -> Double { return fmin(left, right) }
public static func max(left: Double, _ right: Double) -> Double { return fmax(left, right) }
}
#if arch(i386) || arch(x86_64)
extension Float80 : BinaryFloatingPointType {
// Internal implementation details
struct _Float80Representation {
var explicitSignificand: UInt64
var signAndExponent: UInt16
var _padding: (UInt16, UInt16, UInt16) = (0, 0, 0)
var signbit: Bool { return signAndExponent >> 15 == 1 }
var exponentBitPattern: UInt { return UInt(signAndExponent) & 0x7fff }
init(explicitSignificand: UInt64, signAndExponent: UInt16) {
self.explicitSignificand = explicitSignificand
self.signAndExponent = signAndExponent
}
}
var _representation: _Float80Representation {
return unsafeBitCast(self, _Float80Representation.self)
}
// Public requirements
public typealias SignificandBits = UInt64
public static var _fractionalBitCount: UInt { return 63 }
public static var _exponentBitCount: UInt { return 15 }
public var signbit: Bool { return _representation.signbit }
public var exponentBitPattern: UInt {
if _representation.exponentBitPattern == 0 {
if _representation.explicitSignificand >= Float80._integralBitMask {
// Pseudo-denormals have an exponent of 0 but the leading bit of the
// significand field is set. These are non-canonical encodings of the
// same significand with an exponent of 1.
return 1
}
// Exponent is zero, leading bit of significand is clear, so this is
// just a canonical zero or subnormal number.
return 0
}
if _representation.explicitSignificand < Float80._integralBitMask {
// If the exponent is not-zero and the leading bit of the significand
// is clear, then we have an invalid operand (unnormal, pseudo-inf, or
// pseudo-nan). All of these are treated as NaN by the hardware, so
// we pretend that the exponent is that of a NaN.
return Float80._infinityExponent
}
return _representation.exponentBitPattern
}
public var significandBitPattern: UInt64 {
if _representation.exponentBitPattern > 0 &&
_representation.explicitSignificand < Float80._integralBitMask {
// If the exponent is non-zero and the leading bit of the significand
// is clear, then we have an invalid operand (unnormal, pseudo-inf, or
// pseudo-nan). All of these are treated as NaN by the hardware, so
// we make sure that bit of the signficand field is set.
return _representation.explicitSignificand | Float80._quietBitMask
}
// Otherwise we always get the "right" significand by simply clearing the
// integral bit.
return _representation.explicitSignificand & Float80._fractionalBitMask
}
public init(signbit: Bool, exponentBitPattern: UInt, significandBitPattern: UInt64) {
let sign = UInt16(signbit ? 0x8000 : 0)
let exponent = UInt16(exponentBitPattern)
var significand = significandBitPattern
if exponent != 0 { significand |= Float80._integralBitMask }
let representation = _Float80Representation(explicitSignificand: significand, signAndExponent: sign|exponent)
self = unsafeBitCast(representation, Float80.self)
}
public init<T: BinaryFloatingPointType>(_ other: T) {
switch other {
case let f as Float:
self = Float80(f)
case let d as Double:
self = Float80(d)
case let ld as Float80:
self = ld
default:
fatalError()
}
}
public func roundToIntegralTiesToAway() -> Float80 { fatalError("TODO: nead roundl( )") }
public func roundToIntegralTowardZero() -> Float80 { fatalError("TODO: nead truncl( )") }
public func roundToIntegralTowardPositive() -> Float80 { fatalError("TODO: nead ceill( )") }
public func roundToIntegralTowardNegative() -> Float80 { fatalError("TODO: nead floorl( )") }
public static func remainder(left: Float80, _ right: Float80) -> Float80 { fatalError("TODO: nead remainderl( )") }
public static func min(left: Float80, _ right: Float80) -> Float80 { fatalError("TODO: nead fminl( )") }
public static func max(left: Float80, _ right: Float80) -> Float80 { fatalError("TODO: nead fmaxl( )") }
public var isCanonical: Bool {
if exponentBitPattern == 0 {
return _representation.explicitSignificand < Float80._integralBitMask
}
return _representation.explicitSignificand >= Float80._integralBitMask
}
}
#endif
// Unchanged from existing FloatingPoint protocol support.
/// The set of IEEE-754 floating-point "classes". Every floating-point datum
/// belongs to exactly one of these classes.
public enum FloatingPointClassification {
case SignalingNaN
case QuietNaN
case NegativeInfinity
case NegativeNormal
case NegativeSubnormal
case NegativeZero
case PositiveZero
case PositiveSubnormal
case PositiveNormal
case PositiveInfinity
}
extension FloatingPointClassification : Equatable {}
public func ==(lhs: FloatingPointClassification, rhs: FloatingPointClassification) -> Bool {
switch (lhs, rhs) {
case (.SignalingNaN, .SignalingNaN),
(.QuietNaN, .QuietNaN),
(.NegativeInfinity, .NegativeInfinity),
(.NegativeNormal, .NegativeNormal),
(.NegativeSubnormal, .NegativeSubnormal),
(.NegativeZero, .NegativeZero),
(.PositiveZero, .PositiveZero),
(.PositiveSubnormal, .PositiveSubnormal),
(.PositiveNormal, .PositiveNormal),
(.PositiveInfinity, .PositiveInfinity):
return true
default:
return false
}
}
//===--- tests ------------------------------------------------------------===//
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
var tests = TestSuite("Floating Point")
tests.test("Parts") {
expectEqual(Int.max, (-Float.infinity).exponent)
expectEqual(127, (-Float.greatestFiniteMagnitude).exponent)
expectEqual(1, Float(-2).exponent)
expectEqual(0, Float(-1).exponent)
expectEqual(-1, Float(-0.5).exponent)
expectEqual(-23, (-Float.ulp).exponent)
expectEqual(-125, (-2*Float.leastNormalMagnitude).exponent)
expectEqual(-126, Float.leastNormalMagnitude.exponent)
#if !arch(arm)
expectEqual(-127, (-0.5*Float.leastNormalMagnitude).exponent)
expectEqual(-149, (-Float.leastMagnitude).exponent)
#endif
expectEqual(Int.min, Float(-0).exponent)
expectEqual(Int.min, Float(0).exponent)
#if !arch(arm)
expectEqual(-149, Float.leastMagnitude.exponent)
expectEqual(-127, (Float.leastNormalMagnitude/2).exponent)
#endif
expectEqual(-126, Float.leastNormalMagnitude.exponent)
expectEqual(-125, (2*Float.leastNormalMagnitude).exponent)
expectEqual(-23, Float.ulp.exponent)
expectEqual(-1, Float(0.5).exponent)
expectEqual(0, Float(1).exponent)
expectEqual(1, Float(2).exponent)
expectEqual(127, Float.greatestFiniteMagnitude.exponent)
expectEqual(Int.max, Float.infinity.exponent)
expectEqual(Int.max, Float.NaN.exponent)
expectEqual(Int.max, (-Double.infinity).exponent)
expectEqual(1023, (-Double.greatestFiniteMagnitude).exponent)
expectEqual(1, Double(-2).exponent)
expectEqual(0, Double(-1).exponent)
expectEqual(-1, Double(-0.5).exponent)
expectEqual(-52, (-Double.ulp).exponent)
expectEqual(-1021, (-2*Double.leastNormalMagnitude).exponent)
expectEqual(-1022, Double.leastNormalMagnitude.exponent)
#if !arch(arm)
expectEqual(-1023, (-0.5*Double.leastNormalMagnitude).exponent)
expectEqual(-1074, (-Double.leastMagnitude).exponent)
#endif
expectEqual(Int.min, Double(-0).exponent)
expectEqual(Int.min, Double(0).exponent)
#if !arch(arm)
expectEqual(-1074, Double.leastMagnitude.exponent)
expectEqual(-1023, (Double.leastNormalMagnitude/2).exponent)
#endif
expectEqual(-1022, Double.leastNormalMagnitude.exponent)
expectEqual(-1021, (2*Double.leastNormalMagnitude).exponent)
expectEqual(-52, Double.ulp.exponent)
expectEqual(-1, Double(0.5).exponent)
expectEqual(0, Double(1).exponent)
expectEqual(1, Double(2).exponent)
expectEqual(1023, Double.greatestFiniteMagnitude.exponent)
expectEqual(Int.max, Double.infinity.exponent)
expectEqual(Int.max, Double.NaN.exponent)
#if arch(i386) || arch(x86_64)
expectEqual(Int.max, (-Float80.infinity).exponent)
expectEqual(16383, (-Float80.greatestFiniteMagnitude).exponent)
expectEqual(1, Float80(-2).exponent)
expectEqual(0, Float80(-1).exponent)
expectEqual(-1, Float80(-0.5).exponent)
expectEqual(-63, (-Float80.ulp).exponent)
expectEqual(-16381, (-2*Float80.leastNormalMagnitude).exponent)
expectEqual(-16382, Float80.leastNormalMagnitude.exponent)
expectEqual(-16383, (-0.5*Float80.leastNormalMagnitude).exponent)
expectEqual(-16445, (-Float80.leastMagnitude).exponent)
expectEqual(Int.min, Float80(-0).exponent)
expectEqual(Int.min, Float80(0).exponent)
expectEqual(-16445, Float80.leastMagnitude.exponent)
expectEqual(-16383, (Float80.leastNormalMagnitude/2).exponent)
expectEqual(-16382, Float80.leastNormalMagnitude.exponent)
expectEqual(-16381, (2*Float80.leastNormalMagnitude).exponent)
expectEqual(-63, Float80.ulp.exponent)
expectEqual(-1, Float80(0.5).exponent)
expectEqual(0, Float80(1).exponent)
expectEqual(1, Float80(2).exponent)
expectEqual(16383, Float80.greatestFiniteMagnitude.exponent)
expectEqual(Int.max, Float80.infinity.exponent)
expectEqual(Int.max, Float80.NaN.exponent)
#endif
}
runAllTests()
|
apache-2.0
|
3b5d3d9d1ddc27644f6725f8151dac1e
| 38.698765 | 143 | 0.686777 | 4.064549 | false | false | false | false |
Eonil/EditorLegacy
|
Modules/EditorDebuggingFeature/EditorDebuggingFeature/ListenerController.swift
|
1
|
2327
|
//
// ListenerController.swift
// EditorDebuggingFeature
//
// Created by Hoon H. on 2015/02/04.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
import LLDBWrapper
import EditorCommon
public protocol ListenerControllerDelegate: class {
/// Called when the debugger has stopped for a event.
/// Target process is stopped, and won't resume until you call `continue`
/// explicitly.
///
/// This will be called in main thread.
func listenerControllerIsProcessingEvent(e:LLDBEvent)
}
/// Manages event handling in separated thread and route them back to main thread.
/// Set delegate to get notified for events.
///
/// YOU MUST SET A DELEGATE!
/// This object will crash if you have no delegate set when an event fires.
public final class ListenerController {
public weak var delegate:ListenerControllerDelegate? {
get {
return _core.delegate
}
set(v) {
_core.delegate = v
}
}
public init() {
_core = Core()
}
deinit {
}
public var listener:LLDBListener {
get {
return _core.listener
}
}
public func startListening() {
assert(self.delegate != nil)
let core = _core
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) { [unowned self] in
var cont = true
while cont {
let WAIT_SECONDS = 1
if let e = core.listener.waitForEvent(WAIT_SECONDS) {
/// Wait for main thread processing done.
dispatch_sync(dispatch_get_main_queue()) { [unowned self] in
Debug.log(e)
core.delegate!.listenerControllerIsProcessingEvent(e)
cont = core.done == false
()
}
}
}
dispatch_sync(dispatch_get_main_queue()) { [unowned self] in
Debug.log("ListenerController exited.")
}
}
}
public func stopListening() {
_core.done = true
}
////
private let _core:Core
// private var _done:Bool
}
private final class Core {
weak var delegate:ListenerControllerDelegate? {
willSet(v) {
precondition((v == nil) != (delegate == nil), "Set `nil` first before setting a new delegate to express your intention clearly.")
}
}
let listener = LLDBListener(name: "Eonil/Editor LLDB Main Listener")
var done = false
init() {
}
deinit {
assert(done == true, "This `ListenerController`'s listening thread has not been marked as finished. Call `stopListening` first.")
}
}
|
mit
|
5c21c9277d6dd42f8f8eac98d9abb502
| 22.989691 | 132 | 0.683283 | 3.300709 | false | false | false | false |
sora0077/Memcached
|
Sources/ConnectionPool.swift
|
1
|
1452
|
//
// ConnectionPool.swift
// Memcached
//
// Created by 林達也 on 2016/01/11.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import Foundation
import CMemcached
import CMemcachedUtil
final public class ConnectionPool {
public let options: ConnectionOption
private var _pool: COpaquePointer?
private var _connections: [Connection] = []
public init(options: ConnectionOption) {
self.options = options
_pool = memcached_pool(options.configuration, options.configuration.utf8.count)
}
public convenience init(options: [String]) {
self.init(options: ConnectionOptions(options: options.map { StringLiteralConnectionOption(stringLiteral: $0) }))
}
public convenience init(options: String...) {
self.init(options: options)
}
deinit {
detach()
}
func detach() {
if let pool = _pool {
memcached_pool_destroy(pool)
}
}
public func connection() throws -> Connection {
var rc: memcached_return = CMemcached.MEMCACHED_MAXIMUM_RETURN
let mc = memcached_pool_pop(_pool!, false, &rc)
try throwIfError(mc, rc)
let conn = Connection(memcached: mc, pool: self)
return conn
}
func pop(mc: UnsafeMutablePointer<memcached_st>) {
if let pool = _pool {
memcached_pool_push(pool, mc)
}
}
}
|
mit
|
4505a6637f361067e6599c8f5f77fc66
| 23.474576 | 120 | 0.61192 | 4.219298 | false | false | false | false |
ludoded/PineFinders
|
Pine Finders/ViewModel/CarViewModel.swift
|
1
|
2748
|
//
// CarViewModel.swift
// Pine Finders
//
// Created by Haik Ampardjian on 5/26/16.
// Copyright © 2016 Aztech Films. All rights reserved.
//
import Foundation
enum CarFilter: Int {
case Make
case Model
case Years
case Body
case Doors
case Seats
}
class CarViewModel {
private var cars = [CarsObject]()
private var filteredCars = [CarsObject]()
var oneResultRemains: ((CarsObject) -> ())?
var filteredModels: [String]?
var filteredMakes: [String]?
var filteredYears: [String]?
var filteredDoors: [String]?
var filteredSeats: [String]?
var filteredBody: [String]?
var selectedCar: CarsObject?
var makeFilter: String?
var modelFilter: String?
var yearsFilter: String?
var bodyFilter: String?
var doorsFilter: String?
var seatsFilter: String?
func loadData(completionHandler: () -> ()) {
FirebaseManager.sharedInstance.cars { (cars) in
self.cars = cars
self.filteredCars = cars
completionHandler()
}
}
func retrieveMakes() {
filteredMakes = uniq(allFilteredCars().map({ $0.car.make }))
}
func retrieveModels() {
filteredModels = uniq(allFilteredCars().map({ $0.car.model }))
}
func retrieveYears() {
filteredYears = uniq(allFilteredCars().map({ $0.car.yearsProduced }))
}
func retrieveBody() {
filteredBody = uniq(allFilteredCars().map({ $0.car.body }))
}
func retrieveDoors() {
filteredDoors = uniq(allFilteredCars().map({ $0.car.doors }))
}
func retrieveSeats() {
filteredSeats = uniq(allFilteredCars().map({ $0.car.seats }))
}
private func allFilteredCars() -> [CarsObject] {
var allFiltered = filteredCars
if let safeMakeFilter = makeFilter { allFiltered = allFiltered.filter({ $0.car.make == safeMakeFilter }) }
if let safeModelFilter = modelFilter { allFiltered = allFiltered.filter({ $0.car.model == safeModelFilter }) }
if let safeyearsFilter = yearsFilter { allFiltered = allFiltered.filter({ $0.car.yearsProduced == safeyearsFilter }) }
if let safeBodyFilter = bodyFilter { allFiltered = allFiltered.filter({ $0.car.body == safeBodyFilter }) }
if let safeDoorsFilter = doorsFilter { allFiltered = allFiltered.filter({ $0.car.doors == safeDoorsFilter }) }
if let safeSeatsFilter = seatsFilter { allFiltered = allFiltered.filter({ $0.car.seats == safeSeatsFilter }) }
if allFiltered.count == 1 {
oneResultRemains?(allFiltered.first!)
selectedCar = allFiltered.first
}
return allFiltered
}
}
|
mit
|
9bf8e9a7cb5483bc366b768088eaa655
| 29.197802 | 126 | 0.619949 | 4.137048 | false | false | false | false |
ianchengtw/ios_30_apps_in_30_days
|
Day_01_TodoApp/TodoApp/TodoApp/controllers/RootTableViewController.swift
|
1
|
3950
|
//
// RootTableViewController.swift
// TodoApp
//
// Created by Ian on 5/7/16.
// Copyright © 2016 ianchengtw_ios_30_apps_in_30_days. All rights reserved.
//
import UIKit
class RootTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return todoItemModel.todoItemList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
if let cell = cell as? TodoItemCell,
let todoItem = todoItemModel.getTodoItem(indexPath.row)
{
cell.textLabel?.text = todoItem.title
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "editItem",
let selectedIndexPath = self.tableView.indexPathForSelectedRow,
let ctrl = segue.destinationViewController as? EditItemViewController,
let todoItem = todoItemModel.getTodoItem(selectedIndexPath.row)
{
ctrl.todoItem = todoItem
}
}
}
|
mit
|
ce1a25733e43cdcf60a33034435272d2
| 32.752137 | 157 | 0.662953 | 5.609375 | false | false | false | false |
jgonfer/JGFLabRoom
|
JGFLabRoom/Controller/Information Access/OAuth/SGoogleDriveViewController.swift
|
1
|
2618
|
//
// SGoogleDriveViewController.swift
// JGFLabRoom
//
// Created by Josep González on 25/1/16.
// Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved.
//
/*
* MARK: IMPORTANT: For more information about Google Drive API
* go to http://console.developer.google.com
*/
import UIKit
class SGoogleDriveViewController: UITableViewController {
var results = ["Sig in with Google Drive"]
var indexSelected: NSIndexPath?
override func viewDidLoad() {
super.viewDidLoad()
setupController()
}
private func setupController() {
Utils.registerStandardXibForTableView(tableView, name: "cell")
Utils.cleanBackButtonTitle(navigationController)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let indexSelected = indexSelected else {
return
}
switch segue.identifier! {
case kSegueIdListApps:
if let vcToShow = segue.destinationViewController as? ListAppsViewController {
vcToShow.indexSelected = indexSelected
}
default:
break
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 55
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseIdentifier = "cell"
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier)
if (cell != nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
}
cell!.textLabel!.text = results[indexPath.row]
cell?.accessoryType = .DisclosureIndicator
//cell!.detailTextLabel!.text = "some text"
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.indexSelected = indexPath
performSegueWithIdentifier(kSegueIdListApps, sender: tableView)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
9b52c2e5cd37607833ec14cecbe477ee
| 31.308642 | 118 | 0.668578 | 5.542373 | false | false | false | false |
groovelab/SwiftBBS
|
SwiftBBS/SwiftBBS/UserRegisterViewController.swift
|
1
|
2922
|
//
// UserRegisterViewController.swift
// SwiftBBS
//
// Created by Takeo Namba on 2016/01/18.
// Copyright GrooveLab
//
import UIKit
import PerfectLib
class UserRegisterViewController: UIViewController {
let END_POINT: String = "http://\(Config.END_POINT_HOST):\(Config.END_POINT_PORT)/user/register"
var user: JSONDictionaryType?
@IBOutlet weak private var nameTextField: UITextField!
@IBOutlet weak private var passwordTextField: UITextField!
@IBOutlet weak private var password2TextField: UITextField!
@IBAction private func registerAction(sender: UIButton) {
doRegister()
}
private func doRegister() {
guard let name = nameTextField.text else {
return
}
guard let passowrd = passwordTextField.text else {
return
}
guard let passowrd2 = password2TextField.text else {
return
}
if name.isEmpty || passowrd.isEmpty || passowrd2.isEmpty {
return
}
let req = NSMutableURLRequest(URL: NSURL(string: END_POINT)!)
req.HTTPMethod = "POST"
req.addValue("application/json", forHTTPHeaderField: "Accept")
req.addTokenToCookie()
let postBody = "name=\(name)&password=\(passowrd)&password2=\(passowrd2)"
req.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(req, completionHandler: {
(data:NSData?, res:NSURLResponse?, error:NSError?) -> Void in
if let error = error {
print("Request failed with error \(error)")
return;
}
guard let data = data, let stringData = String(data: data, encoding: NSUTF8StringEncoding) else {
print("response is empty")
return;
}
do {
let jsonDecoded = try JSONDecoder().decode(stringData)
if let jsonMap = jsonDecoded as? JSONDictionaryType {
if let status = jsonMap["status"] as? String {
if status == "success" {
dispatch_async(dispatch_get_main_queue(), {
self.didRegister()
})
} else {
print("register failed")
}
}
}
} catch let exception {
print("JSON decoding failed with exception \(exception)")
}
})
task.resume()
}
private func didRegister() {
navigationController?.popToRootViewControllerAnimated(true)
navigationController?.viewControllers.first?.dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
16a61396279256b1d45dfc2aa9c66f85
| 33.785714 | 109 | 0.559206 | 5.312727 | false | false | false | false |
Snowgan/WeiboDemo
|
WeiboDemo/XLBasicStatus.swift
|
1
|
6236
|
//
// XLBasicStatus.swift
// WeiboDemo
//
// Created by Jennifer on 31/1/16.
// Copyright © 2016 Snowgan. All rights reserved.
//
import Foundation
enum XLMatchType {
case Username, Topic, Link
}
struct XLMatchResult {
var result: NSTextCheckingResult
var type: XLMatchType
var value: String
}
class XLBasicStatus: NSObject {
var text: String!
var attributedText: NSMutableAttributedString {
return addAttributeForText(text)
}
var links: [XLAttributedTextLink]?
var matchResults = [XLMatchResult]()
func addAttributeForText(var text: String) -> NSMutableAttributedString {
var attrStr = NSMutableAttributedString(string: text)
var textRange = NSRange(location: 0, length: text.characters.count)
// Emoticons
let emoPattern = "\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+?\\]"
let emoRegExp = try! NSRegularExpression(pattern: emoPattern, options: .CaseInsensitive)
let emoMatchs = emoRegExp.matchesInString(text, options: NSMatchingOptions(rawValue: 0), range: textRange)
if !emoMatchs.isEmpty {
let emoPath = NSBundle.mainBundle().pathForResource("emoticons", ofType: "plist")!
let emoArray = NSArray(contentsOfFile: emoPath)!
for match in emoMatchs.reverse() {
let emoStr = (text as NSString).substringWithRange(match.range)
for i in 0..<emoArray.count {
let curEmo = emoArray[i] as! NSDictionary
let curEmoName = curEmo["chs"] as! String
if curEmoName == emoStr {
let emoAttach = NSTextAttachment()
emoAttach.image = UIImage(named: (curEmo["png"] as! String))?.resizeImageWithWidth(12)
let emoAttrStr = NSAttributedString(attachment: emoAttach)
attrStr.replaceCharactersInRange(match.range, withAttributedString: emoAttrStr)
}
}
}
text = attrStr.string
textRange = NSMakeRange(0, text.characters.count)
}
// URL Tappable: "http(s)://..."
let urlDetector = try! NSDataDetector(types: NSTextCheckingType.Link.rawValue)
let urlMatchs = urlDetector.matchesInString(text, options: NSMatchingOptions(rawValue: 0), range: textRange)
if urlMatchs.count != 0 {
let mutableText = NSMutableString(string: text)
for match in urlMatchs.reverse() {
let res = XLMatchResult(result: match, type: .Link, value: mutableText.substringWithRange(match.range))
matchResults.insert(res, atIndex: 0)
mutableText.replaceCharactersInRange(match.range, withString: "网页链接")
}
text = mutableText as String
textRange = NSMakeRange(0, text.characters.count)
attrStr = NSMutableAttributedString(string: text)
let linkPattern = "网页链接"
let linkRegExp = try! NSRegularExpression(pattern: linkPattern, options: NSRegularExpressionOptions(rawValue: 0))
let linkMatchs = linkRegExp.matchesInString(text, options: NSMatchingOptions(rawValue: 0), range: textRange)
if urlMatchs.count == linkMatchs.count {
for i in 0..<linkMatchs.count {
matchResults[i].result = linkMatchs[i]
}
} else {
print("Link Match Error!")
matchResults.removeAll()
}
}
// Username Tappable: "@..."
let namePattern = "@[^@\\s]+?[:|\\s]"
let nameRegExp = try! NSRegularExpression(pattern: namePattern, options: NSRegularExpressionOptions(rawValue: 0))
let nameMatchs = nameRegExp.matchesInString(text, options: NSMatchingOptions(rawValue: 0), range: textRange)
for match in nameMatchs {
let res = XLMatchResult(result: match, type: .Username, value: "")
matchResults.append(res)
}
// Topic Tappable: "#...#"
let topicPattern = "#[^#]+?#"
let topicRegExp = try! NSRegularExpression(pattern: topicPattern, options: NSRegularExpressionOptions(rawValue: 0))
let topicMatchs = topicRegExp.matchesInString(text, options: NSMatchingOptions(rawValue: 0), range: textRange)
for match in topicMatchs {
let res = XLMatchResult(result: match, type: .Topic, value: "")
matchResults.append(res)
}
if matchResults.count != 0 {
links = [XLAttributedTextLink]()
var attrRange = NSRange()
var linkValue = ""
for res in matchResults {
attrRange = res.result.range
switch res.type {
case .Username:
attrRange = NSMakeRange(attrRange.location, attrRange.length-1)
linkValue = (text as NSString).substringWithRange(NSMakeRange(attrRange.location+1, attrRange.length-1))
case .Topic:
linkValue = (text as NSString).substringWithRange(NSMakeRange(attrRange.location+1, attrRange.length-2))
case .Link:
linkValue = res.value
}
let link = XLAttributedTextLink(withRange: attrRange)
link.linkValue = linkValue
links!.append(link)
print(link.linkValue)
attrStr.addAttributes(link.attributes, range: link.range)
}
}
return attrStr
}
}
extension UIImage {
func resizeImageWithWidth(width: CGFloat) -> UIImage {
let scale = width / self.size.width
let height = self.size.height * scale
UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 0.0)
self.drawInRect(CGRect(x: 0, y: 0, width: width, height: height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
|
mit
|
93f29530ec231b966297e7c17a56dbb0
| 40.46 | 125 | 0.58868 | 4.920095 | false | false | false | false |
Rendel27/RDExtensionsSwift
|
RDExtensionsSwift/RDExtensionsSwiftUnitTests/DateTests.swift
|
1
|
3488
|
//
// DateTests.swift
//
// Created by Giorgi Iashvili on 23.09.16.
// Copyright (c) 2016 Giorgi Iashvili
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
import RDExtensionsSwift
open class DateTests : XCTestCase {
let date = Date(timeIntervalSince1970: 1474647378.123456)
let nanoseconds = 123456
let second = 18
let minute = 16
let hour = 20
let day = 23
let weekDay = 6
let weekdayOrdinal = 4
let month = 9
let year = 2016
let era = 1
func testToString()
{
XCTAssertEqual(self.date.toString("dd-MM-YY"), "23-09-16")
XCTAssertEqual(self.date.toString("ss-mm-HH"), "18-16-20")
}
func testFromString()
{
let d1 = Date(formattedString: "01-01-1970", format: "dd-MM-yyyy", timeZone: .utc)
let d2 = Date(timeIntervalSince1970: 0)
XCTAssertEqual(d1?.day, d2.day)
XCTAssertEqual(d1?.month, d2.month)
XCTAssertEqual(d1?.year, d2.year)
XCTAssertEqual(self.date.toString("ss-mm-HH"), "18-16-20")
}
func testTimeIntervalSince1970Milliseconds()
{
XCTAssertEqual(self.date.timeIntervalSince1970Milliseconds, 1474647378123)
}
func testProperties()
{
// XCTAssertEqual(self.date.nanosecond, self.nanoseconds)
XCTAssertEqual(self.date.second, self.second)
XCTAssertEqual(self.date.minute, self.minute)
XCTAssertEqual(self.date.hour, self.hour)
XCTAssertEqual(self.date.day, self.day)
XCTAssertEqual(self.date.weekDay, self.weekDay)
XCTAssertEqual(self.date.weekdayOrdinal, self.weekdayOrdinal)
XCTAssertEqual(self.date.month, self.month)
XCTAssertEqual(self.date.year, self.year)
XCTAssertEqual(self.date.era, self.era)
}
func testDateWithValue()
{
let d = Date(nanosecond: self.nanoseconds, second: self.second, minute: self.minute, hour: self.hour, day: self.day, month: self.month, year: self.year, timeZone: TimeZone.current)
// XCTAssertEqual(self.date.nanosecond, d?.nanosecond)
XCTAssertEqual(self.date.second, d?.second)
XCTAssertEqual(self.date.minute, d?.minute)
XCTAssertEqual(self.date.hour, d?.hour)
XCTAssertEqual(self.date.day, d?.day)
XCTAssertEqual(self.date.month, d?.month)
XCTAssertEqual(self.date.year, d?.year)
XCTAssertEqual(self.date.year, d?.year)
}
}
|
mit
|
0e21cf327832726158e9d042b17129f8
| 37.32967 | 188 | 0.684633 | 4.018433 | false | true | false | false |
brunomorgado/ScrollableAnimation
|
ScrollableAnimation/Source/Animation/Interpolators/BasicInterpolator/BasicValueInterpolator.swift
|
1
|
6389
|
//
// BasicValueInterpolator.swift
// ScrollableMovie
//
// Created by Bruno Morgado on 25/12/14.
// Copyright (c) 2014 kocomputer. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
class BasicValueInterpolator: BasicInterpolator {
var animatable: CALayer
required init(animatable: CALayer) {
self.animatable = animatable
}
private func interpolatedPoint(offset: Float, animation: ScrollableBasicAnimation) -> CGPoint {
var point = CGPointZero
if let animation = animation as ScrollableBasicAnimation? {
let offsetPercentage = BasicInterpolator.getPercentageForOffset(offset, animation: animation)
if let fromValue = animation.fromValue as NSValue? {
if let toValue = animation.toValue as NSValue? {
if (offsetPercentage <= 0) {
point = fromValue.CGPointValue()
} else if (offsetPercentage > 1) {
point = toValue.CGPointValue()
} else {
let verticalDeltaX = Double(toValue.CGPointValue().x - fromValue.CGPointValue().x)
let verticalDeltaY = Double(toValue.CGPointValue().y - fromValue.CGPointValue().y)
var valueX: Float
var valueY: Float
var tween = animation.offsetFunction
if let tween = tween as TweenBlock? {
valueX = Float(fromValue.CGPointValue().x) + Float(tween(Double(offsetPercentage))) * Float(verticalDeltaX)
valueY = Float(fromValue.CGPointValue().y) + Float(tween(Double(offsetPercentage))) * Float(verticalDeltaY)
} else {
valueX = Float(fromValue.CGPointValue().x) + (offsetPercentage * Float(verticalDeltaX))
valueY = Float(fromValue.CGPointValue().y) + offsetPercentage * Float(verticalDeltaY)
}
point = CGPoint(x: CGFloat(valueX), y: CGFloat(valueY))
}
}
}
}
return point
}
private func interpolatedSize(offset: Float, animation: ScrollableBasicAnimation) -> CGSize {
var size = CGSizeZero
if let animation = animation as ScrollableBasicAnimation? {
let offsetPercentage = BasicInterpolator.getPercentageForOffset(offset, animation: animation)
if let fromValue = animation.fromValue as NSValue? {
if let toValue = animation.toValue as NSValue? {
let verticalDeltaWidth = Double(toValue.CGSizeValue().width - fromValue.CGSizeValue().width)
let verticalDeltaHeight = Double(toValue.CGSizeValue().height - fromValue.CGSizeValue().height)
var valueWidth: Float
var valueHeight: Float
var tween = animation.offsetFunction
if let tween = tween as TweenBlock? {
valueWidth = Float(fromValue.CGSizeValue().width) + Float(tween(Double(offsetPercentage))) * Float(verticalDeltaWidth)
valueHeight = Float(fromValue.CGSizeValue().height) + Float(tween(Double(offsetPercentage))) * Float(verticalDeltaHeight)
} else {
valueWidth = Float(fromValue.CGSizeValue().width) + offsetPercentage * Float(verticalDeltaWidth)
valueHeight = Float(fromValue.CGSizeValue().height) + offsetPercentage * Float(verticalDeltaHeight)
}
size = CGSize(width: CGFloat(valueWidth), height: CGFloat(valueHeight))
}
}
}
return size
}
}
extension BasicValueInterpolator: BasicInterpolatorProtocol {
func interpolateAnimation(animation: ScrollableAnimation, forAnimatable animatable: CALayer, forOffset offset: Float) {
if let animation = animation as? ScrollableBasicAnimation {
if let fromValue = animation.fromValue as NSValue? {
if let toValue = animation.toValue as NSValue? {
let type = String.fromCString(toValue.objCType) ?? ""
switch true {
case type.hasPrefix("{CGPoint"):
let point = self.interpolatedPoint(offset, animation: animation)
self.animatable.setValue(NSValue(CGPoint: point), forKeyPath: animation.keyPath)
case type.hasPrefix("{CGSize"):
let size = self.interpolatedSize(offset, animation: animation)
self.animatable.setValue(NSValue(CGSize: size), forKeyPath: animation.keyPath)
default:
return
}
} else {
println("Warning!! Invalid value type when expecting NSValue")
}
} else {
println("Warning!! Invalid value type when expecting NSValue")
}
} else {
println("Warning!! Invalid value type when expecting NSValue")
}
}
}
|
mit
|
c19d884ef2239b7bbb88179fe42e399b
| 50.532258 | 145 | 0.596494 | 5.428207 | false | false | false | false |
Nyx0uf/MPDRemote
|
src/common/model/MusicalEntity.swift
|
1
|
1563
|
// MusicalEntity.swift
// Copyright (c) 2017 Nyx0uf
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class MusicalEntity : Hashable
{
// MARK: - Public properties
// Name
var name: String
// MARK: - Initializers
init(name: String)
{
self.name = name
}
// MARK: - Hashable
var hashValue: Int
{
get
{
return name.hashValue
}
}
}
// MARK: - Equatable
extension MusicalEntity : Equatable
{
static func ==(lhs: MusicalEntity, rhs: MusicalEntity) -> Bool
{
return (lhs.name == rhs.name)
}
}
|
mit
|
f15590cda8af067d9883b2cd5ef3751d
| 27.418182 | 80 | 0.731926 | 3.927136 | false | false | false | false |
fluttercommunity/plus_plugins
|
packages/battery_plus/battery_plus/macos/Classes/BatteryPlusChargingHandler.swift
|
1
|
2977
|
//
// BatteryPlusChargingHandler.swift
// battery_plus
//
// Created by Neevash Ramdial on 08/09/2020.
//
import Foundation
import FlutterMacOS
class BatteryPlusChargingHandler: NSObject, FlutterStreamHandler {
private var context: Int = 0
private var source: CFRunLoopSource?
private var runLoop: CFRunLoop?
private var eventSink: FlutterEventSink?
func onListen(withArguments arguments: Any?, eventSink event: @escaping FlutterEventSink) -> FlutterError? {
self.eventSink = event
start()
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
stop()
self.eventSink = nil
return nil
}
func start() {
// If there is an added loop, we remove it before adding a new one.
stop()
// Gets the initial battery status
let initialStatus = getBatteryStatus()
if let sink = self.eventSink {
sink(initialStatus)
}
// Registers a run loop which is notified when the battery status changes
let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
source = IOPSNotificationCreateRunLoopSource({ (context) in
let _self = Unmanaged<BatteryPlusChargingHandler>.fromOpaque(UnsafeRawPointer(context!)).takeUnretainedValue()
let status = _self.getBatteryStatus()
print(status)
if let sink = _self.eventSink {
sink(status)
}
}, context).takeUnretainedValue()
// Adds loop to source
runLoop = RunLoop.current.getCFRunLoop()
CFRunLoopAddSource(runLoop, source, .defaultMode)
}
func stop() {
guard let runLoop = runLoop, let source = source else {
return
}
CFRunLoopRemoveSource(runLoop, source, .defaultMode)
}
func getBatteryStatus()-> String {
let powerSourceSnapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let sources = IOPSCopyPowerSourcesList(powerSourceSnapshot).takeRetainedValue() as [CFTypeRef]
// Desktops do not have battery sources and are always charging.
if sources.isEmpty {
return "charging"
}
let description = IOPSGetPowerSourceDescription(powerSourceSnapshot, sources[0]).takeUnretainedValue() as! [String: AnyObject]
if let currentCapacity = description[kIOPSCurrentCapacityKey] as? Int {
if currentCapacity >= 95 {
return "full"
}
}
// Returns nil when battery is discharging
if let isCharging = (description[kIOPSPowerSourceStateKey] as? String) {
if isCharging == kIOPSACPowerValue {
return "charging"
} else if isCharging == kIOPSBatteryPowerValue {
return "discharging"
} else {
return "unknown"
}
}
return "UNAVAILABLE"
}
}
|
bsd-3-clause
|
170d17433cfcbab1375533fb6bc8243a
| 31.714286 | 134 | 0.627141 | 4.945183 | false | false | false | false |
Jasonbit/JBModel-Swift
|
JBModel-SwiftTests/JsonUtils.swift
|
1
|
1396
|
//
// JsonUtils.swift
// JBModel-Swift
//
// Created by Jason Lee on 7/24/14.
// Copyright (c) 2014 Jason Lee. All rights reserved.
//
import UIKit
class JsonUtils: NSObject {
class func returnJsonAsCollection() -> AnyObject? {
let bundles = NSBundle.allBundles()
// JBModel-SwiftTests.xctest
// Still not sure about this part. I took the allBundles() approach because getting a bundle
// for class was not working correctly.. In obj-c I could do:
// NSBundle *bundle = [NSBundle bundleForClass:[self class]];
// NSURL *url = [bundle URLForResource:"user" withExtension:@"json"];
let matches = bundles.filter({$0.bundlePath!.hasSuffix("JBModel-SwiftTests.xctest")})
let bundle:NSBundle = matches[matches.startIndex] as NSBundle
let path = bundle.pathForResource("user", ofType: "json")
var error = NSError?()
let jsonData = NSData.dataWithContentsOfFile(path!, options: .DataReadingMappedIfSafe, error: &error)
let jsonResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error)
// We should only get this if there is some problem with the json not being valid
if error != nil {
println("error: \(error!)")
}
return jsonResult
}
}
|
mit
|
ae8fa16c9ddbfbe46a867d3d4361e3ec
| 33.9 | 149 | 0.649713 | 4.637874 | false | true | false | false |
ivanbruel/SwipeIt
|
SwipeIt/Models/Enums/Scope.swift
|
1
|
925
|
//
// Scope.swift
// Reddit
//
// Created by Ivan Bruel on 03/05/16.
// Copyright © 2016 Faber Ventures. All rights reserved.
//
import Foundation
enum Scope: String {
case Creddits = "creddits"
case ModContributors = "modcontributors"
case ModConfig = "modconfig"
case Subscribe = "subscribe"
case WikiRead = "wikiread"
case WikiEdit = "wikiedit"
case Vote = "vote"
case MySubreddits = "mysubreddits"
case Submit = "submit"
case ModLog = "modlog"
case ModPosts = "modposts"
case ModFlair = "modflair"
case Save = "save"
case ModOthers = "modothers"
case Read = "read"
case PrivateMessages = "privatemessages"
case Report = "report"
case Identity = "identity"
case LiveManage = "livemanage"
case Account = "account"
case ModTraffic = "modtraffic"
case Edit = "edit"
case ModWiki = "modwiki"
case ModSelf = "modself"
case History = "history"
case Flair = "flair"
}
|
mit
|
4a0d3cde379952aa79702c87829b3a35
| 22.1 | 57 | 0.679654 | 3.36 | false | false | false | false |
artemnovichkov/TransitionRouter
|
Sources/SlideTransitionAnimator.swift
|
1
|
2726
|
//
// SlideTransitionAnimator.swift
// TransitionRouter
//
// Created by Artem Novichkov on 06/12/2016.
// Copyright © 2016 Artem Novichkov. All rights reserved.
//
import UIKit
enum AnimationDirection {
case top, left, bottom, right
}
public final class SlideTransitionAnimator: NSObject, TransitionAnimator {
public var presenting = true
public var options = AnimationOptions()
fileprivate let direction: AnimationDirection
init(direction: AnimationDirection) {
self.direction = direction
}
}
extension SlideTransitionAnimator: UIViewControllerAnimatedTransitioning {
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return options.duration
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
return animateTransition(for: presenting)(transitionContext)
}
// MARK: - Private
private func animateTransition(for presenting: Bool) -> AnimateTransitionHandler {
return presenting ? show : dismiss
}
private func show(using transitionContext: UIViewControllerContextTransitioning) {
let (fromViewController, toViewController) = configure(using: transitionContext)
toViewController.updateFrame(with: direction)
animate(with: transitionContext) {
fromViewController.updateFrame(with: self.direction, reverse: true)
toViewController.center()
}
}
private func dismiss(using transitionContext: UIViewControllerContextTransitioning) {
let (fromViewController, toViewController) = configure(using: transitionContext)
animate(with: transitionContext) {
fromViewController.updateFrame(with: self.direction)
toViewController.center()
}
}
}
fileprivate extension UIViewController {
func updateFrame(with direction: AnimationDirection, reverse: Bool = false) {
switch direction {
case .top: reverse ? bottom() : top()
case .left: reverse ? right() : left()
case .bottom: reverse ? top() : bottom()
case .right: reverse ? left() : right()
}
}
func center() {
view.frame.origin = .zero
}
private func top() {
view.frame.origin.y = -view.frame.size.height
}
private func left() {
view.frame.origin.x = -view.frame.size.width
}
private func bottom() {
view.frame.origin.y = view.frame.size.height
}
private func right() {
view.frame.origin.x = view.frame.size.width
}
}
|
mit
|
8c90811be6e5092989b9312aa7c8aed8
| 27.989362 | 116 | 0.657248 | 5.240385 | false | false | false | false |
hulinSun/Better
|
better/better/Classes/Photo/View/PhotoGroupCell.swift
|
1
|
1328
|
//
// PhotoGroupCell.swift
// better
//
// Created by Hony on 2016/11/22.
// Copyright © 2016年 Hony. All rights reserved.
//
import UIKit
import Photos
class PhotoGroupCell: UITableViewCell {
var item: PhotoGroupItem?{
didSet{
let count = (item?.count)!
nameLabel.text = (item?.name)! + " ("+"\(count)"+")张"
if let firstImage = item?.firstImg{
let opt = PHImageRequestOptions()
opt.deliveryMode = .highQualityFormat
PHCachingImageManager.default().requestImage(for: firstImage, targetSize: CGSize(width: 54, height: 54), contentMode: .aspectFit, options: opt, resultHandler: { (img , info) in
print("groupimg = \(img)")
self.iconView.image = img
})
}else{
self.iconView.backgroundColor = UIColor.random()
}
}
}
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var iconView: UIImageView!
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
}
}
|
mit
|
a834bace6782b39bb6fc79093a4bf949
| 27.76087 | 192 | 0.573696 | 4.708185 | false | false | false | false |
louisdh/lioness
|
Sources/Lioness/AST/Nodes/StructNode.swift
|
1
|
1637
|
//
// StructNode.swift
// Lioness
//
// Created by Louis D'hauwe on 09/01/2017.
// Copyright © 2017 Silver Fox. All rights reserved.
//
import Foundation
public struct StructNode: ASTNode {
public let prototype: StructPrototypeNode
init(prototype: StructPrototypeNode) {
self.prototype = prototype
}
public func compile(with ctx: BytecodeCompiler, in parent: ASTNode?) throws -> BytecodeBody {
var bytecode = BytecodeBody()
let structId = ctx.getStructId(for: self)
let headerLabel = ctx.nextIndexLabel()
let headerComment = "\(prototype.name)(\(prototype.members.joined(separator: ", ")))"
let header = BytecodeInstruction(label: headerLabel, type: .virtualHeader, arguments: [.index(structId)], comment: headerComment)
bytecode.append(header)
let initInstr = BytecodeInstruction(label: ctx.nextIndexLabel(), type: .structInit, comment: "init \(prototype.name)")
bytecode.append(initInstr)
for member in prototype.members.reversed() {
guard let id = ctx.getStructMemberId(for: member) else {
throw CompileError.unexpectedCommand
}
let instr = BytecodeInstruction(label: ctx.nextIndexLabel(), type: .structSet, arguments: [.index(id)], comment: "set \(member)")
bytecode.append(instr)
}
bytecode.append(BytecodeInstruction(label: ctx.nextIndexLabel(), type: .virtualEnd))
return bytecode
}
public var childNodes: [ASTNode] {
return [prototype]
}
public var description: String {
return "StructNode(prototype: \(prototype))"
}
public var nodeDescription: String? {
return "Struct"
}
public var descriptionChildNodes: [ASTChildNode] {
return []
}
}
|
mit
|
6bfaf6b26f4afdff76dc77c4057d049a
| 23.41791 | 132 | 0.722494 | 3.533477 | false | false | false | false |
dbahat/conventions-ios
|
Conventions/Conventions/feedback/TextFeedbackQuestionCell.swift
|
1
|
2548
|
//
// TextFeedbackQuestionCell.swift
// Conventions
//
// Created by David Bahat on 7/2/16.
// Copyright © 2016 Amai. All rights reserved.
//
import Foundation
class TextFeedbackQuestionCell: FeedbackQuestionCell, UITextViewDelegate {
@IBOutlet fileprivate weak var questionLabel: UILabel!
@IBOutlet fileprivate weak var answerTextView: UITextView!
fileprivate let answerTextViewDefaultHeight = CGFloat(33)
override var enabled: Bool {
didSet {
answerTextView.isEditable = enabled
answerTextView.isSelectable = enabled
}
}
override var feedbackTextColor: UIColor {
didSet {
questionLabel.textColor = feedbackTextColor
answerTextView.textColor = feedbackTextColor
}
}
override func questionDidSet(_ question: FeedbackQuestion) {
questionLabel.text = question.question
answerTextView.delegate = self
// reset the height state during model binding
cellHeightDelta = answerTextView.heightToFitContent() - answerTextViewDefaultHeight
}
override func setAnswer(_ answer: FeedbackAnswer) {
answerTextView.text = answer.getAnswer()
// resize the text view so it fits the text inside the answer
var newFrame = answerTextView.frame
newFrame.size = CGSize(width: answerTextView.frame.width, height: answerTextView.heightToFitContent())
answerTextView.frame = newFrame;
// re-calcuate the cell height delta, since it probebly changed due to the answer text
cellHeightDelta = answerTextView.heightToFitContent() - answerTextViewDefaultHeight
}
func textViewDidChange(_ textView: UITextView) {
let newCellHeightDelta = answerTextView.heightToFitContent() - answerTextViewDefaultHeight
// If the cell height delta changed, notify the calling table so it can re-size the cell (as cell
// sizes in UITableView cannot "wrap content")
if (cellHeightDelta != newCellHeightDelta) {
cellHeightDelta = answerTextView.heightToFitContent() - answerTextViewDefaultHeight
delegate?.questionViewHeightChanged(caller: self, newHeight: cellHeightDelta)
}
if (textView.text == "") {
delegate?.questionCleared(question!)
return
}
delegate?.questionWasAnswered(FeedbackAnswer.Text(questionText: question!.question, answer: textView.text))
}
}
|
apache-2.0
|
985f99ace818da92fdbdf2ef0cfb8c68
| 35.385714 | 115 | 0.671771 | 5.240741 | false | false | false | false |
finngaida/spotify2applemusic
|
Pods/Sweeft/Sources/Sweeft/Extensions/String.swift
|
1
|
3298
|
//
// Swift.swift
//
// Created by Mathias Quintero on 11/20/16.
// Copyright © 2016 Mathias Quintero. All rights reserved.
//
import Foundation
public extension String {
/// Will say if the String is a palindrome
var isPalindrome: Bool {
return <>self == self
}
/// Will return the string reversed
var reversed: String {
return String(<>characters)
}
/// Returns the decoded representation of the string
var base64Decoded: String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return data.string
}
/// Returns the base 64 encoded representation of the string
var base64Encoded: String? {
return data?.base64EncodedString()
}
/// Encodes the string by escaping unallowed characters
var urlEncoded: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) ?? self
}
/// Turns any string into a url
var url: URL? {
return URL(string: urlEncoded)
}
/**
Turns any string into a possible API
- Parameter baseHeaders: Headers that should be included into every single request
- Parameter baseQueries: Queries that should be included into every single request
- Returns: API using the string as base url
*/
func api<V: APIEndpoint>(baseHeaders: [String : String] = .empty, baseQueries: [String: String]) -> GenericAPI<V> {
return V.api(with: self, baseHeaders: baseHeaders, baseQueries: baseQueries)
}
/**
Will try to decipher the Date coded into a string
- Parameter format: format in which the date is coded (Optional: default is "dd.MM.yyyy hh:mm:ss a")
- Returns: Date object for the time
*/
func date(using format: String = "dd.MM.yyyy hh:mm:ss a") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: self)
}
}
public extension String {
/**
Will say if a String matches a RegEx
- Parameter pattern: RegEx you want to match
- Parameter options: Extra options (Optional: Default is .empty)
- Returns: Whether or not the string matches
*/
func matches(pattern: String, options: NSRegularExpression.Options = []) throws -> Bool {
let regex = try NSRegularExpression(pattern: pattern, options: options)
return regex.numberOfMatches(in: self, options: [], range: NSRange(location: 0, length: 0.distance(to: utf16.count))) != 0
}
}
extension String: Defaultable {
/// Default Value
public static let defaultValue: String = .empty
}
extension String: DataRepresentable {
public init?(data: Data) {
self.init(data: data, encoding: .utf8)
}
/// Data resulting by encoding using utf8
public var data: Data? {
return data(using: .utf8)
}
}
extension String: Serializable {
/// JSON Value
public var json: JSON {
return .string(self)
}
}
public extension ExpressibleByStringLiteral where StringLiteralType == String {
static var empty: Self {
return Self(stringLiteral: "")
}
}
|
mit
|
faf890931cb70a4695a17a5940282841
| 25.58871 | 130 | 0.62936 | 4.553867 | false | false | false | false |
OSzhou/MyTestDemo
|
17_SwiftTestCode/TestCode/CustomAlbum/Source/Scene/Browser/HEPhoneBrowserBottomCell.swift
|
1
|
2774
|
//
// HEPhoneBrowserBottomCell.swift
// SwiftPhotoSelector
//
// Created by heyode on 2018/9/25.
// Copyright (c) 2018 heyode <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Photos
class HEPhoneBrowserBottomCell: UICollectionViewCell {
var imageView : UIImageView!
private var checkBtnnClickClosure : HEPhotoPickerCellClosure?
var model : HEPhotoAsset!{
didSet{
let scale = UIScreen.main.scale / 2
let thumbnailSize = CGSize(width: self.bounds.size.width * scale, height: self.bounds.size.height * scale)
HETool.heRequestImage(for: model.asset,
targetSize: thumbnailSize,
contentMode: .aspectFill)
{ (image, nil) in
self.imageView.image = image
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.backgroundColor = UIColor.black
self.contentView.addSubview(imageView)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = self.bounds
}
override var isSelected: Bool{
didSet{
if isSelected {
self.layer.borderWidth = 2
self.layer.borderColor = UIColor.themeYellow.cgColor
}else{
self.layer.borderWidth = 0
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
77c0b3da57215094d1dfde310cf1dfae
| 37.527778 | 118 | 0.64672 | 4.717687 | false | false | false | false |
instacrate/tapcrate-api
|
Sources/api/Utility/TypesafeOptionsParameter.swift
|
1
|
2744
|
//
// TypesafeOptionsParameter.swift
// polymr-api
//
// Created by Hakon Hanesand on 3/3/17.
//
//
import Vapor
import HTTP
import Node
import Fluent
import Vapor
import HTTP
protocol QueryInitializable: NodeInitializable {
static var key: String { get }
}
protocol TypesafeOptionsParameter: StringInitializable, NodeConvertible {
static var key: String { get }
static var values: [String] { get }
static var defaultValue: Self? { get }
}
extension TypesafeOptionsParameter {
static var humanReadableValuesString: String {
return "Valid values are : [\(Self.values.joined(separator: ", "))]"
}
func modify<E>(_ query: Query<E>) throws -> Query<E> {
return query
}
}
extension RawRepresentable where Self: TypesafeOptionsParameter, RawValue == String {
init?(from string: String) throws {
self.init(rawValue: string)
}
init?(from _string: String?) throws {
guard let string = _string else {
return nil
}
self.init(rawValue: string)
}
init(node: Node) throws {
if node.isNull {
guard let defaultValue = Self.defaultValue else {
throw Abort.custom(status: .badRequest, message: "Missing query parameter value \(Self.key). Acceptable values are : [\(Self.values.joined(separator: ", "))]")
}
self = defaultValue
return
}
guard let string = node.string else {
throw NodeError.unableToConvert(input: node, expectation: "\(String.self)", path: ["self"])
}
guard let value = Self.init(rawValue: string) else {
throw Abort.custom(status: .badRequest, message: "Invalid value for enumerated type. \(Self.humanReadableValuesString)")
}
self = value
}
func makeNode(in context: Context?) throws -> Node {
return Node.string(self.rawValue)
}
}
extension Request {
func extract<T: QueryInitializable>() throws -> T? {
return try T.init(node: self.query?[T.key])
}
func extract<T: TypesafeOptionsParameter>() throws -> T where T: RawRepresentable, T.RawValue == String {
return try T.init(node: self.query?[T.key])
}
func extract<T: TypesafeOptionsParameter>() throws -> [T] where T: RawRepresentable, T.RawValue == String {
guard let optionsArray = self.query?[T.key]?.array else {
throw Abort.custom(status: .badRequest, message: "Missing query option at key \(T.key). Acceptable values are \(T.values)")
}
return try optionsArray.map { try T.init(node: $0) }
}
}
|
mit
|
0fa657fb6470c0a41471c3ae0d2e270f
| 27 | 175 | 0.603863 | 4.355556 | false | false | false | false |
ankurp/Dollar.swift
|
Tests/DollarTests/DollarTests.swift
|
1
|
31316
|
//
// DollarTests.swift
// DollarTests
//
// Created by Ankur Patel on 6/3/14.
// Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved.
//
import XCTest
@testable import Dollar
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class DollarTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testPermutation() {
let result = Dollar.permutation(["a", "b", "c"])
XCTAssertEqual(result, ["abc", "acb", "bac", "bca", "cab", "cba"])
}
func testFirst() {
if let result = Dollar.first([1, 2, 3, 4]) {
XCTAssertEqual(result, 1, "Return first element")
}
XCTAssertNil(Dollar.first([Int]()), "Returns nil when array is empty")
}
func testSecond() {
if let result = Dollar.second([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) {
XCTAssertEqual(result, 2, "Return second element")
}
XCTAssertNil(Dollar.second([Int]()), "Returns nil when array is empty")
}
func testThird() {
if let result = Dollar.third([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) {
XCTAssertEqual(result, 3, "Return third element")
}
XCTAssertNil(Dollar.third([Int]()), "Returns nil when array is empty")
}
func testNoop() {
Dollar.noop()
}
func testCompact() {
XCTAssert(Dollar.compact([3, nil, 4, 5]) == [3, 4, 5], "Return truth array")
XCTAssertEqual(Dollar.compact([nil, nil]) as [NSObject], [], "Return truth array")
}
func testEach() {
var arr: [Int] = []
let result = Dollar.each([1, 3, 4, 5], callback: { arr.append($0 * 2) })
XCTAssert(result == [1, 3, 4, 5], "Return the array itself")
XCTAssert(arr == [2, 6, 8, 10], "Return array with doubled numbers")
}
func testEachWhen() {
var arr: [Int] = []
let result = Dollar.each([1, 3, 4, 5], when: { return $0 < 4 }, callback: { arr.append($0 * 2) })
XCTAssert(result == [1, 3, 4, 5], "Return the array itself")
XCTAssert(arr == [2, 6], "Return array with doubled numbers")
}
func testEqual() {
XCTAssert(Dollar.equal(Optional("hello"), Optional("hello")), "optionalString and otherOptionalString should be equal.")
XCTAssertFalse(Dollar.equal(Optional("hello"), Optional("goodbye")), "optionalString and thirdOptionalString should not be equal.")
XCTAssert(Dollar.equal(nil as String?, nil as String?), "Nil optionals should be equal.")
}
func testFlatten() {
XCTAssertEqual(Dollar.flatten([[3], 4, 5]) as! [Int], [3, 4, 5], "Return flat array")
XCTAssertEqual(Dollar.flatten([[[3], 4], 5]) as! [Int], [3, 4, 5], "Return flat array")
}
func testShuffle() {
XCTAssertEqual(Dollar.shuffle([1]), [1], "Return shuffled array")
XCTAssertEqual(Dollar.shuffle([1, 2, 3]).count, 3, "Return shuffled array")
XCTAssertEqual(Dollar.shuffle([Int]()), [], "Return empty array")
}
func testIndexOf() {
XCTAssertEqual(Dollar.indexOf(["A", "B", "C"], value: "B")!, 1, "Return index of value")
XCTAssertEqual(Dollar.indexOf([3, 4, 5], value: 5)!, 2, "Return index of value")
XCTAssertEqual(Dollar.indexOf([3, 4, 5], value: 3)!, 0, "Return index of value")
XCTAssertNil(Dollar.indexOf([3, 4, 5], value: 2), "Return index of value")
}
func testInitial() {
XCTAssertEqual(Dollar.initial([3, 4, 5]), [3, 4], "Return all values except for last")
XCTAssertEqual(Dollar.initial([3, 4, 5], numElements: 2), [3], "Return first element")
XCTAssertEqual(Dollar.initial([3, 4, 5], numElements: 4), [], "Returns no elements")
XCTAssertEqual(Dollar.initial([3, 4, 5], numElements: -1), [], "Return no elements")
}
func testRest() {
XCTAssertEqual(Dollar.rest([3, 4, 5]), [4, 5], "Returns all value except for first")
XCTAssertEqual(Dollar.rest([3, 4, 5], numElements: 2), [5], "Returns all value except for first two")
XCTAssertEqual(Dollar.rest([3, 4, 5], numElements: 4), [], "Returns no elements")
XCTAssertEqual(Dollar.rest([3, 4, 5], numElements: -1), [], "Returns no elements")
}
func testLast() {
if let result = Dollar.last([3, 4, 5]) {
XCTAssertEqual(result, 5, "Returns last element in array")
}
XCTAssertNil(Dollar.last([NSObject]()), "Returns nil when array is empty")
}
func testFindIndex() {
let arr = [["age": 36], ["age": 40], ["age": 1]]
XCTAssertEqual(Dollar.findIndex(arr) { $0["age"] < 20 }!, 2, "Returns index of element in array")
}
func testFindLastIndex() {
let arr = [["age": 36], ["age": 40], ["age": 1]]
XCTAssertEqual(Dollar.findLastIndex(arr) { $0["age"] > 30 }!, 1, "Returns last index of element in array")
}
func testLastIndexOf() {
XCTAssertEqual(Dollar.lastIndexOf([1, 2, 3, 1, 2, 3], value: 2)!, 4, "Returns last index of element in array")
}
func testContains() {
XCTAssertTrue(Dollar.contains([1, 2, 3, 1, 2, 3], value: 2), "Checks if array contains element")
XCTAssertFalse(Dollar.contains([1, 2, 3, 1, 2, 3], value: 10), "Checks if array contains element")
}
func testRange() {
XCTAssertEqual(Dollar.range(4), [0, 1, 2, 3], "Generates range")
XCTAssertEqual(Dollar.range(from: 1, to: 5), [1, 2, 3, 4], "Generates range")
XCTAssertEqual(Dollar.range(from: 0, to: 20, incrementBy: 5), [0, 5, 10, 15], "Generates range")
XCTAssertEqual(Dollar.range(4.0), [0.0, 1.0, 2.0, 3.0], "Generates range of doubles")
XCTAssertEqual(Dollar.range(from: -2.0, to: 2.0), [-2.0, -1.0, 0.0, 1.0], "Generates range of doubles")
XCTAssertEqual(Dollar.range(from: -10.0, to: 10.0, incrementBy: 5), [-10.0, -5.0, 0.0, 5.0], "Generates range of doubles")
XCTAssertEqual(Dollar.range(from: 1, through: 5), [1, 2, 3, 4, 5], "Increments by 1 and includes 5")
XCTAssertEqual(Dollar.range(from: 0, through: 20, incrementBy: 5), [0, 5, 10, 15, 20], "Includes 20")
XCTAssertEqual(Dollar.range(from: -10.0, through: 10.0, incrementBy: 5), [-10.0, -5.0, 0.0, 5.0, 10.0], "Includes 10.0")
}
func testSequence() {
XCTAssertEqual(Dollar.sequence("abc".characters), ["a", "b", "c"], "Generates array of characters")
}
func testRemove() {
XCTAssertEqual(Dollar.remove([1, 2, 3, 4, 5, 6], callback: { $0 == 2 || $0 == 3 }), [1, 4, 5, 6], "Remove based on callback")
}
func testRemoveElement() {
XCTAssertEqual(Dollar.remove(["ant", "bat", "cat", "dog", "egg"], value: "cat"), ["ant", "bat", "dog", "egg"], "Array after removing element")
XCTAssertEqual(Dollar.remove(["ant", "bat", "cat", "dog", "egg"], value: "fish"), ["ant", "bat", "cat", "dog", "egg"], "Array after removing element that does not exist")
}
func testSortedIndex() {
XCTAssertEqual(Dollar.sortedIndex([3, 4, 6, 10], value: 5), 2, "Index to insert element at in a sorted array")
XCTAssertEqual(Dollar.sortedIndex([10, 20, 30, 50], value: 40), 3, "Index to insert element at in a sorted array")
}
func testWithout() {
XCTAssertEqual(Dollar.without([3, 4, 5, 3, 5], values: 3, 5), [4], "Removes elements passed after the array")
XCTAssertEqual(Dollar.without([3, 4, 5, 3, 5], values: 4), [3, 5, 3, 5], "Removes elements passed after the array")
XCTAssertEqual(Dollar.without([3, 4, 5, 3, 5], values: 3, 4, 5), [], "Removes elements passed after the array")
}
func testPull() {
XCTAssertEqual(Dollar.pull([3, 4, 5, 3, 5], values: 3, 5), [4], "Removes elements passed after the array")
XCTAssertEqual(Dollar.pull([3, 4, 5, 3, 5], values: 4), [3, 5, 3, 5], "Removes elements passed after the array")
XCTAssertEqual(Dollar.pull([3, 4, 5, 3, 5], values: 3, 4, 5), [], "Removes elements passed after the array")
}
func testZip() {
let zipped = Dollar.zip(["fred", "barney"], [30, 40], [true, false])
XCTAssertEqual(zipped[0][0] as! String, "fred", "Zip up arrays")
XCTAssertEqual(zipped[0][1] as! Int, 30, "Zip up arrays")
XCTAssertEqual(zipped[0][2] as! Bool, true, "Zip up arrays")
XCTAssertEqual(zipped[1][0] as! String, "barney", "Zip up arrays")
XCTAssertEqual(zipped[1][1] as! Int, 40, "Zip up arrays")
XCTAssertEqual(zipped[1][2] as! Bool, false, "Zip up arrays")
}
func testZipObject() {
XCTAssertTrue(Dollar.zipObject(["fred", "barney"], values: [30, 40]) as [String: Int] == ["fred": 30, "barney": 40], "Zip up array to object")
}
func testIntersection() {
XCTAssertEqual(Dollar.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]).sorted(by: {$0<$1}), [1, 2], "Intersection of arrays")
}
func testDifference() {
XCTAssertEqual(Dollar.difference([1, 2, 3, 4, 5], [5, 2, 10]), [1, 3, 4], "Difference of arrays")
XCTAssertEqual(Dollar.difference([1, 1, 1, 2, 2], [], [3]), [1, 1, 1, 2, 2], "Difference of arrays")
XCTAssertEqual(Dollar.difference([4, 1, 1, 1, 2, 2], [1, 1], [3]), [4, 2, 2], "Difference of arrays")
XCTAssertEqual(Dollar.difference([1, 1, 1, 2, 2], [1, 1], [1, 2, 2]), [], "Difference of arrays")
XCTAssertEqual(Dollar.difference([1, 1, 1, 2, 2], [1, 1, 1], [1, 2, 2]), [], "Difference of arrays")
XCTAssertEqual(Dollar.difference([1, 1, 1, 2, 2], []), [1, 1, 1, 2, 2], "Difference of arrays")
}
func testUniq() {
XCTAssertEqual(Dollar.uniq([1, 2, 1, 3, 1]), [1, 2, 3], "Uniq of arrays")
XCTAssertEqual(Dollar.uniq([1, 2.5, 3, 1.5, 2, 3.5], by: {floor($0)}), [1, 2.5, 3], "Uniq numbers by condition")
}
func testUnion() {
XCTAssertEqual(Dollar.union([1, 2, 3], [5, 2, 1, 4], [2, 1]), [1, 2, 3, 5, 4], "Union of arrays")
}
func testXOR() {
XCTAssertEqual(Dollar.xor([1, 2, 3], [5, 2, 1, 4]).sorted {$0<$1}, [3, 4, 5], "Xor of arrays")
}
func testTranspose() {
var matrix = Dollar.transpose([[1, 2, 3], [4, 5, 6]])
XCTAssertEqual(matrix[0], [1, 4], "Tranpose of matrix")
XCTAssertEqual(matrix[1], [2, 5], "Tranpose of matrix")
XCTAssertEqual(matrix[2], [3, 6], "Tranpose of matrix")
}
func testAt() {
XCTAssertEqual(Dollar.at(["ant", "bat", "cat", "dog", "egg"], indexes: 0, 2, 4), ["ant", "cat", "egg"], "At of arrays")
}
func testEvery() {
XCTAssertTrue(Dollar.every([1, 2, 3, 4]) { $0 < 20 }, "All elements in collection are true")
XCTAssertFalse(Dollar.every([1, 2, 3, 4]) { $0 == 1 }, "All elements in collection are true")
}
func testFind() {
XCTAssertEqual(Dollar.find([1, 2, 3, 4], callback: { $0 == 2 })!, 2, "Return element when object is found")
XCTAssertNil(Dollar.find([1, 2, 3, 4], callback: { $0 == 10 }), "Return nil when object not found")
}
func testMax() {
XCTAssert(Dollar.max([1, 2, 3, 4, 2, 1]) == 4, "Returns maximum element")
XCTAssertNil(Dollar.max([Int]()), "Returns nil when array is empty")
}
func testMin() {
XCTAssert(Dollar.min([2, 1, 2, 3, 4]) == 1, "Returns minumum element")
XCTAssertNil(Dollar.min([Int]()), "Returns nil when array is empty")
}
func testSample() {
let arr = [2, 1, 2, 3, 4]
XCTAssertTrue(Dollar.contains(arr, value: Dollar.sample(arr)), "Returns sample which is an element from the array")
}
func testPluck() {
let arr = [["age": 20], ["age": 30], ["age": 40]]
XCTAssertEqual(Dollar.pluck(arr, value: "age"), [20, 30, 40], "Returns values from the object where they key is the value")
}
func testFrequencies() {
XCTAssertTrue(Dollar.frequencies(["a", "a", "b", "c", "a", "b"]) == ["a": 3, "b": 2, "c": 1], "Returns correct frequency dictionary")
XCTAssertTrue(Dollar.frequencies([1, 2, 3, 4, 5]) { $0 % 2 == 0 } == [false: 3, true: 2], "Returns correct frequency dictionary from cond")
}
func testKeys() {
let dict = ["Dog": 1, "Cat": 2]
XCTAssertEqual(Dollar.keys(dict).sorted(by: {$0<$1}), ["Cat", "Dog"], "Returns correct array with keys")
}
func testValues() {
let dict = ["Dog": 1, "Cat": 2]
XCTAssertEqual(Dollar.values(dict).sorted(by: {$0<$1}), [1, 2], "Returns correct array with values")
}
func testMerge() {
let dict = ["Dog": 1, "Cat": 2]
let dict2 = ["Cow": 3]
let dict3 = ["Sheep": 4]
XCTAssertTrue(Dollar.merge(dict, dict2, dict3) == ["Dog": 1, "Cat": 2, "Cow": 3, "Sheep": 4], "Returns correct merged dictionary")
let arr = [1, 5]
let arr2 = [2, 4]
let arr3 = [5, 6]
XCTAssertEqual(Dollar.merge(arr, arr2, arr3), [1, 5, 2, 4, 5, 6], "Returns correct merged array")
}
func testPick() {
let dict = ["Dog": 1, "Cat": 2, "Cow": 3]
XCTAssertTrue(Dollar.pick(dict, keys: "Dog", "Cow") == ["Dog": 1, "Cow": 3], "Returns correct picked dictionary")
}
func testOmit() {
let dict = ["Dog": 1, "Cat": 2, "Cow": 3]
XCTAssertTrue(Dollar.omit(dict, keys: "Dog") == ["Cat": 2, "Cow": 3], "Returns correct omited dictionary")
}
func testTap() {
let beatle = CarExample(name: "Fusca")
Dollar.tap(beatle, function: {$0.name = "Beatle"}).color = "Blue"
XCTAssertEqual(beatle.name!, "Beatle", "Set the car name")
XCTAssertEqual(beatle.color!, "Blue", "Set the car color")
}
func testChaining() {
var chain = Dollar.chain([1, 2, 3])
XCTAssertEqual(chain.first()!, 1, "Returns first element which ends the chain")
XCTAssertEqual(chain.second()!, 2, "Returns second element which ends the chain")
XCTAssertEqual(chain.third()!, 3, "Returns third element which ends the chain")
chain = Dollar.chain([10, 20, 30, 40, 50])
var elements: [Int] = []
_ = chain.each { elements.append($0 as Int) }
_ = chain.value
XCTAssertEqual(elements, [10, 20, 30, 40, 50], "Goes through each element in the array")
XCTAssertTrue(chain.all({ ($0 as Int) < 100 }), "All elements are less than 100")
chain = Dollar.chain([10, 20, 30, 40, 50])
XCTAssertFalse(chain.all({ ($0 as Int) < 40 }), "All elements are not less than 40")
chain = Dollar.chain([10, 20, 30, 40, 50])
XCTAssertTrue(chain.any({ ($0 as Int) < 40 }), "At least one element is less than 40")
chain = Dollar.chain([10, 20, 30, 40, 50])
elements = [Int]()
_ = chain.slice(0, end: 3).each { elements.append($0 as Int) }
_ = chain.value
XCTAssertEqual(elements, [10, 20, 30], "Chained seld")
let testarr = [[[1, 2]], 3, [[4], 5]] as [Any]
let chainA = Dollar.chain(testarr)
XCTAssertEqual(chainA.flatten().initial(2).value as! [Int], [1, 2, 3], "Returns flatten array from chaining")
let chainB = Dollar.chain(testarr)
XCTAssertEqual(chainB.initial().flatten().first()! as! Int, 1, "Returns flatten array from chaining")
_ = Dollar.chain(testarr)
// XCTAssertEqual(chainC.flatten().map({ (elem) in elem as Int * 10 }).value, [10, 20, 30, 40, 50], "Returns mapped values")
// XCTAssertEqual(chainC.flatten().map({ (elem) in elem as Int * 10 }).first()!, 100, "Returns first element from mapped value")
}
func testPartial() {
let partialFunc = Dollar.partial({(T: String...) in T[0] + " " + T[1] + " from " + T[2] }, "Hello")
XCTAssertEqual(partialFunc("World", "Swift"), "Hello World from Swift", "Returns curry function that is evaluated")
}
func testBind() {
let helloWorldFunc = Dollar.bind({(T: String...) in T[0] + " " + T[1] + " from " + T[2] }, "Hello", "World", "Swift")
XCTAssertEqual(helloWorldFunc(), "Hello World from Swift", "Returns curry function that is evaluated")
}
func testBind1() {
// let helloWorldFunc = $.bind({ $0 + " World" }, "Hello")
// XCTAssertEqual(helloWorldFunc(), "Hello World", "Returns bind function that is evaluated")
}
func testBind2() {
// let helloWorldFunc = $.bind({ $0 + $1 + " World" }, "Hello ", "Great")
// XCTAssertEqual(helloWorldFunc(), "Hello Great World", "Returns bind function that is evaluated")
}
func testTimes() {
let fun = Dollar.bind({ (names: String...) -> String in
let people = Dollar.join(names, separator: " from ")
return "Hello \(people)"
}, "Ankur", "Swift")
XCTAssertEqual(Dollar.times(3, function: fun) as [String], ["Hello Ankur from Swift", "Hello Ankur from Swift", "Hello Ankur from Swift"], "Call a function 3 times")
}
func testAfter() {
let saves = ["profile", "settings"]
let asyncSave = { (function: () -> ()?) in
function()
}
var isDone = false
let completeCallback = Dollar.after(saves.count) {
isDone = true
}
for _ in saves {
asyncSave(completeCallback)
}
XCTAssertTrue(isDone, "Should be done")
}
func testPartition() {
let array = [1, 2, 3, 4, 5]
var partition = Dollar.partition(array, n: 2)
XCTAssertEqual(partition[0], [1, 2], "Partition uses n for step if not supplied.")
XCTAssertEqual(partition[1], [3, 4], "Partition uses n for step if not supplied.")
partition = Dollar.partition(array, n: 2, step: 1)
XCTAssertEqual(partition[0], [1, 2], "Partition allows specifying a custom step.")
XCTAssertEqual(partition[1], [2, 3], "Partition allows specifying a custom step.")
XCTAssertEqual(partition[2], [3, 4], "Partition allows specifying a custom step.")
XCTAssertEqual(partition[3], [4, 5], "Partition allows specifying a custom step.")
partition = Dollar.partition(array, n: 2, step: 1, pad: nil)
XCTAssertEqual(partition[0], [1, 2], "Partition with nil pad allows the last partition to be less than n length")
XCTAssertEqual(partition[1], [2, 3], "Partition with nil pad allows the last partition to be less than n length")
XCTAssertEqual(partition[2], [3, 4], "Partition with nil pad allows the last partition to be less than n length")
XCTAssertEqual(partition[3], [4, 5], "Partition with nil pad allows the last partition to be less than n length")
XCTAssertEqual(partition[4], [5], "Partition with nil pad allows the last partition to be less than n length")
partition = Dollar.partition(array, n: 4, step: 1, pad: nil)
XCTAssertEqual(partition[0], [1, 2, 3, 4], "Partition with nil pad stops at the first partition less than n length.")
XCTAssertEqual(partition[1], [2, 3, 4, 5], "Partition with nil pad stops at the first partition less than n length.")
XCTAssertEqual(partition[2], [3, 4, 5], "Partition with nil pad stops at the first partition less than n length.")
partition = Dollar.partition(array, n: 2, step: 1, pad: [6, 7, 8])
XCTAssertEqual(partition[0], [1, 2], "Partition pads the last partition to the right length.")
XCTAssertEqual(partition[1], [2, 3], "Partition pads the last partition to the right length.")
XCTAssertEqual(partition[2], [3, 4], "Partition pads the last partition to the right length.")
XCTAssertEqual(partition[3], [4, 5], "Partition pads the last partition to the right length.")
XCTAssertEqual(partition[4], [5, 6], "Partition pads the last partition to the right length.")
partition = Dollar.partition(array, n: 4, step: 3, pad: [6])
XCTAssertEqual(partition[0], [1, 2, 3, 4], "Partition doesn't add more elements than pad has.")
XCTAssertEqual(partition[1], [4, 5, 6], "Partition doesn't add more elements than pad has.")
partition = Dollar.partition(array, n: 4, step: nil, pad: [6, 7])
XCTAssertEqual(partition[0], [1, 2, 3, 4], "Partition with nil step can add pad elements normally, but can't add more elements than pad has.")
XCTAssertEqual(partition[1], [5, 6, 7], "Partition with nil step can add pad elements normally, but can't add more elements than pad has.")
partition = Dollar.partition(array, n: 4, step: nil, pad: [6, 7])
XCTAssertEqual(partition[0], [1, 2, 3, 4], "Partition with nil step can add pad elements normally, but can't add more elements than pad has.")
XCTAssertEqual(partition[1], [5, 6, 7], "Partition with nil step can add pad elements normally, but can't add more elements than pad has.")
partition = Dollar.partition(array, n: 4, step: nil, pad: [6, 7, 8, 9])
XCTAssertEqual(partition[0], [1, 2, 3, 4], "Partition with nil step can add pad elements normally.")
XCTAssertEqual(partition[1], [5, 6, 7, 8], "Partition with nil step can add pad elements normally.")
partition = Dollar.partition(array, n: 4, step: nil, pad: nil)
XCTAssertEqual(partition[0], [1, 2, 3, 4], "Partition with nil step and nil pad can add pad elements normally.")
XCTAssertEqual(partition[1], [5], "Partition with nil step and nil pad can add pad elements normally.")
partition = Dollar.partition([1, 2, 3, 4, 5], n: 2, pad: [6])
XCTAssertEqual(partition[0], [1, 2], "Partition with pad and no step uses n as step.")
XCTAssertEqual(partition[1], [3, 4], "Partition with pad and no step uses n as step.")
XCTAssertEqual(partition[2], [5, 6], "Partition with pad and no step uses n as step.")
partition = Dollar.partition([1, 2, 3, 4, 5, 6], n: 2, step: 4)
XCTAssertEqual(partition[0], [1, 2], "Partition step length works.")
XCTAssertEqual(partition[1], [5, 6], "Partition step length works.")
partition = Dollar.partition(array, n: 10)
XCTAssertEqual(partition[0], [], "Partition without pad returns [[]] if n is longer than array.")
}
func testPartitionAll() {
let array = [1, 2, 3, 4, 5]
var partition = Dollar.partitionAll(array, n: 2, step: 1)
XCTAssertEqual(partition[0], [1, 2], "PartitionAll includes partitions less than n.")
XCTAssertEqual(partition[1], [2, 3], "PartitionAll includes partitions less than n.")
XCTAssertEqual(partition[2], [3, 4], "PartitionAll includes partitions less than n.")
XCTAssertEqual(partition[3], [4, 5], "PartitionAll includes partitions less than n.")
XCTAssertEqual(partition[4], [5], "PartitionAll includes partitions less than n.")
partition = Dollar.partitionAll(array, n: 2)
XCTAssertEqual(partition[0], [1, 2], "PartitionAll uses n as the step when not supplied.")
XCTAssertEqual(partition[1], [3, 4], "PartitionAll uses n as the step when not supplied.")
XCTAssertEqual(partition[2], [5], "PartitionAll uses n as the step when not supplied.")
partition = Dollar.partitionAll(array, n: 4, step: 1)
XCTAssertEqual(partition[0], [1, 2, 3, 4], "PartitionAll does not stop at the first partition less than n length.")
XCTAssertEqual(partition[1], [2, 3, 4, 5], "PartitionAll does not stop at the first partition less than n length.")
XCTAssertEqual(partition[2], [3, 4, 5], "PartitionAll does not stop at the first partition less than n length.")
XCTAssertEqual(partition[3], [4, 5], "PartitionAll does not stop at the first partition less than n length.")
XCTAssertEqual(partition[4], [5], "PartitionAll does not stop at the first partition less than n length.")
}
func testPartitionBy() {
var partition = Dollar.partitionBy([1, 2, 3, 4, 5]) { $0 > 10 }
XCTAssertEqual(partition[0], [1, 2, 3, 4, 5], "PartitionBy doesn't try to split unnecessarily.")
partition = Dollar.partitionBy([1, 2, 4, 3, 5, 6]) { $0 % 2 == 0 }
XCTAssertEqual(partition[0], [1], "PartitionBy splits appropriately on Bool.")
XCTAssertEqual(partition[1], [2, 4], "PartitionBy splits appropriately on Bool.")
XCTAssertEqual(partition[2], [3, 5], "PartitionBy splits appropriately on Bool.")
XCTAssertEqual(partition[3], [6], "PartitionBy splits appropriately on Bool.")
partition = Dollar.partitionBy([1, 7, 3, 6, 10, 12]) { $0 % 3 }
XCTAssertEqual(partition[0], [1, 7], "PartitionBy can split on functions other than Bool.")
XCTAssertEqual(partition[1], [3, 6], "PartitionBy can split on functions other than Bool.")
XCTAssertEqual(partition[2], [10], "PartitionBy can split on functions other than Bool.")
XCTAssertEqual(partition[3], [12], "PartitionBy can split on functions other than Bool.")
}
func testMap() {
XCTAssertEqual(Dollar.map([1, 2, 3, 4, 5]) { $0 * 2 }, [2, 4, 6, 8, 10], "Map function should double values in the array")
}
func testFlatMap() {
XCTAssertEqual(Dollar.flatMap([1, 2, 3]) { [$0, $0] }, [1, 1, 2, 2, 3, 3], "FlatMap should double every item in the array and concatenate them.")
let expected: String? = "swift"
let actual = Dollar.flatMap(URL(string: "https://apple.com/swift/")) { $0.lastPathComponent }
XCTAssert(Dollar.equal(actual, expected), "FlatMap on optionals should run the function and produce a single-level optional containing the last path component of the url.")
}
func testReduce() {
XCTAssertEqual(Dollar.reduce([1, 2, 3, 4, 5], initial: 0) { $0 + $1 } as Int, 15, "Reduce function should sum elements in the array")
}
func testSlice() {
XCTAssertEqual(Dollar.slice([1, 2, 3, 4, 5], start: 0, end: 2), [1, 2], "Slice subarray 0..2")
XCTAssertEqual(Dollar.slice([1, 2, 3, 4, 5], start: 0), [1, 2, 3, 4, 5], "Slice at 0 is whole array")
XCTAssertEqual(Dollar.slice([1, 2, 3, 4, 5], start: 3), [4, 5], "Slice with start goes till end")
XCTAssertEqual(Dollar.slice([1, 2, 3, 4, 5], start: 8), [], "Slice out of bounds is empty")
XCTAssertEqual(Dollar.slice([1, 2, 3, 4, 5], start: 8, end: 10), [], "Slice out of bounds is empty")
XCTAssertEqual(Dollar.slice([1, 2, 3, 4, 5], start: 8, end: 2), [], "Slice with end < start is empty")
XCTAssertEqual(Dollar.slice([1, 2, 3, 4, 5], start: 3, end: 3), [], "Slice at x and x is empty")
XCTAssertEqual(Dollar.slice([1, 2, 3, 4, 5], start: 2, end: 5), [3, 4, 5], "Slice at x and x is subarray")
}
func testFib() {
var times = 0
let fibMemo = Dollar.memoize { (fib: ((Int) -> Int), val: Int) -> Int in
times += 1
return val == 1 || val == 0 ? 1 : fib(val - 1) + fib(val - 2)
}
_ = fibMemo(5)
XCTAssertEqual(times, 6, "Function called 6 times")
times = 0
_ = fibMemo(5)
XCTAssertEqual(times, 0, "Function called 0 times due to memoize")
times = 0
_ = fibMemo(6)
XCTAssertEqual(times, 1, "Function called 1 times due to memoize")
}
func testId() {
XCTAssertEqual(Dollar.id(1), 1, "Id should return the argument it gets passed")
}
func testComposeVariadic() {
let double = { (params: Int...) -> [Int] in
return Dollar.map(params) { $0 * 2 }
}
let subtractTen = { (params: Int...) -> [Int] in
return Dollar.map(params) { $0 - 10 }
}
let doubleSubtractTen = Dollar.compose(double, subtractTen)
XCTAssertEqual(doubleSubtractTen(5, 6, 7), [0, 2, 4], "Should double value and then subtract 10")
}
func testComposeArray() {
let double = { (params: [Int]) -> [Int] in
return Dollar.map(params) { $0 * 2 }
}
let subtractTen = { (params: [Int]) -> [Int] in
return Dollar.map(params) { $0 - 10 }
}
let doubleSubtractTen = Dollar.compose(double, subtractTen)
XCTAssertEqual(doubleSubtractTen([5, 6, 7]), [0, 2, 4], "Should double value and then subtract 10")
}
func testChunk() {
var chunks = Dollar.chunk([1, 2, 3, 4], size: 2)
XCTAssertEqual(chunks[0], [1, 2], "Should chunk with elements in groups of 2")
XCTAssertEqual(chunks[1], [3, 4], "Should chunk with elements in groups of 2")
chunks = Dollar.chunk([1, 2, 3, 4], size: 3)
XCTAssertEqual(chunks[0], [1, 2, 3], "Should chunk with elements in groups of 2")
XCTAssertEqual(chunks[1], [4], "Should chunk with elements in groups of 2")
}
func testFill() {
var arr = Array<Int>(repeating: 1, count: 5)
XCTAssertEqual(Dollar.fill(&arr, withElem: 42), [42, 42, 42, 42, 42], "Should fill array with 42")
_ = Dollar.fill(&arr, withElem: 1, startIndex: 1, endIndex: 3)
XCTAssertEqual(Dollar.fill(&arr, withElem: 1, startIndex: 1, endIndex: 3), [42, 1, 1, 1, 42], "Should fill array with 1")
}
func testPullAt() {
XCTAssertEqual(Dollar.pullAt([10, 20, 30, 40, 50], indices: 1, 2, 3), [10, 50], "Remove elements at index")
}
func testSize() {
XCTAssertEqual(Dollar.size([10, 20, 30, 40, 50]), 5, "Returns size")
}
func testFetch() {
XCTAssertEqual(Dollar.fetch([10, 20, 30, 40, 50], 1), 20, "Returns 20")
XCTAssertEqual(Dollar.fetch([10, 20, 30, 40, 50], 100, orElse: 100), 100, "Returns 100")
}
func testGroupBy() {
let oddEven = Dollar.groupBy([1, 2, 3, 4], callback: {$0 % 2})
XCTAssertEqual(oddEven[0]!, [2, 4], "Returns dictionary grouped by remainders of two")
XCTAssertEqual(oddEven[1]!, [1, 3], "Returns dictionary grouped by remainders of two")
let wordCount = Dollar.groupBy(["strings", "with", "different", "lengths"], callback: {$0.characters.count})
XCTAssertEqual(wordCount[7]!, ["strings", "lengths"], "Returns dictionary with string lengths as keys")
XCTAssertEqual(wordCount[9]!, ["different"], "Returns dictionary with string lengths as keys")
XCTAssertEqual(wordCount[4]!, ["with"], "Returns dictionary with string lengths as keys")
}
func testRandom() {
let upperBoundary = 10
for _ in 1...1000 {
let rand = Dollar.random(upperBoundary)
// This was done so that if this failed, there wouldn't be 1000+ failures, there would just be 1.
// Making it easier to debug.
if (rand < 0 || rand >= upperBoundary) {
XCTAssert(rand > 0 && rand < 10, "random failed to generate a number within boundaries")
break
}
}
}
func testSum() {
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
XCTAssertEqual(Dollar.sum(nums), 45)
let floatingNums = [1.3, 1.5, 2.4, 3]
XCTAssertEqual(Dollar.sum(floatingNums), 8.2)
}
}
|
mit
|
33a78abca66c67aad6077cd78f7a6daf
| 47.32716 | 180 | 0.593626 | 3.673431 | false | true | false | false |
kaushaldeo/Olympics
|
Olympics/AppDelegate.swift
|
1
|
5427
|
//
// AppDelegate.swift
// Olympics
//
// Created by Kaushal Deo on 6/10/16.
// Copyright © 2016 Scorpion Inc. All rights reserved.
//
import UIKit
import CoreData
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
override class func initialize() {
super.initialize()
UINavigationBar.appearance().translucent = false;
UINavigationBar.appearance().barTintColor = UIColor(red: 57, green: 150, blue: 27)
let image = UIImage()
UINavigationBar.appearance().shadowImage = image
UINavigationBar.appearance().setBackgroundImage(image, forBarMetrics:.Default)
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
//UITabBar.appearance().barTintColor = UIColor(red: 14, green: 101, blue: 171)
UITabBar.appearance().tintColor = UIColor.whiteColor()
UIBarButtonItem.appearance().setBackButtonBackgroundImage(UIImage(named: "backButton")?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal, barMetrics: .Default)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// application.registerUserNotificationSettings(<#T##notificationSettings: UIUserNotificationSettings##UIUserNotificationSettings#>)
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
FIRApp.configure()
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.
NSManagedObjectContext.mainContext().saveContext()
}
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.
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
debugPrint(deviceToken)
if let country = Country.country(NSManagedObjectContext.mainContext()) {
if let string = country.alias {
FIRMessaging.messaging().subscribeToTopic(string)
}
}
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
debugPrint(error)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}
// [START receive_message]
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// Print message ID.
debugPrint("Message ID: \(userInfo["gcm.message_id"]!)")
// TODO: Handle data of notification
if let identifier = userInfo["competitor_id"] as? String {
//TODO: Process the identifier for team page
debugPrint(identifier)
}
dispatch_async(dispatch_get_main_queue()) {
completionHandler(.NewData)
application.applicationIconBadgeNumber = 0
}
}
// [END receive_message]
}
|
apache-2.0
|
611da174320fc424cda4d01295199886
| 45.376068 | 285 | 0.702912 | 6.015521 | false | false | false | false |
fizx/jane
|
ruby/lib/vendor/grpc-swift/Sources/SwiftGRPC/Runtime/StreamReceiving.swift
|
4
|
1807
|
/*
* Copyright 2018, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Dispatch
import Foundation
import SwiftProtobuf
public protocol StreamReceiving {
associatedtype ReceivedType: Message
var call: Call { get }
}
extension StreamReceiving {
public func receive(completion: @escaping (ResultOrRPCError<ReceivedType?>) -> Void) throws {
try call.receiveMessage { callResult in
guard let responseData = callResult.resultData else {
if callResult.success {
completion(.result(nil))
} else {
completion(.error(.callError(callResult)))
}
return
}
if let response = try? ReceivedType(serializedData: responseData) {
completion(.result(response))
} else {
completion(.error(.invalidMessageReceived))
}
}
}
public func _receive(timeout: DispatchTime) throws -> ReceivedType? {
var result: ResultOrRPCError<ReceivedType?>?
let sem = DispatchSemaphore(value: 0)
try receive {
result = $0
sem.signal()
}
if sem.wait(timeout: timeout) == .timedOut {
throw RPCError.timedOut
}
switch result! {
case .result(let response): return response
case .error(let error): throw error
}
}
}
|
mit
|
f597e0bd7f4c866822170d7d57b6a903
| 28.622951 | 95 | 0.680133 | 4.450739 | false | false | false | false |
JevinSidhu/Prologue
|
Koloda/OverlayView.swift
|
1
|
950
|
//
// OverlayView.swift
//
// Created by Jevin Sidhu on 7/17/15.
// Copyright (c) 2015 Jevin Sidhu. All rights reserved.
//
import UIKit
import Koloda
private let overlayRightImageName = "yesOverlayImage"
private let overlayLeftImageName = "noOverlayImage"
class ExampleOverlayView: OverlayView {
@IBOutlet lazy var overlayImageView: UIImageView! = {
[unowned self] in
var imageView = UIImageView(frame: self.bounds)
self.addSubview(imageView)
return imageView
}()
override var overlayState:OverlayMode {
didSet {
switch overlayState {
case .Left :
overlayImageView.image = UIImage(named: overlayLeftImageName)
case .Right :
overlayImageView.image = UIImage(named: overlayRightImageName)
default:
overlayImageView.image = nil
}
}
}
}
|
mit
|
b6e7f8f54ffc86701e026cd2ca4302fc
| 24 | 78 | 0.604211 | 4.726368 | false | false | false | false |
gyro-n/PaymentsIos
|
GyronPayments/Classes/Models/TransactionToken.swift
|
1
|
6586
|
//
// TransactionToken.swift
// GyronPayments
//
// Created by David Ye on 2016/11/01.
// Copyright © 2016 gyron. All rights reserved.
//
import Foundation
/**
A list of transaction token types.
*/
public enum TransactionTokenType: String {
case oneTime = "one_time"
case subscription = "subscription"
case recurring = "recurring"
}
open class SimpleTransactionToken: NSObject, NSCoding {
public var id: String
public var type: TransactionTokenType
public var cardholder: String
public var expMonth: Int
public var expYear: Int
public var lastFour: String
public var brand: String
/**
Initializes the SimpleTransactionToken object
*/
public init(id: String,
type: TransactionTokenType,
cardholder: String,
expMonth: Int,
expYear: Int,
lastFour: String,
brand: String) {
self.id = id
self.type = type
self.cardholder = cardholder
self.expMonth = expMonth
self.expYear = expYear
self.lastFour = lastFour
self.brand = brand
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.id, forKey: "id")
aCoder.encode(self.type.rawValue, forKey: "type")
aCoder.encode(self.cardholder, forKey: "cardholder")
aCoder.encode(self.expMonth, forKey: "expMonth")
aCoder.encode(self.expYear, forKey: "expYear")
aCoder.encode(self.lastFour, forKey: "lastFour")
aCoder.encode(self.brand, forKey: "brand")
}
public required init?(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeObject(forKey: "id") as? String ?? ""
let typeString = aDecoder.decodeObject(forKey: "type") as? String
var type = TransactionTokenType.oneTime
if let t = typeString {
type = TransactionTokenType(rawValue: t) ?? TransactionTokenType.oneTime
}
self.type = type
self.cardholder = aDecoder.decodeObject(forKey: "cardholder") as? String ?? ""
self.expMonth = aDecoder.decodeObject(forKey: "expMonth") as? Int ?? 0
self.expYear = aDecoder.decodeObject(forKey: "expYear") as? Int ?? 0
self.lastFour = aDecoder.decodeObject(forKey: "lastFour") as? String ?? ""
self.brand = aDecoder.decodeObject(forKey: "brand") as? String ?? ""
}
}
open class TransactionTokenQRScanDataItem: TransactionTokenBaseData {
}
/**
The TransactionToken class stores the information about a transaction token.
A transaction token is a resource used to collect payment data and personal information gathered about a customer. After creation, the transaction token is used to make a charge or subscription. If your company is not PCI compliant, you should create a transaction token via our provided mobile elements, widgets, or invoicing system.
A recurring/re-usable transaction token can be created if your account has been given permission to do so. Your account may be able to create an infinitely usable token, which can be used freely to make charges at any time. It may also be given a usage limit, in which a token can only be used once in the given time period.
Your account may only have one recurring token per card for every store that you have created. This is to prevent accidental double charging.
To change the amount chargable with a recurring token, you must first send a PATCH request to the token to change the amount. You can not change the currency a transaction. To do so you must first DELETE the existing recurring transaction, and have the customer provide details to make another recurring token, this time created in the currency you wish to use.
Creating an infinitely chargable token is a good way to save payment details for a customer. Creating a recurring token with a usage limit is a good way of handling a service that charges a user a different amount periodically depending on their usage.
A non-recurring token is invalid after 5 minutes.
*/
open class TransactionToken: BaseModel {
/**
The unique identifier for the store the transaction token is under.
*/
public var storeId: String
/**
The unique identifier for the transaction token.
*/
public var id: String
/**
The email of the customer that the payment data is for.
*/
public var email: String
/**
Which mode the token was created under. Can be live or test.
*/
public var mode: ProcessingMode
/**
What type of charge the token with be used for. One of one_time, subscription, or recurring
*/
public var type: TransactionTokenType
/**
If the type of token is recurring, this will be how frequently the token is usable.
One of daily, weekly, monthly, yearly, or null if the recurring token has no usage limit.
*/
public var usageLimit: String?
/**
The time that the transaction token was created on.
*/
public var createdOn: String
/**
The time that this token was last used.
*/
public var lastUsedOn: String
/**
The type of payment data this token will hold. card indicates a credit card, qr_scan indicates a Alipay QR barcode, and apple_pay denotes a Apple Pay token.
*/
public var paymentType: String
/**
The card/payment method data.
*/
public var data: TransactionTokenBaseData
/**
Initializes the TransactionToken object
*/
override init() {
storeId = ""
id = ""
email = ""
mode = ProcessingMode.test
type = TransactionTokenType.oneTime
usageLimit = nil
createdOn = ""
lastUsedOn = ""
paymentType = ""
data = TransactionTokenBaseData()
}
/**
Maps the values from a hash map object into the TransactionToken.
*/
override open func mapFromObject(map: ResponseData) {
storeId = map["store_id"] as? String ?? ""
id = map["id"] as? String ?? ""
email = map["email"] as? String ?? ""
mode = ProcessingMode(rawValue: map["mode"] as? String ?? ProcessingMode.test.rawValue)!
type = TransactionTokenType(rawValue: map["type"] as? String ?? TransactionTokenType.oneTime.rawValue)!
usageLimit = map["usage_limit"] as? String
createdOn = map["created_on"] as? String ?? ""
lastUsedOn = map["last_used_on"] as? String ?? ""
paymentType = map["payment_type"] as? String ?? ""
data = map["data"] as? TransactionTokenBaseData ?? TransactionTokenBaseData()
}
}
|
mit
|
632a0b9769db14a28d1f077dd3ca7cb2
| 38.196429 | 362 | 0.669552 | 4.59205 | false | false | false | false |
TakuSemba/DribbbleSwiftApp
|
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/ImagePicker/ImagePickerController.swift
|
3
|
2409
|
//
// ImagePickerController.swift
// RxExample
//
// Created by Segii Shulga on 1/5/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class ImagePickerController: ViewController {
@IBOutlet var imageView: UIImageView!
@IBOutlet var cameraButton: UIButton!
@IBOutlet var galleryButton: UIButton!
@IBOutlet var cropButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
cameraButton.enabled = UIImagePickerController.isSourceTypeAvailable(.Camera)
cameraButton.rx_tap
.flatMapLatest { [weak self] _ in
return UIImagePickerController.rx_createWithParent(self) { picker in
picker.sourceType = .Camera
picker.allowsEditing = false
}
.flatMap { $0.rx_didFinishPickingMediaWithInfo }
.take(1)
}
.map { info in
return info[UIImagePickerControllerOriginalImage] as? UIImage
}
.bindTo(imageView.rx_image)
.addDisposableTo(disposeBag)
galleryButton.rx_tap
.flatMapLatest { [weak self] _ in
return UIImagePickerController.rx_createWithParent(self) { picker in
picker.sourceType = .PhotoLibrary
picker.allowsEditing = false
}
.flatMap {
$0.rx_didFinishPickingMediaWithInfo
}
.take(1)
}
.map { info in
return info[UIImagePickerControllerOriginalImage] as? UIImage
}
.bindTo(imageView.rx_image)
.addDisposableTo(disposeBag)
cropButton.rx_tap
.flatMapLatest { [weak self] _ in
return UIImagePickerController.rx_createWithParent(self) { picker in
picker.sourceType = .PhotoLibrary
picker.allowsEditing = true
}
.flatMap { $0.rx_didFinishPickingMediaWithInfo }
.take(1)
}
.map { info in
return info[UIImagePickerControllerEditedImage] as? UIImage
}
.bindTo(imageView.rx_image)
.addDisposableTo(disposeBag)
}
}
|
apache-2.0
|
c6b2df291ce3af3865d6e380b61189b8
| 30.272727 | 85 | 0.562292 | 5.626168 | false | false | false | false |
XLabKC/Badger
|
Badger/Badger/SelectTeamViewController.swift
|
1
|
4459
|
import UIKit
protocol SelectTeamDelegate: class {
func selectedTeam(team: Team)
}
class SelectTeamViewController: UITableViewController {
private var teamsObserver: FirebaseListObserver<Team>?
private var userObserver: FirebaseObserver<User>?
private var teams: [Team] = []
private var user: User?
private var uid: String?
weak var delegate: SelectTeamDelegate?
deinit {
self.dispose()
}
override func viewDidLoad() {
self.navigationItem.titleView = Helpers.createTitleLabel("Select User")
let teamCellNib = UINib(nibName: "TeamCell", bundle: nil)
self.tableView.registerNib(teamCellNib, forCellReuseIdentifier: "TeamCell")
let loadingCellNib = UINib(nibName: "LoadingCell", bundle: nil)
self.tableView.registerNib(loadingCellNib, forCellReuseIdentifier: "LoadingCell")
super.viewDidLoad()
}
func setUid(uid: String) {
self.dispose()
let teamsRef = Firebase(url: Global.FirebaseTeamsUrl)
self.teamsObserver = FirebaseListObserver<Team>(ref: teamsRef, onChanged: self.teamsChanged)
self.teamsObserver!.comparisonFunc = { (a, b) -> Bool in
return a.name < b.name
}
let userRef = User.createRef(uid)
self.userObserver = FirebaseObserver<User>(query: userRef, withBlock: { user in
self.user = user
let authUser = UserStore.sharedInstance().getAuthUser()
// Filter out teams that the auth user is not a member of.
var newIds: [String: Bool] = [:]
for id in user.teamIds.keys {
if authUser.teamIds[id] != nil {
newIds[id] = true
}
}
if let observer = self.teamsObserver {
observer.setKeys(newIds.keys.array)
}
})
}
private func teamsChanged(teams: [Team]) {
let oldTeams = self.teams
self.teams = teams
if !self.isViewLoaded() {
return
}
if oldTeams.isEmpty {
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Fade)
} else {
var updates = Helpers.diffArrays(oldTeams, end: teams, section: 0, compare: { (a, b) -> Bool in
return a.id == b.id
})
if !updates.inserts.isEmpty || !updates.deletes.isEmpty {
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths(updates.deletes, withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths(updates.inserts, withRowAnimation: .Fade)
self.tableView.endUpdates()
}
for (index, team) in enumerate(teams) {
let indexPath = NSIndexPath(forRow: index, inSection: 0)
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? TeamCell {
cell.setTopBorder(index == 0 ? .Full : .None)
cell.setTeam(team)
}
}
}
}
// TableViewController Overrides
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.teams.isEmpty ? 1 : self.teams.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 72.0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.row == 0 && self.teams.isEmpty) {
return tableView.dequeueReusableCellWithIdentifier("LoadingCell") as! LoadingCell
}
let cell = tableView.dequeueReusableCellWithIdentifier("TeamCell") as! TeamCell
cell.arrowImage.hidden = true
cell.setTopBorder(indexPath.row == 0 ? .Full : .None)
cell.setTeam(self.teams[indexPath.row])
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let delegate = self.delegate {
delegate.selectedTeam(self.teams[indexPath.row])
}
self.navigationController?.popViewControllerAnimated(true)
}
private func dispose() {
if let observer = self.userObserver {
observer.dispose()
}
if let observer = self.teamsObserver {
observer.dispose()
}
}
}
|
gpl-2.0
|
44463bdb647d950248cbf7ba18d1165b
| 34.11811 | 118 | 0.616506 | 4.841477 | false | false | false | false |
zerovagner/Desafio-Mobfiq
|
desafioMobfiq/desafioMobfiq/Remote.swift
|
1
|
1688
|
//
// Remote.swift
// desafioMobfiq
//
// Created by Vagner Oliveira on 6/16/17.
// Copyright © 2017 Vagner Oliveira. All rights reserved.
//
import Foundation
import Alamofire
func fetchItems (matchingQuery query: String = "", withOffset offset: Int = 0, andSize size: Int = 10, andApiQuery apiQuery: String = "", completed: @escaping (_ list: [Product]?) -> ()) {
let addr = URL(string: "https://desafio.mobfiq.com.br/Search/Criteria")!
let params = [
"query" : query,
"offset": offset,
"size": size,
"apiquery" : apiQuery
] as [String : Any]
var productList: [Product] = []
Alamofire.request(addr, method: .post, parameters: params).validate().responseJSON {
response in
switch response.result {
case .success(let value):
if let content = value as? [String:Any] {
if let list = content["Products"] as? [[String:Any]] {
productList = Product.generateProductList(fromData: list)
completed(productList)
}
}
case .failure(let error):
print(error)
completed(nil)
}
}
}
func fetchCategories (completed: @escaping (_ list: [Category]?) -> ()) {
let addr = URL(string: "https://desafio.mobfiq.com.br/StorePreference/CategoryTree")!
var categoryList: [Category] = []
Alamofire.request(addr, method: .get, parameters: nil).validate().responseJSON {
response in
switch response.result {
case .success(let value):
if let content = value as? [String:Any] {
if let list = content["Categories"] as? [[String:Any]] {
categoryList = Category.generateCategoriesTree(fromData: list)
completed(categoryList)
}
}
case .failure(let error):
print(error)
completed(nil)
}
}
}
|
mit
|
04b2b0daf1e04fb2a79669a0c7db7387
| 28.086207 | 189 | 0.659751 | 3.307843 | false | false | false | false |
ibm-cloud-security/appid-serversdk-swift
|
Sources/IBMCloudAppID/String.swift
|
1
|
1589
|
/*
Copyright 2018 IBM Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import Cryptor
extension String {
func base64decodedData() -> Data? {
let missing = self.count % 4
var ending = ""
if missing > 0 {
let amount = 4 - missing
ending = String(repeating: "=", count: amount)
}
let base64 = self.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") + ending
return Data(base64Encoded: base64, options: Data.Base64DecodingOptions())
}
/// Generates a random state
///
/// - parameter: length - denotes the number of bytes in the random string
/// - returns: a random string of the specified size
static func generateStateParameter(of length: Int) -> String? {
do {
let randomBytes = try Random.generate(byteCount: length)
return CryptoUtils.data(from: randomBytes).base64URLEncode()
.trimmingCharacters(in: CharacterSet(charactersIn: "="))
} catch {
return nil
}
}
}
|
apache-2.0
|
0f8d65a75d831d7523687de9ca35d3c2
| 32.808511 | 116 | 0.657646 | 4.566092 | false | false | false | false |
stephentyrone/swift
|
test/IRGen/prespecialized-metadata/enum-inmodule-0argument-within-class-1argument-1distinct_use.swift
|
3
|
3962
|
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main9NamespaceC5ValueOySi_GMf" = linkonce_odr hidden constant <{
// CHECk-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: }> <{
// i8** getelementptr inbounds (
// %swift.enum_vwtable,
// %swift.enum_vwtable* @"$s4main9NamespaceC5ValueOySi_GWV",
// i32 0,
// i32 0
// ),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.*}}$s4main9NamespaceC5ValueOMn{{.*}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
final class Namespace<First> {
enum Value {
case first(First)
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main9NamespaceC5ValueOySi_GMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Namespace.Value.first(13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueOMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_1]]:
// CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]]
// CHECK: br i1 [[EQUAL_TYPES_1_1]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED_1]]:
// CHECK: ret %swift.metadata_response {
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main9NamespaceC5ValueOySi_GMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] 0
// CHECK-SAME: }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE_1]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main9NamespaceC5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
|
apache-2.0
|
cf0b8c180ee793ac3de1967699233e3a
| 37.466019 | 157 | 0.563857 | 3.008352 | false | false | false | false |
EstefaniaGilVaquero/OrienteeringQuizIOS
|
OrienteeringQuiz/Pods/SideMenu/Pod/Classes/UISideMenuNavigationController.swift
|
1
|
7752
|
//
// UISideMenuNavigationController.swift
//
// Created by Jon Kent on 1/14/16.
// Copyright © 2016 Jon Kent. All rights reserved.
//
import UIKit
open class UISideMenuNavigationController: UINavigationController {
internal var originalMenuBackgroundColor: UIColor?
open override func awakeFromNib() {
super.awakeFromNib()
// if this isn't set here, segues cause viewWillAppear and viewDidAppear to be called twice
// likely because the transition completes and the presentingViewController is added back
// into view for the default transition style.
modalPresentationStyle = .overFullScreen
}
/// Whether the menu appears on the right or left side of the screen. Right is the default.
@IBInspectable open var leftSide:Bool = false {
didSet {
if isViewLoaded && oldValue != leftSide { // suppress warnings
didSetSide()
}
}
}
override open func viewDidLoad() {
super.viewDidLoad()
didSetSide()
}
fileprivate func didSetSide() {
if leftSide {
SideMenuManager.menuLeftNavigationController = self
} else {
SideMenuManager.menuRightNavigationController = self
}
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// we had presented a view before, so lets dismiss ourselves as already acted upon
if view.isHidden {
SideMenuTransition.hideMenuComplete()
dismiss(animated: false, completion: { () -> Void in
self.view.isHidden = false
})
}
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// when presenting a view controller from the menu, the menu view gets moved into another transition view above our transition container
// which can break the visual layout we had before. So, we move the menu view back to its original transition view to preserve it.
if !isBeingDismissed {
if let mainView = presentingViewController?.view {
switch SideMenuManager.menuPresentMode {
case .viewSlideOut, .viewSlideInOut:
mainView.superview?.insertSubview(view, belowSubview: mainView)
case .menuSlideIn, .menuDissolveIn:
if let tapView = SideMenuTransition.tapView {
mainView.superview?.insertSubview(view, aboveSubview: tapView)
} else {
mainView.superview?.insertSubview(view, aboveSubview: mainView)
}
}
}
}
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// we're presenting a view controller from the menu, so we need to hide the menu so it isn't g when the presented view is dismissed.
if !isBeingDismissed {
view.isHidden = true
SideMenuTransition.hideMenuStart()
}
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// don't bother resizing if the view isn't visible
if view.isHidden {
return
}
SideMenuTransition.statusBarView?.isHidden = true
coordinator.animate(alongsideTransition: { (context) -> Void in
SideMenuTransition.presentMenuStart(forSize: size)
}) { (context) -> Void in
SideMenuTransition.statusBarView?.isHidden = false
}
}
override open func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let menuViewController: UINavigationController = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController,
let presentingViewController = menuViewController.presentingViewController as? UINavigationController {
presentingViewController.prepare(for: segue, sender: sender)
}
}
override open func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if let menuViewController: UINavigationController = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController,
let presentingViewController = menuViewController.presentingViewController as? UINavigationController {
return presentingViewController.shouldPerformSegue(withIdentifier: identifier, sender: sender)
}
return super.shouldPerformSegue(withIdentifier: identifier, sender: sender)
}
override open func pushViewController(_ viewController: UIViewController, animated: Bool) {
guard viewControllers.count > 0 && !SideMenuManager.menuAllowSubmenus else {
// NOTE: pushViewController is called by init(rootViewController: UIViewController)
// so we must perform the normal super method in this case.
super.pushViewController(viewController, animated: animated)
return
}
let tabBarController = presentingViewController as? UITabBarController
guard let navigationController = (tabBarController?.selectedViewController ?? presentingViewController) as? UINavigationController else {
print("SideMenu Warning: attempt to push a View Controller from \(presentingViewController.self) where its navigationController == nil. It must be embedded in a Navigation Controller for this to work.")
return
}
// to avoid overlapping dismiss & pop/push calls, create a transaction block where the menu
// is dismissed after showing the appropriate screen
CATransaction.begin()
CATransaction.setCompletionBlock( { () -> Void in
self.dismiss(animated: true, completion: nil)
self.visibleViewController?.viewWillAppear(false) // Hack: force selection to get cleared on UITableViewControllers when reappearing using custom transitions
})
UIView.animate(withDuration: SideMenuManager.menuAnimationDismissDuration, animations: { () -> Void in
SideMenuTransition.hideMenuStart()
})
if SideMenuManager.menuAllowPopIfPossible {
for subViewController in navigationController.viewControllers {
if type(of: subViewController) == type(of: viewController) {
navigationController.popToViewController(subViewController, animated: animated)
CATransaction.commit()
return
}
}
}
if SideMenuManager.menuReplaceOnPush {
var viewControllers = navigationController.viewControllers
viewControllers.removeLast()
viewControllers.append(viewController)
navigationController.setViewControllers(viewControllers, animated: animated)
CATransaction.commit()
return
}
if let lastViewController = navigationController.viewControllers.last, !SideMenuManager.menuAllowPushOfSameClassTwice && type(of: lastViewController) == type(of: viewController) {
CATransaction.commit()
return
}
navigationController.pushViewController(viewController, animated: animated)
CATransaction.commit()
}
}
|
apache-2.0
|
8293f16e402c27f75f0cd3e08bda27ef
| 43.039773 | 214 | 0.653722 | 6.291396 | false | false | false | false |
TelerikAcademy/Mobile-Applications-with-iOS
|
demos/AnimationsDemos/AnimationsDemos/GesturesViewController.swift
|
1
|
3759
|
//
// GesturesViewController.swift
// AnimationsDemos
//
// Created by Doncho Minkov on 3/29/17.
// Copyright © 2017 Doncho Minkov. All rights reserved.
//
import UIKit
class GesturesViewController: UIViewController {
var rect: UIView?
var tapGesture: UITapGestureRecognizer?
func getRandomColor() -> UIColor {
let red: Float = (Float(arc4random()).truncatingRemainder(dividingBy: 10)) / 10
let green: Float = (Float(arc4random()).truncatingRemainder(dividingBy: 10)) / 10
let blue: Float = (Float(arc4random()).truncatingRemainder(dividingBy: 10)) / 10
return UIColor(colorLiteralRed: red, green: green, blue: blue, alpha: 255)
}
override func viewDidLoad() {
super.viewDidLoad()
self.rect = UIView(frame: CGRect(x: 50, y: 50, width: 30, height: 30))
self.rect?.layer.cornerRadius = 20
self.rect?.backgroundColor = .black
self.view.addSubview(rect!)
self.tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap))
self.view.addGestureRecognizer(tapGesture!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var isNormalSize: Bool = true
func tap() {
weak var weakSelf = self
let location = tapGesture?.location(in: self.view)
UIView.animate(withDuration: 1, animations: {
weakSelf?.rect?.backgroundColor = weakSelf?.getRandomColor()
weakSelf?.rect?.frame.origin = location!
weakSelf?.rect?.frame = CGRect(x: (location?.x)!,
y: (location?.y)!,
width: self.isNormalSize
? (weakSelf?.rect?.frame.width)! - 25
: (weakSelf?.rect?.bounds.width)! + 25,
height: self.isNormalSize
? (weakSelf?.rect?.bounds.height)! - 25
: (weakSelf?.rect?.bounds.height)! + 25)
weakSelf?.isNormalSize = !(weakSelf?.isNormalSize)!
}, completion: { isAnimated in
weakSelf?.tap()
})
// UIView.animate(withDuration: 1) {
// weakSelf?.rect?.backgroundColor = weakSelf?.getRandomColor()
// weakSelf?.rect?.frame.origin = location!
// weakSelf?.rect?.frame = CGRect(x: (location?.x)!,
// y: (location?.y)!,
// width: self.isNormalSize
// ? (weakSelf?.rect?.frame.width)! - 25
// : (weakSelf?.rect?.bounds.width)! + 25,
// height: self.isNormalSize
// ? (weakSelf?.rect?.bounds.height)! - 25
// : (weakSelf?.rect?.bounds.height)! + 25)
// weakSelf?.isNormalSize = !(weakSelf?.isNormalSize)!
//
// }
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
0c2e0af7ca27ef920fec9fd5914f8b94
| 41.224719 | 107 | 0.502661 | 5.219444 | false | false | false | false |
younata/RSSClient
|
Tethys/Easter Eggs/RogueLike/RogueLikeGame.swift
|
1
|
3346
|
import SpriteKit
final class RogueLikeGame: NSObject {
let player: SKNode = {
var path = CGMutablePath()
path.addEllipse(in: CGRect(x: -10, y: -10, width: 20, height: 20))
path.closeSubpath()
path.move(to: CGPoint(x: 0, y: 10))
path.addLine(to: CGPoint(x: 5, y: -9))
path.addLine(to: CGPoint(x: -5, y: -9))
path.closeSubpath()
let node = SKShapeNode(path: path, centered: true)
node.fillColor = Theme.highlightColor
node.strokeColor = .white
node.physicsBody = SKPhysicsBody(polygonFrom: CGPath(ellipseIn: CGRect(x: -10, y: -10, width: 20, height: 20),
transform: nil))
node.physicsBody?.allowsRotation = false
node.physicsBody?.restitution = 0
node.physicsBody?.friction = 1.0
return node
}()
let view: SKView
let levelGenerator: LevelGenerator
init(view: SKView, levelGenerator: LevelGenerator) {
self.view = view
self.levelGenerator = levelGenerator
super.init()
}
func start(bounds: CGRect) {
self.view.presentScene(self.levelScene(bounds: bounds, safeArea: self.view.safeAreaInsets))
self.player.position = bounds.center
self.view.scene?.addChild(self.player)
}
func levelScene(bounds: CGRect, safeArea: UIEdgeInsets) -> SKScene {
let scene = self.generateScene(bounds: bounds)
let level = self.levelGenerator.generate(level: 1, bounds: bounds.inset(by: safeArea))
scene.addChild(level.node)
scene.isPaused = false
return scene
}
func guidePlayer(direction: CGVector) {
let unitsPerSecond: CGFloat = 50
self.player.physicsBody?.velocity = CGVector(
dx: direction.dx * unitsPerSecond,
dy: direction.dy * -unitsPerSecond
)
guard direction != .zero else { return }
self.player.zRotation = atan2(-direction.dy, direction.dx) - (.pi / 2)
}
func panCamera(in direction: CGVector) {
guard let camera = self.view.scene?.camera else { return }
camera.position += direction
}
private func generateScene(bounds: CGRect) -> SKScene {
let scene = SKScene(size: bounds.size)
scene.physicsWorld.gravity = .zero
let cameraNode = SKCameraNode()
cameraNode.position = CGPoint(x: bounds.size.width / 2,
y: bounds.size.height / 2)
scene.addChild(cameraNode)
scene.camera = cameraNode
return scene
}
}
struct Level {
let number: Int
let node: SKNode
}
protocol LevelGenerator {
func generate(level number: Int, bounds: CGRect) -> Level
}
struct BoxLevelGenerator: LevelGenerator {
func generate(level number: Int, bounds: CGRect) -> Level {
let roomRect = bounds.inset(by: UIEdgeInsets(top: 24, left: 0, bottom: 8, right: 0))
let room = SKShapeNode(rect: roomRect)
room.fillColor = .clear
room.strokeColor = .white
room.lineWidth = 2
room.physicsBody = SKPhysicsBody(edgeLoopFrom: roomRect)
room.physicsBody?.isDynamic = false
room.physicsBody?.restitution = 0
room.physicsBody?.friction = 1.0
return Level(number: number, node: room)
}
}
|
mit
|
94c4ffd4d07427cf30c10c1a6b829ec0
| 32.46 | 118 | 0.614465 | 4.240811 | false | false | false | false |
gongmingqm10/SwiftTraining
|
Calculator/Calculator/String+Extensions.swift
|
1
|
815
|
//
// String+Extensions.swift
// Calculator
//
// Created by Ming Gong on 6/15/15.
// Copyright © 2015 gongmingqm10. All rights reserved.
//
import Foundation
extension String {
func beginsWith (str: String) -> Bool {
if let range = self.rangeOfString(str) {
return range.startIndex == self.startIndex
}
return false
}
func endsWith (str: String) -> Bool {
if let range = self.rangeOfString(str) {
return range.endIndex == self.endIndex
}
return false
}
mutating func removeCharsFromEnd(removeCount:Int) {
let stringLength = self.characters.count
let substringIndex = max(0, stringLength - removeCount)
self = self.substringToIndex(advance(self.startIndex, substringIndex))
}
}
|
mit
|
6e5d566cf5077f941a321e8bbfab7234
| 24.46875 | 78 | 0.625307 | 4.195876 | false | false | false | false |
larryhou/swift
|
SimpleTableView/SimpleTableView/TableViewController.swift
|
1
|
2834
|
//
// ViewController.swift
// SimpleTableView
//
// Created by larryhou on 3/11/15.
// Copyright (c) 2015 larryhou. All rights reserved.
//
import UIKit
class GroupTableViewController: UITableViewController {
private var _list: [TimeZoneInfo]!
private var _titles: [String]!
private var _dict: [String: [TimeZoneInfo]]!
override func viewDidLoad() {
super.viewDidLoad()
_list = TimeZoneModel.model.list
_dict = TimeZoneModel.model.dict
_titles = TimeZoneModel.model.keys
}
// MARK: basic
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return _dict.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var key = _titles[section]
return _dict[key]!.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("TimeZoneCell") as UITableViewCell
var key = _titles[indexPath.section]
(cell.viewWithTag(1) as UILabel).text = _dict[key]![indexPath.row].formattedString
return cell
}
// MARK: index
override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return index
}
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! {
return _titles
}
// MARK: header
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return _titles[section]
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 32
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
class PlainTableViewController: UITableViewController {
private var _list: [TimeZoneInfo]!
override func viewDidLoad() {
super.viewDidLoad()
_list = TimeZoneModel.model.list
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _list.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("TimeZoneCell") as UITableViewCell
(cell.viewWithTag(1) as UILabel).text = _list[indexPath.row].formattedString
return cell
}
}
|
mit
|
c107de7c38ed88090d51f7f8bd8f42a7
| 28.520833 | 123 | 0.718419 | 4.771044 | false | false | false | false |
taironas/gonawin-engine-ios
|
GonawinEngine/Team.swift
|
1
|
2568
|
//
// Team.swift
// GonawinEngine
//
// Created by Remy JOURDE on 09/03/2016.
// Copyright © 2016 Remy Jourde. All rights reserved.
//
import SwiftyJSON
final public class Team: JSONAble {
public let id: Int64
public let name: String
public let membersCount: Int64
public let isPrivate: Bool
public let imageURL: String
public let description: String?
public let accuracy: Double?
public let joined: Bool?
public let members: [User]?
public let tournaments: [Tournament]?
public init(id: Int64, name: String, membersCount: Int64, isPrivate: Bool, imageURL: String, description: String? = nil, accuracy: Double? = nil, joined: Bool? = nil, members: [User]? = nil, tournaments: [Tournament]? = nil) {
self.id = id
self.name = name
self.membersCount = membersCount
self.isPrivate = isPrivate
self.imageURL = imageURL
self.description = description
self.accuracy = accuracy
self.joined = joined
self.members = members
self.tournaments = tournaments
}
static func fromJSON(_ json: JSONDictionary) -> Team {
let json = JSON(json)
return fromJSON(json)
}
static func fromJSON(_ json: JSON) -> Team {
if json["Team"].exists() {
let jsonTeam = json["Team"]
let id = jsonTeam["Id"].int64Value
let name = jsonTeam["Name"].stringValue
let description = jsonTeam["Description"].stringValue
let isPrivate = jsonTeam["Private"].boolValue
let accuracy = jsonTeam["Accuracy"].doubleValue
let joined = json["Joined"].boolValue
let members = json["Players"].arrayValue.map{ User.fromJSON($0) }
let tournaments = json["Tournaments"].arrayValue.map{ Tournament.fromJSON($0) }
let imageURL = json["ImageURL"].stringValue
return Team(id: id, name: name, membersCount: Int64(members.count), isPrivate: isPrivate, imageURL: imageURL, description: description, accuracy: accuracy, joined: joined, members: members, tournaments: tournaments)
}
let id = json["Id"].int64Value
let name = json["Name"].stringValue
let membersCount = json["MembersCount"].int64Value
let isPrivate = json["Private"].boolValue
let imageURL = json["ImageURL"].stringValue
return Team(id: id, name: name, membersCount: membersCount, isPrivate: isPrivate, imageURL: imageURL)
}
}
|
mit
|
1cb4a711dfdf4869f3df9ea38daf404d
| 36.75 | 230 | 0.623296 | 4.403087 | false | false | false | false |
asp2insp/cptinder
|
CPTinder/CardsViewController.swift
|
1
|
3967
|
//
// ViewController.swift
// CPTinder
//
// Created by Josiah Gaskin on 6/3/15.
// Copyright (c) 2015 CodePathLab. All rights reserved.
//
import UIKit
class CardsViewController: UIViewController, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
@IBOutlet var cardView: DraggableImageView!
var cardInitialCenter : CGPoint!
var isPresenting: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
cardView.image = UIImage(named: "ryan")
// 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 didTapImage(sender: UITapGestureRecognizer) {
self.performSegueWithIdentifier("show_profile", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destinationViewController as! ProfileViewController
controller.modalPresentationStyle = UIModalPresentationStyle.Custom
controller.transitioningDelegate = self
controller.image = cardView.image
}
@IBAction func didPan(sender: UIPanGestureRecognizer) {
switch sender.state {
case .Began:
cardInitialCenter = cardView.center
case .Changed, .Ended, .Cancelled:
cardView.center = CGPointMake(cardInitialCenter.x + sender.translationInView(view).x, cardInitialCenter.y + sender.translationInView(view).y)
cardView.setNeedsLayout()
default:
return
}
}
}
extension CardsViewController: UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = true
return self
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = false
return self
}
}
extension CardsViewController: UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
// The value here should be the duration of the animations scheduled in the animationTransition method
return 0.4
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
println("animating transition")
var containerView = transitionContext.containerView()
var cloneImageView = UIImageView(frame: cardView.frame)
cloneImageView.image = cardView.image
cloneImageView.center = cardView.center
cloneImageView.clipsToBounds = true
containerView.addSubview(cloneImageView)
var toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
var fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
if (isPresenting) {
containerView.addSubview(toViewController.view)
toViewController.view.alpha = 0
UIView.animateWithDuration(0.4, animations: { () -> Void in
toViewController.view.alpha = 1
}) { (finished: Bool) -> Void in
transitionContext.completeTransition(true)
}
} else {
UIView.animateWithDuration(0.4, animations: { () -> Void in
fromViewController.view.alpha = 0
}) { (finished: Bool) -> Void in
transitionContext.completeTransition(true)
fromViewController.view.removeFromSuperview()
}
}
}
}
|
mit
|
3cb08ba228afda12f49f6e218db5e73f
| 36.084112 | 217 | 0.689186 | 6.188768 | false | false | false | false |
bourdakos1/Visual-Recognition-Tool
|
iOS/Visual Recognition/CustomToolbar.swift
|
1
|
1339
|
//
// CustomToolbar.swift
// Visual Recognition
//
// Created by Nicholas Bourdakos on 7/8/17.
// Copyright © 2017 Nicholas Bourdakos. All rights reserved.
//
import UIKit
class CustomToolbar: UIToolbar {
override init(frame: CGRect) {
super.init(frame: frame)
setupToolbar()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupToolbar()
}
private func setupToolbar() {
let color = UIColor(red: 187/255, green: 198/255, blue: 206/255, alpha: 1.0)
let image = getImage(color: color, size: CGSize(width: 1.0, height: 1.0/UIScreen.main.scale))
self.setShadowImage(image, forToolbarPosition: .bottom)
}
func getImage(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: size.width, height: size.height))
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var newSize: CGSize = super.sizeThatFits(size)
newSize.height = 52
return newSize
}
}
|
mit
|
14926ab72e1e5032c2ace3667a6a9a8e
| 27.468085 | 108 | 0.622571 | 4.261146 | false | false | false | false |
Tricertops/YAML
|
Tests/Emitter_Tests.swift
|
1
|
8912
|
//
// Emitter_Tests.swift
// YAML.framework
//
// Created by Martin Kiss on 29 May 2016.
// https://github.com/Tricertops/YAML
//
// The MIT License (MIT)
// Copyright © 2016 Martin Kiss
//
import XCTest
@testable import YAML
class Emitter_Tests: XCTestCase {
override var subdirectory: String {
return "emitted"
}
func test_empty_stream() {
let string = try! Emitter().emit(YAML.Stream())
XCTAssertTrue(string.isEmpty)
}
func test_stream_simple() {
let emitter = Emitter()
let content = Node.Scalar(content: "Hello, YAML!")
let result = try! emitter.emit(content)
let sample = self.file("stream_simple")
XCTAssertEqual(sample, result)
}
func test_stream_multiple() {
let stream = YAML.Stream()
stream.hasVersion = true
stream.prefersStartMark = true
stream.hasEndMark = true
stream.documents = [
Node.Scalar(content: "Hello, YAML!"),
Node.Scalar(content: "Hello, YAML!"),
Node.Scalar(content: "Hello, YAML!"),
]
// libyaml writes single scalar document as:
// --- Hello, YAML!
// I see no way to force the newline there.
let result = try! Emitter().emit(stream)
let sample = self.file("stream_multiple")
XCTAssertEqual(sample, result, "")
}
func test_sequence() {
let stream = YAML.Stream()
stream.documents = [
Node.Sequence(items: [
Node.Scalar(content: "Apple"),
Node.Scalar(content: "Banana"),
Node.Scalar(content: "Citrus"),
]),
Node.Sequence(items: [
Node.Scalar(content: "Apple"),
Node.Scalar(content: "Banana"),
Node.Scalar(content: "Citrus"),
], style: .flow),
Node.Sequence(items: [
Node.Sequence(items: [
Node.Scalar(content: "Apple"),
Node.Scalar(content: "Banana"),
Node.Scalar(content: "Citrus"),
], style: .flow),
Node.Sequence(items: [
Node.Scalar(content: "Apple"),
Node.Scalar(content: "Banana"),
Node.Scalar(content: "Citrus"),
]),
], style: .block),
]
let result = try! Emitter().emit(stream)
let sample = self.file("sequence")
XCTAssertEqual(sample, result, "")
}
func test_mapping() {
let content = Node.Mapping(pairs: [
(Node.Scalar(content: "model"), Node.Scalar(content: "MacBook Pro Retina")),
(Node.Scalar(content: "size"), Node.Scalar(content: "13-inch")),
(Node.Scalar(content: "year"), Node.Scalar(content: "2014")),
(Node.Scalar(content: "processor"), Node.Mapping(pairs: [
(Node.Scalar(content: "model"), Node.Scalar(content: "Intel Core i5")),
(Node.Scalar(content: "speed"), Node.Scalar(content: "2.6 GHz")),
])),
(Node.Scalar(content: "memory"), Node.Mapping(pairs: [
(Node.Scalar(content: "size"), Node.Scalar(content: "8 GB")),
(Node.Scalar(content: "speed"), Node.Scalar(content: "1600 MHz")),
(Node.Scalar(content: "type"), Node.Scalar(content: "DDR3")),
], style: .block)),
(Node.Scalar(content: "graphics"), Node.Mapping(pairs: [
(Node.Scalar(content: "type"), Node.Scalar(content: "Intel Iris")),
(Node.Scalar(content: "memory"), Node.Scalar(content: "1536 MB")),
], style: .flow)),
])
let result = try! Emitter().emit(content)
let sample = self.file("mapping")
XCTAssertEqual(sample, result, "")
}
func test_scalar() {
let content = Node.Mapping(pairs: [
(Node.Scalar(content: "plain"), Node.Scalar(content: "Lorem ipsum dolor sit amet.", style: .plain)),
(Node.Scalar(content: "single quoted"), Node.Scalar(content: "Lorem ipsum dolor sit amet.", style: .singleQuoted)),
(Node.Scalar(content: "double quoted"), Node.Scalar(content: "Lorem ipsum dolor sit amet.", style: .doubleQuoted)),
(Node.Scalar(content: "folded"), Node.Scalar(content: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore\nmagna aliqua.", style: .folded)),
(Node.Scalar(content: "literal"), Node.Scalar(content: "Lorem ipsum dolor sit amet, consectetur adipisicing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna\naliqua.", style: .literal)),
])
let result = try! Emitter().emit(content)
let sample = self.file("scalar")
XCTAssertEqual(sample, result, "")
}
func test_tags() {
let content = Node.Sequence(items: [
Node.Scalar(content: "None"),
Node.Scalar(content: "Standard", tag: .standard(.str)),
Node.Scalar(content: "Custom", tag: .custom("message")),
Node.Scalar(content: "URI", tag: .uri("tag:full.tricertops.com,2016:message")),
Node.Scalar(content: "ShortenedURI", tag: .uri("tag:tricertops.com,2016:message")),
])
let stream = YAML.Stream()
stream.tags = [Tag.Directive(handle: "handle", URI: "tag:tricertops.com,2016")]
stream.documents = [content]
stream.hasEndMark = true
let result = try! Emitter().emit(stream)
let sample = self.file("tags")
XCTAssertEqual(sample, result, "")
}
func test_alias() {
let A = Node.Scalar(content: "A", anchor: "a")
let B = Node.Scalar(content: "B", anchor: "a")
let C = Node.Scalar(content: "C", anchor: "b")
let document1 = Node.Sequence(items: [A, B, C, B, C, B])
let document2 = Node.Sequence()
document2.anchor = "a"
document2.append(document2)
let document3 = Node.Mapping()
document3.anchor = "a"
document3.pairs.append((Node.Scalar(content: "key"), document3))
let document4 = Node.Mapping()
document4.anchor = "a"
document4.pairs.append((document4, Node.Scalar(content: "value")))
let stream = YAML.Stream(documents: [document1, document2, document3, document4])
stream.prefersStartMark = true
stream.hasEndMark = true
let result = try! Emitter().emit(stream)
let sample = self.file("alias")
XCTAssertEqual(sample, result, "")
}
func test_numeric_anchors() {
let A = Node.Scalar(content: "A")
let B = Node.Scalar(content: "B")
let C = Node.Scalar(content: "C")
let D = Node.Scalar(content: "D", anchor: "D")
let E = Node.Scalar(content: "E", anchor: "E")
let sequence = Node.Sequence()
sequence.style = .flow
sequence.anchor = "sequence"
sequence.items = [A, sequence]
let mapping = Node.Mapping()
mapping.style = .flow
mapping.anchor = "mapping"
mapping.pairs = [(B, mapping)]
let F = Node.Scalar(content: "F", anchor: "004")
let G = Node.Scalar(content: "G")
let H = Node.Scalar(content: "H", anchor: "004")
let document1 = Node.Sequence(items: [
A,B,C, C,A,B, D,E, C,
sequence, mapping,
F, G, G, H, F, H,
])
let document2 = Node.Sequence(items: [
A,A, B,B,
])
let stream = YAML.Stream(documents: [document1, document2])
let result = try! Emitter().emit(stream)
let sample = self.file("numeric_anchors")
XCTAssertEqual(sample, result, "")
}
func test_random_anchors() {
let generator: Emitter.AnchorGenerator = .random(length: 2)
XCTAssertEqual(generator.generate(index: 0).characters.count, 2)
XCTAssertEqual(generator.generate(index: 0).characters.count, 2)
XCTAssertEqual(generator.generate(index: 0).characters.count, 2)
XCTAssertEqual(generator.generate(index: 0).characters.count, 2)
// With too many existing anchors, the generator will adjust the length, so it avoids conflicts.
XCTAssertEqual(generator.generate(index: 0, existingCount: 150).characters.count, 2)
XCTAssertEqual(generator.generate(index: 0, existingCount: 160).characters.count, 3)
XCTAssertEqual(generator.generate(index: 0, existingCount: 2500).characters.count, 3)
XCTAssertEqual(generator.generate(index: 0, existingCount: 2600).characters.count, 4)
}
}
|
mit
|
33b2caa3e70e41ef0da8879ef8b1a4a3
| 38.959641 | 215 | 0.560431 | 4.114035 | false | true | false | false |
JensRavens/Interstellar
|
Tests/WarpdriveTests/WaitingTests.swift
|
1
|
1648
|
//
// WarpDriveTests.swift
// WarpDriveTests
//
// Created by Jens Ravens on 13/10/15.
// Copyright © 2015 nerdgeschoss GmbH. All rights reserved.
//
import Foundation
import XCTest
import Interstellar
import Dispatch
fileprivate func asyncOperation(value: String, completion: (Result<String>)->Void) {
completion(Result<String>.success(value))
}
fileprivate func longOperation(value: String, completion: @escaping (Result<String>)->Void) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10){
completion(Result<String>.success(value))
}
}
fileprivate func fail<T>(_ t: T) throws -> T {
throw NSError(domain: "Error", code: 400, userInfo: nil)
}
@available(*, deprecated: 2.0)
class WaitingTests: XCTestCase {
func testWaitingForSuccess() {
let greeting = try! Signal("hello")
.flatMap(asyncOperation)
.wait()
XCTAssertEqual(greeting, "hello")
}
func testWithinTimeoutForSuccess() {
let greeting = try! Signal("hello")
.flatMap(asyncOperation)
.wait(0.3)
XCTAssertEqual(greeting, "hello")
}
func testWithinTimeoutForFail() {
let sig = Signal("hello")
.flatMap(longOperation)
let greeting = try? sig.wait(0.1)
XCTAssertEqual(greeting, nil)
}
func testWaitingForFail() {
do {
let _ = try Signal("hello")
.flatMap(asyncOperation)
.flatMap(fail)
.wait()
XCTFail("This place should never be reached due to an error.")
} catch {
}
}
}
|
mit
|
aa292241ec97fb20ad04cdb8c0955d2a
| 25.564516 | 93 | 0.60595 | 4.19084 | false | true | false | false |
p-rothen/PRSwiftUtils
|
PRSwiftUtils/Colors.swift
|
1
|
2227
|
//
// Colors.swift
// RelayRace
//
// Created by Pedro on 12-08-16.
// Copyright © 2016 Dreamsit. All rights reserved.
//
import Foundation
import UIKit
public enum Colors {
public static let signInBackgroundColor = UIColor(red:0.88, green:0.89, blue:0.89, alpha:1.0)
public static let backgroundColor = UIColor(red:0.93, green:0.93, blue:0.94, alpha:1.0)
public static let startGreen = UIColor(red:0.32, green:0.78, blue:0.31, alpha:1.0)
public static let secondayTextColor = UIColor(red:0.35, green:0.32, blue:0.34, alpha:1.0)
public static let PrimaryColor = UIColor(red:0.29, green:0.44, blue:0.69, alpha:1.0)
public static let PrimaryColorLight = UIColor(red:0.40, green:0.71, blue:0.93, alpha:1.0)
public static let RecyclerItem = UIColor(red:0.97, green:0.97, blue:0.97, alpha:1.0)
public static let PrimaryBackgroud = UIColor(red:0.92, green:0.93, blue:0.94, alpha:1.0)
public static let SecondaryBackground = UIColor(red:0.88, green:0.89, blue:0.89, alpha:1.0)
public static let PromiseLayoutBackground = UIColor(red:0.87, green:0.87, blue:0.87, alpha:1.0)
public static let BlueLightButton = UIColor(red:0.17, green:0.68, blue:0.87, alpha:1.0)
public static let white = UIColor(red:1.00, green:1.00, blue:1.00, alpha:1.0)
public static let GIN = UIColor(red:0.15, green:0.37, blue:0.41, alpha:1.0)
public static let SINorStandBy = UIColor(red:1.00, green:0.40, blue:0.00, alpha:1.0)
public static let SLA = UIColor(red:1.00, green:0.75, blue:0.01, alpha:1.0)
public static let red = UIColor(red:0.93, green:0.00, blue:0.11, alpha:1.0)
public static let notFoundButton = UIColor(red:0.78, green:0.31, blue:0.30, alpha:1.0)
public static let gray = UIColor(red:0.72, green:0.72, blue:0.72, alpha:1.0)
public static let FandC = UIColor(red:0.47, green:0.84, blue:0.81, alpha:1.0)
public static let TRE = UIColor(red:0.41, green:0.26, blue:0.45, alpha:1.0)
public static let relayRaceLog = UIColor(red:0.19, green:0.78, blue:0.81, alpha:1.0)
public static let evaluation = UIColor(red:0.79, green:0.84, blue:0.88, alpha:1.0)
public static let primaryTextColor = UIColor(red:0.46, green:0.49, blue:0.51, alpha:1.0)
}
|
mit
|
7c6d05f076f5fa554d52df60e352140b
| 59.162162 | 100 | 0.691824 | 2.698182 | false | false | false | false |
xedin/swift
|
stdlib/public/core/NativeSet.swift
|
20
|
16647
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A wrapper around __RawSetStorage that provides most of the
/// implementation of Set.
@usableFromInline
@frozen
internal struct _NativeSet<Element: Hashable> {
/// See the comments on __RawSetStorage and its subclasses to understand why we
/// store an untyped storage here.
@usableFromInline
internal var _storage: __RawSetStorage
/// Constructs an instance from the empty singleton.
@inlinable
@inline(__always)
internal init() {
self._storage = __RawSetStorage.empty
}
/// Constructs a native set adopting the given storage.
@inlinable
@inline(__always)
internal init(_ storage: __owned __RawSetStorage) {
self._storage = storage
}
@inlinable
internal init(capacity: Int) {
if capacity == 0 {
self._storage = __RawSetStorage.empty
} else {
self._storage = _SetStorage<Element>.allocate(capacity: capacity)
}
}
#if _runtime(_ObjC)
@inlinable
internal init(_ cocoa: __owned __CocoaSet) {
self.init(cocoa, capacity: cocoa.count)
}
@inlinable
internal init(_ cocoa: __owned __CocoaSet, capacity: Int) {
if capacity == 0 {
self._storage = __RawSetStorage.empty
} else {
_internalInvariant(cocoa.count <= capacity)
self._storage = _SetStorage<Element>.convert(cocoa, capacity: capacity)
for element in cocoa {
let nativeElement = _forceBridgeFromObjectiveC(element, Element.self)
insertNew(nativeElement, isUnique: true)
}
}
}
#endif
}
extension _NativeSet { // Primitive fields
@usableFromInline
internal typealias Bucket = _HashTable.Bucket
@inlinable
internal var capacity: Int {
@inline(__always)
get {
return _assumeNonNegative(_storage._capacity)
}
}
@inlinable
internal var hashTable: _HashTable {
@inline(__always) get {
return _storage._hashTable
}
}
@inlinable
internal var age: Int32 {
@inline(__always) get {
return _storage._age
}
}
// This API is unsafe and needs a `_fixLifetime` in the caller.
@inlinable
internal var _elements: UnsafeMutablePointer<Element> {
return _storage._rawElements.assumingMemoryBound(to: Element.self)
}
@inlinable
@inline(__always)
internal func invalidateIndices() {
_storage._age &+= 1
}
}
extension _NativeSet { // Low-level unchecked operations
@inlinable
@inline(__always)
internal func uncheckedElement(at bucket: Bucket) -> Element {
defer { _fixLifetime(self) }
_internalInvariant(hashTable.isOccupied(bucket))
return _elements[bucket.offset]
}
@inlinable
@inline(__always)
internal func uncheckedInitialize(
at bucket: Bucket,
to element: __owned Element
) {
_internalInvariant(hashTable.isValid(bucket))
(_elements + bucket.offset).initialize(to: element)
}
@_alwaysEmitIntoClient @inlinable // Introduced in 5.1
@inline(__always)
internal func uncheckedAssign(
at bucket: Bucket,
to element: __owned Element
) {
_internalInvariant(hashTable.isOccupied(bucket))
(_elements + bucket.offset).pointee = element
}
}
extension _NativeSet { // Low-level lookup operations
@inlinable
@inline(__always)
internal func hashValue(for element: Element) -> Int {
return element._rawHashValue(seed: _storage._seed)
}
@inlinable
@inline(__always)
internal func find(_ element: Element) -> (bucket: Bucket, found: Bool) {
return find(element, hashValue: self.hashValue(for: element))
}
/// Search for a given element, assuming it has the specified hash value.
///
/// If the element is not present in this set, return the position where it
/// could be inserted.
@inlinable
@inline(__always)
internal func find(
_ element: Element,
hashValue: Int
) -> (bucket: Bucket, found: Bool) {
let hashTable = self.hashTable
var bucket = hashTable.idealBucket(forHashValue: hashValue)
while hashTable._isOccupied(bucket) {
if uncheckedElement(at: bucket) == element {
return (bucket, true)
}
bucket = hashTable.bucket(wrappedAfter: bucket)
}
return (bucket, false)
}
}
extension _NativeSet { // ensureUnique
@inlinable
internal mutating func resize(capacity: Int) {
let capacity = Swift.max(capacity, self.capacity)
let result = _NativeSet(_SetStorage<Element>.resize(
original: _storage,
capacity: capacity,
move: true))
if count > 0 {
for bucket in hashTable {
let element = (self._elements + bucket.offset).move()
result._unsafeInsertNew(element)
}
// Clear out old storage, ensuring that its deinit won't overrelease the
// elements we've just moved out.
_storage._hashTable.clear()
_storage._count = 0
}
_storage = result._storage
}
@inlinable
internal mutating func copyAndResize(capacity: Int) {
let capacity = Swift.max(capacity, self.capacity)
let result = _NativeSet(_SetStorage<Element>.resize(
original: _storage,
capacity: capacity,
move: false))
if count > 0 {
for bucket in hashTable {
result._unsafeInsertNew(self.uncheckedElement(at: bucket))
}
}
_storage = result._storage
}
@inlinable
internal mutating func copy() {
let newStorage = _SetStorage<Element>.copy(original: _storage)
_internalInvariant(newStorage._scale == _storage._scale)
_internalInvariant(newStorage._age == _storage._age)
_internalInvariant(newStorage._seed == _storage._seed)
let result = _NativeSet(newStorage)
if count > 0 {
result.hashTable.copyContents(of: hashTable)
result._storage._count = self.count
for bucket in hashTable {
let element = uncheckedElement(at: bucket)
result.uncheckedInitialize(at: bucket, to: element)
}
}
_storage = result._storage
}
/// Ensure storage of self is uniquely held and can hold at least `capacity`
/// elements. Returns true iff contents were rehashed.
@inlinable
@inline(__always)
internal mutating func ensureUnique(isUnique: Bool, capacity: Int) -> Bool {
if _fastPath(capacity <= self.capacity && isUnique) {
return false
}
if isUnique {
resize(capacity: capacity)
return true
}
if capacity <= self.capacity {
copy()
return false
}
copyAndResize(capacity: capacity)
return true
}
internal mutating func reserveCapacity(_ capacity: Int, isUnique: Bool) {
_ = ensureUnique(isUnique: isUnique, capacity: capacity)
}
}
extension _NativeSet {
@inlinable
@inline(__always)
func validatedBucket(for index: _HashTable.Index) -> Bucket {
_precondition(hashTable.isOccupied(index.bucket) && index.age == age,
"Attempting to access Set elements using an invalid index")
return index.bucket
}
@inlinable
@inline(__always)
func validatedBucket(for index: Set<Element>.Index) -> Bucket {
#if _runtime(_ObjC)
guard index._isNative else {
index._cocoaPath()
let cocoa = index._asCocoa
// Accept Cocoa indices as long as they contain an element that exists in
// this set, and the address of their Cocoa object generates the same age.
if cocoa.age == self.age {
let element = _forceBridgeFromObjectiveC(cocoa.element, Element.self)
let (bucket, found) = find(element)
if found {
return bucket
}
}
_preconditionFailure(
"Attempting to access Set elements using an invalid index")
}
#endif
return validatedBucket(for: index._asNative)
}
}
extension _NativeSet: _SetBuffer {
@usableFromInline
internal typealias Index = Set<Element>.Index
@inlinable
internal var startIndex: Index {
let bucket = hashTable.startBucket
return Index(_native: _HashTable.Index(bucket: bucket, age: age))
}
@inlinable
internal var endIndex: Index {
let bucket = hashTable.endBucket
return Index(_native: _HashTable.Index(bucket: bucket, age: age))
}
@inlinable
internal func index(after index: Index) -> Index {
// Note that _asNative forces this not to work on Cocoa indices.
let bucket = validatedBucket(for: index._asNative)
let next = hashTable.occupiedBucket(after: bucket)
return Index(_native: _HashTable.Index(bucket: next, age: age))
}
@inlinable
@inline(__always)
internal func index(for element: Element) -> Index? {
if count == 0 {
// Fast path that avoids computing the hash of the key.
return nil
}
let (bucket, found) = find(element)
guard found else { return nil }
return Index(_native: _HashTable.Index(bucket: bucket, age: age))
}
@inlinable
internal var count: Int {
@inline(__always) get {
return _assumeNonNegative(_storage._count)
}
}
@inlinable
@inline(__always)
internal func contains(_ member: Element) -> Bool {
// Fast path: Don't calculate the hash if the set has no elements.
if count == 0 { return false }
return find(member).found
}
@inlinable
@inline(__always)
internal func element(at index: Index) -> Element {
let bucket = validatedBucket(for: index)
return uncheckedElement(at: bucket)
}
}
// This function has a highly visible name to make it stand out in stack traces.
@usableFromInline
@inline(never)
internal func ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(
_ elementType: Any.Type
) -> Never {
_assertionFailure(
"Fatal error",
"""
Duplicate elements of type '\(elementType)' were found in a Set.
This usually means either that the type violates Hashable's requirements, or
that members of such a set were mutated after insertion.
""",
flags: _fatalErrorFlags())
}
extension _NativeSet { // Insertions
/// Insert a new element into uniquely held storage.
/// Storage must be uniquely referenced with adequate capacity.
/// The `element` must not be already present in the Set.
@inlinable
internal func _unsafeInsertNew(_ element: __owned Element) {
_internalInvariant(count + 1 <= capacity)
let hashValue = self.hashValue(for: element)
if _isDebugAssertConfiguration() {
// In debug builds, perform a full lookup and trap if we detect duplicate
// elements -- these imply that the Element type violates Hashable
// requirements. This is generally more costly than a direct insertion,
// because we'll need to compare elements in case of hash collisions.
let (bucket, found) = find(element, hashValue: hashValue)
guard !found else {
ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self)
}
hashTable.insert(bucket)
uncheckedInitialize(at: bucket, to: element)
} else {
let bucket = hashTable.insertNew(hashValue: hashValue)
uncheckedInitialize(at: bucket, to: element)
}
_storage._count &+= 1
}
/// Insert a new element into uniquely held storage.
/// Storage must be uniquely referenced.
/// The `element` must not be already present in the Set.
@inlinable
internal mutating func insertNew(_ element: __owned Element, isUnique: Bool) {
_ = ensureUnique(isUnique: isUnique, capacity: count + 1)
_unsafeInsertNew(element)
}
@inlinable
internal func _unsafeInsertNew(_ element: __owned Element, at bucket: Bucket) {
hashTable.insert(bucket)
uncheckedInitialize(at: bucket, to: element)
_storage._count += 1
}
@inlinable
internal mutating func insertNew(
_ element: __owned Element,
at bucket: Bucket,
isUnique: Bool
) {
_internalInvariant(!hashTable.isOccupied(bucket))
var bucket = bucket
let rehashed = ensureUnique(isUnique: isUnique, capacity: count + 1)
if rehashed {
let (b, f) = find(element)
if f {
ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self)
}
bucket = b
}
_unsafeInsertNew(element, at: bucket)
}
@inlinable
internal mutating func update(
with element: __owned Element,
isUnique: Bool
) -> Element? {
var (bucket, found) = find(element)
let rehashed = ensureUnique(
isUnique: isUnique,
capacity: count + (found ? 0 : 1))
if rehashed {
let (b, f) = find(element)
if f != found {
ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self)
}
bucket = b
}
if found {
let old = (_elements + bucket.offset).move()
uncheckedInitialize(at: bucket, to: element)
return old
}
_unsafeInsertNew(element, at: bucket)
return nil
}
/// Insert an element into uniquely held storage, replacing an existing value
/// (if any). Storage must be uniquely referenced with adequate capacity.
@_alwaysEmitIntoClient @inlinable // Introduced in 5.1
internal mutating func _unsafeUpdate(
with element: __owned Element
) {
let (bucket, found) = find(element)
if found {
uncheckedAssign(at: bucket, to: element)
} else {
_precondition(count < capacity)
_unsafeInsertNew(element, at: bucket)
}
}
}
extension _NativeSet {
@inlinable
@inline(__always)
func isEqual(to other: _NativeSet) -> Bool {
if self._storage === other._storage { return true }
if self.count != other.count { return false }
for member in self {
guard other.find(member).found else { return false }
}
return true
}
#if _runtime(_ObjC)
@inlinable
func isEqual(to other: __CocoaSet) -> Bool {
if self.count != other.count { return false }
defer { _fixLifetime(self) }
for bucket in self.hashTable {
let key = self.uncheckedElement(at: bucket)
let bridgedKey = _bridgeAnythingToObjectiveC(key)
guard other.contains(bridgedKey) else { return false }
}
return true
}
#endif
}
extension _NativeSet: _HashTableDelegate {
@inlinable
@inline(__always)
internal func hashValue(at bucket: Bucket) -> Int {
return hashValue(for: uncheckedElement(at: bucket))
}
@inlinable
@inline(__always)
internal func moveEntry(from source: Bucket, to target: Bucket) {
(_elements + target.offset)
.moveInitialize(from: _elements + source.offset, count: 1)
}
}
extension _NativeSet { // Deletion
@inlinable
@_effects(releasenone)
internal mutating func _delete(at bucket: Bucket) {
hashTable.delete(at: bucket, with: self)
_storage._count -= 1
_internalInvariant(_storage._count >= 0)
invalidateIndices()
}
@inlinable
@inline(__always)
internal mutating func uncheckedRemove(
at bucket: Bucket,
isUnique: Bool) -> Element {
_internalInvariant(hashTable.isOccupied(bucket))
let rehashed = ensureUnique(isUnique: isUnique, capacity: capacity)
_internalInvariant(!rehashed)
let old = (_elements + bucket.offset).move()
_delete(at: bucket)
return old
}
@usableFromInline
internal mutating func removeAll(isUnique: Bool) {
guard isUnique else {
let scale = self._storage._scale
_storage = _SetStorage<Element>.allocate(
scale: scale,
age: nil,
seed: nil)
return
}
for bucket in hashTable {
(_elements + bucket.offset).deinitialize(count: 1)
}
hashTable.clear()
_storage._count = 0
invalidateIndices()
}
}
extension _NativeSet: Sequence {
@usableFromInline
@frozen
internal struct Iterator {
// The iterator is iterating over a frozen view of the collection state, so
// it keeps its own reference to the set.
@usableFromInline
internal let base: _NativeSet
@usableFromInline
internal var iterator: _HashTable.Iterator
@inlinable
@inline(__always)
init(_ base: __owned _NativeSet) {
self.base = base
self.iterator = base.hashTable.makeIterator()
}
}
@inlinable
@inline(__always)
internal __consuming func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension _NativeSet.Iterator: IteratorProtocol {
@inlinable
@inline(__always)
internal mutating func next() -> Element? {
guard let index = iterator.next() else { return nil }
return base.uncheckedElement(at: index)
}
}
|
apache-2.0
|
792ee84cf6983c706de00dcd0a8cc172
| 27.701724 | 81 | 0.660059 | 4.249936 | false | false | false | false |
kiroskirin/RunSpeedRun
|
Run Speed Run/UICustomizable.swift
|
1
|
2561
|
//
// UICustomizable.swift
// Run Speed Run
//
// Created by Kraisorn Soisakhu on 2/5/2560 BE.
// Copyright © 2560 UKS Labs. All rights reserved.
//
import UIKit
import MapKit
class RoundCornerView: UIView {
override func draw(_ rect: CGRect) {
let cornerPath = UIBezierPath(roundedRect: rect, byRoundingCorners: [.allCorners], cornerRadii: CGSize(width: 8, height: 8))
UIColor.white.setFill()
cornerPath.fill()
layer.shadowOffset = CGSize(width: 0.13, height: 0.13)
layer.shadowColor = UIColor.laaBlack.cgColor
layer.shadowRadius = 0.5
layer.shadowOpacity = 0.5
}
}
class CircleButton : UIButton {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = self.frame.size.width / 2
}
}
@IBDesignable
class RoundButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
}
protocol InfoViewDelegate {
func startRoute()
}
enum RouteType: String {
case fastest = "Fatest route", longest = "Longest route", normal = "Normal route"
}
class InfoView: UIView {
var delegate: InfoViewDelegate?
var route: MKRoute? {
didSet {
self.timeLabel.text = self.route!.expectedTravelTime.toString()
self.distanceLabel.text = "\(self.route!.distance.toString(with: .abbreviated)) - \(self.route!.name)"
}
}
var routeType: RouteType? {
didSet {
switch routeType! {
case .fastest:
self.goButton.backgroundColor = UIColor.laaGreen
case .longest:
self.goButton.backgroundColor = UIColor.laaRed
default:
self.goButton.backgroundColor = UIColor.laaBlue
}
self.descriptionLabel.isHidden = false
self.descriptionLabel.text = self.routeType!.rawValue
}
}
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var goButton: UIButton!
@IBAction func startRouting(sender: UIButton) {
self.delegate?.startRoute()
}
override func draw(_ rect: CGRect) {
self.descriptionLabel.isHidden = true
layer.shadowOffset = CGSize(width: 0.13, height: 0.13)
layer.shadowColor = UIColor.laaBlack.cgColor
layer.shadowRadius = 0.5
layer.shadowOpacity = 0.5
}
}
|
mit
|
0ac48b1fca6ef816b9d64c73fdae497e
| 27.131868 | 132 | 0.620313 | 4.383562 | false | false | false | false |
wortman/stroll_safe_ios
|
Stroll Safe/MainViewController.swift
|
1
|
8073
|
//
// ViewController.swift
// Stroll Safe
//
// Created by Noah Prince on 3/21/15.
// Copyright (c) 2015 Stroll Safe. All rights reserved.
//
import UIKit
import CoreData
// Lets the time display as 2.00 and not 2
extension Float {
func format(f: String) -> String {
return NSString(format: "%\(f)f", self) as String
}
}
class MainViewController: UIViewController {
// hacked see http://stackoverflow.com/questions/24015207/class-variables-not-yet-supported
static var test: Bool = true
enum state {
case START, THUMB, RELEASE,SHAKE
}
var mode = state.START;
@IBOutlet weak var titleMain: UILabel!
@IBOutlet weak var titleSub: UILabel!
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var thumb: UIButton!
@IBOutlet weak var shake: UIButton!
@IBOutlet weak var shakeDesc: UILabel!
@IBOutlet weak var thumbDesc: UILabel!
/**
Should execute before displaying any view
For now decides which view to start at, set password or main
TODO: Move this to a place that actually executes before the main view loads
:params: The managed object context to check for the passcode
:returns: <#return value description#>
*/
func initializeApp(managedObjectContext: NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!) {
if (MainViewController.test) {
let request = NSFetchRequest(entityName: "Passcode")
var passcodes = try! managedObjectContext.executeFetchRequest(request)
for passcode: AnyObject in passcodes
{
managedObjectContext.deleteObject(passcode as! NSManagedObject)
}
passcodes.removeAll(keepCapacity: false)
try! managedObjectContext.save()
MainViewController.test = false
}
do {
try Passcode.get(managedObjectContext)
} catch Passcode.PasscodeError.NoResultsFound {
dispatch_async(dispatch_get_main_queue(), {
self.performSegueWithIdentifier("firstTimeUserSegue", sender: nil)
})
} catch let error as NSError {
NSLog(error.localizedDescription)
abort()
}
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake && mode == state.SHAKE {
lockdown()
}
}
@IBAction func shakeLongPress(sender: AnyObject) {
if sender.state == UIGestureRecognizerState.Began
{
enterStartState()
}
}
/* Sets an observer to change progress every time
* the timer is updated
*/
var timer:Float = 0 /*{
didSet {
let fractionalProgress = Float(timer) / 200.0
let animated = timer != 0
progressBar.setProgress(fractionalProgress, animated: animated)
progressLabel.text = ("\(timer/100)")
}
}*/
var passcode: String = ""
@IBAction func thumbDown(sender: UIButton) {
enterThumbState()
}
@IBAction func thumbUpInside(sender: UIButton) {
enterReleaseState()
}
@IBAction func thumbUpOutside(sender: AnyObject, forEvent event: UIEvent) {
let buttonView = sender as! UIView
let mainView = self.view
// get any touch on the buttonView
if let touch = event.touchesForView(buttonView)!.first {
let location = touch.locationInView(mainView)
let frame = shake.frame
let minX = CGRectGetMinX(frame)
let maxX = CGRectGetMaxX(frame)
let minY = CGRectGetMinY(frame)
let maxY = CGRectGetMaxY(frame)
if ((location.x < minX || location.x > maxX) ||
(location.y < minY || location.y > maxY)){
enterReleaseState()
}else{
enterShakeState()
}
}
}
@IBAction func releaseButtonAction(sender: AnyObject) {
}
@IBAction func thumbButtonAction(sender: AnyObject) {
}
func enterStartState(){
setThumbVisibility(true)
setProgressVisibility(false)
setShakeVisibility(false, type: true)
changeTitle("Stroll Safe", sub: "Keeping You Safe on Your Late Night Strolls")
mode = state.START
}
func enterThumbState(){
timer = 0
setThumbVisibility(false)
setProgressVisibility(false)
setShakeVisibility(true, type: true)
changeTitle("Release Mode", sub:"Release Thumb to Contact Police")
shakeDesc.text = "Slide Thumb and Release to Enter Shake Mode"
mode = state.THUMB
}
func enterReleaseState(){
setThumbVisibility(true)
setProgressVisibility(true)
setShakeVisibility(false,type: true)
changeTitle("Thumb Released", sub: "Press and Hold Button to Cancel")
mode = state.RELEASE
progressLabel.text = "0"
self.timer = 0
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
for _ in 0..<20 {
if (self.mode != state.RELEASE){
break
}
usleep(2500)
dispatch_async(dispatch_get_main_queue(), {
self.incrementTimer()
})
}
if (self.mode == state.RELEASE){
dispatch_async(dispatch_get_main_queue(), {
self.lockdown()
})
}
})
}
func incrementTimer() {
self.timer++
let fractionalProgress = Float(self.timer) / 20.0
let animated = false;
self.progressBar.setProgress(fractionalProgress, animated: animated)
self.progressLabel.text = ("\(2-(self.timer/10)) seconds remaining")
}
func lockdown() {
performSegueWithIdentifier("lockdownSegue", sender: nil)
}
func enterShakeState(){
timer = 0
setThumbVisibility(true)
setProgressVisibility(false)
setShakeVisibility(true, type: false)
changeTitle("Shake Mode", sub: "Shake Phone to Contact Police")
shakeDesc.text = "Press and Hold to Exit the App"
mode = state.SHAKE
}
func changeTitle(title: NSString, sub: NSString){
titleMain.text = title as String
titleSub.text = sub as String
}
func setProgressVisibility(visibility: Bool){
progressBar.hidden = !visibility
progressLabel.hidden = !visibility
}
func setThumbVisibility(visibility: Bool){
thumb.hidden = !visibility
thumbDesc.hidden = !visibility
}
// First parameter is whether it's visible
// Second sets it as the shake button when true,
// exit button when false
func setShakeVisibility(visibility: Bool, type: Bool){
shake.hidden = !visibility
shakeDesc.hidden = !visibility
// Setup the shake icon
if type{
if let image = UIImage(named: "shake_icon.png") {
shake.setImage(image, forState: .Normal)
}
}
else{
if let image = UIImage(named: "close_icon.png") {
shake.setImage(image, forState: .Normal)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
initializeApp()
enterStartState()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
c011dbbd7ba093a2038c45dd0342a8ac
| 29.349624 | 155 | 0.580082 | 4.995668 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.