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
dathtcheapgo/Jira-Demo
Driver/MVC/Core/View/HLib/HBorderButton.swift
1
2208
import UIKit @IBDesignable class HBorderButton: UIButton { let gradient = CAGradientLayer() override func draw(_ rect: CGRect) { super.draw(rect) if gradientTopColor != nil && gradientBotColor != nil { gradient.removeFromSuperlayer() gradient.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) gradient.colors = [gradientTopColor!.cgColor, gradientBotColor!.cgColor] gradient.startPoint = CGPoint(x: 0.0, y: 0.0) gradient.endPoint = CGPoint(x: 0.0, y: 1.0) self.layer.insertSublayer(gradient, at: 0) } else if gradientLeftColor != nil && gradientRightColor != nil { gradient.removeFromSuperlayer() gradient.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) gradient.colors = [gradientLeftColor!.cgColor, gradientRightColor!.cgColor] gradient.startPoint = CGPoint(x: 0.0, y: 0.0) gradient.endPoint = CGPoint(x: 1.0, y: 0.0) self.layer.insertSublayer(gradient, at: 0) } } @IBInspectable var gradientTopColor: UIColor? = nil @IBInspectable var gradientBotColor: UIColor? = nil @IBInspectable var gradientLeftColor: UIColor? = nil @IBInspectable var gradientRightColor: UIColor? = nil @IBInspectable var borderColor: UIColor = UIColor.black { didSet { self.layer.borderColor = borderColor.cgColor } } @IBInspectable var borderWidth: CGFloat = 1 { didSet { self.layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius: CGFloat = 5 { didSet { self.layer.cornerRadius = cornerRadius self.clipsToBounds = true } } @IBInspectable var enableShadow: Bool = false { didSet { if enableShadow == true { self.layer.masksToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowRadius = 5 self.layer.shadowOpacity = 0.9 } } } }
mit
69ec84f1c9ee5c00e251b091f591a11c
34.047619
99
0.586957
4.628931
false
false
false
false
dropbox/SwiftyDropbox
Source/SwiftyDropbox/Shared/Handwritten/DropboxClient.swift
1
3373
/// /// Copyright (c) 2016 Dropbox, Inc. All rights reserved. /// import Foundation import Alamofire /// The client for the User API. Call routes using the namespaces inside this object (inherited from parent). open class DropboxClient: DropboxBase { private var transportClient: DropboxTransportClient private var accessTokenProvider: AccessTokenProvider private var selectUser: String? /// Initialize a client with a static accessToken string. /// Use this method if your access token is long-lived. /// /// - Parameters: /// - accessToken: Static access token string. /// - selectUser: Id of a team member. This allows the api client to makes call on a team member's behalf. /// - pathRoot: User's path root. public convenience init(accessToken: String, selectUser: String? = nil, pathRoot: Common.PathRoot? = nil) { let transportClient = DropboxTransportClient(accessToken: accessToken, selectUser: selectUser, pathRoot: pathRoot) self.init(transportClient: transportClient) } /// Initialize a client with an `AccessTokenProvider`. /// Use this method if your access token is short-lived. /// See `ShortLivedAccessTokenProvider` for a default implementation. /// /// - Parameters: /// - accessTokenProvider: Access token provider that wraps a short-lived token and its refresh logic. /// - selectUser: Id of a team member. This allows the api client to makes call on a team member's behalf. /// - pathRoot: User's path root. public convenience init( accessTokenProvider: AccessTokenProvider, selectUser: String? = nil, pathRoot: Common.PathRoot? = nil ) { let transportClient = DropboxTransportClient( accessTokenProvider: accessTokenProvider, selectUser: selectUser, pathRoot: pathRoot ) self.init(transportClient: transportClient) } /// Initialize a client with an `DropboxAccessToken`. /// /// - Parameters: /// - accessToken: The token itself, could be long or short lived. /// - dropboxOauthManager: an oauthManager, used for creating the token provider. public convenience init(accessToken: DropboxAccessToken, dropboxOauthManager: DropboxOAuthManager) { let accessTokenProvider = dropboxOauthManager.accessTokenProviderForToken(accessToken) let transportClient = DropboxTransportClient(accessTokenProvider: accessTokenProvider) self.init(transportClient: transportClient) } /// Designated Initializer. /// /// - Parameter transportClient: The underlying DropboxTransportClient to make API calls. public init(transportClient: DropboxTransportClient) { self.transportClient = transportClient self.selectUser = transportClient.selectUser self.accessTokenProvider = transportClient.accessTokenProvider super.init(client: transportClient) } /// Creates a new DropboxClient instance with the given path root. /// /// - Parameter pathRoot: User's path root. /// - Returns: A new DropboxClient instance for the same user but with an updated path root. open func withPathRoot(_ pathRoot: Common.PathRoot) -> DropboxClient { return DropboxClient(accessTokenProvider: accessTokenProvider, selectUser: selectUser, pathRoot: pathRoot) } }
mit
71d8e816c608c14e0d2020e5a3890ee8
45.847222
122
0.708865
5.026826
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Playgrounds/Analysis.playground/Pages/Rolling Output Plot.xcplaygroundpage/Contents.swift
1
1159
//: ## Rolling Output Plot //: ### If you open the Assitant editor and make sure it shows the //: ### "Rolling Output Plot.xcplaygroundpage (Timeline) view", //: ### you should see a plot of the amplitude peaks scrolling in the view import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: "drumloop.wav", baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true var variSpeed = AKVariSpeed(player) variSpeed.rate = 2.0 AudioKit.output = variSpeed AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Playback Speed") addSubview(AKPropertySlider( property: "Rate", format: "%0.3f", value: variSpeed.rate, minimum: 0.3125, maximum: 5, color: AKColor.greenColor() ) { sliderValue in variSpeed.rate = sliderValue }) addSubview(AKRollingOutputPlot.createView()) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
5d1630767c6d9ebbf7f022418ee3d295
27.268293
77
0.666954
4.509728
false
false
false
false
rechsteiner/Parchment
Parchment/Classes/PagingIndicatorLayoutAttributes.swift
1
1574
import UIKit open class PagingIndicatorLayoutAttributes: UICollectionViewLayoutAttributes { open var backgroundColor: UIColor? open override func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) as! PagingIndicatorLayoutAttributes copy.backgroundColor = backgroundColor return copy } open override func isEqual(_ object: Any?) -> Bool { if let rhs = object as? PagingIndicatorLayoutAttributes { if backgroundColor != rhs.backgroundColor { return false } return super.isEqual(object) } else { return false } } func configure(_ options: PagingOptions) { if case let .visible(height, index, _, insets) = options.indicatorOptions { backgroundColor = options.indicatorColor frame.size.height = height switch options.menuPosition { case .top: frame.origin.y = options.menuHeight - height - insets.bottom + insets.top case .bottom: frame.origin.y = insets.bottom } zIndex = index } } func update(from: PagingIndicatorMetric, to: PagingIndicatorMetric, progress: CGFloat) { frame.origin.x = tween(from: from.x, to: to.x, progress: progress) frame.size.width = tween(from: from.width, to: to.width, progress: progress) } func update(to metric: PagingIndicatorMetric) { frame.origin.x = metric.x frame.size.width = metric.width } }
mit
d0c43418d3e627172a8e90a13a59cc7a
32.489362
92
0.609911
4.755287
false
false
false
false
rechsteiner/Parchment
ParchmentTests/PagingDistanceRightTests.swift
1
9789
@testable import Parchment import XCTest final class PagingDistanceRightTests: XCTestCase { private var sizeCache: PagingSizeCache! override func setUp() { sizeCache = PagingSizeCache(options: PagingOptions()) } /// Distance from right aligned item to upcoming item. /// /// ``` /// โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /// โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คโ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /// โ”‚ โ”‚ From โ”‚โ”‚ To โ”‚โ”‚ โ”‚โ”‚ โ”‚ /// โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คโ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /// โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /// x: 0 /// ``` func testDistanceRight() { let distance = createDistance( bounds: CGRect(x: 0, y: 0, width: 500, height: 50), contentSize: CGSize(width: 1000, height: 50), currentItem: Item(index: 0), currentItemBounds: CGRect(x: 400, y: 0, width: 100, height: 50), upcomingItem: Item(index: 1), upcomingItemBounds: CGRect(x: 500, y: 0, width: 100, height: 50), sizeCache: sizeCache, selectedScrollPosition: .right, navigationOrientation: .horizontal ) let value = distance.calculate() XCTAssertEqual(value, 100) } /// Distance from right aligned item to upcoming item. /// /// ``` /// โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /// โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คโ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /// โ”‚ โ”‚ From โ”‚โ”‚ โ”‚โ”‚ To โ”‚โ”‚ โ”‚ /// โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คโ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /// โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /// x: 0 /// ``` func testDistanceRightWithItemsBetween() { let distance = createDistance( bounds: CGRect(x: 0, y: 0, width: 500, height: 50), contentSize: CGSize(width: 1000, height: 50), currentItem: Item(index: 0), currentItemBounds: CGRect(x: 400, y: 0, width: 100, height: 50), upcomingItem: Item(index: 2), upcomingItemBounds: CGRect(x: 600, y: 0, width: 100, height: 50), sizeCache: sizeCache, selectedScrollPosition: .right, navigationOrientation: .horizontal ) let value = distance.calculate() XCTAssertEqual(value, 200) } /// Distance to upcoming item when scrolled slightly. /// /// ``` /// โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /// โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คโ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /// โ”‚ โ”‚โ”‚ โ”‚โ”‚ โ”‚โ”‚ From โ”‚โ”‚ To โ”‚ /// โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คโ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /// โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /// x: 50 /// ``` func testDistanceRightWithContentOffset() { let distance = createDistance( bounds: CGRect(x: 50, y: 0, width: 500, height: 50), contentSize: CGSize(width: 1000, height: 50), currentItem: Item(index: 0), currentItemBounds: CGRect(x: 400, y: 0, width: 100, height: 50), upcomingItem: Item(index: 1), upcomingItemBounds: CGRect(x: 500, y: 0, width: 100, height: 50), sizeCache: sizeCache, selectedScrollPosition: .right, navigationOrientation: .horizontal ) let value = distance.calculate() XCTAssertEqual(value, 50) } /// Distance from larger, right-aligned item positioned before /// smaller upcoming item. /// /// ``` /// โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /// โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คโ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ” /// โ”‚ โ”‚ โ”‚โ”‚ โ”‚โ”‚ โ”‚โ”‚ โ”‚โ”‚ From โ”‚โ”‚ To โ”‚โ”‚ โ”‚ /// โ”‚ โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คโ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜ /// โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /// x: 0 /// ``` func testDistanceRightUsingSizeDelegateScrollingForward() { sizeCache.implementsSizeDelegate = true sizeCache.sizeForPagingItem = { _, isSelected in if isSelected { return 100 } else { return 50 } } let distance = createDistance( bounds: CGRect(x: 0, y: 0, width: 500, height: 50), contentSize: CGSize(width: 1000, height: 50), currentItem: Item(index: 0), currentItemBounds: CGRect(x: 500, y: 0, width: 100, height: 50), upcomingItem: Item(index: 1), upcomingItemBounds: CGRect(x: 500, y: 0, width: 50, height: 50), sizeCache: sizeCache, selectedScrollPosition: .right, navigationOrientation: .horizontal ) let value = distance.calculate() XCTAssertEqual(value, 50) } /// Distance from larger, right-aligned item positioned after /// smaller larger item. /// /// ``` /// โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /// โ”œโ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คโ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ” /// โ”‚ โ”‚โ”‚ โ”‚โ”‚ โ”‚โ”‚ โ”‚โ”‚ To โ”‚โ”‚ From โ”‚โ”‚ โ”‚โ”‚ โ”‚ /// โ”œโ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คโ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜ /// โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /// x: 200 /// ``` func testDistanceRightUsingSizeDelegateScrollingBackward() { sizeCache.implementsSizeDelegate = true sizeCache.sizeForPagingItem = { _, isSelected in if isSelected { return 100 } else { return 50 } } let distance = createDistance( bounds: CGRect(x: 200, y: 0, width: 500, height: 50), contentSize: CGSize(width: 2000, height: 50), currentItem: Item(index: 1), currentItemBounds: CGRect(x: 600, y: 0, width: 100, height: 50), upcomingItem: Item(index: 0), upcomingItemBounds: CGRect(x: 550, y: 0, width: 50, height: 50), sizeCache: sizeCache, selectedScrollPosition: .right, navigationOrientation: .horizontal ) let value = distance.calculate() XCTAssertEqual(value, -50) } /// Distance from an item scrolled out of view (so we don't have any /// layout attributes) to an item all the way on the other side. /// /// ``` /// โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /// โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”ดโ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”ค /// โ”‚ From โ”‚ ...โ”‚ โ”‚โ”‚ โ”‚โ”‚ โ”‚โ”‚ โ”‚โ”‚ โ”‚โ”‚ โ”‚โ”‚ To โ”‚ /// โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”ฌโ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”ค /// โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ /// x: 200 /// ``` func testDistanceRightUsingSizeDelegateWithoutFromAttributes() { sizeCache.implementsSizeDelegate = true sizeCache.sizeForPagingItem = { _, isSelected in if isSelected { return 100 } else { return 50 } } let distance = createDistance( bounds: CGRect(x: 200, y: 0, width: 500, height: 50), contentSize: CGSize(width: 2000, height: 50), currentItem: Item(index: 1), currentItemBounds: nil, upcomingItem: Item(index: 0), upcomingItemBounds: CGRect(x: 650, y: 0, width: 50, height: 50), sizeCache: sizeCache, selectedScrollPosition: .right, navigationOrientation: .horizontal ) let value = distance.calculate() XCTAssertEqual(value, 50) } }
mit
9bcd62861c4bc65c52d694d4daed5322
36.361386
77
0.42772
4.081666
false
false
false
false
rexchen/swift3-snippets
View/uiImageView.swift
1
525
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //set background color self.view.backgroundColor = UIColor.red() //set background image let backgroundImage = UIImageView() backgroundImage.frame = UIScreen.main().bounds backgroundImage.image = UIImage(named: "galaxy.png") backgroundImage.contentMode = UIViewContentMode.scaleAspectFill self.view.addSubview(backgroundImage) } }
mit
c1aba6a8b9d05850aaba66c1778a8c58
28.222222
71
0.672381
5.585106
false
false
false
false
isnine/HutHelper-Open
HutHelper/SwiftApp/Third/FWPopupView/FWSheetView.swift
1
11277
// // FWSheetView.swift // FWPopupView // // Created by xfg on 2018/3/26. // Copyright ยฉ 2018ๅนด xfg. All rights reserved. // /** ************************************************ githubๅœฐๅ€๏ผšhttps://github.com/choiceyou/FWPopupView bugๅ้ฆˆใ€ไบคๆต็พค๏ผš670698309 *************************************************** */ import Foundation import UIKit open class FWSheetView: FWPopupView { private var actionItemArray: [FWPopupItem] = [] private var titleLabel: UILabel? private var titleContainerView: UIView? private var commponenetArray: [UIView] = [] /// ็ฑปๅˆๅง‹ๅŒ–ๆ–นๆณ•1 /// /// - Parameters: /// - title: ๆ ‡้ข˜ /// - itemTitles: ็‚นๅ‡ป้กนๆ ‡้ข˜ /// - itemBlock: ็‚นๅ‡ปๅ›ž่ฐƒ /// - cancenlBlock: ๅ–ๆถˆๆŒ‰้’ฎๅ›ž่ฐƒ๏ผˆๅ•่ฏๆ‹ผ้”™ไบ†๏ผŒๅฐ†้”™ๅฐฑ้”™ๅง๏ผŒๅ“ˆๅ“ˆ๏ผ‰ /// - Returns: self @objc open class func sheet(title: String?, itemTitles: [String], itemBlock: FWPopupItemClickedBlock? = nil, cancenlBlock: FWPopupVoidBlock? = nil) -> FWSheetView { return self.sheet(title: title, itemTitles: itemTitles, itemBlock: itemBlock, cancenlBlock: cancenlBlock, property: nil) } /// ็ฑปๅˆๅง‹ๅŒ–ๆ–นๆณ•2๏ผšๅฏ่ฎพ็ฝฎSheet็›ธๅ…ณๅฑžๆ€ง /// /// - Parameters: /// - title: ๆ ‡้ข˜ /// - itemTitles: ็‚นๅ‡ป้กนๆ ‡้ข˜ /// - itemBlock: ็‚นๅ‡ปๅ›ž่ฐƒ /// - cancenlBlock: ๅ–ๆถˆๆŒ‰้’ฎๅ›ž่ฐƒ /// - property: FWSheetView็š„็›ธๅ…ณๅฑžๆ€ง /// - Returns: self @objc open class func sheet(title: String?, itemTitles: [String], itemBlock: FWPopupItemClickedBlock? = nil, cancenlBlock: FWPopupVoidBlock? = nil, property: FWSheetViewProperty?) -> FWSheetView { return self.sheet(title: title, itemTitles: itemTitles, itemBlock: itemBlock, cancelItemTitle: nil, cancenlBlock: cancenlBlock, property: property) } /// ็ฑปๅˆๅง‹ๅŒ–ๆ–นๆณ•3๏ผšๅฏ่ฎพ็ฝฎSheet็›ธๅ…ณๅฑžๆ€ง /// /// - Parameters: /// - title: ๆ ‡้ข˜ /// - itemTitles: ็‚นๅ‡ป้กนๆ ‡้ข˜ /// - itemBlock: ็‚นๅ‡ปๅ›ž่ฐƒ /// - cancelItemTitle: ๅ–ๆถˆๆŒ‰้’ฎ็š„ๅ็งฐ /// - cancenlBlock: ๅ–ๆถˆๆŒ‰้’ฎๅ›ž่ฐƒ /// - property: FWSheetView็š„็›ธๅ…ณๅฑžๆ€ง /// - Returns: self @objc open class func sheet(title: String?, itemTitles: [String], itemBlock: FWPopupItemClickedBlock? = nil, cancelItemTitle: String?, cancenlBlock: FWPopupVoidBlock? = nil, property: FWSheetViewProperty?) -> FWSheetView { let sheetView = FWSheetView() sheetView.setupUI(title: title, itemTitles: itemTitles, itemBlock: itemBlock, cancelItemTitle: cancelItemTitle, cancenlBlock: cancenlBlock, property: property) return sheetView } public override init(frame: CGRect) { super.init(frame: frame) self.vProperty = FWSheetViewProperty() self.backgroundColor = self.vProperty.backgroundColor } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension FWSheetView { private func setupUI(title: String?, itemTitles: [String], itemBlock: FWPopupItemClickedBlock? = nil, cancelItemTitle: String?, cancenlBlock: FWPopupVoidBlock? = nil, property: FWSheetViewProperty?) { if property != nil { self.vProperty = property! } let itemClickedBlock: FWPopupItemClickedBlock = { (popupView, index, title) in if itemBlock != nil { itemBlock!(self, index, title) } } for title in itemTitles { self.actionItemArray.append(FWPopupItem(title: title, itemType: .normal, isCancel: true, canAutoHide: true, itemClickedBlock: itemClickedBlock)) } self.clipsToBounds = true self.isNotMakeSize = true self.setContentCompressionResistancePriority(.required, for: .horizontal) self.setContentCompressionResistancePriority(.fittingSizeLevel, for: .vertical) let property = self.vProperty as! FWSheetViewProperty property.popupCustomAlignment = .bottomCenter property.popupAnimationType = .position var lastConstraintItem = self.snp.top if title != nil && !title!.isEmpty { self.titleContainerView = UIView() self.addSubview(self.titleContainerView!) self.titleContainerView?.snp.makeConstraints({ (make) in make.top.left.right.equalTo(self) }) self.titleContainerView?.backgroundColor = UIColor.white self.titleLabel = UILabel() self.titleContainerView?.addSubview(self.titleLabel!) self.titleLabel?.snp.makeConstraints({ (make) in make.edges.equalToSuperview().inset(UIEdgeInsets(top: round(self.vProperty.topBottomMargin*1.5), left: self.vProperty.letfRigthMargin, bottom: round(self.vProperty.topBottomMargin*1.5), right: self.vProperty.letfRigthMargin)) }) self.titleLabel?.text = title self.titleLabel?.textColor = self.vProperty.titleColor self.titleLabel?.textAlignment = .center self.titleLabel?.font = (self.vProperty.titleFont != nil) ? self.vProperty.titleFont! : UIFont.systemFont(ofSize: self.vProperty.titleFontSize) self.titleLabel?.numberOfLines = 10 self.titleLabel?.backgroundColor = UIColor.clear self.commponenetArray.append(self.titleLabel!) lastConstraintItem = self.titleContainerView!.snp.bottom } // ๅผ€ๅง‹้…็ฝฎItem let btnContrainerView = UIScrollView() self.addSubview(btnContrainerView) btnContrainerView.bounces = false btnContrainerView.backgroundColor = UIColor.clear btnContrainerView.snp.makeConstraints { (make) in make.top.equalTo(lastConstraintItem) make.left.right.equalTo(self) } let block: FWPopupItemClickedBlock = { (popupView, index, title) in if cancenlBlock != nil { cancenlBlock!() } } self.actionItemArray.append(FWPopupItem(title: (cancelItemTitle != nil) ? cancelItemTitle! : property.cancelItemTitle, itemType: .normal, isCancel: true, canAutoHide: true, itemTitleColor: property.cancelItemTitleColor, itemTitleFont: property.cancelItemTitleFont, itemBackgroundColor: property.cancelItemBackgroundColor, itemClickedBlock: block)) var tmpIndex = 0 var lastBtn: UIButton! var cancelBtn: UIButton! for popupItem: FWPopupItem in self.actionItemArray { let btn = UIButton(type: .custom) if tmpIndex == self.actionItemArray.count - 1 { self.addSubview(btn) cancelBtn = btn } else { btnContrainerView.addSubview(btn) } btn.addTarget(self, action: #selector(btnAction(_:)), for: .touchUpInside) btn.tag = tmpIndex btn.snp.makeConstraints { (make) in make.left.right.equalTo(btnContrainerView).inset(UIEdgeInsets(top: 0, left: -self.vProperty.splitWidth, bottom: 0, right: -self.vProperty.splitWidth)) make.height.equalTo(property.buttonHeight + property.splitWidth) make.width.equalTo(btnContrainerView).offset(property.splitWidth*2) if tmpIndex == 0 { make.top.equalToSuperview() lastBtn = btn } else if tmpIndex > 0 && tmpIndex < self.actionItemArray.count - 1 { make.top.equalTo(lastBtn.snp.bottom).offset(-self.vProperty.splitWidth) lastBtn = btn } } // ๆŒ‰้’ฎๆ ‡้ข˜ btn.setTitle(popupItem.title, for: .normal) // ๆŒ‰้’ฎๆ ‡้ข˜ๅญ—ไฝ“้ขœ่‰ฒ if popupItem.itemTitleColor != nil { btn.setTitleColor(popupItem.itemTitleColor, for: .normal) } else { btn.setTitleColor(popupItem.highlight ? self.vProperty.itemHighlightColor : self.vProperty.itemNormalColor, for: .normal) } // ๆŒ‰้’ฎๆ ‡้ข˜ๅญ—ไฝ“ๅคงๅฐ if popupItem.itemTitleFont != nil { btn.titleLabel?.font = popupItem.itemTitleFont } else { btn.titleLabel?.font = (self.vProperty.buttonFont != nil) ? self.vProperty.buttonFont! : UIFont.systemFont(ofSize: self.vProperty.buttonFontSize) } // ๆŒ‰้’ฎ่ƒŒๆ™ฏ้ขœ่‰ฒ if popupItem.itemBackgroundColor != nil { btn.setBackgroundImage(self.getImageWithColor(color: popupItem.itemBackgroundColor!), for: .normal) } else { btn.setBackgroundImage(self.getImageWithColor(color: UIColor.white), for: .normal) } // ๆŒ‰้’ฎ้€‰ไธญ้ซ˜ไบฎ้ขœ่‰ฒ btn.setBackgroundImage(self.getImageWithColor(color: self.vProperty.itemPressedColor), for: .highlighted) btn.layer.borderWidth = self.vProperty.splitWidth btn.layer.borderColor = self.vProperty.splitColor.cgColor tmpIndex += 1 } btnContrainerView.snp.makeConstraints { (make) in var tmpHeight: CGFloat = property.buttonHeight * CGFloat(self.actionItemArray.count-1) if self.vProperty.popupViewMaxHeightRate > 0 && self.superview != nil && self.superview!.frame.height > 0 { tmpHeight = min(tmpHeight, self.superview!.frame.height * self.vProperty.popupViewMaxHeightRate) } make.height.equalTo(tmpHeight) make.bottom.equalTo(lastBtn.snp.bottom).offset(-self.vProperty.splitWidth) } cancelBtn.snp.makeConstraints { (make) in make.top.equalTo(btnContrainerView.snp.bottom).offset(property.cancelBtnMarginTop) } self.snp.makeConstraints { (make) in make.left.right.equalToSuperview() if #available(iOS 11.0, *) { make.bottom.equalTo(cancelBtn.snp.bottom).inset(-FWPopupWindow.sharedInstance.safeAreaInsets.bottom) } else { make.bottom.equalTo(cancelBtn.snp.bottom) } } } } extension FWSheetView { @objc private func btnAction(_ sender: Any) { let btn = sender as! UIButton let item = self.actionItemArray[btn.tag] if item.disabled { return } if item.canAutoHide { self.hide() } if item.itemClickedBlock != nil { item.itemClickedBlock!(self, btn.tag, item.title) } } } /// FWSheetView็š„็›ธๅ…ณๅฑžๆ€ง๏ผŒ่ฏทๆณจๆ„ๅ…ถ็ˆถ็ฑปไธญ่ฟ˜ๆœ‰ๅพˆๅคšๅ…ฌๅ…ฑๅฑžๆ€ง open class FWSheetViewProperty: FWPopupViewProperty { // ๅ–ๆถˆๆŒ‰้’ฎ่ท็ฆปๅคด้ƒจ็š„่ท็ฆป @objc public var cancelBtnMarginTop: CGFloat = 6 // ๅ–ๆถˆๆŒ‰้’ฎๅ็งฐ @objc public var cancelItemTitle = "ๅ–ๆถˆ" // ๅ–ๆถˆๆŒ‰้’ฎๅญ—ไฝ“้ขœ่‰ฒ @objc public var cancelItemTitleColor: UIColor? // ๅ–ๆถˆๆŒ‰้’ฎๅญ—ไฝ“ๅคงๅฐ @objc public var cancelItemTitleFont: UIFont? // ๅ–ๆถˆๆŒ‰้’ฎ่ƒŒๆ™ฏ้ขœ่‰ฒ @objc public var cancelItemBackgroundColor: UIColor? public override func reSetParams() { super.reSetParams() self.backgroundColor = kPV_RGBA(r: 230, g: 230, b: 230, a: 1) } }
lgpl-2.1
8db934b6073f2065bbfae1d79217480a
37.621429
355
0.627705
4.259157
false
false
false
false
zype/ZypeAppleTVBase
ZypeAppleTVBase/Models/ThumbnailModel.swift
1
976
// // ThumbnailModel.swift // Zype // // Created by Ilya Sorokin on 10/21/15. // Copyright ยฉ 2015 Eugene Lizhnyk. All rights reserved. // import UIKit public enum LayoutOrientation: String { case landscape = "landscape", poster = "poster", square = "square" public init(rawValue: String) { switch rawValue { case "landscape": self = .landscape case "poster": self = .poster case "square": self = .square default: self = .landscape } } } open class ThumbnailModel: NSObject { public let height: Int public let width: Int public let imageURL: String public let name: String public let layout: LayoutOrientation? init(height: Int, width: Int, url:String, name: String, layout: LayoutOrientation?) { self.height = height self.width = width self.imageURL = url self.name = name self.layout = layout super.init() } }
mit
dfce74ba9434ab59ce9e580c0a695a1b
22.214286
89
0.608205
4.079498
false
false
false
false
Jackysonglanlan/Scripts
swift/xunyou_accelerator/Sources/src/constants/AppConst.swift
1
1906
// // AppConstants.swift // xunyou-accelerator // // Created by jackysong on 2018/12/10. // Copyright ยฉ 2018 xunyou.com. All rights reserved. // import Foundation extension K{ struct App { public static let version: String = { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String }() public static let fullVersion: String = { return "\(App.version) Build \(App.build)" }() public static let build: String = { return Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String }() public static let countryCode: String = { return (Locale.current as NSLocale).object(forKey: NSLocale.Key.countryCode) as? String ?? "US" }() public static let languageCode: String = { return (Locale.current as NSLocale).object(forKey: NSLocale.Key.languageCode) as? String ?? "en" }() public static let appName: String = { return Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? "NOT SET" }() public static let bundleName: String = { return Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String }() public static let isTestFlight: Bool = { return isAppStoreReceiptSandbox && !hasEmbeddedMobileProvision }() public static let isAppStore: Bool = { if isAppStoreReceiptSandbox || hasEmbeddedMobileProvision { return false } return true }() private static var isAppStoreReceiptSandbox: Bool { let b = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" debug("isAppStoreReceiptSandbox: \(b)") return b } private static var hasEmbeddedMobileProvision: Bool { let b = Bundle.main.path(forResource: "embedded", ofType: "mobileprovision") != nil debug("hasEmbeddedMobileProvision: \(b)") return b } } }
unlicense
1fba89bb1917c38de8eef08b97ebefda
27.432836
102
0.671391
4.419954
false
false
false
false
jonnguy/HSTracker
HSTracker/UIs/Preferences/OpponentTrackersPreferences.swift
2
4913
// // TrackersPreferences.swift // HSTracker // // Created by Benjamin Michotte on 29/02/16. // Copyright ยฉ 2016 Benjamin Michotte. All rights reserved. // import Foundation import MASPreferences class OpponentTrackersPreferences: NSViewController { @IBOutlet weak var showOpponentTracker: NSButton! @IBOutlet weak var showCardHuds: NSButton! @IBOutlet weak var clearTrackersOnGameEnd: NSButton! @IBOutlet weak var showOpponentCardCount: NSButton! @IBOutlet weak var showOpponentDrawChance: NSButton! @IBOutlet weak var showCthunCounter: NSButton! @IBOutlet weak var showSpellCounter: NSButton! @IBOutlet weak var includeCreated: NSButton! @IBOutlet weak var showDeathrattleCounter: NSButton! @IBOutlet weak var showPlayerClass: NSButton! @IBOutlet weak var showBoardDamage: NSButton! @IBOutlet weak var showGraveyard: NSButton! @IBOutlet weak var showGraveyardDetails: NSButton! @IBOutlet weak var showJadeCounter: NSButton! @IBOutlet weak var preventOpponentNameCovering: NSButton! override func viewDidLoad() { super.viewDidLoad() showOpponentTracker.state = Settings.showOpponentTracker ? .on : .off showCardHuds.state = Settings.showCardHuds ? .on : .off clearTrackersOnGameEnd.state = Settings.clearTrackersOnGameEnd ? .on : .off showOpponentCardCount.state = Settings.showOpponentCardCount ? .on : .off showOpponentDrawChance.state = Settings.showOpponentDrawChance ? .on : .off showCthunCounter.state = Settings.showOpponentCthun ? .on : .off showSpellCounter.state = Settings.showOpponentSpell ? .on : .off includeCreated.state = Settings.showOpponentCreated ? .on : .off showDeathrattleCounter.state = Settings.showOpponentDeathrattle ? .on : .off showPlayerClass.state = Settings.showOpponentClassInTracker ? .on : .off showBoardDamage.state = Settings.opponentBoardDamage ? .on : .off showGraveyard.state = Settings.showOpponentGraveyard ? .on : .off showGraveyardDetails.state = Settings.showOpponentGraveyardDetails ? .on : .off showGraveyardDetails.isEnabled = showGraveyard.state == .on showJadeCounter.state = Settings.showOpponentJadeCounter ? .on : .off preventOpponentNameCovering.state = Settings.preventOpponentNameCovering ? .on : .off } @IBAction func checkboxClicked(_ sender: NSButton) { if sender == showOpponentTracker { Settings.showOpponentTracker = showOpponentTracker.state == .on } else if sender == showCardHuds { Settings.showCardHuds = showCardHuds.state == .on } else if sender == clearTrackersOnGameEnd { Settings.clearTrackersOnGameEnd = clearTrackersOnGameEnd.state == .on } else if sender == showOpponentCardCount { Settings.showOpponentCardCount = showOpponentCardCount.state == .on } else if sender == showOpponentDrawChance { Settings.showOpponentDrawChance = showOpponentDrawChance.state == .on } else if sender == showCthunCounter { Settings.showOpponentCthun = showCthunCounter.state == .on } else if sender == showSpellCounter { Settings.showOpponentSpell = showSpellCounter.state == .on } else if sender == includeCreated { Settings.showOpponentCreated = includeCreated.state == .on } else if sender == showDeathrattleCounter { Settings.showOpponentDeathrattle = showDeathrattleCounter.state == .on } else if sender == showPlayerClass { Settings.showOpponentClassInTracker = showPlayerClass.state == .on } else if sender == showBoardDamage { Settings.opponentBoardDamage = showBoardDamage.state == .on } else if sender == showGraveyard { Settings.showOpponentGraveyard = showGraveyard.state == .on if showGraveyard.state == .on { showGraveyardDetails.isEnabled = true } else { showGraveyardDetails.isEnabled = false } } else if sender == showGraveyardDetails { Settings.showOpponentGraveyardDetails = showGraveyardDetails.state == .on } else if sender == showJadeCounter { Settings.showOpponentJadeCounter = showJadeCounter.state == .on } else if sender == preventOpponentNameCovering { Settings.preventOpponentNameCovering = preventOpponentNameCovering.state == .on } } } // MARK: - MASPreferencesViewController extension OpponentTrackersPreferences: MASPreferencesViewController { var viewIdentifier: String { return "opponent_trackers" } var toolbarItemImage: NSImage? { return NSImage(named: NSImage.Name.advanced) } var toolbarItemLabel: String? { return NSLocalizedString("Opponent tracker", comment: "") } }
mit
12d547c6fa4cad77c46be29882b3de02
46.68932
93
0.69544
5.219979
false
false
false
false
Suninus/SwiftStructures
Source/Factories/Stack.swift
10
2706
// // Stack.swift // SwiftStructures // // Created by Wayne Bishop on 8/1/14. // Copyright (c) 2014 Arbutus Software Inc. All rights reserved. // import Foundation class SwiftStack<T> { private var top: LLNode<T>! = LLNode<T>() //TODO: Convert count method to computed property //push an item onto the stack func push(var key: T) { //check for the instance if (top == nil) { top = LLNode<T>() } //determine if the head node is populated if (top.key == nil){ top.key = key; return } else { //establish the new item instance var childToUse: LLNode<T> = LLNode<T>() childToUse.key = key //set newly created item at the top childToUse.next = top; top = childToUse; } } //remove an item from the stack func pop() -> T? { //determine if the key or instance exist let topitem: T? = self.top?.key if (topitem == nil){ return nil } //retrieve and queue the next item var queueitem: T? = top.key! //reset the top value if let nextitem = top.next { top = nextitem } else { top = nil } return queueitem } //retrieve the top most item func peek() -> T? { //determine if the key or instance exist if let topitem: T = self.top?.key { return topitem } else { return nil } } //check for the presence of a value func isEmpty() -> Bool { //determine if the key or instance exist if let topitem: T = self.top?.key { return false } else { return true } } //determine the count of the queue func count() -> Int { var x: Int = 0 //determine if the key or instance exist let topitem: T? = self.top?.key if (topitem == nil) { return 0 } var current: LLNode = top x++ //cycle through the list of items to get to the end. while ((current.next) != nil) { current = current.next!; x++ } return x } }
mit
376b91830597fed9b973e383f00be93c
17.798611
65
0.422764
5.048507
false
false
false
false
drahot/BSImagePicker
Pod/Classes/Model/PhotoCollectionViewDataSource.swift
3
4179
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllstrรถm // // 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 /** Gives UICollectionViewDataSource functionality with a given data source and cell factory */ final class PhotoCollectionViewDataSource : NSObject, UICollectionViewDataSource { var selections = [PHAsset]() var fetchResult: PHFetchResult<PHAsset> fileprivate let photoCellIdentifier = "photoCellIdentifier" fileprivate let photosManager = PHCachingImageManager.default() fileprivate let imageContentMode: PHImageContentMode = .aspectFill let settings: BSImagePickerSettings? var imageSize: CGSize = CGSize.zero init(fetchResult: PHFetchResult<PHAsset>, selections: PHFetchResult<PHAsset>? = nil, settings: BSImagePickerSettings?) { self.fetchResult = fetchResult self.settings = settings if let selections = selections { var selectionsArray = [PHAsset]() selections.enumerateObjects({ (asset, idx, stop) in selectionsArray.append(asset) }) self.selections = selectionsArray } super.init() } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return fetchResult.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { UIView.setAnimationsEnabled(false) let cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoCellIdentifier, for: indexPath) as! PhotoCell cell.accessibilityIdentifier = "photo_cell_\(indexPath.item)" if let settings = settings { cell.settings = settings } // Cancel any pending image requests if cell.tag != 0 { photosManager.cancelImageRequest(PHImageRequestID(cell.tag)) } let asset = fetchResult[indexPath.row] cell.asset = asset // Request image cell.tag = Int(photosManager.requestImage(for: asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in cell.imageView.image = result }) // Set selection number if let index = selections.index(of: asset) { if let character = settings?.selectionCharacter { cell.selectionString = String(character) } else { cell.selectionString = String(index+1) } cell.photoSelected = true } else { cell.photoSelected = false } UIView.setAnimationsEnabled(true) return cell } func registerCellIdentifiersForCollectionView(_ collectionView: UICollectionView?) { collectionView?.register(UINib(nibName: "PhotoCell", bundle: BSImagePickerViewController.bundle), forCellWithReuseIdentifier: photoCellIdentifier) } }
mit
1dfa753d242683e0f88601966df4d427
38.790476
154
0.679033
5.411917
false
false
false
false
TurfDb/Turf
Turf/ChangeSet/CacheUpdates.swift
1
3012
internal final class CacheUpdates<Key: Hashable, Value>: TypeErasedCacheUpdates { // MARK: Private properties fileprivate var valueUpdates: [Key: Value] = [:] fileprivate var removedKeys: Set<Key> = [] fileprivate var allValuesRemoved = false // MARK: Internal methods func recordValue(_ value: Value, upsertedWithKey key: Key) { valueUpdates[key] = value removedKeys.remove(key) } func recordValueRemovedWithKey(_ key: Key) { valueUpdates.removeValue(forKey: key) removedKeys.insert(key) } func recordAllValuesRemoved() { valueUpdates.removeAll() removedKeys.removeAll() allValuesRemoved = true } func resetUpdates() { valueUpdates.removeAll(keepingCapacity: true) removedKeys.removeAll(keepingCapacity: true) allValuesRemoved = false } func mergeCacheUpdatesFrom(_ otherUpdates: CacheUpdates<Key, Value>) { if otherUpdates.allValuesRemoved { valueUpdates.removeAll(keepingCapacity: true) removedKeys.removeAll(keepingCapacity: true) allValuesRemoved = true for (key, value) in otherUpdates.valueUpdates { valueUpdates[key] = value } } else { for removedKey in otherUpdates.removedKeys { recordValueRemovedWithKey(removedKey) } for (key, value) in otherUpdates.valueUpdates { recordValue(value, upsertedWithKey: key) } } } func applyUpdatesToCache(_ cache: Cache<Key, Value>) { if allValuesRemoved { cache.removeAllValues() for (key, value) in valueUpdates { cache.seValue(value, forKey: key) } } else { for (key, value) in valueUpdates { if cache.hasKey(key) { cache.seValue(value, forKey: key) } } } } func copy() -> CacheUpdates<Key, Value> { let cacheUpdates = CacheUpdates() cacheUpdates.valueUpdates = self.valueUpdates cacheUpdates.removedKeys = self.removedKeys cacheUpdates.allValuesRemoved = self.allValuesRemoved return cacheUpdates } } extension CacheUpdates: CustomDebugStringConvertible { var debugDescription: String { var description = "" if valueUpdates.count == 0 && removedKeys.count == 0 && allValuesRemoved == false { description = "No cache updates" } else { description = "Value updates:\n" for (key, _) in valueUpdates { description += "\t\(key)\n" } description += "Removed keys:\n" for key in removedKeys { description += "\t\(key)\n" } description += "All keys removed: \(allValuesRemoved)\n" } return description } } internal protocol TypeErasedCacheUpdates { }
mit
7c2a0e6cc03a5f7ceb984029baffc1af
29.12
91
0.585989
4.873786
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/Localize/PXLanguages.swift
1
882
import Foundation /** We use PXLanguages raw string values. `WARNING:` - This is an method not intended for public use. Only for reference. - It is not considered part of the public API. - warning: Use this enum only for reference. Donยดt use it. */ public enum PXLanguages: String { /** SPANISH - This is our default value. */ case SPANISH = "es" /** MEXICO */ case SPANISH_MEXICO = "es-MX" /** COLOMBIA */ case SPANISH_COLOMBIA = "es-CO" /** URUGUAY */ case SPANISH_URUGUAY = "es-UY" /** PERU */ case SPANISH_PERU = "es-PE" /** VENEZUELA */ case SPANISH_VENEZUELA = "es-VE" /** PORTUGUESE pt */ case PORTUGUESE = "pt" /** PORTUGUESE Brazil */ case PORTUGUESE_BRAZIL = "pt-BR" /** ENGLISH */ case ENGLISH = "en" }
mit
f2c98f72035e39584e4e44fa7aa511b8
18.152174
69
0.549376
3.017123
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Scene/EnvironmentState.swift
1
1065
// // EnvironmentState.swift // CesiumKit // // Created by Ryan Walklin on 1/05/2016. // Copyright ยฉ 2016 Test Toast. All rights reserved. // import Foundation // Keeps track of the state of a frame. FrameState is the state across // the primitives of the scene. This state is for internally keeping track // of celestial and environment effects that need to be updated/rendered in // a certain order as well as updating/tracking framebuffer usage. struct EnvironmentState { var skyBoxCommand: DrawCommand! = nil var skyAtmosphereCommand: DrawCommand! = nil var sunDrawCommand: DrawCommand! = nil var sunComputeCommand: ComputeCommand! = nil var moonCommand: DrawCommand! = nil var isSunVisible: Bool = false var isMoonVisible: Bool = false var isSkyAtmosphereVisible: Bool = false var clearGlobeDepth: Bool = false var useDepthPlane: Bool = false var originalFramebuffer: Framebuffer! = nil var useGlobeDepthFramebuffer: Bool = false var useOIT: Bool = false var useFXAA: Bool = false }
apache-2.0
7ea4477d260041d0590f8657cfa30b10
31.272727
75
0.723684
4.124031
false
false
false
false
lanjing99/iOSByTutorials
iOS 8 by tutorials/Chapter 11 - Extensions - Action/Quick-Bit-Starter/BitlyKit/BitlyShortenedUrlModel.swift
1
2392
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation public class BitlyShortenedUrlModel: NSObject, NSCoding { public let globalHash: String public let privateHash: String public var longUrl: NSURL? = nil public var shortUrl: NSURL? = nil public init(fromJSON json: JSON) { globalHash = json["data"]["global_hash"].string! privateHash = json["data"]["hash"].string! let longUrlString = json["data"]["long_url"].string! if let longUrl = NSURL(string: longUrlString) { self.longUrl = longUrl } let shortUrlString = json["data"]["url"].string! if let shortUrl = NSURL(string: shortUrlString) { self.shortUrl = shortUrl } super.init() } public required init?(coder aDecoder: NSCoder) { globalHash = aDecoder.decodeObjectForKey("globalHash") as! String privateHash = aDecoder.decodeObjectForKey("privateHash") as! String longUrl = aDecoder.decodeObjectForKey("longUrl") as? NSURL shortUrl = aDecoder.decodeObjectForKey("shortUrl") as? NSURL } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(globalHash, forKey: "globalHash") aCoder.encodeObject(privateHash, forKey: "privateHash") aCoder.encodeObject(longUrl, forKey: "longUrl") aCoder.encodeObject(shortUrl, forKey: "shortUrl") } }
mit
9bd63bedff109840ac9c88e7c9fb6397
36.390625
79
0.730351
4.413284
false
false
false
false
ryanipete/AmericanChronicle
AmericanChronicle/Code/AppWide/ServicesAndManagers/OCRCoordinatesWebService.swift
1
2747
import Alamofire import Foundation // MARK: - // MARK: OCRCoordinatesWebServiceInterface protocol OCRCoordinatesWebServiceInterface { func startRequest(_ pageID: String, contextID: String, completion: @escaping ((Swift.Result<OCRCoordinates, Error>) -> Void)) } // MARK: - // MARK: OCRCoordinatesWebService class final class OCRCoordinatesWebService: OCRCoordinatesWebServiceInterface { private let manager: SessionManagerProtocol private var activeRequests: [String: RequestProtocol] = [:] private let queue = DispatchQueue( label: "com.ryanipete.AmericanChronicle.OCRCoordinatesWebService", attributes: []) init(manager: SessionManagerProtocol = SessionManager()) { self.manager = manager } func startRequest(_ pageID: String, contextID: String, completion: @escaping ((Swift.Result<OCRCoordinates, Error>) -> Void)) { if pageID.isEmpty { let error = NSError(code: .invalidParameter, message: "Tried to fetch highlights info using an empty lccn.".localized()) completion(.failure(error)) return } if isRequestInProgressWith(pageID: pageID, contextID: contextID) { let error = NSError(code: .duplicateRequest, message: "Tried to send a duplicate request.".localized()) completion(.failure(error)) return } let signature = requestSignature(pageID: pageID, contextID: contextID) let routerRequest = Router.ocrCoordinates(pageID: pageID) let request = manager.beginRequest(routerRequest) { [weak self] response in self?.queue.sync { self?.activeRequests[signature] = nil } switch response.result { case .success(let data): let decoder = JSONDecoder() do { let result = try decoder.decode(OCRCoordinates.self, from: data) completion(.success(result)) } catch { completion(.failure(error)) } case .failure(let error): completion(.failure(error)) } } queue.sync { self.activeRequests[signature] = request } } func isRequestInProgressWith(pageID: String, contextID: String) -> Bool { activeRequests[requestSignature(pageID: pageID, contextID: contextID)] != nil } private func requestSignature(pageID: String, contextID: String) -> String { "\(pageID)-\(contextID)" } }
mit
5fb3642147fecc392a969d655135cb77
35.144737
107
0.582818
5.077634
false
false
false
false
kviksilver/Smock
Sources/Smock.swift
1
2440
// // Smock.swift // Smock // // Created by kviksilver on 04/03/2017. // Copyright (c) 2017 kviksilver. All rights reserved. // import Foundation /// Log level for Smock /// /// - quiet: no logs generated /// - verbose: logs every selector registration and return value stub setting to console public enum LogLevel { /// no logs generated case quiet /// logs every selector registration and return value stub setting to console case verbose fileprivate func log(_ string: String) { switch self { case .verbose: print(string) default: break } } } /// Entry point for library, used for setting log level public struct Smock { /// Marks log level for library public static var logLevel = LogLevel.quiet static var mocks = [String: SmockStorage]() static func registerSelectorForKey(key: String, params: [Any?], selector: Selector) { logLevel.log("##############################################################") logLevel.log("registering selector: \(selector.key())") logLevel.log("for key: \(key)") logLevel.log("with params: \(String(describing: params.debugDescription))") logLevel.log("##############################################################") guard var storage = mocks[key] else { mocks[key] = SmockStorage() return registerSelectorForKey(key: key, params: params, selector: selector) } storage.selectors[selector.key()] = (storage.selectors[selector.key()] ?? 0) + 1 storage.params[selector.key()] = params mocks[key] = storage } static func stubValueForKey(key: String, selector: Selector, value: Any?) { logLevel.log("##############################################################") logLevel.log("stubbinn value: \(value.debugDescription)") logLevel.log("for key: \(key)") logLevel.log("with selector: \(selector.key())") logLevel.log("##############################################################") guard var storage = mocks[key] else { mocks[key] = SmockStorage() return stubValueForKey(key: key, selector: selector, value:value) } storage.returnValues[selector.key()] = value mocks[key] = storage } } /// Umbrella protocol for both type and object public protocol Mock: MockedType, MockedObject {}
mit
aacbd8c0eba036cf20c90ec8c6d0ca56
31.533333
89
0.561475
4.656489
false
false
false
false
rudkx/swift
stdlib/public/core/StringComparison.swift
1
11283
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims @inlinable @inline(__always) // top-level fastest-paths @_effects(readonly) internal func _stringCompare( _ lhs: _StringGuts, _ rhs: _StringGuts, expecting: _StringComparisonResult ) -> Bool { if lhs.rawBits == rhs.rawBits { return expecting == .equal } return _stringCompareWithSmolCheck(lhs, rhs, expecting: expecting) } @usableFromInline @_effects(readonly) internal func _stringCompareWithSmolCheck( _ lhs: _StringGuts, _ rhs: _StringGuts, expecting: _StringComparisonResult ) -> Bool { // ASCII small-string fast-path: if lhs.isSmallASCII && rhs.isSmallASCII { let lhsRaw = lhs.asSmall._storage let rhsRaw = rhs.asSmall._storage if lhsRaw.0 != rhsRaw.0 { return _lexicographicalCompare( lhsRaw.0.bigEndian, rhsRaw.0.bigEndian, expecting: expecting) } return _lexicographicalCompare( lhsRaw.1.bigEndian, rhsRaw.1.bigEndian, expecting: expecting) } return _stringCompareInternal(lhs, rhs, expecting: expecting) } @inline(never) // Keep `_stringCompareWithSmolCheck` fast-path fast @usableFromInline @_effects(readonly) internal func _stringCompareInternal( _ lhs: _StringGuts, _ rhs: _StringGuts, expecting: _StringComparisonResult ) -> Bool { guard _fastPath(lhs.isFastUTF8 && rhs.isFastUTF8) else { return _stringCompareSlow(lhs, rhs, expecting: expecting) } let isNFC = lhs.isNFC && rhs.isNFC return lhs.withFastUTF8 { lhsUTF8 in return rhs.withFastUTF8 { rhsUTF8 in return _stringCompareFastUTF8( lhsUTF8, rhsUTF8, expecting: expecting, bothNFC: isNFC) } } } @inlinable @inline(__always) // top-level fastest-paths @_effects(readonly) internal func _stringCompare( _ lhs: _StringGuts, _ lhsRange: Range<Int>, _ rhs: _StringGuts, _ rhsRange: Range<Int>, expecting: _StringComparisonResult ) -> Bool { if lhs.rawBits == rhs.rawBits && lhsRange == rhsRange { return expecting == .equal } return _stringCompareInternal( lhs, lhsRange, rhs, rhsRange, expecting: expecting) } @usableFromInline @_effects(readonly) internal func _stringCompareInternal( _ lhs: _StringGuts, _ lhsRange: Range<Int>, _ rhs: _StringGuts, _ rhsRange: Range<Int>, expecting: _StringComparisonResult ) -> Bool { guard _fastPath(lhs.isFastUTF8 && rhs.isFastUTF8) else { return _stringCompareSlow( lhs, lhsRange, rhs, rhsRange, expecting: expecting) } let isNFC = lhs.isNFC && rhs.isNFC return lhs.withFastUTF8(range: lhsRange) { lhsUTF8 in return rhs.withFastUTF8(range: rhsRange) { rhsUTF8 in return _stringCompareFastUTF8( lhsUTF8, rhsUTF8, expecting: expecting, bothNFC: isNFC) } } } @_effects(readonly) private func _stringCompareFastUTF8( _ utf8Left: UnsafeBufferPointer<UInt8>, _ utf8Right: UnsafeBufferPointer<UInt8>, expecting: _StringComparisonResult, bothNFC: Bool ) -> Bool { if _fastPath(bothNFC) { /* If we know both Strings are NFC *and* we're just checking equality, then we can early-out without looking at the contents if the UTF8 counts are different (without the NFC req, equal characters can have different counts). It might be nicer to do this in _binaryCompare, but we have the information about what operation we're trying to do at this level. */ if expecting == .equal && utf8Left.count != utf8Right.count { return false } let cmp = _binaryCompare(utf8Left, utf8Right) return _lexicographicalCompare(cmp, 0, expecting: expecting) } return _stringCompareFastUTF8Abnormal( utf8Left, utf8Right, expecting: expecting) } @_effects(readonly) private func _stringCompareFastUTF8Abnormal( _ utf8Left: UnsafeBufferPointer<UInt8>, _ utf8Right: UnsafeBufferPointer<UInt8>, expecting: _StringComparisonResult ) -> Bool { // Do a binary-equality prefix scan, to skip over long common prefixes. guard let diffIdx = _findDiffIdx(utf8Left, utf8Right) else { // We finished one of our inputs. // // TODO: This gives us a consistent and good ordering, but technically it // could differ from our stated ordering if combination with a prior scalar // did not produce a greater-value scalar. Consider checking normality. return _lexicographicalCompare( utf8Left.count, utf8Right.count, expecting: expecting) } let scalarDiffIdx = _scalarAlign(utf8Left, diffIdx) _internalInvariant(scalarDiffIdx == _scalarAlign(utf8Right, diffIdx)) let (leftScalar, leftLen) = _decodeScalar(utf8Left, startingAt: scalarDiffIdx) let (rightScalar, rightLen) = _decodeScalar( utf8Right, startingAt: scalarDiffIdx) // Very frequent fast-path: point of binary divergence is a NFC single-scalar // segment. Check that we diverged at the start of a segment, and the next // scalar is both NFC and its own segment. if _fastPath( leftScalar._isNFCStarter && rightScalar._isNFCStarter && utf8Left.hasNormalizationBoundary(before: scalarDiffIdx &+ leftLen) && utf8Right.hasNormalizationBoundary(before: scalarDiffIdx &+ rightLen) ) { guard expecting == .less else { // We diverged _internalInvariant(expecting == .equal) return false } return _lexicographicalCompare( leftScalar.value, rightScalar.value, expecting: .less) } // Back up to the nearest normalization boundary before doing a slow // normalizing compare. let boundaryIdx = Swift.min( _findBoundary(utf8Left, before: diffIdx), _findBoundary(utf8Right, before: diffIdx)) _internalInvariant(boundaryIdx <= diffIdx) return _stringCompareSlow( UnsafeBufferPointer(rebasing: utf8Left[boundaryIdx...]), UnsafeBufferPointer(rebasing: utf8Right[boundaryIdx...]), expecting: expecting) } @_effects(readonly) private func _stringCompareSlow( _ lhs: _StringGuts, _ rhs: _StringGuts, expecting: _StringComparisonResult ) -> Bool { return _stringCompareSlow( lhs, 0..<lhs.count, rhs, 0..<rhs.count, expecting: expecting) } @_effects(readonly) private func _stringCompareSlow( _ lhs: _StringGuts, _ lhsRange: Range<Int>, _ rhs: _StringGuts, _ rhsRange: Range<Int>, expecting: _StringComparisonResult ) -> Bool { // TODO: Just call the normalizer directly with range return _StringGutsSlice(lhs, lhsRange).compare( with: _StringGutsSlice(rhs, rhsRange), expecting: expecting) } @_effects(readonly) private func _stringCompareSlow( _ leftUTF8: UnsafeBufferPointer<UInt8>, _ rightUTF8: UnsafeBufferPointer<UInt8>, expecting: _StringComparisonResult ) -> Bool { // TODO: Just call the normalizer directly let left = _StringGutsSlice(_StringGuts(leftUTF8, isASCII: false)) let right = _StringGutsSlice(_StringGuts(rightUTF8, isASCII: false)) return left.compare(with: right, expecting: expecting) } // Return the point of binary divergence. If they have no binary difference // (even if one is longer), returns nil. @_effects(readonly) private func _findDiffIdx( _ left: UnsafeBufferPointer<UInt8>, _ right: UnsafeBufferPointer<UInt8> ) -> Int? { let count = Swift.min(left.count, right.count) var idx = 0 while idx < count { guard left[_unchecked: idx] == right[_unchecked: idx] else { return idx } idx &+= 1 } return nil } @_effects(readonly) @inline(__always) private func _lexicographicalCompare<I: FixedWidthInteger>( _ lhs: I, _ rhs: I, expecting: _StringComparisonResult ) -> Bool { return expecting == .equal ? lhs == rhs : lhs < rhs } @_effects(readonly) private func _findBoundary( _ utf8: UnsafeBufferPointer<UInt8>, before: Int ) -> Int { var idx = before _internalInvariant(idx >= 0) // End of string is a normalization boundary guard idx < utf8.count else { _internalInvariant(before == utf8.count) return utf8.count } // Back up to scalar boundary while UTF8.isContinuation(utf8[_unchecked: idx]) { idx &-= 1 } while true { if idx == 0 { return 0 } let scalar = _decodeScalar(utf8, startingAt: idx).0 if scalar._isNFCStarter { return idx } idx &-= _utf8ScalarLength(utf8, endingAt: idx) } } @frozen @usableFromInline internal enum _StringComparisonResult { case equal case less @inlinable @inline(__always) internal init(signedNotation int: Int) { _internalInvariant(int <= 0) self = int == 0 ? .equal : .less } @inlinable @inline(__always) static func ==( _ lhs: _StringComparisonResult, _ rhs: _StringComparisonResult ) -> Bool { switch (lhs, rhs) { case (.equal, .equal): return true case (.less, .less): return true default: return false } } } // Perform a binary comparison of bytes in memory. Return value is negative if // less, 0 if equal, positive if greater. @_effects(readonly) internal func _binaryCompare<UInt8>( _ lhs: UnsafeBufferPointer<UInt8>, _ rhs: UnsafeBufferPointer<UInt8> ) -> Int { var cmp = Int(truncatingIfNeeded: _swift_stdlib_memcmp( lhs.baseAddress._unsafelyUnwrappedUnchecked, rhs.baseAddress._unsafelyUnwrappedUnchecked, Swift.min(lhs.count, rhs.count))) if cmp == 0 { cmp = lhs.count &- rhs.count } return cmp } // Double dispatch functions extension _StringGutsSlice { @_effects(readonly) internal func compare( with other: _StringGutsSlice, expecting: _StringComparisonResult ) -> Bool { if _fastPath(self.isFastUTF8 && other.isFastUTF8) { Builtin.onFastPath() // aggressively inline / optimize let isEqual = self.withFastUTF8 { utf8Self in return other.withFastUTF8 { utf8Other in return 0 == _binaryCompare(utf8Self, utf8Other) } } if isEqual { return expecting == .equal } } return _slowCompare(with: other, expecting: expecting) } @inline(never) // opaque slow-path @_effects(readonly) internal func _slowCompare( with other: _StringGutsSlice, expecting: _StringComparisonResult ) -> Bool { var iter1 = Substring(self)._nfc.makeIterator() var iter2 = Substring(other)._nfc.makeIterator() var scalar1: Unicode.Scalar? = nil var scalar2: Unicode.Scalar? = nil while true { scalar1 = iter1.next() scalar2 = iter2.next() if scalar1 == nil || scalar2 == nil { break } if scalar1 == scalar2 { continue } if scalar1! < scalar2! { return expecting == .less } else { return false } } // If both of them ran out of scalars, then these are completely equal. if scalar1 == nil, scalar2 == nil { return expecting == .equal } // Otherwise, one of these strings has more scalars, so the one with less // scalars is considered "less" than. if end < other.end { return expecting == .less } return false } }
apache-2.0
6ffb3b13b710e1abd7908aff001ac04c
29.168449
80
0.682443
3.919069
false
false
false
false
fancymax/12306ForMac
12306ForMac/Service/Service+QueryOrder.swift
1
9906
// // Service+QueryOrder.swift // Train12306 // // Created by fancymax on 16/2/16. // Copyright ยฉ 2016ๅนด fancy. All rights reserved. // import Foundation import Alamofire import PromiseKit import SwiftyJSON extension Service{ // MARK: - Request Flow func queryHistoryOrderFlow(success:@escaping ()->Void, failure:@escaping (NSError)->Void){ self.queryOrderInit().then{()->Promise<Int> in MainModel.historyOrderList.removeAll() return self.queryMyOrderWithPageIndex(0) }.then{totalNum ->Promise<Int> in let index = 1 if (totalNum - 1)/8 > index { return self.queryMyOrderWithPageIndex(index) } else { return Promise{fulfill, reject in fulfill(index)} } }.then{totalNum ->Promise<Int> in let index = 2 if (totalNum - 1)/8 > index { return self.queryMyOrderWithPageIndex(index) } else { return Promise{fulfill, reject in fulfill(index)} } }.then{totalNum ->Promise<Int> in let index = 3 if (totalNum - 1)/8 > index { return self.queryMyOrderWithPageIndex(index) } else { return Promise{fulfill, reject in fulfill(index)} } }.then{totalNum ->Promise<Int> in let index = 4 if (totalNum - 1)/8 > index { return self.queryMyOrderWithPageIndex(index) } else { return Promise{fulfill, reject in fulfill(index)} } }.then{totalNum ->Promise<Int> in let index = 5 if (totalNum - 1)/8 > index { return self.queryMyOrderWithPageIndex(index) } else { return Promise{fulfill, reject in fulfill(2)} } }.then{_ in success() }.catch{error in failure(error as NSError) } } func queryNoCompleteOrderFlow(success:@escaping ()->Void, failure:@escaping ()->Void){ self.queryOrderInitNoComplete().then{() -> Promise<Void> in return self.queryMyOrderNoComplete() }.then{_ in success() }.catch {_ in failure() } } func payFlow(success:@escaping (_ request:URLRequest)->Void, failure:@escaping (NSError)->Void) { self.queryOrderInitNoComplete().then{() -> Promise<Void> in return self.queryMyOrderNoComplete() }.then{() -> Promise<Void> in return self.continuePayNoCompleteMyOrder() }.then{() -> Promise<Void> in return self.payOrderInit() }.then{()->Promise<URLRequest> in return self.paycheckNew() }.then{request in success(request) }.catch {error in failure(error as NSError) } } // MARK: - Chainable Request func queryOrderInit()->Promise<Void>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/queryOrder/init" let params = ["_json_att":""] let headers = ["refer": "https://kyfw.12306.cn/otn/index/initMy12306"] Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseJSON(completionHandler:{response in fulfill() }) } } func queryMyOrderWithPageIndex(_ index:Int)->Promise<Int>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/queryOrder/queryMyOrder" var params = QueryOrderParam() params.pageIndex = index let headers = ["refer": "https://kyfw.12306.cn/otn/queryOrder/init"] Service.Manager.request(url, method:.post, parameters: params.ToPostParams(), headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): let jsonData = JSON(data)["data"] let orderDBList = jsonData["OrderDTODataList"] guard orderDBList.count > 0 else { let error = ServiceError.errorWithCode(.zeroOrderFailed) reject(error) return } let total = jsonData["order_total_number"].string for i in 0..<orderDBList.count { let ticketNum = orderDBList[i]["tickets"].count for y in 0..<ticketNum { MainModel.historyOrderList.append(OrderDTO(json: orderDBList[i], ticketIdx: y)) } } fulfill(Int(total!)!) }}) } } func queryOrderInitNoComplete()->Promise<Void>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/queryOrder/initNoComplete" let params = ["_json_att":""] let headers = ["refer": "https://kyfw.12306.cn/otn/index/initMy12306"] Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseString(completionHandler:{response in fulfill() }) } } func queryMyOrderNoComplete()->Promise<Void>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/queryOrder/queryMyOrderNoComplete" let params = ["_json_att":""] let headers = ["refer": "https://kyfw.12306.cn/otn/queryOrder/initNoComplete"] Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): let orderDBList = JSON(data)["data"]["orderDBList"] MainModel.noCompleteOrderList = [OrderDTO]() if orderDBList.count > 0{ for i in 0..<orderDBList.count { MainModel.orderId = orderDBList[i]["sequence_no"].string let ticketNum = orderDBList[i]["tickets"].count for y in 0..<ticketNum { let ticketOrder = OrderDTO(json: orderDBList[i], ticketIdx: y) MainModel.noCompleteOrderList.append(ticketOrder) } } } fulfill() }}) } } func continuePayNoCompleteMyOrder()->Promise<Void>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/queryOrder/continuePayNoCompleteMyOrder" let params = ["sequence_no":"\(MainModel.orderId!)", "pay_flag":"pay", "_json_att":""] print(params) let headers = ["refer": "https://kyfw.12306.cn/otn/queryOrder/initNoComplete"] Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseJSON(completionHandler:{response in print(response) fulfill() }) } } func payOrderInit()->Promise<Void>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/payOrder/init" let params = ["_json_att":""] let headers = ["refer": "https://kyfw.12306.cn/otn/queryOrder/initNoComplete"] Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseString(completionHandler:{response in fulfill() }) } } func paycheckNew()->Promise<URLRequest>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/payOrder/paycheckNew" let params = PaycheckNewParam().ToPostParams() let headers = ["refer": "https://kyfw.12306.cn/otn/queryOrder/initNoComplete"] Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): let json = JSON(data)["data"] print(json) if let flag = json["flag"].bool { if flag { //make the request let urlStr = "https://epay.12306.cn/pay/payGateway" let headers = ["refer": "https://kyfw.12306.cn/otn/payOrder/init"] let params = ["json_att":"", "interfaceName":"PAY_SERVLET", "interfaceVersion":"PAY_SERVLET", "tranData":json["payForm"]["tranData"].string!, "merSignMsg":json["payForm"]["merSignMsg"].string!, "appId":"0001", "transType":"01" ] let request = Alamofire.request(urlStr, method: .post, parameters:params, headers: headers).request fulfill(request!) } } }}) } } }
mit
8e88f39782c2236b20b8c202fb7509ee
40.609244
150
0.50722
4.767935
false
false
false
false
ahoppen/swift
stdlib/public/core/StringIndexValidation.swift
1
14743
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 // //===----------------------------------------------------------------------===// // Index validation extension _StringGuts { @_alwaysEmitIntoClient @inline(__always) internal func isFastScalarIndex(_ i: String.Index) -> Bool { hasMatchingEncoding(i) && i._isScalarAligned } @_alwaysEmitIntoClient @inline(__always) internal func isFastCharacterIndex(_ i: String.Index) -> Bool { hasMatchingEncoding(i) && i._isCharacterAligned } } // Subscalar index validation (UTF-8 & UTF-16 views) extension _StringGuts { @_alwaysEmitIntoClient internal func validateSubscalarIndex(_ i: String.Index) -> String.Index { let i = ensureMatchingEncoding(i) _precondition(i._encodedOffset < count, "String index is out of bounds") return i } @_alwaysEmitIntoClient internal func validateSubscalarIndex( _ i: String.Index, in bounds: Range<String.Index> ) -> String.Index { _internalInvariant(bounds.upperBound <= endIndex) let i = ensureMatchingEncoding(i) _precondition(i >= bounds.lowerBound && i < bounds.upperBound, "Substring index is out of bounds") return i } @_alwaysEmitIntoClient internal func validateInclusiveSubscalarIndex( _ i: String.Index ) -> String.Index { let i = ensureMatchingEncoding(i) _precondition(i._encodedOffset <= count, "String index is out of bounds") return i } internal func validateInclusiveSubscalarIndex( _ i: String.Index, in bounds: Range<String.Index> ) -> String.Index { _internalInvariant(bounds.upperBound <= endIndex) let i = ensureMatchingEncoding(i) _precondition(i >= bounds.lowerBound && i <= bounds.upperBound, "Substring index is out of bounds") return i } @_alwaysEmitIntoClient internal func validateSubscalarRange( _ range: Range<String.Index> ) -> Range<String.Index> { let upper = ensureMatchingEncoding(range.upperBound) let lower = ensureMatchingEncoding(range.lowerBound) // Note: if only `lower` was miscoded, then the range invariant `lower <= // upper` may no longer hold after the above conversions, so we need to // re-check it here. _precondition(upper <= endIndex && lower <= upper, "String index range is out of bounds") return Range(_uncheckedBounds: (lower, upper)) } @_alwaysEmitIntoClient internal func validateSubscalarRange( _ range: Range<String.Index>, in bounds: Range<String.Index> ) -> Range<String.Index> { _internalInvariant(bounds.upperBound <= endIndex) let upper = ensureMatchingEncoding(range.upperBound) let lower = ensureMatchingEncoding(range.lowerBound) // Note: if only `lower` was miscoded, then the range invariant `lower <= // upper` may no longer hold after the above conversions, so we need to // re-check it here. _precondition( lower >= bounds.lowerBound && lower <= upper && upper <= bounds.upperBound, "Substring index range is out of bounds") return Range(_uncheckedBounds: (lower, upper)) } } // Scalar index validation (Unicode scalar views) extension _StringGuts { /// Validate `i` and adjust its position toward the start, returning the /// resulting index or trapping as appropriate. If this function returns, then /// the returned value /// /// - has an encoding that matches this string, /// - is within the bounds of this string, and /// - is aligned on a scalar boundary. @_alwaysEmitIntoClient internal func validateScalarIndex(_ i: String.Index) -> String.Index { if isFastScalarIndex(i) { _precondition(i._encodedOffset < count, "String index is out of bounds") return i } return scalarAlign(validateSubscalarIndex(i)) } /// Validate `i` and adjust its position toward the start, returning the /// resulting index or trapping as appropriate. If this function returns, then /// the returned value /// /// - has an encoding that matches this string, /// - is within `start ..< end`, and /// - is aligned on a scalar boundary. @_alwaysEmitIntoClient internal func validateScalarIndex( _ i: String.Index, in bounds: Range<String.Index> ) -> String.Index { _internalInvariant(bounds.upperBound <= endIndex) if isFastScalarIndex(i) { _precondition(i >= bounds.lowerBound && i < bounds.upperBound, "Substring index is out of bounds") return i } return scalarAlign(validateSubscalarIndex(i, in: bounds)) } } extension _StringGuts { /// Validate `i` and adjust its position toward the start, returning the /// resulting index or trapping as appropriate. If this function returns, then /// the returned value /// /// - has an encoding that matches this string, /// - is within the bounds of this string (including the `endIndex`), and /// - is aligned on a scalar boundary. @_alwaysEmitIntoClient internal func validateInclusiveScalarIndex( _ i: String.Index ) -> String.Index { if isFastScalarIndex(i) { _precondition(i._encodedOffset <= count, "String index is out of bounds") return i } return scalarAlign(validateInclusiveSubscalarIndex(i)) } /// Validate `i` and adjust its position toward the start, returning the /// resulting index or trapping as appropriate. If this function returns, then /// the returned value /// /// - has an encoding that matches this string, /// - is within the bounds of this string (including the `endIndex`), and /// - is aligned on a scalar boundary. internal func validateInclusiveScalarIndex( _ i: String.Index, in bounds: Range<String.Index> ) -> String.Index { _internalInvariant(bounds.upperBound <= endIndex) if isFastScalarIndex(i) { _precondition(i >= bounds.lowerBound && i <= bounds.upperBound, "Substring index is out of bounds") return i } return scalarAlign(validateInclusiveSubscalarIndex(i, in: bounds)) } } extension _StringGuts { /// Validate `range` and adjust the position of its bounds, returning the /// resulting range or trapping as appropriate. If this function returns, then /// the bounds of the returned value /// /// - have an encoding that matches this string, /// - are within the bounds of this string, and /// - are aligned on a scalar boundary. internal func validateScalarRange( _ range: Range<String.Index> ) -> Range<String.Index> { if isFastScalarIndex(range.lowerBound), isFastScalarIndex(range.upperBound) { _precondition(range.upperBound._encodedOffset <= count, "String index range is out of bounds") return range } let r = validateSubscalarRange(range) return Range( _uncheckedBounds: (scalarAlign(r.lowerBound), scalarAlign(r.upperBound))) } /// Validate `range` and adjust the position of its bounds, returning the /// resulting range or trapping as appropriate. If this function returns, then /// the bounds of the returned value /// /// - have an encoding that matches this string, /// - are within `start ..< end`, and /// - are aligned on a scalar boundary. internal func validateScalarRange( _ range: Range<String.Index>, in bounds: Range<String.Index> ) -> Range<String.Index> { _internalInvariant(bounds.upperBound <= endIndex) if isFastScalarIndex(range.lowerBound), isFastScalarIndex(range.upperBound) { _precondition( range.lowerBound >= bounds.lowerBound && range.upperBound <= bounds.upperBound, "String index range is out of bounds") return range } let r = validateSubscalarRange(range, in: bounds) let upper = scalarAlign(r.upperBound) let lower = scalarAlign(r.lowerBound) return Range(_uncheckedBounds: (lower, upper)) } } // Character index validation (String & Substring) extension _StringGuts { internal func validateCharacterIndex(_ i: String.Index) -> String.Index { if isFastCharacterIndex(i) { _precondition(i._encodedOffset < count, "String index is out of bounds") return i } return roundDownToNearestCharacter(scalarAlign(validateSubscalarIndex(i))) } internal func validateCharacterIndex( _ i: String.Index, in bounds: Range<String.Index> ) -> String.Index { _internalInvariant(bounds.upperBound <= endIndex) if isFastCharacterIndex(i) { _precondition(i >= bounds.lowerBound && i < bounds.upperBound, "Substring index is out of bounds") return i } return roundDownToNearestCharacter( scalarAlign(validateSubscalarIndex(i, in: bounds)), in: bounds) } internal func validateInclusiveCharacterIndex( _ i: String.Index ) -> String.Index { if isFastCharacterIndex(i) { _precondition(i._encodedOffset <= count, "String index is out of bounds") return i } return roundDownToNearestCharacter( scalarAlign(validateInclusiveSubscalarIndex(i))) } internal func validateInclusiveCharacterIndex( _ i: String.Index, in bounds: Range<String.Index> ) -> String.Index { _internalInvariant(bounds.upperBound <= endIndex) if isFastCharacterIndex(i) { _precondition(i >= bounds.lowerBound && i <= bounds.upperBound, "Substring index is out of bounds") return i } return roundDownToNearestCharacter( scalarAlign(validateInclusiveSubscalarIndex(i, in: bounds)), in: bounds) } internal func validateCharacterRange( _ range: Range<String.Index> ) -> Range<String.Index> { if isFastCharacterIndex(range.lowerBound), isFastCharacterIndex(range.upperBound) { _precondition(range.upperBound._encodedOffset <= count, "String index range is out of bounds") return range } let r = validateSubscalarRange(range) let l = roundDownToNearestCharacter(scalarAlign(r.lowerBound)) let u = roundDownToNearestCharacter(scalarAlign(r.upperBound)) return Range(_uncheckedBounds: (l, u)) } internal func validateCharacterRange( _ range: Range<String.Index>, in bounds: Range<String.Index> ) -> Range<String.Index> { _internalInvariant(bounds.upperBound <= endIndex) if isFastCharacterIndex(range.lowerBound), isFastCharacterIndex(range.upperBound) { _precondition( range.lowerBound >= bounds.lowerBound && range.upperBound <= bounds.upperBound, "String index range is out of bounds") return range } let r = validateSubscalarRange(range, in: bounds) let l = roundDownToNearestCharacter(scalarAlign(r.lowerBound), in: bounds) let u = roundDownToNearestCharacter(scalarAlign(r.upperBound), in: bounds) return Range(_uncheckedBounds: (l, u)) } } // Temporary additions to deal with binary compatibility issues with existing // binaries that accidentally pass invalid indices to String APIs in cases that // were previously undiagnosed. // // FIXME: Remove these after a release or two. extension _StringGuts { /// A version of `validateInclusiveSubscalarIndex` that only traps if the main /// executable was linked with Swift Stdlib version 5.7 or better. This is /// used to work around binary compatibility problems with existing apps that /// pass invalid indices to String APIs. internal func validateInclusiveSubscalarIndex_5_7( _ i: String.Index ) -> String.Index { let i = ensureMatchingEncoding(i) _precondition( ifLinkedOnOrAfter: .v5_7_0, i._encodedOffset <= count, "String index is out of bounds") return i } /// A version of `validateInclusiveScalarIndex` that only traps if the main /// executable was linked with Swift Stdlib version 5.7 or better. This is /// used to work around binary compatibility problems with existing apps that /// pass invalid indices to String APIs. internal func validateInclusiveScalarIndex_5_7( _ i: String.Index ) -> String.Index { if isFastScalarIndex(i) { _precondition( ifLinkedOnOrAfter: .v5_7_0, i._encodedOffset <= count, "String index is out of bounds") return i } return scalarAlign(validateInclusiveSubscalarIndex_5_7(i)) } /// A version of `validateSubscalarRange` that only traps if the main /// executable was linked with Swift Stdlib version 5.7 or better. This is /// used to work around binary compatibility problems with existing apps that /// pass invalid indices to String APIs. internal func validateSubscalarRange_5_7( _ range: Range<String.Index> ) -> Range<String.Index> { let upper = ensureMatchingEncoding(range.upperBound) let lower = ensureMatchingEncoding(range.lowerBound) _precondition(upper <= endIndex && lower <= upper, "String index range is out of bounds") return Range(_uncheckedBounds: (lower, upper)) } /// A version of `validateScalarRange` that only traps if the main executable /// was linked with Swift Stdlib version 5.7 or better. This is used to work /// around binary compatibility problems with existing apps that pass invalid /// indices to String APIs. internal func validateScalarRange_5_7( _ range: Range<String.Index> ) -> Range<String.Index> { if isFastScalarIndex(range.lowerBound), isFastScalarIndex(range.upperBound) { _precondition( ifLinkedOnOrAfter: .v5_7_0, range.upperBound._encodedOffset <= count, "String index range is out of bounds") return range } let r = validateSubscalarRange_5_7(range) return Range( _uncheckedBounds: (scalarAlign(r.lowerBound), scalarAlign(r.upperBound))) } /// A version of `validateInclusiveCharacterIndex` that only traps if the main /// executable was linked with Swift Stdlib version 5.7 or better. This is /// used to work around binary compatibility problems with existing apps that /// pass invalid indices to String APIs. internal func validateInclusiveCharacterIndex_5_7( _ i: String.Index ) -> String.Index { if isFastCharacterIndex(i) { _precondition( ifLinkedOnOrAfter: .v5_7_0, i._encodedOffset <= count, "String index is out of bounds") return i } return roundDownToNearestCharacter( scalarAlign(validateInclusiveSubscalarIndex_5_7(i))) } }
apache-2.0
56d719d6bcb04a6f328ce0a487f74df5
32.430839
80
0.684528
4.369591
false
false
false
false
velvetroom/columbus
Source/Model/Store/MStorePerkProtocol+Status.swift
1
975
import Foundation import StoreKit extension MStorePerkProtocol { //MARK: internal mutating func statusUnavailable() { status = MStorePerkStatusUnavailable() } mutating func statusPurchasing( product:SKProduct, price:String) { status = MStorePerkStatusPurchasing( product:product, price:price) } mutating func statusPurchased( product:SKProduct, price:String) { status = MStorePerkStatusPurchased( product:product, price:price) } mutating func statusDeferred( product:SKProduct, price:String) { status = MStorePerkStatusDeferred( product:product, price:price) } mutating func statusNew( product:SKProduct, price:String) { status = MStorePerkStatusNew( product:product, price:price) } }
mit
8aaa90d45cd4176334af7e2a8076af82
19.3125
46
0.569231
4.899497
false
false
false
false
iZhang/travel-architect
main/Additional View Controllers/StatusViewController.swift
1
5231
/* See LICENSE folder for this sampleโ€™s licensing information. Abstract: Utility class for showing messages above the AR view. */ import Foundation import ARKit /** Displayed at the top of the main interface of the app that allows users to see the status of the AR experience, as well as the ability to control restarting the experience altogether. - Tag: StatusViewController */ class StatusViewController: UIViewController { // MARK: - Types enum MessageType { case trackingStateEscalation case planeEstimation case contentPlacement case focusSquare static var all: [MessageType] = [ .trackingStateEscalation, .planeEstimation, .contentPlacement, .focusSquare ] } // MARK: - IBOutlets @IBOutlet weak private var messagePanel: UIVisualEffectView! @IBOutlet weak private var messageLabel: UILabel! @IBOutlet weak private var restartExperienceButton: UIButton! // MARK: - Properties /// Trigerred when the "Restart Experience" button is tapped. var restartExperienceHandler: () -> Void = {} /// Seconds before the timer message should fade out. Adjust if the app needs longer transient messages. private let displayDuration: TimeInterval = 6 // Timer for hiding messages. private var messageHideTimer: Timer? private var timers: [MessageType: Timer] = [:] // MARK: - Message Handling func showMessage(_ text: String, autoHide: Bool = true) { // Cancel any previous hide timer. messageHideTimer?.invalidate() messageLabel.text = text // Make sure status is showing. setMessageHidden(false, animated: true) if autoHide { messageHideTimer = Timer.scheduledTimer(withTimeInterval: displayDuration, repeats: false, block: { [weak self] _ in self?.setMessageHidden(true, animated: true) }) } } func scheduleMessage(_ text: String, inSeconds seconds: TimeInterval, messageType: MessageType) { cancelScheduledMessage(for: messageType) let timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { [weak self] timer in self?.showMessage(text) timer.invalidate() }) timers[messageType] = timer } func cancelScheduledMessage(for messageType: MessageType) { timers[messageType]?.invalidate() timers[messageType] = nil } func cancelAllScheduledMessages() { for messageType in MessageType.all { cancelScheduledMessage(for: messageType) } } // MARK: - ARKit func showTrackingQualityInfo(for trackingState: ARCamera.TrackingState, autoHide: Bool) { showMessage(trackingState.presentationString, autoHide: autoHide) } func escalateFeedback(for trackingState: ARCamera.TrackingState, inSeconds seconds: TimeInterval) { cancelScheduledMessage(for: .trackingStateEscalation) let timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { [unowned self] _ in self.cancelScheduledMessage(for: .trackingStateEscalation) var message = trackingState.presentationString if let recommendation = trackingState.recommendation { message.append(": \(recommendation)") } self.showMessage(message, autoHide: false) }) timers[.trackingStateEscalation] = timer } // MARK: - IBActions @IBAction private func restartExperience(_ sender: UIButton) { restartExperienceHandler() } // MARK: - Panel Visibility private func setMessageHidden(_ hide: Bool, animated: Bool) { // The panel starts out hidden, so show it before animating opacity. messagePanel.isHidden = false guard animated else { messagePanel.alpha = hide ? 0 : 1 return } UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState], animations: { self.messagePanel.alpha = hide ? 0 : 1 }, completion: nil) } } extension ARCamera.TrackingState { var presentationString: String { switch self { case .notAvailable: return "TRACKING UNAVAILABLE" case .normal: return "TRACKING NORMAL" case .limited(.excessiveMotion): return "TRACKING LIMITED\nExcessive motion" case .limited(.insufficientFeatures): return "TRACKING LIMITED\nLow detail" case .limited(.initializing): return "Initializing" case .limited(.relocalizing): return "Recovering from interruption" } } var recommendation: String? { switch self { case .limited(.excessiveMotion): return "Try slowing down your movement, or reset the session." case .limited(.insufficientFeatures): return "Try pointing at a flat surface, or reset the session." case .limited(.relocalizing): return "Return to the location where you left off or try resetting the session." default: return nil } } }
mit
9a3ae5dea469b0dc08e3b3fc2c60e780
29.578947
128
0.649072
5.172107
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Classes/BusinessLayer/Services/DataStore/Transactions/TransactionsDataStoreService.swift
1
790
// Copyright ยฉ 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import Foundation import RealmSwift class TransactionsDataStoreService: RealmStorable<Transaction>, TransactionsDataStoreServiceProtocol { func getTransaction(txHash: String) -> Transaction? { return findOne("txHash = '\(txHash)'") } func observe(token: Token, updateHandler: @escaping ([Transaction]) -> Void) { super.observe(predicate: "tokenMeta.address = '\(token.address)'", updateHandler: updateHandler) } func markAndSaveTransactions(_ transactions: [Transaction], address: String, isNormal: Bool) { var txs = transactions for (i, tx) in txs.enumerated() { txs[i].isIncoming = tx.to == address txs[i].isNormal = isNormal } save(txs) } }
gpl-3.0
cfcfe62ea334431df1f8afba64aab3c2
28.222222
102
0.69962
4.196809
false
false
false
false
brokenhandsio/vapor-oauth
Sources/VaporOAuth/RouteHandlers/TokenHandlers/AuthCodeTokenHandler.swift
1
3058
import Vapor struct AuthCodeTokenHandler { let clientValidator: ClientValidator let tokenManager: TokenManager let codeManager: CodeManager let codeValidator = CodeValidator() let tokenResponseGenerator: TokenResponseGenerator func handleAuthCodeTokenRequest(_ request: Request) throws -> Response { guard let codeString = request.data[OAuthRequestParameters.code]?.string else { return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.invalidRequest, description: "Request was missing the 'code' parameter") } guard let redirectURI = request.data[OAuthRequestParameters.redirectURI]?.string else { return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.invalidRequest, description: "Request was missing the 'redirect_uri' parameter") } guard let clientID = request.data[OAuthRequestParameters.clientID]?.string else { return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.invalidRequest, description: "Request was missing the 'client_id' parameter") } do { try clientValidator.authenticateClient(clientID: clientID, clientSecret: request.data[OAuthRequestParameters.clientSecret]?.string, grantType: .authorization) } catch { return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.invalidClient, description: "Request had invalid client credentials", status: .unauthorized) } guard let code = codeManager.getCode(codeString), codeValidator.validateCode(code, clientID: clientID, redirectURI: redirectURI) else { let errorDescription = "The code provided was invalid or expired, or the redirect URI did not match" return try tokenResponseGenerator.createResponse(error: OAuthResponseParameters.ErrorType.invalidGrant, description: errorDescription) } codeManager.codeUsed(code) let scopes = code.scopes let expiryTime = 3600 let (access, refresh) = try tokenManager.generateAccessRefreshTokens(clientID: clientID, userID: code.userID, scopes: scopes, accessTokenExpiryTime: expiryTime) return try tokenResponseGenerator.createResponse(accessToken: access, refreshToken: refresh, expires: Int(expiryTime), scope: scopes?.joined(separator: " ")) } }
mit
da00a10b6b4c0f68eb3fc7e2594465a1
54.6
138
0.596795
6.305155
false
false
false
false
FuzzyHobbit/bitcoin-swift
BitcoinSwiftTests/NotFoundMessageTests.swift
2
1965
// // NotFoundMessageTests.swift // BitcoinSwift // // Created by James MacWhyte on 9/27/14. // Copyright (c) 2014 DoubleSha. All rights reserved. // import BitcoinSwift import XCTest class NotFoundMessageTests: XCTestCase { let notFoundMessageBytes: [UInt8] = [ 0x01, // Number of inventory vectors (1) 0x02, 0x00, 0x00, 0x00, // First vector type (2: Block) 0x71, 0x40, 0x03, 0x91, 0x50, 0x8c, 0xae, 0x45, 0x35, 0x86, 0x4f, 0x74, 0x91, 0x76, 0xab, 0x7f, 0xa3, 0xa2, 0x51, 0xc2, 0x13, 0x40, 0x21, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] // Block hash var notFoundMessageData: NSData! var notFoundMessage: NotFoundMessage! override func setUp() { super.setUp() let vector0HashBytes: [UInt8] = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x21, 0x40, 0x13, 0xc2, 0x51, 0xa2, 0xa3, 0x7f, 0xab, 0x76, 0x91, 0x74, 0x4f, 0x86, 0x35, 0x45, 0xae, 0x8c, 0x50, 0x91, 0x03, 0x40, 0x71] // Block hash let vector0Hash = SHA256Hash(bytes: vector0HashBytes) let inventoryVectors = [InventoryVector(type: .Block, hash: vector0Hash)] notFoundMessage = NotFoundMessage(inventoryVectors: inventoryVectors) notFoundMessageData = NSData(bytes: notFoundMessageBytes, length: notFoundMessageBytes.count) } // TODO: Add edge test cases: Too many vectors, empty data, etc. func testNotFoundMessageEncoding() { XCTAssertEqual(notFoundMessage.bitcoinData, notFoundMessageData) } func testNotFoundMessageDecoding() { let stream = NSInputStream(data: notFoundMessageData) stream.open() if let testNotFoundMessage = NotFoundMessage.fromBitcoinStream(stream) { XCTAssertEqual(testNotFoundMessage, notFoundMessage) } else { XCTFail("Failed to parse NotFoundMessage") } XCTAssertFalse(stream.hasBytesAvailable) stream.close() } }
apache-2.0
cf91de48a0a94778454675423a29ec9f
34.727273
97
0.66972
3.159164
false
true
false
false
jkolb/Shkadov
Sources/PlatformXCB/XCBConnection.swift
1
4136
/* The MIT License (MIT) Copyright (c) 2016 Justin Kolb 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 ShkadovXCB public final class XCBConnection { private let connection: OpaquePointer private let primaryScreenNumber: Int32 init(displayName: String?) throws { var screenNumber: Int32 = 0 guard let connection = xcb_connect(displayName, &screenNumber) else { throw XCBError.noConnection(displayName) } self.connection = connection self.primaryScreenNumber = screenNumber } deinit { xcb_disconnect(connection) } func valueList(_ values: [Int]) -> [UInt32] { return values.map({ UInt32(truncatingBitPattern: $0) }) } func generateID() -> UInt32 { return xcb_generate_id(connection) } func getFileDescriptor() -> Int32 { return xcb_get_file_descriptor(connection) } func pollForEvent() -> XCBGenericEvent? { guard let pointer = xcb_poll_for_event(connection) else { return nil } return XCBGenericEvent(pointer: pointer) } func primaryScreen() throws -> xcb_screen_t? { var iterator = xcb_setup_roots_iterator(xcb_get_setup(connection)) if iterator.rem == 0 { return nil } if primaryScreenNumber >= iterator.rem { // Return first screen return iterator.data.pointee } for _ in 0..<primaryScreenNumber { xcb_screen_next(&iterator) } return iterator.data.pointee } func screens() -> [xcb_screen_t] { var iterator = xcb_setup_roots_iterator(xcb_get_setup(connection)) var screens = [xcb_screen_t]() screens.reserveCapacity(Int(iterator.rem)) while iterator.rem > 0 { screens.append(iterator.data.pointee) xcb_screen_next(&iterator) } return screens } func createWindow(depth: UInt8, window: xcb_window_t, parent: xcb_window_t, x: Int16, y: Int16, width: UInt16, height: UInt16, borderWidth: UInt16, windowClass: UInt16, visual: xcb_visualid_t, valueMask: XCBCreateWindow, valueList: [UInt32]) throws { let cookie = xcb_create_window_checked(connection, depth, window, parent, x, y, width, height, borderWidth, windowClass, visual, valueMask.rawValue, valueList) if let errorPointer = xcb_request_check(connection, cookie) { defer { free(errorPointer) } throw XCBError.generic(errorPointer.pointee) } } func mapWindow(window: xcb_window_t) throws { let cookie = xcb_map_window_checked(connection, window) if let errorPointer = xcb_request_check(connection, cookie) { defer { free(errorPointer) } throw XCBError.generic(errorPointer.pointee) } } func configure(window: xcb_window_t, valueMask: XCBConfigWindow, valueList: [UInt32]) throws { let cookie = xcb_configure_window_checked(connection, window, valueMask.rawValue, valueList) if let errorPointer = xcb_request_check(connection, cookie) { defer { free(errorPointer) } throw XCBError.generic(errorPointer.pointee) } } func getGeometry(drawable: xcb_drawable_t) -> GetGeometry { return GetGeometry(connection: connection, drawable: drawable) } func getScreenResources(window: xcb_window_t) -> GetScreenResources { return GetScreenResources(connection: connection, window: window) } }
mit
04c596f2a50637900bbf7fa6f6108714
28.333333
251
0.737669
3.660177
false
false
false
false
inderdhir/HNReader
HNReader/CommentsViewController.swift
2
4446
// // CommentsViewController.swift // HNReader // // Created by Inder Dhir on 2/18/16. // Copyright ยฉ 2016 Inder Dhir. All rights reserved. // import UIKit import Firebase class CommentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var noInternetLabel: UILabel! @IBOutlet weak var noInternetRetryButton: UIButton! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var commentsTableView: UITableView! final let refreshControl: UIRefreshControl = UIRefreshControl() final let mainFirebaseRef = Firebase(url:"https://hacker-news.firebaseio.com/v0") final let itemsToLoadAtATime: Int = 30 final var hnItem: HNStoryItem? final var hnComments: [HNCommentItem] = [] final var newsController: NewsController? final var itemCommentCount: Int? final var currentItemsCount: Int = 0 final var currentTabSelected: Int = 0 override func viewDidLoad() { self.currentItemsCount = 0 self.itemCommentCount = hnItem?.comments?.count self.commentsTableView.delegate = self self.commentsTableView.dataSource = self self.commentsTableView.rowHeight = UITableViewAutomaticDimension self.commentsTableView.estimatedRowHeight = 140 // Pull down to refresh refreshControl.tintColor = ColorUtils.NavItemColor() refreshControl.addTarget(self, action: #selector(CommentsViewController.swipeRefreshComments), forControlEvents: UIControlEvents.ValueChanged) commentsTableView.addSubview(refreshControl) // Add infinite scroll handler commentsTableView.addInfiniteScrollWithHandler { (scrollView) -> Void in self.getComments() self.commentsTableView.reloadData() self.commentsTableView.finishInfiniteScroll() } getComments() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() self.hnComments.removeAll() } @IBAction func retryButtonClicked(sender: AnyObject) { getComments() } func swipeRefreshComments(){ getComments() self.refreshControl.endRefreshing() } private struct Storyboard { static let CellReuseIdentifier = "HNCommentItem" } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.CellReuseIdentifier, forIndexPath: indexPath) as! HNCommentTableViewCell let hnComment = self.hnComments[indexPath.row] do { let htmlText = try NSAttributedString(data: hnComment.text!.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) cell.commentTextField.attributedText = htmlText cell.commentTextField.font = cell.commentTextField.font.fontWithSize(15) } catch { cell.commentTextField.text = "" } cell.authorTextField.text = hnComment.author cell.timeTextField.text = DateTimeUtils.changeToDate(hnComment.time!) return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return hnComments.count } private func getComments(){ if(NetworkUtils.connectedToNetwork()){ spinner.hidden = false spinner.startAnimating() scrollView.hidden = false noInternetLabel.hidden = true noInternetRetryButton.hidden = true var endIndex: Int? if(currentItemsCount + itemsToLoadAtATime <= itemCommentCount){ endIndex = currentItemsCount + itemsToLoadAtATime } else{ // Comments are less than itemsToLoadAtATime or approaching end endIndex = self.itemCommentCount! } var currIndex = currentItemsCount while currIndex < endIndex! { if let hnCommentId = hnItem?.comments?[currIndex] { self.newsController!.getComment((hnItem?.id)!, hnCommentId: "\(hnCommentId)") { (hnComment: HNCommentItem) in self.hnComments.append(hnComment) self.commentsTableView.reloadData() } } currIndex = currIndex + 1 } currentItemsCount = endIndex! } else { spinner.hidden = true spinner.stopAnimating() scrollView.hidden = true noInternetLabel.hidden = false noInternetRetryButton.hidden = false } } }
apache-2.0
4bbef2eb4513f2fdbff1ac5285eebe45
31.683824
201
0.71631
4.933407
false
false
false
false
naokits/my-programming-marathon
Bluemix/bluemix-mobile-app-demo/client/HelloTodo/AppDelegate.swift
1
6343
// // AppDelegate.swift // HelloTodo // // Created by Naoki Tsutsui on 4/23/16. // Copyright ยฉ 2016 Naoki Tsutsui. All rights reserved. // import UIKit import BMSCore import BMSSecurity let logger = Logger.logger(forName: "HelloTodoLogger") @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? // PATH TO YOUR PROTECTED RESOURCE internal static let customResourceURL = "/protected2)" // private static let customRealm = "PROTECTED_RESOURCE_REALM_NAOKITS" // auth realm // private static let customRealm = "bmxdemo-custom-realm" private static let customRealm = "mca-backend-strategy" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self setupBluemix() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } // MARK: - Setups func setupBluemix() { let route = "https://BMXDemo.mybluemix.net" let guid = "1de16665-6dc3-43db-aa3a-d9aa37014ed5" let region = BMSClient.REGION_US_SOUTH BMSClient.sharedInstance.initializeWithBluemixAppRoute(route, bluemixAppGUID: guid, bluemixRegion: region) //Auth delegate for handling custom challenge class MyAuthDelegate : AuthenticationDelegate { func onAuthenticationChallengeReceived(authContext: AuthenticationContext, challenge: AnyObject) { print("onAuthenticationChallengeReceived") // Your challenge answer. Should be of type [String:AnyObject]? let challengeAnswer: [String:String] = [ "username":"naokits", "password":"12345" ] authContext.submitAuthenticationChallengeAnswer(challengeAnswer) } func onAuthenticationSuccess(info: AnyObject?) { print("onAuthenticationSuccess") } func onAuthenticationFailure(info: AnyObject?){ print("onAuthenticationFailure") } } let delegate = MyAuthDelegate() let mcaAuthManager = MCAAuthorizationManager.sharedInstance BMSClient.sharedInstance.authorizationManager = MCAAuthorizationManager.sharedInstance mcaAuthManager.registerAuthenticationDelegate(delegate, realm: AppDelegate.customRealm) // do { // try mcaAuthManager.registerAuthenticationDelegate(delegate, realm: AppDelegate.customRealm) // } catch { // print("error with register: \(error)") // } } } ////Auth delegate for handling custom challenge //class MyAuthDelegate : AuthenticationDelegate { // // // func onAuthenticationChallengeReceived(authContext: AuthenticationContext, challenge: AnyObject) { // print("onAuthenticationChallengeReceived") // // Your challenge answer. Should be of type [String:AnyObject]? // let challengeAnswer: [String:String] = [ // "username":"naokits", // "password":"12345" // ] // authContext.submitAuthenticationChallengeAnswer(challengeAnswer) // } // // func onAuthenticationSuccess(info: AnyObject?) { // print("onAuthenticationSuccess") // } // // func onAuthenticationFailure(info: AnyObject?){ // print("onAuthenticationFailure") // } //}
mit
4ee998813a2287847415388fa5c7b33e
44.3
285
0.701829
5.509991
false
false
false
false
RyanTech/Loggerithm
Source/Type.swift
1
1381
// // Type.swift // // Created by Honghao Zhang on 2015-08-13. // Copyright (c) 2015 HonghaoZ. All rights reserved. // import Foundation public enum LogLevel: Int { case All = 0 case Verbose = 1 case Debug = 2 case Info = 3 case Warning = 4 case Error = 5 case Off = 6 static public func descritionForLogLevel(logLevel: LogLevel) -> String { switch logLevel { case .Verbose: return "Verbose" case .Debug: return "Debug" case .Info: return "Info" case .Warning: return "Warning" case .Error: return "Error" default: assertionFailure("Invalid level") return "Null" } } // Be sure to set the "DEBUG" symbol. // Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" line. You add the DEBUG symbol with the -D DEBUG entry. #if DEBUG static public let defaultLevel = LogLevel.All #else static public let defaultLevel = LogLevel.Warning #endif } extension LogLevel: Comparable {} public func <(lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue < rhs.rawValue } public func <=(lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue <= rhs.rawValue } public func >=(lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue >= rhs.rawValue }
mit
062a4d4171ce85e84616ff0ae6e07e07
25.557692
137
0.613324
3.991329
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.RemoteKey.swift
1
2037
import Foundation public extension AnyCharacteristic { static func remoteKey( _ value: Enums.RemoteKey? = nil, permissions: [CharacteristicPermission] = [.write], description: String? = "Remote Key", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 16, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.remoteKey( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func remoteKey( _ value: Enums.RemoteKey? = nil, permissions: [CharacteristicPermission] = [.write], description: String? = "Remote Key", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 16, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Enums.RemoteKey?> { GenericCharacteristic<Enums.RemoteKey?>( type: .remoteKey, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
868acc31c94a9f074fab8de2a317b5ae
32.393443
66
0.575356
5.304688
false
false
false
false
ShowerLi1991/SLButtonIsDifferentFromUIButton
SLButtonDemoSwift/SLButtonDemoSwift/SLButton.swift
1
2871
import UIKit //enum UIButtonType : Int { // // case Custom // no button type // @available(iOS 7.0, *) // case System // standard system button // // case DetailDisclosure // case InfoLight // case InfoDark // case ContactAdd // // static var RoundedRect: UIButtonType { get } // Deprecated, use UIButtonTypeSystem instead //} // //@available(iOS 2.0, *) //class UIButton : UIControl { // // convenience init(type buttonType: UIButtonType) enum SLButtonType: Int { case TitleIsUnderImage = 0 case TitleIsOverImage case TitleIsLeftImage } class SLButton: UIButton { var type: SLButtonType init(type: SLButtonType) { self.type = type super.init(frame:CGRectZero) self.contentEdgeInsets = UIEdgeInsetsMake(0, -1200, 0, -1200) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() setTitleAndImageEdgeInsetsWithSLButtonType(type) } func setTitleAndImageEdgeInsetsWithSLButtonType(type: SLButtonType) { switch type { case SLButtonType.TitleIsUnderImage: imageExsitAndTetExsit({ () -> () in self.imageEdgeInsets = UIEdgeInsetsMake(0, self.titleLabel!.frame.size.width, 0, 0) }, textExsit: { () -> () in self.titleEdgeInsets = UIEdgeInsetsMake(0, -self.imageView!.image!.size.width, -self.imageView!.image!.size.height - self.titleLabel!.frame.size.height * 0.5 - 20, 0) }) case SLButtonType.TitleIsOverImage: imageExsitAndTetExsit({ () -> () in self.imageEdgeInsets = UIEdgeInsetsMake(0, self.titleLabel!.frame.size.width, 0, 0); }, textExsit: { () -> () in self.titleEdgeInsets = UIEdgeInsetsMake(0, -self.imageView!.image!.size.width, self.imageView!.image!.size.height + self.titleLabel!.frame.size.height * 0.5 + 20, 0); }) case SLButtonType.TitleIsLeftImage: imageExsitAndTetExsit({ () -> () in self.imageEdgeInsets = UIEdgeInsetsMake(0, self.frame.size.width - self.imageView!.image!.size.width, 0, 0); }, textExsit: { () -> () in self.titleEdgeInsets = UIEdgeInsetsMake(0, -self.imageView!.image!.size.width * 2, 0, 0); }) } } func imageExsitAndTetExsit(imageExsit: () -> (), textExsit: () -> ()) { if imageView?.image != nil { textExsit() } if titleLabel?.text != nil { imageExsit() } } }
mit
719428d8c250daee6e772446fb3093d0
26.342857
182
0.555556
4.356601
false
false
false
false
mattwelborn/HSTracker
HSTracker/Importers/Handlers/HearthpwnDeckBuilder.swift
1
2588
// // HearthpwnDeckBuilder.swift // HSTracker // // Created by Benjamin Michotte on 25/02/16. // Copyright ยฉ 2016 Benjamin Michotte. All rights reserved. // import Foundation import Kanna import CleanroomLogger final class HearthpwnDeckBuilder: BaseNetImporter, NetImporterAware { var siteName: String { return "HearthpPwn deckbuilder" } func handleUrl(url: String) -> Bool { return url.match("hearthpwn\\.com\\/deckbuilder") } func loadDeck(url: String, completion: Deck? -> Void) throws { loadHtml(url) { (html) -> Void in if let html = html, doc = Kanna.HTML(html: html, encoding: NSUTF8StringEncoding) { var urlParts = url.characters.split { $0 == "#" }.map(String.init) let split = urlParts[0].characters.split { $0 == "/" }.map(String.init) guard let playerClass = split.last else { completion(nil) return } var deckName = "" if let node = doc.at_xpath("//div[contains(@class,'deck-name-container')]/h2") { if let name = node.innerHTML { Log.verbose?.message("got deck name : \(name)") deckName = name } } Log.verbose?.message("\(playerClass)") let cardIds = urlParts.last?.characters.split { $0 == ";" }.map(String.init) var cards = [String: Int]() cardIds?.forEach({ (str) -> () in let split = str.characters.split(":").map(String.init) if let id = split.first, count = Int(split.last!) { if let node = doc.at_xpath("//tr[@data-id='\(id)']/td[1]/b"), cardId = node.text { Log.verbose?.message("id : \(id) count : \(count) text : \(node.text)") if let card = Cards.byEnglishName(cardId) { cards[card.id] = count } } } }) if let cardClass = CardClass(rawValue: playerClass.uppercaseString) where self.isCount(cards) { self.saveDeck(deckName, playerClass: cardClass, cards: cards, isArena: false, completion: completion) return } } completion(nil) } } }
mit
d386ca6b3973f1e2b992c0c68dc7fb12
35.957143
99
0.476614
4.627907
false
false
false
false
chiehwen/Swift3-Exercises
Youtube/Youtube/MenuBar.swift
1
2687
// // MenuBar.swift // Youtube // // Created by Chieh-Wen Yang on 25/05/2017. // Copyright ยฉ 2017 NineThreads Inc. All rights reserved. // import UIKit class MenuBar: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { let imageNames = ["home", "trending", "subscriptions", "account"] override init(frame: CGRect) { super.init(frame:frame) //backgroundColor = UIColor.red //backgroundColor = UIColor(red: 230/255, green: 31/255, blue: 32/255, alpha: 1) collectionView.backgroundColor = UIColor(red: 230/255, green: 31/255, blue: 32/255, alpha: 1) collectionView.delegate = self collectionView.dataSource = self addSubview(collectionView) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true collectionView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true collectionView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true collectionView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true collectionView.register(MenuCell.self, forCellWithReuseIdentifier: "cell") } let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 4 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MenuCell cell.thumbImage.image = UIImage(named: imageNames[indexPath.item])?.withRenderingMode(.alwaysTemplate) cell.tintColor = UIColor(red: 91/255, green: 13/255, blue: 14/255, alpha: 1) //cell.backgroundColor = UIColor.blue return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: frame.width / 4, height: frame.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
0e427baf688211480809d08d371438c3
39.69697
175
0.693969
5.437247
false
false
false
false
phimage/CallbackURLKit
Clients/GoogleChrome.swift
1
2340
// // GoogleChrome // CallbackURLKit /* The MIT License (MIT) Copyright (c) 2017 Eric Marchand (phimage) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if IMPORT import CallbackURLKit #endif import Foundation /* Google chrome client class https://developer.chrome.com/multidevice/ios/links */ public class GoogleChrome: Client { #if os(macOS) public static let DownloadURL = URL(string: "https://www.google.com/chrome/browser/desktop/index.html") #else public static let DownloadURL = URL(string: "itms-apps://itunes.apple.com/us/app/chrome/id535886823") #endif public init() { super.init(urlScheme: "googlechrome-x-callback") } /* If chrome not installed open itunes. */ public func checkInstalled() { if !self.appInstalled, let url = GoogleChrome.DownloadURL { Manager.open(url: url) } } public func open(url: String, newTab: Bool = false, onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws { var parameters = ["url": url] if newTab { parameters = ["create-new-tab": ""] } try self.perform(action: "open", parameters: parameters, onSuccess: onSuccess, onFailure: onFailure, onCancel: onCancel) } }
mit
8b9bbe143d79c40637bc2d127715fe59
36.142857
119
0.70812
4.357542
false
false
false
false
kickstarter/ios-oss
KsApi/mutations/templates/query/FetchProjectFriendsQueryTemplate.swift
1
4633
import Apollo import Foundation @testable import KsApi public enum FetchProjectFriendsQueryTemplate { case valid case errored /// `FetchProjectBySlug` returns identical data. var data: GraphAPI.FetchProjectFriendsByIdQuery.Data { switch self { case .valid: return GraphAPI.FetchProjectFriendsByIdQuery.Data(unsafeResultMap: self.validResultMap) case .errored: return GraphAPI.FetchProjectFriendsByIdQuery.Data(unsafeResultMap: self.erroredResultMap) } } // MARK: Private Properties private var validResultMap: [String: Any] { let json = """ { "project":{ "friends":{ "__typename":"ProjectBackerFriendsConnection", "nodes":[ { "__typename":"User", "chosenCurrency":"USD", "email":"[email protected]", "backingsCount": 0, "hasPassword":true, "id":"VXNlci0xNzA1MzA0MDA2", "imageUrl":"https://ksr-qa-ugc.imgix.net/assets/033/090/101/8667751e512228a62d426c77f6eb8a0b_original.jpg?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=1618227451&auto=format&frame=1&q=92&s=36de925b6797139e096d7b6219f743d0", "isAppleConnected":false, "isCreator":null, "isDeliverable":true, "isEmailVerified":true, "isFollowing":true, "name":"Peppermint Fox", "location":{ "country":"US", "countryName":"United States", "displayableName":"Las Vegas, NV", "id":"TG9jYXRpb24tMjQzNjcwNA==", "name":"Las Vegas" }, "storedCards":{ "__typename":"UserCreditCardTypeConnection", "nodes":[ { "__typename":"CreditCard", "expirationDate":"2023-01-01", "id":"6", "lastFour":"4242", "type":"VISA" } ], "totalCount":1 }, "uid":"1705304006" }, { "__typename":"User", "backings":{ "nodes":[ { "errorReason":null }, { "errorReason":"Something went wrong" }, { "errorReason":null } ] }, "backingsCount": 3, "chosenCurrency":null, "email":"[email protected]", "hasPassword":null, "id":"VXNlci0xNTMyMzU3OTk3", "imageUrl":"https://ksr-qa-ugc.imgix.net/assets/033/846/528/69cae8b2ccc2403e233b5715cb1f869f_original.png?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=1623351187&auto=format&frame=1&q=92&s=d0d5f5993e64056e5ddf7e42b56e50cd", "isAppleConnected":null, "isCreator":true, "isDeliverable":null, "isEmailVerified":true, "isFacebookConnected":false, "isFollowing":true, "isKsrAdmin":true, "name":"Thea Schneider", "needsFreshFacebookToken":true, "showPublicProfile":true, "uid":"1532357997", "location":{ "country":"US", "countryName":"United States", "displayableName":"Las Vegas, NV", "id":"TG9jYXRpb24tMjQzNjcwNA==", "name":"Las Vegas" }, "storedCards":{ "__typename":"UserCreditCardTypeConnection", "nodes":[ ], "totalCount":0 } } ] } } } """ let data = Data(json.utf8) let resultMap = (try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]) ?? [:] return resultMap } private var erroredResultMap: [String: Any?] { return [:] } }
apache-2.0
8737b92860fcf81e5557bc7bd8e48713
35.769841
248
0.431038
4.806017
false
false
false
false
wireapp/wire-ios-data-model
Source/Model/Conversation/Member.swift
1
4178
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // @objcMembers public class Member: ZMManagedObject { @NSManaged public var team: Team? @NSManaged public var user: ZMUser? @NSManaged public var createdBy: ZMUser? @NSManaged public var createdAt: Date? @NSManaged public var remoteIdentifier_data: Data? @NSManaged private var permissionsRawValue: Int64 public var permissions: Permissions { get { return Permissions(rawValue: permissionsRawValue) } set { permissionsRawValue = newValue.rawValue } } public override static func entityName() -> String { return "Member" } public override static func isTrackingLocalModifications() -> Bool { return false } public override static func defaultSortDescriptors() -> [NSSortDescriptor] { return [] } public var remoteIdentifier: UUID? { get { guard let data = remoteIdentifier_data else { return nil } return UUID(data: data) } set { remoteIdentifier_data = newValue?.uuidData } } @objc(getOrCreateMemberForUser:inTeam:context:) public static func getOrCreateMember(for user: ZMUser, in team: Team, context: NSManagedObjectContext) -> Member { precondition(context.zm_isSyncContext) if let existing = user.membership { return existing } else if let userId = user.remoteIdentifier, let existing = Member.fetch(with: userId, in: context) { return existing } let member = insertNewObject(in: context) member.team = team member.user = user member.remoteIdentifier = user.remoteIdentifier member.needsToBeUpdatedFromBackend = true return member } } // MARK: - Transport private enum ResponseKey: String { case user, permissions, createdBy = "created_by", createdAt = "created_at" enum Permissions: String { case `self`, copy } } extension Member { @discardableResult public static func createOrUpdate(with payload: [String: Any], in team: Team, context: NSManagedObjectContext) -> Member? { guard let id = (payload[ResponseKey.user.rawValue] as? String).flatMap(UUID.init) else { return nil } let user = ZMUser.fetchOrCreate(with: id, domain: nil, in: context) let createdAt = (payload[ResponseKey.createdAt.rawValue] as? String).flatMap(NSDate.init(transport:)) as Date? let createdBy = (payload[ResponseKey.createdBy.rawValue] as? String).flatMap(UUID.init) let member = getOrCreateMember(for: user, in: team, context: context) member.updatePermissions(with: payload) member.createdAt = createdAt member.createdBy = createdBy.flatMap({ ZMUser.fetchOrCreate(with: $0, domain: nil, in: context) }) return member } public func updatePermissions(with payload: [String: Any]) { guard let userID = (payload[ResponseKey.user.rawValue] as? String).flatMap(UUID.init) else { return } precondition(remoteIdentifier == userID, "Trying to update member with non-matching payload: \(payload), \(self)") guard let permissionsPayload = payload[ResponseKey.permissions.rawValue] as? [String: Any] else { return } guard let selfPermissions = permissionsPayload[ResponseKey.Permissions.`self`.rawValue] as? NSNumber else { return } permissions = Permissions(rawValue: selfPermissions.int64Value) } }
gpl-3.0
2622549f5eba53971c7a8a13f646f9c4
35.017241
127
0.677118
4.673378
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-enum-1argument-1distinct_use.swift
3
4387
// 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: @"$s4main9NamespaceO5ValueOySS_SiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main9NamespaceO5ValueOySS_SiGWV", i32 0, i32 0) // CHECK-SAME: [[INT]] 513, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceO5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] enum Namespace<Arg> { enum Value<First> { 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: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main9NamespaceO5ValueOySS_SiGMf" // 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<String>.Value.first(13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceO5ValueOMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 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* @"$sSSN" to i8*), [[ERASED_TYPE_1]] // CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]] // CHECK: [[EQUAL_TYPE_1_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]] // CHECK: [[EQUAL_TYPES_1_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_1]], [[EQUAL_TYPE_1_2]] // CHECK: br i1 [[EQUAL_TYPES_1_2]], 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: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main9NamespaceO5ValueOySS_SiGMf" // 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* [[ERASED_TYPE_2]], // CHECK-SAME: i8* undef, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceO5ValueOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
7066f4f17032037cb3f11c8dce3a0532
40
157
0.573057
2.918829
false
false
false
false
alexpotter1/WeightTracker
Project/Weight Tracker/Weight Tracker/GraphDataSource.swift
2
4404
// // GraphDataSource.swift // Weight Tracker // // Created by Alex Potter on 10/12/2015. // Copyright ยฉ 2015 Alex Potter. All rights reserved. // // This class will hold all of the data points for the graph to show. import Cocoa class GraphDataSource: NSObject, CPTPlotDataSource { private var shortDateArray: NSArray private var dateArray: NSArray private var dateArrayIntervals: NSArray = [] private var weightArray: NSMutableArray private var recordCount: Int init(_dateArray: NSMutableArray, _weightArray: NSMutableArray) { recordCount = _weightArray.count weightArray = _weightArray // Translate the string values of the dates to NSDate let formatter = NSDateFormatter() formatter.dateFormat = "EEE, d MMM yyyy" dateArray = NSArray(array: _dateArray.map( {formatter.dateFromString($0 as! String)!} )) formatter.dateFormat = "dd/MM/yyyy" shortDateArray = NSArray(array: dateArray.map( {formatter.stringFromDate($0 as! NSDate)} )) // For some reason, superclass init has to go here, I don't know why super.init() // Create an array of intervals (time since the first date) so that it can be plotted correctly // Hence, the first date is at x=0. dateArrayIntervals = dateArray.map( {$0.timeIntervalSinceDate!(dateArray.firstObject as! NSDate)} ) as NSArray } /* Data source function, called automatically by graph Returns the total number of records to be plotted. */ @objc func numberOfRecordsForPlot(plot: CPTPlot) -> UInt { // Making sure date and weight arrays are of equal length, and they should be. if dateArray.count == weightArray.count { print(dateArray.count) return UInt(dateArray.count) } else { return 0 } } /* Data source function, called automatically by graph Returns each record value to be plotted */ @objc func numberForPlot(plot: CPTPlot, field fieldEnum: UInt, recordIndex idx: UInt) -> AnyObject? { // X = x-axis number, Y = y-axis number var x: NSNumber = idx var y: NSNumber = 0 if plot.identifier?.description == "actual" { /* If the array is empty (and if date array is empty then weight array is also empty) then don't return a value cause it's not needed */ if dateArray.count == 0 { return 0 } // x is the date array interval, y is the weight value - round to 3dp to prevent huge double values x = dateArrayIntervals.objectAtIndex(Int(idx)).doubleValue.roundToDecimalPlaces(3) as NSNumber y = weightArray.objectAtIndex(Int(idx)).doubleValue.roundToDecimalPlaces(3) as NSNumber /* fieldEnum is a variable that the graph uses to keep track of the data for each axis. If the fieldEnum is equal to the 'X-axis' field value, then return the x-axis record values. Else if is equal to the 'Y-axis' field value, then return the y-axis record values. */ return (fieldEnum == UInt(CPTScatterPlotField.X.rawValue) ? x : y) } else { return 0 } } /* Data source function, called automatically by graph Returns the value of the data label that is applied to each data point on the graph */ @objc func dataLabelForPlot(plot: CPTPlot, recordIndex idx: UInt) -> CPTLayer? { var x: AnyObject = idx var y: Double = 0.0 if plot.identifier?.description == "actual" { if dateArray.count == 0 { return nil } // x = date (in short string/human format), y = weight value x = shortDateArray.objectAtIndex(Int(idx)) as! String y = weightArray.objectAtIndex(Int(idx)).doubleValue // Make a data label (bounding rect has to be large enough to contain the value but not encroach on anything on the graph) let layer = CPTLayer(frame: CGRectMake(0, 0, 200, 25)) let textLayer = CPTTextLayer(text: "\(x), \(y)") layer.addSublayer(textLayer) return layer } else { return nil } } }
apache-2.0
9afccc048e43f0cb85a4eb72a4192bc9
40.933333
134
0.611628
4.591241
false
false
false
false
duycao2506/SASCoffeeIOS
Pods/String+Extensions/Sources/StringExtensions.swift
1
15818
// // SwiftString.swift // SwiftString // // Created by Andrew Mayne on 30/01/2016. // Copyright ยฉ 2016 Red Brick Labs. All rights reserved. // import Foundation public extension String { /// Finds the string between two bookend strings if it can be found. /// /// - parameter left: The left bookend /// - parameter right: The right bookend /// /// - returns: The string between the two bookends, or nil if the bookends cannot be found, the bookends are the same or appear contiguously. func between(_ left: String, _ right: String) -> String? { guard let leftRange = range(of:left), let rightRange = range(of: right, options: .backwards), left != right && leftRange.upperBound != rightRange.lowerBound else { return nil } return self[leftRange.upperBound...index(before: rightRange.lowerBound)] } // https://gist.github.com/stevenschobert/540dd33e828461916c11 func camelize() -> String { let source = clean(with: " ", allOf: "-", "_") if source.characters.contains(" ") { let first = self[self.startIndex...self.index(after: startIndex)] //source.substringToIndex(source.index(after: startIndex)) let cammel = source.capitalized.replacingOccurrences(of: " ", with: "") // let cammel = String(format: "%@", strip) let rest = String(cammel.characters.dropFirst()) return "\(first)\(rest)" } else { let first = source[self.startIndex...self.index(after: startIndex)].lowercased() let rest = String(source.characters.dropFirst()) return "\(first)\(rest)" } } func capitalize() -> String { return capitalized } // func contains(_ substring: String) -> Bool { // return range(of: substring) != nil // } func chompLeft(_ prefix: String) -> String { if let prefixRange = range(of: prefix) { if prefixRange.upperBound >= endIndex { return self[startIndex..<prefixRange.lowerBound] } else { return self[prefixRange.upperBound..<endIndex] } } return self } func chompRight(_ suffix: String) -> String { if let suffixRange = range(of: suffix, options: .backwards) { if suffixRange.upperBound >= endIndex { return self[startIndex..<suffixRange.lowerBound] } else { return self[suffixRange.upperBound..<endIndex] } } return self } func collapseWhitespace() -> String { let thecomponents = components(separatedBy: NSCharacterSet.whitespacesAndNewlines).filter { !$0.isEmpty } return thecomponents.joined(separator: " ") } func clean(with: String, allOf: String...) -> String { var string = self for target in allOf { string = string.replacingOccurrences(of: target, with: with) } return string } func count(_ substring: String) -> Int { return components(separatedBy: substring).count-1 } func endsWith(_ suffix: String) -> Bool { return hasSuffix(suffix) } func ensureLeft(_ prefix: String) -> String { if startsWith(prefix) { return self } else { return "\(prefix)\(self)" } } func ensureRight(_ suffix: String) -> String { if endsWith(suffix) { return self } else { return "\(self)\(suffix)" } } @available(*, deprecated, message: "Use `index(of:)` instead") func indexOf(_ substring: String) -> Int? { if let range = range(of: substring) { return self.distance(from: startIndex, to: range.lowerBound) // return startIndex.distanceTo(range.lowerBound) } return nil } func initials() -> String { let words = self.components(separatedBy: " ") return words.reduce(""){$0 + $1[startIndex...startIndex]} // return words.reduce(""){$0 + $1[0...0]} } func initialsFirstAndLast() -> String { let words = self.components(separatedBy: " ") return words.reduce("") { ($0 == "" ? "" : $0[startIndex...startIndex]) + $1[startIndex...startIndex]} } func isAlpha() -> Bool { for chr in characters { if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) { return false } } return true } func isAlphaNumeric() -> Bool { let alphaNumeric = NSCharacterSet.alphanumerics let output = self.unicodeScalars.split { !alphaNumeric.contains($0)}.map(String.init) if output.count == 1 { if output[0] != self { return false } } return output.count == 1 // return componentsSeparatedByCharactersInSet(alphaNumeric).joinWithSeparator("").length == 0 } func isEmpty() -> Bool { return self.trimmingCharacters(in: .whitespacesAndNewlines).length == 0 } func isNumeric() -> Bool { if let _ = defaultNumberFormatter().number(from: self) { return true } return false } private func join<S: Sequence>(_ elements: S) -> String { return elements.map{String(describing: $0)}.joined(separator: self) } func latinize() -> String { return self.folding(options: .diacriticInsensitive, locale: .current) // stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale()) } func lines() -> [String] { return self.components(separatedBy: NSCharacterSet.newlines) } var length: Int { get { return self.characters.count } } func pad(_ n: Int, _ string: String = " ") -> String { return "".join([string.times(n), self, string.times(n)]) } func padLeft(_ n: Int, _ string: String = " ") -> String { return "".join([string.times(n), self]) } func padRight(_ n: Int, _ string: String = " ") -> String { return "".join([self, string.times(n)]) } func slugify(withSeparator separator: Character = "-") -> String { let slugCharacterSet = NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\(separator)") return latinize() .lowercased() .components(separatedBy: slugCharacterSet.inverted) .filter { $0 != "" } .joined(separator: String(separator)) } /// split the string into a string array by white spaces func tokenize() -> [String] { return self.components(separatedBy: .whitespaces) } func split(_ separator: Character = " ") -> [String] { return characters.split{$0 == separator}.map(String.init) } func startsWith(_ prefix: String) -> Bool { return hasPrefix(prefix) } func stripPunctuation() -> String { return components(separatedBy: .punctuationCharacters) .joined(separator: "") .components(separatedBy: " ") .filter { $0 != "" } .joined(separator: " ") } func times(_ n: Int) -> String { return (0..<n).reduce("") { $0.0 + self } } func toFloat() -> Float? { if let number = defaultNumberFormatter().number(from: self) { return number.floatValue } return nil } func toInt() -> Int? { if let number = defaultNumberFormatter().number(from: self) { return number.intValue } return nil } func toBool() -> Bool? { let trimmed = self.trimmed().lowercased() if Int(trimmed) != 0 { return true } switch trimmed { case "true", "yes", "1": return true case "false", "no", "0": return false default: return false } } func toDate(_ format: String = "yyyy-MM-dd") -> Date? { return dateFormatter(format).date(from: self) as Date? } func toDateTime(_ format: String = "yyyy-MM-dd HH:mm:ss") -> Date? { return toDate(format) } func trimmedLeft() -> String { if let range = rangeOfCharacter(from: NSCharacterSet.whitespacesAndNewlines.inverted) { return self[range.lowerBound..<endIndex] } return self } func trimmedRight() -> String { if let range = rangeOfCharacter(from: NSCharacterSet.whitespacesAndNewlines.inverted, options: NSString.CompareOptions.backwards) { return self[startIndex..<range.upperBound] } return self } func trimmed() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } subscript(_ r: CountableRange<Int>) -> String { get { let startIndex = self.characters.index(self.startIndex, offsetBy: r.lowerBound) let endIndex = self.characters.index(self.startIndex, offsetBy: r.upperBound) return self[startIndex..<endIndex] } } subscript(_ range: CountableClosedRange<Int>) -> String { get { return self[range.lowerBound..<range.upperBound + 1] } } subscript(safe range: CountableRange<Int>) -> String { get { if length == 0 { return "" } let lower = range.lowerBound < 0 ? 0 : range.lowerBound let upper = range.upperBound < 0 ? 0 : range.upperBound let s = index(startIndex, offsetBy: lower, limitedBy: endIndex) ?? endIndex let e = index(startIndex, offsetBy: upper, limitedBy: endIndex) ?? endIndex return self[s..<e] } } subscript(safe range: CountableClosedRange<Int>) -> String { get { if length == 0 { return "" } let closedEndIndex = index(endIndex, offsetBy: -1, limitedBy: startIndex) ?? startIndex let lower = range.lowerBound < 0 ? 0 : range.lowerBound let upper = range.upperBound < 0 ? 0 : range.upperBound let s = index(startIndex, offsetBy: lower, limitedBy: closedEndIndex) ?? closedEndIndex let e = index(startIndex, offsetBy: upper, limitedBy: closedEndIndex) ?? closedEndIndex return self[s...e] } } func substring(_ startIndex: Int, length: Int) -> String { let start = self.characters.index(self.startIndex, offsetBy: startIndex) let end = self.characters.index(self.startIndex, offsetBy: startIndex + length) return self[start..<end] } subscript(i: Int) -> Character { get { let index = self.characters.index(self.startIndex, offsetBy: i) return self[index] } } // /// get the left part of the string before the index // func left(_ range:Range<String.Index>?) -> String { // return self.substring(to: (range?.lowerBound)!) // } // /// get the right part of the string after the index // func right(_ range:Range<String.Index>?) -> String { // return self.substring(from: self.index((range?.lowerBound)!, offsetBy:1)) // } /// The first index of the given string public func indexRaw(of str: String, after: Int = 0, options: String.CompareOptions = .literal, locale: Locale? = nil) -> String.Index? { guard str.length > 0 else { // Can't look for nothing return nil } guard (str.length + after) <= self.length else { // Make sure the string you're searching for will actually fit return nil } let startRange = self.index(self.startIndex, offsetBy: after)..<self.endIndex return self.range(of: str, options: options.removing(.backwards), range: startRange, locale: locale)?.lowerBound } public func index(of str: String, after: Int = 0, options: String.CompareOptions = .literal, locale: Locale? = nil) -> Int { guard let index = indexRaw(of: str, after: after, options: options, locale: locale) else { return -1 } return self.distance(from: self.startIndex, to: index) } /// The last index of the given string public func lastIndexRaw(of str: String, before: Int = 0, options: String.CompareOptions = .literal, locale: Locale? = nil) -> String.Index? { guard str.length > 0 else { // Can't look for nothing return nil } guard (str.length + before) <= self.length else { // Make sure the string you're searching for will actually fit return nil } let startRange = self.startIndex..<self.index(self.endIndex, offsetBy: -before) return self.range(of: str, options: options.inserting(.backwards), range: startRange, locale: locale)?.lowerBound } public func lastIndex(of str: String, before: Int = 0, options: String.CompareOptions = .literal, locale: Locale? = nil) -> Int { guard let index = lastIndexRaw(of: str, before: before, options: options, locale: locale) else { return -1 } return self.distance(from: self.startIndex, to: index) } } private enum ThreadLocalIdentifier { case dateFormatter(String) case defaultNumberFormatter case localeNumberFormatter(Locale) var objcDictKey: String { switch self { case .dateFormatter(let format): return "SS\(self)\(format)" case .localeNumberFormatter(let l): return "SS\(self)\(l.identifier)" default: return "SS\(self)" } } } private func threadLocalInstance<T: AnyObject>(_ identifier: ThreadLocalIdentifier, initialValue: @autoclosure () -> T) -> T { #if os(Linux) var storage = Thread.current.threadDictionary #else let storage = Thread.current.threadDictionary #endif let k = identifier.objcDictKey let instance: T = storage[k] as? T ?? initialValue() if storage[k] == nil { storage[k] = instance } return instance } private func dateFormatter(_ format: String) -> DateFormatter { return threadLocalInstance(.dateFormatter(format), initialValue: { let df = DateFormatter() df.dateFormat = format return df }()) } private func defaultNumberFormatter() -> NumberFormatter { return threadLocalInstance(.defaultNumberFormatter, initialValue: NumberFormatter()) } private func localeNumberFormatter(_ locale: Locale) -> NumberFormatter { return threadLocalInstance(.localeNumberFormatter(locale), initialValue: { let nf = NumberFormatter() nf.locale = locale return nf }()) } /// Add the `inserting` and `removing` functions private extension OptionSet where Element == Self { /// Duplicate the set and insert the given option func inserting(_ newMember: Self) -> Self { var opts = self opts.insert(newMember) return opts } /// Duplicate the set and remove the given option func removing(_ member: Self) -> Self { var opts = self opts.remove(member) return opts } } public extension String { func isValidEmail() -> Bool { #if os(Linux) let regex = try? RegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive) #else let regex = try? NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive) #endif return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.characters.count)) != nil } /// Encode a String to Base64 func toBase64() -> String { return Data(self.utf8).base64EncodedString() } /// Decode a String from Base64. Returns nil if unsuccessful. func fromBase64() -> String? { guard let data = Data(base64Encoded: self) else { return nil } return String(data: data, encoding: .utf8) } }
gpl-3.0
5883353bf53652e2c29fea111bec7523
31.952083
211
0.604982
4.134083
false
false
false
false
yeziahehe/Gank
Pods/LeanCloud/Sources/Storage/DataType/ACL.swift
1
7251
// // LCACL.swift // LeanCloud // // Created by Tang Tianyong on 5/4/16. // Copyright ยฉ 2016 LeanCloud. All rights reserved. // import Foundation /** LeanCloud access control lists type. You can use it to set access control lists on an object. */ public final class LCACL: NSObject, LCValue, LCValueExtension { typealias Access = [String: Bool] typealias AccessTable = [String: Access] var value: AccessTable = [:] /// The key for public, aka, all users. static let publicAccessKey = "*" /// The key for `read` permission. static let readPermissionKey = "read" /// The key for `write` permission. static let writePermissionKey = "write" public override init() { super.init() } init?(jsonValue: Any?) { guard let value = jsonValue as? AccessTable else { return nil } self.value = value } public required init?(coder aDecoder: NSCoder) { value = (aDecoder.decodeObject(forKey: "value") as? AccessTable) ?? [:] } public func encode(with aCoder: NSCoder) { aCoder.encode(value, forKey: "value") } public func copy(with zone: NSZone?) -> Any { let copy = LCACL() copy.value = value return copy } public override func isEqual(_ object: Any?) -> Bool { if let object = object as? LCACL { return object === self || object.value == value } else { return false } } public var jsonValue: Any { return value } func formattedJSONString(indentLevel: Int, numberOfSpacesForOneIndentLevel: Int = 4) -> String { return LCDictionary(value).formattedJSONString(indentLevel: indentLevel, numberOfSpacesForOneIndentLevel: numberOfSpacesForOneIndentLevel) } public var jsonString: String { return formattedJSONString(indentLevel: 0) } public var rawValue: LCValueConvertible { return self } var lconValue: Any? { return jsonValue } static func instance() -> LCValue { return self.init() } func forEachChild(_ body: (_ child: LCValue) throws -> Void) rethrows { /* Nothing to do. */ } func add(_ other: LCValue) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be added.") } func concatenate(_ other: LCValue, unique: Bool) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be concatenated.") } func differ(_ other: LCValue) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be differed.") } /** Permission type. */ public struct Permission: OptionSet { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let read = Permission(rawValue: 1 << 0) public static let write = Permission(rawValue: 1 << 1) } /** Generate access key for role name. - parameter roleName: The name of role. - returns: An access key for role name. */ static func accessKey(roleName: String) -> String { return "role:\(roleName)" } /** Get access permission for public. - parameter permission: The permission that you want to get. - returns: true if the permission is allowed, false otherwise. */ public func getAccess(_ permission: Permission) -> Bool { return getAccess(permission, key: LCACL.publicAccessKey) } /** Set access permission for public. - parameter permission: The permission to be set. - parameter allowed: A boolean value indicates whether permission is allowed or not. */ public func setAccess(_ permission: Permission, allowed: Bool) { setAccess(permission, key: LCACL.publicAccessKey, allowed: allowed) } /** Get access permission for user. - parameter permission: The permission that you want to get. - parameter userID: The user object ID for which you want to get. - returns: true if the permission is allowed, false otherwise. */ public func getAccess(_ permission: Permission, forUserID userID: String) -> Bool { return getAccess(permission, key: userID) } /** Set access permission for user. - parameter permission: The permission to be set. - parameter allowed: A boolean value indicates whether permission is allowed or not. - parameter userID: The user object ID for which the permission will be set. */ public func setAccess(_ permission: Permission, allowed: Bool, forUserID userID: String) { setAccess(permission, key: userID, allowed: allowed) } /** Get access permission for role. - parameter permission: The permission that you want to get. - parameter roleName: The role name for which you want to get. - returns: true if the permission is allowed, false otherwise. */ public func getAccess(_ permission: Permission, forRoleName roleName: String) -> Bool { return getAccess(permission, key: LCACL.accessKey(roleName: roleName)) } /** Set access permission for role. - parameter permission: The permission to be set. - parameter allowed: A boolean value indicates whether permission is allowed or not. - parameter roleName: The role name for which the permission will be set. */ public func setAccess(_ permission: Permission, allowed: Bool, forRoleName roleName: String) { setAccess(permission, key: LCACL.accessKey(roleName: roleName), allowed: allowed) } /** Get access for key. - parameter permission: The permission that you want to get. - parameter key: The key for which you want to get. - returns: true if all permission is allowed, false otherwise. */ func getAccess(_ permission: Permission, key: String) -> Bool { guard let access = value[key] else { return false } /* We use AND logic here. If any one of permissions is disallowed, return false. */ if permission.contains(.read) { if access[LCACL.readPermissionKey] == nil { return false } } if permission.contains(.write) { if access[LCACL.writePermissionKey] == nil { return false } } return true } /** Update permission for given key. - parameter permission: The permission. - parameter key: The key for which the permission to be updated. - parameter allowed: A boolean value indicates whether permission is allowed or not. */ func setAccess(_ permission: Permission, key: String, allowed: Bool) { var access = value[key] ?? [:] /* We reserve the allowed permissions only. */ if permission.contains(.read) { access[LCACL.readPermissionKey] = allowed ? allowed : nil } if permission.contains(.write) { access[LCACL.writePermissionKey] = allowed ? allowed : nil } value[key] = !access.isEmpty ? access : nil } }
gpl-3.0
ad691ffc85783e8cc052f3cb1d32a1cc
28.352227
146
0.626069
4.539762
false
false
false
false
Davidde94/StemCode_iOS
StemCode/StemCode/Code/View Controllers/ProjectViewController.swift
1
24093
// // ProjectViewController.swift // StemCode // // Created by David Evans on 12/04/2018. // Copyright ยฉ 2018 BlackPoint LTD. All rights reserved. // import UIKit import MBProgressHUD import StemProjectKit class ProjectViewController: UIViewController, UIDropInteractionDelegate, TabDelegate, UIScrollViewDelegate, WindowDelegate { var project: Stem! var executor: ProjectExecutor? @IBOutlet var windowScroller: UIScrollView! @IBOutlet var windowContainer: UIStackView! @IBOutlet var tabScroller: UIScrollView! @IBOutlet var tabContainer: UIStackView! @IBOutlet var projectNameLabel: UILabel! @IBOutlet var currentFileNameLabel: UILabel! @IBOutlet var progressBar: UIProgressView! @IBOutlet var dropView: UIView! @IBOutlet var warningsContainer: UIStackView! @IBOutlet var fatalsContainer: UIStackView! @IBOutlet var warningsCountlabel: UILabel! @IBOutlet var fatalsCountlabel: UILabel! @IBOutlet var windowContainerBottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() setupKeyboardManagement() registerObservers() executor = OnlineExecutor(project: project, delegate: self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let dropInteraction = UIDropInteraction(delegate: self) view.addInteraction(dropInteraction) createTabs() } override func back() { let unsaved = project.unsavedFiles if unsaved.count == 0 { dismiss(animated: true, completion: nil) return } let alert = UIAlertController(title: "You have unsaved files", message: "Would you like to save before closing the project?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Save", style: .default, handler: { (_) in self.project.unsavedFiles.forEach({ (file) in file.save() }) self.dismiss() })) alert.addAction(UIAlertAction(title: "Don't Save", style: .destructive, handler: { (_) in self.dismiss() })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } // MARK: - func registerObservers() { ErrorManager.shared.errorCountsChanged.subscribe(with: self) { [weak self] (warnings, fatals) in self?.updateWarnings(warnings, fatals: fatals) } } func updateWarnings(_ warnings: Int, fatals: Int) { warningsCountlabel.text = "\(warnings)" fatalsCountlabel.text = "\(fatals)" let showWarnings = warnings > 0 var warningsTransform = CGAffineTransform(scaleX: 0, y: 0) var warningsAlpha: CGFloat = 0 if showWarnings { warningsTransform = CGAffineTransform(scaleX: 0, y: 0) warningsAlpha = 1 } let showFatals = fatals > 0 var fatalsTransform = CGAffineTransform(scaleX: 0, y: 0) var fatalsAlpha: CGFloat = 0 if showFatals { fatalsTransform = CGAffineTransform(scaleX: 1, y: 1) fatalsAlpha = 1 } self.warningsContainer.isHidden = !showWarnings self.fatalsContainer.isHidden = !showFatals UIView.animate(withDuration: 0.25, delay: 0, options: .beginFromCurrentState, animations: { self.warningsContainer.transform = warningsTransform self.warningsContainer.alpha = warningsAlpha self.fatalsContainer.transform = fatalsTransform self.fatalsContainer.alpha = fatalsAlpha }, completion: nil) } @IBAction func save() { guard let tab = tabContainer.arrangedSubviews[project.currentTabIndex] as? Tab else { return } let window = tab.stemWindow let strategy = window.fileEditor.editor as? FileStrategy strategy?.save() } @IBAction func changeTarget(_ sender: UIButton) { var title: String? = nil var style = UIAlertController.Style.actionSheet if UIDevice.current.userInterfaceIdiom == .phone { title = "Select an executor to use" style = UIAlertController.Style.alert } let alert = UIAlertController(title: title, message: nil, preferredStyle: style) alert.addAction(UIAlertAction(title: "BlackPoint Online", style: .default, handler: { (_) in self.executor = OnlineExecutor(project: self.project, delegate: self) })) if UIDevice.current.userInterfaceIdiom == .phone { alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) } else if UIDevice.current.userInterfaceIdiom == .pad { alert.popoverPresentationController?.sourceRect = sender.bounds alert.popoverPresentationController?.sourceView = sender } present(alert, animated: true, completion: nil) } @IBAction func execute() { executor?.execute() } // MARK: - Keyboard management func setupKeyboardManagement() { NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: nil) { [weak self] (notification) in self?.keyboardWillChangeFrame(notification: notification) } } func keyboardWillChangeFrame(notification: Notification) { guard let info = notification.userInfo else { return } let frame = info[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect let curve = UIView.AnimationOptions(rawValue: info[UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt) let duration = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double windowContainerBottomConstraint.constant = self.view.frame.size.height - frame.origin.y UIView.animate(withDuration: duration, delay: 0.0, options: [UIView.AnimationOptions.beginFromCurrentState, curve], animations: { self.view.layoutIfNeeded() }, completion: nil) } // MARK: - Creation @IBAction func create(sender: UIView) { var title: String? = nil var message: String? = nil let compact = view.traitCollection.horizontalSizeClass == .compact if compact { title = "Create" message = "Choose what you would like to create below" } let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) alert.popoverPresentationController?.sourceView = sender alert.popoverPresentationController?.sourceRect = sender.bounds alert.addAction(UIAlertAction(title: "Create file", style: .default, handler: { (action) in self.createFile() })) alert.addAction(UIAlertAction(title: "Create group", style: .default, handler: { (action) in self.createGroup(folder: true) })) alert.addAction(UIAlertAction(title: "Create group (without folder)", style: .default, handler: { (action) in self.createGroup(folder: false) })) if compact { alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) } present(alert, animated: true, completion: nil) } func createFile() { } func createGroup(folder: Bool, parentGroup: StemGroup? = nil) { if let parentGroup = parentGroup { let alert = UIAlertController(title: "Create Group", message: "Enter the new group name below", preferredStyle: .alert) alert.addTextField { (textfield) in textfield.placeholder = "Group Name" } alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action) in let name = alert.textFields?.first?.text ?? "" let group = StemGroup(project: parentGroup.parentProject, name: name, isFolder: folder) parentGroup.addChild(group) StemManager.shared.saveProject(parentGroup.parentProject) })) present(alert, animated: true, completion: nil) } } // MARK: - Sharing @IBAction func displayShareOptions(sender: UIView) { let file = project.openTab.file var title: String? = nil var message: String? = nil let compact = view.traitCollection.horizontalSizeClass == .compact if compact { title = "What would you like to share?" message = "You can share either the whole project, or just the active file." } let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) alert.popoverPresentationController?.sourceView = sender alert.popoverPresentationController?.sourceRect = sender.bounds alert.addAction(UIAlertAction(title: "Share '\(file.name)'", style: .default, handler: { (action) in self.shareFile(self.project.openTab.file, sourceView: sender) })) alert.addAction(UIAlertAction(title: "Share project", style: .default, handler: { (action) in self.shareProject(sourceView: sender) })) if compact { alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) } present(alert, animated: true, completion: nil) } func shareFile(_ file: StemFile, sourceView: UIView) { let url = URL(fileURLWithPath: file.absolutePath) let actionController = UIActivityViewController(activityItems: [url], applicationActivities: nil) actionController.popoverPresentationController?.sourceView = sourceView actionController.popoverPresentationController?.sourceRect = sourceView.bounds present(actionController, animated: true, completion: nil) } func shareProject(sourceView: UIView) { let hud = MBProgressHUD() view.addSubview(hud) hud.mode = .annularDeterminate hud.label.text = "Compressing project..." hud.removeFromSuperViewOnHide = true hud.animationType = .zoomOut hud.show(animated: true) hud.removeFromSuperViewOnHide = true StemManager.shared.compressProject(project, progressHandler: { (progress) in hud.progress = Float(progress) }) { (path) in hud.hide(animated: true) let url = URL(fileURLWithPath: path) let actionController = UIActivityViewController(activityItems: [url], applicationActivities: nil) actionController.popoverPresentationController?.sourceView = sourceView actionController.popoverPresentationController?.sourceRect = sourceView.bounds self.present(actionController, animated: true, completion: nil) } } func confirmRenameFile(_ file: StemFile) { let alert = UIAlertController(title: "Rename '\(file.name)'?", message: "This will also relocate in the filesystem.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Rename", style: .destructive, handler: { (action) in if let tf = alert.textFields?.first, let name = tf.text { file.setName(name) StemManager.shared.saveProject(self.project) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addTextField { (textfield) in textfield.placeholder = file.name textfield.text = file.name } present(alert, animated: true, completion: nil) } // MARK: - Deletion func deleteFile(_ file: StemFile) { func delete() { } let confirm = UIAlertController(title: "Delete '\(file.name)'?", message: "This cannot be undone.", preferredStyle: .alert) confirm.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) confirm.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { (action) in delete() })) present(confirm, animated: true, completion: nil) } // MARK: - Tab managemenet func createTabs() { createViewsForTab(project.tabs.first!) for stemTab in project.tabs[1...] { createViewsForTab(stemTab) } let selected = tabContainer.arrangedSubviews[project.currentTabIndex] as! Tab tabWasSelected(selected) } func createViewsForTab(_ tab: StemTab) { let tabView = Bundle.main.loadNibNamed("Tab", owner: self, options: nil)?.first as! Tab tabView.stemTab = tab tabView.selected = false tabView.delegate = self tabView.translatesAutoresizingMaskIntoConstraints = false tabContainer.addArrangedSubview(tabView) tabView.widthAnchor.constraint(equalToConstant: 250).isActive = true let window = tabView.stemWindow window.delegate = self addChild(window) windowContainer.addArrangedSubview(window.view) window.view.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true } @IBAction func duplicateTab() { let newStemTab = project.openTab.clone() let tabView = Bundle.main.loadNibNamed("Tab", owner: self, options: nil)?.first as! Tab tabView.stemTab = newStemTab tabView.translatesAutoresizingMaskIntoConstraints = false tabView.delegate = self tabView.widthAnchor.constraint(equalToConstant: 250).isActive = true tabView.stemWindow.delegate = self if project.currentTabIndex == project.tabs.count - 1 { tabContainer.addArrangedSubview(tabView) windowContainer.addArrangedSubview(tabView.stemWindow.view) } else { tabContainer.insertArrangedSubview(tabView, at: project.currentTabIndex + 1) windowContainer.insertArrangedSubview(tabView.stemWindow.view, at: project.currentTabIndex + 1) } windowScroller.setContentOffset(CGPoint(x: CGFloat(project.currentTabIndex + 1) * self.view.frame.size.width, y: 0), animated: false) (tabContainer.arrangedSubviews[project.currentTabIndex] as! Tab).selected = false project.currentTabIndex += 1 (tabContainer.arrangedSubviews[project.currentTabIndex] as! Tab).selected = true project.tabs.append(newStemTab) } // MARK: - TabDelegate func tabWasSelected(_ tab: Tab) { let index = tabContainer.arrangedSubviews.index(of: tab)! (tabContainer.arrangedSubviews[project.currentTabIndex] as? Tab)?.selected = false project.currentTabIndex = index (tabContainer.arrangedSubviews[project.currentTabIndex] as! Tab).selected = true StemManager.shared.saveProject(project) let stemWindow = tab.stemWindow windowScroller.scrollRectToVisible(stemWindow.view.frame, animated: false) projectNameLabel.text = tab.stemTab.file.parentProject.name.uppercased() currentFileNameLabel.text = tab.stemTab.file.name tabScroller.scrollRectToVisible(tabContainer.subviews[project.currentTabIndex].frame, animated: true) StemManager.shared.saveProject(project) } func tabWasClosed(_ tab: Tab) { guard project.tabs.count > 1 else { let alert = UIAlertController(title: "You can't close the last open tab", message: "Don't be a fool", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Sorry for being a fool", style: .default, handler: nil)) present(alert, animated: true, completion: nil) return } let index = tabContainer.arrangedSubviews.index(of: tab)! tab.removeFromSuperview() tab.stemWindow.view.removeFromSuperview() project.tabs.remove(at: index) if index == 0, let firstTab = tabContainer.arrangedSubviews.first as? Tab { firstTab.widthAnchor.constraint(equalToConstant: 250).isActive = true firstTab.stemWindow.view.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true if !tab.selected { project.currentTabIndex -= 1 } } else { project.currentTabIndex -= 1 } if tab.selected { tabWasSelected(tabContainer.arrangedSubviews[project.currentTabIndex] as! Tab) } StemManager.shared.saveProject(project) } // MARK: - UIScrollViewDelegate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == windowScroller { let page = Int(round(scrollView.contentOffset.x / view.frame.width)) if page >= 0 && page < project.tabs.count { (tabContainer.subviews[project.currentTabIndex] as! Tab).selected = false project.currentTabIndex = page (tabContainer.subviews[page] as! Tab).selected = true StemManager.shared.saveProject(project) tabScroller.scrollRectToVisible(tabContainer.subviews[project.currentTabIndex].frame, animated: true) } } } // MARK: - WindowDelegate func windowDidSelectFile(_ window: Window, file: StemFile) { if window == windowContainer.arrangedSubviews[project.currentTabIndex] { currentFileNameLabel.text = file.name } } func windowDidRequestFileOptions(_ window: Window, fileView: StemFileView) { let file = fileView.stemItem! var title: String? = nil var message: String? = nil if UIDevice.current.userInterfaceIdiom == .phone { title = "'\(file.name)'" message = "What would you like to do?" } let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Rename", style: .default, handler: { (action) in self.confirmRenameFile(file) })) alert.addAction(UIAlertAction(title: "Share", style: .default, handler: { (action) in self.shareFile(file, sourceView: fileView) })) alert.addAction(UIAlertAction(title: "New Group", style: .default, handler: { (action) in self.createGroup(folder: true, parentGroup: fileView.stemItem.parentGroup) })) alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { (action) in self.deleteFile(file) })) if UIDevice.current.userInterfaceIdiom == .pad { alert.popoverPresentationController?.sourceView = fileView alert.popoverPresentationController?.sourceRect = fileView.bounds alert.popoverPresentationController?.permittedArrowDirections = [.left] } else if UIDevice.current.userInterfaceIdiom == .phone { alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) } present(alert, animated: true, completion: nil) } func windowDidRequestFileTypeChange(_window: Window, file: StemFile, sourceView: UIView!) { let types = StemFileType.allCases let alert = UIAlertController(title: "Choose a file type", message: "We'll use this to decide which editor to use whe opening the file", preferredStyle: .actionSheet) for type in types { let action = UIAlertAction(title: type.description, style: .default) { (_) in file.rawType = type } alert.addAction(action) } alert.popoverPresentationController?.sourceView = sourceView alert.popoverPresentationController?.sourceRect = sourceView.bounds alert.popoverPresentationController?.permittedArrowDirections = [.right] alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } // MARK: - UIDropInteractionDelegate func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool { return true } func dropInteraction(_ interaction: UIDropInteraction, sessionDidEnter session: UIDropSession) { UIView.animate(withDuration: 0.2, delay: 0, options: UIView.AnimationOptions.beginFromCurrentState, animations: { self.dropView.alpha = 1.0 }, completion: nil) } func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal { return UIDropProposal(operation: .copy) } func dropInteraction(_ interaction: UIDropInteraction, sessionDidExit session: UIDropSession) { UIView.animate(withDuration: 0.2, delay: 0, options: UIView.AnimationOptions.beginFromCurrentState, animations: { self.dropView.alpha = 0.0 }, completion: nil) } func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) { currentFileNameLabel.text = "Importing \(session.items.count) items..." let sema = DispatchSemaphore(value: 1) var complete = 0 progressBar.progress = 0 for item in session.items { let provider = item.itemProvider provider.loadFileRepresentation(forTypeIdentifier: "public.content") { (url, error) in let name = url!.lastPathComponent let file = self.project.fileWith(name: name) DispatchQueue.main.async { self.project.rootGroup.addChild(file) sema.wait() complete += 1 self.progressBar.progress = Float(complete) / Float(session.items.count) if complete == session.items.count { UIView.animate(withDuration: 0.5, animations: { self.progressBar.alpha = 0.0 }, completion: { (complete) in self.progressBar.alpha = 1.0 self.progressBar.progress = 0.0 }) self.currentFileNameLabel.text = self.project.openTab.file.name } sema.signal() } do { try FileManager.default.copyItem(atPath: url!.path, toPath: file.absolutePath) } catch { print(error.localizedDescription) } } } UIView.animate(withDuration: 0.2, delay: 0, options: UIView.AnimationOptions.beginFromCurrentState, animations: { self.dropView.alpha = 0.0 }, completion: nil) // StemManager.shared.saveProject(project) } } // MARK: - ProjectExecutorDelegate extension ProjectViewController: ProjectExecutorDelegate { func executor(_ executor: ProjectExecutor, didFailWithError error: ProjectExecutorError) { NSLog("Project executor error: %s", error.localizedDescription) } func executor(_ executor: ProjectExecutor, didSetProgress progress: Double) { progressBar.progress = Float(progress) } func executor(_ executor: ProjectExecutor, didWantToShowProgressBar showProgressBar: Bool) { progressBar.alpha = showProgressBar ? 1.0 : 0.0 } func executor(_ executor: ProjectExecutor, didSendMessage message: String) { } func executor(_ executor: ProjectExecutor, didUpdateAction action: String) { currentFileNameLabel.text = action } func executorDidFinish(_ executor: ProjectExecutor) { } }
mit
72780a65173dde9497990b3f62d22feb
38.821488
174
0.638594
4.886815
false
false
false
false
Tinkertanker/intro-coding-swift
1-2 More Functions.playground/Sources/RTurtle.swift
1
6396
import Cocoa import SpriteKit import XCPlayground import Foundation public class RTurtle : NSObject { var view:SKView = SKView(frame: CGRectMake(0,0,900,600)) var scene:SKScene = SKScene(size: CGSizeMake(1024, 768)) var turtle:SKSpriteNode = SKSpriteNode(imageNamed: "karel.png", normalMapped: false) let squareSize:Int=50 var moveSequence = [SKAction]() var rotation:Double = 0.0 var pickups=[SKSpriteNode](); var walls=[SKSpriteNode](); var xcord = 0; var ycord = 0; var dead = false; var score = 0; var won = true; var maze = [ /*Start*/[0,1,1,1,1,1,1,1,1,1,1,1,1,0,0],//bottom right [0,0,0,3,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0], // 0 denotes space, 1 denotes wall [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0], // 2 denotes pickup [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0], // 3 denotes goal [1,1,1,1,1,1,1,1,1,1,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],//top right ] public func start()->String{ scene.scaleMode = SKSceneScaleMode.AspectFit view.presentScene(scene) XCPShowView("Live View",view); // Create the scene and add it to the view turtle.size = CGSizeMake(CGFloat(squareSize),CGFloat(squareSize)); turtle.position = positionAtGrid(0 , y:0) // turtle.runAction(SKAction.repeatActionForever(SKAction.rotateByAngle(6, duration: 2))) //Generate terrain, assuming that it's rectangular var i=0; var j=0; for row in maze { j=0; for cell in row{ if(cell != 0){ switch(cell){ case 1: walls.append(SKSpriteNode(color: SKColor.redColor(), size: CGSizeMake(CGFloat(squareSize),CGFloat(squareSize)))); walls[walls.count-1].position=positionAtGrid(j, y: i) scene.addChild(walls[walls.count-1]) break case 2: pickups.append(SKSpriteNode(imageNamed:"cherry.png",normalMapped:false)); pickups[pickups.count-1].size=CGSizeMake(CGFloat(squareSize),CGFloat(squareSize)) pickups[pickups.count-1].position=positionAtGrid(j, y: i) scene.addChild(pickups[pickups.count-1]) break case 3: walls.append(SKSpriteNode(color: SKColor.yellowColor(), size: CGSizeMake(CGFloat(squareSize),CGFloat(squareSize)))); walls[walls.count-1].position=positionAtGrid(j, y: i) scene.addChild(walls[walls.count-1]) break default: break } } j++; } i++; } //last so it's on top of everything else scene.addChild(turtle) return "K@rel, reporting for duty! Where should I go?" } public func moveForward()->String{ if(!dead){ var dx=sin(rotation)*Double(squareSize)*Double(-1) var dy=cos(rotation)*Double(squareSize) xcord-=Int(sin(rotation)) ycord+=Int(cos(rotation)) moveSequence.append(SKAction.moveBy(CGVector(dx: dx, dy: dy), duration: 0.5)) } return "Okay, I'll move forward next." } public func turnRight()->String{ if(!dead){ rotation=rotation-M_PI_2 moveSequence.append(SKAction.rotateToAngle(CGFloat(rotation), duration: 0.5)) } return "Okay, I'll turn right next." } public func turnLeft()->String{ if(!dead){ rotation=rotation+M_PI_2 moveSequence.append(SKAction.rotateToAngle(CGFloat(rotation), duration: 0.5)) } return "Okay, I'll turn left next." } // public func moveRight(){ // moveSequence.append(SKAction.moveBy(CGVector(dx: squareSize, dy: 0), duration: 0.5)) // } public func move()->String{ doMove(0) return "Moving~" } private func doMove(step:Int){ if(step>=moveSequence.count){ print("Done! I picked up ") print(score) print(" cherries!") } else{ print(self.roundPosition(self.turtle.position)) var action=self.moveSequence[step] turtle.runAction(action,completion:{ var mazeValue = self.mazeValueAtPosition(self.turtle.position) if(mazeValue==1){ print("I died!") self.dead=true self.turtle.runAction(SKAction.repeatActionForever(SKAction.rotateByAngle(6,duration: 2))) } else if(mazeValue==2){ for pickup in self.pickups { print(pickup.position) print(self.roundPosition(self.turtle.position)) if(pickup.position==self.roundPosition(self.turtle.position)){ if(!pickup.hidden){ print(self.score) self.score++ pickup.hidden=true; } } } self.doMove(step+1) } else if(mazeValue==3){ print("I'm done!") } else{ self.doMove(step+1) } }) } } private func positionAtGrid(x:Int,y:Int)->CGPoint{ return CGPointMake(CGFloat(60+x*squareSize),CGFloat(60+y*squareSize)) } private func mazeValueAtPosition(position:CGPoint)->Int{ var xcord=round((position.x-60)/CGFloat(squareSize)) var ycord=round((position.y-60)/CGFloat(squareSize)) return maze[Int(ycord)][Int(xcord)] } private func roundPosition(position:CGPoint) -> CGPoint{ return CGPointMake(CGFloat(round(position.x*10)/10), CGFloat(round(position.y*10)/10)) } public func getScore()->Int{ return score; } }
mit
e0bbd8bae6ecde8f044849f308574a5b
38
140
0.516886
3.955473
false
false
false
false
aryehToDog/DYZB
DYZB/DYZB/Class/Home/Controller/WKGameViewController.swift
1
4766
// // WKGameViewController.swift // DYZB // // Created by ้˜ฟๆ‹‰ๆ–ฏๅŠ ็š„็‹— on 2017/9/1. // Copyright ยฉ 2017ๅนด ้˜ฟๆ‹‰ๆ–ฏๅŠ ็š„๐Ÿถ. All rights reserved. // import UIKit private let kMaragin: CGFloat = 10 private let kItemW: CGFloat = (WKWidth - 2 * kMaragin) / 3 private let kItemH : CGFloat = kItemW * 6 / 5 //layout ็š„ๅคด้ƒจ้ซ˜ๅบฆ private let kItemwGroupH: CGFloat = 50 private let kGameViewH : CGFloat = 90 private let gameViewCellID = "gameViewCellID" //private let kReusableView = "kReusableView" class WKGameViewController: WKBaseViewController { //่Žทๅ–gameViewModel let gameViewModel: WKGameViewModel = WKGameViewModel() //ๆ‡’ๅŠ ่ฝฝไธ€ไธชcollectionView fileprivate lazy var collectionView: UICollectionView = {[unowned self] in let layout = UICollectionViewFlowLayout() //่ฎพ็ฝฎๅฑžๆ€ง layout.itemSize = CGSize(width: kItemW, height: kItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: kMaragin, bottom: 0, right: kMaragin) layout.headerReferenceSize = CGSize(width: WKWidth, height: kItemwGroupH) let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.dataSource = self collectionView.autoresizingMask = [.flexibleWidth,.flexibleHeight] collectionView.register(UINib(nibName: "WKGameViewCell", bundle: nil), forCellWithReuseIdentifier: gameViewCellID) collectionView.register(UINib(nibName: "WKReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kReusableView) collectionView.backgroundColor = UIColor.white return collectionView }() //ๆ‡’ๅŠ ่ฝฝheadView fileprivate lazy var headView:WKReusableView = { let headView = WKReusableView.reusableView() headView.frame = CGRect(x: 0, y: -(kGameViewH + kItemwGroupH), width: WKWidth, height: kItemwGroupH) headView.nickNameLable.text = "็ƒญ้—จ" headView.iconView.image = UIImage(named: "Img_orange") headView.moreBtn.isHidden = true return headView }() //ๆทปๅŠ gameView fileprivate lazy var gameView: WKRecommendGanmeView = { let gameView = WKRecommendGanmeView.recommendGanmeView() gameView.frame = CGRect(x: 0, y: -kGameViewH , width: WKWidth, height: kGameViewH) return gameView }() override func viewDidLoad() { super.viewDidLoad() setupUI() setLoadData() } } extension WKGameViewController { func setLoadData() { gameViewModel.loadGameData { //ๅˆทๆ–ฐๆ•ฐๆฎ self.collectionView.reloadData() self.gameView.groupModel = Array(self.gameViewModel.gameModelArray[0..<10]) //ๅฎŒๆˆๆ•ฐๆฎ่ฏทๆฑ‚ๅฎŒๆฏ•็š„ๅ›ž่ฐƒ self.finishedCallBackEndAnimatin() } } } extension WKGameViewController { override func setupUI() { contentView = collectionView view.addSubview(collectionView) //ๆทปๅŠ ๅคด้ƒจ collectionView.addSubview(headView) //ๆทปๅŠ gameView collectionView.addSubview(gameView) collectionView.contentInset = UIEdgeInsets(top: kItemwGroupH + kGameViewH, left: 0, bottom: 0, right: 0) super.setupUI() } } extension WKGameViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameViewModel.gameModelArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: gameViewCellID, for: indexPath) as! WKGameViewCell cell.groupM = gameViewModel.gameModelArray[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kReusableView, for: indexPath) as! WKReusableView cell.nickNameLable.text = "ๅ…จ้ƒจ" cell.iconView.image = UIImage(named: "Img_orange") cell.moreBtn.isHidden = true return cell } }
apache-2.0
0bf8e02a8d15812689dd0f096d114949
30.181208
180
0.653465
5.191061
false
false
false
false
JaSpa/swift
test/SILGen/switch_abstraction.swift
4
1597
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -parse-stdlib %s | %FileCheck %s struct A {} enum Optionable<T> { case Summn(T) case Nuttn } // CHECK-LABEL: sil hidden @_T018switch_abstraction18enum_reabstractionyAA10OptionableOyAA1AVAFcG1x_AF1atF : $@convention(thin) (@owned Optionable<(A) -> A>, A) -> () // CHECK: switch_enum {{%.*}} : $Optionable<(A) -> A>, case #Optionable.Summn!enumelt.1: [[DEST:bb[0-9]+]] // CHECK: [[DEST]]([[ORIG:%.*]] : $@callee_owned (@in A) -> @out A): // CHECK: [[REABSTRACT:%.*]] = function_ref @_T0{{.*}}TR : // CHECK: [[SUBST:%.*]] = partial_apply [[REABSTRACT]]([[ORIG]]) func enum_reabstraction(x x: Optionable<(A) -> A>, a: A) { switch x { case .Summn(var f): f(a) case .Nuttn: () } } enum Wacky<A, B> { case Foo(A) case Bar((B) -> A) } // CHECK-LABEL: sil hidden @_T018switch_abstraction45enum_addr_only_to_loadable_with_reabstraction{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@in Wacky<T, A>, A) -> @out T { // CHECK: switch_enum_addr [[ENUM:%.*]] : $*Wacky<T, A>, {{.*}} case #Wacky.Bar!enumelt.1: [[DEST:bb[0-9]+]] // CHECK: [[DEST]]: // CHECK: [[ORIG_ADDR:%.*]] = unchecked_take_enum_data_addr [[ENUM]] : $*Wacky<T, A>, #Wacky.Bar // CHECK: [[ORIG:%.*]] = load [take] [[ORIG_ADDR]] // CHECK: [[REABSTRACT:%.*]] = function_ref @_T0{{.*}}TR : // CHECK: [[SUBST:%.*]] = partial_apply [[REABSTRACT]]<T>([[ORIG]]) func enum_addr_only_to_loadable_with_reabstraction<T>(x x: Wacky<T, A>, a: A) -> T { switch x { case .Foo(var b): return b case .Bar(var f): return f(a) } }
apache-2.0
6aa42e80dcacd00771967afff388f6b5
34.488889
174
0.583594
2.801754
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Components/GradientView.swift
1
6707
// // Xcore // Copyright ยฉ 2017 Xcore // MIT license, see LICENSE file for details // import UIKit import CoreGraphics // MARK: - GradientView open class GradientView: UIView { private let gradientLayer = GradientLayer() // MARK: - Init Methods public required init() { super.init(frame: .zero) commonInit() } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } /// The style of gradient. /// /// The default value is `.axial`. open var type: CAGradientLayerType { get { gradientLayer.type } set { gradientLayer.type = newValue } } /// An optional array of `Double` defining the location of each gradient stop. /// This property is animatable. /// /// The gradient stops are specified as values between `0` and `1`. The values /// must be monotonically increasing. If `nil`, the stops are spread uniformly /// across the range. /// /// The default value is `nil`. /// /// When rendered, the colors are mapped to the output color space before being /// interpolated. open var locations: [Double]? { get { gradientLayer.locations } set { gradientLayer.locations = newValue } } /// An array of `UIColor` objects defining the color of each gradient stop. /// /// This property is animatable. open var colors: [UIColor] { get { gradientLayer.colors } set { gradientLayer.colors = newValue } } /// The direction of the gradient when drawn in the layerโ€™s coordinate space. /// /// This property is animatable. /// /// The default value is `.topToBottom`. open var direction: GradientDirection { get { gradientLayer.direction } set { gradientLayer.direction = newValue } } // MARK: - Setup Methods /// Subclasses can override it to perform additional actions, for example, add /// new subviews or configure properties. This method is called when `self` is /// initialized using any of the relevant `init` methods. open func commonInit() { layer.addSublayer(gradientLayer) } open override func layoutSubviews() { super.layoutSubviews() CATransaction.performWithoutAnimation { gradientLayer.frame = bounds } } public func setColors(_ colors: [UIColor], animated: Bool) { guard !animated else { self.colors = colors return } CATransaction.performWithoutAnimation { self.colors = colors } } } // MARK: - GradientLayer open class GradientLayer: CALayer { private let gradient = CAGradientLayer() /// The style of gradient drawn by the layer. /// /// The default value is `.axial`. open var type: CAGradientLayerType = .axial { didSet { gradient.type = type } } /// An optional array of `Double` defining the location of each gradient stop. /// This property is animatable. /// /// The gradient stops are specified as values between `0` and `1`. The values /// must be monotonically increasing. If `nil`, the stops are spread uniformly /// across the range. /// /// The default value is `nil`. /// /// When rendered, the colors are mapped to the output color space before being /// interpolated. open var locations: [Double]? { didSet { guard let locations = locations else { gradient.locations = nil return } gradient.locations = locations.map { NSNumber(value: $0) } } } /// An array of `UIColor` objects defining the color of each gradient stop. /// /// This property is animatable. open var colors: [UIColor] = [] { didSet { // If only color is assigned. Then fill by using the same color. So it works as // expected. if colors.count == 1 { colors = [colors[0], colors[0]] } gradient.colors = colors.map(\.cgColor) } } /// The direction of the gradient when drawn in the layerโ€™s coordinate space. /// /// This property is animatable. /// /// The default value is `.topToBottom`. open var direction: GradientDirection = .topToBottom { didSet { updateGradient(direction: direction) } } public override init() { super.init() commonInit() } public override init(layer: Any) { super.init(layer: layer) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } open func commonInit() { addSublayer(gradient) updateGradient(direction: direction) } open override func layoutSublayers() { super.layoutSublayers() CATransaction.performWithoutAnimation { gradient.frame = frame } } private func updateGradient(direction: GradientDirection) { (gradient.startPoint, gradient.endPoint) = direction.points } } // MARK: - GradientDirection public enum GradientDirection { case topToBottom case bottomToTop case leftToRight case rightToLeft case topLeftToBottomRight case topRightToBottomLeft case bottomLeftToTopRight case bottomRightToTopLeft case custom(start: CGPoint, end: CGPoint) public var points: (start: CGPoint, end: CGPoint) { switch self { case .topToBottom: return (CGPoint(x: 0.5, y: 0.0), CGPoint(x: 0.5, y: 1.0)) case .bottomToTop: return (CGPoint(x: 0.5, y: 1.0), CGPoint(x: 0.5, y: 0.0)) case .leftToRight: return (CGPoint(x: 1.0, y: 0.5), CGPoint(x: 0.0, y: 0.5)) case .rightToLeft: return (CGPoint(x: 0.0, y: 0.5), CGPoint(x: 1.0, y: 0.5)) case .topLeftToBottomRight: return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 1.0, y: 1.0)) case .topRightToBottomLeft: return (CGPoint(x: 1.0, y: 0.0), CGPoint(x: 0.0, y: 1.0)) case .bottomLeftToTopRight: return (CGPoint(x: 0.0, y: 1.0), CGPoint(x: 1.0, y: 0.0)) case .bottomRightToTopLeft: return (CGPoint(x: 1.0, y: 1.0), CGPoint(x: 0.0, y: 0.0)) case let .custom(start, end): return (start, end) } } }
mit
b71847be811804ffec6521c72c8688b9
27.763948
91
0.584005
4.476954
false
false
false
false
YifengBai/YuDou
YuDou/YuDou/Classes/Live/View/ScrollSegement.swift
1
8774
// // ScrollSegement.swift // YuDou // // Created by Bemagine on 2017/2/7. // Copyright ยฉ 2017ๅนด bemagine. All rights reserved. // import UIKit private let TitleNorColor : (CGFloat, CGFloat, CGFloat) = (220.0, 220.0, 220.0) private let TitleSelColor : (CGFloat, CGFloat, CGFloat) = (255.0, 255.0, 255.0) class ScrollSegement: UIView { /// ๆ ‡้ข˜ๆ•ฐ็ป„ var titles: [String]? /// ๆ ‡้ข˜labelๆ•ฐ็ป„ fileprivate var titleLabels: [UILabel] = [UILabel]() /// ๅบ•้ƒจๆปšๅŠจ็บฟๆก fileprivate lazy var scrollLine : UIView = { let line = UIView(frame: CGRect.zero) line.backgroundColor = UIColor.white return line }() /// label็ˆถ่ง†ๅ›พ fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 40)) scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.backgroundColor = UIColor.clear scrollView.bounces = false return scrollView }() // scrollView ็š„ contentSize ็š„ๅฎฝๅบฆ fileprivate var contenWidth : CGFloat = 0 /// ๅฝ“ๅ‰้€‰ไธญ็š„label var curSelectedIndex : Int = 0 /// ไผ ้€’ๅฝ“ๅ‰้€‰ไธญ็š„label็š„ไธ‹ๆ ‡ var selectedIndex: ((_ selectedIndex: Int) -> ())? init(frame: CGRect, titles: [String], norSelectedIndex: Int) { super.init(frame: frame) self.titles = titles self.curSelectedIndex = norSelectedIndex setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UI extension ScrollSegement { /// ่ฎพ็ฝฎ่ง†ๅ›พ fileprivate func setupView() { for subView in subviews { subView.removeFromSuperview() } scrollView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) addSubview(scrollView) // ่ฎพ็ฝฎlabel setupLabels() // ่ฎพ็ฝฎๅบ•้ƒจๆป‘ๅŠจ็บฟๆก setupScrollLine() } private func setupLabels() { let labelH : CGFloat = frame.height let labelY : CGFloat = 0 var labelX : CGFloat = 0 for (index, title) in titles!.enumerated() { // ่ฎก็ฎ—ๅญ—็ฌฆไธฒ็š„ๅฎฝๅบฆ๏ผŒ้ซ˜ๅบฆ let font : UIFont = UIFont.systemFont(ofSize: 15) let attributes = [NSFontAttributeName:font] let option = NSStringDrawingOptions.usesLineFragmentOrigin let labelW : CGFloat = title.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: labelH), options: option, attributes: attributes, context: nil).size.width + 20.0 let label = UILabel(frame: CGRect(x: labelX, y: labelY, width: labelW, height: labelH)) labelX = labelX + labelW label.text = title label.tag = index label.font = font label.textAlignment = .center // ้ป˜่ฎค้€‰ไธญ็ฌฌไบŒไธช if index == curSelectedIndex { label.textColor = UIColor(r: TitleSelColor.0, g: TitleSelColor.1, b: TitleSelColor.2) } else { label.textColor = UIColor(r: TitleNorColor.0, g: TitleNorColor.1, b: TitleNorColor.2) } label.backgroundColor = UIColor.clear // ๆทปๅŠ ไบ‹ไปถ label.isUserInteractionEnabled = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.labelTapAction(tapGes:))) label.addGestureRecognizer(tapGesture) scrollView.addSubview(label) titleLabels.append(label) } // ่ฎพ็ฝฎscrollView็š„contenSize contenWidth = labelX scrollView.contentSize = CGSize(width: labelX, height: 0) } private func setupScrollLine() { let label = titleLabels[1] scrollLine.frame = CGRect(x: label.frame.origin.x + 5, y: frame.height - 2.0, width: label.frame.width - 10, height: 2.0) addSubview(scrollLine) } } // MARK: - Action extension ScrollSegement { /// title label tap action @objc fileprivate func labelTapAction(tapGes : UITapGestureRecognizer) { guard let label = tapGes.view as? UILabel else { return } // ่Žทๅ–ไธŠไธ€ไธช้€‰ไธญ็š„label let sourceLabel = titleLabels[curSelectedIndex] curSelectedIndex = label.tag // ๆ›ดๆขlabel้ขœ่‰ฒ sourceLabel.textColor = UIColor(r: TitleNorColor.0, g: TitleNorColor.1, b: TitleNorColor.2) label.textColor = UIColor(r: TitleSelColor.0, g: TitleSelColor.1, b: TitleSelColor.2) titleLabelTransform(sourceLabel: sourceLabel, targetLabel: label) // ้—ญๅŒ…ไผ ๅ€ผ guard let selectedIndex = selectedIndex else { return } selectedIndex(curSelectedIndex) } } // MARK: - ๅ†…้ƒจๆ–นๆณ• extension ScrollSegement { /// ่ฎพ็ฝฎtitle label็š„ๅ˜ๆข fileprivate func titleLabelTransform(sourceLabel: UILabel, targetLabel label: UILabel) { let x = getScrollViewBoundsWith(label: label) // scrollView็š„contentOffSet scrollView.setContentOffset(CGPoint(x: x.scrollViewX, y: 0), animated: true) // ่ฎพ็ฝฎscrollLine็š„ไฝ็ฝฎ UIView.animate(withDuration: 0.5, animations: { self.scrollLine.frame = CGRect(x: x.scrollLineX + 5, y: self.scrollLine.frame.origin.y, width: label.frame.width - 10, height: self.scrollLine.frame.height) }) } /// ๆ นๆฎlabel่ฎก็ฎ—scrollViewๅฝ“ๅ‰็š„bounds็š„xไปฅๅŠๅฝ“ๅ‰scrollLine็š„frame็š„x fileprivate func getScrollViewBoundsWith(label: UILabel) -> (scrollViewX: CGFloat, scrollLineX: CGFloat) { let labelX = label.frame.origin.x let labelV = label.frame.width * 0.5 if labelX + label.frame.width * 0.5 > frame.width * 0.5 && contenWidth - label.frame.origin.x - label.frame.size.width * 0.5 > frame.width * 0.5 { // ๆญคๆ—ถlabelๅœจไธญ้—ด return (labelX + labelV - frame.width * 0.5, frame.width * 0.5 - labelV) } else if labelX + labelV <= frame.width * 0.5 { // ๆญคๆ—ถscrollViewๅœจๆœ€ๅทฆ่พน return (0, label.frame.origin.x) } else if contenWidth - labelX - labelV <= frame.width * 0.5 { // ๆญคๆ—ถscrollViewๅœจๆœ€ๅณ่พน return (contenWidth - frame.width, frame.width - (contenWidth - labelX)) } return (0, 0) } } // MARK: - ๅค–้ƒจๆ–นๆณ• extension ScrollSegement { func setTitleLabelWithProgress(_ progress: CGFloat, sourceIndex: Int, targetIndex: Int) { // ่ทŸๆ–ฐๅฝ“ๅ‰้€‰ไธญไธ‹ๆ ‡ curSelectedIndex = targetIndex // ๅ–ๅ‡บๅฝ“ๅ‰labelๅŠ็›ฎๆ ‡label let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] let sourceLabelW = sourceLabel.frame.width let targetLabelW = targetLabel.frame.width // ๆบlabelๆ—ถscrollView็š„bounds็š„xๅŠscrollLine็š„x let sourceX = getScrollViewBoundsWith(label: sourceLabel) // ็›ฎๆ ‡label็š„scrollView็š„bounds็š„xๅŠscrollLine็š„x let targetX = getScrollViewBoundsWith(label: targetLabel) // scrollViewไฝ็ฝฎๅ˜ๆข let progressX = sourceX.scrollViewX + (targetX.scrollViewX - sourceX.scrollViewX) * progress scrollView.contentOffset = CGPoint(x: progressX, y: 0) // scrollLine็š„frame็š„x let targetLineX = (targetX.scrollLineX - sourceX.scrollLineX) * progress + sourceX.scrollLineX // scrollLine็š„ๅฎฝๅบฆ let targetLineW = (targetLabelW - sourceLabelW) * progress + sourceLabelW - 10 // ่ฎพ็ฝฎscrollLine็š„ไฝ็ฝฎ self.scrollLine.frame = CGRect(x: targetLineX + 5 * progress, y: self.scrollLine.frame.origin.y, width: targetLineW, height: self.scrollLine.frame.height) // label้ขœ่‰ฒๅ˜ๆข sourceLabel.textColor = UIColor(r: (TitleNorColor.0 - TitleSelColor.0) * progress + TitleSelColor.0, g: (TitleNorColor.1 - TitleSelColor.1) * progress + TitleSelColor.1, b: (TitleNorColor.2 - TitleSelColor.2) * progress + TitleSelColor.2) targetLabel.textColor = UIColor(r: TitleNorColor.0 - (TitleNorColor.0 - TitleSelColor.0) * progress , g: TitleNorColor.1 - (TitleNorColor.1 - TitleSelColor.1) * progress, b: TitleNorColor.2 - (TitleNorColor.2 - TitleSelColor.2) * progress) } }
mit
c4e65fb0c42250de2c5c289d664f6736
34.281513
247
0.612123
4.348524
false
false
false
false
27629678/RxDemo
RxSwift.playground/Pages/Combining.xcplaygroundpage/Contents.swift
1
3001
//: [Previous Chapter: Filtering](@previous) import RxSwift import Foundation //:>ไปปไฝ•ไธ€ไธชObservableSequencesๆŠ›ๅ‡บError๏ผŒๆ†็ป‘ๅŽ็š„ObservableSequence็ซ‹ๅณๅœๆญข let disposeBag = DisposeBag() let error = NSError(domain: "playground", code: 404, userInfo: ["key" : "description"]) //:![CombineLatest](RxSwift_CombineLatest.png) run("Combine") { let source1 = PublishSubject<Int>() let source2 = PublishSubject<String>() Observable .combineLatest(source2, source1, resultSelector: { "N:\($0), A:\($1)" }) .subscribe({print($0)}) .addDisposableTo(disposeBag) source1.onNext(18) source2.onNext("xiao ming") // source2(error) source2.onNext("xiao hong") source1.onNext(20) } //:![Merge](RxSwift_Merge.png) run("Merge") { let source1 = PublishSubject<String>() let source2 = PublishSubject<String>() Observable .of(source1, source2) .merge() .subscribe({print($0)}) .addDisposableTo(disposeBag) source1.onNext("18") source2.onNext("xiao ming") // source1.onError(error) source2.onNext("xiao hong") source1.onNext("20") } //:>่ฆMerge็š„Observables่ฆๆฑ‚ไธบๅŒไธ€็ฑปๅž‹๏ผŒๅณObservable<Element>ไธญ**Element**็›ธๅŒ //:![StartWith](RxSwift_StartWith.png) run("StartWith") { Observable<Int> .range(start: 1, count: 2) .startWith(0) .subscribe({print($0)}) .addDisposableTo(disposeBag) } //:![Zip](RxSwift_Zip.png) run("Zip") { let source1 = PublishSubject<String>() let source2 = PublishSubject<String>() Observable .zip(source2, source1, resultSelector: { "N:\($0), A:\($1)" }) .subscribe({print($0)}) .addDisposableTo(disposeBag) source1.onNext("18") source2.onNext("xiao ming") source1.onNext("19") source1.onNext("20") source1.onNext("21") source2.onNext("xiao hong") source1.onNext("22") } //:![Switch](RxSwift_Switch.png) run("Switch") { runInfinite() let source1 = PublishSubject<String>() let source2 = PublishSubject<String>() Observable .of(source1, source2) .switchLatest() .subscribe({print($0)}) .addDisposableTo(disposeBag) // delay(0.1, action: { // source2.onNext("xiao zhang") // }) delay(0.2, action: { source1.onNext("18") }) delay(0.3, action: { source1.onNext("19") }) delay(0.6, action: { source1.onNext("20") }) delay(0.4, action: { source2.onNext("xiao ming") }) delay(0.9, action: { source2.onNext("xiao hong") }) delay(1.2, action: { source1.onNext("21") }) } delay(5) { stopRun() } //:>ไธŽๅ›พ็‰‡ๆ่ฟฐไธ็ฌฆ๏ผŒๆœช้ชŒ่ฏๅ…ถๅฎž็Žฐๆ–นๆณ• //: [Next Chapter: ErrorHandling](@next)
mit
a8b2243e452541868ffe2de17b8827f5
20.404412
64
0.56338
3.64787
false
false
false
false
luzefeng/iOS8-day-by-day
39-watchkit/NightWatch/NightWatch WatchKit Extension/InterfaceController.swift
22
2231
// // Copyright 2014 Scott Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import WatchKit import Foundation import NightWatchData class InterfaceController: WKInterfaceController { var quotes = [Quote]() var currentQuote: Int = 0 let quoteGenerator = NightWatchQuotes() var timer: NSTimer? let quoteCycleTime: NSTimeInterval = 30 @IBOutlet weak var quoteLabel: WKInterfaceLabel! @IBOutlet weak var quoteChangeTimer: WKInterfaceTimer! override func awakeWithContext(context: AnyObject!) { if quotes.count != 5 { quotes = quoteGenerator.randomQuotes(5) } quoteLabel.setText(quotes[currentQuote]) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() timer?.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(quoteCycleTime, target: self, selector: "fireTimer:", userInfo: nil, repeats: true) quoteChangeTimer.setDate(NSDate(timeIntervalSinceNow: quoteCycleTime)) quoteChangeTimer.start() } override func didDeactivate() { // This method is called when watch view controller is no longer visible timer?.invalidate() super.didDeactivate() } @IBAction func handleSkipButtonPressed() { timer?.fire() timer?.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(quoteCycleTime, target: self, selector: "fireTimer:", userInfo: nil, repeats: true) } @objc func fireTimer(t: NSTimer) { currentQuote = (currentQuote + 1) % quotes.count quoteLabel.setText(quotes[currentQuote]) quoteChangeTimer.setDate(NSDate(timeIntervalSinceNow: quoteCycleTime)) quoteChangeTimer.start() } }
apache-2.0
87e87bc0a774136bdcb11792f584670a
30.871429
134
0.731511
4.525355
false
false
false
false
zhihuilong/ZHTabBarController
ZHTabBarController/Classes/ZHTabBarController.swift
1
2927
// // CenterViewController.swift // ZHSideMenu // // Created by Sunny on 15/4/4. // Copyright (c) 2015ๅนด Sunny. All rights reserved. // import UIKit @objc public protocol ZHTabBarControllerProtocol { var childViewControllers: [UIViewController] { get } var items: [ZHItemData] { get } } @objc public enum ZHTabBarStyle: Int { case Default // build-in case CentralButton // central button like Instagram } public final class ZHItemData: NSObject { let icon: String let selectedIcon: String let title: String? public init(icon: String, selectedIcon: String, title: String? = nil) { self.icon = icon self.selectedIcon = selectedIcon self.title = title super.init() } } public class ZHTabBarController: UIViewController { public var delegate: ZHTabBarControllerProtocol! public var tabBarColor = UIColor.white public var itemTitleColor = UIColor.black public var itemSelectedTitleColor = UIColor.black public var allowSwitchTabClosure: ((_ index: Int) -> Bool)? fileprivate var selectedVC:UIViewController? fileprivate let contentView = UIView() fileprivate let style: ZHTabBarStyle fileprivate let tabBarHeight: CGFloat fileprivate let tabBar: ZHTabBar public init(style: ZHTabBarStyle = .Default, tabBarHeight: CGFloat = 50) { self.style = style self.tabBarHeight = tabBarHeight self.tabBar = ZHTabBar(height: tabBarHeight) super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ZHTabBarController { public override func viewDidLoad() { super.viewDidLoad() for vc in delegate.childViewControllers { addChildViewController(vc) } view.addSubview(contentView) contentView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - tabBarHeight) view.addSubview(tabBar) for item in delegate.items { tabBar.add(item: item, titleColor: itemTitleColor, selectedTitleColor: itemSelectedTitleColor) } tabBar.backgroundColor = tabBarColor tabBar.itemClickBlock = { index in let newVC = self.childViewControllers[index] if newVC == self.selectedVC { return } self.selectedVC?.view.removeFromSuperview() self.contentView.addSubview(newVC.view) newVC.view.frame = self.contentView.bounds self.selectedVC = newVC self.title = self.selectedVC!.title } tabBar.allowSwitchTabClosure = allowSwitchTabClosure switchTab(AtIndex: 0) // default selection } public func switchTab(AtIndex index: Int) { tabBar.selectedIndex = index } }
mit
16207c0671a6ebbd6204487a244a2ff5
30.117021
106
0.652308
4.771615
false
false
false
false
argent-os/argent-ios
app-ios/BankWebLoginViewController.swift
1
6199
// // BankWebLoginViewController.swift // app-ios // // Created by Sinan Ulkuatam on 8/29/16. // Copyright ยฉ 2016 Sinan Ulkuatam. All rights reserved. // import Foundation import UIKit import WebKit import CWStatusBarNotification import SwiftyJSON import Alamofire import Crashlytics class BankWebLoginViewController: UIViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler { @IBOutlet var containerView : UIView! var webView: WKWebView? override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func loadView() { super.loadView() let screen = UIScreen.mainScreen().bounds let screenWidth = screen.width let screenHeight = screen.height let configuration = WKWebViewConfiguration() let controller = WKUserContentController() controller.addScriptMessageHandler(self, name: "observe") configuration.userContentController = controller self.webView = WKWebView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight), configuration: configuration) self.webView?.contentMode = .ScaleAspectFit self.webView?.UIDelegate = self self.view = self.webView! } override func viewDidLoad() { super.viewDidLoad() if ENVIRONMENT == "DEV" { let url = NSURL(string:"http://localhost:5000/link") let req = NSURLRequest(URL:url!) self.webView!.loadRequest(req) } else if ENVIRONMENT == "PROD" { let url = NSURL(string:"https://www.argentapp.com/link") let req = NSURLRequest(URL:url!) self.webView!.loadRequest(req) } } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { // print("Received \(message.body)") // convert the json to an nsdict let _ = String(message.body["access_token"].map({ (unwrap) -> () in self.updateUserPlaidToken(unwrap) })) let _ = String(message.body["stripe_bank_account_token"].map({ (unwrap) -> () in self.linkBankToStripe(unwrap) })) } func updateUserPlaidToken(accessToken: AnyObject) { if(userAccessToken != nil) { User.getProfile { (user, NSError) in let endpoint = API_URL + "/profile/" + (user?.id)! let headers = [ "Authorization": "Bearer " + (userAccessToken as! String), "Content-Type": "application/json" ] let plaidObj = [ "access_token" : accessToken ] let plaidNSDict = plaidObj as NSDictionary //no error message let parameters : [String : AnyObject] = [ "plaid" : plaidNSDict ] Alamofire.request(.PUT, endpoint, parameters: parameters, encoding: .JSON, headers: headers).responseJSON { response in switch response.result { case .Success: Answers.logCustomEventWithName("Plaid token update success", customAttributes: [:]) case .Failure(let error): print(error) Answers.logCustomEventWithName("Plaid token update failed", customAttributes: [ "error": error.localizedDescription ]) } } } } } func linkBankToStripe(bankToken: AnyObject) { if(userAccessToken != nil) { User.getProfile { (user, NSError) in let endpoint = API_URL + "/stripe/" + user!.id + "/external_account" let headers = [ "Authorization": "Bearer " + (userAccessToken as! String), "Content-Type": "application/json" ] let parameters = ["external_account": bankToken] Alamofire.request(.POST, endpoint, parameters: parameters, encoding: .JSON, headers: headers).responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let data = JSON(value) if data["error"]["message"].stringValue != "" { showAlert(.Error, title: "Error", msg: data["error"]["message"].stringValue) self.dismissViewControllerAnimated(true, completion: nil) Answers.logCustomEventWithName("Bank account link failure", customAttributes: [:]) } else { showAlert(.Success, title: "Success", msg: "Your bank account is now linked!") self.dismissViewControllerAnimated(true, completion: nil) Answers.logCustomEventWithName("Link bank to Stripe success", customAttributes: [:]) } } case .Failure(let error): print(error) self.dismissViewControllerAnimated(true, completion: nil) Answers.logCustomEventWithName("Link bank to Stripe failed", customAttributes: [ "error": error.localizedDescription ]) } } } } } }
mit
0a692ece8fbbfb6b667b840f1779fb05
37.265432
131
0.496934
6.106404
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/16661-getselftypeforcontainer.swift
11
2394
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func a<T where g func f: e =b class a<T where f } protocol A { let : e let t: b func a class A.d<T { class c, let i: d () -> U) typealias e { case c, let t: a { func f: Int -> U) struct S<T , A { func f: e : e return "\() { struct A.b<T>: a { struct Q<T { protocol P { return " typealias e : e { struct B return "[Void{ } { func i: BooleanType, A { class c(f: P private let t: T> enum b { let t: c, let a { { enum k { class { let a { struct e func a protocol A : BooleanType, A : a { struct Q<b.h class B { println(f: P struct Q<T where I.h protocol A { } } for b: NSObject { let i() -> () { protocol A : a { return "\() { case } struct S<T where I : a { } } typealias e : BooleanType, A { struct S<T : a { class struct A.c, typealias b protocol P { class A<T> let a { func i: Array { class if true { protocol A { return "[Void{ let t: a { var d where h: BooleanType, A : BooleanType, A { } func a<T where f: a { class b<T : a { func a func f: c, class func f: e : c { let b class A<T { { } struct S<T { func a return "\() -> U) let i: a { { for b: a<T where T : e class b class class return "\(f: e<T { { let end = { } } func a<d = [Void{ return "[Void{ class b { func i() { func a<T where f: C { { func f: a { } func a { { { } } protocol A { } let t: e { case c> Bool { return "\(f: Array { { protocol A { var d where e : A<c, func a<T where T where T where g<d where I.d.d.d<T { class func i: a { return " enum A : P enum b { let end = { { class a enum S<T) { class b: b class a class a { class class a { } var d = { func d.d.c, struct S<d where I : BooleanType, A { class a } let t: S<h class struct A : a { class b deinit { } struct Q<b class b class a let : BooleanType, A : a { protocol A { println() { struct S<c { } protocol P { func f: e<T { func a } { return "[Void{ class b } protocol P { class b { typealias e { protocol P { struct Q<T where S<d = " return "\(" { class b let t: c() -> U) func a<T where T where f: c> Bool { enum B { let a { var d where g let t: a { { func f: c("[Void{ let end = compose() { func b var d where T where I.h let t: Int -> (self.h: e typealias e : c, return ""[Void{ { struct S<T { struct Q<T { case c, class c, } func i: b return " let i(T) -> Bool { class a } { let i: e<T where
mit
931d1f7dd22cf55dad7fcbf5b0659b0e
10.735294
87
0.603175
2.396396
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/Exporters/Zipkin/ZipkinTraceExporterOptions.swift
1
853
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation public struct ZipkinTraceExporterOptions { let endpoint: String let timeoutSeconds: TimeInterval let serviceName: String let useShortTraceIds: Bool let additionalHeaders: [String:String] public init(endpoint: String = "http://localhost:9411/api/v2/spans", serviceName: String = "Open Telemetry Exporter", timeoutSeconds: TimeInterval = 10.0, useShortTraceIds: Bool = false, additionalHeaders: [String:String] = [String:String]()) { self.endpoint = endpoint self.serviceName = serviceName self.timeoutSeconds = timeoutSeconds self.useShortTraceIds = useShortTraceIds self.additionalHeaders = additionalHeaders } }
apache-2.0
556275a4d21aec988e6614c5e5590ab7
29.464286
73
0.670574
4.792135
false
false
false
false
daggmano/photo-management-studio
src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/DatabaseManager.swift
1
2855
// // DatabaseManager.swift // Photo Management Studio // // Created by Darren Oster on 1/04/2016. // Copyright ยฉ 2016 Criterion Software. All rights reserved. // import Foundation public class DatabaseManager { public static func setupReplication(remoteAddress: String, serverId: String) { let localName = "photos_\(serverId)" NSUserDefaults.standardUserDefaults().setObject(localName, forKey: "CouchDbLocalName") Event.emit("local-database-changed", obj: NSObject()) // Need to test if local DB exists, and create if not let couchDb = CouchDb(url: "http://localhost:5984", name: nil, password: nil) couchDb.list { listResponse in switch listResponse { case .Error(let error): print(error) case .Success(let data): if (!data.databases.contains(localName)) { couchDb.createDatabase(localName, done: { createDatabaseResponse in switch createDatabaseResponse { case .Error(let error): print(error) case .Success: setupReplicationActual(remoteAddress, serverId: serverId, couchDb: couchDb) } }) } else { setupReplicationActual(remoteAddress, serverId: serverId, couchDb: couchDb) } } } } private static func setupReplicationActual(remoteAddress: String, serverId: String, couchDb: CouchDb) { let remote = "http://\(remoteAddress):5984/photos" let localName = "photos_\(serverId)" let local = "http://localhost:5984/\(localName)" AppDelegate.getInstance()?.setRemoteDatabaseAddress(remoteAddress); // Need to test if local DB exists, and create if not let remoteToLocalName = "repPhotosR2L_\(serverId)" let localToRemoteName = "repPhotosL2R_\(serverId)" var request1 = CouchDb.ReplicationRequest(replicationId: remoteToLocalName, source: remote, target: local) request1.continuous = true var request2 = CouchDb.ReplicationRequest(replicationId: localToRemoteName, source: local, target: remote) request2.continuous = true couchDb.replicate(request1) { response in switch response { case .Error(let error): print(error) case .Success: print("OK") } } couchDb.replicate(request2) { response in switch response { case .Error(let error): print(error) case .Success: print("OK") } } } }
mit
3384ad600eb88ba2562d9d52c2c106ae
36.064935
114
0.562018
4.98951
false
false
false
false
Nirma/UIDeviceComplete
Tests/DeviceFamilyTests.swift
1
2320
// // DeviceFamilyTests.swift // // Copyright (c) 2017-2019 Nicholas Maccharoli // // 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. @testable import UIDeviceComplete import XCTest class DeviceFamilyTests: XCTestCase { func testDeviceFamilyIPhone() { let deviceFamily = DeviceFamily(rawValue: "iPhone") XCTAssert(deviceFamily == .iPhone, "DeviceFamily - .iPhone is failing") } func testDeviceFamilyIPod() { let deviceFamily = DeviceFamily(rawValue: "iPod") XCTAssert(deviceFamily == .iPod, "DeviceFamily - .iPod is failing") } func testDeviceFamilyIPad() { let deviceFamily = DeviceFamily(rawValue: "iPad") XCTAssert(deviceFamily == .iPad, "DeviceFamily - .iPad is failing") } func testInvalidDeviceFamily() { let deviceFamily = DeviceFamily(rawValue: "Apple II") XCTAssert(deviceFamily == .unknown, "DeviceFamily - .unknown is failing") } func testDeviceIsSimulator() { let deviceFamily = DeviceFamily(rawValue: "iPhone") #if arch(i386) || arch(x86_64) XCTAssert(deviceFamily.isSimulator, "DeviceFamily - .isSimulator is failing") #else XCTAssert(!(deviceFamily.isSimulator), "DeviceFamily - .isSimulator is failing") #endif } }
mit
3d210f25b0e926f128ad0788e0e9747c
39
88
0.712069
4.470135
false
true
false
false
dche/FlatColor
Sources/Color.swift
1
1067
// // FlatColor - Color.swift // // The Color protocol. // // Copyright (c) 2017 The FlatColor authors. // Licensed under MIT License. import FlatUtil import GLMath /// Generic color type. public protocol Color: Equatable, Random, ApproxEquatable where InexactNumber == Float { /// Constructs a color from a RGB color. init (rgb: Rgb) /// The corresponding RGB color. var rgbColor: Rgb { get } /// The `alpha` value. var alpha: Float { get } /// The vector representation of `self`. var vector: vec4 { get } } extension Color { public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.vector == rhs.vector } public func isClose(to other: Self, tolerance: Float) -> Bool { return self.vector.isClose(to: other.vector, tolerance: tolerance) } /// Returns `true` if `self`'s `alpha` is less than `1`. public var isTransparent: Bool { return self.alpha < 1 } /// Returns `true` if `self` is _NOT_ transparent. public var isOpaque: Bool { return !isTransparent } }
mit
f93ce38cb684537114f5a2bbee634a35
22.711111
74
0.637301
3.851986
false
false
false
false
mozilla-mobile/focus-ios
Blockzilla/Extensions/URLExtensions.swift
1
16578
/* 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 private struct ETLDEntry: CustomStringConvertible { let entry: String var isNormal: Bool { return isWild || !isException } var isWild: Bool = false var isException: Bool = false init(entry: String) { self.entry = entry self.isWild = entry.hasPrefix("*") self.isException = entry.hasPrefix("!") } fileprivate var description: String { return "{ Entry: \(entry), isWildcard: \(isWild), isException: \(isException) }" } } private typealias TLDEntryMap = [String: ETLDEntry] private func loadEntriesFromDisk() -> TLDEntryMap? { guard let filepath = Bundle.main.path(forResource: "effective_tld_names", ofType: "dat"), let data = try? String(contentsOfFile: filepath) else { return nil } let lines = data.components(separatedBy: "\n") let trimmedLines = lines.filter { !$0.hasPrefix("//") && $0 != "\n" && $0 != "" } var entries = TLDEntryMap() for line in trimmedLines { let entry = ETLDEntry(entry: line) let key: String if entry.isWild { // Trim off the '*.' part of the line key = String(line[line.index(line.startIndex, offsetBy: 2)...]) } else if entry.isException { // Trim off the '!' part of the line key = String(line[line.index(line.startIndex, offsetBy: 1)...]) } else { key = line } entries[key] = entry } return entries } private var etldEntries: TLDEntryMap? = { return loadEntriesFromDisk() }() // MARK: - Local Resource URL Extensions extension URL { public func allocatedFileSize() -> Int64 { // First try to get the total allocated size and in failing that, get the file allocated size return getResourceLongLongForKey(URLResourceKey.totalFileAllocatedSizeKey.rawValue) ?? getResourceLongLongForKey(URLResourceKey.fileAllocatedSizeKey.rawValue) ?? 0 } public func getResourceValueForKey(_ key: String) -> Any? { let resourceKey = URLResourceKey(key) let keySet = Set<URLResourceKey>([resourceKey]) var val: Any? do { let values = try resourceValues(forKeys: keySet) val = values.allValues[resourceKey] } catch _ { return nil } return val } public func getResourceLongLongForKey(_ key: String) -> Int64? { return (getResourceValueForKey(key) as? NSNumber)?.int64Value } public func getResourceBoolForKey(_ key: String) -> Bool? { return getResourceValueForKey(key) as? Bool } public var isRegularFile: Bool { return getResourceBoolForKey(URLResourceKey.isRegularFileKey.rawValue) ?? false } public func lastComponentIsPrefixedBy(_ prefix: String) -> Bool { return (pathComponents.last?.hasPrefix(prefix) ?? false) } } // The list of permanent URI schemes has been taken from http://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml private let permanentURISchemes = ["aaa", "aaas", "about", "acap", "acct", "cap", "cid", "coap", "coaps", "crid", "data", "dav", "dict", "dns", "example", "file", "ftp", "geo", "go", "gopher", "h323", "http", "https", "iax", "icap", "im", "imap", "info", "ipp", "ipps", "iris", "iris.beep", "iris.lwz", "iris.xpc", "iris.xpcs", "jabber", "ldap", "mailto", "mid", "msrp", "msrps", "mtqp", "mupdate", "news", "nfs", "ni", "nih", "nntp", "opaquelocktoken", "pkcs11", "pop", "pres", "reload", "rtsp", "rtsps", "rtspu", "service", "session", "shttp", "sieve", "sip", "sips", "sms", "snmp", "soap.beep", "soap.beeps", "stun", "stuns", "tag", "tel", "telnet", "tftp", "thismessage", "tip", "tn3270", "turn", "turns", "tv", "urn", "vemmi", "vnc", "ws", "wss", "xcon", "xcon-userid", "xmlrpc.beep", "xmlrpc.beeps", "xmpp", "z39.50r", "z39.50s"] extension URL { public func withQueryParams(_ params: [URLQueryItem]) -> URL { var components = URLComponents(url: self, resolvingAgainstBaseURL: false)! var items = (components.queryItems ?? []) for param in params { items.append(param) } components.queryItems = items return components.url! } public func withQueryParam(_ name: String, value: String) -> URL { var components = URLComponents(url: self, resolvingAgainstBaseURL: false)! let item = URLQueryItem(name: name, value: value) components.queryItems = (components.queryItems ?? []) + [item] return components.url! } public func getQuery() -> [String: String] { var results = [String: String]() let keyValues = self.query?.components(separatedBy: "&") if keyValues?.count ?? 0 > 0 { for pair in keyValues! { let kv = pair.components(separatedBy: "=") if kv.count > 1 { results[kv[0]] = kv[1] } } } return results } public static func getQuery(url: URL) -> [String: String] { var results = [String: String]() let keyValues = url.query?.components(separatedBy: "&") if keyValues?.count ?? 0 > 0 { for pair in keyValues! { let kv = pair.components(separatedBy: "=") if kv.count > 1 { results[kv[0]] = kv[1] } } } return results } public var hostPort: String? { if let host = self.host { if let port = (self as NSURL).port?.int32Value { return "\(host):\(port)" } return host } return nil } public var origin: String? { guard isWebPage(includeDataURIs: false), let hostPort = self.hostPort, let scheme = scheme else { return nil } return "\(scheme)://\(hostPort)" } /** * Returns the second level domain (SLD) of a url. It removes any subdomain/TLD * * E.g., https://m.foo.com/bar/baz?noo=abc#123 => foo **/ public var hostSLD: String { guard let publicSuffix = self.publicSuffix, let baseDomain = self.baseDomain else { return self.normalizedHost ?? self.absoluteString } return baseDomain.replacingOccurrences(of: ".\(publicSuffix)", with: "") } public var normalizedHostAndPath: String? { return normalizedHost.flatMap { $0 + self.path } } public var absoluteDisplayString: String { var urlString = self.absoluteString // For http URLs, get rid of the trailing slash if the path is empty or '/' if (self.scheme == "http" || self.scheme == "https") && (self.path == "/") && urlString.hasSuffix("/") { urlString = String(urlString[..<urlString.index(urlString.endIndex, offsetBy: -1)]) } // If it's basic http, strip out the string but leave anything else in if urlString.hasPrefix("http://") { return String(urlString[urlString.index(urlString.startIndex, offsetBy: 7)...]) } else { return urlString } } /// String suitable for displaying outside of the app, for example in notifications, were Data Detectors will /// linkify the text and make it into a openable-in-Safari link. public var absoluteDisplayExternalString: String { return self.absoluteDisplayString.replacingOccurrences(of: ".", with: "\u{2024}") } /** Returns the base domain from a given hostname. The base domain name is defined as the public domain suffix with the base private domain attached to the front. For example, for the URL www.bbc.co.uk, the base domain would be bbc.co.uk. The base domain includes the public suffix (co.uk) + one level down (bbc). :returns: The base domain string for the given host name. */ public var baseDomain: String? { guard host != nil else { return absoluteDisplayString } guard !isIPv4 && !isIPv6, let host = host else { return host } // If this is just a hostname and not a FQDN, use the entire hostname. if !host.contains(".") { return host } return publicSuffixFromHost(host, withAdditionalParts: 1) ?? host } /** * Returns just the domain, but with the same scheme, and a trailing '/'. * * E.g., https://m.foo.com/bar/baz?noo=abc#123 => https://foo.com/ * * Any failure? Return this URL. */ public var domainURL: URL { if let normalized = self.normalizedHost { // Use NSURLComponents instead of NSURL since the former correctly preserves // brackets for IPv6 hosts, whereas the latter escapes them. var components = URLComponents() components.scheme = self.scheme components.port = self.port components.host = normalized components.path = "/" return components.url ?? self } return self } public var normalizedHost: String? { // Use components.host instead of self.host since the former correctly preserves // brackets for IPv6 hosts, whereas the latter strips them. guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false), var host = components.host, host != "" else { return nil } if let range = host.range(of: "^(www|mobile|m)\\.", options: .regularExpression) { host.replaceSubrange(range, with: "") } return host } /** Returns the public portion of the host name determined by the public suffix list found here: https://publicsuffix.org/list/. For example for the url www.bbc.co.uk, based on the entries in the TLD list, the public suffix would return co.uk. :returns: The public suffix for within the given hostname. */ public var publicSuffix: String? { return host.flatMap { publicSuffixFromHost($0, withAdditionalParts: 0) } } public func isWebPage(includeDataURIs: Bool = true) -> Bool { let schemes = includeDataURIs ? ["http", "https", "data"] : ["http", "https"] return scheme.map { schemes.contains($0) } ?? false } public func isWebPage() -> Bool { let schemes = ["http", "https"] if let scheme = scheme, schemes.contains(scheme) { return true } return false } // This helps find local urls that we do not want to show loading bars on. // These utility pages should be invisible to the user public var isLocalUtility: Bool { guard self.isLocal else { return false } let utilityURLs = ["/errors", "/about/sessionrestore", "/about/home", "/reader-mode"] return utilityURLs.contains { self.path.hasPrefix($0) } } public var isLocal: Bool { guard isWebPage(includeDataURIs: false) else { return false } // iOS forwards hostless URLs (e.g., http://:6571) to localhost. guard let host = host, !host.isEmpty else { return true } return host.lowercased() == "localhost" || host == "127.0.0.1" } public var isIPv4: Bool { let ipv4Pattern = #"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"# return host?.range(of: ipv4Pattern, options: .regularExpression) != nil } public var isIPv6: Bool { return host?.contains(":") ?? false } /** Returns whether the URL's scheme is one of those listed on the official list of URI schemes. This only accepts permanent schemes: historical and provisional schemes are not accepted. */ public var schemeIsValid: Bool { guard let scheme = scheme else { return false } return permanentURISchemes.contains(scheme.lowercased()) } public func havingRemovedAuthorisationComponents() -> URL { guard var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: false) else { return self } urlComponents.user = nil urlComponents.password = nil if let url = urlComponents.url { return url } return self } } // MARK: Private Helpers private extension URL { func publicSuffixFromHost( _ host: String, withAdditionalParts additionalPartCount: Int) -> String? { if host.isEmpty { return nil } // Check edge case where the host is either a single or double '.'. if host.isEmpty || NSString(string: host).lastPathComponent == "." { return "" } /** * The following algorithm breaks apart the domain and checks each sub domain against the effective TLD * entries from the effective_tld_names.dat file. It works like this: * * Example Domain: test.bbc.co.uk * TLD Entry: bbc * * 1. Start off by checking the current domain (test.bbc.co.uk) * 2. Also store the domain after the next dot (bbc.co.uk) * 3. If we find an entry that matches the current domain (test.bbc.co.uk), perform the following checks: * i. If the domain is a wildcard AND the previous entry is not nil, then the current domain matches * since it satisfies the wildcard requirement. * ii. If the domain is normal (no wildcard) and we don't have anything after the next dot, then * currentDomain is a valid TLD * iii. If the entry we matched is an exception case, then the base domain is the part after the next dot * * On the next run through the loop, we set the new domain to check as the part after the next dot, * update the next dot reference to be the string after the new next dot, and check the TLD entries again. * If we reach the end of the host (nextDot = nil) and we haven't found anything, then we've hit the * top domain level so we use it by default. */ let tokens = host.components(separatedBy: ".") let tokenCount = tokens.count var suffix: String? var previousDomain: String? = nil var currentDomain: String = host for offset in 0..<tokenCount { // Store the offset for use outside of this scope so we can add additional parts if needed let nextDot: String? = offset + 1 < tokenCount ? tokens[offset + 1..<tokenCount].joined(separator: ".") : nil if let entry = etldEntries?[currentDomain] { if entry.isWild && (previousDomain != nil) { suffix = previousDomain break } else if entry.isNormal || (nextDot == nil) { suffix = currentDomain break } else if entry.isException { suffix = nextDot break } } previousDomain = currentDomain if let nextDot = nextDot { currentDomain = nextDot } else { break } } var baseDomain: String? if additionalPartCount > 0 { if let suffix = suffix { // Take out the public suffixed and add in the additional parts we want. let literalFromEnd: NSString.CompareOptions = [.literal, // Match the string exactly. .backwards, // Search from the end. .anchored] // Stick to the end. let suffixlessHost = host.replacingOccurrences(of: suffix, with: "", options: literalFromEnd, range: nil) let suffixlessTokens = suffixlessHost.components(separatedBy: ".").filter { $0 != "" } let maxAdditionalCount = max(0, suffixlessTokens.count - additionalPartCount) let additionalParts = suffixlessTokens[maxAdditionalCount..<suffixlessTokens.count] let partsString = additionalParts.joined(separator: ".") baseDomain = [partsString, suffix].joined(separator: ".") } else { return nil } } else { baseDomain = suffix } return baseDomain } }
mpl-2.0
2767c780b6e565f0f16ec8435a380bc8
38.099057
835
0.592894
4.32846
false
false
false
false
daggmano/photo-management-studio
src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/NetworkSupervisor.swift
1
7076
// // NetworkSupervisor.swift // Photo Management Studio // // Created by Darren Oster on 31/03/2016. // Copyright ยฉ 2016 Criterion Software. All rights reserved. // import Alamofire import CocoaAsyncSocket enum ConnectionState: String { var description: String { return self.rawValue } case Disconnected = "Disconnected" case Connecting = "Connecting" case Connected = "Connected" } protocol ServerInfoReceivedDelegate { func onServerInfoReceived(message: NSData) func onDbServerInfoReceived(message: ServerInfoResponseObject) } protocol NetworkConnectionStatusDelegate { func onServerConnectionStatusChanged(status: ConnectionState) func setServerUrl(url: String) } class NetworkSupervisor: NSObject, ServerInfoReceivedDelegate { var _delegate: NetworkConnectionStatusDelegate var _connectionStatus: ConnectionState var _watchdogTimer: NSTimer? var _socketIn: InSocket! var _socketOut: OutSocket! var _serverPort: UInt16! var _imageServerAddress: String! var _imageServerPort: UInt16! required init(delegate: NetworkConnectionStatusDelegate) { _delegate = delegate _connectionStatus = .Disconnected _delegate.onServerConnectionStatusChanged(_connectionStatus) _imageServerPort = 0 _imageServerAddress = "" super.init() _socketIn = InSocket.init(delegate: self, port: 0) _serverPort = _socketIn.getPort() NSLog("Server Port is \(_serverPort)") _socketOut = OutSocket.init(ipAddress: "255.255.255.255", port: Config.udpSearchPort) setupWatchdog(500, repeats: true) } private func setupWatchdog(timeout: Int, repeats: Bool) { dispatch_async(dispatch_get_main_queue()) { [unowned self] in if let watchdogTimer = self._watchdogTimer { watchdogTimer.invalidate() } self._watchdogTimer = NSTimer.scheduledTimerWithTimeInterval(Double(timeout) / 1000.0, target: self, selector: #selector(NetworkSupervisor.onWatchdogTimer(_:)), userInfo: nil, repeats: repeats) } } func onWatchdogTimer(sender: NSTimer!) { switch (_connectionStatus) { case .Disconnected: print(".Disconnected") attemptConnection() break case .Connecting: print(".Connecting") pingServer() break case .Connected: print(".Connected") pingServer() break } } func onServerInfoReceived(message: NSData) { do { if let json = try NSJSONSerialization.JSONObjectWithData(message, options: .AllowFragments) as? [String: AnyObject] { let networkMessage = NetworkMessageObject.init(json: json) if let messageType = networkMessage.messageType { switch (messageType) { case .ServerSpecification: let serverSpec = NetworkMessageObjectGeneric<ServerSpecificationObject>.init(json: json) guard let message = serverSpec.message, let serverAddress = message.serverAddress, let serverPort = message.serverPort else { break } _imageServerAddress = serverAddress _imageServerPort = serverPort _connectionStatus = .Connecting _delegate.onServerConnectionStatusChanged(_connectionStatus) break } } } } catch {} } func onDbServerInfoReceived(message: ServerInfoResponseObject) { print(message.data?.serverId) print(message.data?.serverName) if let serverId = message.data?.serverId { DatabaseManager.setupReplication(_imageServerAddress, serverId: serverId) _connectionStatus = .Connected _delegate.onServerConnectionStatusChanged(_connectionStatus) _delegate.setServerUrl("http://\(_imageServerAddress):\(_imageServerPort)") } } func attemptConnection() { print("attemptConnection: _serverPort = \(_serverPort)") let discoveryObject = NetworkDiscoveryObject(identifier: "Photo.Management.Studio", clientSocketPort: _serverPort) _socketOut!.send(discoveryObject.toJSON()); } func pingServer() { print("pingServer...") let url = "http://\(_imageServerAddress):\(_imageServerPort)/api/ping" Alamofire.request(.GET, url).responseJSON { response in if response.result.isFailure { self._connectionStatus = .Disconnected self.setupWatchdog(500, repeats: true) self._delegate.onServerConnectionStatusChanged(self._connectionStatus) } else if response.result.isSuccess { if let json = response.result.value as? [String: AnyObject] { let pingResponse = PingResponseObject(json: json) if let responseData = pingResponse.data { print(responseData.serverDateTime) if (self._connectionStatus == .Connecting) { self.getDbServerId() self.setupWatchdog(1000, repeats: false) } else { self.setupWatchdog(5000, repeats: false) } } else { self._connectionStatus = .Disconnected self.setupWatchdog(500, repeats: true) self._delegate.onServerConnectionStatusChanged(self._connectionStatus) print("unable to get responseData") } } } } } func getDbServerId() { print("getDbServerId...") let url = "http://\(_imageServerAddress):\(_imageServerPort)/api/serverInfo" let request = NSMutableURLRequest(URL: NSURL(string: url)!) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in do { if let data = data { if let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String: AnyObject] { let serverInfoResponse = ServerInfoResponseObject(json: json) self.onDbServerInfoReceived(serverInfoResponse) } } } catch {} }) task.resume() } }
mit
ea92a4aa85aa5bc4986239c6d66aac38
35.848958
205
0.570459
5.535994
false
false
false
false
LaurentiuUngur/LUAutocompleteView
LUAutocompleteViewExample/LUAutocompleteViewExample/ViewController.swift
1
1580
// // ViewController.swift // LUAutocompleteViewExample // // Created by Laurentiu Ungur on 24/04/2017. // Copyright ยฉ 2017 Laurentiu Ungur. All rights reserved. // import UIKit import LUAutocompleteView final class ViewController: UIViewController { // MARK: - Properties @IBOutlet weak var textField: UITextField! private let autocompleteView = LUAutocompleteView() private let elements = (1...100).map { "\($0)" } // MARK: - ViewController override func viewDidLoad() { super.viewDidLoad() view.addSubview(autocompleteView) autocompleteView.textField = textField autocompleteView.dataSource = self autocompleteView.delegate = self // Customisation autocompleteView.rowHeight = 45 //autocompleteView.autocompleteCell = CustomAutocompleteTableViewCell.self // Uncomment this line in order to use customised autocomplete cell } } // MARK: - LUAutocompleteViewDataSource extension ViewController: LUAutocompleteViewDataSource { func autocompleteView(_ autocompleteView: LUAutocompleteView, elementsFor text: String, completion: @escaping ([String]) -> Void) { let elementsThatMatchInput = elements.filter { $0.lowercased().contains(text.lowercased()) } completion(elementsThatMatchInput) } } // MARK: - LUAutocompleteViewDelegate extension ViewController: LUAutocompleteViewDelegate { func autocompleteView(_ autocompleteView: LUAutocompleteView, didSelect text: String) { print(text + " was selected from autocomplete view") } }
mit
3d8af0e3534d42750d8ee0ef400216c8
28.792453
150
0.720709
4.699405
false
false
false
false
taybenlor/Saliva
SalivaExample/SalivaExample/ViewController.swift
1
1119
// // ViewController.swift // SalivaExample // // Created by Ben Taylor on 24/12/2014. // Copyright (c) 2014 Ben Taylor. All rights reserved. // import UIKit import Saliva class ViewController: UIViewController { @IBOutlet weak var greenRectangle: UIView! var touchLocation: CGPoint = CGPoint(x: -200, y: -200) override func viewDidLoad() { super.viewDidLoad() bind(from: { self.touchLocation }, to: { self.greenRectangle.center = $0 }) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { if let touch: UITouch = touches.anyObject() as UITouch? { self.touchLocation = touch.locationInView(self.view) } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { if let touch: UITouch = touches.anyObject() as UITouch? { self.touchLocation = touch.locationInView(self.view) } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { self.touchLocation = CGPoint(x: -200, y: -200) } override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { self.touchLocation = CGPoint(x: -200, y: -200) } }
bsd-3-clause
b162a48efdacea8d203761c7fe037d5b
23.326087
77
0.705987
3.57508
false
false
false
false
stanislavfeldman/FutureKit-Extensions
FutureKit+MapKit.swift
1
1455
// // MapKit.swift // whereabout // // Created by ะกั‚ะฐั on 13/07/15. // Copyright (c) 2015 Limehat. All rights reserved. // import Foundation import MapKit extension MKDirections { func calculateDirections() -> Future<MKDirectionsResponse> { return self.calculateDirections(.Primary) } func calculateDirections(executor : Executor) -> Future<MKDirectionsResponse> { let promise = Promise<MKDirectionsResponse>() executor.execute { self.calculateDirectionsWithCompletionHandler { (response, error) in if error == nil || response != nil { promise.completeWithSuccess(response) } else { promise.completeWithFail(error) } } } return promise.future } func calculateETA() -> Future<MKETAResponse> { return self.calculateETA(.Primary) } func calculateETA(executor : Executor) -> Future<MKETAResponse> { let promise = Promise<MKETAResponse>() executor.execute { self.calculateETAWithCompletionHandler { (response, error) in if error == nil || response != nil { promise.completeWithSuccess(response) } else { promise.completeWithFail(error) } } } return promise.future } }
bsd-2-clause
277c3f3b711338eba47ce5b601c571e0
28.04
83
0.560992
5.055749
false
false
false
false
gu704823/DYTV
dytv/Pods/Kingfisher/Sources/Image.swift
20
32758
// // Image.swift // Kingfisher // // Created by Wei Wang on 16/1/6. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit private var imagesKey: Void? private var durationKey: Void? #else import UIKit import MobileCoreServices private var imageSourceKey: Void? #endif private var animatedImageDataKey: Void? import ImageIO import CoreGraphics #if !os(watchOS) import Accelerate import CoreImage #endif // MARK: - Image Properties extension Kingfisher where Base: Image { fileprivate(set) var animatedImageData: Data? { get { return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data } set { objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } #if os(macOS) var cgImage: CGImage? { return base.cgImage(forProposedRect: nil, context: nil, hints: nil) } var scale: CGFloat { return 1.0 } fileprivate(set) var images: [Image]? { get { return objc_getAssociatedObject(base, &imagesKey) as? [Image] } set { objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var duration: TimeInterval { get { return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0 } set { objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.representations.reduce(CGSize.zero, { size, rep in return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh))) }) } #else var cgImage: CGImage? { return base.cgImage } var scale: CGFloat { return base.scale } var images: [Image]? { return base.images } var duration: TimeInterval { return base.duration } fileprivate(set) var imageSource: ImageSource? { get { return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource } set { objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.size } #endif } // MARK: - Image Conversion extension Kingfisher where Base: Image { #if os(macOS) static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { return Image(cgImage: cgImage, size: CGSize.zero) } /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ public var normalized: Image { return base } static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? { return nil } #else static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { if let refImage = refImage { return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation) } else { return Image(cgImage: cgImage, scale: scale, orientation: .up) } } /** Normalize the image. This method will try to redraw an image with orientation and scale considered. - returns: The normalized image with orientation set to up and correct scale. */ public var normalized: Image { // prevent animated image (GIF) lose it's images guard images == nil else { return base } // No need to do anything if already up guard base.imageOrientation != .up else { return base } return draw(cgImage: nil, to: size) { base.draw(in: CGRect(origin: CGPoint.zero, size: size)) } } static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? { return .animatedImage(with: images, duration: duration) } #endif } // MARK: - Image Representation extension Kingfisher where Base: Image { // MARK: - PNG public func pngRepresentation() -> Data? { #if os(macOS) guard let cgimage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgimage) return rep.representation(using: .PNG, properties: [:]) #else return UIImagePNGRepresentation(base) #endif } // MARK: - JPEG public func jpegRepresentation(compressionQuality: CGFloat) -> Data? { #if os(macOS) guard let cgImage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgImage) return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality]) #else return UIImageJPEGRepresentation(base, compressionQuality) #endif } // MARK: - GIF public func gifRepresentation() -> Data? { return animatedImageData } } // MARK: - Create images from data extension Kingfisher where Base: Image { static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool, onlyFirstFrame: Bool = false) -> Image? { func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? { //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary func frameDuration(from gifInfo: NSDictionary?) -> Double { let gifDefaultFrameDuration = 0.100 guard let gifInfo = gifInfo else { return gifDefaultFrameDuration } let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber let duration = unclampedDelayTime ?? delayTime guard let frameDuration = duration else { return gifDefaultFrameDuration } return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration } let frameCount = CGImageSourceGetCount(imageSource) var images = [Image]() var gifDuration = 0.0 for i in 0 ..< frameCount { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else { return nil } if frameCount == 1 { // Single frame gifDuration = Double.infinity } else { // Animated GIF guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else { return nil } let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary gifDuration += frameDuration(from: gifInfo) } images.append(Kingfisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil)) if onlyFirstFrame { break } } return (images, gifDuration) } // Start of kf.animatedImageWithGIFData let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF] guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else { return nil } #if os(macOS) guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image: Image? if onlyFirstFrame { image = images.first } else { image = Image(data: data) image?.kf.images = images image?.kf.duration = gifDuration } image?.kf.animatedImageData = data return image #else let image: Image? if preloadAll || onlyFirstFrame { guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } image = onlyFirstFrame ? images.first : Kingfisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration) } else { image = Image(data: data) image?.kf.imageSource = ImageSource(ref: imageSource) } image?.kf.animatedImageData = data return image #endif } static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool, onlyFirstFrame: Bool) -> Image? { var image: Image? #if os(macOS) switch data.kf.imageFormat { case .JPEG: image = Image(data: data) case .PNG: image = Image(data: data) case .GIF: image = Kingfisher<Image>.animated( with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData, onlyFirstFrame: onlyFirstFrame) case .unknown: image = Image(data: data) } #else switch data.kf.imageFormat { case .JPEG: image = Image(data: data, scale: scale) case .PNG: image = Image(data: data, scale: scale) case .GIF: image = Kingfisher<Image>.animated( with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData, onlyFirstFrame: onlyFirstFrame) case .unknown: image = Image(data: data, scale: scale) } #endif return image } } // MARK: - Image Transforming extension Kingfisher where Base: Image { // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. public func image(withRoundRadius radius: CGFloat, fit size: CGSize) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Round corner image only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius) path.windingRule = .evenOddWindingRule path.addClip() base.draw(in: rect) #else guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("[Kingfisher] Failed to create CG context for image.") return } let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath context.addPath(path) context.clip() base.draw(in: rect) #endif } } #if os(iOS) || os(tvOS) func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image { switch contentMode { case .scaleAspectFit: return resize(to: size, for: .aspectFit) case .scaleAspectFill: return resize(to: size, for: .aspectFill) default: return resize(to: size) } } #endif // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. public func resize(to size: CGSize) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Resize only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) #else base.draw(in: rect) #endif } } /// Resize `self` to an image of new size, respecting the content mode. /// /// - Parameters: /// - size: The target size. /// - contentMode: Content mode of output image should be. /// - Returns: An image with new size. public func resize(to size: CGSize, for contentMode: ContentMode) -> Image { switch contentMode { case .aspectFit: let newSize = self.size.kf.constrained(size) return resize(to: newSize) case .aspectFill: let newSize = self.size.kf.filling(size) return resize(to: newSize) default: return resize(to: size) } } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. public func blurred(withRadius radius: CGFloat) -> Image { #if os(watchOS) return base #else guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Blur only works for CG-based image.") return base } // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // if d is odd, use three box-blurs of size 'd', centered on the output pixel. let s = Float(max(radius, 2.0)) // We will do blur on a resized image (*0.5), so the blur radius could be half as well. // Fix the slow compiling time for Swift 3. // See https://github.com/onevcat/Kingfisher/issues/611 let pi2 = 2 * Float.pi let sqrtPi2 = sqrt(pi2) var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5) if targetRadius.isEven { targetRadius += 1 } let iterations: Int if radius < 0.5 { iterations = 1 } else if radius < 1.5 { iterations = 2 } else { iterations = 3 } let w = Int(size.width) let h = Int(size.height) let rowBytes = Int(CGFloat(cgImage.bytesPerRow)) func createEffectBuffer(_ context: CGContext) -> vImage_Buffer { let data = context.data let width = vImagePixelCount(context.width) let height = vImagePixelCount(context.height) let rowBytes = context.bytesPerRow return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) } guard let context = beginContext() else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } defer { endContext() } context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h)) var inBuffer = createEffectBuffer(context) guard let outContext = beginContext() else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } defer { endContext() } var outBuffer = createEffectBuffer(outContext) for _ in 0 ..< iterations { vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend)) (inBuffer, outBuffer) = (outBuffer, inBuffer) } #if os(macOS) let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) } #else let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) } #endif guard let blurredImage = result else { assertionFailure("[Kingfisher] Can not make an blurred image within this context.") return base } return blurredImage #endif } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. public func overlaying(with color: Color, fraction: CGFloat) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Overlaying only works for CG-based image.") return base } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) return draw(cgImage: cgImage, to: rect.size) { #if os(macOS) base.draw(in: rect) if fraction > 0 { color.withAlphaComponent(1 - fraction).set() NSRectFillUsingOperation(rect, .sourceAtop) } #else color.set() UIRectFill(rect) base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0) if fraction > 0 { base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction) } #endif } } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. public func tinted(with color: Color) -> Image { #if os(watchOS) return base #else return apply(.tint(color)) #endif } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { #if os(watchOS) return base #else return apply(.colorControl(brightness, contrast, saturation, inputEV)) #endif } } // MARK: - Decode extension Kingfisher where Base: Image { var decoded: Image? { return decoded(scale: scale) } func decoded(scale: CGFloat) -> Image { // prevent animated image (GIF) lose it's images #if os(iOS) if imageSource != nil { return base } #else if images != nil { return base } #endif guard let imageRef = self.cgImage else { assertionFailure("[Kingfisher] Decoding only works for CG-based image.") return base } let colorSpace = CGColorSpaceCreateDeviceRGB() guard let context = beginContext() else { assertionFailure("[Kingfisher] Decoding fails to create a valid context.") return base } defer { endContext() } let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height) context.draw(imageRef, in: rect) let decompressedImageRef = context.makeImage() return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base) } } /// Reference the source image reference class ImageSource { var imageRef: CGImageSource? init(ref: CGImageSource) { self.imageRef = ref } } // MARK: - Image format private struct ImageHeaderData { static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] static var JPEG_SOI: [UInt8] = [0xFF, 0xD8] static var JPEG_IF: [UInt8] = [0xFF] static var GIF: [UInt8] = [0x47, 0x49, 0x46] } enum ImageFormat { case unknown, PNG, JPEG, GIF } // MARK: - Misc Helpers public struct DataProxy { fileprivate let base: Data init(proxy: Data) { base = proxy } } extension Data: KingfisherCompatible { public typealias CompatibleType = DataProxy public var kf: DataProxy { return DataProxy(proxy: self) } } extension DataProxy { var imageFormat: ImageFormat { var buffer = [UInt8](repeating: 0, count: 8) (base as NSData).getBytes(&buffer, length: 8) if buffer == ImageHeaderData.PNG { return .PNG } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] && buffer[1] == ImageHeaderData.JPEG_SOI[1] && buffer[2] == ImageHeaderData.JPEG_IF[0] { return .JPEG } else if buffer[0] == ImageHeaderData.GIF[0] && buffer[1] == ImageHeaderData.GIF[1] && buffer[2] == ImageHeaderData.GIF[2] { return .GIF } return .unknown } } public struct CGSizeProxy { fileprivate let base: CGSize init(proxy: CGSize) { base = proxy } } extension CGSize: KingfisherCompatible { public typealias CompatibleType = CGSizeProxy public var kf: CGSizeProxy { return CGSizeProxy(proxy: self) } } extension CGSizeProxy { func constrained(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } func filling(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } private var aspectRatio: CGFloat { return base.height == 0.0 ? 1.0 : base.width / base.height } } extension Kingfisher where Base: Image { func beginContext() -> CGContext? { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return nil } rep.size = size NSGraphicsContext.saveGraphicsState() guard let context = NSGraphicsContext(bitmapImageRep: rep) else { assertionFailure("[Kingfisher] Image contenxt cannot be created.") return nil } NSGraphicsContext.setCurrent(context) return context.cgContext #else UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext() context?.scaleBy(x: 1.0, y: -1.0) context?.translateBy(x: 0, y: -size.height) return context #endif } func endContext() { #if os(macOS) NSGraphicsContext.restoreGraphicsState() #else UIGraphicsEndImageContext() #endif } func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return base } rep.size = size NSGraphicsContext.saveGraphicsState() let context = NSGraphicsContext(bitmapImageRep: rep) NSGraphicsContext.setCurrent(context) draw() NSGraphicsContext.restoreGraphicsState() let outputImage = Image(size: size) outputImage.addRepresentation(rep) return outputImage #else UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } draw() return UIGraphicsGetImageFromCurrentImageContext() ?? base #endif } #if os(macOS) func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image { let image = Image(cgImage: cgImage, size: base.size) let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: self.size) { image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) } } #endif } extension Float { var isEven: Bool { return truncatingRemainder(dividingBy: 2.0) == 0 } } // MARK: - Deprecated. Only for back compatibility. extension Image { /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.", renamed: "kf.normalized") public func kf_normalized() -> Image { return kf.normalized } // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// - parameter scale: The image scale of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.", renamed: "kf.image") public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { return kf.image(withRoundRadius: radius, fit: size) } // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.", renamed: "kf.resize") public func kf_resize(to size: CGSize) -> Image { return kf.resize(to: size) } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.", renamed: "kf.blurred") public func kf_blurred(withRadius radius: CGFloat) -> Image { return kf.blurred(withRadius: radius) } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.", renamed: "kf.overlaying") public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image { return kf.overlaying(with: color, fraction: fraction) } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.", renamed: "kf.tinted") public func kf_tinted(with color: Color) -> Image { return kf.tinted(with: color) } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.", renamed: "kf.adjusted") public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) } } extension Kingfisher where Base: Image { @available(*, deprecated, message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)") public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { return image(withRoundRadius: radius, fit: size) } }
mit
8ef3a04c445a96697ae861819e11107f
33.848936
158
0.57763
4.844425
false
false
false
false
mansoor92/MaksabComponents
Example/Pods/StylingBoilerPlate/StylingBoilerPlate/Classes/Extensions/UITextField+custom.swift
1
1750
// // UITextField+custom.swift // 71stStreet // // Created by Pantera Engineering on 22/11/2016. // Copyright ยฉ 2016 Incubasys IT Solutions. All rights reserved. // import Foundation import UIKit public protocol Shakeable {} public extension Shakeable where Self: UIView{ public func shake() { let animation = CAKeyframeAnimation(keyPath: "transform.translation.x") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = 1 animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ] self.layer.add(animation, forKey: "shake") } } public enum RegularExpressions: String{ case email = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" case password = "" } extension UITextField: Shakeable{ public func isValid(exp:RegularExpressions) -> Bool{ return UITextField.isValid(text: self.text ?? "", forExp: exp) } static public func isValid(text: String, forExp exp: RegularExpressions) -> Bool { if let emailTest = NSPredicate(format:"SELF MATCHES %@", exp.rawValue) as NSPredicate? { return emailTest.evaluate(with: text) } return false } } extension UITextField{ public func addActivityIndicatory() { let ind = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 12, height: 12)) ind.activityIndicatorViewStyle = .gray let view = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 15)) view.addSubview(ind) self.rightViewMode = .always ind.startAnimating() self.rightView = view } public func removeActivityIndicator() { self.rightView = nil self.rightViewMode = .never } }
mit
34a20e0528ef545d519dffee6f58d287
28.15
92
0.651229
3.810458
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Profile Editor OutlineView/PropertyListEditor Source/Items/PropertyListCollection.swift
1
4104
// swiftlint:disable:next file_header // PropertyListCollection.swift // PropertyListEditor // // Created by Prachi Gauriar on 7/19/2015. // Copyright ยฉ 2015 Quantum Lens Cap. 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 Foundation /// The `PropertyListCollection` protocol defines a set of properties and methods that all property /// collections provide. It is primarily useful for providing default behavior using a protocol /// extension. protocol PropertyListCollection: CustomStringConvertible, Hashable { /// The type of element the instance contains. associatedtype ElementType: CustomStringConvertible, Hashable /// The elements in the instance var elements: [ElementType] { get } /// The number of elements in the instance var count: Int { get } subscript(index: Int) -> ElementType { get set } /// Adds the specified element to the end of the instance. /// - parameter element: The element to add mutating func append(_ element: ElementType) /// Inserts the specified element at the specified index in the instance. /// - parameter element: The element to insert /// - parameter index: The index at which to insert the element. Raises an assertion if beyond /// the bounds of the instance. mutating func insert(_ element: ElementType, at index: Int) /// Moves the element from the specified index to the new index. /// - parameter oldIndex: The index of the element being moved. Raises an assertion if beyond /// the bounds of the instance. /// - parameter newIndex: The index to which to move the element. Raises an assertion if beyond /// the bounds of the instance. mutating func moveElement(at oldIndex: Int, to newIndex: Int) /// Removes the element at the specified index. /// - parameter index: The index of the element being removed. Raises an assertion if beyond /// the bounds of the instance. /// - returns: The element that was removed. @discardableResult mutating func remove(at index: Int) -> ElementType } extension PropertyListCollection { var description: String { let elementDescriptions = elements.map { $0.description } return "[" + elementDescriptions.joined(separator: ", ") + "]" } public func hash(into hasher: inout Hasher) { hasher.combine(count) } var count: Int { elements.count } subscript(index: Int) -> ElementType { get { elements[index] } set { remove(at: index) insert(newValue, at: index) } } mutating func append(_ element: ElementType) { insert(element, at: count) } mutating func moveElement(at oldIndex: Int, to newIndex: Int) { let element = self[oldIndex] remove(at: oldIndex) insert(element, at: newIndex) } } func ==<CollectionType: PropertyListCollection>(lhs: CollectionType, rhs: CollectionType) -> Bool { lhs.elements == rhs.elements }
mit
43f6b12d1a126e7683a522544176c06f
37.707547
99
0.693883
4.641403
false
false
false
false
DrabWeb/Komikan
Komikan/Komikan/KMAddMangaViewController.swift
1
30487
// // KMAddMangaViewController.swift // Komikan // // Created by Seth on 2016-01-03. // import Cocoa class KMAddMangaViewController: NSViewController { // The visual effect view for the background of the window @IBOutlet weak var backgroundVisualEffectView: NSVisualEffectView! // The manga we will send back var newManga : KMManga = KMManga(); // An array to store all the manga we want to batch open, if thats what we are doing var newMangaMultiple : [KMManga] = [KMManga()]; // The NSTimer to update if we can add the manga with our given values var addButtonUpdateLoop : Timer = Timer(); // Does the user want to batch add them? var addingMultiple : Bool = false; /// The image view for the cover image @IBOutlet weak var coverImageView: NSImageView! /// The token text field for the mangas title @IBOutlet weak var titleTokenTextField: KMSuggestionTokenField! /// The token text field for the mangas series @IBOutlet weak var seriesTokenTextField: KMSuggestionTokenField! /// The token text field for the mangas artist @IBOutlet weak var artistTokenTextField: KMSuggestionTokenField! /// The token text field for the mangas writer @IBOutlet weak var writerTokenTextField: KMSuggestionTokenField! /// The text field for the mangas tags @IBOutlet weak var tagsTextField: KMAlwaysActiveTextField! /// The token text field for the mangas group @IBOutlet weak var groupTokenTextField: KMSuggestionTokenField! /// The text field for setting the manga's release date(s) @IBOutlet var releaseDateTextField: KMAlwaysActiveTextField! /// The date formatter for releaseDateTextField @IBOutlet var releaseDateTextFieldDateFormatter: DateFormatter! /// The checkbox to say if this manga is l-lewd... @IBOutlet weak var llewdCheckBox: NSButton! /// The button to say if the manga we add should be favourited @IBOutlet weak var favouriteButton: KMFavouriteButton! /// The open panel to let the user choose the mangas directory var chooseDirectoryOpenPanel : NSOpenPanel = NSOpenPanel(); /// The "Choose Directory" button @IBOutlet weak var chooseDirectoryButton: NSButton! /// When we click chooseDirectoryButton... @IBAction func chooseDirectoryButtonPressed(_ sender: AnyObject) { // Run he choose directory open panel chooseDirectoryOpenPanel.runModal(); } /// The add button @IBOutlet weak var addButton: NSButton! /// When we click the add button... @IBAction func addButtonPressed(_ sender: AnyObject) { // Dismiss the popver self.dismiss(self); // Add the manga we described in the open panel addSelf(); } /// The URLs of the files we are adding var addingMangaURLs : [URL] = []; /// The local key down monitor var keyDownMonitor : AnyObject?; override func viewDidLoad() { super.viewDidLoad() // Do view setup here. // Style the window styleWindow(); // Update the favourite button favouriteButton.updateButton(); // Setup the choose directory open panel // Allow multiple files chooseDirectoryOpenPanel.allowsMultipleSelection = true; // Only allow CBZ, CBR, ZIP, RAR and Folders chooseDirectoryOpenPanel.allowedFileTypes = ["cbz", "cbr", "zip", "rar"]; chooseDirectoryOpenPanel.canChooseDirectories = true; // Set the Open button to say choose chooseDirectoryOpenPanel.prompt = "Choose"; // Setup all the suggestions for the property text fields seriesTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allSeries(); artistTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allArtists(); writerTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allWriters(); groupTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allGroups(); // Start a 0.1 second loop that will set if we can add this manga or not addButtonUpdateLoop = Timer.scheduledTimer(timeInterval: TimeInterval(0.1), target: self, selector: #selector(KMAddMangaViewController.updateAddButton), userInfo: nil, repeats: true); // Prompt for a manga startPrompt(); } func addSelf() { // If we are only adding one... if(!addingMultiple) { // Set the new mangas cover image newManga.coverImage = coverImageView.image!; // Resize the cover image to be compressed for faster loading newManga.coverImage = newManga.coverImage.resizeToHeight(400); // Set the new mangas title newManga.title = titleTokenTextField.stringValue; // Set the new mangas series newManga.series = seriesTokenTextField.stringValue; // Set the new mangas artist newManga.artist = artistTokenTextField.stringValue; // If the release date field isnt blank... if(releaseDateTextField.stringValue != "") { // Set the release date newManga.releaseDate = releaseDateTextFieldDateFormatter.date(from: releaseDateTextField.stringValue)!; } // Set if the manga is l-lewd... newManga.lewd = Bool(llewdCheckBox.state as NSNumber); // Set the new mangas directory newManga.directory = (addingMangaURLs[0].absoluteString.removingPercentEncoding!).replacingOccurrences(of: "file://", with: ""); // Set the new mangas writer newManga.writer = writerTokenTextField.stringValue; // For every part of the tags text field's string value split at every ", "... for (_, currentTag) in tagsTextField.stringValue.components(separatedBy: ", ").enumerated() { // Print to the log what tag we are adding and what manga we are adding it to print("KMAddMangaViewController: Adding tag \"" + currentTag + "\" to \"" + newManga.title + "\""); // Append the current tags to the mangas tags newManga.tags.append(currentTag); } // Set the new manga's group newManga.group = groupTokenTextField.stringValue; // Set if the manga is a favourite newManga.favourite = Bool(favouriteButton.state as NSNumber); // Post the notification saying we are done and sending back the manga NotificationCenter.default.post(name: Notification.Name(rawValue: "KMAddMangaViewController.Finished"), object: newManga); } else { for (_, currentMangaURL) in addingMangaURLs.enumerated() { // A temporary variable for storing the manga we are currently working on var currentManga : KMManga = KMManga(); // Set the new mangas directory currentManga.directory = (currentMangaURL.absoluteString).removingPercentEncoding!.replacingOccurrences(of: "file://", with: ""); // Get the information of the manga(Cover image, title, ETC.)(Change this function to be in KMManga) currentManga = getMangaInfo(currentManga); // Set the manga's series currentManga.series = seriesTokenTextField.stringValue; // Set the manga's artist currentManga.artist = artistTokenTextField.stringValue; // Set the manga's writer currentManga.writer = writerTokenTextField.stringValue; // If the release date field isnt blank... if(releaseDateTextField.stringValue != "") { // Set the release date currentManga.releaseDate = releaseDateTextFieldDateFormatter.date(from: releaseDateTextField.stringValue)!; } // Set if the manga is l-lewd... currentManga.lewd = Bool(llewdCheckBox.state as NSNumber); // For every part of the tags text field's string value split at every ", "... for (_, currentTag) in tagsTextField.stringValue.components(separatedBy: ", ").enumerated() { // Print to the log what tag we are adding and what manga we are adding it to print("KMAddMangaViewController: Adding tag \"" + currentTag + "\" to \"" + newManga.title + "\""); // Append the current tags to the mangas tags currentManga.tags.append(currentTag); } // Set the manga's group currentManga.group = groupTokenTextField.stringValue; // Set if the manga is a favourite currentManga.favourite = Bool(favouriteButton.state as NSNumber); // Add curentManga to the newMangaMultiple array newMangaMultiple.append(currentManga); } // Remove the first element in newMangaMultiple, for some reason its always empty newMangaMultiple.remove(at: 0); // Post the notification saying we are done and sending back the manga NotificationCenter.default.post(name: Notification.Name(rawValue: "KMAddMangaViewController.Finished"), object: newMangaMultiple); } } /// DId the user specify a custom title in the JSON? var gotTitleFromJSON : Bool = false; /// Did the user specify a custom cover image in the JSON? var gotCoverImageFromJSON : Bool = false; /// Gets the data from the optional JSON file that contains metadata info func fetchJsonData() { // If we actually selected anything... if(addingMangaURLs != []) { // Print to the log that we are fetching the JSON data print("KMAddMangaViewController: Fetching JSON data..."); /// The selected Mangas folder it is in var folderURLString : String = (addingMangaURLs.first?.absoluteString)!; // Remove everything after the last "/" in the string so we can get the folder folderURLString = folderURLString.substring(to: folderURLString.range(of: "/", options: NSString.CompareOptions.backwards, range: nil, locale: nil)!.lowerBound); // Append a slash to the end because it removes it folderURLString += "/"; // Remove the file:// from the folder URL string folderURLString = folderURLString.replacingOccurrences(of: "file://", with: ""); // Remove the percent encoding from the folder URL string folderURLString = folderURLString.removingPercentEncoding!; // Add the "Komikan" folder to the end of it folderURLString += "Komikan/" // If we chose multiple manga... if(addingMangaURLs.count > 1) { /// The URL of the multiple Manga's possible JSON file let mangaJsonURL : String = folderURLString + "series.json"; // If there is a "series.json" file in the Manga's folder... if(FileManager.default.fileExists(atPath: mangaJsonURL)) { // Print to the log that we found the JSON file for the selected manga print("KMAddMangaViewController: Found a series.json file for the selected Manga at \"" + mangaJsonURL + "\""); /// The SwiftyJSON object for the Manga's JSON info let mangaJson = JSON(data: FileManager.default.contents(atPath: mangaJsonURL)!); // Set the series text field's value to the series value seriesTokenTextField.stringValue = mangaJson["series"].stringValue; // Set the series text field's value to the artist value artistTokenTextField.stringValue = mangaJson["artist"].stringValue; // Set the series text field's value to the writer value writerTokenTextField.stringValue = mangaJson["writer"].stringValue; // If there is a released value... if(mangaJson["published"].exists()) { // If there is a release date listed... if(mangaJson["published"].stringValue.lowercased() != "unknown" && mangaJson["published"].stringValue != "") { // If the release date is valid... if(releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue) != nil) { // Set the release date text field's value to the release date value releaseDateTextField.stringValue = releaseDateTextFieldDateFormatter.string(from: (releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue)!)); } } } // For every item in the tags value of the JSON... for(_, currentTag) in mangaJson["tags"].arrayValue.enumerated() { // Print the current tag print("KMAddMangaViewController: Found tag \"" + currentTag.stringValue + "\""); // Add the current item to the tag text field tagsTextField.stringValue += currentTag.stringValue + ", "; } // If the tags text field is not still blank... if(tagsTextField.stringValue != "") { // Remove the extra ", " from the tags text field tagsTextField.stringValue = tagsTextField.stringValue.substring(to: tagsTextField.stringValue.index(before: tagsTextField.stringValue.characters.index(before: tagsTextField.stringValue.endIndex))); } // Set the group text field's value to the group value groupTokenTextField.stringValue = mangaJson["group"].stringValue; // Set the favourites buttons value to the favourites value of the JSON favouriteButton.state = Int.fromBool(bool: mangaJson["favourite"].boolValue); // Update the favourites button favouriteButton.updateButton(); // Set the l-lewd... checkboxes state to the lewd value of the JSON llewdCheckBox.state = Int.fromBool(bool: mangaJson["lewd"].boolValue); } } // If we chose 1 manga... else if(addingMangaURLs.count == 1) { /// The URL to the single Manga's possible JSON file let mangaJsonURL : String = folderURLString + (addingMangaURLs.first?.lastPathComponent.removingPercentEncoding!)! + ".json"; // If there is a file that has the same name but with a .json on the end... if(FileManager.default.fileExists(atPath: mangaJsonURL)) { // Print to the log that we found the JSON file for the single manga print("KMAddMangaViewController: Found single Manga's JSON file at \"" + mangaJsonURL + "\""); /// The SwiftyJSON object for the Manga's JSON info let mangaJson = JSON(data: FileManager.default.contents(atPath: mangaJsonURL)!); // If the title value from the JSON is not "auto" or blank... if(mangaJson["title"].stringValue != "auto" && mangaJson["title"].stringValue != "") { // Set the title text fields value to the title value from the JSON titleTokenTextField.stringValue = mangaJson["title"].stringValue; // Say we got a title from the JSON gotTitleFromJSON = true; } // If the cover image value from the JSON is not "auto" or blank... if(mangaJson["cover-image"].stringValue != "auto" && mangaJson["cover-image"].stringValue != "") { // If the first character is not a "/"... if(mangaJson["cover-image"].stringValue.substring(to: mangaJson["cover-image"].stringValue.characters.index(after: mangaJson["cover-image"].stringValue.startIndex)) == "/") { // Set the cover image views image to an NSImage at the path specified in the JSON coverImageView.image = NSImage(contentsOf: URL(fileURLWithPath: mangaJson["cover-image"].stringValue)); // Say we got a cover image from the JSON gotCoverImageFromJSON = true; } else { // Get the relative image coverImageView.image = NSImage(contentsOf: URL(fileURLWithPath: folderURLString + mangaJson["cover-image"].stringValue)); // Say we got a cover image from the JSON gotCoverImageFromJSON = true; } } // Set the series text field's value to the series value seriesTokenTextField.stringValue = mangaJson["series"].stringValue; // Set the series text field's value to the artist value artistTokenTextField.stringValue = mangaJson["artist"].stringValue; // Set the series text field's value to the writer value writerTokenTextField.stringValue = mangaJson["writer"].stringValue; // If there is a released value... if(mangaJson["published"].exists()) { // If there is a release date listed... if(mangaJson["published"].stringValue.lowercased() != "unknown" && mangaJson["published"].stringValue != "") { // If the release date is valid... if(releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue) != nil) { // Set the release date text field's value to the release date value releaseDateTextField.stringValue = releaseDateTextFieldDateFormatter.string(from: (releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue)!)); } } } // For every item in the tags value of the JSON... for(_, currentTag) in mangaJson["tags"].arrayValue.enumerated() { // Print the current tag print("KMAddMangaViewController: Found tag \"" + currentTag.stringValue + "\""); // Add the current item to the tag text field tagsTextField.stringValue += currentTag.stringValue + ", "; } // If the tags text field is not still blank... if(tagsTextField.stringValue != "") { // Remove the extra ", " from the tags text field tagsTextField.stringValue = tagsTextField.stringValue.substring(to: tagsTextField.stringValue.index(before: tagsTextField.stringValue.characters.index(before: tagsTextField.stringValue.endIndex))); } // Set the group text field's value to the group value groupTokenTextField.stringValue = mangaJson["group"].stringValue; // Set the favourites buttons value to the favourites value of the JSON favouriteButton.state = Int.fromBool(bool: mangaJson["favourite"].boolValue); // Update the favourites button favouriteButton.updateButton(); // Set the l-lewd... checkboxes state to the lewd value of the JSON llewdCheckBox.state = Int.fromBool(bool: mangaJson["lewd"].boolValue); } } } } // Updates the add buttons enabled state func updateAddButton() { // A variable to say if we can add the manga with the given values var canAdd : Bool = false; // If we are only adding one... if(!addingMultiple) { // If the cover image selected is not the default one... if(coverImageView.image != NSImage(named: "NSRevealFreestandingTemplate")) { // If the title is not nothing... if(titleTokenTextField.stringValue != "") { // If the directory is not nothing... if(addingMangaURLs != []) { // Say we can add with these variables canAdd = true; } } } } else { // Say we can add canAdd = true; } // If we can add with these variables... if(canAdd) { // Enable the add button addButton.isEnabled = true; } else { // Disable the add button addButton.isEnabled = false; } } func getMangaInfo(_ manga : KMManga) -> KMManga { // Set the mangas title to the mangas archive name manga.title = KMFileUtilities().getFileNameWithoutExtension(manga.directory); // Delete /tmp/komikan/addmanga, if it exists do { // Remove /tmp/komikan/addmanga try FileManager().removeItem(atPath: "/tmp/komikan/addmanga"); // Print to the log that we deleted it print("KMAddMangaViewController: Deleted /tmp/komikan/addmanga folder for \"" + manga.title + "\""); // If there is an error... } catch _ as NSError { // Print to the log that there is no /tmp/komikan/addmanga folder to delete print("KMAddMangaViewController: No /tmp/komikan/addmanga to delete for \"" + manga.title + "\""); } // If the manga's file isnt a folder... if(!KMFileUtilities().isFolder(manga.directory.replacingOccurrences(of: "file://", with: ""))) { // Extract the passed manga to /tmp/komikan/addmanga KMFileUtilities().extractArchive(manga.directory.replacingOccurrences(of: "file://", with: ""), toDirectory: "/tmp/komikan/addmanga"); } // If the manga's file is a folder... else { // Copy the folder to /tmp/komikan/addmanga do { try FileManager.default.copyItem(atPath: manga.directory.replacingOccurrences(of: "file://", with: ""), toPath: "/tmp/komikan/addmanga"); } catch _ as NSError { } } // Clean up the directory print("KMAddMangaViewController: \(KMCommandUtilities().runCommand(Bundle.main.bundlePath + "/Contents/Resources/cleanmangadir", arguments: ["/tmp/komikan/addmanga"], waitUntilExit: true))"); /// All the files in /tmp/komikan/addmanga var addMangaFolderContents : [String] = []; // Get the contents of /tmp/komikan/addmanga do { // Set addMangaFolderContents to all the files in /tmp/komikan/addmanga addMangaFolderContents = try FileManager().contentsOfDirectory(atPath: "/tmp/komikan/addmanga"); // Sort the files by their integer values addMangaFolderContents = (addMangaFolderContents as NSArray).sortedArray(using: [NSSortDescriptor(key: "integerValue", ascending: true)]) as! [String]; } catch _ as NSError { // Do nothing } // Get the first image in the folder, and set the cover image selection views image to it // The first item in /tmp/komikan/addmanga var firstImage : NSImage = NSImage(); // For every item in the addmanga folder... for(_, currentFile) in addMangaFolderContents.enumerated() { // If this file is an image and not a dot file... if(KMFileUtilities().isImage("/tmp/komikan/addmanga/" + (currentFile )) && ((currentFile).substring(to: (currentFile).characters.index(after: (currentFile).startIndex))) != ".") { // If the first image isnt already set... if(firstImage.size == NSSize.zero) { // Set the first image to the current image file firstImage = NSImage(contentsOfFile: "/tmp/komikan/addmanga/\(currentFile)")!; } } } // Set the cover image selecting views image to firstImage manga.coverImage = firstImage; // Resize the cover image to be compressed for faster loading manga.coverImage = manga.coverImage.resizeToHeight(400); // Print the image to the log(It for some reason needs this print or it wont work) print("KMAddMangaViewController: \(firstImage)"); // Return the changed manga return manga; } // Asks for a manga, and deletes the old ones tmp folder func promptForManga() { // Delete /tmp/komikan/addmanga do { // Remove /tmp/komikan/addmanga try FileManager().removeItem(atPath: "/tmp/komikan/addmanga"); // If there is an error... } catch _ as NSError { // Do nothing } // Ask for the manga's directory, and if we clicked "Choose"... if(Bool(chooseDirectoryOpenPanel.runModal() as NSNumber)) { // Set the adding manga URLs to the choose directory open panels URLs addingMangaURLs = chooseDirectoryOpenPanel.urls; } } // The prompt you get when you open this view with the open panel func startPrompt() { // If addingMangaURLs is []... if(addingMangaURLs == []) { // Prompt for a file promptForManga(); } // Fetch the JSON data fetchJsonData(); // Subscribe to the key down event keyDownMonitor = NSEvent.addLocalMonitorForEvents(matching: NSEventMask.keyDown, handler: keyHandler) as AnyObject?; // If we selected multiple files... if(addingMangaURLs.count > 1) { // Say we are adding multiple addingMultiple = true; // Say we cant edit the image view coverImageView.isEditable = false; // Dont allow us to set the title titleTokenTextField.isEnabled = false; // Dont allow us to change the directory chooseDirectoryButton.isEnabled = false; // Set the cover image image views image to NSFlowViewTemplate coverImageView.image = NSImage(named: "NSFlowViewTemplate"); } else { // If the directory is not nothing... if(addingMangaURLs != []) { // Set the new mangas directory newManga.directory = addingMangaURLs[0].absoluteString.removingPercentEncoding!; // Get the information of the manga(Cover image, title, ETC.)(Change this function to be in KMManga) newManga = getMangaInfo(newManga); // If we didnt get a cover image from the JSON... if(!gotCoverImageFromJSON) { // Set the cover image views cover image coverImageView.image = newManga.coverImage; } // If we didnt get a title from the JSON... if(!gotTitleFromJSON) { // Set the title text fields value to the mangas title titleTokenTextField.stringValue = newManga.title; } } } } func keyHandler(_ event : NSEvent) -> NSEvent { // If we pressed enter... if(event.keyCode == 36 || event.keyCode == 76) { // If the add button is enabled... if(addButton.isEnabled) { // Hide the popover self.dismiss(self); // Add the chosen manga addSelf(); } } // Return the event return event; } override func viewWillDisappear() { // Unsubscribe from key down NSEvent.removeMonitor(keyDownMonitor!); // Stop the add button update loop addButtonUpdateLoop.invalidate(); } func styleWindow() { // Set the background effect view to be dark backgroundVisualEffectView.material = NSVisualEffectMaterial.dark; } }
gpl-3.0
7d18839ce2521f72f5ba3e4a7f749108
47.162717
221
0.560272
5.345783
false
false
false
false
chaoyang805/DoubanMovie
DoubanMovie/Snackbar.swift
1
6360
/* * Copyright 2016 chaoyang805 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit let SnackbarShouldShowNotification = Notification.Name("show snackbar") let SnackbarShouldDismissNotification = Notification.Name("dismiss snackbar") let SnackbarUserInfoKey = "targetSnackbar" @objc protocol SnackbarDelegate: NSObjectProtocol { @objc optional func snackbarWillAppear(_ snackbar: Snackbar) @objc optional func snackbarDidAppear(_ snackbar: Snackbar) @objc optional func snackbarWillDisappear(_ snackbar: Snackbar) @objc optional func snackbarDidDisappear(_ snackbar: Snackbar) } enum SnackbarDuration: TimeInterval { case Short = 1.5 case Long = 3 } class Snackbar: NSObject { private(set) lazy var view: SnackbarView = { let _barView = SnackbarView() // ไธบไบ†Snackbarไธ่ขซ้”€ๆฏ _barView.snackbar = self return _barView }() private var showing: Bool = false private var dismissHandler: (() -> Void)? var duration: TimeInterval! private weak var delegate: SnackbarDelegate? class func make(text: String, duration: SnackbarDuration) -> Snackbar { return make(text, duration: duration.rawValue) } private class func make(_ text: String, duration: TimeInterval) -> Snackbar { let snackbar = Snackbar() snackbar.setSnackbarText(text: text) snackbar.duration = duration snackbar.registerNotification() snackbar.delegate = SnackbarManager.defaultManager() return snackbar } func show() { let record = SnackbarRecord(duration: duration, identifier: hash) SnackbarManager.defaultManager().show(record) } func dispatchDismiss() { let record = SnackbarRecord(duration: duration, identifier: hash) SnackbarManager.defaultManager().dismiss(record) } // MARK: - Notification func registerNotification() { let manager = SnackbarManager.defaultManager() NotificationCenter.default.addObserver(self, selector: #selector(Snackbar.handleNotification(_:)), name: SnackbarShouldShowNotification, object: manager) NotificationCenter.default.addObserver(self, selector: #selector(Snackbar.handleNotification(_:)), name: SnackbarShouldDismissNotification, object: manager) } func unregisterNotification() { NotificationCenter.default.removeObserver(self) } deinit { NSLog("deinit") } func handleNotification(_ notification: NSNotification) { guard let identifier = notification.userInfo?[SnackbarUserInfoKey] as? Int else { NSLog("not found snackbar in notification's userInfo") return } guard identifier == self.hash else { NSLog("not found specified snackbar:\(identifier)") return } switch notification.name { case SnackbarShouldShowNotification: handleShowNotification() case SnackbarShouldDismissNotification: handleDismissNotification() default: break } } func handleShowNotification() { self.showView() } func handleDismissNotification() { self.dismissView() } // MARK: - Configure Snackbar func setSnackbarText(text: String) { view.messageView.text = text view.messageView.sizeToFit() } // MARK: - Warning Retain cycle๏ผˆsolved๏ผ‰ func setAction(title: String, action: @escaping ((_ sender: AnyObject) -> Void)) -> Snackbar { view.setAction(title: title) { (sender) in action(sender) self.dispatchDismiss() } return self } func dismissHandler(block: @escaping (() -> Void)) -> Snackbar { self.dismissHandler = block return self } // MARK: - Snackbar View show & dismiss private func showView() { guard let window = UIApplication.shared.keyWindow else { return } self.delegate?.snackbarWillAppear?(self) window.addSubview(view) UIView.animate( withDuration: 0.25, delay: 0, options: .curveEaseIn, animations: { [weak self] in guard let `self` = self else { return } self.view.frame = self.view.frame.offsetBy(dx: 0, dy: -40) }, completion: { (done ) in self.delegate?.snackbarDidAppear?(self) self.showing = true }) } func dismissView() { guard self.showing else { return } self.delegate?.snackbarWillDisappear?(self) UIView.animate( withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: { [weak self] in guard let `self` = self else { return } self.view.frame = self.view.frame.offsetBy(dx: 0, dy: 40) }, completion: { (done) in self.showing = false self.view.snackbar = nil self.view.removeFromSuperview() self.dismissHandler?() self.delegate?.snackbarDidDisappear?(self) self.delegate = nil self.unregisterNotification() } ) } }
apache-2.0
96d8aa7f717a45976459d384d002f611
29.796117
164
0.583859
5.385399
false
false
false
false
oarrabi/RangeSliderView
Pod/Classes/RangeSliderView.swift
1
3469
// // RangeSliderView.swift // DublinBusMenu // // Created by Omar Abdelhafith on 04/02/2016. // Copyright ยฉ 2016 Omar Abdelhafith. All rights reserved. // protocol RangeSlider: AnyObject { var minimumValue: Int { get set } var maximumValue: Int { get set } var minimumSelectedValue: Int { get set } var maximumSelectedValue: Int { get set } var backgroundView: SliderBackground { get set } var minimumKnobView: SliderKnob { get set } var maximumKnobView: SliderKnob { get set } var fullRange: Range<Int> { get set } var selectedRange: Range<Int> { get set } var bounds: CGRect { get set } var selectedValuesChanged: ((Int, Int) -> ())? { get set } func addViewsAndRegisterCallbacks() func updateKnobsPlacements() func informAboutValueChanged() #if os(OSX) func addSubview(view: NSView) #else func addSubview(view: UIView) #endif } extension RangeSlider { private var width: CGFloat { return CGRectGetWidth(bounds) } func addViewsAndRegisterCallbacks() { addToView(backgroundView.view) addToView(minimumKnobView.view) addToView(maximumKnobView.view) minimumKnobView.knobMovementCallback = { rect in self.updateKnobViews() } maximumKnobView.knobMovementCallback = { rect in self.updateKnobViews() } fullRange = 0..<100 } #if os(OSX) private func addToView(subView: NSView) { addSubview(subView) subView.frame = bounds } #else private func addToView(subView: UIView) { addSubview(subView) subView.frame = bounds } #endif private func updateKnobViews() { let minimumXAllowed = CGRectGetMaxX(minimumKnobView.knobFrame) self.maximumKnobView.boundRange.moveStart(minimumXAllowed) self.backgroundView.boundRange.moveStart(minimumXAllowed) let maximumXAllowed = CGRectGetMinX(maximumKnobView.knobFrame) self.minimumKnobView.boundRange.moveEnd(maximumXAllowed) self.backgroundView.boundRange.moveEnd(maximumXAllowed) self.updateSelectedRange() } private func updateSelectedRange() { let start = Int(locationForView(minimumKnobView.view)) let end = Int(locationForView(maximumKnobView.view)) if start == 0 && end == 0 { return } self.selectedRange = start..<end informAboutValueChanged() selectedValuesChanged?(minimumSelectedValue, maximumSelectedValue) } private func locationForView(view: SliderKnobView) -> CGFloat { let xLocation = getViewCenterX(view) return locationInRange(range: fullRange, viewWidth: self.width, xLocationInView: xLocation, itemWidth: minimumKnobView.knobFrame.size.width) } private func getViewCenterX(view: SliderKnobView) -> CGFloat { return CGRectGetMinX(view.knobFrame) + (CGRectGetWidth(view.knobFrame)) / 2.0 } func updateKnobsPlacements() { let range = BoundRange.range( withFullRange: fullRange, selectedRange: selectedRange, fullWidth: width) backgroundView.boundRange = range.boundByApplyingInset(7) minimumKnobView.boundRange = BoundRange(start: 0, width: width) maximumKnobView.boundRange = BoundRange(start: 0, width: width) minimumKnobView.knobFrame = KnobPlacment.RangeStart.placeRect(forRange: range, size: minimumKnobView.knobFrame.size) maximumKnobView.knobFrame = KnobPlacment.RangeEnd.placeRect(forRange: range, size: maximumKnobView.knobFrame.size) } }
mit
2b599110805660599379a3558d0e7376
26.531746
120
0.711938
4.094451
false
false
false
false
ndleon09/SwiftSample500px
pictures/Modules/List/ListDataManager.swift
1
2881
// // ListDataManager.swift // pictures // // Created by Nelson Dominguez on 04/11/15. // Copyright ยฉ 2015 Nelson Dominguez. All rights reserved. // import Foundation class ListDataManager: ListDataManagerProtocol { var networkService : NetworkingServiceProtocol? var persistenceLayer : PersistenceLayerProtocol? func findMostPopularPictures(completion: @escaping ([PictureModel]) -> ()) { findMostPopularPicturesInNetwork(completion: completion) } fileprivate func findMostPopularPicturesInNetwork(completion: @escaping ([PictureModel]) -> ()) { networkService?.findMostPopularPictures { photos in let pictureModels = photos.map { PictureModel(dictionary: $0 as! NSDictionary) } self.saveMostPopularPictures(pictures: pictureModels) self.findMostPopularPicturesInLocal(completion: completion) } } fileprivate func findMostPopularPicturesInLocal(completion: @escaping ([PictureModel]) -> ()) { let sortDescriptor = NSSortDescriptor(key: "rating", ascending: false) persistenceLayer?.fetchPicturesEntries(predicate: nil, sortDescriptors: [sortDescriptor], completionBlock: { objects in let pictureModels: [PictureModel] = objects.map { object in let keys = Array(object.entity.attributesByName.keys) let dictionary = object.dictionaryWithValues(forKeys: keys) return PictureModel(coreDataDictionary: dictionary) } DispatchQueue.main.async(execute: { completion(pictureModels) }) }) } fileprivate func saveMostPopularPictures(pictures: [PictureModel]) { for picture in pictures { persistenceLayer?.findPicture(id: picture.id!, completion: { object in if object == nil { let pictureDataModel = self.persistenceLayer?.newPictureDataModel() pictureDataModel?.id = picture.id as NSNumber? pictureDataModel?.name = picture.name pictureDataModel?.image = picture.image pictureDataModel?.detailText = picture.detailText pictureDataModel?.userName = picture.user?.name pictureDataModel?.userImage = picture.user?.image pictureDataModel?.rating = picture.rating as NSNumber? pictureDataModel?.camera = picture.camera pictureDataModel?.latitude = picture.latitude as NSNumber? pictureDataModel?.longitude = picture.longitude as NSNumber? self.persistenceLayer?.save() } }) } } }
mit
21957539a9da5b2de3ba1bd1d6e0fd1b
39
127
0.605903
5.714286
false
false
false
false
JoeLago/MHGDB-iOS
MHGDB/Screens/Menu/ListMenu.swift
1
1695
// // MIT License // Copyright (c) Gathering Hall Studios // import UIKit class ListMenu: SimpleTableViewController { var searchController: SearchAllController! override func loadView() { super.loadView() title = "MHGDB" definesPresentationContext = true searchController = SearchAllController(mainViewController: self) if #available(iOS 11, *) { navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = false } else { tableView.tableHeaderView = searchController.searchBar } addCell(text: "Quests", imageName: "Quest-Icon-Red.png") { QuestList() } addCell(text: "Monsters", imageName: "Rathalos.png") { MonsterList() } addCell(text: "Weapons", imageName: "great_sword8.png") { WeaponTypeList() } addCell(text: "Armor", imageName: "body4.png") { ArmorList() } addCell(text: "Items", imageName: "Ore-Purple.png") { ItemList() } addCell(text: "Combinations", imageName: "Liquid-Green.png") { CombinationList() } addCell(text: "Locations", imageName: "Map-Icon-White.png") { LocationList() } addCell(text: "Decorations", imageName: "Jewel-Cyan.png") { DecorationList() } addCell(text: "Skills", imageName: "Monster-Jewel-Teal.png") { SkillList() } addCell(text: "Palico", imageName: "cutting3.png") { PalicoList() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if #available(iOS 10.3, *) { ReviewManager.presentReviewControllerIfElligible() } } }
mit
2e199c6352fabb53e0a4f6de9d56a355
36.666667
90
0.626549
4.185185
false
false
false
false
househappy/MapPointMapper
MapPointMapper/Parser/Parser.swift
2
8922
// // Parser.swift // MapPointMapper // // Created by Daniel on 11/20/14. // Copyright (c) 2014 dmiedema. All rights reserved. // import Foundation import MapKit extension NSString { /** Convenience so `isEmpty` can be performed on an `NSString` instance just as if it were a `String` - returns: `true` if the string is empty, `false` if not */ var isEmpty: Bool { get { return self.length == 0 || self.isEqualToString("") } } } extension String { /** Strip all leading and trailing whitespace from a given `String` instance. - returns: a newly stripped string instance. */ func stringByStrippingLeadingAndTrailingWhiteSpace() -> String { let mutable = self.mutableCopy() as! NSMutableString CFStringTrimWhitespace(mutable) return mutable.copy() as! String } } enum ParseError : ErrorType { case InvalidWktString(description: String) } class Parser { // MARK: - Public /** Parse a given string of Lat/Lng values to return a collection of `CLLocationCoordinate2D` arrays. - note: The preferred way/format of the input string is `Well-Known Text` as the parser supports that for multipolygons and such - parameter input: String to parse - parameter longitudeFirst: Only used if it is determined to not be `Well-Known Text` format. - returns: An array of `CLLocationCoordinate2D` arrays representing the parsed areas/lines */ class func parseString(input: NSString, longitudeFirst: Bool) throws -> [[CLLocationCoordinate2D]] { let coordinate_set = Parser(longitudeFirst: longitudeFirst).parseInput(input) guard coordinate_set.count > 0 else { throw ParseError.InvalidWktString(description: "Unable to parse input string") } return coordinate_set } var longitudeFirst = false convenience init(longitudeFirst: Bool) { self.init() self.longitudeFirst = longitudeFirst } init() {} // MARK: - Private // MARK: Parsing /** Parse input string into a collection of `CLLocationCoordinate2D` arrays that can be drawn on a map - note: This method supports (and really works best with/prefers) `Well-Known Text` format - parameter input: `NSString` to parse - returns: Collection of `CLLocationCoordinate2D` arrays */ internal func parseInput(input: NSString) -> [[CLLocationCoordinate2D]] { var array = [[NSString]]() let line = input as String if isProbablyGeoString(line) { self.longitudeFirst = true var items = [NSString]() if isMultiItem(line) { items = stripExtraneousCharacters(line).componentsSeparatedByString("),") } else { items = [stripExtraneousCharacters(line)] } array = items.map({ self.formatStandardGeoDataString($0) }) } let results = convertStringArraysToTuples(array) return results.filter({ !$0.isEmpty }).map{ self.convertToCoordinates($0, longitudeFirst: self.longitudeFirst) } } /** Convert an array of strings into tuple pairs. - note: the number of values passed in should probably be even, since it creates pairs. - parameter array: of `[NSString]` array to create tuples from - returns: array of collections of tuple pairs where the tuples are lat/lng values as `NSString`s */ internal func convertStringArraysToTuples(array: [[NSString]]) -> [[(NSString, NSString)]] { var tmpResults = [(NSString, NSString)]() var results = [[(NSString, NSString)]]() for arr in array { for i in 0.stride(to: arr.count - 1, by: 2) { let elem = (arr[i], arr[i + 1]) tmpResults.append(elem) } if tmpResults.count == 1 { tmpResults.append(tmpResults.first!) } results.append(tmpResults) tmpResults.removeAll(keepCapacity: false) } // end for arr in array return results } /** _abstract_: Naively format a `Well-Known Text` string into array of string values, where each string is a single value _discussion_: This removes any lingering parens from the given string, breaks on `,` then breaks on ` ` while filtering out any empty strings. - parameter input: String to format, assumed `Well-Known Text` format - returns: array of strings where each string is one value from the string with all empty strings filtered out. */ internal func formatStandardGeoDataString(input: NSString) -> [NSString] { // Remove Extra () let stripped = input .stringByReplacingOccurrencesOfString("(", withString: "") .stringByReplacingOccurrencesOfString(")", withString: "") // Break on ',' to get pairs separated by ' ' let pairs = stripped.componentsSeparatedByString(",") // break on " " and remove empties var filtered = [NSString]() for pair in pairs { pair.componentsSeparatedByString(" ").filter({!$0.isEmpty}).forEach({filtered.append($0)}) } return filtered.filter({!$0.isEmpty}) } private func formatCustomLatLongString(input: NSString) -> [NSString] { return input.stringByReplacingOccurrencesOfString("\n", withString: ",").componentsSeparatedByString(",") as [NSString] } private func splitLine(input: NSString, delimiter: NSString) -> (NSString, NSString) { let array = input.componentsSeparatedByString(delimiter as String) return (array.first! as NSString, array.last! as NSString) } /** :abstract: Convert a given array of `(String, String)` tuples to array of `CLLocationCoordinate2D` values :discussion: This attempts to parse the string's double values but does no safety checks if they can be parsed as `double`s. - parameter pairs: array of `String` tuples to parse as `Double`s - parameter longitudeFirst: boolean flag if the first item in the tuple should be the longitude value - returns: array of `CLLocationCoordinate2D` values */ internal func convertToCoordinates(pairs: [(NSString, NSString)], longitudeFirst: Bool) -> [CLLocationCoordinate2D] { var coordinates = [CLLocationCoordinate2D]() for pair in pairs { var lat: Double = 0.0 var lng: Double = 0.0 if longitudeFirst { lat = pair.1.doubleValue lng = pair.0.doubleValue } else { lat = pair.0.doubleValue lng = pair.1.doubleValue } coordinates.append(CLLocationCoordinate2D(latitude: lat, longitude: lng)) } return coordinates } /** Removes any text before lat long points as well as two outer sets of parens. Example: ``` input => "POLYGON(( 15 32 ))" output => "15 32" input => "MULTIPOLYGON((( 15 32 )))" output => "( 15 32 )" ``` - parameter input: NSString to strip extraneous characters from - returns: stripped string instance */ internal func stripExtraneousCharacters(input: NSString) -> NSString { let regex: NSRegularExpression? do { regex = try NSRegularExpression(pattern: "\\w+\\s*\\((.*)\\)", options: .CaseInsensitive) } catch _ { regex = nil } let match: AnyObject? = regex?.matchesInString(input as String, options: .ReportCompletion, range: NSMakeRange(0, input.length)).first let range = match?.rangeAtIndex(1) let loc = range?.location as Int! let len = range?.length as Int! guard loc != nil && len != nil else { return "" } return input.substringWithRange(NSRange(location: loc, length: len)) as NSString } /** _abstract_: Attempt to determine if a given string is in `Well-Known Text` format (GeoString as its referred to internally) _discussion_: This strips any leading & trailing white space before checking for the existance of word characters at the start of the string. - parameter input: String to attempt determine if is in `Well-Known Text` format - returns: `true` if it thinks it is, `false` otherwise */ internal func isProbablyGeoString(input: String) -> Bool { let stripped = input.stringByStrippingLeadingAndTrailingWhiteSpace() if stripped.rangeOfString("^\\w+", options: .RegularExpressionSearch) != nil { return true } return false } /** Determine if a given string is a `MULTI*` item. - parameter input: String to check - returns: `true` if the string starts with `MULTI`. `false` otherwise */ internal func isMultiItem(input: String) -> Bool { if input.rangeOfString("MULTI", options: .RegularExpressionSearch) != nil { return true } return false } /** Determines if a the collection is space delimited or not - note: This function should only be passed a single entry or else it will probably have incorrect results - parameter input: a single entry from the collection as a string - returns: `true` if elements are space delimited, `false` otherwise */ private func isSpaceDelimited(input: String) -> Bool { let array = input.componentsSeparatedByString(" ") return array.count > 1 } }
mit
325b27fc597e6816abc17ce9153e5c12
31.562044
144
0.681574
4.382122
false
false
false
false
alexanderwohltan/TimeTable
TimeTable/Data Classes/WebuntisAPI.swift
1
25921
// // WebuntisAPI.swift // TimeTable // // Created by Alexander Wohltan on 23.03.15. // Copyright (c) 2015 Alexander Wohltan. All rights reserved. // import Foundation let APIUSERNAME = "api" let APIUSERPASS = "a9067b34" public class WebUntisSession { var sessionID = "" var personType = 0 var personID = 0 var klasseID = 0 let jsonrpcURL : String = "/WebUntis/jsonrpc.do" var serverURL : String = "" var school : String = "" var isAuthenticating = false var isLoggedOut = true private var isRequestingTeachers = false private var isRequestingTutorGroups = false private var isRequestingSubjects = false private var isRequestingRooms = false private var isRequestingDepartments = false private var isRequestingHolidays = false private var isRequestingTimeGrid = false private var isRequestingStatusData = false private var isRequestingCurrentSchoolyear = false private var isRequestingSchoolyears = false private var isRequestingTimeTable = false private var operatingTasks: [Byte] = [] private var teachers: [Teacher] = [] private var tutorGroups: [TutorGroup] = [] private var subjects: [Subject] = [] private var rooms: [Room] = [] private var departments: [Department] = [] private var holidays: [Holiday] = [] private var timeGrid: TimeGrid = TimeGrid() private var statusData: StatusData = StatusData() private var currentSchoolyear: Schoolyear = Schoolyear() private var schoolyears: [Schoolyear] = [] private var timeTable: [Period] = [] init(user:String, pass:String, serverURL:String, school:String) { self.serverURL = serverURL self.school = school self.authenticate(user, pass: pass) } func sendAuthPOSTRequestToServer(requestBody: String, completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) { if isLoggedOut { var requestURL = "\(serverURL)\(jsonrpcURL)?school=\(school)" operatingTasks.append(1) sendPOSTRequest(requestURL, requestBody, completionHandler) } else { println("Cannot Authenticate - Already logged in. Log out first") } } func sendPOSTRequestToServer(requestBody: String, completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) { while self.isAuthenticating { NSThread.sleepForTimeInterval(0.1) } if !isLoggedOut { while(self.sessionID == "") { NSThread.sleepForTimeInterval(0.1) } var requestURL = "\(serverURL)\(jsonrpcURL)?jsessionid=\(sessionID)&school=\(school)" operatingTasks.append(1) var cookies: [String: String] = ["jsessionid": "\(sessionID)"] sendPOSTRequest(requestURL, requestBody, completionHandler) } else { println("Cannot send POST Request. Not logged in. Authenticate first") } } func sendDeAuthPOSTRequestToServer(requestBody: String, completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) { while operatingTasks.count != 0 { NSThread.sleepForTimeInterval(0.1) } sendPOSTRequestToServer(requestBody, completionHandler: completionHandler) } func authenticate(user:String, pass:String) { while isAuthenticating { NSThread.sleepForTimeInterval(0.1) } isAuthenticating = true let authID = 000001 var postBodyJSON : JSON = ["id":authID.toString(), "method":"authenticate", "params":["user":user,"password":pass,"client":"BESTSWIFTCLIENTEVER"], "jsonrpc":"2.0"] sendAuthPOSTRequestToServer(postBodyJSON.description, completionHandler: authenticationHandler) } func logout() { let logoutID = 000000 var postBodyJSON : JSON = ["id":"00000", "method":"logout", "params":[], "jsonrpc":"2.0"] sendDeAuthPOSTRequestToServer(postBodyJSON.description, completionHandler: logoutHandler) } func requestTeachers() { while isRequestingTeachers { NSThread.sleepForTimeInterval(0.1) } self.isRequestingTeachers = true let requestID = 001001 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getTeachers", "params":[], "jsonrpc":"2.0"] teachers.removeAll(keepCapacity: false) sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestTeachersHandler) } func requestTutorGroups() { while isRequestingTutorGroups { NSThread.sleepForTimeInterval(0.1) } self.isRequestingTutorGroups = true let requestID = 001002 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getKlassen", "params":[], "jsonrpc":"2.0"] tutorGroups.removeAll(keepCapacity: false) sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestTutorGroupsHandler) } func requestSubjects() { while isRequestingSubjects { NSThread.sleepForTimeInterval(0.1) } self.isRequestingSubjects = true let requestID = 001003 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getSubjects", "params":[], "jsonrpc":"2.0"] subjects.removeAll(keepCapacity: false) sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestSubjectsHandler) } func requestRooms() { while isRequestingRooms { NSThread.sleepForTimeInterval(0.1) } self.isRequestingRooms = true let requestID = 001004 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getRooms", "params":[], "jsonrpc":"2.0"] rooms.removeAll(keepCapacity: false) sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestRoomsHandler) } func requestDepartments() { while isRequestingDepartments { NSThread.sleepForTimeInterval(0.1) } self.isRequestingDepartments = true let requestID = 001005 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getDepartments", "params":[], "jsonrpc":"2.0"] departments.removeAll(keepCapacity: false) sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestDepartmentsHandler) } func requestHolidays() { while isRequestingHolidays { NSThread.sleepForTimeInterval(0.1) } self.isRequestingHolidays = true let requestID = 001006 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getHolidays", "params":[], "jsonrpc":"2.0"] holidays.removeAll(keepCapacity: false) sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestHolidaysHandler) } func requestTimeGrid() { while isRequestingTimeGrid { NSThread.sleepForTimeInterval(0.1) } self.isRequestingTimeGrid = true let requestID = 001007 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getTimegridUnits", "params":[], "jsonrpc":"2.0"] sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestTimeGridHandler) } func requestStatusData() { while isRequestingStatusData { NSThread.sleepForTimeInterval(0.1) } self.isRequestingStatusData = true let requestID = 001008 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getStatusData", "params":[], "jsonrpc":"2.0"] sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestStatusDataHandler) } func requestCurrentSchoolyear() { while isRequestingCurrentSchoolyear { NSThread.sleepForTimeInterval(0.1) } self.isRequestingCurrentSchoolyear = true let requestID = 001009 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getCurrentSchoolyear", "params":[], "jsonrpc":"2.0"] sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestCurrentSchoolyearHandler) } func requestSchoolyears() { while isRequestingSchoolyears { NSThread.sleepForTimeInterval(0.1) } self.isRequestingStatusData = true let requestID = 001010 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getSchoolyears", "params":[], "jsonrpc":"2.0"] sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestSchoolyearsHandler) } func requestTimeTable(id: Int, type: Int, startDate: String, endDate: String) { while isRequestingTimeTable { NSThread.sleepForTimeInterval(0.1) } if tutorGroups.count == 0 || subjects.count == 0 || rooms.count == 0 || teachers.count == 0 { println("Cannot request Time Table. Request tutorGroups, subjects, rooms and teachers first.") return } self.isRequestingTimeTable = true let requestID = 0010111 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getTimetable", "params":["id":id, "type":type, "startDate":startDate, "endDate":endDate], "jsonrpc":"2.0"] sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestTimeTableHandler) } func requestTimeTable(id: Int, type: Int) { while isRequestingTimeTable { NSThread.sleepForTimeInterval(0.1) } if tutorGroups.count == 0 || subjects.count == 0 || rooms.count == 0 || teachers.count == 0 { println("Cannot request Time Table. Request tutorGroups, subjects, rooms and teachers first.") return } self.isRequestingTimeTable = true let requestID = 0010110 var requestBodyJSON : JSON = ["id":requestID.toString(), "method":"getTimetable", "params":["id":id, "type":type], "jsonrpc":"2.0"] sendPOSTRequestToServer(requestBodyJSON.description, completionHandler: requestTimeTableHandler) } func authenticationHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error While Authenticating = \(error)") return } //println("response = \(response)") //let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! //println("responseString (Authentication) = \(responseString)") let responseJSON = JSON(data: data!) self.sessionID = (responseJSON["result"]["sessionId"] as JSON).stringValue self.personType = (responseJSON["result"]["personType"] as JSON).intValue self.personID = (responseJSON["resudddlt"]["personId"] as JSON).intValue self.klasseID = (responseJSON["result"]["klasseId"] as JSON).intValue println("Authenticated with Session ID \(self.sessionID) at school \(school)") self.isAuthenticating = false self.isLoggedOut = false endHandler() } func logoutHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error while logging out = \(error)") return } for cookie : NSHTTPCookie in NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies! as [NSHTTPCookie] { NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(cookie) } //println("response = \(response)") let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) self.isLoggedOut = true println("Logged out (Session ID: \(self.sessionID))") endHandler() } func requestTeachersHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error While Fetching Teachers = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! let responseJSON = JSON(data: data!) for teacher in responseJSON["result"] { teachers.append(Teacher(json: teacher.1)) } self.isRequestingTeachers = false println("Requested Teachers from school \(school). Got \(teachers.count) teachers") endHandler() } func requestTutorGroupsHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error While Fetching Tutor Groups = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! let responseJSON = JSON(data: data!) for tutorGroup in responseJSON["result"] { tutorGroups.append(TutorGroup(json: tutorGroup.1)) } self.isRequestingTutorGroups = false println("Requested Tutor Groups from school \(school). Got \(tutorGroups.count) Tutor Groups") endHandler() } func requestSubjectsHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error While Fetching Subjects = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! let responseJSON = JSON(data: data!) for subject in responseJSON["result"] { subjects.append(Subject(json: subject.1)) } self.isRequestingSubjects = false println("Requested Subjects from school \(school). Got \(subjects.count) Subjects") endHandler() } func requestRoomsHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error While Fetching Rooms = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! let responseJSON = JSON(data: data!) for room in responseJSON["result"] { rooms.append(Room(json: room.1)) } self.isRequestingRooms = false println("Requested Rooms from school \(school). Got \(rooms.count) Rooms") endHandler() } func requestDepartmentsHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error While Fetching Departments = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! //println("Response (Requesting Departments): \(responseString)") let responseJSON = JSON(data: data!) for department in responseJSON["result"] { departments.append(Department(json: department.1)) } self.isRequestingDepartments = false println("Requested Departments from school \(school). Got \(departments.count) Department") endHandler() } func requestHolidaysHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error While Fetching Holidays = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! //println("Response (Requesting Holidays): \(responseString)") let responseJSON = JSON(data: data!) for holiday in responseJSON["result"] { holidays.append(Holiday(json: holiday.1)) } self.isRequestingHolidays = false println("Requested Holidays from school \(school). Got \(holidays.count) Holidays") endHandler() } func requestTimeGridHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error While Fetching the Time Grid = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! //println("Response (Requesting TimeGrid): \(responseString)") let responseJSON = JSON(data: data!) timeGrid = TimeGrid(json: responseJSON["result"]) self.isRequestingTimeGrid = false println("Requested the Time Grid from school \(school). Got \(timeGrid.days.count) Days") endHandler() } func requestStatusDataHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error While Fetching Status Data = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! //println("Response (Requesting StatusData): \(responseString)") let responseJSON = JSON(data: data!) statusData = StatusData(json: responseJSON["result"]) self.isRequestingStatusData = false println("Requested Status Data from school \(school). The backcolor of a normal lesson is \(statusData.lessonTypeData[LessonType.Lesson]?.backColor)") endHandler() } func requestCurrentSchoolyearHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error while fetching current schoolyear = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! //println("Response (Requesting Current Schoolyear): \(responseString)") let responseJSON = JSON(data: data!) currentSchoolyear = Schoolyear(json: responseJSON["result"]) self.isRequestingCurrentSchoolyear = false println("Requested the current schoolyear from school \(school). The current schoolyear is \(currentSchoolyear.name)") endHandler() } func requestSchoolyearsHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error while fetching schoolyears = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! //println("Response (Requesting Schoolyears): \(responseString)") let responseJSON = JSON(data: data!) for year in responseJSON["result"] { schoolyears.append(Schoolyear(json: year.1)) } self.isRequestingSchoolyears = false println("Requested Status Data from school \(school). Got \(schoolyears.count) schoolyears") endHandler() } func requestTimeTableHandler(data: NSData!, response: NSURLResponse!, error: NSError!) { if error != nil { println("Error while fetching timeTable = \(error)") return } //println("response = \(response)") let responseString : String = NSString(data: data, encoding: NSUTF8StringEncoding)! println("Response (Requesting timetable): \(responseString)") let responseJSON = JSON(data: data!) for period in responseJSON["result"] { timeTable.append(Period(json: period.1, tutorGroupList: tutorGroups, teacherList: teachers, subjectList: subjects, roomList: rooms)) } self.isRequestingTimeTable = false println("Requested the time table from school \(school). The time table has \(timeTable.count) entries.") endHandler() } func getTeachers() -> [Teacher] { requestTeachers() while isRequestingTeachers { NSThread.sleepForTimeInterval(0.1) } return teachers } func getTutorGroups() -> [TutorGroup] { requestTutorGroups() while isRequestingTutorGroups { NSThread.sleepForTimeInterval(0.1) } return tutorGroups } func getSubjects() -> [Subject] { requestSubjects() while isRequestingSubjects { NSThread.sleepForTimeInterval(0.1) } return subjects } func getRooms() -> [Room] { requestRooms() while isRequestingRooms { NSThread.sleepForTimeInterval(0.1) } return rooms } func getDepartments() -> [Department] { requestDepartments() while isRequestingDepartments { NSThread.sleepForTimeInterval(0.1) } return departments } func getHolidays() -> [Holiday] { requestHolidays() while isRequestingHolidays { NSThread.sleepForTimeInterval(0.1) } return holidays } func getTimeGrid() -> TimeGrid { requestTimeGrid() while isRequestingTimeGrid { NSThread.sleepForTimeInterval(0.1) } return timeGrid } func getStatusData() -> StatusData { requestStatusData() while isRequestingStatusData { NSThread.sleepForTimeInterval(0.1) } return statusData } func getCurrentSchoolyear() -> Schoolyear { requestCurrentSchoolyear() while isRequestingCurrentSchoolyear { NSThread.sleepForTimeInterval(0.1) } return currentSchoolyear } func getSchoolyears() -> [Schoolyear] { requestSchoolyears() while isRequestingSchoolyears { NSThread.sleepForTimeInterval(0.1) } return schoolyears } func getTimeTable(id: Int, type: Int, startDate: String, endDate: String) -> [Period] { requestTimeTable(id, type: type, startDate: startDate, endDate: endDate) while isRequestingTimeTable { NSThread.sleepForTimeInterval(0.1) } return timeTable } func getTimeTable(id: Int, type: Int) -> [Period] { requestTimeTable(id, type: type) while isRequestingTimeTable { NSThread.sleepForTimeInterval(0.1) } return timeTable } func endHandler() { operatingTasks.removeLast() } func toString() -> String { return "SessionID: \(sessionID)" } } func testAPI() { var x = WebUntisSession(user: APIUSERNAME, pass: APIUSERPASS, serverURL: "https://melete.webuntis.com", school: "htl-donaustadt") x.getTeachers() var tg = x.getTutorGroups() x.getSubjects() x.getRooms() x.getDepartments() x.getHolidays() x.getTimeGrid() x.getStatusData() x.getCurrentSchoolyear() x.getSchoolyears() for tutorGroup in tg { if tutorGroup.id == x.klasseID { println(tutorGroup.name) } } x.getTimeTable(x.getTeachers()[26].id, type: ElementType.Teacher.rawValue, startDate: "20150324", endDate: "20150324") x.logout() } func sendPOSTRequest(requestURL: String, requestBody: String, completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?, cookies: [String : String]) { let request = NSMutableURLRequest(URL: NSURL(string: requestURL)!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") for (title, value) in cookies { request.addValue(value, forHTTPHeaderField: title) } request.HTTPBody = requestBody.dataUsingEncoding(NSUTF8StringEncoding) //request.HTTPShouldHandleCookies = false NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: completionHandler).resume() } func sendPOSTRequest(requestURL: String, requestBody: String, completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) { sendPOSTRequest(requestURL, requestBody, completionHandler, [:]) }
gpl-3.0
f666ce87cc90010ac928deefa0bb5608
31.042027
181
0.593264
5.016644
false
false
false
false
DanielZakharin/Shelfie
Shelfie/Shelfie/TESTViewController.swift
1
3033
// // TESTViewController.swift // Shelfie // // Created by iosdev on 11.10.2017. // Copyright ยฉ 2017 Group-6. All rights reserved. // import UIKit import CoreData import PieCharts class TESTViewController: UIViewController { let coreSingleton = CoreDataSingleton.sharedInstance; @IBOutlet weak var testTxtField: UITextView! @IBOutlet weak var testTxtField2: UITextView! @IBOutlet weak var testTxtField3: UITextView! @IBOutlet weak var testCont: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // legetest.setLegends(.circle(radius: 7), [ // (text: "Chemicals", color: UIColor.orange), // (text: "Forestry", color: UIColor.green) // ]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func testBtn1(_ sender: Any) { coreSingleton.deleteAllData(entity: "Chain"); coreSingleton.deleteAllData(entity: "StoreChain"); coreSingleton.deleteAllData(entity: "Store"); coreSingleton.deleteAllData(entity: "ShelfPlan"); coreSingleton.deleteAllData(entity: "ShelfBox"); coreSingleton.deleteAllData(entity: "Manufacturer"); coreSingleton.deleteAllData(entity: "Product"); coreSingleton.deleteAllData(entity: "ProductBrand"); } @IBAction func testBtn2(_ sender: Any) { let stores = coreSingleton.fetchEntitiesFromCoreData("Store") as! [Store]; var testStr = "here is what i got:\n"; for jee in stores{ testStr += "Name:\(jee.storeName!)\nAddress:\(jee.storeAddress!)\nContactPerson:\(jee.contactPerson!)\nContactNumber:\(jee.contactNumber!)\nStoreChain:\(jee.storeChain?.storeChainName)\n\n"; } testTxtField.text = testStr; } @IBAction func testBtn3(_ sender: UIButton) { let chains = CoreDataSingleton.sharedInstance.fetchEntitiesFromCoreData("Chain") as! [Chain]; testTxtField2.text! = ""; for chain in chains{ testTxtField2.text! += "Chain name: \(chain.chainName!)\nStoreChains: \(chain.storeChains!.count)\n\n" } } @IBAction func testBtn4(_ sender: UIButton) { let sps = coreSingleton.fetchEntitiesFromCoreData("ShelfPlan") as! [ShelfPlan]; testTxtField3.text = ""; for sp in sps { testTxtField3.text! += "ShelfPlan: \nstore:\(sp.store?.storeName)\nboxes: \(sp.boxes?.count) \n\n" } } /* // 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. } */ }
gpl-3.0
98ed25fe9ca83c056c6197a94e0ebd6e
34.255814
202
0.640501
4.282486
false
true
false
false
slavapestov/swift
stdlib/public/core/StringUTF8.swift
1
14488
//===--- StringUTF8.swift - A UTF8 view of _StringCore --------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // _StringCore currently has three representations: Native ASCII, // Native UTF-16, and Opaque Cocoa. Expose each of these as UTF-8 in a // way that will hopefully be efficient to traverse // //===----------------------------------------------------------------------===// extension _StringCore { /// An integral type that holds a sequence of UTF-8 code units, starting in /// its low byte. public typealias UTF8Chunk = UInt64 /// Encode text starting at `i` as UTF-8. Returns a pair whose first /// element is the index of the text following whatever got encoded, /// and the second element contains the encoded UTF-8 starting in its /// low byte. Any unused high bytes in the result will be set to /// 0xFF. @warn_unused_result func _encodeSomeUTF8(i: Int) -> (Int, UTF8Chunk) { _sanityCheck(i <= count) if _fastPath(elementWidth == 1) { // How many UTF-16 code units might we use before we've filled up // our UTF8Chunk with UTF-8 code units? let utf16Count = min(sizeof(UTF8Chunk.self), count - i) var result: UTF8Chunk = ~0 // Start with all bits set _memcpy( dest: UnsafeMutablePointer(Builtin.addressof(&result)), src: UnsafeMutablePointer(startASCII + i), size: numericCast(utf16Count)) return (i + utf16Count, result) } else if _fastPath(!_baseAddress._isNull) { return _encodeSomeContiguousUTF16AsUTF8(i) } else { #if _runtime(_ObjC) return _encodeSomeNonContiguousUTF16AsUTF8(i) #else _sanityCheckFailure("_encodeSomeUTF8: Unexpected cocoa string") #endif } } /// Helper for `_encodeSomeUTF8`, above. Handles the case where the /// storage is contiguous UTF-16. @warn_unused_result func _encodeSomeContiguousUTF16AsUTF8(i: Int) -> (Int, UTF8Chunk) { _sanityCheck(elementWidth == 2) _sanityCheck(!_baseAddress._isNull) let storage = UnsafeBufferPointer(start: startUTF16, count: self.count) return _transcodeSomeUTF16AsUTF8(storage, i) } #if _runtime(_ObjC) /// Helper for `_encodeSomeUTF8`, above. Handles the case where the /// storage is non-contiguous UTF-16. @warn_unused_result func _encodeSomeNonContiguousUTF16AsUTF8(i: Int) -> (Int, UTF8Chunk) { _sanityCheck(elementWidth == 2) _sanityCheck(_baseAddress._isNull) let storage = _CollectionOf<Int, UInt16>( startIndex: 0, endIndex: self.count) { (i: Int) -> UInt16 in return _cocoaStringSubscript(self, i) } return _transcodeSomeUTF16AsUTF8(storage, i) } #endif } extension String { /// A collection of UTF-8 code units that encodes a `String` value. public struct UTF8View : CollectionType, CustomStringConvertible, CustomDebugStringConvertible { internal let _core: _StringCore internal let _startIndex: Index internal let _endIndex: Index init(_ _core: _StringCore) { self._core = _core self._endIndex = Index(_core, _core.endIndex, Index._emptyBuffer) if _fastPath(_core.count != 0) { let (_, buffer) = _core._encodeSomeUTF8(0) self._startIndex = Index(_core, 0, buffer) } else { self._startIndex = self._endIndex } } init(_ _core: _StringCore, _ s: Index, _ e: Index) { self._core = _core self._startIndex = s self._endIndex = e } /// A position in a `String.UTF8View`. public struct Index : ForwardIndexType { internal typealias Buffer = _StringCore.UTF8Chunk init(_ _core: _StringCore, _ _coreIndex: Int, _ _buffer: Buffer) { self._core = _core self._coreIndex = _coreIndex self._buffer = _buffer _sanityCheck(_coreIndex >= 0) _sanityCheck(_coreIndex <= _core.count) } /// Returns the next consecutive value after `self`. /// /// - Requires: The next value is representable. @warn_unused_result public func successor() -> Index { let currentUnit = UTF8.CodeUnit(truncatingBitPattern: _buffer) let hiNibble = currentUnit >> 4 // Map the high nibble of the current code unit into the // amount by which to increment the utf16 index. Only when // the high nibble is 1111 do we have a surrogate pair. let u16Increments = Int(bitPattern: // 1111 1110 1101 1100 1011 1010 1001 1000 0111 0110 0101 0100 0011 0010 0001 0000 0b10___01___01___01___00___00___00___00___01___01___01___01___01___01___01___01) let increment = (u16Increments >> numericCast(hiNibble << 1)) & 0x3 let nextCoreIndex = _coreIndex &+ increment let nextBuffer = Index._nextBuffer(_buffer) // if the nextBuffer is non-empty, we have all we need if _fastPath(nextBuffer != Index._emptyBuffer) { return Index(_core, nextCoreIndex, nextBuffer) } // If the underlying UTF16 isn't exhausted, fill a new buffer else if _fastPath(nextCoreIndex < _core.endIndex) { let (_, freshBuffer) = _core._encodeSomeUTF8(nextCoreIndex) return Index(_core, nextCoreIndex, freshBuffer) } else { // Produce the endIndex _precondition( nextCoreIndex == _core.endIndex, "Can't increment past endIndex of String.UTF8View") return Index(_core, nextCoreIndex, nextBuffer) } } /// True iff the index is at the end of its view or if the next /// byte begins a new UnicodeScalar. internal var _isOnUnicodeScalarBoundary : Bool { let next = UTF8.CodeUnit(truncatingBitPattern: _buffer) return UTF8._numTrailingBytes(next) != 4 || _isAtEnd } /// True iff the index is at the end of its view internal var _isAtEnd : Bool { return _buffer == Index._emptyBuffer && _coreIndex == _core.endIndex } /// The value of the buffer when it is empty internal static var _emptyBuffer: Buffer { return ~0 } /// A Buffer value with the high byte set internal static var _bufferHiByte: Buffer { return 0xFF << numericCast((sizeof(Buffer.self) &- 1) &* 8) } /// Consume a byte of the given buffer: shift out the low byte /// and put FF in the high byte internal static func _nextBuffer(thisBuffer: Buffer) -> Buffer { return (thisBuffer >> 8) | _bufferHiByte } /// The underlying buffer we're presenting as UTF8 internal let _core: _StringCore /// The position of `self`, rounded up to the nearest unicode /// scalar boundary, in the underlying UTF16. internal let _coreIndex: Int /// If `self` is at the end of its `_core`, has the value `_endBuffer`. /// Otherwise, the low byte contains the value of internal let _buffer: Buffer } /// The position of the first code unit if the `String` is /// non-empty; identical to `endIndex` otherwise. public var startIndex: Index { return self._startIndex } /// The "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Index { return self._endIndex } /// Access the element at `position`. /// /// - Requires: `position` is a valid position in `self` and /// `position != endIndex`. public subscript(position: Index) -> UTF8.CodeUnit { let result: UTF8.CodeUnit = numericCast(position._buffer & 0xFF) _precondition(result != 0xFF, "cannot subscript using endIndex") return result } /// Access the elements delimited by the given half-open range of /// indices. /// /// - Complexity: O(1) unless bridging from Objective-C requires an /// O(N) conversion. public subscript(subRange: Range<Index>) -> UTF8View { return UTF8View(_core, subRange.startIndex, subRange.endIndex) } public var description: String { return String._fromCodeUnitSequenceWithRepair(UTF8.self, input: self).0 } public var debugDescription: String { return "UTF8View(\(self.description.debugDescription))" } } /// A UTF-8 encoding of `self`. public var utf8: UTF8View { return UTF8View(self._core) } public var _contiguousUTF8: UnsafeMutablePointer<UTF8.CodeUnit> { return _core.elementWidth == 1 ? _core.startASCII : nil } /// A contiguously-stored nul-terminated UTF-8 representation of /// `self`. /// /// To access the underlying memory, invoke /// `withUnsafeBufferPointer` on the `ContiguousArray`. public var nulTerminatedUTF8: ContiguousArray<UTF8.CodeUnit> { var result = ContiguousArray<UTF8.CodeUnit>() result.reserveCapacity(utf8.count + 1) result += utf8 result.append(0) return result } /// Construct the `String` corresponding to the given sequence of /// UTF-8 code units. If `utf8` contains unpaired surrogates, the /// result is `nil`. public init?(_ utf8: UTF8View) { let wholeString = String(utf8._core) if let start = utf8.startIndex.samePositionIn(wholeString), let end = utf8.endIndex.samePositionIn(wholeString) { self = wholeString[start..<end] return } return nil } /// The index type for subscripting a `String`'s `.utf8` view. public typealias UTF8Index = UTF8View.Index } @warn_unused_result public func == ( lhs: String.UTF8View.Index, rhs: String.UTF8View.Index ) -> Bool { // If the underlying UTF16 index differs, they're unequal if lhs._coreIndex != rhs._coreIndex { return false } // Match up bytes in the buffer var buffer = (lhs._buffer, rhs._buffer) var isContinuation: Bool repeat { let unit = ( UTF8.CodeUnit(truncatingBitPattern: buffer.0), UTF8.CodeUnit(truncatingBitPattern: buffer.1)) isContinuation = UTF8.isContinuation(unit.0) if !isContinuation { // We don't check for unit equality in this case because one of // the units might be an 0xFF read from the end of the buffer. return !UTF8.isContinuation(unit.1) } // Continuation bytes must match exactly else if unit.0 != unit.1 { return false } // Move the buffers along. buffer = ( String.UTF8Index._nextBuffer(buffer.0), String.UTF8Index._nextBuffer(buffer.1)) } while true } // Index conversions extension String.UTF8View.Index { internal init(_ core: _StringCore, _utf16Offset: Int) { let (_, buffer) = core._encodeSomeUTF8(_utf16Offset) self.init(core, _utf16Offset, buffer) } /// Construct the position in `utf8` that corresponds exactly to /// `utf16Index`. If no such position exists, the result is `nil`. /// /// - Requires: `utf8Index` is an element of /// `String(utf16)!.utf8.indices`. public init?(_ utf16Index: String.UTF16Index, within utf8: String.UTF8View) { let utf16 = String.UTF16View(utf8._core) if utf16Index != utf16.startIndex && utf16Index != utf16.endIndex { _precondition( utf16Index >= utf16.startIndex && utf16Index <= utf16.endIndex, "Invalid String.UTF16Index for this UTF-8 view") // Detect positions that have no corresponding index. Note that // we have to check before and after, because an unpaired // surrogate will be decoded as a single replacement character, // thus making the corresponding position valid in UTF8. if UTF16.isTrailSurrogate(utf16[utf16Index]) && UTF16.isLeadSurrogate(utf16[utf16Index.predecessor()]) { return nil } } self.init(utf8._core, _utf16Offset: utf16Index._offset) } /// Construct the position in `utf8` that corresponds exactly to /// `unicodeScalarIndex`. /// /// - Requires: `unicodeScalarIndex` is an element of /// `String(utf8)!.unicodeScalars.indices`. public init( _ unicodeScalarIndex: String.UnicodeScalarIndex, within utf8: String.UTF8View ) { self.init(utf8._core, _utf16Offset: unicodeScalarIndex._position) } /// Construct the position in `utf8` that corresponds exactly to /// `characterIndex`. /// /// - Requires: `characterIndex` is an element of /// `String(utf8)!.indices`. public init(_ characterIndex: String.Index, within utf8: String.UTF8View) { self.init(utf8._core, _utf16Offset: characterIndex._base._position) } /// Return the position in `utf16` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// - Requires: `self` is an element of `String(utf16)!.utf8.indices`. @warn_unused_result public func samePositionIn( utf16: String.UTF16View ) -> String.UTF16View.Index? { return String.UTF16View.Index(self, within: utf16) } /// Return the position in `unicodeScalars` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// - Requires: `self` is an element of /// `String(unicodeScalars).utf8.indices`. @warn_unused_result public func samePositionIn( unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarIndex? { return String.UnicodeScalarIndex(self, within: unicodeScalars) } /// Return the position in `characters` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// - Requires: `self` is an element of `characters.utf8.indices`. @warn_unused_result public func samePositionIn( characters: String ) -> String.Index? { return String.Index(self, within: characters) } } // Reflection extension String.UTF8View : CustomReflectable { /// Returns a mirror that reflects `self`. @warn_unused_result public func customMirror() -> Mirror { return Mirror(self, unlabeledChildren: self) } } extension String.UTF8View : CustomPlaygroundQuickLookable { public func customPlaygroundQuickLook() -> PlaygroundQuickLook { return .Text(description) } }
apache-2.0
aaaf4d3139f3beca60c76cf27f77d057
33.413302
98
0.647363
4.074241
false
false
false
false
slavapestov/swift
test/SILGen/witness_tables.swift
2
39128
// RUN: %target-swift-frontend -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module > %t.sil // RUN: FileCheck -check-prefix=TABLE -check-prefix=TABLE-ALL %s < %t.sil // RUN: FileCheck -check-prefix=SYMBOL %s < %t.sil // RUN: %target-swift-frontend -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-testing > %t.testable.sil // RUN: FileCheck -check-prefix=TABLE-TESTABLE -check-prefix=TABLE-ALL %s < %t.testable.sil // RUN: FileCheck -check-prefix=SYMBOL-TESTABLE %s < %t.testable.sil import witness_tables_b struct Arg {} @objc class ObjCClass {} infix operator <~> {} protocol AssocReqt { func requiredMethod() } protocol ArchetypeReqt { func requiredMethod() } protocol AnyProtocol { typealias AssocType typealias AssocWithReqt: AssocReqt func method(x x: Arg, y: Self) func generic<A: ArchetypeReqt>(x x: A, y: Self) func assocTypesMethod(x x: AssocType, y: AssocWithReqt) static func staticMethod(x x: Self) func <~>(x: Self, y: Self) } protocol ClassProtocol : class { typealias AssocType typealias AssocWithReqt: AssocReqt func method(x x: Arg, y: Self) func generic<B: ArchetypeReqt>(x x: B, y: Self) func assocTypesMethod(x x: AssocType, y: AssocWithReqt) static func staticMethod(x x: Self) func <~>(x: Self, y: Self) } @objc protocol ObjCProtocol { func method(x x: ObjCClass) static func staticMethod(y y: ObjCClass) } class SomeAssoc {} struct ConformingAssoc : AssocReqt { func requiredMethod() {} } // TABLE-LABEL: sil_witness_table hidden ConformingAssoc: AssocReqt module witness_tables { // TABLE-TESTABLE-LABEL: sil_witness_table ConformingAssoc: AssocReqt module witness_tables { // TABLE-ALL-NEXT: method #AssocReqt.requiredMethod!1: @_TTWV14witness_tables15ConformingAssocS_9AssocReqtS_FS1_14requiredMethod{{.*}} // TABLE-ALL-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables15ConformingAssocS_9AssocReqtS_FS1_14requiredMethod{{.*}} : $@convention(witness_method) (@in_guaranteed ConformingAssoc) -> () // SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables15ConformingAssocS_9AssocReqtS_FS1_14requiredMethod{{.*}} : $@convention(witness_method) (@in_guaranteed ConformingAssoc) -> () struct ConformingStruct : AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ConformingStruct) {} func generic<D: ArchetypeReqt>(x x: D, y: ConformingStruct) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: ConformingStruct) {} } func <~>(x: ConformingStruct, y: ConformingStruct) {} // TABLE-LABEL: sil_witness_table hidden ConformingStruct: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} // TABLE-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_7generic{{.*}}: ArchetypeReqt> (@in A, @in ConformingStruct, @in_guaranteed ConformingStruct) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingStruct, @thick ConformingStruct.Type) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> () // SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> () // SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in ConformingStruct, @in_guaranteed ConformingStruct) -> () // SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> () // SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingStruct, @thick ConformingStruct.Type) -> () // SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> () protocol AddressOnly {} struct ConformingAddressOnlyStruct : AnyProtocol { var p: AddressOnly // force address-only layout with a protocol-type field typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ConformingAddressOnlyStruct) {} func generic<E: ArchetypeReqt>(x x: E, y: ConformingAddressOnlyStruct) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: ConformingAddressOnlyStruct) {} } func <~>(x: ConformingAddressOnlyStruct, y: ConformingAddressOnlyStruct) {} // TABLE-LABEL: sil_witness_table hidden ConformingAddressOnlyStruct: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} // TABLE-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingAddressOnlyStruct) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingAddressOnlyStruct, @in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> () class ConformingClass : AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ConformingClass) {} func generic<F: ArchetypeReqt>(x x: F, y: ConformingClass) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} class func staticMethod(x x: ConformingClass) {} } func <~>(x: ConformingClass, y: ConformingClass) {} // TABLE-LABEL: sil_witness_table hidden ConformingClass: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} // TABLE-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingClass, @in_guaranteed ConformingClass) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in ConformingClass, @in_guaranteed ConformingClass) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingClass) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingClass, @thick ConformingClass.Type) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingClass, @in ConformingClass, @thick ConformingClass.Type) -> () struct ConformsByExtension {} extension ConformsByExtension : AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ConformsByExtension) {} func generic<G: ArchetypeReqt>(x x: G, y: ConformsByExtension) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: ConformsByExtension) {} } func <~>(x: ConformsByExtension, y: ConformsByExtension) {} // TABLE-LABEL: sil_witness_table hidden ConformsByExtension: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} // TABLE-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsByExtension) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformsByExtension, @thick ConformsByExtension.Type) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformsByExtension, @in ConformsByExtension, @thick ConformsByExtension.Type) -> () extension OtherModuleStruct : AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: OtherModuleStruct) {} func generic<H: ArchetypeReqt>(x x: H, y: OtherModuleStruct) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: OtherModuleStruct) {} } func <~>(x: OtherModuleStruct, y: OtherModuleStruct) {} // TABLE-LABEL: sil_witness_table hidden OtherModuleStruct: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_oi3ltg{{.*}} // TABLE-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_6method{{.*}} : $@convention(witness_method) (Arg, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed OtherModuleStruct) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_12staticMethod{{.*}} : $@convention(witness_method) (@in OtherModuleStruct, @thick OtherModuleStruct.Type) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_oi3ltg{{.*}} : $@convention(witness_method) (@in OtherModuleStruct, @in OtherModuleStruct, @thick OtherModuleStruct.Type) -> () protocol OtherProtocol {} struct ConformsWithMoreGenericWitnesses : AnyProtocol, OtherProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method<I, J>(x x: I, y: J) {} func generic<K, L>(x x: K, y: L) {} func assocTypesMethod<M, N>(x x: M, y: N) {} static func staticMethod<O>(x x: O) {} } func <~> <P: OtherProtocol>(x: P, y: P) {} // TABLE-LABEL: sil_witness_table hidden ConformsWithMoreGenericWitnesses: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} // TABLE-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsWithMoreGenericWitnesses) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGenericWitnesses, @in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> () class ConformingClassToClassProtocol : ClassProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ConformingClassToClassProtocol) {} func generic<Q: ArchetypeReqt>(x x: Q, y: ConformingClassToClassProtocol) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} class func staticMethod(x x: ConformingClassToClassProtocol) {} } func <~>(x: ConformingClassToClassProtocol, y: ConformingClassToClassProtocol) {} // TABLE-LABEL: sil_witness_table hidden ConformingClassToClassProtocol: ClassProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #ClassProtocol.method!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_6method{{.*}} // TABLE-NEXT: method #ClassProtocol.generic!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_7generic{{.*}} // TABLE-NEXT: method #ClassProtocol.assocTypesMethod!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_16assocTypesMethod{{.*}} // TABLE-NEXT: method #ClassProtocol.staticMethod!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_12staticMethod{{.*}} // TABLE-NEXT: method #ClassProtocol."<~>"!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_oi3ltg{{.*}} // TABLE-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <B where B : ArchetypeReqt> (@in B, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @guaranteed ConformingClassToClassProtocol) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@owned ConformingClassToClassProtocol, @owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> () class ConformingClassToObjCProtocol : ObjCProtocol { @objc func method(x x: ObjCClass) {} @objc class func staticMethod(y y: ObjCClass) {} } // TABLE-NOT: sil_witness_table hidden ConformingClassToObjCProtocol struct ConformingGeneric<R: AssocReqt> : AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = R func method(x x: Arg, y: ConformingGeneric) {} func generic<Q: ArchetypeReqt>(x x: Q, y: ConformingGeneric) {} func assocTypesMethod(x x: SomeAssoc, y: R) {} static func staticMethod(x x: ConformingGeneric) {} } func <~> <R: AssocReqt>(x: ConformingGeneric<R>, y: ConformingGeneric<R>) {} // TABLE-LABEL: sil_witness_table hidden <R where R : AssocReqt> ConformingGeneric<R>: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: R // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_FS2_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_FS2_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_FS2_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_ZFS2_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_ZFS2_oi3ltg{{.*}} // TABLE-NEXT: } protocol AnotherProtocol {} struct ConformingGenericWithMoreGenericWitnesses<S: AssocReqt> : AnyProtocol, AnotherProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = S func method<T, U>(x x: T, y: U) {} func generic<V, W>(x x: V, y: W) {} func assocTypesMethod<X, Y>(x x: X, y: Y) {} static func staticMethod<Z>(x x: Z) {} } func <~> <AA: AnotherProtocol, BB: AnotherProtocol>(x: AA, y: BB) {} // TABLE-LABEL: sil_witness_table hidden <S where S : AssocReqt> ConformingGenericWithMoreGenericWitnesses<S>: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: S // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_FS2_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_FS2_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_FS2_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_ZFS2_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_ZFS2_oi3ltg{{.*}} // TABLE-NEXT: } protocol InheritedProtocol1 : AnyProtocol { func inheritedMethod() } protocol InheritedProtocol2 : AnyProtocol { func inheritedMethod() } protocol InheritedClassProtocol : class, AnyProtocol { func inheritedMethod() } struct InheritedConformance : InheritedProtocol1 { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: InheritedConformance) {} func generic<H: ArchetypeReqt>(x x: H, y: InheritedConformance) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: InheritedConformance) {} func inheritedMethod() {} } func <~>(x: InheritedConformance, y: InheritedConformance) {} // TABLE-LABEL: sil_witness_table hidden InheritedConformance: InheritedProtocol1 module witness_tables { // TABLE-NEXT: base_protocol AnyProtocol: InheritedConformance: AnyProtocol module witness_tables // TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_TTWV14witness_tables20InheritedConformanceS_18InheritedProtocol1S_FS1_15inheritedMethod{{.*}} // TABLE-NEXT: } // TABLE-LABEL: sil_witness_table hidden InheritedConformance: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} // TABLE-NEXT: } struct RedundantInheritedConformance : InheritedProtocol1, AnyProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: RedundantInheritedConformance) {} func generic<H: ArchetypeReqt>(x x: H, y: RedundantInheritedConformance) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: RedundantInheritedConformance) {} func inheritedMethod() {} } func <~>(x: RedundantInheritedConformance, y: RedundantInheritedConformance) {} // TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: InheritedProtocol1 module witness_tables { // TABLE-NEXT: base_protocol AnyProtocol: RedundantInheritedConformance: AnyProtocol module witness_tables // TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_18InheritedProtocol1S_FS1_15inheritedMethod{{.*}} // TABLE-NEXT: } // TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} // TABLE-NEXT: } struct DiamondInheritedConformance : InheritedProtocol1, InheritedProtocol2 { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: DiamondInheritedConformance) {} func generic<H: ArchetypeReqt>(x x: H, y: DiamondInheritedConformance) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} static func staticMethod(x x: DiamondInheritedConformance) {} func inheritedMethod() {} } func <~>(x: DiamondInheritedConformance, y: DiamondInheritedConformance) {} // TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol1 module witness_tables { // TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables // TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_18InheritedProtocol1S_FS1_15inheritedMethod{{.*}} // TABLE-NEXT: } // TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol2 module witness_tables { // TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables // TABLE-NEXT: method #InheritedProtocol2.inheritedMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_18InheritedProtocol2S_FS1_15inheritedMethod{{.*}} // TABLE-NEXT: } // TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} // TABLE-NEXT: } class ClassInheritedConformance : InheritedClassProtocol { typealias AssocType = SomeAssoc typealias AssocWithReqt = ConformingAssoc func method(x x: Arg, y: ClassInheritedConformance) {} func generic<H: ArchetypeReqt>(x x: H, y: ClassInheritedConformance) {} func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {} class func staticMethod(x x: ClassInheritedConformance) {} func inheritedMethod() {} } func <~>(x: ClassInheritedConformance, y: ClassInheritedConformance) {} // TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: InheritedClassProtocol module witness_tables { // TABLE-NEXT: base_protocol AnyProtocol: ClassInheritedConformance: AnyProtocol module witness_tables // TABLE-NEXT: method #InheritedClassProtocol.inheritedMethod!1: @_TTWC14witness_tables25ClassInheritedConformanceS_22InheritedClassProtocolS_FS1_15inheritedMethod{{.*}} // TABLE-NEXT: } // TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: AnyProtocol module witness_tables { // TABLE-NEXT: associated_type AssocType: SomeAssoc // TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc // TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables // TABLE-NEXT: method #AnyProtocol.method!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}} // TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}} // TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} // TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} // TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} // TABLE-NEXT: } // -- Witnesses have the 'self' abstraction level of their protocol. // AnyProtocol has no class bound, so its witnesses treat Self as opaque. // InheritedClassProtocol has a class bound, so its witnesses treat Self as // a reference value. // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables25ClassInheritedConformanceS_22InheritedClassProtocolS_FS1_15inheritedMethod{{.*}} : $@convention(witness_method) (@guaranteed ClassInheritedConformance) -> () // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ClassInheritedConformance, @in_guaranteed ClassInheritedConformance) -> () struct GenericAssocType<T> : AssocReqt { func requiredMethod() {} } protocol AssocTypeWithReqt { typealias AssocType : AssocReqt } struct ConformsWithDependentAssocType1<CC: AssocReqt> : AssocTypeWithReqt { typealias AssocType = CC } // TABLE-LABEL: sil_witness_table hidden <CC where CC : AssocReqt> ConformsWithDependentAssocType1<CC>: AssocTypeWithReqt module witness_tables { // TABLE-NEXT: associated_type AssocType: CC // TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): dependent // TABLE-NEXT: } struct ConformsWithDependentAssocType2<DD> : AssocTypeWithReqt { typealias AssocType = GenericAssocType<DD> } // TABLE-LABEL: sil_witness_table hidden <DD> ConformsWithDependentAssocType2<DD>: AssocTypeWithReqt module witness_tables { // TABLE-NEXT: associated_type AssocType: GenericAssocType<DD> // TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): GenericAssocType<DD>: specialize <DD> (<T> GenericAssocType<T>: AssocReqt module witness_tables) // TABLE-NEXT: } protocol InheritedFromObjC : ObjCProtocol { func inheritedMethod() } class ConformsInheritedFromObjC : InheritedFromObjC { @objc func method(x x: ObjCClass) {} @objc class func staticMethod(y y: ObjCClass) {} func inheritedMethod() {} } // TABLE-LABEL: sil_witness_table hidden ConformsInheritedFromObjC: InheritedFromObjC module witness_tables { // TABLE-NEXT: method #InheritedFromObjC.inheritedMethod!1: @_TTWC14witness_tables25ConformsInheritedFromObjCS_17InheritedFromObjCS_FS1_15inheritedMethod{{.*}} // TABLE-NEXT: } protocol ObjCAssoc { typealias AssocType : ObjCProtocol } struct HasObjCAssoc : ObjCAssoc { typealias AssocType = ConformsInheritedFromObjC } // TABLE-LABEL: sil_witness_table hidden HasObjCAssoc: ObjCAssoc module witness_tables { // TABLE-NEXT: associated_type AssocType: ConformsInheritedFromObjC // TABLE-NEXT: } protocol Initializer { init(arg: Arg) } // TABLE-LABEL: sil_witness_table hidden HasInitializerStruct: Initializer module witness_tables { // TABLE-NEXT: method #Initializer.init!allocator.1: @_TTWV14witness_tables20HasInitializerStructS_11InitializerS_FS1_C{{.*}} // TABLE-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables20HasInitializerStructS_11InitializerS_FS1_C{{.*}} : $@convention(witness_method) (@out HasInitializerStruct, Arg, @thick HasInitializerStruct.Type) -> () struct HasInitializerStruct : Initializer { init(arg: Arg) { } } // TABLE-LABEL: sil_witness_table hidden HasInitializerClass: Initializer module witness_tables { // TABLE-NEXT: method #Initializer.init!allocator.1: @_TTWC14witness_tables19HasInitializerClassS_11InitializerS_FS1_C{{.*}} // TABLE-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables19HasInitializerClassS_11InitializerS_FS1_C{{.*}} : $@convention(witness_method) (@out HasInitializerClass, Arg, @thick HasInitializerClass.Type) -> () class HasInitializerClass : Initializer { required init(arg: Arg) { } } // TABLE-LABEL: sil_witness_table hidden HasInitializerEnum: Initializer module witness_tables { // TABLE-NEXT: method #Initializer.init!allocator.1: @_TTWO14witness_tables18HasInitializerEnumS_11InitializerS_FS1_C{{.*}} // TABLE-NEXT: } // SYMBOL: sil hidden [transparent] [thunk] @_TTWO14witness_tables18HasInitializerEnumS_11InitializerS_FS1_C{{.*}} : $@convention(witness_method) (@out HasInitializerEnum, Arg, @thick HasInitializerEnum.Type) -> () enum HasInitializerEnum : Initializer { case A init(arg: Arg) { self = .A } }
apache-2.0
7e852a951e5993ca323637cb322a8958
70.141818
300
0.770982
3.776469
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ChatCommentsHeaderItem.swift
1
4258
// // ChatCommentsHeaderItem.swift // Telegram // // Created by Mikhail Filimonov on 15/09/2020. // Copyright ยฉ 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import Postbox class ChatCommentsHeaderItem : TableStickItem { private let entry:ChatHistoryEntry fileprivate let chatInteraction:ChatInteraction? let isBubbled: Bool let layout:TextViewLayout let presentation: TelegramPresentationTheme init(_ initialSize:NSSize, _ entry:ChatHistoryEntry, interaction: ChatInteraction, theme: TelegramPresentationTheme) { self.entry = entry self.isBubbled = entry.renderType == .bubble self.chatInteraction = interaction self.presentation = theme let text: String switch entry { case let .commentsHeader(empty, _, _): if interaction.mode.isTopicMode { if empty { text = strings().chatTopicHeaderEmpty } else { text = strings().chatTopicHeaderFull } } else { if empty { text = strings().chatCommentsHeaderEmpty } else { text = strings().chatCommentsHeaderFull } } default: text = "" } self.layout = TextViewLayout(.initialize(string: text, color: theme.chatServiceItemTextColor, font: .medium(theme.fontSize)), maximumNumberOfLines: 1, truncationType: .end, alignment: .center) super.init(initialSize) } override var canBeAnchor: Bool { return false } required init(_ initialSize: NSSize) { entry = .commentsHeader(true, MessageIndex.absoluteLowerBound(), .list) self.isBubbled = false self.layout = TextViewLayout(NSAttributedString()) self.chatInteraction = nil self.presentation = theme super.init(initialSize) } override func makeSize(_ width: CGFloat, oldWidth:CGFloat) -> Bool { let success = super.makeSize(width, oldWidth: oldWidth) layout.measure(width: width - 40) return success } override var stableId: AnyHashable { return entry.stableId } override var height: CGFloat { return 30 } override func viewClass() -> AnyClass { return ChatCommentsHeaderView.self } } class ChatCommentsHeaderView : TableRowView { private let textView:TextView private let containerView: Control = Control() private var borderView: View = View() required init(frame frameRect: NSRect) { self.textView = TextView() self.textView.isSelectable = false self.containerView.wantsLayer = true self.textView.disableBackgroundDrawing = true super.init(frame: frameRect) addSubview(textView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var backdorColor: NSColor { return .clear } override func updateColors() { super.updateColors() guard let item = item as? ChatCommentsHeaderItem else { return } if item.presentation.shouldBlurService { textView.blurBackground = theme.blurServiceColor textView.backgroundColor = .clear } else { textView.backgroundColor = theme.chatServiceItemColor textView.blurBackground = nil } } override func draw(_ layer: CALayer, in ctx: CGContext) { super.draw(layer, in: ctx) } override func layout() { super.layout() textView.center() } override func set(item: TableRowItem, animated: Bool) { if let item = item as? ChatCommentsHeaderItem { textView.update(item.layout) textView.setFrameSize(item.layout.layoutSize.width + 16, item.layout.layoutSize.height + 6) textView.layer?.cornerRadius = textView.frame.height / 2 self.needsLayout = true } super.set(item: item, animated:animated) } }
gpl-2.0
639948c79ebae778442e43e56c07b145
27.959184
200
0.604416
5.110444
false
false
false
false
randymarsh77/streams
Sources/Streams/stream.swift
1
2167
import IDisposable import Scope public class Stream<T> : IStream { public typealias ChunkType = T public init() { } public func dispose() { let disposables = self.disposables + (ownershipSemantic == .Chained || ownershipSemantic == .Source ? self.downstreamDisposables : []) + (ownershipSemantic == .Chained || ownershipSemantic == .Sink ? self.upstreamDisposables : []) self.subscribers = [Subscriber<ChunkType>]() self.downstreamDisposables = [IDisposable]() self.upstreamDisposables = [IDisposable]() self.disposables = [IDisposable]() for disposable in disposables { disposable.dispose() } } public func publish(_ chunk: ChunkType) -> Void { for subscriber in self.subscribers { subscriber.publish(chunk) } } public func subscribe(_ onChunk: @escaping (_ chunk: ChunkType) -> Void) -> Scope { let subscriber = Subscriber(callback: onChunk) self.subscribers.append(subscriber) return Scope(dispose: { self.removeSubscriber(subscriber: subscriber) }) } func removeSubscriber(subscriber: Subscriber<ChunkType>) -> Void { if let i = self.subscribers.firstIndex(where: { (x) -> Bool in return x === subscriber }) { self.subscribers.remove(at: i) } } public func addDownstreamDisposable(_ disposable: IDisposable) { downstreamDisposables.append(disposable) } public func addUpstreamDisposable(_ disposable: IDisposable) { upstreamDisposables.append(disposable) } public func addDisposable(_ disposable: IDisposable) { disposables.append(disposable) } public func configureOwnershipSemantic(_ semantic: OwnershipSemantic) { ownershipSemantic = semantic } var subscribers: [Subscriber<ChunkType>] = [Subscriber<ChunkType>]() var disposables: [IDisposable] = [IDisposable]() var downstreamDisposables: [IDisposable] = [IDisposable]() var upstreamDisposables: [IDisposable] = [IDisposable]() var ownershipSemantic = OwnershipSemantic.Chained } internal class Subscriber<T> { var callback: (_ chunk: T) -> Void internal init(callback: @escaping (_ chunk: T) -> Void) { self.callback = callback } internal func publish(_ chunk: T) -> Void { self.callback(chunk) } }
mit
891e31929beb8032b22675b1f3d3be7f
24.797619
102
0.720351
3.704274
false
false
false
false
chayelheinsen/GamingStreams-tvOS-App
StreamCenter/HitboxStreamsViewController.swift
3
5016
// // HitboxStreamsViewController.swift // GamingStreamsTVApp // // Created by Olivier Boucher on 2015-09-14. import UIKit import Foundation class HitboxStreamsViewController : LoadingViewController { private let LOADING_BUFFER = 12 override var NUM_COLUMNS: Int { get { return 3 } } override var ITEMS_INSETS_X : CGFloat { get { return 45 } } override var HEIGHT_RATIO: CGFloat { get { return 0.5625 } } private var game : HitboxGame! private var streams = [HitboxMedia]() convenience init(game : HitboxGame){ self.init(nibName: nil, bundle: nil) self.game = game } override func viewDidLoad() { super.viewDidLoad() self.configureViews() } /* * viewWillAppear(animated: Bool) * * Overrides the super function to reload the collection view with fresh data * */ override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.streams.count == 0 { loadContent() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func loadContent() { self.removeErrorView() self.displayLoadingView("Loading Streams...") HitboxAPI.getLiveStreams(forGame: game.id, offset: 0, limit: LOADING_BUFFER) { (streams, error) -> () in guard let streams = streams else { dispatch_async(dispatch_get_main_queue(), { self.removeLoadingView() self.displayErrorView("Error loading streams list.\nPlease check your internet connection.") }) return } self.streams = streams dispatch_async(dispatch_get_main_queue(), { self.removeLoadingView() self.collectionView.reloadData() }) } } private func configureViews() { super.configureViews("Live Streams - \(self.game!.name)", centerView: nil, leftView: nil, rightView: nil) } override func reloadContent() { loadContent() super.reloadContent() } override func loadMore() { HitboxAPI.getLiveStreams(forGame: self.game.id, offset: streams.count, limit: LOADING_BUFFER, completionHandler: { (streams, error) -> () in guard let streams = streams else { return } var paths = [NSIndexPath]() let filteredStreams = streams.filter({ let streamId = $0.id if let _ = self.streams.indexOf({$0.id == streamId}) { return false } return true }) for i in 0..<filteredStreams.count { paths.append(NSIndexPath(forItem: i + self.streams.count, inSection: 0)) } self.collectionView.performBatchUpdates({ self.streams.appendContentsOf(filteredStreams) self.collectionView.insertItemsAtIndexPaths(paths) }, completion: nil) }) } override var itemCount: Int { get { return streams.count } } override func getItemAtIndex(index: Int) -> CellItem { return streams[index] } } //////////////////////////////////////////// // MARK - UICollectionViewDelegate interface //////////////////////////////////////////// extension HitboxStreamsViewController { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let selectedStream = streams[indexPath.row] let videoViewController = HitboxVideoViewController(media: selectedStream) self.presentViewController(videoViewController, animated: true, completion: nil) } } ////////////////////////////////////////////// // MARK - UICollectionViewDataSource interface ////////////////////////////////////////////// extension HitboxStreamsViewController { override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { //The number of possible rows return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // If the count of streams allows the current row to be full return streams.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell : ItemCellView = collectionView.dequeueReusableCellWithReuseIdentifier(ItemCellView.CELL_IDENTIFIER, forIndexPath: indexPath) as! ItemCellView cell.setRepresentedItem(streams[indexPath.row]) return cell } }
mit
ec1dd9556d8827f26eb89387541b7043
29.222892
159
0.572568
5.512088
false
false
false
false
uShip/iOSIdeaFlow
IdeaFlow/IdeaFlowEvent+CreateDelete.swift
1
2501
// // IdeaFlowEvent+CreateDelete.swift // IdeaFlow // // Created by Matthew Hayes on 9/4/15. // Copyright ยฉ 2015 uShip. All rights reserved. // import Foundation import CoreData extension IdeaFlowEvent { class func addNewEvent(eventType: EventType) { let startDate = NSDate() if let previousEvent = getPreviousEvent(startDate) { if EventType(int:previousEvent.eventType.intValue) == eventType { return } } createNewEvent(eventType, startDate: startDate) } class func createNewEvent(eventType: EventType, startDate: NSDate) -> IdeaFlowEvent { let newEvent = IdeaFlowEvent.MR_createEntity() newEvent.startTimeStamp = startDate newEvent.identifier = NSUUID().UUIDString newEvent.eventType = NSNumber(int: eventType.intValue()) NSManagedObjectContext.MR_defaultContext().MR_saveToPersistentStoreAndWait() NSNotificationCenter.defaultCenter().postNotification(Notification.EventAdded.notification(self)) return newEvent } class func createDemoEvents() { createNewEvent(.Troubleshooting, startDate: _getTodayDateWithTime(1, minute: 15)!) createNewEvent(.Learning, startDate: _getTodayDateWithTime(1, minute: 50)!) createNewEvent(.Rework, startDate: _getTodayDateWithTime(5, minute: 30)!) createNewEvent(.Learning, startDate: _getTodayDateWithTime(5, minute: 45)!) createNewEvent(.Troubleshooting, startDate: _getTomorrowDateWithTime(4, minute: 15)!) createNewEvent(.Learning, startDate: _getTomorrowDateWithTime(4, minute: 50)!) createNewEvent(.Productivity, startDate: _getTomorrowDateWithTime(5, minute: 30)!) createNewEvent(.Rework, startDate: _getTomorrowDateWithTime(8, minute: 0)!) createNewEvent(.Pause, startDate: _getTomorrowDateWithTime(16, minute: 0)!) NSManagedObjectContext.MR_defaultContext().MR_saveToPersistentStoreAndWait() NSNotificationCenter.defaultCenter().postNotification(Notification.EventAdded.notification(self)) } class func deleteAllEvents() { IdeaFlowEvent.MR_truncateAll() NSManagedObjectContext.MR_defaultContext().MR_saveToPersistentStoreAndWait() NSNotificationCenter.defaultCenter().postNotification(Notification.AllEventsDeleted.notification(self)) } }
gpl-3.0
6650edb945629fe27a7b0bb87a411e5e
35.246377
111
0.6772
4.98008
false
false
false
false
xiaoxionglaoshi/SwiftProgramming
006 Functions.playground/Contents.swift
1
470
// ไผ ๅ…ฅๆ•ฐ็ป„,่พ“ๅ‡บๆœ€ๅคงๆœ€ๅฐๅ€ผ func minMax(array: [Int]) -> (min: Int, max: Int) { assert(array.count > 0, "ๆ•ฐ็ป„ๅฟ…้กปๆœ‰ๅ…ƒ็ด ") var currentMin = array[0] var currentMax = array[0] for value in array { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) } let (min, max) = minMax(array: [1,5,8,3,9,2]) min max
apache-2.0
f1b6e2d4600838add1602e4d4dfadff0
21.894737
51
0.562212
3.312977
false
false
false
false
huonw/swift
stdlib/public/core/ArrayBufferProtocol.swift
3
8168
//===--- ArrayBufferProtocol.swift ----------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// The underlying buffer for an ArrayType conforms to /// `_ArrayBufferProtocol`. This buffer does not provide value semantics. @usableFromInline internal protocol _ArrayBufferProtocol : MutableCollection, RandomAccessCollection { associatedtype Indices = Range<Int> /// Create an empty buffer. init() /// Adopt the entire buffer, presenting it at the provided `startIndex`. init(_buffer: _ContiguousArrayBuffer<Element>, shiftedToStartIndex: Int) init(copying buffer: Self) /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @discardableResult func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> /// Get or set the index'th element. subscript(index: Int) -> Element { get nonmutating set } /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the `self` /// buffer store `minimumCapacity` elements, returns that buffer. /// Otherwise, returns `nil`. /// /// - Note: The result's firstElementAddress may not match ours, if we are a /// _SliceBuffer. /// /// - Note: This function must remain mutating; otherwise the buffer /// may acquire spurious extra references, which will cause /// unnecessary reallocation. mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? /// Returns `true` iff this buffer is backed by a uniquely-referenced mutable /// _ContiguousArrayBuffer. /// /// - Note: This function must remain mutating; otherwise the buffer /// may acquire spurious extra references, which will cause /// unnecessary reallocation. mutating func isMutableAndUniquelyReferenced() -> Bool /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? /// Replace the given `subRange` with the first `newCount` elements of /// the given collection. /// /// - Precondition: This buffer is backed by a uniquely-referenced /// `_ContiguousArrayBuffer`. mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newCount: Int, elementsOf newValues: C ) where C : Collection, C.Element == Element /// Returns a `_SliceBuffer` containing the elements in `bounds`. subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Precondition: Such contiguous storage exists or the buffer is empty. mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R /// The number of elements the buffer stores. var count: Int { get set } /// The number of elements the buffer can store without reallocation. var capacity: Int { get } /// An object that keeps the elements stored in this buffer alive. var owner: AnyObject { get } /// A pointer to the first element. /// /// - Precondition: The elements are known to be stored contiguously. var firstElementAddress: UnsafeMutablePointer<Element> { get } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { get } /// Returns a base address to which you can add an index `i` to get the /// address of the corresponding element at `i`. var subscriptBaseAddress: UnsafeMutablePointer<Element> { get } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. var identity: UnsafeRawPointer { get } var startIndex: Int { get } var endIndex: Int { get } } extension _ArrayBufferProtocol where Indices == Range<Int>{ @inlinable internal var subscriptBaseAddress: UnsafeMutablePointer<Element> { return firstElementAddress } // Make sure the compiler does not inline _copyBuffer to reduce code size. @inline(never) @usableFromInline internal init(copying buffer: Self) { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: buffer.count, minimumCapacity: buffer.count) buffer._copyContents( subRange: buffer.indices, initializing: newBuffer.firstElementAddress) self = Self( _buffer: newBuffer, shiftedToStartIndex: buffer.startIndex) } @inlinable internal mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newCount: Int, elementsOf newValues: C ) where C : Collection, C.Element == Element { _sanityCheck(startIndex == 0, "_SliceBuffer should override this function.") let oldCount = self.count let eraseCount = subrange.count let growth = newCount - eraseCount self.count = oldCount + growth let elements = self.subscriptBaseAddress let oldTailIndex = subrange.upperBound let oldTailStart = elements + oldTailIndex let newTailIndex = oldTailIndex + growth let newTailStart = oldTailStart + growth let tailCount = oldCount - subrange.upperBound if growth > 0 { // Slide the tail part of the buffer forwards, in reverse order // so as not to self-clobber. newTailStart.moveInitialize(from: oldTailStart, count: tailCount) // Assign over the original subrange var i = newValues.startIndex for j in subrange { elements[j] = newValues[i] newValues.formIndex(after: &i) } // Initialize the hole left by sliding the tail forward for j in oldTailIndex..<newTailIndex { (elements + j).initialize(to: newValues[i]) newValues.formIndex(after: &i) } _expectEnd(of: newValues, is: i) } else { // We're not growing the buffer // Assign all the new elements into the start of the subrange var i = subrange.lowerBound var j = newValues.startIndex for _ in 0..<newCount { elements[i] = newValues[j] i += 1 newValues.formIndex(after: &j) } _expectEnd(of: newValues, is: j) // If the size didn't change, we're done. if growth == 0 { return } // Move the tail backward to cover the shrinkage. let shrinkage = -growth if tailCount > shrinkage { // If the tail length exceeds the shrinkage // Assign over the rest of the replaced range with the first // part of the tail. newTailStart.moveAssign(from: oldTailStart, count: shrinkage) // Slide the rest of the tail back oldTailStart.moveInitialize( from: oldTailStart + shrinkage, count: tailCount - shrinkage) } else { // Tail fits within erased elements // Assign over the start of the replaced range with the tail newTailStart.moveAssign(from: oldTailStart, count: tailCount) // Destroy elements remaining after the tail in subrange (newTailStart + tailCount).deinitialize( count: shrinkage - tailCount) } } } }
apache-2.0
072d6c422d11cd47aff6e3a8344472f6
35.464286
80
0.68046
4.838863
false
false
false
false
ShunzhiTang/LifeMethodDemo
LifeMethodDemo/LifeMethodDemo/ViewController.swift
2
1718
// ViewController.swift // LifeMethodDemo import UIKit class ViewController: UIViewController { override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let Vc = LifeDemoViewController() Vc.transitioningDelegate = self //่ฟ™ไธชๅชๆ˜ฏ้œ€่ฆmodal็š„ๆ˜พ็คบ ๏ผŒๅ’Œๅ…ถไป–็š„ๆฒกๆœ‰ๅ…ณ็ณป Vc.modalPresentationStyle = UIModalPresentationStyle.Custom //่ฟ™ไธชๆ‰ๆ˜ฏdismissๆ˜พ็คบ็š„ๅŠจ็”ป่ฝฌๆข็š„ๆ–นๅผ Vc.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal presentViewController(Vc, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() print(__FUNCTION__) print(view) } } //MARK: ๅฎž็Žฐ่ฝฌๅœบๅŠจ็”ปๅฐฑ่ฆ้ตๅฎˆๅ่ฎฎ extension ViewController: UIViewControllerTransitioningDelegate{ func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self } } //MARK: ้œ€่ฆ้ตๅฎˆ่ฝฌๅœบ่ฟ™ไธชๅ่ฎฎ extension ViewController:UIViewControllerAnimatedTransitioning{ func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 2.0 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! transitionContext.containerView()?.addSubview(toView) //ๅผ€ๅง‹ๅŠจ็”ป transitionContext.completeTransition(true) } }
mit
e6fc31b6bd15e38f4342be737de8064a
29.226415
217
0.707865
6.209302
false
false
false
false
alecananian/osx-coin-ticker
CoinTicker/Source/Exchange.swift
1
10389
// // Exchange.swift // CoinTicker // // Created by Alec Ananian on 5/30/17. // Copyright ยฉ 2017 Alec Ananian. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Cocoa import Starscream import Alamofire import SwiftyJSON import PromiseKit enum ExchangeSite: Int, Codable { case bibox = 100 case binance = 200 case bitfinex = 205 case bithumb = 207 case bitstamp = 210 case bittrex = 225 case bitz = 230 case btcturk = 233 case coincheck = 235 case coinone = 237 case gateio = 239 case gdax = 240 case hitbtc = 241 case huobi = 243 case korbit = 245 case kraken = 250 case kucoin = 255 case lbank = 260 case okex = 275 case paribu = 290 case poloniex = 300 case upbit = 350 case zb = 400 func exchange(delegate: ExchangeDelegate? = nil) -> Exchange { switch self { case .bibox: return BiboxExchange(delegate: delegate) case .binance: return BinanceExchange(delegate: delegate) case .bitfinex: return BitfinexExchange(delegate: delegate) case .bithumb: return BithumbExchange(delegate: delegate) case .bitstamp: return BitstampExchange(delegate: delegate) case .bittrex: return BittrexExchange(delegate: delegate) case .bitz: return BitZExchange(delegate: delegate) case .btcturk: return BTCTurkExchange(delegate: delegate) case .coincheck: return CoincheckExchange(delegate: delegate) case .coinone: return CoinoneExchange(delegate: delegate) case .gateio: return GateIOExchange(delegate: delegate) case .gdax: return GDAXExchange(delegate: delegate) case .hitbtc: return HitBTCExchange(delegate: delegate) case .huobi: return HuobiExchange(delegate: delegate) case .korbit: return KorbitExchange(delegate: delegate) case .kraken: return KrakenExchange(delegate: delegate) case .kucoin: return KuCoinExchange(delegate: delegate) case .lbank: return LBankExchange(delegate: delegate) case .okex: return OKExExchange(delegate: delegate) case .paribu: return ParibuExchange(delegate: delegate) case .poloniex: return PoloniexExchange(delegate: delegate) case .upbit: return UPbitExchange(delegate: delegate) case .zb: return ZBExchange(delegate: delegate) } } } protocol ExchangeDelegate { func exchange(_ exchange: Exchange, didUpdateAvailableCurrencyPairs availableCurrencyPairs: [CurrencyPair]) func exchangeDidUpdatePrices(_ exchange: Exchange) } struct ExchangeAPIResponse { var representedObject: Any? var json: JSON } class Exchange { internal var site: ExchangeSite internal var delegate: ExchangeDelegate? private var requestTimer: Timer? var updateInterval = TickerConfig.defaultUpdateInterval var availableCurrencyPairs = [CurrencyPair]() var selectedCurrencyPairs = [CurrencyPair]() private var currencyPrices = [String: Double]() private lazy var apiResponseQueue: DispatchQueue = { [unowned self] in return DispatchQueue(label: "cointicker.\(self.site.rawValue)-api", qos: .utility, attributes: [.concurrent]) }() internal var socket: WebSocket? internal lazy var socketResponseQueue: DispatchQueue = { [unowned self] in return DispatchQueue(label: "cointicker.\(self.site.rawValue)-socket") }() internal var isUpdatingInRealTime: Bool { return updateInterval == TickerConfig.Constants.RealTimeUpdateInterval } var isSingleBaseCurrencySelected: Bool { return (Set(selectedCurrencyPairs.map({ $0.baseCurrency })).count == 1) } // MARK: Initialization deinit { stop() } init(site: ExchangeSite, delegate: ExchangeDelegate? = nil) { self.site = site self.delegate = delegate } // MARK: Currency Helpers func toggleCurrencyPair(baseCurrency: Currency, quoteCurrency: Currency) { guard let currencyPair = availableCurrencyPairs.first(where: { $0.baseCurrency == baseCurrency && $0.quoteCurrency == quoteCurrency }) else { return } if let index = selectedCurrencyPairs.firstIndex(of: currencyPair) { if selectedCurrencyPairs.count > 0 { selectedCurrencyPairs.remove(at: index) reset() TrackingUtils.didDeselectCurrencyPair(currencyPair) } } else if selectedCurrencyPairs.count < 5 { selectedCurrencyPairs.append(currencyPair) selectedCurrencyPairs = selectedCurrencyPairs.sorted() reset() TrackingUtils.didSelectCurrencyPair(currencyPair) } } func isCurrencyPairSelected(baseCurrency: Currency, quoteCurrency: Currency? = nil) -> Bool { if let quoteCurrency = quoteCurrency { return selectedCurrencyPairs.contains(where: { $0.baseCurrency == baseCurrency && $0.quoteCurrency == quoteCurrency }) } return selectedCurrencyPairs.contains(where: { $0.baseCurrency == baseCurrency }) } func selectedCurrencyPair(withCustomCode customCode: String) -> CurrencyPair? { return selectedCurrencyPairs.first(where: { $0.customCode == customCode }) } internal func setPrice(_ price: Double, for currencyPair: CurrencyPair) { currencyPrices[currencyPair.customCode] = price } func price(for currencyPair: CurrencyPair) -> Double { return currencyPrices[currencyPair.customCode] ?? -1 } // MARK: Exchange Request Lifecycle func load() { // Override } internal func load(from apiPath: String, getAvailableCurrencyPairs: @escaping (ExchangeAPIResponse) -> [CurrencyPair]) { requestAPI(apiPath).map { [weak self] result in self?.setAvailableCurrencyPairs(getAvailableCurrencyPairs(result)) }.catch { error in print("Error loading exchange: \(error)") } } internal func setAvailableCurrencyPairs(_ availableCurrencyPairs: [CurrencyPair]) { self.availableCurrencyPairs = availableCurrencyPairs.sorted() selectedCurrencyPairs = selectedCurrencyPairs.compactMap { currencyPair in if let newCurrencyPair = self.availableCurrencyPairs.first(where: { $0 == currencyPair }) { return newCurrencyPair } // Keep pair selected if new exchange has USDT instead of USD or vice versa if currencyPair.quoteCurrency.code == "USDT" || currencyPair.quoteCurrency.code == "USD", let newCurrencyPair = self.availableCurrencyPairs.first(where: { $0.baseCurrency == currencyPair.baseCurrency && ($0.quoteCurrency.code == "USD" || $0.quoteCurrency.code == "USDT") }) { return newCurrencyPair } return nil } if selectedCurrencyPairs.count == 0 { let localCurrency = Currency(code: Locale.current.currencyCode) if let currencyPair = self.availableCurrencyPairs.first(where: { $0.quoteCurrency == localCurrency }) ?? self.availableCurrencyPairs.first(where: { $0.quoteCurrency.code == "USD" }) ?? self.availableCurrencyPairs.first(where: { $0.quoteCurrency.code == "USDT" }) ?? self.availableCurrencyPairs.first { selectedCurrencyPairs.append(currencyPair) } } delegate?.exchange(self, didUpdateAvailableCurrencyPairs: self.availableCurrencyPairs) fetch() } internal func fetch() { // Override } internal func onFetchComplete() { delegate?.exchangeDidUpdatePrices(self) startRequestTimer() } internal func stop() { socket?.disconnect() requestTimer?.invalidate() requestTimer = nil Session.default.session.getTasksWithCompletionHandler({ dataTasks, _, _ in dataTasks.forEach({ $0.cancel() }) }) } private func startRequestTimer() { DispatchQueue.main.async { self.requestTimer = Timer.scheduledTimer(timeInterval: Double(self.updateInterval), target: self, selector: #selector(self.onRequestTimerFired(_:)), userInfo: nil, repeats: false) } } @objc private func onRequestTimerFired(_ timer: Timer) { requestTimer?.invalidate() requestTimer = nil fetch() } func reset() { stop() fetch() } // MARK: API Helpers internal func requestAPI(_ apiPath: String, for representedObject: Any? = nil) -> Promise<ExchangeAPIResponse> { return Promise { seal in AF.request(apiPath).responseJSON(queue: apiResponseQueue) { response in switch response.result { case .success(let value): seal.fulfill(ExchangeAPIResponse(representedObject: representedObject, json: JSON(value))) case .failure(let error): print("Error in API request: \(apiPath) \(error)") seal.reject(error) } } } } }
mit
f95991c5930efd6f78c1cb7bc13a4e55
37.332103
287
0.65335
4.679279
false
false
false
false
tkohout/Genie
GenieFramework/Commands/CurriedInitializer.swift
1
4110
// // CurriedSplitInitializer.swift // Genee // // Created by Tomas Kohout on 15/10/2016. // Copyright ยฉ 2016 Genie. All rights reserved. // import Foundation import SourceKittenFramework public class CurriedInitializer: GeneeCommand { let curryMaximum = 20 func commaConcat(_ xs: [String]) -> String { return xs.joined(separator: ", ") } func curriedReturnTypes(_ xs: [(name:String, type:String)]) -> String { guard let last = xs.last else { fatalError("Attempted to get return types with no variables") } let types = Array(xs.map{ $0.type }.dropLast()) var all = stride(from: 0, to: types.count, by: curryMaximum).map { index -> String in let end = (index + curryMaximum < types.count ? index + curryMaximum : types.count) - 1 let slice = Array(types[index...end]) return "(\(commaConcat(slice)))" } all += [last.type] return all.joined(separator: " -> ") } func initializersGenerator(_ xs: [(name:String, type:String)]) -> [String] { let initializers = stride(from: 0, to: xs.count, by: curryMaximum).map { index -> String in let end = (index + curryMaximum < xs.count ? index+curryMaximum : xs.count) - 1 let types = Array(xs[index...end]).map { $0.type } let definition = "(\(commaConcat(types)))" let implementation = (0 ..< end-index+1).map { "$\($0)"} let letter = Character(UnicodeScalar(65+(Int(index/curryMaximum)))!) return "static var init\(letter): \(definition) -> \(definition) = { (\(commaConcat(implementation))) }" } return initializers } func curryDefinitionGenerator(curriedClass:String, arguments: [Variable]) -> String { let arguments = arguments.map { (name: $0.name, type: $0.typeName!) } let curriedParameters = arguments + [(name:"_", type: curriedClass)] let innerFunctionArguments = commaConcat(arguments.map { "\($0.name): \($0.name)" }) // "a, b, c" let functionDefinition = "\(curriedClass)(\(innerFunctionArguments))" // MyStruct(a, b, c) let implementation = stride(from: 0, to: arguments.count, by: curryMaximum).reversed().reduce(functionDefinition) { accum, index in let indent = String(repeating: " ", count: (1 + Int((index+1)/curryMaximum)) * 4) let end = (index + curryMaximum < arguments.count ? index+curryMaximum : arguments.count) - 1 let parameters = Array(arguments[index...end]).map { $0.name } return "{ \(commaConcat(parameters)) in\n\(indent)\(accum) \n\(indent)}" } var curry = initializersGenerator(arguments) curry += [ "", "static var create: \(curriedReturnTypes(curriedParameters)) = ", "\(implementation)" ] return curry.joined(separator: "\n") } public init(){} public var identifier: String { return "CurriedInitializer" } public var name: String { return "Generate Curried Initializer" } public func perform(buffer: Buffer, completionCallback: (Void) -> Void) throws { let selectionRange = buffer.selectionRange() let source = try buffer.source() guard let parent = source.declarations.containing(range: selectionRange).first as? Type else { completionCallback() return } let variables = parent.variables.in(range: selectionRange).filter { $0.typeName != nil } let lines = curryDefinitionGenerator(curriedClass: parent.name, arguments: variables).components(separatedBy: "\n").indent(by: buffer.indentationWidth) //try buffer.insert(lines: lines, inRange: buffer.selectionEnd.line + 1..<buffer.selectionEnd.line + 1 + lines.count) buffer.update(source: source) completionCallback() } }
mit
ede8b575906ff5f7086357c8d3594c1e
37.764151
159
0.584814
4.466304
false
false
false
false
juliand665/LeagueKit
Sources/LeagueKit/Model/Static Data/Item.swift
1
2055
import Foundation public final class Items: WritableAssetProvider { public typealias AssetType = Item public typealias Raw = SimpleRaw<Items> public static let shared = load() public static let assetIdentifier = "item" public var contents: [Int: Item] = [:] public var version = "N/A" public required init() {} } public final class Item: SimpleAsset { public typealias Provider = Items public let id: Int public let name: String public let description: String public let requiredChampion: String? public let summary: String public let searchTerms: [String] public let version: String public let imageName: String public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if decoder.useAPIFormat { let dataContainer = try decoder.container(keyedBy: DataCodingKeys.self) try id = decoder.codingPath.last?.intValue ??? DecodingError.dataCorruptedError(forKey: .id, in: container, debugDescription: "expected int as key in item dictionary!") try summary = dataContainer.decodeValue(forKey: .summary) try searchTerms = dataContainer.decode(String.self, forKey: .searchTerms) .components(separatedBy: ";") .filter { !$0.isEmpty } version = decoder.assetVersion! try imageName = dataContainer.decode(ImageData.self, forKey: .imageData).full } else { try id = container.decodeValue(forKey: .id) try summary = container.decodeValue(forKey: .summary) try searchTerms = container.decodeValue(forKey: .searchTerms) try version = container.decodeValue(forKey: .version) try imageName = container.decodeValue(forKey: .imageName) } try name = container.decodeValue(forKey: .name) try description = container.decodeValue(forKey: .description) try requiredChampion = container.decodeValueIfPresent(forKey: .requiredChampion) } /// translate riot's data into something usable private enum DataCodingKeys: String, CodingKey { case summary = "plaintext" case searchTerms = "colloq" case imageData = "image" } }
mit
868fe66b390a12f4d1d427e0056a9ae7
31.619048
129
0.742092
3.982558
false
false
false
false
austinzheng/swift
test/SILOptimizer/definite_init_failable_initializers_objc.swift
2
3375
// RUN: %target-swift-frontend -emit-sil -enable-sil-ownership -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck %s // FIXME: This needs more tests @objc protocol P3 { init?(p3: Int64) } extension P3 { // CHECK-LABEL: sil hidden @$s40definite_init_failable_initializers_objc2P3PAAE3p3axSgs5Int64V_tcfC : $@convention(method) <Self where Self : P3> (Int64, @thick Self.Type) -> @owned Optional<Self> init!(p3a: Int64) { self.init(p3: p3a)! // unnecessary-but-correct '!' } // CHECK-LABEL: sil hidden @$s40definite_init_failable_initializers_objc2P3PAAE3p3bxs5Int64V_tcfC : $@convention(method) <Self where Self : P3> (Int64, @thick Self.Type) -> @owned Self init(p3b: Int64) { self.init(p3: p3b)! // necessary '!' } } class LifetimeTracked { init(_: Int) {} } class FakeNSObject { @objc dynamic init() {} } class Cat : FakeNSObject { let x: LifetimeTracked // CHECK-LABEL: sil hidden @$s40definite_init_failable_initializers_objc3CatC1n5afterACSgSi_Sbtcfc : $@convention(method) (Int, Bool, @owned Cat) -> @owned Optional<Cat> // CHECK: bb0(%0 : $Int, %1 : $Bool, %2 : $Cat): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $Cat // CHECK: store %2 to [[SELF_BOX]] : $*Cat // CHECK: [[FIELD_ADDR:%.*]] = ref_element_addr %2 : $Cat, #Cat.x // CHECK-NEXT: store {{%.*}} to [[FIELD_ADDR]] : $*LifetimeTracked // CHECK-NEXT: [[COND:%.*]] = struct_extract %1 : $Bool, #Bool._value // CHECK-NEXT: cond_br [[COND]], bb1, bb2 // CHECK: bb1: // CHECK-NEXT: [[FIELD_ADDR:%.*]] = ref_element_addr %2 : $Cat, #Cat.x // CHECK-NEXT: destroy_addr [[FIELD_ADDR]] : $*LifetimeTracked // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: dealloc_partial_ref %2 : $Cat, [[METATYPE]] : $@thick Cat.Type // CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*Cat // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br bb3([[RESULT]] : $Optional<Cat>) // CHECK: bb2: // CHECK-NEXT: [[SUPER:%.*]] = upcast %2 : $Cat to $FakeNSObject // CHECK-NEXT: [[SUB:%.*]] = unchecked_ref_cast [[SUPER]] : $FakeNSObject to $Cat // CHECK-NEXT: [[SUPER_FN:%.*]] = objc_super_method [[SUB]] : $Cat, #FakeNSObject.init!initializer.1.foreign : (FakeNSObject.Type) -> () -> FakeNSObject, $@convention(objc_method) (@owned FakeNSObject) -> @owned FakeNSObject // CHECK-NEXT: [[NEW_SUPER_SELF:%.*]] = apply [[SUPER_FN]]([[SUPER]]) : $@convention(objc_method) (@owned FakeNSObject) -> @owned FakeNSObject // CHECK-NEXT: [[NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SUPER_SELF]] : $FakeNSObject to $Cat // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] : $*Cat // TODO: Once we re-enable arbitrary take promotion, this retain and the associated destroy_addr will go away. // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<Cat>, #Optional.some!enumelt.1, [[NEW_SELF]] : $Cat // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*Cat // CHECK-NEXT: br bb3([[RESULT]] : $Optional<Cat>) // CHECK: bb3([[RESULT:%.*]] : $Optional<Cat>): // CHECK-NEXT: return [[RESULT]] : $Optional<Cat> init?(n: Int, after: Bool) { self.x = LifetimeTracked(0) if after { return nil } super.init() } }
apache-2.0
1705b60dbc6762705ad82ec5d823b0f7
44.608108
228
0.620741
3.196023
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Intro/IntroViewController.swift
1
10390
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import UIKit import Shared class IntroViewController: UIViewController, OnboardingViewControllerProtocol, Themeable { private var viewModel: IntroViewModel private let profile: Profile private var onboardingCards = [OnboardingCardViewController]() var didFinishFlow: (() -> Void)? var notificationCenter: NotificationProtocol var themeManager: ThemeManager var themeObserver: NSObjectProtocol? struct UX { static let closeButtonSize: CGFloat = 30 static let closeHorizontalMargin: CGFloat = 24 static let closeVerticalMargin: CGFloat = 20 static let pageControlHeight: CGFloat = 40 static let pageControlBottomPadding: CGFloat = 8 } // MARK: - Var related to onboarding private lazy var closeButton: UIButton = .build { button in button.setImage(UIImage(named: ImageIdentifiers.bottomSheetClose), for: .normal) button.addTarget(self, action: #selector(self.closeOnboarding), for: .touchUpInside) button.accessibilityIdentifier = AccessibilityIdentifiers.Onboarding.closeButton } private lazy var pageController: UIPageViewController = { let pageVC = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal) pageVC.dataSource = self pageVC.delegate = self return pageVC }() private lazy var pageControl: UIPageControl = .build { pageControl in pageControl.currentPage = 0 pageControl.numberOfPages = self.viewModel.enabledCards.count pageControl.isUserInteractionEnabled = false pageControl.accessibilityIdentifier = AccessibilityIdentifiers.Onboarding.pageControl } // MARK: Initializer init(viewModel: IntroViewModel, profile: Profile, themeManager: ThemeManager = AppContainer.shared.resolve(), notificationCenter: NotificationProtocol = NotificationCenter.default) { self.viewModel = viewModel self.profile = profile self.themeManager = themeManager self.notificationCenter = notificationCenter super.init(nibName: nil, bundle: nil) setupLayout() applyTheme() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() listenForThemeChange() setupPageController() } // MARK: View setup private func setupPageController() { // Create onboarding card views var cardViewController: OnboardingCardViewController for cardType in viewModel.enabledCards { if let viewModel = viewModel.getCardViewModel(cardType: cardType) { cardViewController = OnboardingCardViewController(viewModel: viewModel, delegate: self) onboardingCards.append(cardViewController) } } if let firstViewController = onboardingCards.first { pageController.setViewControllers([firstViewController], direction: .forward, animated: true, completion: nil) } } private func setupLayout() { addChild(pageController) view.addSubview(pageController.view) pageController.didMove(toParent: self) view.addSubviews(pageControl, closeButton) NSLayoutConstraint.activate([ pageControl.leadingAnchor.constraint(equalTo: view.leadingAnchor), pageControl.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -UX.pageControlBottomPadding), pageControl.trailingAnchor.constraint(equalTo: view.trailingAnchor), closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: UX.closeVerticalMargin), closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -UX.closeHorizontalMargin), closeButton.widthAnchor.constraint(equalToConstant: UX.closeButtonSize), closeButton.heightAnchor.constraint(equalToConstant: UX.closeButtonSize), ]) } @objc private func closeOnboarding() { didFinishFlow?() viewModel.sendCloseButtonTelemetry(index: pageControl.currentPage) } func getNextOnboardingCard(index: Int, goForward: Bool) -> OnboardingCardViewController? { guard let index = viewModel.getNextIndex(currentIndex: index, goForward: goForward) else { return nil } return onboardingCards[index] } // Used to programmatically set the pageViewController to show next card func moveToNextPage(cardType: IntroViewModel.InformationCards) { if let nextViewController = getNextOnboardingCard(index: cardType.rawValue, goForward: true) { pageControl.currentPage = cardType.rawValue + 1 pageController.setViewControllers([nextViewController], direction: .forward, animated: false) } } // Due to restrictions with PageViewController we need to get the index of the current view controller // to calculate the next view controller func getCardIndex(viewController: OnboardingCardViewController) -> Int? { let cardType = viewController.viewModel.cardType guard let index = viewModel.enabledCards.firstIndex(of: cardType) else { return nil } return index } } // MARK: UIPageViewControllerDataSource & UIPageViewControllerDelegate extension IntroViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let onboardingVC = viewController as? OnboardingCardViewController, let index = getCardIndex(viewController: onboardingVC) else { return nil } pageControl.currentPage = index return getNextOnboardingCard(index: index, goForward: false) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let onboardingVC = viewController as? OnboardingCardViewController, let index = getCardIndex(viewController: onboardingVC) else { return nil } pageControl.currentPage = index return getNextOnboardingCard(index: index, goForward: true) } } extension IntroViewController: OnboardingCardDelegate { func showNextPage(_ cardType: IntroViewModel.InformationCards) { guard cardType != viewModel.enabledCards.last else { self.didFinishFlow?() return } moveToNextPage(cardType: cardType) } func primaryAction(_ cardType: IntroViewModel.InformationCards) { switch cardType { case .welcome: moveToNextPage(cardType: cardType) case .signSync: presentSignToSync() default: break } } // Extra step to make sure pageControl.currentPage is the right index card // because UIPageViewControllerDataSource call fails func pageChanged(_ cardType: IntroViewModel.InformationCards) { if let cardIndex = viewModel.enabledCards.firstIndex(of: cardType), cardIndex != pageControl.currentPage { pageControl.currentPage = cardIndex } } private func presentSignToSync(_ fxaOptions: FxALaunchParams? = nil, flowType: FxAPageType = .emailLoginFlow, referringPage: ReferringPage = .onboarding) { let singInSyncVC = FirefoxAccountSignInViewController.getSignInOrFxASettingsVC(fxaOptions, flowType: flowType, referringPage: referringPage, profile: profile) let controller: DismissableNavigationViewController let buttonItem = UIBarButtonItem(title: .SettingsSearchDoneButton, style: .plain, target: self, action: #selector(dismissSignInViewController)) buttonItem.tintColor = themeManager.currentTheme.colors.actionPrimary singInSyncVC.navigationItem.rightBarButtonItem = buttonItem controller = DismissableNavigationViewController(rootViewController: singInSyncVC) controller.onViewDismissed = { self.closeOnboarding() } self.present(controller, animated: true) } @objc func dismissSignInViewController() { dismiss(animated: true, completion: nil) closeOnboarding() } } // MARK: UIViewController setup extension IntroViewController { override var prefersStatusBarHidden: Bool { return true } override var shouldAutorotate: Bool { return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { // This actually does the right thing on iPad where the modally // presented version happily rotates with the iPad orientation. return .portrait } // MARK: - Themable func applyTheme() { let theme = themeManager.currentTheme pageControl.currentPageIndicatorTintColor = theme.colors.actionPrimary pageControl.pageIndicatorTintColor = theme.colors.actionSecondary view.backgroundColor = theme.colors.layer2 onboardingCards.forEach { cardViewController in cardViewController.applyTheme() } } }
mpl-2.0
4787e4079192ab72f47bb90a4b9a8543
39.428016
116
0.649952
6.1735
false
false
false
false
yagiz/Bagel
mac/Bagel/Components/Details/DetailSections/DataViewController/DataViewController.swift
1
2138
// // DataViewController.swift // Bagel // // Created by Yagiz Gurgul on 2.10.2018. // Copyright ยฉ 2018 Yagiz Lab. All rights reserved. // import Cocoa class DataViewController: BaseViewController, DetailSectionProtocol { var viewModel: DataViewModel? var dataTextViewController: DataTextViewController! var dataJSONViewController: DataJSONViewController! override func setup() { self.viewModel?.onChange = { [weak self] in self?.refresh() } self.refresh() } func refreshViewModel() { self.viewModel?.didSelectPacket() } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if let destinationVC = segue.destinationController as? DataTextViewController { self.dataTextViewController = destinationVC self.dataTextViewController?.viewModel = DataTextViewModel() } if let destinationVC = segue.destinationController as? DataJSONViewController{ self.dataJSONViewController = destinationVC self.dataJSONViewController?.viewModel = DataJSONViewModel() } } func refresh() { if let data = self.viewModel?.dataRepresentation { if data.type == .json { self.dataJSONViewController.viewModel?.dataRepresentation = self.viewModel?.dataRepresentation self.dataJSONViewController.view.isHidden = false self.dataTextViewController.view.isHidden = true } else { self.dataTextViewController.viewModel?.dataRepresentation = self.viewModel?.dataRepresentation self.dataTextViewController.view.isHidden = false self.dataJSONViewController.view.isHidden = true } } else { self.dataJSONViewController.view.isHidden = true self.dataTextViewController.view.isHidden = true } } }
apache-2.0
02cfa64cf6e99b75ec42da91395de940
28.273973
110
0.594759
5.903315
false
false
false
false
HabitRPG/habitrpg-ios
Habitica API Client/Habitica API Client/DateDecodingStrategy-Extension.swift
1
2986
// // DateDecodingStrategy-Extension.swift // Habitica API Client // // Created by Phillip Thelen on 07.03.18. // Copyright ยฉ 2018 HabitRPG Inc. All rights reserved. // import Foundation import Shared extension JSONDecoder { func setHabiticaDateDecodingStrategy() { dateDecodingStrategy = .custom({ dateDecoder -> Date in let container = try dateDecoder.singleValueContainer() if let timestampNumber = try? container.decode(Double.self) { return Date(timeIntervalSince1970: timestampNumber) } let dateStr = try container.decode(String.self) if let date = ISO8601DateFormatter().date(from: dateStr) { return date } let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone(identifier: "UTC") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" if let date = dateFormatter.date(from: dateStr) { return date } dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mmzzz" if let date = dateFormatter.date(from: dateStr) { return date } //This is sometimes used for the `nextDue` dates var splitString = dateStr.split(separator: " ") if splitString.count == 6 { splitString[5] = splitString[5].trimmingCharacters(in: CharacterSet(charactersIn: "01234567890+").inverted).split(separator: " ")[0] dateFormatter.dateFormat = "E MMM dd yyyy HH:mm:ss Z" if let date = dateFormatter.date(from: splitString.joined(separator: " ")) { return date } } //Various formats for just the day dateFormatter.dateFormat = "yyyy-MM-dd" if let date = dateFormatter.date(from: dateStr) { return date } dateFormatter.dateFormat = "MM/dd/yyyy" if let date = dateFormatter.date(from: dateStr) { return date } dateFormatter.dateFormat = "dd/MM/yyyy" if let date = dateFormatter.date(from: dateStr) { return date } dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" if let date = dateFormatter.date(from: dateStr) { return date } dateFormatter.dateFormat = "dd MMM yyyy HH:mm zzz" if let date = dateFormatter.date(from: dateStr) { return date } RemoteLogger.shared.record(name: "DateParserException", reason: "Date \(dateStr) could not be parsed") return Date(timeIntervalSince1970: 0) }) } }
gpl-3.0
dc8af229b167d33022668b22999b1e2f
35.851852
148
0.540704
5
false
true
false
false
TCA-Team/iOS
TUM Campus App/LectureTableViewCell.swift
1
1430
// // LectureTableViewCell.swift // TUM Campus App // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit class LectureTableViewCell: CardTableViewCell { override func setElement(_ element: DataElement) { if let lecture = element as? Lecture { titleLabel.text = lecture.name let text = lecture.type + " - " + lecture.semester detailsLabel.text = text + " - " + lecture.sws.description + " SWS" contributorsLabel.text = lecture.contributors } } @IBOutlet weak var titleLabel: UILabel! { didSet { titleLabel.textColor = Constants.tumBlue } } @IBOutlet weak var detailsLabel: UILabel! @IBOutlet weak var contributorsLabel: UILabel! }
gpl-3.0
64c297603d485c8cc2c536db7fb65b96
33.047619
88
0.677622
4.169096
false
false
false
false
demetrio812/EurekaCreditCard
Example/Pods/Eureka/Source/Rows/TextAreaRow.swift
1
11095
// // AlertRow.swift // Eureka // // Created by Martin Barreto on 2/23/16. // Copyright ยฉ 2016 Xmartlabs. All rights reserved. // import Foundation public enum TextAreaHeight { case Fixed(cellHeight: CGFloat) case Dynamic(initialTextViewHeight: CGFloat) } protocol TextAreaConformance: FormatterConformance { var placeholder : String? { get set } var textAreaHeight : TextAreaHeight { get set } } /** * Protocol for cells that contain a UITextView */ public protocol AreaCell : TextInputCell { var textView: UITextView { get } } extension AreaCell { public var textInput: UITextInput { return textView } } public class _TextAreaCell<T where T: Equatable, T: InputTypeInitiable> : Cell<T>, UITextViewDelegate, AreaCell { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public lazy var placeholderLabel : UILabel = { let v = UILabel() v.translatesAutoresizingMaskIntoConstraints = false v.numberOfLines = 0 v.textColor = UIColor(white: 0, alpha: 0.22) return v }() public lazy var textView : UITextView = { let v = UITextView() v.translatesAutoresizingMaskIntoConstraints = false return v }() public var dynamicConstraints = [NSLayoutConstraint]() public override func setup() { super.setup() let textAreaRow = row as! TextAreaConformance switch textAreaRow.textAreaHeight { case .Dynamic(_): height = { UITableViewAutomaticDimension } textView.scrollEnabled = false case .Fixed(let cellHeight): height = { cellHeight } } textView.keyboardType = .Default textView.delegate = self textView.font = .preferredFontForTextStyle(UIFontTextStyleBody) textView.textContainer.lineFragmentPadding = 0 textView.textContainerInset = UIEdgeInsetsZero placeholderLabel.font = textView.font selectionStyle = .None contentView.addSubview(textView) contentView.addSubview(placeholderLabel) imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.Old.union(.New), context: nil) setNeedsUpdateConstraints() } deinit { textView.delegate = nil imageView?.removeObserver(self, forKeyPath: "image") } public override func update() { super.update() textLabel?.text = nil detailTextLabel?.text = nil textView.editable = !row.isDisabled textView.textColor = row.isDisabled ? .grayColor() : .blackColor() textView.text = row.displayValueFor?(row.value) placeholderLabel.text = (row as? TextAreaConformance)?.placeholder placeholderLabel.sizeToFit() placeholderLabel.hidden = textView.text.characters.count != 0 } public override func cellCanBecomeFirstResponder() -> Bool { return !row.isDisabled && textView.canBecomeFirstResponder() } public override func cellBecomeFirstResponder(fromDiretion: Direction) -> Bool { return textView.becomeFirstResponder() } public override func cellResignFirstResponder() -> Bool { return textView.resignFirstResponder() } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let obj = object, let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKindKey] where obj === imageView && keyPathValue == "image" && changeType.unsignedLongValue == NSKeyValueChange.Setting.rawValue { setNeedsUpdateConstraints() updateConstraintsIfNeeded() } } //Mark: Helpers private func displayValue(useFormatter useFormatter: Bool) -> String? { guard let v = row.value else { return nil } if let formatter = (row as? FormatterConformance)?.formatter where useFormatter { return textView.isFirstResponder() ? formatter.editingStringForObjectValue(v as! AnyObject) : formatter.stringForObjectValue(v as? AnyObject) } return String(v) } //MARK: TextFieldDelegate public func textViewDidBeginEditing(textView: UITextView) { formViewController()?.beginEditing(self) formViewController()?.textInputDidBeginEditing(textView, cell: self) if let textAreaConformance = (row as? TextAreaConformance), let _ = textAreaConformance.formatter where textAreaConformance.useFormatterOnDidBeginEditing ?? textAreaConformance.useFormatterDuringInput { textView.text = self.displayValue(useFormatter: true) } else { textView.text = self.displayValue(useFormatter: false) } } public func textViewDidEndEditing(textView: UITextView) { formViewController()?.endEditing(self) formViewController()?.textInputDidEndEditing(textView, cell: self) textViewDidChange(textView) textView.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil) } public func textViewDidChange(textView: UITextView) { if let textAreaConformance = row as? TextAreaConformance, case .Dynamic = textAreaConformance.textAreaHeight, let tableView = formViewController()?.tableView { let currentOffset = tableView.contentOffset UIView.setAnimationsEnabled(false) tableView.beginUpdates() tableView.endUpdates() UIView.setAnimationsEnabled(true) tableView.setContentOffset(currentOffset, animated: false) } placeholderLabel.hidden = textView.text.characters.count != 0 guard let textValue = textView.text else { row.value = nil return } guard let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter else { row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value) return } if fieldRow.useFormatterDuringInput { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.alloc(1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?> = nil if formatter.getObjectValue(value, forString: textValue, errorDescription: errorDesc) { row.value = value.memory as? T guard var selStartPos = textView.selectedTextRange?.start else { return } let oldVal = textView.text textView.text = row.displayValueFor?(row.value) selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(selStartPos, inTextInput: textView, oldValue: oldVal, newValue: textView.text) ?? selStartPos textView.selectedTextRange = textView.textRangeFromPosition(selStartPos, toPosition: selStartPos) return } } else { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.alloc(1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?> = nil if formatter.getObjectValue(value, forString: textValue, errorDescription: errorDesc) { row.value = value.memory as? T } } } public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { return formViewController()?.textInput(textView, shouldChangeCharactersInRange: range, replacementString: text, cell: self) ?? true } public func textViewShouldBeginEditing(textView: UITextView) -> Bool { return formViewController()?.textInputShouldBeginEditing(textView, cell: self) ?? true } public func textViewShouldEndEditing(textView: UITextView) -> Bool { return formViewController()?.textInputShouldEndEditing(textView, cell: self) ?? true } public override func updateConstraints(){ customConstraints() super.updateConstraints() } public func customConstraints() { contentView.removeConstraints(dynamicConstraints) dynamicConstraints = [] var views : [String: AnyObject] = ["textView": textView, "label": placeholderLabel] dynamicConstraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]", options: [], metrics: nil, views: views)) if let textAreaConformance = row as? TextAreaConformance, case .Dynamic(let initialTextViewHeight) = textAreaConformance.textAreaHeight { dynamicConstraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[textView(>=initialHeight@800)]-|", options: [], metrics: ["initialHeight": initialTextViewHeight], views: views)) } else { dynamicConstraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[textView]-|", options: [], metrics: nil, views: views)) } if let imageView = imageView, let _ = imageView.image { views["imageView"] = imageView dynamicConstraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("H:[imageView]-(15)-[textView]-|", options: [], metrics: nil, views: views)) dynamicConstraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("H:[imageView]-(15)-[label]-|", options: [], metrics: nil, views: views)) } else { dynamicConstraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textView]-|", options: [], metrics: nil, views: views)) dynamicConstraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|", options: [], metrics: nil, views: views)) } contentView.addConstraints(dynamicConstraints) } } public class TextAreaCell : _TextAreaCell<String>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } } public class AreaRow<T: Equatable, Cell: CellType where Cell: BaseCell, Cell: TypedCellType, Cell: AreaCell, Cell.Value == T>: FormatteableRow<T, Cell>, TextAreaConformance { public var placeholder : String? public var textAreaHeight = TextAreaHeight.Fixed(cellHeight: 110) public required init(tag: String?) { super.init(tag: tag) } } public class _TextAreaRow: AreaRow<String, TextAreaCell> { required public init(tag: String?) { super.init(tag: tag) } } /// A row with a UITextView where the user can enter large text. public final class TextAreaRow: _TextAreaRow, RowType { required public init(tag: String?) { super.init(tag: tag) } }
mit
ee16e6187f08195e867896ffefb0d34d
41.343511
228
0.676762
5.541459
false
false
false
false
DrabWeb/Azusa
Azusa.Previous/Azusa/Objects/Music/AZAlbum.swift
1
5371
// // AZAlbum.swift // Azusa // // Created by Ushio on 12/8/16. // import Foundation /// The object to represent an album in the user's music collection class AZAlbum: CustomStringConvertible { // MARK: - Properties /// The name of this album var name : String = ""; /// The artists of this album var artists : [AZArtist] { var noDuplicateArtists : [AZArtist] = []; self.songs.map { $0.artist }.forEach { artist in if(!noDuplicateArtists.contains(artist)) { noDuplicateArtists.append(artist); } } return noDuplicateArtists; }; /// The duration in seconds for all the songs in this album var duration : Int { var length : Int = 0; self.songs.forEach { length += $0.duration; } return length; } /// The genres of this album var genres : [AZGenre] { var noDuplicateGenres : [AZGenre] = []; self.songs.map { $0.genre }.forEach { genre in if(!noDuplicateGenres.contains(genre)) { noDuplicateGenres.append(genre); } } return noDuplicateGenres; }; /// The year this album was released var year : Int { var releaseYear : Int = -1; self.songs.forEach { releaseYear = $0.year; } return releaseYear; }; /// All the songs in this album var songs : [AZSong] = []; /// The user readable version of this album's name var displayName : String { return ((self.name != "") ? self.name : "Unknown Album"); } /// Gets the user readable version of this album's artist(s) /// /// - Parameter shorten: If there are multiple artists, should the string be shortened to "Various Artists"? /// - Returns: The user readable version of this album's artist(s) func displayArtists(shorten : Bool) -> String { let artists : [AZArtist] = self.artists; if(artists.count == 1) { return self.artists[0].displayName; } else if(artists.count > 1) { if(shorten) { return "Various Artists"; } else { var displayArtistsString : String = ""; for(index, artist) in artists.enumerated() { displayArtistsString += "\(artist.displayName)\((index == (artists.count - 1)) ? "" : ", ")"; } return displayArtistsString; } } else { return "Unknown Artist"; } } /// The user readable version of this album's genres var displayGenres : String { var displayGenreString : String = ""; let albumGenres : [AZGenre] = self.genres; for(index, genre) in albumGenres.enumerated() { if(genre.name != "") { displayGenreString += "\(genre.name)\((index == (albumGenres.count - 1)) ? "" : ", ")"; } } if(displayGenreString == "") { displayGenreString = "Unknown Genre"; } return displayGenreString; } /// The user readable version of this album's release year var displayYear : String { let year : Int = self.year; return (year == -1 || year == 0) ? "Unknown Year" : "\(year)"; } /// Gets the thumbnail image for this album /// /// - Parameter completionHandler: The completion handler for when the thumbnail image is loaded, passed the thumbnail func getThumbnailImage(_ completionHandler: @escaping ((NSImage) -> ())) { // Return the thumbnail image of the first song if there is one if(self.songs.count > 0) { self.songs[0].getThumbnailImage({ thumbnail in completionHandler(thumbnail); }); } // Default to the default cover if there are no songs else { completionHandler(#imageLiteral(resourceName: "AZDefaultCover")); } } /// Gets the cover image for this album /// /// - Parameter completionHandler: The completion handler for when the cover image is loaded, passed the cover func getCoverImage(_ completionHandler: @escaping ((NSImage) -> ())) { // Return the cover image of the first song if there is one if(self.songs.count > 0) { self.songs[0].getCoverImage({ cover in completionHandler(cover); }); } // Default to the default cover if there are no songs else { completionHandler(#imageLiteral(resourceName: "AZDefaultCover")); } } var description : String { return "AZAlbum: \(self.displayName) by \(self.artists)(\(self.genres)), \(self.songs.count) songs, released in \(year)" } // MARK: - Initialization and Deinitialization init(name : String, songs : [AZSong]) { self.name = name; self.songs = songs; } init(name : String) { self.name = name; self.songs = []; } init() { self.name = ""; self.songs = []; } }
gpl-3.0
ca069b193696b3c29c9e66395580482d
28.510989
128
0.530069
4.753097
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/PaymentMethods/AddPaymentMethod/AddPaymentMethodCellPresenter.swift
1
2972
// Copyright ยฉ Blockchain Luxembourg S.A. All rights reserved. import ComposableNavigation import MoneyKit import PlatformKit import PlatformUIKit import RxCocoa import RxDataSources import RxRelay import RxSwift final class AddPaymentMethodCellPresenter: AsyncPresenting { // MARK: - Exposed Properties var isLoading: Bool { isLoadingRelay.value } var action: SettingsScreenAction { actionTypeRelay.value } var addIconImageVisibility: Driver<Visibility> { imageVisibilityRelay.asDriver() } var descriptionLabelContent: LabelContent { LabelContent( text: localizedStrings.cta, font: .main(.medium, 16.0), color: .textFieldText ) } var isAbleToAddNew: Observable<Bool> { interactor.isEnabledForUser } let badgeImagePresenter: BadgeImageAssetPresenting let labelContentPresenter: AddPaymentMethodLabelContentPresenter // MARK: - Private Properties private let imageVisibilityRelay = BehaviorRelay<Visibility>(value: .hidden) private let actionTypeRelay = BehaviorRelay<SettingsScreenAction>(value: .none) private let isLoadingRelay = BehaviorRelay<Bool>(value: true) private let disposeBag = DisposeBag() private let localizedStrings: AddPaymentMethodLocalizedStrings private let interactor: AddPaymentMethodInteractor init(interactor: AddPaymentMethodInteractor) { self.interactor = interactor localizedStrings = AddPaymentMethodLocalizedStrings(interactor.paymentMethod) labelContentPresenter = AddPaymentMethodLabelContentPresenter( interactor: AddPaymentMethodLabelContentInteractor( interactor: interactor, localizedStrings: localizedStrings ) ) badgeImagePresenter = AddPaymenMethodBadgePresenter( interactor: interactor ) setup() } private func setup() { interactor.isEnabledForUser .map { $0 ? .visible : .hidden } .bindAndCatch(to: imageVisibilityRelay) .disposed(by: disposeBag) let paymentMethod = interactor.paymentMethod interactor.isEnabledForUser .map { isEnabled in guard isEnabled else { return .none } switch paymentMethod { case .card: return .showAddCardScreen case .bank(let fiatCurrency): return .showAddBankScreen(fiatCurrency) } } .bindAndCatch(to: actionTypeRelay) .disposed(by: disposeBag) badgeImagePresenter.state .map(\.isLoading) .bindAndCatch(to: isLoadingRelay) .disposed(by: disposeBag) } } // MARK: - IdentifiableType extension AddPaymentMethodCellPresenter: IdentifiableType { var identity: String { localizedStrings.accessibilityId } }
lgpl-3.0
5526b58b7da92af04959d8051286fe4b
28.127451
85
0.662403
5.637571
false
false
false
false
xshfsky/WeiBo
WeiBo/WeiBo/AppDelegate.swift
1
1307
// // AppDelegate.swift // WeiBo // // Created by Miller on 15/9/26. // Copyright ยฉ 2015ๅนด Xie Yufeng. All rights reserved. // import UIKit //@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // ไฟฎๆ”นTabBar็š„ๆธฒๆŸ“่‰ฒ้…็ฝฎ UITabBar.appearance().tintColor = UIColor.orangeColor() // ไฟฎๆ”นๆœช็™ปๅฝ•ๆ—ถ็š„ๅฏผ่ˆชๆ ๅทฆๅณๆ–‡ๅญ—็š„ๆธฒๆŸ“่‰ฒ UINavigationBar.appearance().tintColor = UIColor.orangeColor() // ๆ นๆฎๅฑๅน•ๅฐบๅฏธๅˆๅง‹ๅŒ–UIWidow window = UIWindow(frame: UIScreen.mainScreen().bounds) // ่ฎพ็ฝฎWindow็š„ๆ นๆŽงๅˆถๅ™จไธบMainTabBarController window?.rootViewController = MainTabBarController() // ไฝฟWindowไธบKeyWindowๅนถไธ”ๆ˜พ็คบ window?.makeKeyAndVisible() return true } } /** <32>[WeiBo.HomeTableViewController titleBtnClick:] message */ func YFLog<T>(message: T, fileName: NSString = __FILE__, lineNum: Int = __LINE__, funcName: String = __FUNCTION__) { #if DEBUG print("<\(lineNum)>[\(fileName.lastPathComponent) " + "\(funcName)]: \(message)") #endif }
mit
054067b81878975670b12dc25a688aed
26.409091
127
0.651741
4.62069
false
false
false
false
tjw/swift
stdlib/public/core/UnicodeScalar.swift
1
15302
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Unicode.Scalar Type //===----------------------------------------------------------------------===// extension Unicode { /// A Unicode scalar value. /// /// The `Unicode.Scalar` type, representing a single Unicode scalar value, is /// the element type of a string's `unicodeScalars` collection. /// /// You can create a `Unicode.Scalar` instance by using a string literal that /// contains a single character representing exactly one Unicode scalar value. /// /// let letterK: Unicode.Scalar = "K" /// let kim: Unicode.Scalar = "๊น€" /// print(letterK, kim) /// // Prints "K ๊น€" /// /// You can also create Unicode scalar values directly from their numeric /// representation. /// /// let airplane = Unicode.Scalar(9992) /// print(airplane) /// // Prints "โœˆ๏ธŽ" @_fixed_layout public struct Scalar { @inlinable // FIXME(sil-serialize-all) internal init(_value: UInt32) { self._value = _value } @usableFromInline // FIXME(sil-serialize-all) internal var _value: UInt32 } } extension Unicode.Scalar : _ExpressibleByBuiltinUnicodeScalarLiteral, ExpressibleByUnicodeScalarLiteral { /// A numeric representation of the Unicode scalar. @inlinable // FIXME(sil-serialize-all) public var value: UInt32 { return _value } @inlinable // FIXME(sil-serialize-all) @_transparent public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self._value = UInt32(value) } /// Creates a Unicode scalar with the specified value. /// /// Do not call this initializer directly. It may be used by the compiler /// when you use a string literal to initialize a `Unicode.Scalar` instance. /// /// let letterK: Unicode.Scalar = "K" /// print(letterK) /// // Prints "K" /// /// In this example, the assignment to the `letterK` constant is handled by /// this initializer behind the scenes. @inlinable // FIXME(sil-serialize-all) @_transparent public init(unicodeScalarLiteral value: Unicode.Scalar) { self = value } /// Creates a Unicode scalar with the specified numeric value. /// /// For example, the following code sample creates a `Unicode.Scalar` /// instance with a value of an emoji character: /// /// let codepoint: UInt32 = 127881 /// let emoji = Unicode.Scalar(codepoint) /// print(emoji!) /// // Prints "๐ŸŽ‰" /// /// In case of an invalid input value, nil is returned. /// /// let codepoint: UInt32 = extValue // This might be an invalid value /// if let emoji = Unicode.Scalar(codepoint) { /// print(emoji) /// } else { /// // Do something else /// } /// /// - Parameter v: The Unicode code point to use for the scalar. The /// initializer succeeds if `v` is a valid Unicode scalar value---that is, /// if `v` is in the range `0...0xD7FF` or `0xE000...0x10FFFF`. If `v` is /// an invalid Unicode scalar value, the result is `nil`. @inlinable // FIXME(sil-serialize-all) public init?(_ v: UInt32) { // Unicode 6.3.0: // // D9. Unicode codespace: A range of integers from 0 to 10FFFF. // // D76. Unicode scalar value: Any Unicode code point except // high-surrogate and low-surrogate code points. // // * As a result of this definition, the set of Unicode scalar values // consists of the ranges 0 to D7FF and E000 to 10FFFF, inclusive. if (v < 0xD800 || v > 0xDFFF) && v <= 0x10FFFF { self._value = v return } // Return nil in case of an invalid unicode scalar value. return nil } /// Creates a Unicode scalar with the specified numeric value. /// /// For example, the following code sample creates a `Unicode.Scalar` /// instance with a value of `"๋ฐฅ"`, the Korean word for rice: /// /// let codepoint: UInt16 = 48165 /// let bap = Unicode.Scalar(codepoint) /// print(bap!) /// // Prints "๋ฐฅ" /// /// In case of an invalid input value, the result is `nil`. /// /// let codepoint: UInt16 = extValue // This might be an invalid value /// if let bap = Unicode.Scalar(codepoint) { /// print(bap) /// } else { /// // Do something else /// } /// /// - Parameter v: The Unicode code point to use for the scalar. The /// initializer succeeds if `v` is a valid Unicode scalar value, in the /// range `0...0xD7FF` or `0xE000...0x10FFFF`. If `v` is an invalid /// unicode scalar value, the result is `nil`. @inlinable // FIXME(sil-serialize-all) public init?(_ v: UInt16) { self.init(UInt32(v)) } /// Creates a Unicode scalar with the specified numeric value. /// /// For example, the following code sample creates a `Unicode.Scalar` /// instance with a value of `"7"`: /// /// let codepoint: UInt8 = 55 /// let seven = Unicode.Scalar(codepoint) /// print(seven) /// // Prints "7" /// /// - Parameter v: The code point to use for the scalar. @inlinable // FIXME(sil-serialize-all) public init(_ v: UInt8) { self._value = UInt32(v) } /// Creates a duplicate of the given Unicode scalar. @inlinable // FIXME(sil-serialize-all) public init(_ v: Unicode.Scalar) { // This constructor allows one to provide necessary type context to // disambiguate between function overloads on 'String' and 'Unicode.Scalar'. self = v } /// Returns a string representation of the Unicode scalar. /// /// Scalar values representing characters that are normally unprintable or /// that otherwise require escaping are escaped with a backslash. /// /// let tab = Unicode.Scalar(9) /// print(tab) /// // Prints " " /// print(tab.escaped(asASCII: false)) /// // Prints "\t" /// /// When the `forceASCII` parameter is `true`, a `Unicode.Scalar` instance /// with a value greater than 127 is represented using an escaped numeric /// value; otherwise, non-ASCII characters are represented using their /// typical string value. /// /// let bap = Unicode.Scalar(48165) /// print(bap.escaped(asASCII: false)) /// // Prints "๋ฐฅ" /// print(bap.escaped(asASCII: true)) /// // Prints "\u{BC25}" /// /// - Parameter forceASCII: Pass `true` if you need the result to use only /// ASCII characters; otherwise, pass `false`. /// - Returns: A string representation of the scalar. @inlinable // FIXME(sil-serialize-all) public func escaped(asASCII forceASCII: Bool) -> String { func lowNibbleAsHex(_ v: UInt32) -> String { let nibble = v & 15 if nibble < 10 { return String(Unicode.Scalar(nibble+48)!) // 48 = '0' } else { return String(Unicode.Scalar(nibble-10+65)!) // 65 = 'A' } } if self == "\\" { return "\\\\" } else if self == "\'" { return "\\\'" } else if self == "\"" { return "\\\"" } else if _isPrintableASCII { return String(self) } else if self == "\0" { return "\\0" } else if self == "\n" { return "\\n" } else if self == "\r" { return "\\r" } else if self == "\t" { return "\\t" } else if UInt32(self) < 128 { return "\\u{" + lowNibbleAsHex(UInt32(self) >> 4) + lowNibbleAsHex(UInt32(self)) + "}" } else if !forceASCII { return String(self) } else if UInt32(self) <= 0xFFFF { var result = "\\u{" result += lowNibbleAsHex(UInt32(self) >> 12) result += lowNibbleAsHex(UInt32(self) >> 8) result += lowNibbleAsHex(UInt32(self) >> 4) result += lowNibbleAsHex(UInt32(self)) result += "}" return result } else { // FIXME: Type checker performance prohibits this from being a // single chained "+". var result = "\\u{" result += lowNibbleAsHex(UInt32(self) >> 28) result += lowNibbleAsHex(UInt32(self) >> 24) result += lowNibbleAsHex(UInt32(self) >> 20) result += lowNibbleAsHex(UInt32(self) >> 16) result += lowNibbleAsHex(UInt32(self) >> 12) result += lowNibbleAsHex(UInt32(self) >> 8) result += lowNibbleAsHex(UInt32(self) >> 4) result += lowNibbleAsHex(UInt32(self)) result += "}" return result } } /// A Boolean value indicating whether the Unicode scalar is an ASCII /// character. /// /// ASCII characters have a scalar value between 0 and 127, inclusive. For /// example: /// /// let canyon = "Caรฑรณn" /// for scalar in canyon.unicodeScalars { /// print(scalar, scalar.isASCII, scalar.value) /// } /// // Prints "C true 67" /// // Prints "a true 97" /// // Prints "รฑ false 241" /// // Prints "รณ false 243" /// // Prints "n true 110" @inlinable // FIXME(sil-serialize-all) public var isASCII: Bool { return value <= 127 } // FIXME: Is there a similar term of art in Unicode? @inlinable // FIXME(sil-serialize-all) public var _isASCIIDigit: Bool { return self >= "0" && self <= "9" } // FIXME: Unicode makes this interesting. @inlinable // FIXME(sil-serialize-all) internal var _isPrintableASCII: Bool { return (self >= Unicode.Scalar(0o040) && self <= Unicode.Scalar(0o176)) } } extension Unicode.Scalar : CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the Unicode scalar. @inlinable // FIXME(sil-serialize-all) public var description: String { return String(self) } /// An escaped textual representation of the Unicode scalar, suitable for /// debugging. @inlinable // FIXME(sil-serialize-all) public var debugDescription: String { return "\"\(escaped(asASCII: true))\"" } } extension Unicode.Scalar : LosslessStringConvertible { @inlinable // FIXME(sil-serialize-all) public init?(_ description: String) { let scalars = description.unicodeScalars guard let v = scalars.first, scalars.count == 1 else { return nil } self = v } } extension Unicode.Scalar : Hashable { /// The Unicode scalar's hash value. /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. @inlinable // FIXME(sil-serialize-all) public var hashValue: Int { return Int(self.value) } } extension Unicode.Scalar { /// Creates a Unicode scalar with the specified numeric value. /// /// - Parameter v: The Unicode code point to use for the scalar. `v` must be /// a valid Unicode scalar value, in the ranges `0...0xD7FF` or /// `0xE000...0x10FFFF`. In case of an invalid unicode scalar value, nil is /// returned. /// /// For example, the following code sample creates a `Unicode.Scalar` instance /// with a value of an emoji character: /// /// let codepoint = 127881 /// let emoji = Unicode.Scalar(codepoint) /// print(emoji) /// // Prints "๐ŸŽ‰" /// /// In case of an invalid input value, nil is returned. /// /// let codepoint: UInt32 = extValue // This might be an invalid value. /// if let emoji = Unicode.Scalar(codepoint) { /// print(emoji) /// } else { /// // Do something else /// } @inlinable // FIXME(sil-serialize-all) public init?(_ v: Int) { if let us = Unicode.Scalar(UInt32(v)) { self = us } else { return nil } } } extension UInt8 { /// Construct with value `v.value`. /// /// - Precondition: `v.value` can be represented as ASCII (0..<128). @inlinable // FIXME(sil-serialize-all) public init(ascii v: Unicode.Scalar) { _precondition(v.value < 128, "Code point value does not fit into ASCII") self = UInt8(v.value) } } extension UInt32 { /// Construct with value `v.value`. @inlinable // FIXME(sil-serialize-all) public init(_ v: Unicode.Scalar) { self = v.value } } extension UInt64 { /// Construct with value `v.value`. @inlinable // FIXME(sil-serialize-all) public init(_ v: Unicode.Scalar) { self = UInt64(v.value) } } extension Unicode.Scalar : Equatable { @inlinable // FIXME(sil-serialize-all) public static func == (lhs: Unicode.Scalar, rhs: Unicode.Scalar) -> Bool { return lhs.value == rhs.value } } extension Unicode.Scalar : Comparable { @inlinable // FIXME(sil-serialize-all) public static func < (lhs: Unicode.Scalar, rhs: Unicode.Scalar) -> Bool { return lhs.value < rhs.value } } extension Unicode.Scalar { @_fixed_layout // FIXME(sil-serialize-all) public struct UTF16View { @inlinable // FIXME(sil-serialize-all) internal init(value: Unicode.Scalar) { self.value = value } @usableFromInline // FIXME(sil-serialize-all) internal var value: Unicode.Scalar } @inlinable // FIXME(sil-serialize-all) public var utf16: UTF16View { return UTF16View(value: self) } } extension Unicode.Scalar.UTF16View : RandomAccessCollection { public typealias Indices = Range<Int> /// The position of the first code unit. @inlinable // FIXME(sil-serialize-all) public var startIndex: Int { return 0 } /// The "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// If the collection is empty, `endIndex` is equal to `startIndex`. @inlinable // FIXME(sil-serialize-all) public var endIndex: Int { return 0 + UTF16.width(value) } /// Accesses the code unit at the specified position. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. @inlinable // FIXME(sil-serialize-all) public subscript(position: Int) -> UTF16.CodeUnit { return position == 0 ? ( endIndex == 1 ? UTF16.CodeUnit(value.value) : UTF16.leadSurrogate(value) ) : UTF16.trailSurrogate(value) } } /// Returns c as a UTF16.CodeUnit. Meant to be used as _ascii16("x"). @inlinable // FIXME(sil-serialize-all) public // SPI(SwiftExperimental) func _ascii16(_ c: Unicode.Scalar) -> UTF16.CodeUnit { _sanityCheck(c.value >= 0 && c.value <= 0x7F, "not ASCII") return UTF16.CodeUnit(c.value) } extension Unicode.Scalar { @inlinable // FIXME(sil-serialize-all) internal static var _replacementCharacter: Unicode.Scalar { return Unicode.Scalar(_value: UTF32._replacementCodeUnit) } } extension Unicode.Scalar { /// Creates an instance of the NUL scalar value. @available(*, unavailable, message: "use 'Unicode.Scalar(0)'") public init() { Builtin.unreachable() } } // @available(swift, obsoleted: 4.0, renamed: "Unicode.Scalar") public typealias UnicodeScalar = Unicode.Scalar
apache-2.0
f223a77726a33c1d1fb2fc733b961631
31.437367
82
0.618667
3.840623
false
false
false
false
melvinmt/TPStateMachine
TPStateMachine.swift
1
11965
// // TPStateMachine.swift // github.com/melvinmt/TPStateMachine // // Created by Melvin Tercan (github.com/melvinmt) on 10/31/14. // Copyright (c) 2014 Melvin Tercan. 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 Foundation typealias TPStateMachineCompletionHandler = () -> () protocol TPStateMachineDelegate : class { func didInsertItemsAtIndexPaths(indexPaths:[NSIndexPath]) func didReloadItemsAtIndexPaths(indexPaths:[NSIndexPath]) func didMoveItemAtIndexPath(fromIndexPath:NSIndexPath, toIndexPath: NSIndexPath) func didRemoveItemsAtIndexPaths(indexPaths:[NSIndexPath]) func didReloadData() } class TPStateMachine : NSObject { // Public weak var collectionView : UICollectionView? { didSet { self.collectionView?.reloadData() } } weak var tableView : UITableView? { didSet { self.tableView?.reloadData() } } weak var delegate : TPStateMachineDelegate? var section = 0 // Use a separate state machine for each section. var rowAnimation = UITableViewRowAnimation.None var delayBetweenStates : NSTimeInterval = 0 // Private private var items = [AnyObject]() let serialQueue = NSOperationQueue() override init() { super.init() self.serialQueue.maxConcurrentOperationCount = 1 } } // Serial Manipulation extension TPStateMachine { func setItems(items:[AnyObject]) { self.setItems(items, completionHandler:nil) } func setItems(items:[AnyObject], completionHandler:TPStateMachineCompletionHandler?) { serialOperation { self.mainThread { self.items = items self.reloadData() completionHandler?() } NSThread.sleepForTimeInterval(self.delayBetweenStates) } } func clearItems() { self.clearItems(nil) } func clearItems(completionHandler:TPStateMachineCompletionHandler?) { serialOperation { self.mainThread { self.items = [AnyObject]() self.reloadData() completionHandler?() } NSThread.sleepForTimeInterval(self.delayBetweenStates) } } func insertItem(item:AnyObject, atIndex index: Int) { self.insertItem(item, atIndex:index) {} } func insertItem(item:AnyObject, atIndex index:Int, completionHandler:TPStateMachineCompletionHandler?) { serialOperation { self.mainThread { if index <= self.items.count { self.items.insert(item, atIndex: index) self.insertItemsAtIndexPaths([index]) completionHandler?() } else { NSLog("index out of bounds: %d", index) } } NSThread.sleepForTimeInterval(self.delayBetweenStates) } } func appendItem(item:AnyObject) { self.appendItem(item, completionHandler:nil) } func appendItem(item:AnyObject, completionHandler:TPStateMachineCompletionHandler?) { serialOperation { self.mainThread { self.items.append(item) self.insertItemsAtIndexPaths([self.items.count - 1]) completionHandler?() } NSThread.sleepForTimeInterval(self.delayBetweenStates) } } func updateItem(item:AnyObject, atIndex index:Int) { self.updateItem(item, atIndex:index, completionHandler:nil) } func updateItem(item:AnyObject, atIndex index:Int, completionHandler:TPStateMachineCompletionHandler?) { serialOperation { self.mainThread { if index < self.items.count { self.items[index] = item self.reloadItemsAtIndexPaths([index]) completionHandler?() } else { NSLog("index out of bounds: %d", index) } } NSThread.sleepForTimeInterval(self.delayBetweenStates) } } func removeItemAtIndex(index:Int) { self.removeItemAtIndex(index, completionHandler:nil) } func removeItemAtIndex(index:Int, completionHandler:TPStateMachineCompletionHandler?) { serialOperation { self.mainThread { if index < self.items.count { self.items.removeAtIndex(index) self.removeItemsAtIndexPaths([index]) completionHandler?() } else { NSLog("index out of bounds: %d", index) } } NSThread.sleepForTimeInterval(self.delayBetweenStates) } } func moveItemFromIndex(fromIndex:Int, toIndex: Int) { self.moveItemFromIndex(fromIndex, toIndex:toIndex, completionHandler:nil) } func moveItemFromIndex(fromIndex:Int, toIndex: Int, completionHandler:TPStateMachineCompletionHandler?) { serialOperation { self.mainThread { if fromIndex < self.items.count && toIndex < self.items.count { if fromIndex == toIndex { return } if let item = self.itemAtIndex(fromIndex) { self.items.removeAtIndex(fromIndex) self.items.insert(item, atIndex: toIndex) self.moveItemAtIndexPath(fromIndex, toIndex: toIndex) completionHandler?() } } } NSThread.sleepForTimeInterval(self.delayBetweenStates) } } func moveUpdatedItem(updatedItem:AnyObject, toIndex: Int) { self.moveUpdatedItem(updatedItem, toIndex:toIndex, completionHandler:nil) } func moveUpdatedItem(updatedItem:AnyObject, toIndex: Int, completionHandler:TPStateMachineCompletionHandler?) { serialOperation { self.mainThread { if toIndex < self.items.count { if let fromIndex = self.indexForItem(updatedItem) { if fromIndex == toIndex { return } self.items.removeAtIndex(fromIndex) self.items.insert(updatedItem, atIndex: toIndex) self.moveItemAtIndexPath(fromIndex, toIndex: toIndex) completionHandler?() } } } NSThread.sleepForTimeInterval(self.delayBetweenStates) } } func moveUpdatedItem(updatedItem:AnyObject, fromIndex: Int, toIndex: Int) { self.moveUpdatedItem(updatedItem, fromIndex: fromIndex, toIndex: toIndex, completionHandler:nil) } func moveUpdatedItem(updatedItem:AnyObject, fromIndex: Int, toIndex: Int, completionHandler:TPStateMachineCompletionHandler?) { if fromIndex == toIndex { return } serialOperation { self.mainThread { if fromIndex < self.items.count && toIndex < self.items.count { self.items.removeAtIndex(fromIndex) self.items.insert(updatedItem, atIndex: toIndex) self.moveItemAtIndexPath(fromIndex, toIndex: toIndex) completionHandler?() } } NSThread.sleepForTimeInterval(self.delayBetweenStates) } } } // Data retrieval extension TPStateMachine { func countItems() -> Int { return self.items.count } func itemAtIndex(index:Int) -> AnyObject? { if index < self.items.count { return self.items[index] } else { NSLog("index out of bounds: %d", index) } return nil } func indexForItem(item:AnyObject) -> Int? { for (index, existingItem) in enumerate(self.items) { if existingItem.isEqual(item) { return index } } return nil } func itemExists(item:AnyObject) -> Bool { for existingItem in self.items { if existingItem.isEqual(item) { return true } } return false } func allItems() -> [AnyObject] { return self.items } } // Private functions extension TPStateMachine { private func mainThread(dispatch_block:()->()) { dispatch_async(dispatch_get_main_queue()) { dispatch_block() } } private func serialOperation(dispatch_block:()->()) { self.serialQueue.addOperationWithBlock() { dispatch_block() } } private func indexPathsForIndexes(indexes:[Int]) -> [NSIndexPath] { var indexPaths = [NSIndexPath]() for index in indexes { let indexPath = NSIndexPath(forItem: index, inSection: self.section) indexPaths.append(indexPath) } return indexPaths } private func insertItemsAtIndexPaths(indexes:[Int]) { let indexPaths = self.indexPathsForIndexes(indexes) self.collectionView?.insertItemsAtIndexPaths(indexPaths) self.tableView?.insertRowsAtIndexPaths(indexPaths, withRowAnimation: self.rowAnimation) self.delegate?.didInsertItemsAtIndexPaths(indexPaths) } private func reloadItemsAtIndexPaths(indexes:[Int]) { let indexPaths = self.indexPathsForIndexes(indexes) self.collectionView?.reloadItemsAtIndexPaths(indexPaths) self.tableView?.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: self.rowAnimation) self.delegate?.didReloadItemsAtIndexPaths(indexPaths) } private func moveItemAtIndexPath(fromIndex:Int, toIndex: Int) { let fromIndexPath = NSIndexPath(forItem: fromIndex, inSection: self.section) let toIndexPath = NSIndexPath(forItem: toIndex, inSection: self.section) self.collectionView?.moveItemAtIndexPath(fromIndexPath, toIndexPath: toIndexPath) self.tableView?.moveRowAtIndexPath(fromIndexPath, toIndexPath: toIndexPath) self.delegate?.didMoveItemAtIndexPath(fromIndexPath, toIndexPath: toIndexPath) } private func removeItemsAtIndexPaths(indexes:[Int]) { let indexPaths = self.indexPathsForIndexes(indexes) self.collectionView?.deleteItemsAtIndexPaths(indexPaths) self.tableView?.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: self.rowAnimation) self.delegate?.didRemoveItemsAtIndexPaths(indexPaths) } private func reloadData() { self.collectionView?.reloadData() self.tableView?.reloadData() self.delegate?.didReloadData() } }
mit
fb2f96712a7086a5877dfa516b1f45d4
33.185714
131
0.613456
5.339134
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
Frameworks/TBAKit/Sources/TBATeam.swift
1
15237
import Foundation public struct TBATeam: TBAModel { public var key: String public var teamNumber: Int public var nickname: String? public var name: String public var schoolName: String? public var city: String? public var stateProv: String? public var country: String? public var address: String? public var postalCode: String? public var gmapsPlaceID: String? public var gmapsURL: String? public var lat: Double? public var lng: Double? public var locationName: String? public var website: String? public var rookieYear: Int? public var homeChampionship: [String: String]? public init(key: String, teamNumber: Int, nickname: String? = nil, name: String, schoolName: String? = nil, city: String? = nil, stateProv: String? = nil, country: String? = nil, address: String? = nil, postalCode: String? = nil, gmapsPlaceID: String? = nil, gmapsURL: String? = nil, lat: Double? = nil, lng: Double? = nil, locationName: String? = nil, website: String? = nil, rookieYear: Int? = nil, homeChampionship: [String: String]? = nil) { self.key = key self.teamNumber = teamNumber self.nickname = nickname self.name = name self.schoolName = schoolName self.city = city self.stateProv = stateProv self.country = country self.address = address self.postalCode = postalCode self.gmapsPlaceID = gmapsPlaceID self.gmapsURL = gmapsURL self.lat = lat self.lng = lng self.locationName = locationName self.website = website self.rookieYear = rookieYear self.homeChampionship = homeChampionship } init?(json: [String: Any]) { // Required: key, name, teamNumber guard let key = json["key"] as? String else { return nil } self.key = key guard let name = json["name"] as? String else { return nil } self.name = name guard let teamNumber = json["team_number"] as? Int else { return nil } self.teamNumber = teamNumber self.address = json["address"] as? String self.city = json["city"] as? String self.country = json["country"] as? String self.gmapsPlaceID = json["gmaps_place_id"] as? String self.gmapsURL = json["gmaps_url"] as? String self.homeChampionship = json["home_championship"] as? [String: String] self.lat = json["lat"] as? Double self.lng = json["lng"] as? Double self.locationName = json["location_name"] as? String self.nickname = json["nickname"] as? String self.postalCode = json["postal_code"] as? String self.rookieYear = json["rookie_year"] as? Int self.schoolName = json["school_name"] as? String self.stateProv = json["state_prov"] as? String self.website = json["website"] as? String } } public struct TBARobot: TBAModel { public var key: String public var name: String public var teamKey: String public var year: Int public init(key: String, name: String, teamKey: String, year: Int) { self.key = key self.name = name self.teamKey = teamKey self.year = year } init?(json: [String: Any]) { // Required: key, name, teamKey, year guard let key = json["key"] as? String else { return nil } self.key = key guard let name = json["robot_name"] as? String else { return nil } self.name = name guard let teamKey = json["team_key"] as? String else { return nil } self.teamKey = teamKey guard let year = json["year"] as? Int else { return nil } self.year = year } } public struct TBAEventStatus: TBAModel { public var teamKey: String public var eventKey: String public var qual: TBAEventStatusQual? public var alliance: TBAEventStatusAlliance? public var playoff: TBAAllianceStatus? public var allianceStatusString: String? public var playoffStatusString: String? public var overallStatusString: String? public var nextMatchKey: String? public var lastMatchKey: String? public init(teamKey: String, eventKey: String, qual: TBAEventStatusQual? = nil, alliance: TBAEventStatusAlliance? = nil, playoff: TBAAllianceStatus? = nil, allianceStatusString: String? = nil, playoffStatusString: String? = nil, overallStatusString: String? = nil, nextMatchKey: String? = nil, lastMatchKey: String? = nil) { self.teamKey = teamKey self.eventKey = eventKey self.qual = qual self.alliance = alliance self.playoff = playoff self.allianceStatusString = allianceStatusString self.playoffStatusString = playoffStatusString self.overallStatusString = overallStatusString self.nextMatchKey = nextMatchKey self.lastMatchKey = lastMatchKey } init?(json: [String: Any]) { // Required: teamKey, eventKey (as passed in by JSON manually) guard let teamKey = json["team_key"] as? String else { return nil } self.teamKey = teamKey guard let eventKey = json["event_key"] as? String else { return nil } self.eventKey = eventKey if let qualJSON = json["qual"] as? [String: Any] { self.qual = TBAEventStatusQual(json: qualJSON) } if let allianceJSON = json["alliance"] as? [String: Any] { self.alliance = TBAEventStatusAlliance(json: allianceJSON) } if let playoffJSON = json["playoff"] as? [String: Any] { self.playoff = TBAAllianceStatus(json: playoffJSON) } self.allianceStatusString = json["alliance_status_str"] as? String self.playoffStatusString = json["playoff_status_str"] as? String self.overallStatusString = json["overall_status_str"] as? String self.nextMatchKey = json["next_match_key"] as? String self.lastMatchKey = json["last_match_key"] as? String } } public struct TBAEventStatusQual: TBAModel { public var numTeams: Int? public var status: String? public var ranking: TBAEventRanking? public var sortOrder: [TBAEventRankingSortOrder]? public init(numTeams: Int? = nil, status: String? = nil, ranking: TBAEventRanking? = nil, sortOrder: [TBAEventRankingSortOrder]? = nil) { self.numTeams = numTeams self.status = status self.ranking = ranking self.sortOrder = sortOrder } init?(json: [String: Any]) { self.numTeams = json["num_teams"] as? Int self.status = json["status"] as? String if let rankingJSON = json["ranking"] as? [String: Any] { self.ranking = TBAEventRanking(json: rankingJSON) } if let sortOrdersJSON = json["sort_order_info"] as? [[String: Any]] { self.sortOrder = sortOrdersJSON.compactMap({ (sortOrderJSON) -> TBAEventRankingSortOrder? in return TBAEventRankingSortOrder(json: sortOrderJSON) }) } } } public struct TBAEventStatusAlliance: TBAModel { public var number: Int public var pick: Int public var name: String? public var backup: TBAAllianceBackup? public init(number: Int, pick: Int, name: String? = nil, backup: TBAAllianceBackup? = nil) { self.number = number self.pick = pick self.name = name self.backup = backup } init?(json: [String: Any]) { // Required: number, pick guard let number = json["number"] as? Int else { return nil } self.number = number guard let pick = json["pick"] as? Int else { return nil } self.pick = pick self.name = json["name"] as? String if let backupJSON = json["backup"] as? [String: Any] { self.backup = TBAAllianceBackup(json: backupJSON) } } } public struct TBAMedia: TBAModel { public var type: String public var foreignKey: String public var details: [String: Any]? public var preferred: Bool public var directURL: String? public var viewURL: String? public init(type: String, foreignKey: String, details: [String: Any]? = nil, preferred: Bool = false, directURL: String? = nil, viewURL: String? = nil) { self.type = type self.foreignKey = foreignKey self.details = details self.preferred = preferred self.directURL = directURL self.viewURL = viewURL } init?(json: [String: Any]) { // Required: type, foreign_key guard let type = json["type"] as? String else { return nil } self.type = type guard let foreignKey = json["foreign_key"] as? String else { return nil } self.foreignKey = foreignKey self.details = json["details"] as? [String: Any] self.preferred = json["preferred"] as? Bool ?? false self.directURL = json["direct_url"] as? String self.viewURL = json["view_url"] as? String } } extension TBAKit { public func fetchTeams(simple: Bool = false, completion: @escaping (Result<[TBATeam], Error>, Bool) -> ()) -> TBAKitOperation { let method = simple ? "teams/all/simple" : "teams/all" return callArray(method: method, completion: completion) } public func fetchTeams(page: Int, year: Int? = nil, completion: @escaping (Result<[TBATeam], Error>, Bool) -> ()) -> TBAKitOperation { var method = "teams" if let year = year { method = "\(method)/\(year)" } method = "\(method)/\(page)" return callArray(method: method, completion: completion) } public func fetchTeam(key: String, completion: @escaping (Result<TBATeam?, Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)" return callObject(method: method, completion: completion) } public func fetchTeamYearsParticipated(key: String, completion: @escaping (Result<[Int], Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)/years_participated" return callArray(method: method) { (result, notModified) in switch result { case .failure(let error): completion(.failure(error), notModified) case .success(let years): if let years = years as? [Int] { completion(.success(years), notModified) } else { completion(.failure(APIError.error("Unexpected response from server.")), notModified) } } } } public func fetchTeamDistricts(key: String, completion: @escaping (Result<[TBADistrict], Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)/districts" return callArray(method: method, completion: completion) } public func fetchTeamRobots(key: String, completion: @escaping (Result<[TBARobot], Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)/robots" return callArray(method: method, completion: completion) } public func fetchTeamEvents(key: String, year: Int? = nil, completion: @escaping (Result<[TBAEvent], Error>, Bool) -> ()) -> TBAKitOperation { var method = "team/\(key)/events" if let year = year { method = "\(method)/\(year)" } return callArray(method: method, completion: completion) } public func fetchTeamStatuses(key: String, year: Int, completion: @escaping (Result<[TBAEventStatus], Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)/events/\(year)/statuses" return callDictionary(method: method, completion: { (result, notModified) in switch result { case .failure(let error): completion(.failure(error), notModified) case .success(let dictionary): let eventStatuses = dictionary.compactMap({ (eventKey, statusJSON) -> TBAEventStatus? in // Add teamKey/eventKey to statusJSON guard var json = statusJSON as? [String: Any] else { return nil } json["team_key"] = key json["event_key"] = eventKey return TBAEventStatus(json: json) }) completion(.success(eventStatuses), notModified) } }) } public func fetchTeamMatches(key: String, eventKey: String, completion: @escaping (Result<[TBAMatch], Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)/event/\(eventKey)/matches" return callArray(method: method, completion: completion) } public func fetchTeamAwards(key: String, eventKey: String, completion: @escaping (Result<[TBAAward], Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)/event/\(eventKey)/awards" return callArray(method: method, completion: completion) } public func fetchTeamStatus(key: String, eventKey: String, completion: @escaping (Result<TBAEventStatus?, Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)/event/\(eventKey)/status" return callDictionary(method: method, completion: { (result, notModified) in switch result { case .failure(let error): completion(.failure(error), notModified) case .success(var dictionary): dictionary["team_key"] = key dictionary["event_key"] = eventKey if let status = TBAEventStatus(json: dictionary) { completion(.success(status), notModified) } else { completion(.failure(APIError.error("Unexpected response from server.")), notModified) } } }) } public func fetchTeamAwards(key: String, year: Int? = nil, completion: @escaping (Result<[TBAAward], Error>, Bool) -> ()) -> TBAKitOperation { var method = "team/\(key)/awards" if let year = year { method = "\(method)/\(year)" } return callArray(method: method, completion: completion) } public func fetchTeamMatches(key: String, year: Int, completion: @escaping (Result<[TBAMatch], Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)/matches/\(year)" return callArray(method: method, completion: completion) } public func fetchTeamMedia(key: String, year: Int, completion: @escaping (Result<[TBAMedia], Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)/media/\(year)" return callArray(method: method, completion: completion) } public func fetchTeamSocialMedia(key: String, completion: @escaping (Result<[TBAMedia], Error>, Bool) -> ()) -> TBAKitOperation { let method = "team/\(key)/social_media" return callArray(method: method, completion: completion) } }
mit
54eb6735ed8f9113bad0beb8385503f9
35.627404
449
0.604909
4.322553
false
false
false
false
ink-spot/UPActionButton
UPActionButton/UPActionButton.swift
1
48930
// // UPActionButton.swift // UPActionButtonDemo // // Created by Paul Ulric on 28/02/2017. // Copyright ยฉ 2017 Paul Ulric. All rights reserved. // import UIKit @objc public protocol UPActionButtonDelegate { @objc optional func actionButtonWillOpen(_: UPActionButton) @objc optional func actionButtonDidOpen(_: UPActionButton) @objc optional func actionButtonWillClose(_: UPActionButton) @objc optional func actionButtonDidClose(_: UPActionButton) } public enum UPActionButtonPosition { case free(center: CGPoint) case topLeft(padding: CGPoint) case topRight(padding: CGPoint) case bottomLeft(padding: CGPoint) case bottomRight(padding: CGPoint) } public enum UPActionButtonDisplayAnimationType { case none case slideUp, slideDown, slideLeft, slideRight case scaleUp, scaleDown } public enum UPActionButtonTransitionType { case none case rotate(degrees: CGFloat) case crossDissolveImage(UIImage) case crossDissolveText(String) } public enum UPActionButtonOverlayType { case plain(UIColor) case blurred(UIVisualEffect) } public enum UPActionButtonOverlayAnimationType { case none case fade case bubble } public enum UPActionButtonItemsPosition { case up case down case round, roundHalfUp, roundHalfRight, roundHalfDown, roundHalfLeft case roundQuarterUp, roundQuarterUpRight, roundQuarterRight, roundQuarterDownRight case roundQuarterDown, roundQuarterDownLeft, roundQuarterLeft, roundQuarterUpLeft } public enum UPActionButtonItemsAnimationType { case none case fade, fadeUp, fadeDown, fadeLeft, fadeRight case scaleUp, scaleDown case slide case bounce } public enum UPActionButtonItemsAnimationOrder { case linear, progressive, progressiveInverse } open class UPActionButton: UIView { fileprivate enum ScrollDirection { case none, up, down } fileprivate typealias AnimationSteps = (preparation: (() -> Void)?, animation: (() -> Void)?, completion: (() -> Void)?) // MARK: - Properties fileprivate var backgroundView: UIVisualEffectView! fileprivate var containerView: UIView! fileprivate var button: UIButton! fileprivate var openTitleLabel: UILabel! fileprivate var closedTitleLabel: UILabel! fileprivate var openTitleImageView: UIImageView! fileprivate var closedTitleImageView: UIImageView! fileprivate var visibleOpenTitleView: UIView? { if openTitleImageView.image != nil { return openTitleImageView } if openTitleLabel.text != nil { return openTitleLabel } return nil } fileprivate var containerOpenSize: CGSize = .zero fileprivate var buttonOpenCenter: CGPoint = .zero fileprivate var isAnimatingOpenClose = false fileprivate var isAnimatingShowHide = false fileprivate let slideAnimationOffset: CGFloat = 20.0 fileprivate let scaleAnimationOffset: CGFloat = 0.5 fileprivate var observesSuperviewBounds = false fileprivate var observesSuperviewContentOffset = false fileprivate var observesInteractiveScrollView = false fileprivate var scrollCurrentDirection: ScrollDirection = .none fileprivate var scrollStartOffset: CGFloat = 0 fileprivate var scrollLastOffset: CGFloat = 0 fileprivate let interactiveScrollDistance: CGFloat = 64.0 fileprivate(set) var items = [UPActionButtonItem]() public fileprivate(set) var isOpen = false public var delegate: UPActionButtonDelegate? @IBOutlet public var interactiveScrollView: UIScrollView? { didSet { if let scrollView = oldValue, observesInteractiveScrollView { scrollView.removeObserver(self, forKeyPath: "contentOffset") observesInteractiveScrollView = false } if let scrollView = interactiveScrollView { scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.old, .new], context: nil) observesInteractiveScrollView = true } } } @IBInspectable public var floating: Bool = false { didSet { if !floating && observesSuperviewContentOffset { self.superview?.removeObserver(self, forKeyPath: "contentOffset") observesSuperviewContentOffset = false } if let superview = self.superview as? UIScrollView, floating { superview.addObserver(self, forKeyPath: "contentOffset", options: [.old, .new], context: nil) observesSuperviewContentOffset = true } } } /* Customization */ public var animationDuration: TimeInterval = 0.3 // Button public var position: UPActionButtonPosition = .free(center: .zero) { didSet { updateButtonPosition() } } public var showAnimationType: UPActionButtonDisplayAnimationType = .none public var hideAnimationType: UPActionButtonDisplayAnimationType = .none public var buttonTransitionType: UPActionButtonTransitionType = .none @IBInspectable public var image: UIImage? { get { return openTitleImageView.image } set { openTitleImageView.image = newValue openTitleImageView.isHidden = false openTitleImageView.alpha = 1.0 openTitleLabel.text = nil openTitleLabel.isHidden = true } } @IBInspectable public var title: String? { get { return openTitleLabel.text } set { openTitleLabel.text = newValue openTitleLabel.isHidden = false openTitleLabel.alpha = 1.0 openTitleImageView.image = nil openTitleImageView.isHidden = true } } @IBInspectable public var titleColor: UIColor { get { return openTitleLabel.textColor } set { openTitleLabel.textColor = newValue closedTitleLabel.textColor = newValue } } public var titleFont: UIFont { get { return openTitleLabel.font } set { openTitleLabel.font = newValue closedTitleLabel.font = newValue } } @IBInspectable public var color: UIColor? { get { return button.backgroundColor } set { button.backgroundColor = newValue } } @IBInspectable public var cornerRadius: CGFloat { get { return button.layer.cornerRadius } set { button.layer.cornerRadius = newValue } } // Overlay public var overlayType: UPActionButtonOverlayType? { didSet { let type: UPActionButtonOverlayType = overlayType ?? .plain(.clear) switch type { case .plain(let color): backgroundView.backgroundColor = color backgroundView.effect = nil case .blurred(let visualEffect): guard self.overlayAnimationType != .bubble else { print("[UPActionButton] The blurred overlay type is not compatible with the bubble overlay animation") self.overlayType = oldValue return } backgroundView.backgroundColor = .clear backgroundView.effect = visualEffect print(backgroundView) } } } public var overlayAnimationType: UPActionButtonOverlayAnimationType = .none { didSet { if self.overlayType != nil, case .blurred(_) = self.overlayType!, overlayAnimationType == .bubble { print("[UPActionButton] The bubble overlay animation is not compatible with the blurred overlay type") self.overlayAnimationType = oldValue return } } } // Items public var itemsPosition: UPActionButtonItemsPosition = .up { didSet { computeOpenSize() } } @IBInspectable public var itemSize: CGSize = CGSize(width: 30, height: 30) { didSet { items.forEach({ $0.size = itemSize }) } } @IBInspectable public var itemsInterSpacing: CGFloat = 10.0 { didSet { computeOpenSize() } } public var itemsAnimationType: UPActionButtonItemsAnimationType = .none public var itemsAnimationOrder: UPActionButtonItemsAnimationOrder = .linear // MARK: - Initialization public init(frame: CGRect, image: UIImage?, title: String?) { super.init(frame: frame) setupElements() if let image = image { self.image = image } else if let title = title { self.title = title } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupElements() } deinit { if let superview = self.superview { if observesSuperviewBounds { superview.removeObserver(self, forKeyPath: "frame") observesSuperviewBounds = false } if observesSuperviewContentOffset { superview.removeObserver(self, forKeyPath: "contentOffset") observesSuperviewContentOffset = false } } if let scrollView = interactiveScrollView, observesInteractiveScrollView { scrollView.removeObserver(self, forKeyPath: "contentOffset") observesInteractiveScrollView = false } } override open func willMove(toSuperview newSuperview: UIView?) { if let superview = self.superview { if observesSuperviewBounds { superview.removeObserver(self, forKeyPath: "frame") observesSuperviewBounds = false } if observesSuperviewContentOffset { superview.removeObserver(self, forKeyPath: "contentOffset") observesSuperviewContentOffset = false } } super.willMove(toSuperview: newSuperview) } override open func didMoveToSuperview() { if let superview = self.superview { updateButtonPosition() superview.addObserver(self, forKeyPath: "frame", options: [.old, .new], context: nil) observesSuperviewBounds = true if (floating && superview is UIScrollView) { superview.addObserver(self, forKeyPath: "contentOffset", options: [.old, .new], context: nil) observesSuperviewContentOffset = true } } super.didMoveToSuperview() } // MARK: - UI Elements Setup func setupElements() { let innerFrame = CGRect(origin: .zero, size: self.frame.size) self.backgroundColor = .clear backgroundView = UIVisualEffectView(frame: innerFrame) backgroundView.isHidden = true let backgroundTapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle)) backgroundView.addGestureRecognizer(backgroundTapGesture) self.addSubview(backgroundView) containerView = UIView(frame: innerFrame) let containerTapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle)) containerView.addGestureRecognizer(containerTapGesture) self.addSubview(containerView) button = UIButton(type: .custom) button.frame = innerFrame button.addTarget(self, action: #selector(toggle), for: .touchUpInside) containerView.addSubview(button) openTitleLabel = UILabel() closedTitleLabel = UILabel() [openTitleLabel, closedTitleLabel].forEach { (label: UILabel) in label.frame = innerFrame label.alpha = 0.0 label.isHidden = true label.textAlignment = .center button.addSubview(label) } openTitleImageView = UIImageView() closedTitleImageView = UIImageView() [openTitleImageView, closedTitleImageView].forEach { (image: UIImageView!) in image.frame = innerFrame image.alpha = 0.0 image.isHidden = true image.contentMode = .scaleAspectFill button.addSubview(image) } let center = CGPoint(x: self.frame.origin.x + self.frame.size.width / 2, y: self.frame.origin.y + self.frame.size.height / 2) self.position = .free(center: center) setDefaultConfiguration() } func setDefaultConfiguration() { showAnimationType = .scaleUp hideAnimationType = .scaleDown color = .blue let midSize = min(frame.size.width, frame.size.height) / 2 cornerRadius = midSize setShadow(color: .black, opacity: 0.5, radius: 3.0, offset: CGSize(width: 0, height: 2)) titleColor = .white titleFont = UIFont.systemFont(ofSize: midSize) let inset = midSize / 2 setTitleInset(dx: inset, dy: inset) overlayType = .plain(UIColor(white: 0.0, alpha: 0.3)) overlayAnimationType = .fade itemsPosition = .up itemsAnimationType = .bounce itemsAnimationOrder = .progressive itemSize = CGSize(width: midSize, height: midSize) } } // MARK: - Public API extension UPActionButton { /* Customization */ open func setShadow(color: UIColor, opacity: Float, radius: CGFloat, offset: CGSize) { button.layer.shadowColor = color.cgColor button.layer.shadowOpacity = opacity button.layer.shadowRadius = radius button.layer.shadowOffset = offset } open func setTitleTextOffset(_ offset: CGPoint) { [openTitleLabel, closedTitleLabel].forEach { (label: UIView) in var anchorPoint = CGPoint(x: 0.5, y: 0.5) anchorPoint.x += offset.x / label.frame.size.width anchorPoint.y += offset.y / label.frame.size.height label.layer.anchorPoint = anchorPoint } } open func setTitleInset(dx: CGFloat, dy: CGFloat) { [openTitleLabel, closedTitleLabel, openTitleImageView, closedTitleImageView].forEach { (view: UIView) in view.frame = self.button.frame.insetBy(dx: dx, dy: dy) } } /* Display */ open func show(animated: Bool = true) { guard isHidden && !isAnimatingShowHide else { return } if showAnimationType == .none || !animated { self.isHidden = false return } let animation = appearAnimations(type: showAnimationType) isAnimatingShowHide = true animation.preparation?() UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: { animation.animation?() }) { (finished: Bool) in animation.completion?() self.isAnimatingShowHide = false } } open func hide(animated: Bool = true) { guard !isHidden && !isAnimatingShowHide else { return } if isOpen { close(animated: false) } if showAnimationType == .none || !animated { self.isHidden = true return } let animation = disappearAnimations(type: hideAnimationType) isAnimatingShowHide = true animation.preparation?() UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: { animation.animation?() }) { (finished: Bool) in animation.completion?() self.isAnimatingShowHide = false } } /* Items management */ open func add(item: UPActionButtonItem) { add(item: item, computeSize: true) } open func add(items: [UPActionButtonItem]) { items.forEach({ self.add(item: $0, computeSize: false) }) computeOpenSize() } open func remove(item: UPActionButtonItem) { remove(item: item, computeSize: true) } open func remove(itemAt index: Int) { guard index >= 0 && index < items.count else { return } remove(item: items[index], computeSize: true) } open func removeAllItems() { items.forEach({ self.remove(item: $0, computeSize: false) }) computeOpenSize() } /* Interactions */ open func toggle() { if isOpen { close() } else { open() } } open func open(animated: Bool = true) { guard !isOpen && !isAnimatingOpenClose else { return } delegate?.actionButtonWillOpen?(self) isAnimatingOpenClose = true expandContainers() expandOverlay(animated: animated) expandItems(animated: animated) transitionButtonTitle(animated: animated) } open func close(animated: Bool = true) { guard isOpen && !isAnimatingOpenClose else { return } delegate?.actionButtonWillClose?(self) isAnimatingOpenClose = true reduceOverlay(animated: animated) reduceItems(animated: animated) transitionButtonTitle(animated: animated) } /* Observers */ override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let newValue = change?[.newKey] as? NSObject, let oldValue = change?[.oldKey] as? NSObject, newValue == oldValue { return } if (object as? UIView) == superview && keyPath == "frame" { guard let superview = self.superview else { return } if isOpen { let superFrame = CGRect(origin: .zero, size: superview.frame.size) self.frame = superFrame backgroundView.frame = superFrame } self.updateButtonPosition() } if (object as? UIView) == superview && keyPath == "contentOffset" && floating { guard let scrollView = self.superview as? UIScrollView else { return } if isOpen { var frame = self.frame frame.origin.y = scrollView.contentOffset.y self.frame = frame } else { self.updateButtonPosition() } } if (object as? UIScrollView) == interactiveScrollView && keyPath == "contentOffset" { guard let scrollView = interactiveScrollView, !isOpen else { return } handleInteractiveScroll(from: scrollView) } } } // MARK: - UPActionButtonItem Delegate Methods extension UPActionButton: UPActionButtonItemDelegate { public func didTouch(item: UPActionButtonItem) { guard item.closeOnTap else { return } self.close() } } // MARK: - Private Helpers (Items) extension UPActionButton/*: CAAnimationDelegate*/ { /* Items Management */ fileprivate func add(item: UPActionButtonItem, computeSize compute: Bool) { item.delegate = self items.append(item) item.size = itemSize item.center = button.center containerView.insertSubview(item, at: 0) if compute { computeOpenSize() } } fileprivate func remove(item: UPActionButtonItem, computeSize compute: Bool) { guard let index = items.index(of: item) else { return } item.removeFromSuperview() items.remove(at: index) if compute { computeOpenSize() } } /* Interactions */ fileprivate func expandContainers() { let origin = self.frame.origin var superOrigin: CGPoint = .zero if let superScrollview = self.superview as? UIScrollView { superOrigin = superScrollview.contentOffset } let superSize: CGSize = superview?.frame.size ?? .zero let superFrame = CGRect(origin: superOrigin, size: superSize) self.frame = superFrame var containerFrame = containerView.frame containerFrame.origin = CGPoint(x: origin.x - superOrigin.x, y: origin.y - superOrigin.y) containerFrame.size = containerOpenSize containerFrame.origin.x -= buttonOpenCenter.x - button.frame.size.width / 2.0 containerFrame.origin.y -= buttonOpenCenter.y - button.frame.size.height / 2.0 containerView.frame = containerFrame button.center = buttonOpenCenter items.forEach({ $0.center = button.center }) } fileprivate func expandOverlay(animated: Bool = true) { backgroundView.isHidden = false let animate = animated && self.overlayAnimationType != .none if animate { let animation = self.overlayAnimations(opening: true, type: overlayAnimationType) animation.preparation?() UIView.animate(withDuration: animationDuration, delay: 0.0, options: .curveEaseInOut, animations: { animation.animation?() }, completion: { (finished: Bool) in animation.completion?() if self.itemsAnimationType == .none { self.openAnimationDidStop() } }) } else { backgroundView.frame = CGRect(origin: .zero, size: self.frame.size) backgroundView.alpha = 1.0 } } fileprivate func expandItems(animated: Bool = true) { let lastAnimatedItemIndex: Int = itemsAnimationOrder == .progressiveInverse ? 0 : self.items.count - 1 for (index, item) in self.items.enumerated() { let center = self.center(forItem: item, index: index, itemsPosition: itemsPosition, opening: true) var duration = self.animationDuration var delay = 0.0 switch itemsAnimationOrder { case .linear: break case .progressive: delay = Double(index) * 0.02 case .progressiveInverse: delay = Double(items.count - (index+1)) * 0.02 } DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { let animate = animated && self.itemsAnimationType != .none item.expand(animated: animate, duration: duration) if animate { var damping: CGFloat = 1.0 if self.itemsAnimationType == .bounce { damping = 0.7 var durationOffset: TimeInterval = 0 if self.itemsAnimationOrder == .progressive { durationOffset = Double(index) * duration / Double(self.items.count) } else if self.itemsAnimationOrder == .progressiveInverse { durationOffset = Double(self.items.count - index) * duration / Double(self.items.count) } duration += durationOffset } let animation = self.openAnimations(forItem: item, to: center, type: self.itemsAnimationType) animation.preparation?() UIView.animate(withDuration: duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: 0.0, options: .curveEaseInOut, animations: { animation.animation?() }) { (finished: Bool) in animation.completion?() if index == lastAnimatedItemIndex { self.openAnimationDidStop() } } } else { item.center = center item.alpha = 1.0 if index == lastAnimatedItemIndex { self.openAnimationDidStop() } } }) } } fileprivate func reduceContainers() { let superview = self.superview ?? self let baseOrigin = containerView.convert(button.frame.origin, to: superview) let baseSize = button.frame.size let frame = CGRect(origin: baseOrigin, size: baseSize) let innerFrame = CGRect(origin: CGPoint(x: 0, y: 0), size: baseSize) self.frame = frame containerView.frame = innerFrame button.frame = innerFrame items.forEach({ $0.center = button.center }) } fileprivate func reduceOverlay(animated: Bool = true) { let animate = animated && self.overlayAnimationType != .none if animate { let animation = self.overlayAnimations(opening: false, type: overlayAnimationType) animation.preparation?() UIView.animate(withDuration: animationDuration, delay: 0.0, options: .curveEaseInOut, animations: { animation.animation?() }, completion: { (finished: Bool) in animation.completion?() if self.itemsAnimationType == .none { self.closeAnimationDidStop() } }) } else { self.backgroundView.frame = CGRect(origin: .zero, size: self.frame.size) self.backgroundView.alpha = 0.0 self.backgroundView.isHidden = true } } fileprivate func reduceItems(animated: Bool = true) { let lastAnimatedItemIndex: Int = itemsAnimationOrder == .progressiveInverse ? 0 : self.items.count - 1 for (index, item) in self.items.enumerated() { let center = self.center(forItem: item, index: index, itemsPosition: itemsPosition, opening: false) var duration = self.animationDuration var delay = 0.0 switch itemsAnimationOrder { case .linear: break case .progressive: delay = Double(index) * 0.02 case .progressiveInverse: delay = Double(items.count - (index+1)) * 0.02 } DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { let animate = animated && self.itemsAnimationType != .none item.reduce(animated: animate, duration: duration) if animate { var damping: CGFloat = 1.0 var velocity: CGFloat = 0.0 if self.itemsAnimationType == .bounce { damping = 1.0 velocity = -5 var durationOffset: TimeInterval = 0 if self.itemsAnimationOrder == .progressive { durationOffset = Double(index) * duration / Double(self.items.count) } else if self.itemsAnimationOrder == .progressiveInverse { durationOffset = Double(self.items.count - (index + 1)) * duration / Double(self.items.count) } duration += durationOffset duration *= 2 } let animation = self.closeAnimations(forItem: item, to: center, type: self.itemsAnimationType) animation.preparation?() UIView.animate(withDuration: duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .curveEaseInOut, animations: { animation.animation?() }) { (finished: Bool) in animation.completion?() if index == lastAnimatedItemIndex { self.closeAnimationDidStop() } } } else { item.center = center item.alpha = 0.0 if index == lastAnimatedItemIndex { self.closeAnimationDidStop() } } }) } } fileprivate func openAnimationDidStop() { guard !isOpen else { return } isOpen = true delegate?.actionButtonDidOpen?(self) isAnimatingOpenClose = false } fileprivate func closeAnimationDidStop() { guard isOpen else { return } isOpen = false reduceContainers() delegate?.actionButtonDidClose?(self) isAnimatingOpenClose = false } /* Geometry Computations */ fileprivate func computeOpenSize() { let center = button.center var topLeftCorner = button.frame.origin var bottomRightCorner = CGPoint(x: button.frame.origin.x + button.frame.size.width, y: button.frame.origin.y + button.frame.size.height) for (index, item) in self.items.enumerated() { let itemLeftOffset = item.center.x - item.frame.origin.x let itemRightOffset = item.frame.origin.x + item.frame.size.width - item.center.x let itemTopOffset = item.center.y - item.frame.origin.y let itemBottomOffset = item.frame.origin.y + item.frame.size.height - item.center.y let itemCenter = self.center(forItem: item, index: index, itemsPosition: self.itemsPosition, opening: true) topLeftCorner = CGPoint(x: min(topLeftCorner.x, itemCenter.x - itemLeftOffset), y: min(topLeftCorner.y, itemCenter.y - itemTopOffset)) bottomRightCorner = CGPoint(x: max(bottomRightCorner.x, itemCenter.x + itemRightOffset), y: max(bottomRightCorner.y, itemCenter.y + itemBottomOffset)) } containerOpenSize = CGSize(width: bottomRightCorner.x - topLeftCorner.x, height: bottomRightCorner.y - topLeftCorner.y) buttonOpenCenter = CGPoint(x: abs(center.x - topLeftCorner.x), y: abs(center.y - topLeftCorner.y)) } fileprivate func center(forItem item: UPActionButtonItem, index: Int, itemsPosition position: UPActionButtonItemsPosition, opening: Bool) -> CGPoint { var center = button.center if (opening) { let buttonFrame = button.frame let itemSize = item.frame.size let itemOffset = (itemSize.height + self.itemsInterSpacing) * CGFloat(index + 1) switch position { case .up: center.y = buttonFrame.origin.y - itemOffset + itemSize.height / 2 case .down: center.y = buttonFrame.origin.y + buttonFrame.size.height + itemOffset - itemSize.height / 2 case .round, .roundHalfUp, .roundHalfRight, .roundHalfDown, .roundHalfLeft, .roundQuarterUp, .roundQuarterUpRight, .roundQuarterRight, .roundQuarterDownRight, .roundQuarterDown, .roundQuarterDownLeft, .roundQuarterLeft, .roundQuarterUpLeft: let radius = self.itemsInterSpacing + button.frame.size.width / 2 + self.itemSize.width / 2 let angles = self.angles(forItemsRoundPosition: position) var count = CGFloat(self.items.count) if position != .round { count -= 1 } let angle = (angles.max / count * CGFloat(index) + angles.start) let xOffset = radius * cos(radians(degrees: angle)) * -1 let yOffset = radius * sin(radians(degrees: angle)) * -1 center.x += xOffset center.y += yOffset } } return center } fileprivate func angles(forItemsRoundPosition position: UPActionButtonItemsPosition) -> (max: CGFloat, start: CGFloat) { switch position { case .round: return (max: 360, start: 0) case .roundHalfUp: return (max: 180, start: 0) case .roundHalfRight: return (max: 180, start: 90) case .roundHalfDown: return (max: 180, start: 180) case .roundHalfLeft: return (max: 180, start: 270) case .roundQuarterUp: return (max: 90, start: 45) case .roundQuarterUpRight: return (max: 90, start: 90) case .roundQuarterRight: return (max: 90, start: 135) case .roundQuarterDownRight: return (max: 90, start: 180) case .roundQuarterDown: return (max: 90, start: 225) case .roundQuarterDownLeft: return (max: 90, start: 270) case .roundQuarterLeft: return (max: 90, start: 315) case .roundQuarterUpLeft: return (max: 90, start: 0) default: return (max: 0, start: 0) } } fileprivate func coveringBubbleDiameter(for center: CGPoint) -> CGFloat { let maxOffsetX = max(center.x, self.frame.size.width - center.x) let maxOffsetY = max(center.y, self.frame.size.height - center.y) let radius = sqrt(pow(maxOffsetX, 2) + pow(maxOffsetY, 2)) return radius * 2 } fileprivate func radians(degrees: CGFloat) -> CGFloat { return degrees * .pi / 180 } /* Animations */ fileprivate func overlayAnimations(opening: Bool, type: UPActionButtonOverlayAnimationType) -> AnimationSteps { return (preparation: { switch type { case .none: break case .fade: self.backgroundView.alpha = opening ? 0.0 : 1.0 self.backgroundView.frame = CGRect(origin: .zero, size: self.frame.size) case .bubble: let center = self.containerView.convert(self.button.center, to: self) self.backgroundView.frame = CGRect(origin: .zero, size: CGSize(width: 1, height: 1)) self.backgroundView.center = center self.backgroundView.layer.cornerRadius = self.backgroundView.frame.size.width / 2.0 self.backgroundView.alpha = 1.0 if !opening { let diameter = self.coveringBubbleDiameter(for: self.backgroundView.center) self.backgroundView.transform = CGAffineTransform(scaleX: diameter, y: diameter) } } }, animation: { switch type { case .none: break case .fade: self.backgroundView.alpha = opening ? 1.0 : 0.0 case .bubble: if opening { let diameter = self.coveringBubbleDiameter(for: self.backgroundView.center) self.backgroundView.transform = CGAffineTransform(scaleX: diameter, y: diameter) } else { self.backgroundView.transform = CGAffineTransform.identity } } }, completion: { if opening { self.backgroundView.transform = CGAffineTransform.identity } else { self.backgroundView.isHidden = true } self.backgroundView.frame = CGRect(origin: .zero, size: self.frame.size) self.backgroundView.layer.cornerRadius = 0 }) } fileprivate func openAnimations(forItem item: UPActionButtonItem, to: CGPoint, type: UPActionButtonItemsAnimationType) -> AnimationSteps { let translationOffset: CGFloat = 20.0 let scaleOffset: CGFloat = 0.5 return (preparation: { var alpha: CGFloat = 0.0 switch type { case .none: break case .fade: item.center = to case .fadeDown: item.center = CGPoint(x: to.x, y: to.y - translationOffset) case .fadeUp: item.center = CGPoint(x: to.x, y: to.y + translationOffset) case .fadeLeft: item.center = CGPoint(x: to.x + translationOffset, y: to.y) case .fadeRight: item.center = CGPoint(x: to.x - translationOffset, y: to.y) case .scaleDown: item.center = to item.transform = CGAffineTransform(scaleX: 1 + scaleOffset, y: 1 + scaleOffset) case .scaleUp: item.center = to item.transform = CGAffineTransform(scaleX: 1 - scaleOffset, y: 1 - scaleOffset) case .slide: break case .bounce: alpha = 1.0 } item.alpha = alpha }, animation: { item.transform = CGAffineTransform.identity item.center = to item.alpha = 1.0 }, completion: nil) } fileprivate func closeAnimations(forItem item: UPActionButtonItem, to: CGPoint, type: UPActionButtonItemsAnimationType) -> AnimationSteps { let translationOffset: CGFloat = 20.0 let scaleOffset: CGFloat = 0.5 return (preparation: { item.alpha = 1.0 }, animation: { var alpha: CGFloat = 0.0 let center = item.center switch type { case .none: break case .fade: break case .fadeDown: item.center = CGPoint(x: center.x, y: center.y - translationOffset) case .fadeUp: item.center = CGPoint(x: center.x, y: center.y + translationOffset) case .fadeLeft: item.center = CGPoint(x: center.x + translationOffset, y: center.y) case .fadeRight: item.center = CGPoint(x: center.x - translationOffset, y: center.y) case .scaleDown: item.transform = CGAffineTransform(scaleX: 1 + scaleOffset, y: 1 + scaleOffset) case .scaleUp: item.transform = CGAffineTransform(scaleX: 1 - scaleOffset, y: 1 - scaleOffset) case .slide: item.center = to case .bounce: item.center = to alpha = 1.0 } item.alpha = alpha }, completion: { item.transform = CGAffineTransform.identity item.center = to item.alpha = 0.0 }) } } // MARK: - Private Helpers (Button) extension UPActionButton { fileprivate func updateButtonPosition() { let superSize: CGSize = superview?.frame.size ?? .zero var contentOffset: CGPoint = .zero if let scrollView = superview as? UIScrollView, floating { contentOffset = scrollView.contentOffset } if !isOpen { var translatedCenter = self.center switch position { case .free(let center): translatedCenter = center case .topLeft(let padding): translatedCenter.x = padding.x + self.frame.size.width/2 translatedCenter.y = padding.y + self.frame.size.height/2 case .topRight(let padding): translatedCenter.x = superSize.width - (padding.x + self.frame.size.width/2) translatedCenter.y = padding.y + self.frame.size.height/2 case .bottomLeft(let padding): translatedCenter.x = padding.x + self.frame.size.width/2 translatedCenter.y = superSize.height - (padding.y + self.frame.size.height/2) case .bottomRight(let padding): translatedCenter.x = superSize.width - (padding.x + self.frame.size.width/2) translatedCenter.y = superSize.height - (padding.y + self.frame.size.height/2) } translatedCenter.x += contentOffset.x translatedCenter.y += contentOffset.y self.center = translatedCenter } else { var containerCenter = self.containerView.center let centerHorizontalDistance = self.button.center.x - self.containerView.frame.size.width/2 let centerVerticalDistance = self.button.center.y - self.containerView.frame.size.height/2 let buttonSize = button.frame.size switch position { case .free(let center): containerCenter.x = center.x + centerHorizontalDistance containerCenter.y = center.y + centerVerticalDistance case .topLeft(let padding): containerCenter.x = padding.x - centerHorizontalDistance + buttonSize.width/2 containerCenter.y = padding.y - centerVerticalDistance + buttonSize.height/2 case .topRight(let padding): containerCenter.x = superSize.width - (padding.x + centerHorizontalDistance + buttonSize.width/2) containerCenter.y = padding.y - centerVerticalDistance + buttonSize.height/2 case .bottomLeft(let padding): containerCenter.x = padding.x - centerHorizontalDistance + buttonSize.width/2 containerCenter.y = superSize.height - (padding.y + centerVerticalDistance + buttonSize.height/2) case .bottomRight(let padding): containerCenter.x = superSize.width - (padding.x + centerHorizontalDistance + buttonSize.width/2) containerCenter.y = superSize.height - (padding.y + centerVerticalDistance + buttonSize.height/2) } self.containerView.center = containerCenter } } fileprivate func handleInteractiveScroll(from scrollView: UIScrollView) { let scrollCurrentOffset = scrollView.contentOffset.y let scrollableSize = scrollView.contentSize.height - scrollView.frame.size.height guard scrollCurrentOffset >= 0 && scrollCurrentOffset <= scrollableSize else { return } let scrolledDistance = scrollLastOffset - scrollCurrentOffset let direction: ScrollDirection = scrolledDistance < 0 ? .down : scrolledDistance > 0 ? .up : .none if direction != .none { if direction != scrollCurrentDirection { scrollCurrentDirection = direction scrollStartOffset = scrollCurrentOffset } else { if (scrollCurrentDirection == .down && !self.isHidden) || (scrollCurrentDirection == .up && self.isHidden) { let totalScrolledDistance = scrollStartOffset - scrollCurrentOffset if fabsf(Float(totalScrolledDistance)) > Float(interactiveScrollDistance) { switch scrollCurrentDirection { case .down: hide() case .up: show() default: break } } // Show the button right away when scrolling up from the bottom of the scrollview else if scrollCurrentDirection == .up && scrollLastOffset > scrollableSize - 10 { show() } } } } scrollLastOffset = scrollCurrentOffset } /* Animations */ fileprivate func appearAnimations(type: UPActionButtonDisplayAnimationType) -> AnimationSteps { let initialContainerFrame = containerView.frame return (preparation: { var containerFrame = self.containerView.frame switch type { case .none: break case .slideDown: containerFrame.origin.y -= self.slideAnimationOffset self.containerView.frame = containerFrame case .slideUp: containerFrame.origin.y += self.slideAnimationOffset self.containerView.frame = containerFrame case .slideLeft: containerFrame.origin.x += self.slideAnimationOffset self.containerView.frame = containerFrame case .slideRight: containerFrame.origin.x -= self.slideAnimationOffset self.containerView.frame = containerFrame case .scaleDown: self.containerView.transform = CGAffineTransform(scaleX: 1 + self.scaleAnimationOffset, y: 1 + self.scaleAnimationOffset) case .scaleUp: self.containerView.transform = CGAffineTransform(scaleX: 1 - self.scaleAnimationOffset, y: 1 - self.scaleAnimationOffset) } self.isHidden = false self.containerView.alpha = 0.0 }, animation: { self.containerView.transform = CGAffineTransform.identity self.containerView.frame = initialContainerFrame self.containerView.alpha = 1.0 }, completion: nil) } fileprivate func disappearAnimations(type: UPActionButtonDisplayAnimationType) -> AnimationSteps { let initialContainerFrame = containerView.frame return (preparation: { self.containerView.alpha = 1.0 }, animation: { var containerFrame = self.containerView.frame switch type { case .none: break case .slideDown: containerFrame.origin.y += self.slideAnimationOffset self.containerView.frame = containerFrame case .slideUp: containerFrame.origin.y -= self.slideAnimationOffset self.containerView.frame = containerFrame case .slideLeft: containerFrame.origin.x -= self.slideAnimationOffset self.containerView.frame = containerFrame case .slideRight: containerFrame.origin.x += self.slideAnimationOffset self.containerView.frame = containerFrame case .scaleDown: self.containerView.transform = CGAffineTransform(scaleX: 1 - self.scaleAnimationOffset, y: 1 - self.scaleAnimationOffset) case .scaleUp: self.containerView.transform = CGAffineTransform(scaleX: 1 + self.scaleAnimationOffset, y: 1 + self.scaleAnimationOffset) } self.containerView.alpha = 0.0 }, completion: { self.isHidden = true self.containerView.transform = CGAffineTransform.identity self.containerView.frame = initialContainerFrame }) } fileprivate func transitionButtonTitle(animated: Bool = true) { let duration = animated ? animationDuration : 0.0 let opening = !isOpen switch buttonTransitionType { case .none: break case .rotate(let degrees): guard let titleView = self.visibleOpenTitleView else { return } let angle = radians(degrees: degrees) UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: .curveEaseInOut, animations: { titleView.transform = opening ? CGAffineTransform(rotationAngle: angle) : CGAffineTransform.identity }, completion: nil) case .crossDissolveText(let title): if opening { closedTitleLabel.text = title } closedTitleLabel.isHidden = false visibleOpenTitleView?.isHidden = false UIView.animate(withDuration: duration, animations: { self.visibleOpenTitleView?.alpha = opening ? 0.0 : 1.0 self.closedTitleLabel.alpha = opening ? 1.0 : 0.0 }, completion: { (finished: Bool) in self.visibleOpenTitleView?.isHidden = opening self.closedTitleLabel.isHidden = !opening }) case .crossDissolveImage(let image): if opening { closedTitleImageView.image = image } closedTitleImageView.isHidden = false visibleOpenTitleView?.isHidden = false UIView.animate(withDuration: duration, animations: { self.visibleOpenTitleView?.alpha = opening ? 0.0 : 1.0 self.closedTitleImageView.alpha = opening ? 1.0 : 0.0 }, completion: { (finished: Bool) in self.visibleOpenTitleView?.isHidden = opening self.closedTitleImageView.isHidden = !opening }) } } }
mit
10548aeb159c819bd63826540745a9c0
38.205929
178
0.581577
5.171105
false
false
false
false
kchitalia/SalesforceMobileSDK-iOS
build/app_template_files/__NativeSwiftTemplateAppName__/__NativeSwiftTemplateAppName__/RootViewController.swift
1
4305
/* Copyright (c) 2015, salesforce.com, inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of salesforce.com, inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation import SalesforceRestAPI class RootViewController : UITableViewController, SFRestDelegate { var dataRows = [NSDictionary]() // MARK: - View lifecycle override func loadView() { super.loadView() self.title = "Mobile SDK Sample App" //Here we use a query that should work on either Force.com or Database.com let request = SFRestAPI.sharedInstance().requestForQuery("SELECT Name FROM User LIMIT 10"); SFRestAPI.sharedInstance().send(request, delegate: self); } // MARK: - SFRestAPIDelegate func request(request: SFRestRequest!, didLoadResponse jsonResponse: AnyObject!) { self.dataRows = jsonResponse["records"] as! [NSDictionary] self.log(.Debug, msg: "request:didLoadResponse: #records: \(self.dataRows.count)") dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } func request(request: SFRestRequest!, didFailLoadWithError error: NSError!) { self.log(.Debug, msg: "didFailLoadWithError: \(error)") // Add your failed error handling here } func requestDidCancelLoad(request: SFRestRequest!) { self.log(.Debug, msg: "requestDidCancelLoad: \(request)") // Add your failed error handling here } func requestDidTimeout(request: SFRestRequest!) { self.log(.Debug, msg: "requestDidTimeout: \(request)") // Add your failed error handling here } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return 1 } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { return self.dataRows.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "CellIdentifier" // Dequeue or create a cell of the appropriate type. var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) if (cell == nil) { cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellIdentifier) } // If you want to add an image to your cell, here's how. let image = UIImage(named: "icon.png") cell!.imageView!.image = image // Configure the cell to show the data. let obj = dataRows[indexPath.row] cell!.textLabel!.text = obj["Name"] as? String // This adds the arrow to the right hand side. cell?.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell! } }
apache-2.0
6e7b4e2a47e66dcfc43edeee9be6e001
39.613208
116
0.700581
4.971132
false
false
false
false
EvgeneOskin/animals-mobile
ios/HelloAnimals/AppDelegate.swift
2
3352
// // AppDelegate.swift // HelloAnimals // // Created by Eugene Oskin on 02.07.15. // Copyright (c) 2015 Eugene Oskin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } }
apache-2.0
7cf306dfe82f179623b8cda3f20bd149
52.206349
285
0.750895
6.230483
false
false
false
false
roambotics/swift
test/Sema/diag_defer_block_end.swift
3
574
// RUN: %target-typecheck-verify-swift let x = 1 let y = 2 if (x > y) { defer { // expected-warning {{'defer' statement at end of scope always executes immediately}}{{5-10=do}} print("not so useful defer stmt.") } } // https://github.com/apple/swift/issues/49855 do { func f(_ value: Bool) { let negated = !value defer { // expected-warning {{'defer' statement at end of scope always executes immediately}}{{7-12=do}} print("negated value is \(negated)") } } f(true) } defer { // No note print("end of program.") }
apache-2.0
66ea4670c05a82511f2b7b414acaa895
21.076923
110
0.601045
3.478788
false
false
false
false