repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
chenchangqing/learniosRAC | refs/heads/master | FRP-Swift/FRP-Swift/ViewModels/FRPPhotoViewModel.swift | gpl-2.0 | 1 | //
// FRPPhotoViewModel.swift
// FRP-Swift
//
// Created by green on 15/9/4.
// Copyright (c) 2015年 green. All rights reserved.
//
import UIKit
import ReactiveViewModel
import ReactiveCocoa
class FRPPhotoViewModel: ImageViewModel {
let photoModelDataSourceProtocol = FRPPhotoModelDataSource.shareInstance()
var searchFullsizedURLCommand :RACCommand!
var errorMsg : String = ""
var isLoading : Bool = false
init(photoModel:FRPPhotoModel) {
super.init(urlString: nil,model:photoModel,isNeedCompress:false)
// 初始化command
searchFullsizedURLCommand = RACCommand(signalBlock: { (any:AnyObject!) -> RACSignal! in
self.setValue(true, forKey: "isLoading")
if let identifier=(self.model as! FRPPhotoModel).identifier {
return self.photoModelDataSourceProtocol.searchFullsizedURL(identifier)
} else {
return RACSignal.empty()
}
})
// 错误处理
searchFullsizedURLCommand.errors.subscribeNextAs { (error:NSError) -> () in
self.setValue(false, forKey: "isLoading")
self.setValue(error.localizedDescription, forKey: "errorMsg")
}
downloadImageCommand.errors.subscribeNextAs { (error:NSError) -> () in
self.setValue(false, forKey: "isLoading")
self.setValue(error.localizedDescription, forKey: "errorMsg")
}
// 更新大图URLString
searchFullsizedURLCommand.executionSignals.switchToLatest()
// .takeUntil(didBecomeInactiveSignal.skip(1))
.subscribeNext({ (any:AnyObject!) -> Void in
// 更新图片
self.urlString = any as? String
self.downloadImageCommand.execute(nil)
}, completed: { () -> Void in
println("searchFullsizedURLCommand completed")
})
downloadImageCommand.executionSignals.switchToLatest()
// .takeUntil(didBecomeInactiveSignal.skip(1))
.subscribeNext({ (any:AnyObject!) -> Void in
self.setValue(false, forKey: "isLoading")
}, completed: { () -> Void in
self.setValue(false, forKey: "isLoading")
})
// 激活后开始查询
didBecomeActiveSignal.subscribeNext { (any:AnyObject!) -> Void in
searchFullsizedURLCommand.execute(nil)
}
}
}
| fdbd0b9791d0fce3df7ce4d5bccceceb | 31.341772 | 95 | 0.579256 | false | false | false | false |
c-shen/PlayThePlane | refs/heads/master | PlayThePlane/PlayThePlane/Main/MyPlaneCollectionViewControler.swift | apache-2.0 | 1 | //
// MyPlaneView.swift
// Play the plane
//
// Created by Aiya on 15/8/22.
// Copyright © 2015年 aiya. All rights reserved.
//
import UIKit
protocol MyPlaneCollectionViewControlerDelegate: NSObjectProtocol {
func result(standard: Bool)
}
private let reuseIdentifier = "Cell"
class MyPlaneCollectionViewControler: UICollectionViewController {
weak var myPlaneDelegate: MyPlaneCollectionViewControlerDelegate?
var attackCount = Int()
var myHearArray = [NSIndexPath]()
var myPlane = [NSIndexPath]()
private let imageIcon = UIImage(named: "background3")!
override func viewDidLoad() {
super.viewDidLoad()
prepareCollectionView()
}
func addMyPlane(firstPlane: [NSIndexPath], secondPlane: [NSIndexPath], thirdPlane: [NSIndexPath], planeImageView : UIImageView, myPlaneArray: [NSIndexPath], headArray : [NSIndexPath]) {
// for index in firstPlane {
// (self.collectionView!.cellForItemAtIndexPath(index) as! MyCollectionViewCell).status = 1
// }
// for index in secondPlane {
// (self.collectionView!.cellForItemAtIndexPath(index) as! MyCollectionViewCell).status = 2
// }
// for index in thirdPlane {
// (self.collectionView!.cellForItemAtIndexPath(index) as! MyCollectionViewCell).status = 3
// }
myPlane = myPlaneArray
myHearArray = headArray
// 1. 开启一个图片的图形上下文
UIGraphicsBeginImageContextWithOptions(collectionView!.frame.size, false, 0.0)
// 3. 把原图片绘制到上下文中
imageIcon.drawInRect((collectionView?.frame)!)
planeImageView.image!.drawInRect((collectionView?.frame)!)
// 4. 从图形上下文中取出图片
let image = UIGraphicsGetImageFromCurrentImageContext()
// 结束图形上下文
UIGraphicsEndImageContext();
collectionView!.layer.contents = image.CGImage
}
func clearMyPlane (planeArray : [NSIndexPath]) {
collectionView!.layer.contents = imageIcon.CGImage
attackCount = 0
myHearArray.removeAll()
for index in 0...80 {
let indexPath = NSIndexPath(forItem: index, inSection: 0)
(self.collectionView!.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell).status = 0
(self.collectionView!.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell).hit = 0
}
}
//MARK: 单机的方法
func solitaireGame(difficulty: Int , headArray : [NSIndexPath]) {
if attackCount == difficulty {
(collectionView?.cellForItemAtIndexPath(myHearArray.last!) as! MyCollectionViewCell).hit = 1
myHearArray.removeLast()
if myHearArray.count == 0 {
self.myPlaneDelegate?.result(false)
}
} else {
attackCount++
let firstPoint = Int(arc4random_uniform(75) + 3)
let index = NSIndexPath(forItem: firstPoint, inSection: 0)
if (collectionView?.cellForItemAtIndexPath(index) as! MyCollectionViewCell).hit == 0 {
for indexPlane in myPlane {
if indexPlane == index {
(collectionView?.cellForItemAtIndexPath(index) as! MyCollectionViewCell).hit = 2
break
} else {
(collectionView?.cellForItemAtIndexPath(index) as! MyCollectionViewCell).hit = 3
}
}
for head in headArray {
var j = 0
j++
if index == head {
(collectionView?.cellForItemAtIndexPath(index) as! MyCollectionViewCell).hit = 1
myHearArray.removeAtIndex(j - 1)
if myHearArray.count == 0 {
self.myPlaneDelegate?.result(false)
}
}
}
} else {
solitaireGame(difficulty, headArray: headArray)
}
}
}
/// 布局属性
private let layout = MyFlowLayout()
init() {
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 准备 CollectionView
private func prepareCollectionView() {
self.collectionView!.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
/// 自定义流水布局
private class MyFlowLayout: UICollectionViewFlowLayout {
private override func prepareLayout() {
minimumLineSpacing = 0
minimumInteritemSpacing = 0
let wh = collectionView!.bounds.width / 9.0
itemSize = CGSize(width: wh, height: wh)
collectionView?.showsHorizontalScrollIndicator = false
}
}
// MARK: - UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 81
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
as! MyCollectionViewCell
return cell
}
}
private class MyCollectionViewCell: UICollectionViewCell {
var isHead : Bool = false
var status : Int = 0 {
didSet {
switch status {
case 1 :
viewBtn.highlighted = true
// viewBtn.backgroundColor = UIColor.whiteColor()
// viewBtn.setBackgroundImage(UIImage(named: "purple"), forState: UIControlState.Highlighted)
case 2 :
viewBtn.highlighted = true
// viewBtn.backgroundColor = UIColor.whiteColor()
// viewBtn.setBackgroundImage(UIImage(named: "red"), forState: UIControlState.Highlighted)
case 3 :
viewBtn.highlighted = true
// viewBtn.backgroundColor = UIColor.whiteColor()
// viewBtn.setBackgroundImage(UIImage(named: "green"), forState: UIControlState.Highlighted)
case 4 :
viewBtn.highlighted = true
// viewBtn.backgroundColor = UIColor.whiteColor()
// viewBtn.setBackgroundImage(UIImage(named: ""), forState: UIControlState.Highlighted)
default :
viewBtn.selected = false
viewBtn.highlighted = false
viewBtn.backgroundColor = UIColor.clearColor()
}
}
}
var hit : Int = 0 {
didSet {
switch hit {
case 1 :
viewBtn.selected = true
viewBtn.highlighted = false
viewBtn.setImage(UIImage(named: "die"), forState: UIControlState.Selected)
case 2 :
viewBtn.selected = true
viewBtn.highlighted = false
viewBtn.setImage(UIImage(named: "fuselage"), forState: UIControlState.Selected)
case 3 :
viewBtn.selected = true
viewBtn.setImage(UIImage(named: "noBuy"), forState: UIControlState.Selected)
default :
viewBtn.selected = false
viewBtn.highlighted = false
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
contentView.addSubview(viewBtn)
viewBtn.userInteractionEnabled = false
viewBtn.frame = contentView.frame
viewBtn.frame = CGRectInset(bounds, 0.5 , 0.5)
}
private lazy var viewBtn: UIButton = {
let btn = UIButton()
btn.backgroundColor = UIColor.clearColor()
// btn.setBackgroundImage(UIImage(named: ""), forState: UIControlState.Normal)
// btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Selected)
// btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
return btn
}()
}
| 81216c7799c81cee66c8cc6bde89751c | 31.949275 | 189 | 0.550803 | false | false | false | false |
ingresse/ios-sdk | refs/heads/dev | IngresseSDK/Services/UserTickets/Requests/TicketsWalletRequest.swift | mit | 1 | //
// Copyright © 2020 Ingresse. All rights reserved.
//
public struct TicketsRequest: Encodable {
public let usertoken: String
public let eventId: Int?
public let page: Int?
public let pageSize: Int?
public let sessionId: String?
public let itemType: String?
public init(usertoken: String,
eventId: Int?,
page: Int?,
pageSize: Int?) {
self.usertoken = usertoken
self.eventId = eventId
self.page = page
self.pageSize = pageSize
self.sessionId = nil
self.itemType = nil
}
public init(usertoken: String,
page: Int?,
pageSize: Int?) {
self.usertoken = usertoken
self.eventId = nil
self.page = page
self.pageSize = pageSize
self.sessionId = nil
self.itemType = nil
}
public init(usertoken: String,
eventId: Int?,
page: Int?,
pageSize: Int?,
sessionId: String? = nil,
itemType: TicketType? = nil) {
self.usertoken = usertoken
self.eventId = eventId
self.page = page
self.pageSize = pageSize
self.sessionId = sessionId
self.itemType = itemType?.rawValue
}
public enum TicketType: String {
case ticket
case passport
}
public func getType(_ string: String) -> TicketType {
if string == TicketType.ticket.rawValue {
return TicketType.ticket
}
return TicketType.passport
}
}
| 72be0d74488b84745949710ffb7eb70c | 23.19697 | 57 | 0.548528 | false | false | false | false |
hoowang/WKRefreshDemo | refs/heads/master | RefreshToolkit/Views/WKPureRefreshHeader.swift | mit | 1 | //
// WKPureRefreshHeader.swift
// WKRefreshDemo
//
// Created by hooge on 16/5/4.
// Copyright © 2016年 hooge. All rights reserved.
//
import UIKit
public class WKPureRefreshHeader: WKRefreshHeader {
private let activityView = UIActivityIndicatorView(activityIndicatorStyle:.Gray)
override func initialize() {
super.initialize()
self.addSubview(self.activityView)
}
override func placeSubViews() {
super.placeSubViews()
let activityWH:CGFloat = 30.0
let activityX = (self.wk_Width - activityWH) * 0.5
let activityY = (self.wk_Height - activityWH) * 0.5
self.activityView.frame = CGRectMake(activityX, activityY, activityWH, activityWH)
}
override func loadAnimators() {
dispatch_async(dispatch_get_main_queue()) {
self.activityView.startAnimating()
}
}
override func unloadAnimators() {
dispatch_async(dispatch_get_main_queue()) {
self.activityView.stopAnimating()
}
}
public override func completeRefresh() {
super.completeRefresh()
self.activityView.stopAnimating()
}
override func changeIndicatorState(state:AnimationState) {
self.activityView.startAnimating()
}
deinit{
wkLog("WKPureRefreshHeader deinit")
}
}
extension WKPureRefreshHeader{
internal override func refreshHandler() {
self.codeToRefresh = true
super.refreshHandler()
}
}
extension WKPureRefreshHeader{
public override class func refreshHeaderFor(
scrollView:UIScrollView, callback:()->(Void)) -> (WKRefreshControl){
let header = WKPureRefreshHeader()
header.callbackMode = .ClosureMode
header.callback = callback
scrollView.addSubview(header)
return header
}
public override class func refreshHeaderFor(
scrollView:UIScrollView, target:AnyObject, action:Selector) -> (WKRefreshControl){
let refreshHeader = WKPureRefreshHeader()
refreshHeader.callbackMode = .SelectorMode
refreshHeader.targetObject = target
refreshHeader.selector = action
scrollView.addSubview(refreshHeader)
return refreshHeader
}
}
| c26212f45967f027cfcbf03f3d719fc8 | 26.890244 | 90 | 0.65282 | false | false | false | false |
XSega/Words | refs/heads/master | Words/UIView+Extension.swift | mit | 1 | //
// UIView+Extension.swift
//
import UIKit
//
// Inspectable - Design and layout for View
// cornerRadius, borderWidth, borderColor
//
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable
var borderColor: UIColor? {
get {
let color = UIColor.init(cgColor: layer.borderColor!)
return color
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 2)
layer.shadowOpacity = 0.4
layer.shadowRadius = shadowRadius
}
}
}
//
// View for UILabel Accessory
//
extension UIView {
func rightValidAccessoryView() -> UIView {
let imgView = UIImageView(image: UIImage(named: "check_valid"))
imgView.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
imgView.backgroundColor = UIColor.clear
return imgView
}
func rightInValidAccessoryView() -> UIView {
let imgView = UIImageView(image: UIImage(named: "check_invalid"))
imgView.frame = CGRect(x: self.cornerRadius, y: self.cornerRadius, width: 20, height: 20)
imgView.backgroundColor = UIColor.clear
return imgView
}
}
| ed4735d48408bf025bad1499ea25b3f7 | 21.506173 | 97 | 0.56226 | false | false | false | false |
ilhanadiyaman/firefox-ios | refs/heads/master | Client/Frontend/Settings/ClearPrivateDataTableViewController.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
private let SectionToggles = 0
private let SectionButton = 1
private let NumberOfSections = 2
private let SectionHeaderFooterIdentifier = "SectionHeaderFooterIdentifier"
private let HeaderFooterHeight: CGFloat = 44
private let TogglesPrefKey = "clearprivatedata.toggles"
private let log = Logger.browserLogger
class ClearPrivateDataTableViewController: UITableViewController {
private var clearButton: UITableViewCell?
var profile: Profile!
var tabManager: TabManager!
private typealias DefaultCheckedState = Bool
private lazy var clearables: [(clearable: Clearable, checked: DefaultCheckedState)] = {
return [
(HistoryClearable(profile: self.profile), true),
(CacheClearable(tabManager: self.tabManager), true),
(CookiesClearable(tabManager: self.tabManager), true),
(SiteDataClearable(tabManager: self.tabManager), true),
]
}()
private lazy var toggles: [Bool] = {
if let savedToggles = self.profile.prefs.arrayForKey(TogglesPrefKey) as? [Bool] {
return savedToggles
}
return self.clearables.map { $0.checked }
}()
private var clearButtonEnabled = true {
didSet {
clearButton?.textLabel?.textColor = clearButtonEnabled ? UIConstants.DestructiveRed : UIColor.lightGrayColor()
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Clear Private Data", tableName: "ClearPrivateData", comment: "Navigation title in settings.")
tableView.registerClass(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderFooterIdentifier)
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
let footer = SettingsTableSectionHeaderFooterView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: HeaderFooterHeight))
footer.showBottomBorder = false
tableView.tableFooterView = footer
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
if indexPath.section == SectionToggles {
cell.textLabel?.text = clearables[indexPath.item].clearable.label
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = toggles[indexPath.item]
cell.accessoryView = control
cell.selectionStyle = .None
control.tag = indexPath.item
} else {
assert(indexPath.section == SectionButton)
cell.textLabel?.text = NSLocalizedString("Clear Private Data", tableName: "ClearPrivateData", comment: "Button in settings that clears private data for the selected items.")
cell.textLabel?.textAlignment = NSTextAlignment.Center
cell.textLabel?.textColor = UIConstants.DestructiveRed
cell.accessibilityTraits = UIAccessibilityTraitButton
clearButton = cell
}
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return NumberOfSections
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == SectionToggles {
return clearables.count
}
assert(section == SectionButton)
return 1
}
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
guard indexPath.section == SectionButton else { return false }
// Highlight the button only if it's enabled.
return clearButtonEnabled
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
guard indexPath.section == SectionButton else { return }
let toggles = self.toggles
clearables
.enumerate()
.flatMap { (i, pair) in
guard toggles[i] else {
return nil
}
log.debug("Clearing \(pair.clearable).")
return pair.clearable.clear()
}
.allSucceed()
.upon { result in
assert(result.isSuccess, "Private data cleared successfully")
self.profile.prefs.setObject(self.toggles, forKey: TogglesPrefKey)
dispatch_async(dispatch_get_main_queue()) {
// Disable the Clear Private Data button after it's clicked.
self.clearButtonEnabled = false
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderFooterIdentifier) as! SettingsTableSectionHeaderFooterView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return HeaderFooterHeight
}
@objc func switchValueChanged(toggle: UISwitch) {
toggles[toggle.tag] = toggle.on
// Dim the clear button if no clearables are selected.
clearButtonEnabled = toggles.contains(true)
}
} | a3a4fe39fdd171d63a7f7f67e032399a | 38.829932 | 185 | 0.675777 | false | false | false | false |
Coderian/SwiftedGPX | refs/heads/master | SwiftedGPX/Elements/Number.swift | mit | 1 | //
// Number.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/16.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX Number
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:element name="number" type="xsd:nonNegativeInteger" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// GPS route number.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
///
/// <xsd:element name="number" type="xsd:nonNegativeInteger" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// GPS track number.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
public class Number : SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue {
public static var elementName: String = "number"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as Route: v.value.number = self
case let v as Track: v.value.number = self
default: break
}
}
}
}
public var value: UInt!
public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{
self.value = UInt(contents)
self.parent = parent
return parent
}
public required init(attributes:[String:String]){
super.init(attributes: attributes)
}
} | ceae985f6e7c64bd06fc150bb6c5001a | 28.818182 | 83 | 0.575961 | false | false | false | false |
JGiola/swift | refs/heads/main | stdlib/public/core/SwiftNativeNSArray.swift | apache-2.0 | 9 | //===--- SwiftNativeNSArray.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
//
//===----------------------------------------------------------------------===//
//
// __ContiguousArrayStorageBase supplies the implementation of the
// _NSArrayCore API (and thus, NSArray the API) for our
// _ContiguousArrayStorage<T>. We can't put this implementation
// directly on _ContiguousArrayStorage because generic classes can't
// override Objective-C selectors.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
/// Returns `true` if the given `index` is valid as a position (`0
/// ≤ index ≤ count`); otherwise, returns `false`.
@usableFromInline @_transparent
internal func _isValidArrayIndex(_ index: Int, count: Int) -> Bool {
return (index >= 0) && (index <= count)
}
/// Returns `true` if the given `index` is valid for subscripting
/// (`0 ≤ index < count`); otherwise, returns `false`.
@usableFromInline @_transparent
internal func _isValidArraySubscript(_ index: Int, count: Int) -> Bool {
return (index >= 0) && (index < count)
}
/// An `NSArray` with Swift-native reference counting and contiguous
/// storage.
///
/// NOTE: older runtimes called this
/// _SwiftNativeNSArrayWithContiguousStorage. The two must coexist, so
/// it was renamed. The old name must not be used in the new runtime.
@_fixed_layout
@usableFromInline
internal class __SwiftNativeNSArrayWithContiguousStorage
: __SwiftNativeNSArray { // Provides NSArray inheritance and native refcounting
@inlinable
@nonobjc internal override init() { super.init() }
@inlinable
deinit {}
// Operate on our contiguous storage
internal func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
_internalInvariantFailure(
"Must override withUnsafeBufferOfObjects in derived classes")
}
}
private let NSNotFound: Int = .max
// Implement the APIs required by NSArray
extension __SwiftNativeNSArrayWithContiguousStorage {
@objc internal var count: Int {
return withUnsafeBufferOfObjects { $0.count }
}
@inline(__always)
@_effects(readonly)
@nonobjc private func _objectAt(_ index: Int) -> Unmanaged<AnyObject> {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArraySubscript(index, count: objects.count),
"Array index out of range")
return Unmanaged.passUnretained(objects[index])
}
}
@objc(objectAtIndexedSubscript:)
@_effects(readonly)
dynamic internal func objectAtSubscript(_ index: Int) -> Unmanaged<AnyObject> {
return _objectAt(index)
}
@objc(objectAtIndex:)
@_effects(readonly)
dynamic internal func objectAt(_ index: Int) -> Unmanaged<AnyObject> {
return _objectAt(index)
}
@objc internal func getObjects(
_ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange
) {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArrayIndex(range.location, count: objects.count),
"Array index out of range")
_precondition(
_isValidArrayIndex(
range.location + range.length, count: objects.count),
"Array index out of range")
if objects.isEmpty { return }
// These objects are "returned" at +0, so treat them as pointer values to
// avoid retains. Copy bytes via a raw pointer to circumvent reference
// counting while correctly aliasing with all other pointer types.
UnsafeMutableRawPointer(aBuffer).copyMemory(
from: objects.baseAddress! + range.location,
byteCount: range.length * MemoryLayout<AnyObject>.stride)
}
}
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
var enumerationState = state.pointee
if enumerationState.state != 0 {
return 0
}
return withUnsafeBufferOfObjects {
objects in
enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr
enumerationState.itemsPtr =
AutoreleasingUnsafeMutablePointer(objects.baseAddress)
enumerationState.state = 1
state.pointee = enumerationState
return objects.count
}
}
@objc(copyWithZone:)
internal func copy(with _: _SwiftNSZone?) -> AnyObject {
return self
}
}
@_fixed_layout
@usableFromInline
@objc internal final class _SwiftNSMutableArray :
_SwiftNativeNSMutableArray
{
internal var contents: [AnyObject]
internal init(_ array: [AnyObject]) {
contents = array
super.init()
}
@objc internal var count: Int {
return contents.count
}
@objc(objectAtIndexedSubscript:)
@_effects(readonly)
dynamic internal func objectAtSubscript(_ index: Int) -> Unmanaged<AnyObject> {
//TODO: exception instead of precondition, once that's possible
return Unmanaged.passUnretained(contents[index])
}
@objc(objectAtIndex:)
@_effects(readonly)
dynamic internal func objectAt(_ index: Int) -> Unmanaged<AnyObject> {
//TODO: exception instead of precondition, once that's possible
return Unmanaged.passUnretained(contents[index])
}
@objc internal func getObjects(
_ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange
) {
return contents.withContiguousStorageIfAvailable { objects in
//TODO: exceptions instead of preconditions, once that's possible
_precondition(
_isValidArrayIndex(range.location, count: objects.count),
"Array index out of range")
_precondition(
_isValidArrayIndex(
range.location + range.length, count: objects.count),
"Array index out of range")
if objects.isEmpty { return }
// These objects are "returned" at +0, so treat them as pointer values to
// avoid retains. Copy bytes via a raw pointer to circumvent reference
// counting while correctly aliasing with all other pointer types.
UnsafeMutableRawPointer(aBuffer).copyMemory(
from: objects.baseAddress! + range.location,
byteCount: range.length * MemoryLayout<AnyObject>.stride)
}!
}
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
var enumerationState = state.pointee
if enumerationState.state != 0 {
return 0
}
return contents.withContiguousStorageIfAvailable {
objects in
enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr
enumerationState.itemsPtr =
AutoreleasingUnsafeMutablePointer(objects.baseAddress)
enumerationState.state = 1
state.pointee = enumerationState
return objects.count
}!
}
@objc(copyWithZone:)
dynamic internal func copy(with _: _SwiftNSZone?) -> AnyObject {
return contents._bridgeToObjectiveCImpl()
}
@objc(insertObject:atIndex:)
dynamic internal func insert(_ anObject: AnyObject, at index: Int) {
contents.insert(anObject, at: index)
}
@objc(removeObjectAtIndex:)
dynamic internal func removeObject(at index: Int) {
contents.remove(at: index)
}
@objc(addObject:)
dynamic internal func add(_ anObject: AnyObject) {
contents.append(anObject)
}
@objc(removeLastObject)
dynamic internal func removeLastObject() {
if !contents.isEmpty {
contents.removeLast()
}
}
@objc(replaceObjectAtIndex:withObject:)
dynamic internal func replaceObject(at index: Int, with anObject: AnyObject) {
//enforces bounds, unlike set equivalent, which can append
contents[index] = anObject
}
//Non-core methods overridden for performance
@objc(exchangeObjectAtIndex:withObjectAtIndex:)
dynamic internal func exchange(at index: Int, with index2: Int) {
contents.swapAt(index, index2)
}
@objc(replaceObjectsInRange:withObjects:count:)
dynamic internal func replaceObjects(in range: _SwiftNSRange,
with objects: UnsafePointer<AnyObject>,
count: Int) {
let range = range.location ..< range.location + range.length
let buf = UnsafeBufferPointer(start: objects, count: count)
if range == contents.startIndex..<contents.endIndex {
contents = Array(buf)
} else {
// We make an Array here to make sure that something is holding onto the
// objects in `buf`, since replaceSubrange could release them
contents.replaceSubrange(range, with: Array(buf))
}
}
@objc(insertObjects:count:atIndex:)
dynamic internal func insertObjects(_ objects: UnsafePointer<AnyObject>,
count: Int,
at index: Int) {
let buf = UnsafeBufferPointer(start: objects, count: count)
contents.insert(contentsOf: buf, at: index)
}
@objc(indexOfObjectIdenticalTo:)
dynamic internal func index(ofObjectIdenticalTo object: AnyObject) -> Int {
return contents.firstIndex { $0 === object } ?? NSNotFound
}
@objc(removeObjectsInRange:)
dynamic internal func removeObjects(in range: _SwiftNSRange) {
let range = range.location ..< range.location + range.length
contents.replaceSubrange(range, with: [])
}
@objc(removeAllObjects)
dynamic internal func removeAllObjects() {
contents = []
}
@objc(setObject:atIndex:)
dynamic internal func setObject(_ anObject: AnyObject, at index: Int) {
if index == contents.count {
contents.append(anObject)
} else {
contents[index] = anObject
}
}
@objc(setObject:atIndexedSubscript:) dynamic
internal func setObjectSubscript(_ anObject: AnyObject, at index: Int) {
if index == contents.count {
contents.append(anObject)
} else {
contents[index] = anObject
}
}
}
/// An `NSArray` whose contiguous storage is created and filled, upon
/// first access, by bridging the elements of a Swift `Array`.
///
/// Ideally instances of this class would be allocated in-line in the
/// buffers used for Array storage.
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
@objc internal final class __SwiftDeferredNSArray
: __SwiftNativeNSArrayWithContiguousStorage {
// This stored property should be stored at offset zero. We perform atomic
// operations on it.
//
// Do not access this property directly.
@nonobjc
internal var _heapBufferBridged_DoNotUse: AnyObject?
// When this class is allocated inline, this property can become a
// computed one.
@usableFromInline
@nonobjc
internal let _nativeStorage: __ContiguousArrayStorageBase
@nonobjc
internal var _heapBufferBridgedPtr: UnsafeMutablePointer<AnyObject?> {
return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(
to: Optional<AnyObject>.self)
}
internal var _heapBufferBridged: __BridgingBufferStorage? {
if let ref =
_stdlib_atomicLoadARCRef(object: _heapBufferBridgedPtr) {
return unsafeBitCast(ref, to: __BridgingBufferStorage.self)
}
return nil
}
@inlinable // FIXME(sil-serialize-all)
@nonobjc
internal init(_nativeStorage: __ContiguousArrayStorageBase) {
self._nativeStorage = _nativeStorage
}
internal func _destroyBridgedStorage(_ hb: __BridgingBufferStorage?) {
if let bridgedStorage = hb {
let buffer = _BridgingBuffer(bridgedStorage)
let count = buffer.count
buffer.baseAddress.deinitialize(count: count)
}
}
deinit {
_destroyBridgedStorage(_heapBufferBridged)
}
internal override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
while true {
var buffer: UnsafeBufferPointer<AnyObject>
// If we've already got a buffer of bridged objects, just use it
if let bridgedStorage = _heapBufferBridged {
let bridgingBuffer = _BridgingBuffer(bridgedStorage)
buffer = UnsafeBufferPointer(
start: bridgingBuffer.baseAddress, count: bridgingBuffer.count)
}
// If elements are bridged verbatim, the native buffer is all we
// need, so return that.
else if let buf = _nativeStorage._withVerbatimBridgedUnsafeBuffer(
{ $0 }
) {
buffer = buf
}
else {
// Create buffer of bridged objects.
let objects = _nativeStorage._getNonVerbatimBridgingBuffer()
// Atomically store a reference to that buffer in self.
if !_stdlib_atomicInitializeARCRef(
object: _heapBufferBridgedPtr, desired: objects.storage!) {
// Another thread won the race. Throw out our buffer.
_destroyBridgedStorage(
unsafeDowncast(objects.storage!, to: __BridgingBufferStorage.self))
}
continue // Try again
}
defer { _fixLifetime(self) }
return try body(buffer)
}
}
/// Returns the number of elements in the array.
///
/// This override allows the count to be read without triggering
/// bridging of array elements.
@objc
internal override var count: Int {
return _nativeStorage.countAndCapacity.count
}
}
#else
// Empty shim version for non-objc platforms.
@usableFromInline
@_fixed_layout
internal class __SwiftNativeNSArrayWithContiguousStorage {
@inlinable
internal init() {}
@inlinable
deinit {}
}
#endif
/// Base class of the heap buffer backing arrays.
///
/// NOTE: older runtimes called this _ContiguousArrayStorageBase. The
/// two must coexist, so it was renamed. The old name must not be used
/// in the new runtime.
@usableFromInline
@_fixed_layout
internal class __ContiguousArrayStorageBase
: __SwiftNativeNSArrayWithContiguousStorage {
@usableFromInline
final var countAndCapacity: _ArrayBody
@inlinable
@nonobjc
internal init(_doNotCallMeBase: ()) {
_internalInvariantFailure("creating instance of __ContiguousArrayStorageBase")
}
#if _runtime(_ObjC)
internal override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
if let result = try _withVerbatimBridgedUnsafeBuffer(body) {
return result
}
_internalInvariantFailure(
"Can't use a buffer of non-verbatim-bridged elements as an NSArray")
}
/// If the stored type is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
internal func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
_internalInvariantFailure(
"Concrete subclasses must implement _withVerbatimBridgedUnsafeBuffer")
}
internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer {
_internalInvariantFailure(
"Concrete subclasses must implement _getNonVerbatimBridgingBuffer")
}
@objc(mutableCopyWithZone:)
dynamic internal func mutableCopy(with _: _SwiftNSZone?) -> AnyObject {
let arr = Array<AnyObject>(_ContiguousArrayBuffer(self))
return _SwiftNSMutableArray(arr)
}
@objc(indexOfObjectIdenticalTo:)
dynamic internal func index(ofObjectIdenticalTo object: AnyObject) -> Int {
let arr = Array<AnyObject>(_ContiguousArrayBuffer(self))
return arr.firstIndex { $0 === object } ?? NSNotFound
}
#endif
@inlinable
internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
_internalInvariantFailure(
"Concrete subclasses must implement canStoreElements(ofDynamicType:)")
}
/// A type that every element in the array is.
@inlinable
internal var staticElementType: Any.Type {
_internalInvariantFailure(
"Concrete subclasses must implement staticElementType")
}
@inlinable
deinit {
_internalInvariant(
self !== _emptyArrayStorage, "Deallocating empty array storage?!")
}
}
| 2ed69ac1d0e73c7c7e62319894597244 | 30.658301 | 82 | 0.689066 | false | false | false | false |
Ahyufei/DouYuTV | refs/heads/master | DYTV/DYTV/Classes/Home/Controller/FunnyViewController.swift | mit | 1 | //
// FunnyViewController.swift
// DYTV
//
// Created by Yufei on 2017/1/17.
// Copyright © 2017年 张玉飞. All rights reserved.
//
import UIKit
class FunnyViewController: BaseAnchorViewController {
fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel()
}
extension FunnyViewController {
override func setupUI() {
super.setupUI()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize.zero
collectionView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0)
}
}
extension FunnyViewController {
override func loadData() {
// 给父类中的baseVM赋值
baseVM = funnyVM
// 请求数据
funnyVM.loadFunnyData {
self.collectionView.reloadData()
// 3.数据请求完成
self.loadDataFinished()
}
}
}
| d4bff5c6e1d73b75553399286fc80015 | 19.531915 | 88 | 0.595855 | false | false | false | false |
dbahat/conventions-ios | refs/heads/sff | Conventions/Conventions/model/EventType.swift | apache-2.0 | 1 | //
// EventType.swift
// Conventions
//
// Created by David Bahat on 2/1/16.
// Copyright © 2016 Amai. All rights reserved.
//
import Foundation
import UIKit
class EventType {
var backgroundColor: UIColor?
var description: String
var presentation: Presentation
init(backgroundColor: UIColor?, description: String, presentation: Presentation) {
self.backgroundColor = backgroundColor
self.description = description
self.presentation = presentation
}
class Presentation {
var mode: PredentationMode
var location: PredentationLocation
init(mode: PredentationMode, location: PredentationLocation) {
self.mode = mode
self.location = location
}
// To seperate projected hybrid events from events that were designed for virtual audience
func designedAsVirtual() -> Bool {
return mode == .Virtual || (mode == .Hybrid && location == .Virtual)
}
}
enum PredentationMode: String {
case Physical, Virtual, Hybrid
}
enum PredentationLocation: String {
case Indoors, Virtual
}
}
| 77db181fbe8a2a2920b65cb9c043bb01 | 25.818182 | 98 | 0.633898 | false | false | false | false |
society2012/PGDBK | refs/heads/master | PGDBK/Pods/DrawerController/DrawerController/DrawerBarButtonItem.swift | mit | 1 | // Copyright (c) 2014 evolved.io (http://evolved.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Foundation
open class DrawerBarButtonItem: UIBarButtonItem {
var menuButton: AnimatedMenuButton
// MARK: - Initializers
public override init() {
self.menuButton = AnimatedMenuButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
super.init()
self.customView = self.menuButton
}
public convenience init(target: AnyObject?, action: Selector) {
self.init(target: target, action: action, menuIconColor: UIColor.gray)
}
public convenience init(target: AnyObject?, action: Selector, menuIconColor: UIColor) {
let menuButton = AnimatedMenuButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30), strokeColor: menuIconColor)
menuButton.addTarget(target, action: action, for: UIControlEvents.touchUpInside)
self.init(customView: menuButton)
self.menuButton = menuButton
}
public required init?(coder aDecoder: NSCoder) {
self.menuButton = AnimatedMenuButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
super.init(coder: aDecoder)
self.customView = self.menuButton
}
// MARK: - Animations
open func animate(withPercentVisible percentVisible: CGFloat, drawerSide: DrawerSide) {
if let btn = self.customView as? AnimatedMenuButton {
btn.animate(withPercentVisible: percentVisible, drawerSide: drawerSide)
}
}
}
| 26fdeb77604da194e696e5a77ab323b1 | 41.081967 | 121 | 0.708609 | false | false | false | false |
qzephyrmor/antavo-sdk-swift | refs/heads/master | AntavoLoyaltySDK/Classes/ANTReward.swift | mit | 1 | //
// Reward.swift
// AntavoSDK
//
// Copyright © 2017 Antavo Ltd. All rights reserved.
//
// MARK: Base Antavo Reward object.
open class ANTReward {
/**
Reward's unique identifier specified as string.
*/
open var id: String?
/**
Reward's name specified as string or array of strings.
*/
open var name: Any?
/**
Reward's description specified as string or array of strings.
*/
open var description: Any?
/**
Reward's category specified as string.
*/
open var category: String?
/**
Reward's price specified as integer or array of integers.
*/
open var price: Any?
/**
Creates a new instance of Reward, and assigns the given properties to it.
- Parameter data: Properties to assign as NSDictionary object.
*/
open func assign(data: NSDictionary) -> ANTReward {
let reward = ANTReward()
if let id = data.object(forKey: "id") {
reward.id = id as? String
}
if let name = data.object(forKey: "name") {
reward.name = name
}
if let description = data.object(forKey: "description") {
reward.description = description
}
if let category = data.object(forKey: "category") {
reward.category = category as? String
}
if let price = data.object(forKey: "price") {
reward.price = price
}
return reward
}
}
| 64f96f78e46edfe08b42b8949df7ebf0 | 22.8 | 78 | 0.55139 | false | false | false | false |
Vostro162/VaporTelegram | refs/heads/master | Sources/App/PhotoSize+Extensions.swift | mit | 1 | //
// PhotoSize+Extensions.swift
// VaporTelegram
//
// Created by Marius Hartig on 11.05.17.
//
//
import Foundation
import Vapor
// MARK: - JSON
extension PhotoSize: JSONInitializable {
public init(json: JSON) throws {
guard
let fileId = json["file_id"]?.string,
let width = json["width"]?.int,
let height = json["height"]?.int
else { throw VaporTelegramError.parsing }
self.fileId = fileId
self.width = width
self.height = height
/*
*
* Optionals
*
*/
if let fileSize = json["file_size"]?.int {
self.fileSize = fileSize
} else {
self.fileSize = nil
}
}
public static func create(arrayJSON: JSON) throws -> [PhotoSize] {
guard
let photosArray = arrayJSON.node.nodeArray
else { throw VaporTelegramError.parsing }
var photos = [PhotoSize]()
for photo in photosArray {
guard let json = try? JSON(node: photo), let photo = try? PhotoSize(json: json) else { continue }
photos.append(photo)
}
return photos
}
public static func create(arrayOfArrayJSON: JSON) throws -> [[PhotoSize]] {
guard
let photoArrays = arrayOfArrayJSON.node.nodeArray
else { throw VaporTelegramError.parsing }
var photos = [[PhotoSize]]()
for photoArray in photoArrays {
guard let photoArray = photoArray.node.nodeArray else { continue }
var photoSizes = [PhotoSize]()
for photo in photoArray {
guard let json = try? JSON(node: photo), let photoSize = try? PhotoSize(json: json) else { continue }
photoSizes.append(photoSize)
}
photos.append(photoSizes)
}
return photos
}
}
| 088b9d438e00da05aa53abc32aa21a6b | 25.285714 | 117 | 0.522727 | false | false | false | false |
AlexeyTyurenkov/NBUStats | refs/heads/develop | NBUStatProject/NBUStat/Modules/InterbankRatesModule/InterbankRatesModuleBuilder.swift | mit | 1 | //
// InterbankRatesModuleBuilder.swift
// FinStat Ukraine
//
// Created by Aleksey Tyurenkov on 2/20/18.
// Copyright © 2018 Oleksii Tiurenkov. All rights reserved.
//
import Foundation
import UIKit
class InterbankRatesModuleBuilder: ModuleBuilderProtocol
{
func viewController() -> UIViewController {
let storyBoard = UIStoryboard(name: "CurrencyRates", bundle: nil)
let initialController = storyBoard.instantiateInitialViewController()
if let navigationController = initialController as? UINavigationController
{
if let controller = navigationController.topViewController as? CurrencyViewController
{
controller.presenter = InterbankRatesManager(date: Date())
}
}
return initialController ?? UIViewController()
}
var moduleName: String
{
return NSLocalizedString("Курси міжбанку", comment: "")
}
}
| fc8d2a9a1baeedfda927f4528dbcf61a | 27.818182 | 97 | 0.675079 | false | false | false | false |
alskipp/Monoid | refs/heads/master | MonoidTests/ProductMonoidTests.swift | mit | 1 | // Copyright © 2016 Al Skipp. All rights reserved.
import XCTest
import Monoid
class ProductMonoidTests: XCTestCase {
func testMempty() {
XCTAssertTrue(Product<Int>.mempty.value == 1)
XCTAssertTrue(Product<Double>.mempty.value == 1)
XCTAssertTrue(Product<Int8>.mempty.value == 1)
}
func testMappend() {
XCTAssertTrue(Product<Int>(2) <> Product(2) <> Product(2) == Product(8))
XCTAssertTrue(Product<Int>(0) <> Product(5) <> Product(0) == Product(0))
XCTAssertTrue(Product<Int>(1) <> Product(5) <> Product.mempty == Product(5))
XCTAssertTrue(Product<Int>(0) <> Product(0) <> Product(0) < Product(1))
XCTAssertTrue(Product<Int>(1) <> Product(1) <> Product(1) == Product.mempty)
}
func testMconcat() {
XCTAssertTrue(.mconcat([Product<Int>(2), Product(2), Product(2)]) == Product(8))
XCTAssertTrue(.mconcat([Product<Int>(5), Product(17), Product(0)]) == Product(0))
XCTAssertTrue(.mconcat([Product<Int>(1), Product(1), Product(3)]) == Product(3))
XCTAssertTrue(.mconcat([Product<Int>(1), Product(1), Product(1)]) == Product.mempty)
}
func testDescription() {
XCTAssertTrue(Product(1).description == "Product(1)")
}
}
| 92090ad1b0ed7a16794249f8df3eb090 | 35 | 88 | 0.658249 | false | true | false | false |
JGiola/swift | refs/heads/main | test/Incremental/Verifier/single-file-private/AnyObject.swift | apache-2.0 | 5 | // UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// UNSUPPORTED: CPU=armv7k && OS=ios
// Exclude iOS-based 32-bit platforms because the Foundation overlays introduce
// an extra dependency on _KeyValueCodingAndObservingPublishing only for 64-bit
// platforms.
// REQUIRES: objc_interop
// RUN: %empty-directory(%t)
// RUN: cd %t && %target-swift-frontend(mock-sdk: %clang-importer-sdk) -c -module-name main -verify-incremental-dependencies -primary-file %s -o /dev/null
import Foundation
// expected-provides {{LookupFactory}}
// expected-provides {{NSObject}}
// expected-provides {{Selector}}
// expected-provides {{Bool}}
// expected-provides {{ObjCBool}}
// expected-provides {{==}}
// expected-provides {{Equatable}}
// expected-provides {{Hasher}}
// expected-provides {{_ObjectiveCBridgeable}}
// expected-provides{{Hashable}}
// expected-member {{ObjectiveC.NSObject.NSObject}}
// expected-superclass {{ObjectiveC.NSObject}}
// expected-conformance {{ObjectiveC.NSObjectProtocol}}
// expected-member {{ObjectiveC.NSObjectProtocol.NSObject}}
// expected-member {{ObjectiveC.NSObject.Bool}}
// expected-conformance {{Swift.Hashable}}
// expected-conformance {{Swift.Equatable}}
// expected-member {{Swift._ExpressibleByBuiltinIntegerLiteral.init}}
@objc private class LookupFactory: NSObject {
// expected-provides {{AssignmentPrecedence}}
// expected-provides {{IntegerLiteralType}}
// expected-provides {{FloatLiteralType}}
// expected-provides {{Int}}
// expected-member {{ObjectiveC.NSObject.someMember}}
// expected-member {{ObjectiveC.NSObject.Int}}
// expected-member {{ObjectiveC.NSObjectProtocol.someMember}}
// expected-member {{ObjectiveC.NSObjectProtocol.Int}}
// expected-member {{main.LookupFactory.Int}}
@objc var someMember: Int = 0
// expected-member {{ObjectiveC.NSObject.someMethod}}
// expected-member {{ObjectiveC.NSObjectProtocol.someMethod}}
@objc func someMethod() {}
// expected-member {{ObjectiveC.NSObject.init}}
// expected-member {{ObjectiveC.NSObject.deinit}}
// expected-member {{ObjectiveC.NSObjectProtocol.init}}
// expected-member {{ObjectiveC.NSObjectProtocol.deinit}}
// expected-member {{main.LookupFactory.init}}
// expected-member {{main.LookupFactory.deinit}}
// expected-member {{main.LookupFactory.someMember}}
// expected-member {{main.LookupFactory.someMethod}}
}
// expected-member {{Swift.ExpressibleByNilLiteral.callAsFunction}}
// expected-member {{Swift.CustomReflectable.callAsFunction}}
// expected-member {{Swift._ObjectiveCBridgeable.callAsFunction}}
// expected-member {{Swift.Optional<Wrapped>.callAsFunction}}
// expected-member {{Swift.CustomDebugStringConvertible.callAsFunction}}
// expected-member {{Swift.Equatable.callAsFunction}}
// expected-member {{Swift.Hashable.callAsFunction}}
// expected-member {{Swift.Encodable.callAsFunction}}
// expected-member {{Swift.Decodable.callAsFunction}}
// expected-member {{Swift.Hashable._rawHashValue}}
// expected-member {{ObjectiveC.NSObject.hash}}
// expected-member {{Swift.Equatable.hashValue}}
// expected-member{{Swift.Hashable.hashValue}}
// expected-member{{Swift.Hashable.hash}}
// expected-member{{ObjectiveC.NSObjectProtocol.==}}
// expected-member {{ObjectiveC.NSObjectProtocol.hashValue}}
// expected-member {{ObjectiveC.NSObjectProtocol.Hasher}}
// expected-member {{Swift.Equatable._rawHashValue}}
// expected-member {{ObjectiveC.NSObject.hashValue}}
// expected-member {{ObjectiveC.NSObjectProtocol.Bool}}
// expected-member {{ObjectiveC.NSObject.==}}
// expected-member {{Swift.Equatable.==}}
// expected-member {{ObjectiveC.NSObject.Hasher}}
// expected-member {{ObjectiveC.NSObjectProtocol.hash}}
// expected-member {{Swift.Hashable.init}}
// expected-member {{Swift.Hashable.deinit}}
// expected-member {{Swift.Equatable.init}}
// expected-member {{Swift.Equatable.deinit}}
// expected-member {{Swift.Hashable.==}}
// expected-member {{Swift.Equatable.hash}}
// expected-member {{ObjectiveC.NSObject._rawHashValue}}
// expected-member {{ObjectiveC.NSObjectProtocol._rawHashValue}}
// expected-provides {{AnyObject}}
func lookupOnAnyObject(object: AnyObject) { // expected-provides {{lookupOnAnyObject}}
_ = object.someMember // expected-dynamic-member {{someMember}}
object.someMethod() // expected-dynamic-member {{someMethod}}
}
// expected-member {{Swift.Hashable.someMethod}}
// expected-member {{Swift.Equatable.someMethod}}
// expected-member {{Swift.Equatable.someMember}}
// expected-member {{Swift.Hashable.someMember}}
// expected-member {{Swift.Sendable.callAsFunction}}
// expected-member {{ObjectiveC.NSObject.someMethodWithDeprecatedOptions}}
// expected-member {{ObjectiveC.NSObject.someMethodWithPotentiallyUnavailableOptions}}
// expected-member {{ObjectiveC.NSObject.someMethodWithUnavailableOptions}}
// expected-member {{ObjectiveC.NSObjectProtocol.someMethodWithUnavailableOptions}}
// expected-member {{ObjectiveC.NSObjectProtocol.someMethodWithPotentiallyUnavailableOptions}}
// expected-member {{ObjectiveC.NSObjectProtocol.someMethodWithDeprecatedOptions}}
| bafb182e13eca814e194893834e3d252 | 45.609091 | 154 | 0.759508 | false | false | false | false |
loganSims/wsdot-ios-app | refs/heads/master | wsdot/NewsViewController.swift | gpl-3.0 | 1 | //
// NewsViewController.swift
// WSDOT
//
// Copyright (c) 2016 Washington State Department of Transportation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
import Foundation
import UIKit
import SafariServices
class NewsViewController: RefreshViewController, UITableViewDelegate, UITableViewDataSource {
let cellIdentifier = "NewsCell"
var newsItems = [NewsItem]()
let refreshControl = UIRefreshControl()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = "WSDOT News"
tableView.rowHeight = UITableView.automaticDimension
// refresh controller
refreshControl.addTarget(self, action: #selector(NewsViewController.refreshAction(_:)), for: .valueChanged)
tableView.addSubview(refreshControl)
showOverlay(self.view)
refresh()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
MyAnalytics.screenView(screenName: "News")
}
@objc func refreshAction(_ sender: UIRefreshControl){
refresh()
}
func refresh() {
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { [weak self] in
NewsStore.getNews({ data, error in
if let validData = data {
DispatchQueue.main.async { [weak self] in
if let selfValue = self{
selfValue.newsItems = validData
selfValue.tableView.reloadData()
selfValue.hideOverlayView()
selfValue.refreshControl.endRefreshing()
}
}
} else {
DispatchQueue.main.async { [weak self] in
if let selfValue = self{
selfValue.refreshControl.endRefreshing()
selfValue.hideOverlayView()
AlertMessages.getConnectionAlert(backupURL: "https", message: WSDOTErrorStrings.posts)
}
}
}
})
}
}
// MARK: Table View Data Source Methods
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newsItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! NewsCell
cell.titleLabel.text = newsItems[indexPath.row].title
cell.publishedLabel.text = TimeUtils.formatTime(newsItems[indexPath.row].published, format: "MMMM dd, YYYY h:mm a")
return cell
}
// MARK: Table View Delegate Methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = true
let svc = SFSafariViewController(url: URL(string: newsItems[indexPath.row].link)!, configuration: config)
if #available(iOS 10.0, *) {
svc.preferredControlTintColor = ThemeManager.currentTheme().secondaryColor
svc.preferredBarTintColor = ThemeManager.currentTheme().mainColor
} else {
svc.view.tintColor = ThemeManager.currentTheme().mainColor
}
self.present(svc, animated: true, completion: nil)
}
}
| 93cb28d39be8f2c54dfbd4cf28428d9f | 36.608333 | 123 | 0.621759 | false | false | false | false |
ruiying123/YRPageView | refs/heads/master | YRPageView/Sources/YRPageViewCell.swift | mit | 1 | //
// YRPageViewCell.swift
// YRPageView
//
// Created by kilrae on 2017/4/12.
// Copyright © 2017年 yang. All rights reserved.
//
import UIKit
open class YRPageViewCell: UICollectionViewCell {
/// Returns the label used for the main textual content of the pager view cell.
open var textLabel: UILabel? {
if let _ = _textLabel {
return _textLabel
}
let view = UIView(frame: .zero)
view.isUserInteractionEnabled = false
view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
let textLabel = UILabel(frame: .zero)
textLabel.textColor = .white
textLabel.font = UIFont.preferredFont(forTextStyle: .body)
self.contentView.addSubview(view)
view.addSubview(textLabel)
textLabel.addObserver(self, forKeyPath: "font", options: [.old,.new], context: kvoContext)
_textLabel = textLabel
return textLabel
}
/// Returns the image view of the pager view cell. Default is nil.
open var imageView: UIImageView? {
if let _ = _imageView {
return _imageView
}
let imageView = UIImageView(frame: .zero)
self.contentView.addSubview(imageView)
_imageView = imageView
return imageView
}
fileprivate weak var _textLabel: UILabel?
fileprivate weak var _imageView: UIImageView?
fileprivate let kvoContext = UnsafeMutableRawPointer(bitPattern: 0)
fileprivate let selectionColor = UIColor(white: 0.2, alpha: 0.2)
fileprivate weak var _selectedForegroundView: UIView?
fileprivate var selectedForegroundView: UIView? {
if let _ = _selectedForegroundView {
return _selectedForegroundView
}
let view = UIView(frame: self.contentView.bounds)
self.contentView.addSubview(view)
_selectedForegroundView = view
return view
}
open override var isHighlighted: Bool {
set {
super.isHighlighted = newValue
if newValue {
self.selectedForegroundView?.layer.backgroundColor = self.selectionColor.cgColor
} else if !super.isSelected {
self.selectedForegroundView?.layer.backgroundColor = UIColor.clear.cgColor
}
}
get {
return super.isHighlighted
}
}
open override var isSelected: Bool {
set {
super.isSelected = newValue
self.selectedForegroundView?.layer.backgroundColor = newValue ? self.selectionColor.cgColor : UIColor.clear.cgColor
}
get {
return super.isSelected
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
self.contentView.backgroundColor = UIColor.clear
self.backgroundColor = UIColor.clear
self.contentView.layer.shadowColor = UIColor.black.cgColor
self.contentView.layer.shadowRadius = 5
self.contentView.layer.shadowOpacity = 0.75
self.contentView.layer.shadowOffset = .zero
}
deinit {
if let textLabel = _textLabel {
textLabel.removeObserver(self, forKeyPath: "font", context: kvoContext)
}
}
override open func layoutSubviews() {
super.layoutSubviews()
if let imageView = _imageView {
imageView.frame = self.contentView.bounds
}
if let textLabel = _textLabel {
textLabel.superview!.frame = {
var rect = self.contentView.bounds
let height = textLabel.font.pointSize*1.5
rect.size.height = height
rect.origin.y = self.contentView.frame.height-height
return rect
}()
textLabel.frame = {
var rect = textLabel.superview!.bounds
rect = rect.insetBy(dx: 8, dy: 0)
rect.size.height -= 1
rect.origin.y += 1
return rect
}()
}
if let selectedForegroundView = _selectedForegroundView {
selectedForegroundView.frame = self.contentView.bounds
}
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == kvoContext {
if keyPath == "font" {
self.setNeedsLayout()
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
| 4f4a16006cacd16f0b1d78500fb6b31e | 31.540541 | 156 | 0.596346 | false | false | false | false |
Daltron/Spartan | refs/heads/master | Spartan/Classes/PagingObject.swift | mit | 1 | /*
The MIT License (MIT)
Copyright (c) 2017 Dalton Hinterscher
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 Alamofire
import ObjectMapper
public class PagingObject<T: Paginatable> : Mappable {
public private(set) var href: String!
public private(set) var items: [T]!
public private(set) var limit: Int!
public private(set) var next: String?
public private(set) var offset: Int!
public private(set) var previous: String?
public private(set) var total: Int!
public private(set) var cursors: CursorsObject?
public var canMakeNextRequest: Bool {
return next != nil
}
public var canMakePreviousRequest: Bool {
return previous != nil
}
public required init?(map: Map) {
mapping(map: map)
}
public func mapping(map: Map) {
href <- map["href"]
items <- map["items"]
limit <- map["limit"]
next <- map["next"]
offset <- map["offset"]
previous <- map["previous"]
total <- map["total"]
cursors <- map["cursors"]
}
@discardableResult
public func getNext(success: @escaping ((PagingObject<T>) -> Void), failure: ((SpartanError) -> Void)?) -> Request? {
guard let next = next else {
let error = SpartanError(errorType: .other,
errorMessage: "PagingObject does not have a next URL")
failure?(error)
return nil
}
let url = SpartanURL(url: next, isRelative: false)
return SpartanRequestManager.default.mapObject(.get, url: url, success: success, failure: failure)
}
@discardableResult
public func getPrevious(success: @escaping ((PagingObject<T>) -> Void), failure: ((SpartanError) -> Void)?) -> Request? {
guard let previous = previous else {
let error = SpartanError(errorType: .other,
errorMessage: "PagingObject does not have a previous URL")
failure?(error)
return nil
}
let url = SpartanURL(url: previous, isRelative: false)
return SpartanRequestManager.default.mapObject(.get, url: url, success: success, failure: failure)
}
}
| 3a2d7b91b27d92a260b192bcc2e9b6a8 | 38.926829 | 147 | 0.653024 | false | false | false | false |
WalterCreazyBear/Swifter30 | refs/heads/master | SectionDemo/SectionDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// SectionDemo
//
// Created by 熊伟 on 2017/6/27.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController {
var dataSource :NSArray = NSArray()
let cellId = "edfa"
lazy var tableView : UITableView = {
let tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.cellId)
tableView.backgroundColor = UIColor.white
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "Mine"
view.backgroundColor = UIColor.white
view.addSubview(self.tableView)
setupDataSource()
}
func setupDataSource() {
guard let url = Bundle.main.url(forResource: "section", withExtension: "json") else {
return
}
do {
let data = try Data(contentsOf: url)
guard let rootObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSArray else {
return
}
dataSource = rootObject
} catch {
return
}
}
}
extension ViewController:UITableViewDelegate,UITableViewDataSource
{
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (dataSource[section] as? NSArray)?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellId, for: indexPath)
if indexPath.section == 0
{
cell.imageView?.image = UIImage.init(named: ((dataSource[0] as? NSArray)![0] as! NSDictionary).object(forKey: "image") as! String)
}
return cell
}
}
| d569fc1233e7982252520a45a52553f4 | 28.066667 | 144 | 0.620183 | false | false | false | false |
kay-kim/stitch-examples | refs/heads/master | todo/ios/Pods/ExtendedJson/ExtendedJson/ExtendedJson/Source/ExtendedJson/BsonSymbol+ExtendedJson.swift | apache-2.0 | 1 | //
// BsonSymbol+ExtendedJson.swift
// ExtendedJson
//
// Created by Jason Flax on 10/6/17.
// Copyright © 2017 MongoDB. All rights reserved.
//
import Foundation
extension Symbol: ExtendedJsonRepresentable {
enum CodingKeys: String, CodingKey {
case symbol = "$symbol"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.init(try container.decode(String.self, forKey: CodingKeys.symbol))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.symbol, forKey: CodingKeys.symbol)
}
public static func fromExtendedJson(xjson: Any) throws -> ExtendedJsonRepresentable {
guard let json = xjson as? [String: Any],
let symbol = json[ExtendedJsonKeys.symbol.rawValue] as? String,
json.count == 1 else {
throw BsonError.parseValueFailure(value: xjson, attemptedType: Symbol.self)
}
return Symbol(symbol)
}
public var toExtendedJson: Any {
return [ExtendedJsonKeys.symbol.rawValue: self.symbol]
}
public func isEqual(toOther other: ExtendedJsonRepresentable) -> Bool {
return other is Symbol && (other as! Symbol).symbol == self.symbol
}
}
| b9a2c0df3ba48b198e78622ddbf732b3 | 30.534884 | 91 | 0.668879 | false | false | false | false |
djflsdl08/BasicIOS | refs/heads/master | Aaron Hillegass/Homepwner/Homepwner/ItemCell.swift | mit | 1 | //
// ItemCell.swift
// Homepwner
//
// Created by 김예진 on 2017. 10. 27..
// Copyright © 2017년 Kim,Yejin. All rights reserved.
//
import UIKit
class ItemCell: UITableViewCell {
// MARK: - Properties
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var serialNumberLabel: UILabel!
@IBOutlet weak var valueLabel: UILabel!
// MARK: - function
func updateLabels() {
let bodyFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
nameLabel.font = bodyFont
valueLabel.font = bodyFont
let caption1Font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption1)
serialNumberLabel.font = caption1Font
}
}
| d528dc03feb512d031b56b563115d69e | 24.25 | 87 | 0.66761 | false | false | false | false |
polymr/polymyr-api | refs/heads/master | Sources/App/Controllers/AuthenticationCollection.swift | mit | 1 | //
// AuthenticationController.swift
// polymr-api
//
// Created by Hakon Hanesand on 3/3/17.
//
//
import Vapor
import HTTP
import Fluent
import FluentProvider
import Routing
import Node
import JWT
import AuthProvider
import CTLS
import Crypto
enum SessionType: String, TypesafeOptionsParameter {
case customer
case maker
case anonymous
static let key = "type"
static let values = [SessionType.customer.rawValue, SessionType.maker.rawValue]
static var defaultValue: SessionType? = .none
var type: Authenticatable.Type {
switch self {
case .customer:
return Customer.self
case .maker:
return Maker.self
case .anonymous:
// TODO : figure this out
return Customer.self
}
}
}
final class ProviderData: NodeConvertible {
public let uid: String?
public let displayName: String
public let photoURL: String?
public let email: String
public let providerId: String?
init(node: Node) throws {
uid = try node.extract("uid")
displayName = try node.extract("displayName")
photoURL = try node.extract("photoURL")
email = try node.extract("email")
providerId = try node.extract("providerId")
}
func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"displayName" : .string(displayName),
"email" : .string(email),
]).add(objects: [
"uid" : uid,
"photoURL" : photoURL,
"providerId" : providerId
])
}
}
protocol JWTInitializable {
init(subject: String, request: Request) throws
}
extension RSASigner {
init(certificate: String) throws {
let certificateBytes = certificate.bytes
let cert_bio = BIO_new_mem_buf(certificateBytes, Int32(certificateBytes.count))
var _cert: UnsafeMutablePointer<X509>?
PEM_read_bio_X509(cert_bio, &_cert, nil, nil)
guard let cert = _cert else {
throw Abort.custom(status: .internalServerError, message: "Failed to decode certificate.")
}
guard let publicKey = X509_get_pubkey(cert) else {
throw Abort.custom(status: .internalServerError, message: "Failed to decode public key.")
}
guard let rsa = EVP_PKEY_get1_RSA(publicKey) else {
throw Abort.custom(status: .internalServerError, message: "Failed to get rsa key.")
}
self.init(key: .public(rsa))
}
}
final class AuthenticationCollection {
typealias AuthenticationSubject = Entity & Authenticatable & JWTInitializable & NodeConvertible & Persistable
var keys: [String : String] = [:]
func build(_ builder: RouteBuilder) {
builder.grouped(PasswordAuthenticationMiddleware(Maker.self)).post("login") { request in
guard let maker = request.auth.authenticated(Maker.self) else {
if drop.environment == .development {
throw Abort.custom(status: .badRequest, message: "Could not fetch authenticated user. \(request.storage.description)")
} else {
throw AuthenticationError.notAuthenticated
}
}
return try maker.makeResponse()
}
builder.post("authentication") { request in
guard
let token: String = try request.json?.extract("token"),
let subject: String = try request.json?.extract("subject")
else {
throw AuthenticationError.notAuthenticated
}
if drop.environment == .development && subject.hasPrefix("__testing__") {
guard let newSubject = subject.replacingOccurrences(of: "__testing__", with: "").int else {
throw AuthenticationError.notAuthenticated
}
let type: SessionType = try request.extract()
switch type {
case .customer:
if let customer = try Customer.find(newSubject) {
try request.auth.authenticate(customer, persist: true)
return try customer.makeResponse()
}
break
case .maker:
if let maker = try Maker.find(newSubject) {
try request.auth.authenticate(maker, persist: true)
return try maker.makeResponse()
}
break
case .anonymous:
throw Abort.custom(status: .badRequest, message: "Can not sign user up with anonymous session type.")
}
}
let jwt = try JWT(token: token)
let certificate = try self.fetchSigningKey(for: jwt.headers.extract("kid") as String)
let signer = try RS256(certificate: certificate)
// TODO : IssuedAtClaim should be in the past
let claims = [ExpirationTimeClaim(createTimestamp: { return Seconds(Date().timeIntervalSince1970) }, leeway: 60),
AudienceClaim(string: "polymyr-a5014"),
IssuerClaim(string: "https://securetoken.google.com/polymyr-a5014"),
SubjectClaim(string: subject)] as [Claim]
do {
try jwt.verifySignature(using: signer)
} catch {
throw Abort.custom(status: .internalServerError, message: "Failed to verify JWT token with error : \(error)")
}
if drop.environment != .development {
do {
try jwt.verifyClaims(claims)
} catch {
throw Abort.custom(status: .internalServerError, message: "Failed to verifiy claims with error \(error)")
}
}
return try self.authenticateUserFor(subject: subject, with: request, create: true).makeResponse()
}
}
func fetchSigningKey(for identifier: String) throws -> String {
if let key = keys[identifier] {
return key
}
let response = try drop.client.get("https://www.googleapis.com/robot/v1/metadata/x509/[email protected]")
guard let fetchedKeys = response.json?.object else {
throw Abort.custom(status: .internalServerError, message: "Could not get new signing keys.")
}
var newKeyLookup: [String : String] = [:]
try fetchedKeys.forEach {
guard let value = $1.string else {
throw NodeError.unableToConvert(input: $1.node, expectation: "\(String.self)", path: [$0])
}
newKeyLookup[$0] = value
}
keys = newKeyLookup
guard let key = newKeyLookup[identifier] else {
throw Abort.custom(status: .internalServerError, message: "\(identifier) key does not exist.")
}
return key
}
func authenticateUserFor(subject: String, with request: Request, create: Bool) throws -> AuthenticationSubject {
let type: SessionType = try request.extract()
switch type {
case .customer:
let customer = try getAuthenticationSubject(subject: subject, request: request, create: create) as Customer
try request.auth.authenticate(customer, persist: true)
return customer
case .maker:
let maker = try getAuthenticationSubject(subject: subject, request: request, create: create) as Maker
try request.auth.authenticate(maker, persist: true)
return maker
case .anonymous:
throw Abort.custom(status: .badRequest, message: "Can not sign user up with anonymous session type.")
}
}
func getAuthenticationSubject<T: AuthenticationSubject>(subject: String, request: Request? = nil, create new: Bool = true) throws -> T {
if let callee = try T.makeQuery().filter("sub_id", subject).first() {
return callee
}
if new {
guard let request = request else {
throw AuthenticationError.notAuthenticated
}
return try T.init(subject: subject, request: request)
} else {
throw AuthenticationError.notAuthenticated
}
}
}
| d4f517c3aa08a75ecb286b540759a8b5 | 33.191235 | 140 | 0.573526 | false | false | false | false |
jyliang/fibonacci | refs/heads/master | fibonacci/fibonacci/FirstViewController.swift | mit | 1 | //
// FirstViewController.swift
// fibonacci
//
// Created by Jason Liang on 11/4/14.
// Copyright (c) 2014 Jason Liang. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, ListViewModelDelegate {
let loadmoreThreshold : CGFloat = 100
var listVM = ListViewModel()
let cellHeight : CGFloat = 44
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
listVM.delegate = self
listVM.initSeedItems()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Data Source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.listVM.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as NumberTableViewCell
let item = self.listVM.items[indexPath.item]
cell.tag = indexPath.item
// item.populateCell(cell)
cell.loadItem(item)
return cell
}
//MARK: - Delegates
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = self.listVM.items[indexPath.item]
let value = Utility.getStringValue(item.valueList)
let alert = UIAlertView(title: "Value of fibonacci number #\(indexPath.item+1)", message: "\(value)", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if (scrollViewReachedThreshold(scrollView)) {
self.loadMore()
}
}
func loadMore() {
var insertionRows = Array<NSIndexPath>()
let count = 20
let base = self.listVM.items.count
for (var i = 0; i < count; i++) {
insertionRows.append(NSIndexPath(forItem: i+base, inSection: 0))
}
self.listVM.loadMoreItems(count)
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(insertionRows, withRowAnimation: UITableViewRowAnimation.None)
self.tableView.endUpdates()
}
func scrollViewReachedThreshold(scrollView : UIScrollView) -> Bool {
let threshold = (CGFloat(self.listVM.items.count) * self.cellHeight - CGRectGetHeight(scrollView.frame)-scrollView.contentOffset.y)
return threshold < loadmoreThreshold
}
//MARK: - ListViewModelDelegate
func updateCellAtIndex(index: Int) {
for (cellIndex, element) in enumerate(self.tableView.visibleCells()) {
if (element.tag == index) {
let item = self.listVM.items[index]
if (element.isKindOfClass(NumberTableViewCell)) {
let cell = element as NumberTableViewCell
cell.loadItem(item)
}
return
}
}
}
}
| 3d243e43545c38a20856ce1564883393 | 32.291667 | 149 | 0.652378 | false | false | false | false |
amraboelela/swift | refs/heads/master | test/SILGen/downcast_reabstraction.swift | apache-2.0 | 12 |
// RUN: %target-swift-emit-silgen -module-name downcast_reabstraction %s | %FileCheck %s
// CHECK-LABEL: sil hidden [ossa] @$s22downcast_reabstraction19condFunctionFromAnyyyypF
// CHECK: checked_cast_addr_br take_always Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed () -> @out (), [[YES:bb[0-9]+]], [[NO:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: [[ORIG_VAL:%.*]] = load [take] [[OUT]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @$sytIegr_Ieg_TR
// CHECK: [[SUBST_VAL:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[ORIG_VAL]])
func condFunctionFromAny(_ x: Any) {
if let f = x as? () -> () {
f()
}
}
// CHECK-LABEL: sil hidden [ossa] @$s22downcast_reabstraction21uncondFunctionFromAnyyyypF : $@convention(thin) (@in_guaranteed Any) -> () {
// CHECK: unconditional_checked_cast_addr Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed () -> @out ()
// CHECK: [[ORIG_VAL:%.*]] = load [take] [[OUT]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @$sytIegr_Ieg_TR
// CHECK: [[SUBST_VAL:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[ORIG_VAL]])
// CHECK: [[BORROW:%.*]] = begin_borrow [[SUBST_VAL]]
// CHECK: apply [[BORROW]]()
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value [[SUBST_VAL]]
func uncondFunctionFromAny(_ x: Any) {
(x as! () -> ())()
}
| ade7d51912882b8999d4dad79a84d648 | 50.571429 | 175 | 0.553324 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Healthcare | refs/heads/master | iOS/Healthcare/DataSources/FormsDataManager.swift | epl-1.0 | 1 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2014, 2015. All Rights Reserved.
*/
import UIKit
/**
Enum to report the state of the forms data retrival
*/
enum FormsResultType {
case Success
case Failure
}
/**
Data Manager is a wrapper to the database connection
*/
class FormsDataManager: NSObject, WLDataDelegate {
private(set) var forms : [Forms]!
typealias FormsCallback = (FormsResultType)->Void
var formsCallBack: FormsCallback!
//Class variable that will return a singleton when requested
class var formsDataManager : FormsDataManager{
struct Singleton {
static let instance = FormsDataManager()
}
return Singleton.instance
}
/**
Delgate method for WorkLight. Called when connection and return is successful
- parameter response: Response from WorkLight
*/
func onSuccess(response: WLResponse!) {
let responseJson = response.getResponseJson() as NSDictionary
print("---formsDataManager onSuccess")
print(response.responseText)
// on success, call utils method to format data
forms = Utils.getQuestionnaireForUser(responseJson)
formsCallBack(FormsResultType.Success)
}
/**
Delgate method for WorkLight. Called when connection or return is unsuccessful
- parameter response: Response from WorkLight
*/
func onFailure(response: WLFailResponse!) {
print("---formsDataManager onFailure")
print(response.responseText)
formsCallBack(FormsResultType.Failure)
}
/**
Delgate method for WorkLight. Task to do before executing a call.
*/
func onPreExecute() {
}
/**
Delgate method for WorkLight. Task to do after executing a call.
*/
func onPostExecute() {
}
/**
Method called to get exercises from the server
- parameter username: the username to get questions for
- parameter callback: callback for when we have a result
*/
func getQuestionnaireForUser(username: String!, callback: (FormsResultType)->()) {
formsCallBack = callback
let adapterName : String = "HealthcareAdapter"
let procedureName : String = "getQuestionnaireForUser"
let caller = WLProcedureCaller(adapterName : adapterName, procedureName: procedureName, dataDelegate: self)
let params : [String] = [username]
caller.invokeWithResponse(self, params: params)
}
} | 8b7546cc469e53df577258189bf359b6 | 27.3 | 115 | 0.663001 | false | false | false | false |
imryan/swifty-tinder | refs/heads/master | Example/Tests/Tests.swift | mit | 1 | // https://github.com/Quick/Quick
import Quick
import Nimble
import SwiftyTinder
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| 0a65cdf17544162de6ac33b63aa53708 | 22.46 | 63 | 0.364876 | false | false | false | false |
CD1212/Doughnut | refs/heads/master | Pods/GRDB.swift/GRDB/QueryInterface/SQLCollatedExpression.swift | gpl-3.0 | 1 | /// SQLCollatedExpression taints an expression so that every derived expression
/// is eventually evaluated using an SQLite collation.
///
/// You create one by calling the SQLSpecificExpressible.collating() method.
///
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
///
/// // SELECT * FROM players WHERE email = '[email protected]' COLLATE NOCASE
/// Players.filter(email == "[email protected]")
public struct SQLCollatedExpression {
/// The tainted expression
public let expression: SQLExpression
/// The name of the collation
public let collationName: Database.CollationName
/// Returns an ordering suitable for QueryInterfaceRequest.order()
///
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
///
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE ASC
/// Players.order(email.asc)
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var asc: SQLOrderingTerm {
return SQLOrdering.asc(sqlExpression)
}
/// Returns an ordering suitable for QueryInterfaceRequest.order()
///
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
///
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE DESC
/// Players.order(email.desc)
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var desc: SQLOrderingTerm {
return SQLOrdering.desc(sqlExpression)
}
init(_ expression: SQLExpression, collationName: Database.CollationName) {
self.expression = expression
self.collationName = collationName
}
var sqlExpression: SQLExpression {
return SQLExpressionCollate(expression, collationName: collationName)
}
}
extension SQLCollatedExpression : SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var reversed: SQLOrderingTerm {
return desc
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.orderingTermSQL(&arguments)
}
}
| 18bc956b448cb30df6cc0da808eb9c1b | 36.290323 | 93 | 0.676471 | false | false | false | false |
obrichak/discounts | refs/heads/master | discounts/Classes/BarCodeGenerator/RSEANGenerator.swift | gpl-3.0 | 1 | //
// RSEANGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
let RSBarcodesTypeISBN13Code = "com.pdq.rsbarcodes.isbn13"
let RSBarcodesTypeISSN13Code = "com.pdq.rsbarcodes.issn13"
// http://blog.sina.com.cn/s/blog_4015406e0100bsqk.html
class RSEANGenerator: RSAbstractCodeGenerator {
var length = 0
// 'O' for odd and 'E' for even
let lefthandParities = [
"OOOOOO",
"OOEOEE",
"OOEEOE",
"OOEEEO",
"OEOOEE",
"OEEOOE",
"OEEEOO",
"OEOEOE",
"OEOEEO",
"OEEOEO"
]
// 'R' for right-hand
let parityEncodingTable = [
["O" : "0001101", "E" : "0100111", "R" : "1110010"],
["O" : "0011001", "E" : "0110011", "R" : "1100110"],
["O" : "0010011", "E" : "0011011", "R" : "1101100"],
["O" : "0111101", "E" : "0100001", "R" : "1000010"],
["O" : "0100011", "E" : "0011101", "R" : "1011100"],
["O" : "0110001", "E" : "0111001", "R" : "1001110"],
["O" : "0101111", "E" : "0000101", "R" : "1010000"],
["O" : "0111011", "E" : "0010001", "R" : "1000100"],
["O" : "0110111", "E" : "0001001", "R" : "1001000"],
["O" : "0001011", "E" : "0010111", "R" : "1110100"]
]
init(length:Int) {
self.length = length
}
override func isValid(contents: String) -> Bool {
if super.isValid(contents) && self.length == contents.length() {
var sum_odd = 0
var sum_even = 0
for i in 0..<(self.length - 1) {
let digit = contents[i].toInt()!
if i % 2 == (self.length == 13 ? 0 : 1) {
sum_even += digit
} else {
sum_odd += digit
}
}
let checkDigit = (10 - (sum_even + sum_odd * 3) % 10) % 10
return contents[contents.length() - 1].toInt() == checkDigit
}
return false
}
override func initiator() -> String {
return "101"
}
override func terminator() -> String {
return "101"
}
func centerGuardPattern() -> String {
return "01010"
}
override func barcode(contents: String) -> String {
var lefthandParity = "OOOO"
var newContents = contents
if self.length == 13 {
lefthandParity = self.lefthandParities[contents[0].toInt()!]
newContents = contents.substring(1, length: contents.length() - 1)
}
var barcode = ""
for i in 0..<newContents.length() {
let digit = newContents[i].toInt()!
if i < lefthandParity.length() {
barcode += self.parityEncodingTable[digit][lefthandParity[i]]!
if i == lefthandParity.length() - 1 {
barcode += self.centerGuardPattern()
}
} else {
barcode += self.parityEncodingTable[digit]["R"]!
}
}
return barcode
}
}
class RSEAN8Generator: RSEANGenerator {
init() {
super.init(length: 8)
}
}
class RSEAN13Generator: RSEANGenerator {
init() {
super.init(length: 13)
}
}
class RSISBN13Generator: RSEAN13Generator {
override func isValid(contents: String) -> Bool {
// http://www.appsbarcode.com/ISBN.php
return super.isValid(contents) && contents.substring(0, length: 3) == "978"
}
}
class RSISSN13Generator: RSEAN13Generator {
override func isValid(contents: String) -> Bool {
// http://www.appsbarcode.com/ISSN.php
return super.isValid(contents) && contents.substring(0, length: 3) == "977"
}
} | 1f5ed9142d0d67923dc85674ae44e9b9 | 28.795276 | 83 | 0.513349 | false | false | false | false |
alphatroya/hhkl-ios | refs/heads/develop | HHKL/Classes/Modules/Match/MatchViewController.swift | mit | 1 | //
// Created by Alexey Korolev on 02.02.16.
// Copyright (c) 2016 Heads and Hands. All rights reserved.
//
import UIKit
import Localize_Swift
import SnapKit
import ATRSlideSelectorView
class MatchViewController: ParentViewController {
let viewModel: MatchViewModelProtocol
init(viewModel: MatchViewModelProtocol) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
let tableView = UITableView()
let matchHeaderView = MatchHeaderView()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "match-view-controller-title".localized()
view.backgroundColor = UIColor.whiteColor()
view.addSubview(tableView)
tableView.snp_makeConstraints {
$0.edges.equalTo(0)
}
tableView.dataSource = self
tableView.registerClass(MatchSectionResultViewCell.self, forCellReuseIdentifier: String(MatchSectionResultViewCell))
tableView.separatorStyle = .None
tableView.rowHeight = 44
tableView.tableHeaderView = matchHeaderView
matchHeaderView.snp_makeConstraints {
make in
make.width.equalTo(tableView)
make.height.equalTo(120)
}
matchHeaderView.setNeedsLayout()
matchHeaderView.layoutIfNeeded()
tableView.tableHeaderView = matchHeaderView
tableView.tableFooterView = UIView()
}
private var matchesResultArray = [(Int, Int)]()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
guard let match = viewModel.match else {
return
}
matchHeaderView.yellowNameLabel.text = match.yellow.name
matchHeaderView.redNameLabel.text = match.red.name
matchesResultArray = [(Int, Int)]()
if let scoreArray = match.score where !scoreArray.isEmpty {
let resultMatch = scoreArray.getResultOfMatch()
matchHeaderView.scoreLabel.text = "\(resultMatch.yellow) : \(resultMatch.red)"
var resultGame = scoreArray[0]
matchesResultArray += [(resultGame.yellow, resultGame.red)]
if scoreArray.count > 1 {
resultGame = scoreArray[1]
matchesResultArray += [(resultGame.yellow, resultGame.red)]
if scoreArray.count > 2 {
resultGame = scoreArray[2]
matchesResultArray += [(resultGame.yellow, resultGame.red)]
}
}
} else {
matchHeaderView.scoreLabel.text = "match-view-controller-vernus".localized()
}
tableView.reloadData()
}
}
extension MatchViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.matchesResultArray.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "match-view-controller-first-section-title".localized()
case 1:
return "match-view-controller-second-section-title".localized()
case 2:
return "match-view-controller-third-section-title".localized()
default:
return nil
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(String(MatchSectionResultViewCell), forIndexPath: indexPath) as! MatchSectionResultViewCell
let (yellow, red) = self.matchesResultArray[indexPath.section]
if yellow > red {
cell.sliderView.currentRatio = CGFloat(yellow + (9 - red)) / 19.0
} else {
cell.sliderView.currentRatio = CGFloat(yellow) / 19.0
}
return cell
}
}
| 2fa596a7baaea248fa06553e3af8d3d7 | 33.355932 | 154 | 0.646029 | false | false | false | false |
dws741119/Tos | refs/heads/master | TOS/TOS/GameViewController.swift | mit | 1 | import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks")
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
let skView = self.view as SKView
skView.ignoresSiblingOrder = true
scene.size = view.frame.size
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw())
} else {
return Int(UIInterfaceOrientationMask.All.toRaw())
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| d743f4825b930fc20c99423a3502ee12 | 28.017857 | 106 | 0.670154 | false | false | false | false |
onevcat/Kingfisher | refs/heads/master | Demo/Demo/Kingfisher-Demo/ViewControllers/ProcessorCollectionViewController.swift | mit | 1 | //
// ProcessorCollectionViewController.swift
// Kingfisher
//
// Created by onevcat on 2018/11/19.
//
// Copyright (c) 2019 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.
import UIKit
import Kingfisher
private let reuseIdentifier = "ProcessorCell"
class ProcessorCollectionViewController: UICollectionViewController {
var currentProcessor: ImageProcessor = DefaultImageProcessor.default {
didSet {
collectionView.reloadData()
}
}
var processors: [(ImageProcessor, String)] = [
(DefaultImageProcessor.default, "Default"),
(ResizingImageProcessor(referenceSize: CGSize(width: 50, height: 50)), "Resizing"),
(RoundCornerImageProcessor(radius: .point(20)), "Round Corner"),
(RoundCornerImageProcessor(radius: .widthFraction(0.5), roundingCorners: [.topLeft, .bottomRight]), "Round Corner Partial"),
(BorderImageProcessor(border: .init(color: .systemBlue, lineWidth: 8)), "Border"),
(RoundCornerImageProcessor(radius: .widthFraction(0.2)) |> BorderImageProcessor(border: .init(color: UIColor.systemBlue.withAlphaComponent(0.7), lineWidth: 12, radius: .widthFraction(0.2))), "Round Border"),
(BlendImageProcessor(blendMode: .lighten, alpha: 1.0, backgroundColor: .red), "Blend"),
(BlurImageProcessor(blurRadius: 5), "Blur"),
(OverlayImageProcessor(overlay: .red, fraction: 0.5), "Overlay"),
(TintImageProcessor(tint: UIColor.red.withAlphaComponent(0.5)), "Tint"),
(ColorControlsProcessor(brightness: 0.0, contrast: 1.1, saturation: 1.1, inputEV: 1.0), "Vibrancy"),
(BlackWhiteProcessor(), "B&W"),
(CroppingImageProcessor(size: CGSize(width: 100, height: 100)), "Cropping"),
(DownsamplingImageProcessor(size: CGSize(width: 25, height: 25)), "Downsampling"),
(BlurImageProcessor(blurRadius: 5) |> RoundCornerImageProcessor(cornerRadius: 20), "Blur + Round Corner")
]
override func viewDidLoad() {
super.viewDidLoad()
title = "Processor"
setupOperationNavigationBar()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ImageLoader.sampleImageURLs.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCollectionViewCell
let url = ImageLoader.sampleImageURLs[indexPath.row]
KF.url(url)
.setProcessor(currentProcessor)
.serialize(as: .PNG)
.onSuccess { print($0) }
.onFailure { print($0) }
.set(to: cell.cellImageView)
return cell
}
override func alertPopup(_ sender: Any) -> UIAlertController {
let alert = super.alertPopup(sender)
alert.addAction(UIAlertAction(title: "Processor", style: .default, handler: { _ in
let alert = UIAlertController(title: "Processor", message: nil, preferredStyle: .actionSheet)
for item in self.processors {
alert.addAction(UIAlertAction(title: item.1, style: .default) { _ in self.currentProcessor = item.0 })
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
alert.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
self.present(alert, animated: true)
}))
return alert
}
}
| 56eb3a0b6ab34a5404eb253a128e289b | 46.868687 | 215 | 0.691496 | false | false | false | false |
adamontherun/economist | refs/heads/master | EconomistNotes/EconomistSectionRSSClient.swift | mit | 1 | //
// EconomistSectionRSSClient.swift
// EconomistNotes
//
// Created by adam smith on 7/25/16.
// Copyright © 2016 adam smith. All rights reserved.
//
import Foundation
import MWFeedParser
typealias ArticleFromRSSCompletionHandler = (articles: [Article], error: NSError?)->()
/// This classes processes the RSS feed for one section of the Economist magazine and creates an Article from the results
final class EconomistSectionRSSClient: NSObject, MWFeedParserDelegate {
/// The parsing client
private var feedParser: MWFeedParser
/// Handler to be called when the feed has been processed or has encountered an error
private var completionHandler: ArticleFromRSSCompletionHandler
/// The section of the Economist magazine that's being processed
private var section: String
/// The NSManagedObjectContext that the Article should be created in
private var context: NSManagedObjectContext
/// The date the RSS feed was last accessed. Any articles written prior to this date will be ignored
private var lastAccessedDate: NSDate?
// Holds onto instances of articles as they're being created so they can be returned in the ArticleFromRSSCompletionHandler
private var articles = [Article]()
init(feedURLString: String, section: String, context: NSManagedObjectContext, lastAccessedDate: NSDate?) {
self.section = section
self.context = context
self.completionHandler = {(_, _) in return }
let feedURL = NSURL(string: feedURLString)
feedParser = MWFeedParser(feedURL: feedURL)
feedParser.feedParseType = ParseTypeFull
feedParser.connectionType = ConnectionTypeAsynchronously
self.lastAccessedDate = lastAccessedDate
super.init()
feedParser.delegate = self
}
/**
Fetches all articles in the RSS feed written since the lastAccessedDate
- parameter completionHandler: Called when the processing is complete or the parser has run into an error
*/
func fetchLatestArticlesForSection(completionHandler: ArticleFromRSSCompletionHandler) {
self.completionHandler = completionHandler
feedParser.parse()
}
@objc internal func feedParser(parser: MWFeedParser!, didParseFeedItem item: MWFeedItem!) {
let converter = MWFeedItemToArticleConverter(context: context, lastAccessedDate: lastAccessedDate, section: section)
if let article = converter.createArticleIfNeeded(forFeedItem: item) {
articles.append(article)
}
}
@objc internal func feedParser(parser: MWFeedParser!, didFailWithError error: NSError!) {
completionHandler(articles: articles, error: error)
}
@objc internal func feedParserDidFinish(parser: MWFeedParser!) {
completionHandler(articles: articles, error: nil)
}
} | bbc77857dfcaf1d273a12497d58d072b | 37.631579 | 127 | 0.705281 | false | false | false | false |
AdamSliwakowski/solid-succotash | refs/heads/master | Succotash/Carthage/Checkouts/Koloda/Example/Koloda/ViewController.swift | mit | 1 | //
// ViewController.swift
// Koloda
//
// Created by Eugene Andreyev on 4/23/15.
// Copyright (c) 2015 Eugene Andreyev. All rights reserved.
//
import UIKit
import Koloda
private var numberOfCards: UInt = 5
class ViewController: UIViewController {
@IBOutlet weak var kolodaView: KolodaView!
private var dataSource: Array<UIImage> = {
var array: Array<UIImage> = []
for index in 0..<numberOfCards {
array.append(UIImage(named: "Card_like_\(index + 1)")!)
}
return array
}()
//MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
kolodaView.dataSource = self
kolodaView.delegate = self
self.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
}
//MARK: IBActions
@IBAction func leftButtonTapped() {
kolodaView?.swipe(SwipeResultDirection.Left)
}
@IBAction func rightButtonTapped() {
kolodaView?.swipe(SwipeResultDirection.Right)
}
@IBAction func undoButtonTapped() {
kolodaView?.revertAction()
}
}
//MARK: KolodaViewDelegate
extension ViewController: KolodaViewDelegate {
func kolodaDidRunOutOfCards(koloda: KolodaView) {
dataSource.insert(UIImage(named: "Card_like_6")!, atIndex: kolodaView.currentCardIndex - 1)
let position = kolodaView.currentCardIndex
kolodaView.insertCardAtIndexRange(position...position, animated: true)
}
func koloda(koloda: KolodaView, didSelectCardAtIndex index: UInt) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://yalantis.com/")!)
}
}
//MARK: KolodaViewDataSource
extension ViewController: KolodaViewDataSource {
func kolodaNumberOfCards(koloda:KolodaView) -> UInt {
return UInt(dataSource.count)
}
func koloda(koloda: KolodaView, viewForCardAtIndex index: UInt) -> UIView {
return UIImageView(image: dataSource[Int(index)])
}
func koloda(koloda: KolodaView, viewForCardOverlayAtIndex index: UInt) -> OverlayView? {
return NSBundle.mainBundle().loadNibNamed("OverlayView",
owner: self, options: nil)[0] as? OverlayView
}
}
| d0493247e0fc17c5ea9aea9480e77264 | 26.439024 | 99 | 0.656889 | false | false | false | false |
chrisjmendez/swift-exercises | refs/heads/master | Animation/Flicker/Carthage/Checkouts/SYBlinkAnimationKit/Source/SYButton.swift | mit | 2 | //
// SYButton.swift
// SYBlinkAnimationKit
//
// Created by Shohei Yokoyama on 12/13/2015.
// Copyright © 2015年 Shohei. All rights reserved.
//
import UIKit
@IBDesignable
public class SYButton: UIButton, AnimatableComponent, TextConvertible {
public enum AnimationType: Int {
case border, borderWithShadow, background, ripple, text
}
@IBInspectable public var animationBorderColor = AnimationDefaultColor.border {
didSet {
syLayer.setBorderColor(animationBorderColor)
}
}
@IBInspectable public var animationBackgroundColor = AnimationDefaultColor.background {
didSet {
syLayer.setAnimationBackgroundColor(animationBackgroundColor)
}
}
@IBInspectable public var animationTextColor = AnimationDefaultColor.text {
didSet {
syLayer.setAnimationTextColor(animationTextColor)
}
}
@IBInspectable public var animationRippleColor = AnimationDefaultColor.ripple {
didSet {
syLayer.setRippleColor(animationRippleColor)
}
}
@IBInspectable var animationTimingAdapter: Int {
get {
return animationTimingFunction.rawValue
}
set(index) {
animationTimingFunction = SYMediaTimingFunction(rawValue: index) ?? .linear
}
}
@IBInspectable public var animationDuration: CGFloat = 1.5 {
didSet {
syLayer.setAnimationDuration( CFTimeInterval(animationDuration) )
}
}
@IBInspectable var animationAdapter: Int {
get {
return animationType.rawValue
}
set(index) {
animationType = AnimationType(rawValue: index) ?? .border
}
}
public var animationTimingFunction: SYMediaTimingFunction = .linear {
didSet {
syLayer.setTimingFunction(animationTimingFunction)
}
}
public var animationType: AnimationType = .border {
didSet {
syLayer.animationType = {
switch animationType {
case .border:
return .border
case .borderWithShadow:
return .borderWithShadow
case .background:
return .background
case .ripple:
return .ripple
case .text:
return .text
}
}()
}
}
override public var bounds: CGRect {
didSet {
syLayer.resizeSuperLayer()
}
}
override public var frame: CGRect {
didSet {
syLayer.resizeSuperLayer()
}
}
override public var backgroundColor: UIColor? {
didSet {
if let backgroundColor = backgroundColor {
syLayer.setBackgroundColor(backgroundColor)
}
}
}
public var isAnimating = false
var textLayer = CATextLayer()
public var textAlignmentMode: TextAlignmentMode = .center {
didSet {
resetTextLayer()
}
}
fileprivate lazy var syLayer: SYLayer = .init(layer: self.layer)
fileprivate var textColor: UIColor = .black {
didSet {
syLayer.setTextColor(textColor)
}
}
// MARK: - initializer -
public override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
// MARK: - Override Methods -
override public func setTitle(_ title: String?, for state: UIControlState) {
super.setTitle(title ?? "", for: state)
resetTextLayer()
}
override public func setTitleColor(_ color: UIColor?, for state: UIControlState) {
super.setTitleColor(UIColor.clear, for: state)
if let color = color {
textLayer.foregroundColor = color.cgColor
textColor = color
}
}
// MARK: - Public Methods -
public func setFont(name fontName: String = ".SFUIText-Medium", ofSize fontSize: CGFloat) -> Self {
titleLabel?.font = UIFont(name: fontName, size: fontSize)
resetTextLayer()
return self
}
public func startAnimating() {
isAnimating = true
syLayer.startAnimating()
}
public func stopAnimating() {
isAnimating = false
syLayer.startAnimating()
}
}
// MARK: - Fileprivate Methods -
fileprivate extension SYButton {
func configure() {
layer.cornerRadius = 5
let padding: CGFloat = 5
contentEdgeInsets = UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding)
syLayer.animationType = .border
setTitleColor(.black, for: .normal)
}
func resetTextLayer() {
configureTextLayer(currentTitle, font: titleLabel?.font, textColor: textColor)
syLayer.resetTextLayer(textLayer)
}
}
| 69a0fcc61b235a129cc1762ea0de9bb9 | 26.403226 | 103 | 0.584658 | false | false | false | false |
LKY769215561/KYHandMade | refs/heads/master | KYHandMade/Pods/DynamicColor/Sources/DynamicColor+Lab.swift | apache-2.0 | 2 | /*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: CIE L*a*b* Color Space
public extension DynamicColor {
/**
Initializes and returns a color object using CIE XYZ color space component values with an observer at 2° and a D65 illuminant.
Notes that values out of range are clipped.
- parameter L: The lightness, specified as a value from 0 to 100.0.
- parameter a: The red-green axis, specified as a value from -128.0 to 127.0.
- parameter b: The yellow-blue axis, specified as a value from -128.0 to 127.0.
- parameter alpha: The opacity value of the color object, specified as a value from 0.0 to 1.0. Default to 1.0.
*/
public convenience init(L: CGFloat, a: CGFloat, b: CGFloat, alpha: CGFloat = 1) {
let clippedL = clip(L, 0, 100)
let clippedA = clip(a, -128, 127)
let clippedB = clip(b, -128, 127)
let normalized = { (c: CGFloat) -> CGFloat in
pow(c, 3) > 0.008856 ? pow(c, 3) : (c - 16 / 116) / 7.787
}
let preY = (clippedL + 16) / 116
let preX = clippedA / 500 + preY
let preZ = preY - clippedB / 200
let X = 95.05 * normalized(preX)
let Y = 100 * normalized(preY)
let Z = 108.9 * normalized(preZ)
self.init(X: X, Y: Y, Z: Z, alpha: alpha)
}
// MARK: - Getting the L*a*b* Components
/**
Returns the Lab (lightness, red-green axis, yellow-blue axis) components.
It is based on the CIE XYZ color space with an observer at 2° and a D65 illuminant.
Notes that L values are between 0 to 100.0, a values are between -128 to 127.0 and b values are between -128 to 127.0.
- returns: The L*a*b* components as a tuple (L, a, b).
*/
public final func toLabComponents() -> (L: CGFloat, a: CGFloat, b: CGFloat) {
let normalized = { (c: CGFloat) -> CGFloat in
c > 0.008856 ? pow(c, 1.0 / 3) : 7.787 * c + 16.0 / 116
}
let xyz = toXYZComponents()
let normalizedX = normalized(xyz.X / 95.05)
let normalizedY = normalized(xyz.Y / 100)
let normalizedZ = normalized(xyz.Z / 108.9)
let L = roundDecimal(116 * normalizedY - 16, precision: 1000)
let a = roundDecimal(500 * (normalizedX - normalizedY), precision: 1000)
let b = roundDecimal(200 * (normalizedY - normalizedZ), precision: 1000)
return (L: L, a: a, b: b)
}
}
| fd06320eb52c6d75f6297319e219d175 | 37.119565 | 129 | 0.678072 | false | false | false | false |
ALHariPrasad/BluetoothKit | refs/heads/develop | Carthage/Checkouts/CryptoSwift/CryptoSwift/HMAC.swift | apache-2.0 | 20 | //
// HMAC.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 13/01/15.
// Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
final public class HMAC {
public enum Variant {
case sha1, sha256, sha384, sha512, md5
var size:Int {
switch (self) {
case .sha1:
return SHA1(NSData()).size
case .sha256:
return SHA2.Variant.sha256.size
case .sha384:
return SHA2.Variant.sha384.size
case .sha512:
return SHA2.Variant.sha512.size
case .md5:
return MD5(NSData()).size
}
}
func calculateHash(bytes bytes:[UInt8]) -> [UInt8]? {
switch (self) {
case .sha1:
return NSData.withBytes(bytes).sha1()?.arrayOfBytes()
case .sha256:
return NSData.withBytes(bytes).sha256()?.arrayOfBytes()
case .sha384:
return NSData.withBytes(bytes).sha384()?.arrayOfBytes()
case .sha512:
return NSData.withBytes(bytes).sha512()?.arrayOfBytes()
case .md5:
return NSData.withBytes(bytes).md5()?.arrayOfBytes();
}
}
func blockSize() -> Int {
switch self {
case .md5, .sha1, .sha256:
return 64
case .sha384, .sha512:
return 128
}
}
}
var key:[UInt8]
let variant:Variant
class internal func authenticate(key key: [UInt8], message: [UInt8], variant:HMAC.Variant = .md5) -> [UInt8]? {
return HMAC(key, variant: variant)?.authenticate(message: message)
}
// MARK: - Private
internal init? (_ key: [UInt8], variant:HMAC.Variant = .md5) {
self.variant = variant
self.key = key
if (key.count > variant.blockSize()) {
if let hash = variant.calculateHash(bytes: key) {
self.key = hash
}
}
if (key.count < variant.blockSize()) { // keys shorter than blocksize are zero-padded
self.key = key + [UInt8](count: variant.blockSize() - key.count, repeatedValue: 0)
}
}
internal func authenticate(message message:[UInt8]) -> [UInt8]? {
var opad = [UInt8](count: variant.blockSize(), repeatedValue: 0x5c)
for (idx, _) in key.enumerate() {
opad[idx] = key[idx] ^ opad[idx]
}
var ipad = [UInt8](count: variant.blockSize(), repeatedValue: 0x36)
for (idx, _) in key.enumerate() {
ipad[idx] = key[idx] ^ ipad[idx]
}
var finalHash:[UInt8]? = nil;
if let ipadAndMessageHash = variant.calculateHash(bytes: ipad + message) {
finalHash = variant.calculateHash(bytes: opad + ipadAndMessageHash);
}
return finalHash
}
} | 8c54e50ceddeaac930302bbaa1e277d4 | 30.208333 | 116 | 0.522871 | false | false | false | false |
aquarchitect/MyKit | refs/heads/master | Sources/Shared/Utilities/Promise.swift | mit | 1 | //
// Promise.swift
// MyKit
//
// Created by Hai Nguyen.
// Copyright (c) 2015 Hai Nguyen.
//
import Dispatch
/// _Promise_ represents the future value of a (usually) asynchronous task.
public struct Promise<T> {
public typealias Operation = (@escaping Result<T>.Callback) -> Void
// MARK: Properties
fileprivate let operation: Operation
// MARK: Initialization
public init(_ operation: @escaping Operation) {
self.operation = operation
}
public init(_ result: Result<T>) {
self.operation = { $0(result) }
}
public init(_ value: T) {
self.init(.fulfill(value))
}
public init(_ error: Swift.Error) {
self.init(.reject(error))
}
}
// MARK: - Execution
public extension Promise {
/// Execute promise with a callback (for internal usage only)
internal func resolve(_ callback: @escaping Result<T>.Callback) {
self.operation(callback)
}
/// Execute promise on module level
func resolve() {
self.operation({ _ in })
}
}
// MARK: - Transformation
public extension Promise {
/// Transform one type to another.
func map<U>(_ transformer: @escaping (T) throws -> U) -> Promise<U> {
return Promise<U> { callback in
self.resolve { result in
callback(result.map(transformer))
}
}
}
/// Transform one type to another.
func flatMap<U>(_ transformer: @escaping (T) -> Promise<U>) -> Promise<U> {
return Promise<U> { callback in
self.resolve { result in
do {
transformer(try result.resolve()).resolve(callback)
} catch {
callback(.reject(error))
}
}
}
}
}
// MARK: - Result Action
public extension Promise {
private func onResult(_ handle: @escaping (Result<T>) -> Void) -> Promise {
return Promise { callback in
self.resolve { result in
handle(result)
callback(result)
}
}
}
func always(_ handle: @escaping () -> Void) -> Promise {
return onResult { _ in handle() }
}
func onSuccess(_ handle: @escaping (T) -> Void) -> Promise {
return onResult {
if case let .fulfill(value) = $0 { handle(value) }
}
}
func onFailure(_ handle: @escaping (Swift.Error) -> Void) -> Promise {
return onResult {
if case let .reject(error) = $0 { handle(error) }
}
}
}
// MARK: - Failure Action
public extension Promise {
func recover(_ transformer: @escaping (Swift.Error) -> Promise) -> Promise {
return Promise { callback in
self.resolve { result in
do {
callback(.fulfill(try result.resolve()))
} catch {
transformer(error).resolve(callback)
}
}
}
}
func retry(attempCount count: Int) -> Promise {
return Promise { callback in
func _retry(attemptCount count: Int) {
self.resolve { result in
switch (result, count) {
case (.fulfill(_), _),
(.reject(_), 0):
callback(result)
default:
_retry(attemptCount: count - 1)
}
}
}
_retry(attemptCount: count)
}
}
}
// MARK: - Threading
public extension Promise {
func on(_ queue: DispatchQueue) -> Promise {
return Promise { callback in
queue.async { self.resolve(callback) }
}
}
func inBackground() -> Promise {
return on(.global(qos: .background))
}
func inDispatchGroup(_ group: DispatchGroup) -> Promise {
return Promise { callback in
group.enter()
self.resolve { result in
callback(result)
group.leave()
}
}
}
}
// MARK: - Multiple Promises
public extension Promise {
/// Execute promises of the same type asynchronously.
static func concat(_ promises: [Promise]) -> Promise<[T]> {
let group = DispatchGroup()
return Promise<[T]> { callback in
var outputs: [Result<T>] = []
for promise in promises {
promise
.inDispatchGroup(group)
.resolve { outputs.append($0) }
}
group.notify(queue: .main) {
(Result.concat >>> callback)(outputs)
}
}
}
static func concat(_ promises: Promise...) -> Promise<[T]> {
return concat(promises)
}
}
/// Execute promises of different tpes asynchronously
public func zip<A, B>(_ promiseA: Promise<A>, _ promiseB: Promise<B>) -> Promise<(A, B)> {
let group = DispatchGroup()
return Promise<(A, B)> { callback in
var resultA: Result<A>?
var resultB: Result<B>?
promiseA
.inDispatchGroup(group)
.resolve({ resultA = $0 })
promiseB
.inDispatchGroup(group)
.resolve({ resultB = $0 })
group.notify(queue: .main) {
zip(resultA, resultB).map {
callback(zip($0, $1))
}
}
}
}
/// Execute promises of different tpes asynchronously
public func zip<A, B, C>(_ promiseA: Promise<A>, _ promiseB: Promise<B>, _ promiseC: Promise<C>) -> Promise<(A, B, C)> {
let group = DispatchGroup()
return Promise<(A, B, C)> { callback in
var resultA: Result<A>?
var resultB: Result<B>?
var resultC: Result<C>?
promiseA
.inDispatchGroup(group)
.resolve({ resultA = $0 })
promiseB
.inDispatchGroup(group)
.resolve({ resultB = $0 })
promiseC
.inDispatchGroup(group)
.resolve({ resultC = $0 })
group.notify(queue: .main) {
zip(resultA, resultB, resultC).map {
callback(zip($0, $1, $2))
}
}
}
}
| 6d3e2c5d2baa0f6d57da329ff2fe0c4b | 23.677291 | 120 | 0.515176 | false | false | false | false |
iAugux/ENSwiftSideMenu | refs/heads/swift_2.0 | ENSwiftSideMenu/MyMenuTableViewController.swift | mit | 1 | //
// MyMenuTableViewController.swift
// SwiftSideMenu
//
// Created by Evgeny Nazarov on 29.09.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
class MyMenuTableViewController: UITableViewController {
var selectedMenuItem : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Customize apperance of table view
tableView.contentInset = UIEdgeInsetsMake(64.0, 0, 0, 0) //
tableView.separatorStyle = .None
tableView.backgroundColor = UIColor.clearColor()
tableView.scrollsToTop = false
// Preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
tableView.selectRowAtIndexPath(NSIndexPath(forRow: selectedMenuItem, inSection: 0), animated: false, scrollPosition: .Middle)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return 4
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CELL")
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CELL")
cell!.backgroundColor = UIColor.clearColor()
cell!.textLabel?.textColor = UIColor.darkGrayColor()
let selectedBackgroundView = UIView(frame: CGRectMake(0, 0, cell!.frame.size.width, cell!.frame.size.height))
selectedBackgroundView.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.2)
cell!.selectedBackgroundView = selectedBackgroundView
}
cell!.textLabel?.text = "ViewController #\(indexPath.row+1)"
return cell!
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 50.0
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("did select row: \(indexPath.row)")
if (indexPath.row == selectedMenuItem) {
return
}
selectedMenuItem = indexPath.row
//Present new view controller
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main",bundle: nil)
var destViewController : UIViewController
switch (indexPath.row) {
case 0:
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ViewController1")
break
case 1:
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ViewController2")
break
case 2:
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ViewController3")
break
default:
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ViewController4")
break
}
sideMenuController()?.setContentViewController(destViewController)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| d60daf734e2f2c8ef8e9b860acb79c33 | 35.747664 | 133 | 0.665565 | false | false | false | false |
Look-ARound/LookARound2 | refs/heads/hd-callouts | Pods/HDAugmentedReality/HDAugmentedReality/Classes/ARConfiguration.swift | apache-2.0 | 1 | import CoreLocation
import UIKit
let LAT_LON_FACTOR: CGFloat = 1.33975031663 // Used in azimuzh calculation, don't change
let MAX_VISIBLE_ANNOTATIONS: Int = 500 // Do not change, can affect performance
internal func radiansToDegrees(_ radians: Double) -> Double
{
return (radians) * (180.0 / Double.pi)
}
internal func degreesToRadians(_ degrees: Double) -> Double
{
return (degrees) * (Double.pi / 180.0)
}
/// Normalizes degree to 0-360
internal func normalizeDegree(_ degree: Double) -> Double
{
var degreeNormalized = fmod(degree, 360)
if degreeNormalized < 0
{
degreeNormalized = 360 + degreeNormalized
}
return degreeNormalized
}
/// Normalizes degree to 0...180, 0...-180
internal func normalizeDegree2(_ degree: Double) -> Double
{
var degreeNormalized = fmod(degree, 360)
if degreeNormalized > 180
{
degreeNormalized -= 360
}
else if degreeNormalized < -180
{
degreeNormalized += 360
}
return degreeNormalized
}
/// Finds shortes angle distance between two angles. Angles must be normalized(0-360)
internal func deltaAngle(_ angle1: Double, _ angle2: Double) -> Double
{
var deltaAngle = angle1 - angle2
if deltaAngle > 180
{
deltaAngle -= 360
}
else if deltaAngle < -180
{
deltaAngle += 360
}
return deltaAngle
}
/// DataSource provides the ARViewController with the information needed to display annotations.
@objc public protocol ARDataSource : NSObjectProtocol
{
/// Asks the data source to provide annotation view for annotation. Annotation view must be subclass of ARAnnotationView.
func ar(_ arViewController: ARViewController, viewForAnnotation: ARAnnotation) -> ARAnnotationView
/**
* READ BEFORE IMPLEMENTING
* ARViewController tracks user movement and shows/hides annotations accordingly. But if there is huge amount
* of annotations or for some other reason annotations cannot be set all at once, this method can be used to
* set annotations part by part.
*
* Use ARViewController.trackingManager.reloadDistanceFilter to change how often this is called.
*
* - parameter arViewController: ARViewController instance
* - parameter location: Current location of the user
* - returns: Annotations to load, previous annotations are removed
*/
@objc optional func ar(_ arViewController: ARViewController, shouldReloadWithLocation location: CLLocation) -> [ARAnnotation]
}
/**
Holds all location and device related information
*/
public struct ARStatus
{
/// Horizontal field of view od device. Changes when device rotates(hFov becomes vFov).
public var hFov: Double = 0
/// Vertical field of view od device. Changes when device rotates(vFov becomes hFov).
public var vFov: Double = 0
/// How much pixels(logical) on screen is 1 degree, horizontally.
public var hPixelsPerDegree: Double = 0
/// How much pixels(logical) on screen is 1 degree, vertically.
public var vPixelsPerDegree: Double = 0
/// Heading of the device, 0-360.
public var heading: Double = 0
/// Pitch of the device, device pointing straight = 0, up(upper edge tilted toward user) = 90, down = -90.
public var pitch: Double = 0
/// Last known location of the user.
public var userLocation: CLLocation?
/// True if all properties have been set.
public var ready: Bool
{
get
{
let hFovOK = hFov > 0
let vFovOK = vFov > 0
let hPixelsPerDegreeOK = hPixelsPerDegree > 0
let vPixelsPerDegreeOK = vPixelsPerDegree > 0
let headingOK = heading != 0 //@TODO
let pitchOK = pitch != 0 //@TODO
let userLocationOK = self.userLocation != nil && CLLocationCoordinate2DIsValid(self.userLocation!.coordinate)
return hFovOK && vFovOK && hPixelsPerDegreeOK && vPixelsPerDegreeOK && headingOK && pitchOK && userLocationOK
}
}
}
public struct Platform
{
public static let isSimulator: Bool =
{
var isSim = false
#if arch(i386) || arch(x86_64)
isSim = true
#endif
return isSim
}()
}
| 5d304e1cd66a55b2f7a695ac791c3dd8 | 31.81203 | 129 | 0.651237 | false | false | false | false |
Quick/Quick | refs/heads/main | Sources/Quick/DSL/World+DSL.swift | apache-2.0 | 1 | import Foundation
/**
Adds methods to World to support top-level DSL functions (Swift) and
macros (Objective-C). These functions map directly to the DSL that test
writers use in their specs.
*/
extension World {
// MARK: - Before Suite
internal func beforeSuite(_ closure: @escaping BeforeSuiteClosure) {
suiteHooks.appendBefore(closure)
}
@nonobjc
internal func beforeSuite(_ closure: @escaping BeforeSuiteAsyncClosure) {
suiteHooks.appendBefore(closure)
}
// MARK: - After Suite
internal func afterSuite(_ closure: @escaping AfterSuiteClosure) {
suiteHooks.appendAfter(closure)
}
@nonobjc
internal func afterSuite(_ closure: @escaping AfterSuiteAsyncClosure) {
suiteHooks.appendAfter(closure)
}
// MARK: - Specifying shared examples
internal func sharedExamples(_ name: String, closure: @escaping SharedExampleClosure) {
registerSharedExample(name, closure: closure)
}
// MARK: - Example groups.
internal func describe(_ description: String, flags: FilterFlags = [:], closure: () -> Void) {
guard currentExampleMetadata == nil else {
raiseError("'describe' cannot be used inside '\(currentPhase)', 'describe' may only be used inside 'context' or 'describe'.")
}
guard currentExampleGroup != nil else {
// swiftlint:disable:next line_length
raiseError("Error: example group was not created by its parent QuickSpec spec. Check that describe() or context() was used in QuickSpec.spec() and not a more general context (i.e. an XCTestCase test)")
}
let group = ExampleGroup(description: description, flags: flags)
currentExampleGroup.appendExampleGroup(group)
performWithCurrentExampleGroup(group, closure: closure)
}
internal func context(_ description: String, flags: FilterFlags = [:], closure: () -> Void) {
guard currentExampleMetadata == nil else {
raiseError("'context' cannot be used inside '\(currentPhase)', 'context' may only be used inside 'context' or 'describe'.")
}
self.describe(description, flags: flags, closure: closure)
}
internal func fdescribe(_ description: String, closure: () -> Void) {
self.describe(description, flags: [Filter.focused: true], closure: closure)
}
internal func xdescribe(_ description: String, closure: () -> Void) {
self.describe(description, flags: [Filter.pending: true], closure: closure)
}
// MARK: - Just Before Each
#if canImport(Darwin)
@objc(justBeforeEach:)
internal func objc_justBeforeEach(_ closure: @escaping BeforeExampleClosure) {
guard currentExampleMetadata == nil else {
raiseError("'justBeforeEach' cannot be used inside '\(currentPhase)', 'justBeforeEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendJustBeforeEach(closure)
}
#endif
@nonobjc
internal func justBeforeEach(_ closure: @escaping BeforeExampleAsyncClosure) {
guard currentExampleMetadata == nil else {
raiseError("'justBeforeEach' cannot be used inside '\(currentPhase)', 'justBeforeEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendJustBeforeEach(closure)
}
// MARK: - Before Each
#if canImport(Darwin)
@objc(beforeEachWithMetadata:)
internal func objc_beforeEach(closure: @escaping BeforeExampleWithMetadataClosure) {
guard currentExampleMetadata == nil else {
raiseError("'beforeEach' cannot be used inside '\(currentPhase)', 'beforeEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendBefore(closure)
}
#endif
@nonobjc
internal func beforeEach(closure: @escaping BeforeExampleWithMetadataClosure) {
guard currentExampleMetadata == nil else {
raiseError("'beforeEach' cannot be used inside '\(currentPhase)', 'beforeEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendBefore(closure)
}
internal func beforeEach(_ closure: @escaping BeforeExampleClosure) {
guard currentExampleMetadata == nil else {
raiseError("'beforeEach' cannot be used inside '\(currentPhase)', 'beforeEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendBefore(closure)
}
@nonobjc
internal func beforeEach(_ closure: @escaping BeforeExampleAsyncClosure) {
guard currentExampleMetadata == nil else {
raiseError("'beforeEach' cannot be used inside '\(currentPhase)', 'beforeEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendBefore(closure)
}
@nonobjc
internal func beforeEach(closure: @escaping BeforeExampleWithMetadataAsyncClosure) {
guard currentExampleMetadata == nil else {
raiseError("'beforeEach' cannot be used inside '\(currentPhase)', 'beforeEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendBefore(closure)
}
// MARK: - After Each
#if canImport(Darwin)
@objc(afterEachWithMetadata:)
internal func objc_afterEach(closure: @escaping AfterExampleWithMetadataClosure) {
guard currentExampleMetadata == nil else {
raiseError("'afterEach' cannot be used inside '\(currentPhase)', 'afterEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendAfter(closure)
}
#endif
@nonobjc
internal func afterEach(closure: @escaping AfterExampleWithMetadataClosure) {
guard currentExampleMetadata == nil else {
raiseError("'afterEach' cannot be used inside '\(currentPhase)', 'afterEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendAfter(closure)
}
internal func afterEach(_ closure: @escaping AfterExampleClosure) {
guard currentExampleMetadata == nil else {
raiseError("'afterEach' cannot be used inside '\(currentPhase)', 'afterEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendAfter(closure)
}
@nonobjc
internal func afterEach(_ closure: @escaping AfterExampleAsyncClosure) {
guard currentExampleMetadata == nil else {
raiseError("'afterEach' cannot be used inside '\(currentPhase)', 'afterEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendAfter(closure)
}
@nonobjc
internal func afterEach(closure: @escaping AfterExampleWithMetadataAsyncClosure) {
guard currentExampleMetadata == nil else {
raiseError("'afterEach' cannot be used inside '\(currentPhase)', 'afterEach' may only be used inside 'context' or 'describe'.")
}
currentExampleGroup.hooks.appendAfter(closure)
}
// MARK: - Around Each
@nonobjc
internal func aroundEach(_ closure: @escaping AroundExampleAsyncClosure) {
guard currentExampleMetadata == nil else {
raiseError("'aroundEach' cannot be used inside '\(currentPhase)', 'aroundEach' may only be used inside 'context' or 'describe'. ")
}
currentExampleGroup.hooks.appendAround(closure)
}
@nonobjc
internal func aroundEach(_ closure: @escaping AroundExampleWithMetadataAsyncClosure) {
guard currentExampleMetadata == nil else {
raiseError("'aroundEach' cannot be used inside '\(currentPhase)', 'aroundEach' may only be used inside 'context' or 'describe'. ")
}
currentExampleGroup.hooks.appendAround(closure)
}
// MARK: - Examples (Swift)
@nonobjc
internal func it(_ description: String, flags: FilterFlags = [:], file: FileString, line: UInt, closure: @escaping () async throws -> Void) {
if beforesCurrentlyExecuting {
raiseError("'it' cannot be used inside 'beforeEach', 'it' may only be used inside 'context' or 'describe'.")
}
if aftersCurrentlyExecuting {
raiseError("'it' cannot be used inside 'afterEach', 'it' may only be used inside 'context' or 'describe'.")
}
guard currentExampleMetadata == nil else {
raiseError("'it' cannot be used inside 'it', 'it' may only be used inside 'context' or 'describe'.")
}
let callsite = Callsite(file: file, line: line)
let example = Example(description: description, callsite: callsite, flags: flags, closure: closure)
currentExampleGroup.appendExample(example)
}
@nonobjc
internal func fit(_ description: String, file: FileString, line: UInt, closure: @escaping () async throws -> Void) {
self.it(description, flags: [Filter.focused: true], file: file, line: line, closure: closure)
}
@nonobjc
internal func xit(_ description: String, file: FileString, line: UInt, closure: @escaping () async throws -> Void) {
self.it(description, flags: [Filter.pending: true], file: file, line: line, closure: closure)
}
// MARK: - Shared Behavior
@nonobjc
internal func itBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, flags: FilterFlags = [:], file: FileString, line: UInt) {
guard currentExampleMetadata == nil else {
raiseError("'itBehavesLike' cannot be used inside '\(currentPhase)', 'itBehavesLike' may only be used inside 'context' or 'describe'.")
}
let callsite = Callsite(file: file, line: line)
let closure = World.sharedWorld.sharedExample(name)
let group = ExampleGroup(description: name, flags: flags)
currentExampleGroup.appendExampleGroup(group)
performWithCurrentExampleGroup(group) {
closure(sharedExampleContext)
}
group.walkDownExamples { (example: Example) in
example.isSharedExample = true
example.callsite = callsite
}
}
@nonobjc
internal func fitBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, file: FileString, line: UInt) {
self.itBehavesLike(name, sharedExampleContext: sharedExampleContext, flags: [Filter.focused: true], file: file, line: line)
}
@nonobjc
internal func xitBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, file: FileString, line: UInt) {
self.itBehavesLike(name, sharedExampleContext: sharedExampleContext, flags: [Filter.pending: true], file: file, line: line)
}
internal func itBehavesLike<C>(_ behavior: Behavior<C>.Type, context: @escaping () -> C, flags: FilterFlags = [:], file: FileString, line: UInt) {
guard currentExampleMetadata == nil else {
raiseError("'itBehavesLike' cannot be used inside '\(currentPhase)', 'itBehavesLike' may only be used inside 'context' or 'describe'.")
}
let callsite = Callsite(file: file, line: line)
let closure = behavior.spec
let group = ExampleGroup(description: behavior.name, flags: flags)
currentExampleGroup.appendExampleGroup(group)
performWithCurrentExampleGroup(group) {
closure(context)
}
group.walkDownExamples { (example: Example) in
example.isSharedExample = true
example.callsite = callsite
}
}
internal func fitBehavesLike<C>(_ behavior: Behavior<C>.Type, context: @escaping () -> C, file: FileString, line: UInt) {
self.itBehavesLike(behavior, context: context, flags: [Filter.focused: true], file: file, line: line)
}
internal func xitBehavesLike<C>(_ behavior: Behavior<C>.Type, context: @escaping () -> C, file: FileString, line: UInt) {
self.itBehavesLike(behavior, context: context, flags: [Filter.pending: true], file: file, line: line)
}
// MARK: Examples & Shared behavior (objc)
#if canImport(Darwin) && !SWIFT_PACKAGE
@nonobjc
internal func syncIt(_ description: String, flags: FilterFlags = [:], file: FileString, line: UInt, closure: @escaping @MainActor () throws -> Void) {
if beforesCurrentlyExecuting {
raiseError("'it' cannot be used inside 'beforeEach', 'it' may only be used inside 'context' or 'describe'.")
}
if aftersCurrentlyExecuting {
raiseError("'it' cannot be used inside 'afterEach', 'it' may only be used inside 'context' or 'describe'.")
}
guard currentExampleMetadata == nil else {
raiseError("'it' cannot be used inside 'it', 'it' may only be used inside 'context' or 'describe'.")
}
let callsite = Callsite(file: file, line: line)
let example = Example(description: description, callsite: callsite, flags: flags, closure: closure)
currentExampleGroup.appendExample(example)
}
@objc(itWithDescription:file:line:closure:)
internal func objc_it(_ description: String, file: FileString, line: UInt, closure: @escaping () -> Void) {
syncIt(description, file: file, line: line, closure: closure)
}
@objc(fitWithDescription:file:line:closure:)
internal func objc_fit(_ description: String, file: FileString, line: UInt, closure: @escaping () -> Void) {
syncIt(description, flags: [Filter.focused: true], file: file, line: line, closure: closure)
}
@objc(xitWithDescription:file:line:closure:)
internal func objc_xit(_ description: String, file: FileString, line: UInt, closure: @escaping () -> Void) {
syncIt(description, flags: [Filter.pending: true], file: file, line: line, closure: closure)
}
@objc(itBehavesLikeSharedExampleNamed:sharedExampleContext:file:line:)
internal func objc_itBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, file: FileString, line: UInt) {
itBehavesLike(name, sharedExampleContext: sharedExampleContext, file: file, line: line)
}
@objc(fitBehavesLikeSharedExampleNamed:sharedExampleContext:file:line:)
internal func objc_fitBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, file: FileString, line: UInt) {
fitBehavesLike(name, sharedExampleContext: sharedExampleContext, file: file, line: line)
}
@objc(xitBehavesLikeSharedExampleNamed:sharedExampleContext:file:line:)
internal func objc_xitBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, file: FileString, line: UInt) {
xitBehavesLike(name, sharedExampleContext: sharedExampleContext, file: file, line: line)
}
#endif
// MARK: - Pending
@nonobjc
internal func pending(_ description: String, closure: () async throws -> Void) {
print("Pending: \(description)")
}
internal func pending(_ description: String, closure: () -> Void) {
print("Pending: \(description)")
}
private var currentPhase: String {
if beforesCurrentlyExecuting {
return "beforeEach"
} else if aftersCurrentlyExecuting {
return "afterEach"
}
return "it"
}
}
| ab14272baf1d2cc67c515d40a08c889c | 44.918919 | 213 | 0.674057 | false | false | false | false |
josve05a/wikipedia-ios | refs/heads/develop | Wikipedia/Code/WMFImageGalleryGradientViews.swift | mit | 3 |
@objcMembers class WMFImageGalleryBottomGradientView: SetupGradientView {
override public func setup(gradientLayer: CAGradientLayer) {
gradientLayer.locations = [0.0, 0.5, 1.0]
gradientLayer.colors = [
UIColor(white: 0, alpha: 1.0).cgColor,
UIColor(white: 0, alpha: 0.5).cgColor,
UIColor.clear.cgColor
]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
}
}
class WMFImageGalleryDescriptionGradientView : UIView {
private let fadeHeight = 6.0
private var normalizedFadeHeight: Double {
return bounds.size.height > 0 ? fadeHeight / Double(bounds.size.height) : 0
}
private lazy var gradientMask: CAGradientLayer = {
let mask = CAGradientLayer()
mask.startPoint = .zero
mask.endPoint = CGPoint(x: 0, y: 1)
mask.colors = [
UIColor.black.cgColor,
UIColor.clear.cgColor,
UIColor.clear.cgColor,
UIColor.black.cgColor
]
layer.backgroundColor = UIColor.black.cgColor
layer.mask = mask
return mask
}()
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
guard layer == gradientMask.superlayer else {
assertionFailure("Unexpected superlayer")
return
}
gradientMask.locations = [ // Keep fade heights fixed to `fadeHeight` regardless of text view height
0.0,
NSNumber(value: normalizedFadeHeight), // upper stop
NSNumber(value: 1.0 - normalizedFadeHeight), // lower stop
1.0
]
gradientMask.frame = bounds
}
}
| 531b2d1c4f948be4fe0353b516b249f6 | 34.16 | 109 | 0.602958 | false | false | false | false |
Armanoide/CubeFlip | refs/heads/master | SRC/CubeFlip.swift | mit | 1 | //
// CubeFlip.swift
// CubeFlip
//
// Created by Norbert Billa on 22/09/2015.
// Copyright © 2015 norbert-billa. All rights reserved.
//
import UIKit
import QuartzCore
public enum CubeFlipAnimation : CGFloat {
case none = 1
case bouncing = 0.58
case whizzing = 0.1
}
@IBDesignable open class CubeFlip<T: UIView>: UIView {
public typealias CustomizeView = (T) -> ()
open var animationWith : CubeFlipAnimation = .bouncing
fileprivate var view1 : T!
fileprivate var view2 : T!
fileprivate (set) open var viewOff : T!
fileprivate (set) open var viewOn : T!
fileprivate var isAnimated : Bool = false
open var duration : Double = 1
open var perspective : CGFloat = 500
init(frame: CGRect, view1: T, view2: T, CubeFlipAnimation animation: CubeFlipAnimation = .bouncing) {
super.init(frame: frame)
self.view1 = view1
self.view2 = view2
self.animationWith = animation
view1.frame = self.bounds
view2.frame = self.bounds
self.subviewsSetup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if self.subviews.count == 0 {
self.xibSetup()
}
}
fileprivate func xibSetup() {
self.view1 = UIView(frame:self.bounds) as! T
self.view2 = UIView(frame:self.bounds) as! T
self.view1.backgroundColor = UIColor.black
self.view2.backgroundColor = UIColor.blue
self.subviewsSetup()
}
fileprivate func subviewsSetup() {
self.addSubview(self.view1)
self.addSubview(self.view2)
self.viewOn = self.view1
self.viewOff = self.view2
self.viewOff.removeFromSuperview()
}
fileprivate func DEGREES_TO_RADIANS(_ degress : CGFloat) -> CGFloat { return degress * CGFloat(M_PI) / 180 }
fileprivate func makeCloneViewIntoImage(_ viewOrigin : UIView) -> UIImageView {
UIGraphicsBeginImageContext(viewOrigin.frame.size)
viewOrigin.layer.render(in: UIGraphicsGetCurrentContext()!)
let __ = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let viewImage = UIImageView(image: __)
viewImage.frame = viewImage.frame
self.addSubview(viewImage)
return viewImage
}
fileprivate func commonSetupFlipEnd(imageOff : UIImageView, imageOn : UIImageView) {
imageOff.removeFromSuperview()
imageOn.removeFromSuperview()
self.addSubview(self.viewOff)
let tmp = self.viewOff
self.viewOff = self.viewOn
self.viewOn = tmp
self.isAnimated = !self.isAnimated
}
fileprivate func commonSetupFlipStart() -> (imageOff:UIImageView, imageOn:UIImageView)? {
if self.isAnimated { return nil }
self.isAnimated = !self.isAnimated
let imageOff = self.makeCloneViewIntoImage(self.viewOff)
let imageOn = self.makeCloneViewIntoImage(self.viewOn)
self.viewOff.removeFromSuperview()
self.viewOn.removeFromSuperview()
var rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -(abs(self.perspective))
self.layer.sublayerTransform = rotationAndPerspectiveTransform
return (imageOff, imageOn)
}
open func flipDown(_ to: CustomizeView? = nil) {
let imageOff : UIImageView!
let imageOn : UIImageView!
if let setupBlock = to {
setupBlock(self.viewOff)
}
if let __ = self.commonSetupFlipStart() {
imageOff = __.imageOff
imageOn = __.imageOn
} else { return }
var trans : CATransform3D = CATransform3DIdentity
trans = CATransform3DRotate(trans, self.DEGREES_TO_RADIANS(90), 1, 0, 0 )
trans = CATransform3DTranslate ( trans, 0, -self.bounds.height/2, 0 )
trans = CATransform3DTranslate ( trans, 0, 0, self.bounds.height/2 )
imageOff.layer.transform = trans
UIView.animate(withDuration: self.duration, delay: 0, usingSpringWithDamping: self.animationWith.rawValue, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: {
trans = CATransform3DIdentity
imageOff.layer.transform = trans
imageOff.frame.origin.y = 0
trans = CATransform3DIdentity
trans = CATransform3DRotate(trans, self.DEGREES_TO_RADIANS(-90), 1, 0, 0 )
imageOn.layer.transform = trans
imageOn.frame.origin.y = self.bounds.height
}) { (__) -> Void in
self.commonSetupFlipEnd(imageOff: imageOff, imageOn: imageOn)
}
}
open func flipUp(_ to: CustomizeView? = nil) {
let imageOff : UIImageView!
let imageOn : UIImageView!
if let setupBlock = to {
setupBlock(self.viewOff)
}
if let __ = self.commonSetupFlipStart() {
imageOff = __.imageOff
imageOn = __.imageOn
} else { return }
var trans : CATransform3D = CATransform3DIdentity
trans = CATransform3DRotate(trans, self.DEGREES_TO_RADIANS(-90), 1, 0, 0 )
trans = CATransform3DTranslate ( trans, 0, self.bounds.height/2, 0 )
trans = CATransform3DTranslate ( trans, 0, 0, -self.bounds.height/2 )
imageOff.frame.origin.y = self.bounds.height
imageOff.layer.transform = trans
UIView.animate(withDuration: self.duration, delay: 0, usingSpringWithDamping: self.animationWith.rawValue, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: {
trans = CATransform3DIdentity
trans = CATransform3DRotate(trans, self.DEGREES_TO_RADIANS(90), 1, 0, 0 )
imageOn.layer.transform = trans
imageOn.frame.origin.y = 0
trans = CATransform3DIdentity
imageOff.layer.transform = trans
imageOff.frame.origin.y = 0
self.layoutIfNeeded()
}) { (_) in
self.commonSetupFlipEnd(imageOff: imageOff, imageOn: imageOn)
}
}
}
| 406fd6b1169f9dc887c693b0316d9d0e | 34.585492 | 190 | 0.567997 | false | false | false | false |
angelopino/APJExtensions | refs/heads/master | Source/UIView+extension.swift | mit | 1 | //
// UIView+extension.swift
// APJExtensions
//
// Created by Pino, Angelo on 01/08/2017.
// Copyright © 2017 Pino, Angelo. All rights reserved.
//
import UIKit
public extension UIView {
func removeSubviews() {
for view in self.subviews {
view.removeFromSuperview()
}
}
func loadViewFromNib(_ nibName: String? = nil) -> UIView? {
guard let nibObjects = Bundle(for: type(of: self)).loadNibNamed(nibName ?? className, owner: self, options: nil) else { return nil }
return nibObjects.first as? UIView
}
func bindFrameToSuperviewBounds(marginLeft: CGFloat = 0, marginRight: CGFloat = 0, marginTop: CGFloat = 0, marginBottom: CGFloat = 0) {
guard let superview = self.superview else {
print("Error! `superview` was nil – call `addSubview(view: UIView)` before calling `bindFrameToSuperviewBounds()` to fix this.")
return
}
let views = ["subview": self]
translatesAutoresizingMaskIntoConstraints = false
superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(marginLeft)-[subview]-\(marginRight)-|", metrics: nil, views: views))
superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(marginTop)-[subview]-\(marginBottom)-|", metrics: nil, views: views))
}
func snapshot() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
drawHierarchy(in: bounds, afterScreenUpdates: true)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
| 36a2eba807ed5710a02e107321ae29fb | 38.857143 | 158 | 0.670251 | false | false | false | false |
eddieruano/SentinelGreen | refs/heads/master | snowboy/examples/iOS/Swift3/SnowboyTest/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// SnowboyTest
//
// Created by Bi, Sheng on 2/13/17.
// Copyright © 2017 Bi, Sheng. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "SnowboyTest")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| d77a9a5e5f61191d0c2755e44ce2df84 | 47.861702 | 285 | 0.685173 | false | false | false | false |
mbigatti/StatusApp | refs/heads/master | StatusApp/StatusEntityDatabase.swift | mit | 1 | //
// StatusEntityDatabase.swift
// StatusApp
//
// Created by Massimiliano Bigatti on 25/09/14.
// Copyright (c) 2014 Massimiliano Bigatti. All rights reserved.
//
import Foundation
/**
Contains of all the entries stored in the app.
The database is a simple `NSKeyedArchiver` file. The entities are returned orderder by title.
*/
class StatusEntityDatabase {
/// singleton
class var sharedInstance : StatusEntityDatabase {
struct Static {
static let instance = StatusEntityDatabase()
}
return Static.instance
}
/// database file name
private let databaseFilename = "entries.db"
/// database file path complete of file name
private let databaseFilePath : String
/// array of entities contained in the database
lazy var entities : [StatusEntity] = {
var data = NSKeyedUnarchiver.unarchiveObjectWithFile(sharedInstance.databaseFilePath) as? [StatusEntity]
return data == nil ? [StatusEntity]() : data!.sorted({$0.title < $1.title})
}()
/**
Private initializer. Inits the `databaseFilePath` property
*/
private init() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as [NSString]
databaseFilePath = paths[0].stringByAppendingPathComponent(databaseFilename)
// dumps complete database file path for debugging purposes
println("Using database file \(databaseFilePath)")
}
/**
Add an entity
:param: entity entity to be added
*/
func addEntity(entity: StatusEntity) {
entities.append(entity)
refresh()
}
/**
Removes the entity at specified index
:param: index index of entity to be removed
*/
func removeEntityAtIndex(index: Int) {
entities.removeAtIndex(index)
}
/**
Saves pending changes to the permanent storage
*/
func synchronize() {
NSKeyedArchiver.archiveRootObject(entities, toFile: databaseFilePath)
// resort entities in case something was changed
refresh()
}
private func refresh() {
entities = entities.sorted({
$0.title < $1.title
})
}
} | 77c2af3ab0c894fb88613c6692406cc0 | 27.280488 | 134 | 0.635893 | false | false | false | false |
zhouguangjie/Toast-Swift | refs/heads/master | SwiftToastDemo/ToastDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// ToastDemo
//
// Created by Rannie on 14/7/6.
// Copyright (c) 2014年 Rannie. All rights reserved.
//
import UIKit
let ButtonWidth : CGFloat = 120.0
let ButtonHeight : CGFloat = 40.0
let MarginY : CGFloat = 10.0
let MarginX = (UIScreen.mainScreen().bounds.size.width - ButtonWidth) / 2
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "Swift Toast"
self.edgesForExtendedLayout = .None
self.setupButtons()
}
func setupButtons() {
var singleToastBtn = self.quickAddButtonWithTitle("Single Toast", target: self, action: Selector("handleSingleToastClicked:"))
singleToastBtn.frame = CGRectMake(MarginX, 2*MarginY, ButtonWidth, ButtonHeight)
self.view.addSubview(singleToastBtn)
var titleToastBtn = self.quickAddButtonWithTitle("Title Toast", target: self, action: Selector("handleTitleToastClicked:"))
titleToastBtn.frame = CGRectMake(MarginX, 3*MarginY + ButtonHeight, ButtonWidth, ButtonHeight)
self.view.addSubview(titleToastBtn)
var imageToastBtn = self.quickAddButtonWithTitle("Image Toast", target: self, action: Selector("handleImageToastClicked:"))
imageToastBtn.frame = CGRectMake(MarginX, 4*MarginY + 2*ButtonHeight, ButtonWidth, ButtonHeight)
self.view.addSubview(imageToastBtn)
var showActivityBtn = self.quickAddButtonWithTitle("Show Activity", target: self, action: Selector("showActivity"))
showActivityBtn.frame = CGRectMake(MarginX, 5*MarginY + 3*ButtonHeight, ButtonWidth, ButtonHeight)
self.view.addSubview(showActivityBtn)
var hideActivityBtn = self.quickAddButtonWithTitle("Hide Activity", target: self, action: Selector("hideActivity"))
hideActivityBtn.frame = CGRectMake(MarginX, 6*MarginY + 6*ButtonHeight, ButtonWidth, ButtonHeight)
self.view.addSubview(hideActivityBtn)
}
// handle events
func handleSingleToastClicked(sender: UIButton) {
self.view.makeToast(message: sender.titleForState(.Normal)!)
}
func handleTitleToastClicked(sender: UIButton) {
self.view.makeToast(message: sender.titleForState(.Normal)!, duration: 2, position: HRToastPositionTop, title: "<Title>")
}
func handleImageToastClicked(sender: UIButton) {
var image = UIImage(named: "swift-logo.png")
self.view.makeToast(message: sender.titleForState(.Normal)!, duration: 2, position: "center", title: "Image!", image: image!)
}
func showActivity() {
self.view.makeToastActivity()
}
func hideActivity() {
self.view.hideToastActivity()
}
// ui helper
func quickAddButtonWithTitle(title: String, target: AnyObject!, action: Selector) -> UIButton {
var ret = UIButton.buttonWithType(.Custom) as! UIButton
ret.setTitle(title, forState: .Normal)
ret.setTitleColor(UIColor.redColor(), forState: .Normal)
ret.addTarget(target, action: action, forControlEvents: .TouchUpInside)
return ret
}
}
| 80ca6e8110e31d619da46d64e397a902 | 38.759036 | 136 | 0.673939 | false | false | false | false |
1170197998/SinaWeibo | refs/heads/master | SFWeiBo/SFWeiBo/Classes/Home/User.swift | apache-2.0 | 1 | //
// User.swift
// SFWeiBo
//
// Created by mac on 16/4/20.
// Copyright © 2016年 ShaoFeng. All rights reserved.
//
import UIKit
class User: NSObject {
/// 用户ID
var id: Int = 0
/// 友好显示名称
var name: String?
/// 用户头像地址(中图),50×50像素
var profile_image_url: String? {
didSet {
if let urlStr = profile_image_url {
imageUrl = NSURL(string: urlStr)
}
}
}
/// 粉丝数
var followers_count: Int = 0
/// 关注数
var friends_count: Int = 0
/// 认证原因
var verified_reason: String?
///用于保存用户头像的URL
var imageUrl: NSURL?
/// 时候是认证, true是, false不是
var verified: Bool = false
/// 用户的认证类型,-1:没有认证,0,认证用户,2,3,5: 企业认证,220: 达人
var verified_type: Int = -1 {
//数据请求下来后根据认证类型确定认证图标
didSet {
switch verified_type {
case 0:verifiedImage = UIImage(named: "avatar_vip")
case 2,3,5: verifiedImage = UIImage(named: "avatar_enterprise_vip")
case 220: verifiedImage = UIImage(named: "avatar_grassroot")
default: verifiedImage = nil
}
}
}
///保存当前用户的认证图片
var verifiedImage: UIImage?
///会员等级图像,如果属性是内置类型,必须指定初始值,不然不会分配内存空间,无法被赋值
var mbrank: Int = 0 {
didSet {
if mbrank > 0 && mbrank < 7 {
mbrankImage = UIImage(named: "common_icon_membership_level" + "\(mbrank)")
}
}
}
var mbrankImage: UIImage?
// 字典转模型
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
// 打印当前模型
var properties = ["id", "name", "profile_image_url", "verified", "verified_type"]
override var description: String {
let dict = dictionaryWithValuesForKeys(properties)
return "\(dict)"
}
}
| 4b7c3120fdeb091fbd62c5fb4b804374 | 24.128205 | 90 | 0.545918 | false | false | false | false |
ccloveswift/CLSCommon | refs/heads/master | Classes/UI/class_NavigationController.swift | mit | 1 | //
// extension_navigation.swift
// Pods
//
// Created by TT on 2017/1/7.
// Copyright © 2017年 TT. All rights reserved.
//
import Foundation
import UIKit
class class_NavigationController : UINavigationController, UINavigationBarDelegate
{
func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
if let delegate = self.topViewController as? UINavigationBarDelegate {
let ret = delegate.navigationBar?(navigationBar, shouldPop: item)
return ret ?? true
}
return true
}
func navigationBar(_ navigationBar: UINavigationBar, didPop item: UINavigationItem) {
if let delegate = self.topViewController as? UINavigationBarDelegate {
delegate.navigationBar?(navigationBar, didPop: item)
}
}
func navigationBar(_ navigationBar: UINavigationBar, shouldPush item: UINavigationItem) -> Bool {
if let delegate = self.topViewController as? UINavigationBarDelegate {
let ret = delegate.navigationBar?(navigationBar, shouldPush: item)
return ret ?? true
}
return true
}
func navigationBar(_ navigationBar: UINavigationBar, didPush item: UINavigationItem) {
if let delegate = self.topViewController as? UINavigationBarDelegate {
delegate.navigationBar?(navigationBar, didPush: item)
}
}
}
| 634fd031da39024f2a5fdcc786e594c1 | 29.612245 | 101 | 0.64 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | stdlib/public/SDK/AVFoundation/AVCaptureDevice.swift | apache-2.0 | 6 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import AVFoundation // Clang module
import Foundation
#if os(iOS)
public protocol _AVCaptureDeviceFormatSupportedColorSpaces {
@available(iOS, introduced: 10.0)
var __supportedColorSpaces: [NSNumber] { get }
}
extension _AVCaptureDeviceFormatSupportedColorSpaces {
@available(swift, obsoleted: 4.0)
@available(iOS, introduced: 10.0)
@nonobjc
public var supportedColorSpaces: [NSNumber]! {
return __supportedColorSpaces
}
@available(swift, introduced: 4.0)
@available(iOS, introduced: 10.0)
@nonobjc
public var supportedColorSpaces: [AVCaptureColorSpace] {
return __supportedColorSpaces.map { AVCaptureColorSpace(rawValue: $0.intValue)! }
}
}
@available(iOS, introduced: 10.0)
extension AVCaptureDevice.Format : _AVCaptureDeviceFormatSupportedColorSpaces {
}
#endif
| f12f07e0a7951340e843a2fd0b181fce | 28.777778 | 85 | 0.658209 | false | false | false | false |
iosyoujian/SwiftTask | refs/heads/swift/2.0 | SwiftTask/_StateMachine.swift | mit | 4 | //
// _StateMachine.swift
// SwiftTask
//
// Created by Yasuhiro Inami on 2015/01/21.
// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved.
//
import Foundation
///
/// fast, naive event-handler-manager in replace of ReactKit/SwiftState (dynamic but slow),
/// introduced from SwiftTask 2.6.0
///
/// see also: https://github.com/ReactKit/SwiftTask/pull/22
///
internal class _StateMachine<Progress, Value, Error>
{
internal typealias ErrorInfo = Task<Progress, Value, Error>.ErrorInfo
internal typealias ProgressTupleHandler = Task<Progress, Value, Error>._ProgressTupleHandler
internal let weakified: Bool
internal let state: _Atomic<TaskState>
internal let progress: _Atomic<Progress?> = _Atomic(nil) // NOTE: always nil if `weakified = true`
internal let value: _Atomic<Value?> = _Atomic(nil)
internal let errorInfo: _Atomic<ErrorInfo?> = _Atomic(nil)
internal let configuration = TaskConfiguration()
/// wrapper closure for `_initClosure` to invoke only once when started `.Running`,
/// and will be set to `nil` afterward
internal var initResumeClosure: _Atomic<(Void -> Void)?> = _Atomic(nil)
private lazy var _progressTupleHandlers = _Handlers<ProgressTupleHandler>()
private lazy var _completionHandlers = _Handlers<Void -> Void>()
private var _lock = _RecursiveLock()
internal init(weakified: Bool, paused: Bool)
{
self.weakified = weakified
self.state = _Atomic(paused ? .Paused : .Running)
}
internal func addProgressTupleHandler(inout token: _HandlerToken?, _ progressTupleHandler: ProgressTupleHandler) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if self.state.rawValue == .Running || self.state.rawValue == .Paused {
token = self._progressTupleHandlers.append(progressTupleHandler)
return token != nil
}
else {
return false
}
}
internal func removeProgressTupleHandler(handlerToken: _HandlerToken?) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if let handlerToken = handlerToken {
let removedHandler = self._progressTupleHandlers.remove(handlerToken)
return removedHandler != nil
}
else {
return false
}
}
internal func addCompletionHandler(inout token: _HandlerToken?, _ completionHandler: Void -> Void) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if self.state.rawValue == .Running || self.state.rawValue == .Paused {
token = self._completionHandlers.append(completionHandler)
return token != nil
}
else {
return false
}
}
internal func removeCompletionHandler(handlerToken: _HandlerToken?) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if let handlerToken = handlerToken {
let removedHandler = self._completionHandlers.remove(handlerToken)
return removedHandler != nil
}
else {
return false
}
}
internal func handleProgress(progress: Progress)
{
self._lock.lock()
defer { self._lock.unlock() }
if self.state.rawValue == .Running {
let oldProgress = self.progress.rawValue
// NOTE: if `weakified = false`, don't store progressValue for less memory footprint
if !self.weakified {
self.progress.rawValue = progress
}
for handler in self._progressTupleHandlers {
handler(oldProgress: oldProgress, newProgress: progress)
}
}
}
internal func handleFulfill(value: Value)
{
self._lock.lock()
defer { self._lock.unlock() }
let (_, updated) = self.state.tryUpdate { $0 == .Running ? (.Fulfilled, true) : ($0, false) }
if updated {
self.value.rawValue = value
self._finish()
}
}
internal func handleRejectInfo(errorInfo: ErrorInfo)
{
self._lock.lock()
defer { self._lock.unlock() }
let toState = errorInfo.isCancelled ? TaskState.Cancelled : .Rejected
let (_, updated) = self.state.tryUpdate { $0 == .Running || $0 == .Paused ? (toState, true) : ($0, false) }
if updated {
self.errorInfo.rawValue = errorInfo
self._finish()
}
}
internal func handlePause() -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
let (_, updated) = self.state.tryUpdate { $0 == .Running ? (.Paused, true) : ($0, false) }
if updated {
self.configuration.pause?()
return true
}
else {
return false
}
}
internal func handleResume() -> Bool
{
self._lock.lock()
if let initResumeClosure = self.initResumeClosure.update({ _ in nil }) {
self.state.rawValue = .Running
self._lock.unlock()
//
// NOTE:
// Don't use `_lock` here so that dispatch_async'ed `handleProgress` inside `initResumeClosure()`
// will be safely called even when current thread goes into sleep.
//
initResumeClosure()
//
// Comment-Out:
// Don't call `configuration.resume()` when lazy starting.
// This prevents inapropriate starting of upstream in ReactKit.
//
//self.configuration.resume?()
return true
}
else {
let resumed = _handleResume()
self._lock.unlock()
return resumed
}
}
private func _handleResume() -> Bool
{
let (_, updated) = self.state.tryUpdate { $0 == .Paused ? (.Running, true) : ($0, false) }
if updated {
self.configuration.resume?()
return true
}
else {
return false
}
}
internal func handleCancel(error: Error? = nil) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
let (_, updated) = self.state.tryUpdate { $0 == .Running || $0 == .Paused ? (.Cancelled, true) : ($0, false) }
if updated {
self.errorInfo.rawValue = ErrorInfo(error: error, isCancelled: true)
self._finish()
return true
}
else {
return false
}
}
private func _finish()
{
for handler in self._completionHandlers {
handler()
}
self._progressTupleHandlers.removeAll()
self._completionHandlers.removeAll()
self.configuration.finish()
self.initResumeClosure.rawValue = nil
self.progress.rawValue = nil
}
}
//--------------------------------------------------
// MARK: - Utility
//--------------------------------------------------
internal struct _HandlerToken
{
internal let key: Int
}
internal struct _Handlers<T>: SequenceType
{
internal typealias KeyValue = (key: Int, value: T)
private var currentKey: Int = 0
private var elements = [KeyValue]()
internal mutating func append(value: T) -> _HandlerToken
{
self.currentKey = self.currentKey &+ 1
self.elements += [(key: self.currentKey, value: value)]
return _HandlerToken(key: self.currentKey)
}
internal mutating func remove(token: _HandlerToken) -> T?
{
for var i = 0; i < self.elements.count; i++ {
if self.elements[i].key == token.key {
return self.elements.removeAtIndex(i).value
}
}
return nil
}
internal mutating func removeAll(keepCapacity: Bool = false)
{
self.elements.removeAll(keepCapacity: keepCapacity)
}
internal func generate() -> AnyGenerator<T>
{
return anyGenerator(self.elements.map { $0.value }.generate())
}
} | f9bc97b4634a46d398db5e96ef8f0d7b | 28.617021 | 124 | 0.548198 | false | false | false | false |
wowiwj/WDayDayCook | refs/heads/master | WDayDayCook/WDayDayCook/Models/ThemeRecipe.swift | mit | 1 | //
// ThemeRecipe.swift
// WDayDayCook
//
// Created by wangju on 16/8/20.
// Copyright © 2016年 wangju. All rights reserved.
//
import UIKit
import ObjectMapper
struct ThemeRecipeList :Mappable {
var themeRecipes:[ThemeRecipe] = [ThemeRecipe]()
var theme1:[ThemeRecipe]?{
didSet{
guard let theme1 = theme1 else{
return
}
themeRecipes += theme1
}
}
var theme2:[ThemeRecipe]?{
didSet{
guard let theme2 = theme2 else{
return
}
themeRecipes += theme2
}
}
var theme3:[ThemeRecipe]?{
didSet{
guard let theme3 = theme3 else{
return
}
themeRecipes += theme3
}
}
var theme4:[ThemeRecipe]?{
didSet{
guard let theme4 = theme4 else{
return
}
themeRecipes += theme4
}
}
var theme5:[ThemeRecipe]?{
didSet{
guard let theme5 = theme5 else{
return
}
themeRecipes += theme5
}
}
var theme6:[ThemeRecipe]?{
didSet{
guard let theme6 = theme6 else{
return
}
themeRecipes += theme6
}
}
var theme7:[ThemeRecipe]?{
didSet{
guard let theme7 = theme7 else{
return
}
themeRecipes += theme7
}
}
var theme8:[ThemeRecipe]?{
didSet{
guard let theme8 = theme8 else{
return
}
themeRecipes += theme8
}
}
var headerRecipes:[ThemeRecipe]?
init?(map: Map) {
// for i in 1...8 {
// let str = "\(i).0.value"
// let object = Mapper<ThemeRecipeArray>().map(map.JSONDictionary[1])
//
// themeRecipes.append(object!)
//
// }
}
mutating func mapping(map: Map) {
headerRecipes <- map["-1"]
theme1 <- map["1"]
theme2 <- map["2"]
theme3 <- map["3"]
theme4 <- map["4"]
theme5 <- map["5"]
theme6 <- map["6"]
theme7 <- map["7"]
theme8 <- map["8"]
}
}
struct ThemeRecipeArray: Mappable {
var obj :[ThemeRecipe]?
var key = "1"
init?(map: Map) {
key = map.JSON.keys.first!
}
mutating func mapping(map: Map) {
obj <- map[key]
}
}
struct ThemeRecipe: Mappable {
var description:String?
var favorite:Bool?
var locationName:String?
var recipe_type:String?
var click_count:Int?
var favorite_count:Int?
var image_url:String?
var rid:Int?
var title:String?
var locationId:Int?
var recommend_type:String?
var recipe_id:Int?
var group_id:String?
var share_count:String?
var str_date:String?
init?(map: Map) {
}
mutating func mapping(map: Map) {
description <- map["description"]
favorite <- map["favorite"]
locationName <- map["locationName"]
recipe_type <- map["recipe_type"]
click_count <- map["click_count"]
favorite_count <- map["favorite_count"]
image_url <- map["image_url"]
rid <- map["rid"]
title <- map["title"]
locationId <- map["locationId"]
recommend_type <- map["recommend_type"]
recipe_id <- map["recipe_id"]
group_id <- map["group_id"]
share_count <- map["share_count"]
str_date <- map["str_date"]
}
}
| fef0bd0afc3ea0e88be6da43ba0f5137 | 21.423313 | 80 | 0.485363 | false | false | false | false |
gustavoavena/BandecoUnicamp | refs/heads/master | BandecoUnicamp/Refeicao.swift | mit | 1 | //
// Refeicao.swift
// BandecoUnicamp
//
// Created by Gustavo Avena on 28/08/17.
// Copyright © 2017 Gustavo Avena. All rights reserved.
//
import UIKit
import Gloss
public struct Refeicao: Gloss.JSONDecodable {
let tipo: TipoRefeicao
let arrozFeijao: String
let pratoPrincipal: String
let guarnicao: String
let pts: String
let salada: String
let sobremesa: String
let suco: String
let observacoes: String
init(tipo: TipoRefeicao, arrozFeijao: String, pratoPrincipal: String, guarnicao: String, pts: String, salada: String, sobremesa: String, suco: String, observacoes: String) {
self.tipo = tipo
self.arrozFeijao = arrozFeijao
self.pratoPrincipal = pratoPrincipal
self.guarnicao = guarnicao
self.pts = pts
self.salada = salada
self.sobremesa = sobremesa
self.suco = suco
self.observacoes = observacoes
}
public init?(json: JSON) {
guard let pratoPrincipal: String = JSONKeys.pratoPrincipal.rawValue <~~ json,
let arrozFeijao: String = JSONKeys.arrozFeijao.rawValue <~~ json,
let guarnicao: String = JSONKeys.guarnicao.rawValue <~~ json,
let pts: String = JSONKeys.pts.rawValue <~~ json,
let salada: String = JSONKeys.salada.rawValue <~~ json,
let suco: String = JSONKeys.suco.rawValue <~~ json,
let observacoes: String = JSONKeys.observacoes.rawValue <~~ json,
let sobremesa: String = JSONKeys.sobremesa.rawValue <~~ json,
let tipo: String = JSONKeys.tipo.rawValue <~~ json else {
print("problema deserializando o JSON refeicao")
return nil
}
self.pratoPrincipal = pratoPrincipal
self.guarnicao = guarnicao
self.pts = pts
self.salada = salada
self.sobremesa = sobremesa
self.suco = suco
self.observacoes = observacoes
self.arrozFeijao = arrozFeijao
switch tipo {
case TipoRefeicao.almoco.rawValue:
self.tipo = .almoco
case TipoRefeicao.jantar.rawValue:
self.tipo = .jantar
case TipoRefeicao.almocoVegetariano.rawValue:
self.tipo = .almocoVegetariano
case TipoRefeicao.jantarVegetariano.rawValue:
self.tipo = .jantarVegetariano
default:
print("nao reconheceu o tipo da refeicao")
self.tipo = .almoco
}
}
}
| 7c822c526e90733a3ffeffbe6d612a30 | 31.818182 | 177 | 0.616541 | false | false | false | false |
IBM-Swift/Kitura-net | refs/heads/master | Sources/KituraNet/FastCGI/FastCGI.swift | apache-2.0 | 1 | /*
* Copyright IBM Corporation 2016
*
* 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.
*/
/**
The "root" class for the FastCGI server implementation. A `FastCGIServer` instance can be created.
### Usage Example: ###
````swift
//Implement a `FastCGI` server.
let server = FastCGI.createServer()
````
*/
public class FastCGI {
//
// Global Constants used through FastCGI protocol implementation
//
struct Constants {
// general
//
static let FASTCGI_PROTOCOL_VERSION : UInt8 = 1
static let FASTCGI_DEFAULT_REQUEST_ID : UInt16 = 0
// FastCGI record types
//
static let FCGI_NO_TYPE : UInt8 = 0
static let FCGI_BEGIN_REQUEST : UInt8 = 1
static let FCGI_END_REQUEST : UInt8 = 3
static let FCGI_PARAMS : UInt8 = 4
static let FCGI_STDIN : UInt8 = 5
static let FCGI_STDOUT : UInt8 = 6
// sub types
//
static let FCGI_SUBTYPE_NO_TYPE : UInt8 = 99
static let FCGI_REQUEST_COMPLETE : UInt8 = 0
static let FCGI_CANT_MPX_CONN : UInt8 = 1
static let FCGI_UNKNOWN_ROLE : UInt8 = 3
// roles
//
static let FCGI_NO_ROLE : UInt16 = 99
static let FCGI_RESPONDER : UInt16 = 1
// flags
//
static let FCGI_KEEP_CONN : UInt8 = 1
// request headers of note
// we translate these into internal variables
//
static let HEADER_REQUEST_METHOD : String = "REQUEST_METHOD";
static let HEADER_REQUEST_SCHEME : String = "REQUEST_SCHEME";
static let HEADER_HTTP_HOST : String = "HTTP_HOST";
static let HEADER_REQUEST_URI : String = "REQUEST_URI";
}
//
// Exceptions
//
enum RecordErrors : Swift.Error {
case invalidType
case invalidSubType
case invalidRequestId
case invalidRole
case oversizeData
case invalidVersion
case emptyParameters
case bufferExhausted
case unsupportedRole
case internalError
case protocolError
}
/**
Create a `FastCGIServer` instance.
Provided as a convenience and for consistency
with the HTTP implementation.
- Returns: A `FastCGIServer` instance.
### Usage Example: ###
````swift
let server = FastCGI.createServer()
````
*/
public static func createServer() -> FastCGIServer {
return FastCGIServer()
}
}
| d9e83bc2d394001a26e97b86e1f1076c | 27.336449 | 98 | 0.610158 | false | false | false | false |
zSOLz/viper-base | refs/heads/master | ViperBase/ViperBase/Routers/Router.swift | mit | 1 | //
// Router.swift
// ViperBase
//
// Created by SOL on 28.04.17.
// Copyright © 2017 SOL. All rights reserved.
//
import UIKit
/**
The base class for the navigation(routing) logic in VIPER arhitecture. Basically one router is connected with one container controller like PresentableNavigationController, PresentableTabBarController and e.t.c.
All navigation logic as well as screen transition control should be kept it this 'Router' layer.
Custom router can interact with 'Views' and 'Presenters' layers to setup screens in proper way.
Custom router may contain:
- Strong references to assembly interface
- In most cases, strong references to base container controllr
- Strong references to it's child routers ('childRouters' property)
- Weak reference to its parent router
*/
open class Router: NSObject, RouterInterface {
/// All child routers references to keep tree-like application navigation structure.
/// Use *addChild(router:)* and *removeFromParent()* to modify this array.
open fileprivate(set) lazy var childRouters = [Router]()
/// The rotuer's parent, or nil if it has none
open fileprivate(set) weak var parentRouter: Router?
/// The base container controller associated with this router. Each custom router must return the ViewController's object
open var baseViewController: UIViewController {
fatalError("ViperBase.Router.baseViewController\n" +
"Abstract getter. Please override 'baseViewController' getter in child class")
}
/// The currently active (top, selected, etc.) view controller inside the container controller
open var activeViewController: UIViewController? {
fatalError("ViperBase.Router.activeViewController\n" +
"Abstract getter. Please override 'activeController' getter in child class")
}
/// Adds a router to the end of the list of child routers. Use this method to build navigation tree-like structure inside you application.
/// - parameter router: router object that should be added as child. This router should not have parent before the method call.
open func addChild(router: Router) {
if router.parentRouter != nil {
assertionFailure("ViperBase.Router.addChild(router:)\n" +
"Attempt to add child router which already has parent")
}
if childRouters.contains(router) {
assertionFailure("ViperBase.Router.addChild(router:)\n" +
"Child router already contains in children routers list")
}
childRouters.append(router)
router.parentRouter = self
}
/// Removes a router from its parent's child routers list
open func removeFromParent() {
guard let parentRouter = parentRouter else {
return
}
guard let index = parentRouter.childRouters.index(of: self) else {
assertionFailure("ViperBase.Router.removeFromParent()\n" +
"Parent router does not contain current router in children list")
self.parentRouter = nil
return
}
parentRouter.childRouters.remove(at: index)
self.parentRouter = nil
}
/// Present router modally router and add it to child routers list
/// - parameter router: router object that should be added as child. This router should not have parent before the method call.
/// - parameter animated: if presenting will be animated or not
/// - parameter completion: the closure to execute after the presentation finishes
open func presentModalRouter(_ router: Router, animated: Bool = true, completion: (()->Void)? = nil) {
addChild(router: router)
baseViewController.present(router.baseViewController, animated: true, completion: completion)
}
/// Dismiss modally presented router also remove this router from child list
/// - parameter router: child router to be dismissed
/// - parameter animated: if dismissing will be animated or not
/// - parameter completion: the closure to execute after the dismissing finishes
open func dismissModalRouter(_ router: Router, animated: Bool = true, completion: (()->Void)? = nil) {
guard router.parentRouter == self else {
assertionFailure("ViperBase.Router.dismissModalRouter(:animated:completion:)\n" +
"Unable to dismiss modal router: invalid parent router")
return
}
guard router.baseViewController == baseViewController.presentedViewController else {
assertionFailure("ViperBase.Router.dismissModalRouter(:animated:completion:)\n" +
"Unable to dismiss modal router: base view controller should be presented modally")
return
}
router.removeFromParent()
baseViewController.dismiss(animated: animated, completion: completion)
}
/// Returns first router in child list with required type or nil if not found
/// - parameter type: router's type to be found
open func childRouter<RouterType: Router>(withType type: RouterType.Type) -> RouterType? {
let router = (childRouters.first { $0 is RouterType } as? RouterType)
return router
}
/// Should current router automatically dismiss modally presented view controller or router on *closeCurrentView* method call. Override to change closing behavior. Default value is *true*.
open var shouldAutomaticallyDismissModalController: Bool {
return true
}
/// Returns *true* if the base view controller has modally presented view controller. Otherwise returns *false*.
open var hasPresentedViewController: Bool {
return (baseViewController.presentedViewController != nil)
}
// MARK: - RouterInterface
/// Close currently active view animated. Override to change default behavior.
/// By default dismiss modally presented child controller and router if presented.
/// Otherwhise calls *closeCurrentView(animated:,completion:)* for parent router if exists.
open func closeCurrentView() {
closeCurrentView(animated: true)
}
/// Close currently active view. Override to change default behavior.
/// By default dismiss modally presented child controller and router if presented.
/// Otherwhise calls *closeCurrentView(animated:,completion:)* for parent router if exists.
/// - parameter animated: indicates if closing process should be animated or not
open func closeCurrentView(animated: Bool) {
closeCurrentView(animated: animated, completion: nil)
}
/// Close currently active view. Override to change default behavior.
/// By default dismiss modally presented child controller and router if presented.
/// Otherwhise calls *closeCurrentView(animated:,completion:)* for parent router if exists.
/// - parameter animated: indicates if closing process should be animated or not
/// - parameter completion: the closure to execute after the closing finishes
open func closeCurrentView(animated: Bool, completion: (()->Void)?) {
if shouldAutomaticallyDismissModalController && hasPresentedViewController {
let router = childRouters.first { baseViewController.presentedViewController == $0.baseViewController }
if let modalRouter = router {
dismissModalRouter(modalRouter)
} else {
baseViewController.dismiss(animated: animated, completion: completion)
}
} else if let parentRouter = parentRouter {
parentRouter.closeCurrentView(animated: animated, completion: completion)
} else {
completion?()
}
}
}
| 076b0187d759ca93853b4937f37cf73f | 47.987342 | 212 | 0.693928 | false | false | false | false |
richardpiazza/SOSwift | refs/heads/master | Sources/SOSwift/ProductModelOrText.swift | mit | 1 | import Foundation
import CodablePlus
public enum ProductModelOrText: Codable {
case productModel(value: ProductModel)
case text(value: String)
public init(_ value: ProductModel) {
self = .productModel(value: value)
}
public init(_ value: String) {
self = .text(value: value)
}
public init(from decoder: Decoder) throws {
var dictionary: [String : Any]?
do {
let jsonContainer = try decoder.container(keyedBy: DictionaryKeys.self)
dictionary = try jsonContainer.decode(Dictionary<String, Any>.self)
} catch {
}
guard let jsonDictionary = dictionary else {
let container = try decoder.singleValueContainer()
let value = try container.decode(String.self)
self = .text(value: value)
return
}
guard let type = jsonDictionary[SchemaKeys.type.rawValue] as? String else {
throw SchemaError.typeDecodingError
}
let container = try decoder.singleValueContainer()
switch type {
case ProductModel.schemaName:
let value = try container.decode(ProductModel.self)
self = .productModel(value: value)
default:
throw SchemaError.typeDecodingError
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .productModel(let value):
try container.encode(value)
case .text(let value):
try container.encode(value)
}
}
public var productModel: ProductModel? {
switch self {
case .productModel(let value):
return value
default:
return nil
}
}
public var text: String? {
switch self {
case .text(let value):
return value
default:
return nil
}
}
}
| 3c6dd43e77ac0dd1ff1863197b101434 | 26.013158 | 83 | 0.558208 | false | false | false | false |
moonrailgun/OpenCode | refs/heads/master | OpenCode/Classes/UserInfo/View/UserInfoHeaderView.swift | gpl-2.0 | 1 | //
// UserInfoHeaderView.swift
// OpenCode
//
// Created by 陈亮 on 16/5/19.
// Copyright © 2016年 moonrailgun. All rights reserved.
//
import UIKit
class UserInfoHeaderView: UIView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
var headerView:UIView?
var avatar:UIImageView?
var name:UILabel?
var followers:RepoInfoView?
var following:RepoInfoView?
init(){
super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 200))
initView()
}
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func initView(){
self.headerView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 150))
headerView!.backgroundColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)
self.avatar = UIImageView(frame: CGRect(x: headerView!.frame.width/2-50, y: 10, width: 100, height: 100))
headerView?.addSubview(avatar!)
self.name = UILabel(frame: CGRect(x: 0, y: 110, width: headerView!.frame.width, height: 40))
name?.textAlignment = .Center
name?.textColor = UIColor.whiteColor()
headerView?.addSubview(name!)
self.followers = RepoInfoView(frame: CGRectMake(0, 150, headerView!.frame.width / 2, 40), name: "粉丝", value: 0)
self.following = RepoInfoView(frame: CGRectMake(headerView!.frame.width / 2, 150, headerView!.frame.width / 2, 40), name: "关注", value: 0)
self.addSubview(followers!)
self.addSubview(following!)
self.addSubview(headerView!)
}
func setData(avatar:UIImage, name:String,followersNum:Int, followingNum:Int) {
self.avatar?.image = avatar
self.name?.text = name
self.followers?.setValue(followersNum)
self.following?.setValue(followingNum)
}
}
| 78aa7b137605a6a3c7f7ee0f6ab994f3 | 29.486111 | 145 | 0.616856 | false | false | false | false |
1457792186/JWOCLibertyDemoWithPHP | refs/heads/master | Carthage/Checkouts/Charts/Source/Charts/Renderers/BarChartRenderer.swift | apache-2.0 | 30 | //
// BarChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class BarChartRenderer: BarLineScatterCandleBubbleRenderer
{
fileprivate class Buffer
{
var rects = [CGRect]()
}
open weak var dataProvider: BarChartDataProvider?
public init(dataProvider: BarChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
// [CGRect] per dataset
fileprivate var _buffers = [Buffer]()
open override func initBuffers()
{
if let barData = dataProvider?.barData
{
// Matche buffers count to dataset count
if _buffers.count != barData.dataSetCount
{
while _buffers.count < barData.dataSetCount
{
_buffers.append(Buffer())
}
while _buffers.count > barData.dataSetCount
{
_buffers.removeLast()
}
}
for i in stride(from: 0, to: barData.dataSetCount, by: 1)
{
let set = barData.dataSets[i] as! IBarChartDataSet
let size = set.entryCount * (set.isStacked ? set.stackSize : 1)
if _buffers[i].rects.count != size
{
_buffers[i].rects = [CGRect](repeating: CGRect(), count: size)
}
}
}
else
{
_buffers.removeAll()
}
}
fileprivate func prepareBuffer(dataSet: IBarChartDataSet, index: Int)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData,
let animator = animator
else { return }
let barWidthHalf = barData.barWidth / 2.0
let buffer = _buffers[index]
var bufferIndex = 0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
let phaseY = animator.phaseY
var barRect = CGRect()
var x: Double
var y: Double
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
let vals = e.yValues
x = e.x
y = e.y
if !containsStacks || vals == nil
{
let left = CGFloat(x - barWidthHalf)
let right = CGFloat(x + barWidthHalf)
var top = isInverted
? (y <= 0.0 ? CGFloat(y) : 0)
: (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted
? (y >= 0.0 ? CGFloat(y) : 0)
: (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if top > 0
{
top *= CGFloat(phaseY)
}
else
{
bottom *= CGFloat(phaseY)
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
else
{
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// fill the stack
for k in 0 ..< vals!.count
{
let value = vals![k]
if value == 0.0 && (posY == 0.0 || negY == 0.0)
{
// Take care of the situation of a 0.0 value, which overlaps a non-zero bar
y = value
yStart = y
}
else if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let left = CGFloat(x - barWidthHalf)
let right = CGFloat(x + barWidthHalf)
var top = isInverted
? (y <= yStart ? CGFloat(y) : CGFloat(yStart))
: (y >= yStart ? CGFloat(y) : CGFloat(yStart))
var bottom = isInverted
? (y >= yStart ? CGFloat(y) : CGFloat(yStart))
: (y <= yStart ? CGFloat(y) : CGFloat(yStart))
// multiply the height of the rect with the phase
top *= CGFloat(phaseY)
bottom *= CGFloat(phaseY)
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
}
}
}
open override func drawData(context: CGContext)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
for i in 0 ..< barData.dataSetCount
{
guard let set = barData.getDataSetByIndex(i) else { continue }
if set.isVisible
{
if !(set is IBarChartDataSet)
{
fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset")
}
drawDataSet(context: context, dataSet: set as! IBarChartDataSet, index: i)
}
}
}
fileprivate var _barShadowRectBuffer: CGRect = CGRect()
open func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int)
{
guard
let dataProvider = dataProvider,
let viewPortHandler = self.viewPortHandler
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
prepareBuffer(dataSet: dataSet, index: index)
trans.rectValuesToPixel(&_buffers[index].rects)
let borderWidth = dataSet.barBorderWidth
let borderColor = dataSet.barBorderColor
let drawBorder = borderWidth > 0.0
context.saveGState()
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
guard
let animator = animator,
let barData = dataProvider.barData
else { return }
let barWidth = barData.barWidth
let barWidthHalf = barWidth / 2.0
var x: Double = 0.0
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
x = e.x
_barShadowRectBuffer.origin.x = CGFloat(x - barWidthHalf)
_barShadowRectBuffer.size.width = CGFloat(barWidth)
trans.rectValueToPixel(&_barShadowRectBuffer)
if !viewPortHandler.isInBoundsLeft(_barShadowRectBuffer.origin.x + _barShadowRectBuffer.size.width)
{
continue
}
if !viewPortHandler.isInBoundsRight(_barShadowRectBuffer.origin.x)
{
break
}
_barShadowRectBuffer.origin.y = viewPortHandler.contentTop
_barShadowRectBuffer.size.height = viewPortHandler.contentHeight
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(_barShadowRectBuffer)
}
}
let buffer = _buffers[index]
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(barRect)
}
}
let isSingleColor = dataSet.colors.count == 1
if isSingleColor
{
context.setFillColor(dataSet.color(atIndex: 0).cgColor)
}
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
if !isSingleColor
{
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
context.setFillColor(dataSet.color(atIndex: j).cgColor)
}
context.fill(barRect)
if drawBorder
{
context.setStrokeColor(borderColor.cgColor)
context.setLineWidth(borderWidth)
context.stroke(barRect)
}
}
context.restoreGState()
}
open func prepareBarHighlight(
x: Double,
y1: Double,
y2: Double,
barWidthHalf: Double,
trans: Transformer,
rect: inout CGRect)
{
let left = x - barWidthHalf
let right = x + barWidthHalf
let top = y1
let bottom = y2
rect.origin.x = CGFloat(left)
rect.origin.y = CGFloat(top)
rect.size.width = CGFloat(right - left)
rect.size.height = CGFloat(bottom - top)
trans.rectValueToPixel(&rect, phaseY: animator?.phaseY ?? 1.0)
}
open override func drawValues(context: CGContext)
{
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
guard
let dataProvider = dataProvider,
let viewPortHandler = self.viewPortHandler,
let barData = dataProvider.barData,
let animator = animator
else { return }
var dataSets = barData.dataSets
let valueOffsetPlus: CGFloat = 4.5
var posOffset: CGFloat
var negOffset: CGFloat
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
for dataSetIndex in 0 ..< barData.dataSetCount
{
guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue }
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
// calculate the correct offset depending on the draw position of the value
let valueFont = dataSet.valueFont
let valueTextHeight = valueFont.lineHeight
posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus)
negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus))
if isInverted
{
posOffset = -posOffset - valueTextHeight
negOffset = -negOffset - valueTextHeight
}
let buffer = _buffers[dataSetIndex]
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
let iconsOffset = dataSet.iconsOffset
// if only single values are drawn (sum)
if !dataSet.isStacked
{
for j in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let rect = buffer.rects[j]
let x = rect.origin.x + rect.size.width / 2.0
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(rect.origin.y)
|| !viewPortHandler.isInBoundsLeft(x)
{
continue
}
let val = e.y
if dataSet.isDrawValuesEnabled
{
drawValue(
context: context,
value: formatter.stringForValue(
val,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: val >= 0.0
? (rect.origin.y + posOffset)
: (rect.origin.y + rect.size.height + negOffset),
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(j))
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
var px = x
var py = val >= 0.0
? (rect.origin.y + posOffset)
: (rect.origin.y + rect.size.height + negOffset)
px += iconsOffset.x
py += iconsOffset.y
ChartUtils.drawImage(
context: context,
image: icon,
x: px,
y: py,
size: icon.size)
}
}
}
else
{
// if we have stacks
var bufferIndex = 0
for index in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(index) as? BarChartDataEntry else { continue }
let vals = e.yValues
let rect = buffer.rects[bufferIndex]
let x = rect.origin.x + rect.size.width / 2.0
// we still draw stacked bars, but there is one non-stacked in between
if vals == nil
{
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(rect.origin.y)
|| !viewPortHandler.isInBoundsLeft(x)
{
continue
}
if dataSet.isDrawValuesEnabled
{
drawValue(
context: context,
value: formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: rect.origin.y +
(e.y >= 0 ? posOffset : negOffset),
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(index))
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
var px = x
var py = rect.origin.y +
(e.y >= 0 ? posOffset : negOffset)
px += iconsOffset.x
py += iconsOffset.y
ChartUtils.drawImage(
context: context,
image: icon,
x: px,
y: py,
size: icon.size)
}
}
else
{
// draw stack values
let vals = vals!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for k in 0 ..< vals.count
{
let value = vals[k]
var y: Double
if value == 0.0 && (posY == 0.0 || negY == 0.0)
{
// Take care of the situation of a 0.0 value, which overlaps a non-zero bar
y = value
}
else if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: 0.0, y: CGFloat(y * phaseY)))
}
trans.pointValuesToPixel(&transformed)
for k in 0 ..< transformed.count
{
let val = vals[k]
let drawBelow = (val == 0.0 && negY == 0.0 && posY > 0.0) || val < 0.0
let y = transformed[k].y + (drawBelow ? negOffset : posOffset)
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x)
{
continue
}
if dataSet.isDrawValuesEnabled
{
drawValue(
context: context,
value: formatter.stringForValue(
vals[k],
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: y,
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(index))
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
ChartUtils.drawImage(
context: context,
image: icon,
x: x + iconsOffset.x,
y: y + iconsOffset.y,
size: icon.size)
}
}
}
bufferIndex = vals == nil ? (bufferIndex + 1) : (bufferIndex + vals!.count)
}
}
}
}
}
/// Draws a value at the specified x and y position.
open func drawValue(context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: NSUIFont, align: NSTextAlignment, color: NSUIColor)
{
ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
context.saveGState()
var barRect = CGRect()
for high in indices
{
guard
let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet,
set.isHighlightEnabled
else { continue }
if let e = set.entryForXValue(high.x, closestToY: high.y) as? BarChartDataEntry
{
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
context.setFillColor(set.highlightColor.cgColor)
context.setAlpha(set.highlightAlpha)
let isStack = high.stackIndex >= 0 && e.isStacked
let y1: Double
let y2: Double
if isStack
{
if dataProvider.isHighlightFullBarEnabled
{
y1 = e.positiveSum
y2 = -e.negativeSum
}
else
{
let range = e.ranges?[high.stackIndex]
y1 = range?.from ?? 0.0
y2 = range?.to ?? 0.0
}
}
else
{
y1 = e.y
y2 = 0.0
}
prepareBarHighlight(x: e.x, y1: y1, y2: y2, barWidthHalf: barData.barWidth / 2.0, trans: trans, rect: &barRect)
setHighlightDrawPos(highlight: high, barRect: barRect)
context.fill(barRect)
}
}
context.restoreGState()
}
/// Sets the drawing position of the highlight object based on the riven bar-rect.
internal func setHighlightDrawPos(highlight high: Highlight, barRect: CGRect)
{
high.setDraw(x: barRect.midX, y: barRect.origin.y)
}
}
| 2fb931eea80cce19828322077349e584 | 36.657143 | 186 | 0.394537 | false | false | false | false |
balazs630/Bad-Jokes | refs/heads/develop | BadJokes/Custom Types/DatePart.swift | apache-2.0 | 1 | //
// Date&Time.swift
// BadJokes
//
// Created by Horváth Balázs on 2018. 03. 03..
// Copyright © 2018. Horváth Balázs. All rights reserved.
//
import Foundation
extension Date {
class DatePart {
var year: Int
var month: Int
var day: Int
init(year: Int = 1970, month: Int = 1, day: Int = 1) {
self.year = year
self.month = month
self.day = day
}
}
}
| 019700a86dc9a235f646ef6fd59ecde5 | 18.217391 | 62 | 0.531674 | false | false | false | false |
vmalakhovskiy/thisisstonemasonsmusicapp | refs/heads/master | Sources/App/Models/Token.swift | mit | 1 | import Vapor
import FluentProvider
import Crypto
final class Token: Model {
let storage = Storage()
/// The actual token
let token: String
/// The identifier of the user to which the token belongs
let userId: Identifier
/// Creates a new Token
init(string: String, user: User) throws {
token = string
userId = try user.assertExists()
}
// MARK: Row
init(row: Row) throws {
token = try row.get("token")
userId = try row.get(User.foreignIdKey)
}
func makeRow() throws -> Row {
var row = Row()
try row.set("token", token)
try row.set(User.foreignIdKey, userId)
return row
}
}
// MARK: Convenience
extension Token {
/// Generates a new token for the supplied User.
static func generate(for user: User) throws -> Token {
// generate 128 random bits using OpenSSL
let random = try Crypto.Random.bytes(count: 16)
// create and return the new token
return try Token(string: random.base64Encoded.makeString(), user: user)
}
}
// MARK: Relations
extension Token {
/// Fluent relation for accessing the user
var user: Parent<Token, User> {
return parent(id: userId)
}
}
// MARK: Preparation
extension Token: Preparation {
/// Prepares a table/collection in the database
/// for storing Tokens
static func prepare(_ database: Database) throws {
try database.create(Token.self) { builder in
builder.id()
builder.string("token")
builder.foreignId(for: User.self)
}
}
/// Undoes what was done in `prepare`
static func revert(_ database: Database) throws {
try database.delete(Token.self)
}
}
// MARK: JSON
/// Allows the token to convert to JSON.
extension Token: JSONRepresentable {
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("token", token)
return json
}
}
// MARK: HTTP
/// Allows the Token to be returned directly in route closures.
extension Token: ResponseRepresentable { }
| 91679aedfb4c2bf8943f28221a3e635c | 22.388889 | 79 | 0.620903 | false | false | false | false |
ait8/enpit-space | refs/heads/master | enpit-space/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// enpit-space
//
// Created by Kengo Yokoyama on 2015/07/17.
// Copyright (c) 2015年 Kengo Yokoyama. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Compatible for iOS7 and iOS8
if application.respondsToSelector("isRegisteredForRemoteNotifications") {
let types: UIUserNotificationType = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: types, categories: nil))
application.registerForRemoteNotifications()
} else {
application.registerForRemoteNotificationTypes(UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert)
}
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:.
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println("error: \(error)")
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let deviceToken = deviceToken.description
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(deviceToken, forKey:"deviceToken")
userDefaults.synchronize()
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
let musicNotification = NSNotification(name: "didReceiveMusicNotification", object: self, userInfo: nil)
NSNotificationCenter.defaultCenter().postNotification(musicNotification)
let nexturnNotification = NSNotification(name: "didReceiveNexturnNotification", object: self, userInfo: nil)
NSNotificationCenter.defaultCenter().postNotification(nexturnNotification)
let payloadNotification = NSNotification(name: "didReceivePayloadNotification", object: self, userInfo: userInfo)
NSNotificationCenter.defaultCenter().postNotification(payloadNotification)
switch application.applicationState {
case .Active:
println("Active")
case .Inactive:
println("Inactive")
case .Background:
println("background")
}
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
completionHandler()
}
}
| c3bbb004b15bda904255f43790f6005c | 48.384615 | 285 | 0.738763 | false | false | false | false |
toshiapp/toshi-ios-client | refs/heads/master | Toshi/Models/RLP.swift | gpl-3.0 | 1 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import Foundation
/// Implementation of RLP (Recursive Length Prefix) encoding and decoding
/// <https://github.com/ethereum/wiki/wiki/RLP>
class RLP {
enum RLPDataType {
case string
case list
}
enum RLPDecodeError: Error {
case invalidHexString
case encodedAsShortStringAlthoughSingleByteWasPossible
case lengthStartsWithZeroBytes
case longStringPrefixUsedForShortString
case longListPrefixUsedForShortList
case listLengthPrefixTooSmall
case stringTooShort
case stringEndsWithSuperfluousBytes
case unsupportedIntegerSize
}
enum RLPEncodeError: Error {
case unsupportedDataType
case lengthGreaterThanMax
}
static func decode(from hex: String) throws -> Any {
guard let data = hex.hexadecimalData else {
throw RLPDecodeError.invalidHexString
}
do {
return try decode(from: data)
} catch let error {
throw error
}
}
static func decode(from data: Data) throws -> Any {
do {
let (item, end) = try consumeItem(data, 0)
if end != data.count {
throw RLPDecodeError.stringEndsWithSuperfluousBytes
}
return item
} catch let error {
throw error
}
}
private static func consumeItem(_ rlp: Data, _ start: UInt) throws -> (Any, UInt) {
do {
let (type, length, start) = try consumeLengthPrefix(rlp, start)
return try consumePayload(rlp, type, length, start)
} catch let error {
throw error
}
}
private static func consumePayload(_ rlp: Data, _ type: RLPDataType, _ length: UInt, _ start: UInt) throws -> (Any, UInt) {
switch type {
case .string:
if rlp.count < start + length {
throw RLPDecodeError.stringTooShort
}
let string: Data
if length == 0 {
string = Data(capacity: 0)
} else {
string = Data(rlp[start..<start + length])
}
return (string, start + length)
case .list:
var items: [Any] = []
var nextItemStart = start
let end = nextItemStart + length
while nextItemStart < end {
let item: Any
do {
(item, nextItemStart) = try consumeItem(rlp, nextItemStart)
} catch let error {
throw error
}
items.append(item)
}
if nextItemStart > end {
throw RLPDecodeError.listLengthPrefixTooSmall
}
return (items, nextItemStart)
}
}
// swiftlint:disable cyclomatic_complexity - Keep code as ported over from another language rather than trying to refine it please.
// This method has a lot of short variable names. I've done this on purpose as I find it easier to parse
// most of the syntax lines easier to parse with the short names. Longer names just make it too verbose.
// Common variable naming:
// - b0 : Byte Zero
// - start : The start of the current length prefix
// - length : The length of the item the current length prefix describes
// - ll : "Length length", the length of the current length prefix field
// returns (item type, item length, item start offset)
private static func consumeLengthPrefix(_ rlp: Data, _ start: UInt) throws -> (RLPDataType, UInt, UInt) { //swiftlint:disable:this large_tuple
if rlp.count <= start {
throw RLPDecodeError.stringTooShort
}
let b0 = UInt(UInt8(rlp[Int(start)]))
if b0 < 128 { // single byte
return (.string, 1, start)
} else if b0 < 128 + 56 { // short string
if b0 - 128 == 1 {
if rlp.count <= start + 1 {
throw RLPDecodeError.stringTooShort
} else if rlp[Int(start) + 1] < 128 {
throw RLPDecodeError.encodedAsShortStringAlthoughSingleByteWasPossible
}
}
return (.string, b0 - 128, start + 1)
} else if b0 < 192 { // long string
let ll = b0 - 128 - 56 + 1
if rlp.count <= start + 1 + ll {
throw RLPDecodeError.stringTooShort
}
if rlp[Int(start) + 1] == 0 {
throw RLPDecodeError.lengthStartsWithZeroBytes
}
guard let length = UInt(bigEndianData: rlp[start + 1..<start + 1 + ll]) else {
throw RLPDecodeError.unsupportedIntegerSize
}
if length < 56 {
throw RLPDecodeError.longStringPrefixUsedForShortString
}
return (.string, length, start + 1 + ll)
} else if b0 < 192 + 56 {
return (.list, b0 - 192, start + 1)
} else {
let ll = b0 - 192 - 56 + 1
if rlp.count <= start + 1 + ll {
throw RLPDecodeError.stringTooShort
}
if rlp[Int(start) + 1] == 0 {
throw RLPDecodeError.lengthStartsWithZeroBytes
}
guard let length = UInt(bigEndianData: rlp[start + 1..<start + 1 + ll]) else {
throw RLPDecodeError.unsupportedIntegerSize
}
if length < 56 {
throw RLPDecodeError.longListPrefixUsedForShortList
}
return (.list, length, start + 1 + ll)
}
}
//swiftlint:enable cyclomatic_complexity
static func encode(_ obj: Any) throws -> Data {
let bytes: Data
let prefixOffset: UInt8
if let list = obj as? [Any] {
do {
bytes = try Data(list.map { try encode($0) }.flatMap { $0 })
} catch let err {
throw err
}
prefixOffset = 192
} else {
if let uint8 = obj as? UInt8 {
bytes = Data(bigEndianFrom: uint8)
} else if let uint16 = obj as? UInt16 {
bytes = Data(bigEndianFrom: uint16)
} else if let uint32 = obj as? UInt32 {
bytes = Data(bigEndianFrom: uint32)
} else if let uint64 = obj as? UInt64 {
bytes = Data(bigEndianFrom: uint64)
} else if let str = obj as? String {
guard let temp = str.data(using: .utf8) else {
throw RLPEncodeError.unsupportedDataType
}
bytes = temp
} else if let data = obj as? Data {
bytes = data
} else {
throw RLPEncodeError.unsupportedDataType
}
if bytes.count == 1 && bytes[0] < 128 {
return bytes
}
prefixOffset = 128
}
do {
let prefix = try lengthPrefix(UInt(bytes.count), prefixOffset)
return prefix + bytes
} catch let err {
throw err
}
}
private static func lengthPrefix(_ length: UInt, _ offset: UInt8) throws -> Data {
if length < 56 {
return Data([offset + UInt8(length)])
} else if length < UInt.max {
let lengthString = Data(bigEndianFrom: length)
return Data([offset + 56 - 1 + UInt8(lengthString.count)]) + lengthString
} else {
throw RLPEncodeError.lengthGreaterThanMax
}
}
}
extension Data {
init<T: FixedWidthInteger>(bigEndianFrom value: T) {
if value == 0 {
self.init()
return
}
var value = value.bigEndian
self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
if let paddingIndex = self.index(where: { $0 != 0 }) {
self.removeSubrange(0..<Int(paddingIndex))
} else {
self.removeAll()
}
}
}
protocol BigEndianDataConvertible {
init?(bigEndianData: Data)
}
extension BigEndianDataConvertible where Self: FixedWidthInteger {
init?(bigEndianData: Data) {
let padding = MemoryLayout<Self>.size - bigEndianData.count
let paddedBigEndianData: Data
if padding > 0 {
paddedBigEndianData = Data(count: padding) + bigEndianData
} else {
paddedBigEndianData = Data(bigEndianData)
}
self.init(bigEndian: paddedBigEndianData.withUnsafeBytes { $0.pointee })
}
}
extension UInt8: BigEndianDataConvertible {}
extension UInt16: BigEndianDataConvertible {}
extension UInt32: BigEndianDataConvertible {}
extension UInt64: BigEndianDataConvertible {}
extension UInt: BigEndianDataConvertible {}
extension Data {
func hexEncodedString() -> String {
return map { String(format: "%02hhx", $0) }.joined()
}
}
| 02733f95e05887bac3582303a73c1fc7 | 33.711191 | 146 | 0.564223 | false | false | false | false |
TomLinthwaite/SKTilemap | refs/heads/master | SKTilemapTileData.swift | mit | 1 | /*
SKTilemap
SKTilemapTileData.swift
Created by Thomas Linthwaite on 07/04/2016.
GitHub: https://github.com/TomLinthwaite/SKTilemap
Website (Guide): http://tomlinthwaite.com/
Wiki: https://github.com/TomLinthwaite/SKTilemap/wiki
YouTube: https://www.youtube.com/channel/UCAlJgYx9-Ub_dKD48wz6vMw
Twitter: https://twitter.com/Mr_Tomoso
-----------------------------------------------------------------------------------------------------------------------
MIT License
Copyright (c) 2016 Tom Linthwaite
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 SpriteKit
// MARK: SKTileData
class SKTilemapTileData : Equatable, Hashable {
// MARK: Properties
var hashValue: Int { get { return self.id.hashValue } }
/** Properties shared by all TMX object types. */
var properties: [String : String] = [:]
/** The tile datas ID. */
let id: Int
/** Returns the Tile ID you would see in Tiled. */
var rawID: Int { get { return self.id - self.tileset.firstGID } }
/** Weak pointer to the tileset this data belongs to. */
weak var tileset: SKTilemapTileset!
/** The texture used to draw tiles with this data. */
let texture: SKTexture
/** The filename of the texture used for this data. If it is empty the tileset used a spritesheet to create the
the texture for this data. */
let source: String
/** The tile IDs and durations used for animating this tile. */
var animationFrames: [(id: Int, duration: CGFloat)] = []
// MARK: Initialization
init(id: Int, texture: SKTexture, source: String = "", tileset: SKTilemapTileset) {
self.id = id
self.tileset = tileset
self.source = source
self.texture = texture
texture.filteringMode = .Nearest
}
init(id: Int, imageNamed source: String, tileset: SKTilemapTileset) {
self.id = id
self.tileset = tileset
self.source = source
texture = SKTexture(imageNamed: source)
texture.filteringMode = .Nearest
}
// MARK: Debug
func printDebugDescription() {
print("TileData: \(id), Source: \(source), Properties: \(properties)")
}
// MARK: Animation
/** Returns the animation for this tileData if it has one. The animation is created from the animationFrames property. */
func getAnimation(tilemap: SKTilemap) -> SKAction? {
if animationFrames.isEmpty {
return nil
}
var frames: [SKAction] = []
for frameData in animationFrames {
if let texture = tilemap.getTileData(id: frameData.id)?.texture {
let textureAction = SKAction.setTexture(texture)
let delayAction = SKAction.waitForDuration(NSTimeInterval(frameData.duration / 1000))
frames.append(SKAction.group([textureAction, delayAction]))
}
}
return SKAction.sequence(frames)
}
}
func ==(lhs: SKTilemapTileData, rhs: SKTilemapTileData) -> Bool {
return (lhs.hashValue == rhs.hashValue)
} | 0f9bde03ee65afc1b9bc41bdd003430f | 35.237288 | 125 | 0.629474 | false | false | false | false |
AnthonyMDev/Nimble | refs/heads/TableViewCells | Carthage/Checkouts/Commandant/Carthage/Checkouts/Nimble/Sources/Nimble/Adapters/AssertionRecorder.swift | apache-2.0 | 48 | import Foundation
/// A data structure that stores information about an assertion when
/// AssertionRecorder is set as the Nimble assertion handler.
///
/// @see AssertionRecorder
/// @see AssertionHandler
public struct AssertionRecord: CustomStringConvertible {
/// Whether the assertion succeeded or failed
public let success: Bool
/// The failure message the assertion would display on failure.
public let message: FailureMessage
/// The source location the expectation occurred on.
public let location: SourceLocation
public var description: String {
return "AssertionRecord { success=\(success), message='\(message.stringValue)', location=\(location) }"
}
}
/// An AssertionHandler that silently records assertions that Nimble makes.
/// This is useful for testing failure messages for matchers.
///
/// @see AssertionHandler
public class AssertionRecorder: AssertionHandler {
/// All the assertions that were captured by this recorder
public var assertions = [AssertionRecord]()
public init() {}
public func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) {
assertions.append(
AssertionRecord(
success: assertion,
message: message,
location: location))
}
}
extension NMBExceptionCapture {
internal func tryBlockThrows(_ unsafeBlock: () throws -> Void) throws {
var catchedError: Error?
tryBlock {
do {
try unsafeBlock()
} catch {
catchedError = error
}
}
if let error = catchedError {
throw error
}
}
}
/// Allows you to temporarily replace the current Nimble assertion handler with
/// the one provided for the scope of the closure.
///
/// Once the closure finishes, then the original Nimble assertion handler is restored.
///
/// @see AssertionHandler
public func withAssertionHandler(_ tempAssertionHandler: AssertionHandler,
file: FileString = #file,
line: UInt = #line,
closure: () throws -> Void) {
let environment = NimbleEnvironment.activeInstance
let oldRecorder = environment.assertionHandler
let capturer = NMBExceptionCapture(handler: nil, finally: ({
environment.assertionHandler = oldRecorder
}))
environment.assertionHandler = tempAssertionHandler
do {
try capturer.tryBlockThrows {
try closure()
}
} catch {
let failureMessage = FailureMessage()
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
let location = SourceLocation(file: file, line: line)
tempAssertionHandler.assert(false, message: failureMessage, location: location)
}
}
/// Captures expectations that occur in the given closure. Note that all
/// expectations will still go through to the default Nimble handler.
///
/// This can be useful if you want to gather information about expectations
/// that occur within a closure.
///
/// @param silently expectations are no longer send to the default Nimble
/// assertion handler when this is true. Defaults to false.
///
/// @see gatherFailingExpectations
public func gatherExpectations(silently: Bool = false, closure: () -> Void) -> [AssertionRecord] {
let previousRecorder = NimbleEnvironment.activeInstance.assertionHandler
let recorder = AssertionRecorder()
let handlers: [AssertionHandler]
if silently {
handlers = [recorder]
} else {
handlers = [recorder, previousRecorder]
}
let dispatcher = AssertionDispatcher(handlers: handlers)
withAssertionHandler(dispatcher, closure: closure)
return recorder.assertions
}
/// Captures failed expectations that occur in the given closure. Note that all
/// expectations will still go through to the default Nimble handler.
///
/// This can be useful if you want to gather information about failed
/// expectations that occur within a closure.
///
/// @param silently expectations are no longer send to the default Nimble
/// assertion handler when this is true. Defaults to false.
///
/// @see gatherExpectations
/// @see raiseException source for an example use case.
public func gatherFailingExpectations(silently: Bool = false, closure: () -> Void) -> [AssertionRecord] {
let assertions = gatherExpectations(silently: silently, closure: closure)
return assertions.filter { assertion in
!assertion.success
}
}
| 819f5d774daafc853f7dbcf106e0d4ae | 35.307087 | 111 | 0.67686 | false | false | false | false |
BBRick/wp | refs/heads/master | wp/Scenes/User/CustomView/ProductCollectionCell.swift | apache-2.0 | 2 | //
// ProductCollectionCell.swift
// wp
//
// Created by macbook air on 17/1/11.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
import DKNightVersion
class ProductCollectionCell: TitleItem {
@IBOutlet weak var redView: UIView!
@IBOutlet weak var productLabel: UILabel!
let selectorBtn: UIButton = UIButton()
override func awakeFromNib() {
super.awakeFromNib()
}
override func update(object: AnyObject, hiddle: Bool) {
if let model = object as? ProductModel {
productLabel.text = model.showSymbol
redView.isHidden = hiddle
selectorBtn.isSelected = hiddle ? false : true
if selectorBtn.isSelected {
productLabel.dk_textColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main)
}
else{
productLabel.textColor = UIColor(rgbHex: 0x333333)
}
}
}
}
| c8bf9fd895c13670061d2d71b37494c5 | 26.75 | 108 | 0.601602 | false | false | false | false |
liuwin7/FDCountDownView | refs/heads/master | Example/FDCountDownView/ViewController.swift | mit | 1 | //
// ViewController.swift
// FDCountDownView
//
// Created by liuwin7 on 05/10/2016.
// Copyright (c) 2016 liuwin7. All rights reserved.
//
import UIKit
import FDCountDownView
let presentAdvertisementSegueID = "presentAdvertisementSegueID"
let showLoginButtonViewController = "showLoginButtonViewController"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func prefersStatusBarHidden() -> Bool {
return false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == showLoginButtonViewController {
segue.destinationViewController.title = "Login ViewController"
}
}
}
| 1f9b712e1b6cbe8e720110105c548ad7 | 23.741935 | 81 | 0.697523 | false | false | false | false |
webim/webim-client-sdk-ios | refs/heads/master | WebimClientLibrary/Implementation/MessageStreamImpl.swift | mit | 1 | //
// MessageStreamImpl.swift
// WebimClientLibrary
//
// Created by Nikita Lazarev-Zubov on 08.08.17.
// Copyright © 2017 Webim. 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
import UIKit
/**
Class that responsible for handling full set of events inside message stream.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
final class MessageStreamImpl {
// MARK: - Properties
private let accessChecker: AccessChecker
private let currentChatMessageFactoriesMapper: MessageMapper
private let locationSettingsHolder: LocationSettingsHolder
private let messageComposingHandler: MessageComposingHandler
private let messageHolder: MessageHolder
private let sendingMessageFactory: SendingFactory
private let serverURLString: String
private let webimActions: WebimActionsImpl
private var chat: ChatItem?
private weak var chatStateListener: ChatStateListener?
private var currentOperator: OperatorImpl?
private var departmentList: [Department]?
private weak var departmentListChangeListener: DepartmentListChangeListener?
private weak var currentOperatorChangeListener: CurrentOperatorChangeListener?
private var isChatIsOpening = false
private var lastChatState: ChatItem.ChatItemState = .unknown
private var lastOperatorTypingStatus: Bool?
private weak var locationSettingsChangeListener: LocationSettingsChangeListener?
private var operatorFactory: OperatorFactory
private weak var operatorTypingListener: OperatorTypingListener?
private var onlineStatus: OnlineStatusItem = .unknown
private weak var onlineStatusChangeListener: OnlineStatusChangeListener?
private var surveyFactory: SurveyFactory
private var unreadByOperatorTimestamp: Date?
private weak var unreadByOperatorTimestampChangeListener: UnreadByOperatorTimestampChangeListener?
private var unreadByVisitorMessageCount: Int
private weak var unreadByVisitorMessageCountChangeListener: UnreadByVisitorMessageCountChangeListener?
private var unreadByVisitorTimestamp: Date?
private weak var unreadByVisitorTimestampChangeListener: UnreadByVisitorTimestampChangeListener?
private var visitSessionState: VisitSessionStateItem = .unknown
private weak var visitSessionStateListener: VisitSessionStateListener?
private var surveyController: SurveyController?
private var helloMessage: String?
private weak var helloMessageListener: HelloMessageListener?
// MARK: - Initialization
init(serverURLString: String,
currentChatMessageFactoriesMapper: MessageMapper,
sendingMessageFactory: SendingFactory,
operatorFactory: OperatorFactory,
surveyFactory: SurveyFactory,
accessChecker: AccessChecker,
webimActions: WebimActionsImpl,
messageHolder: MessageHolder,
messageComposingHandler: MessageComposingHandler,
locationSettingsHolder: LocationSettingsHolder) {
self.serverURLString = serverURLString
self.currentChatMessageFactoriesMapper = currentChatMessageFactoriesMapper
self.sendingMessageFactory = sendingMessageFactory
self.operatorFactory = operatorFactory
self.surveyFactory = surveyFactory
self.accessChecker = accessChecker
self.webimActions = webimActions
self.messageHolder = messageHolder
self.messageComposingHandler = messageComposingHandler
self.locationSettingsHolder = locationSettingsHolder
self.unreadByVisitorMessageCount = -1
}
// MARK: - Methods
func getWebimActions() -> WebimActionsImpl {
return webimActions
}
func set(visitSessionState: VisitSessionStateItem) {
let previousVisitSessionState = self.visitSessionState
self.visitSessionState = visitSessionState
isChatIsOpening = false
visitSessionStateListener?.changed(state: publicState(ofVisitSessionState: previousVisitSessionState),
to: publicState(ofVisitSessionState: visitSessionState))
}
func disableBotButtons() {
for message in self.messageHolder.getCurrentChatMessages() {
if message.disableBotButtons() {
self.messageHolder.changed(message: message)
}
}
}
func set(onlineStatus: OnlineStatusItem) {
self.onlineStatus = onlineStatus
}
func set(unreadByOperatorTimestamp: Date?) {
let previousValue = self.unreadByOperatorTimestamp
self.unreadByOperatorTimestamp = unreadByOperatorTimestamp
if previousValue != unreadByOperatorTimestamp {
unreadByOperatorTimestampChangeListener?.changedUnreadByOperatorTimestampTo(newValue: self.unreadByOperatorTimestamp)
}
}
func set(unreadByVisitorTimestamp: Date?) {
let previousValue = self.unreadByVisitorTimestamp
self.unreadByVisitorTimestamp = unreadByVisitorTimestamp
if previousValue != unreadByVisitorTimestamp {
unreadByVisitorTimestampChangeListener?.changedUnreadByVisitorTimestampTo(newValue: self.unreadByVisitorTimestamp)
}
}
func set(unreadByVisitorMessageCount: Int) {
let previousValue = self.unreadByVisitorMessageCount
self.unreadByVisitorMessageCount = unreadByVisitorMessageCount
if previousValue != unreadByVisitorMessageCount {
unreadByVisitorMessageCountChangeListener?.changedUnreadByVisitorMessageCountTo(newValue: self.unreadByVisitorMessageCount)
}
}
func changingChatStateOf(chat: ChatItem?) {
guard let chat = chat else {
self.disableBotButtons()
messageHolder.receiving(newChat: self.chat,
previousChat: nil,
newMessages: [MessageImpl]())
chatStateListener?.changed(state: publicState(ofChatState: lastChatState),
to: publicState(ofChatState: ChatItem.ChatItemState.closed))
lastChatState = ChatItem.ChatItemState.closed
let newOperator = operatorFactory.createOperatorFrom(operatorItem: nil)
let previousOperator = currentOperator
currentOperatorChangeListener?.changed(operator: previousOperator,
to: newOperator)
currentOperator = newOperator
operatorTypingListener?.onOperatorTypingStateChanged(isTyping: false)
return
}
let newOperator = operatorFactory.createOperatorFrom(operatorItem: chat.getOperator())
let newChatState = chat.getState()
if newOperator != currentOperator || lastChatState != newChatState {
self.disableBotButtons()
}
let previousChat = self.chat
self.chat = chat
messageHolder.receiving(newChat: self.chat,
previousChat: previousChat,
newMessages: currentChatMessageFactoriesMapper.mapAll(messages: chat.getMessages()))
if let newChatState = newChatState {
// Recieved chat state can be unsupported by the library.
if lastChatState != newChatState {
chatStateListener?.changed(state: publicState(ofChatState: lastChatState),
to: publicState(ofChatState: newChatState))
}
lastChatState = newChatState
}
if newOperator != currentOperator {
let previousOperator = currentOperator
currentOperator = newOperator
currentOperatorChangeListener?.changed(operator: previousOperator,
to: newOperator)
}
let operatorTypingStatus = chat.isOperatorTyping()
if lastOperatorTypingStatus != operatorTypingStatus {
operatorTypingListener?.onOperatorTypingStateChanged(isTyping: operatorTypingStatus)
}
lastOperatorTypingStatus = operatorTypingStatus
if let unreadByOperatorTimestamp = chat.getUnreadByOperatorTimestamp() {
set(unreadByOperatorTimestamp: Date(timeIntervalSince1970: unreadByOperatorTimestamp))
}
let unreadByVisitorMessageCount = chat.getUnreadByVisitorMessageCount()
set(unreadByVisitorMessageCount: unreadByVisitorMessageCount)
if let unreadByVisitorTimestamp = chat.getUnreadByVisitorTimestamp() {
set(unreadByVisitorTimestamp: Date(timeIntervalSince1970: unreadByVisitorTimestamp))
}
if chat.getReadByVisitor() == true {
set(unreadByVisitorTimestamp: nil)
}
}
func saveLocationSettingsOn(fullUpdate: FullUpdate) {
let hintsEnabled = (fullUpdate.getHintsEnabled() == true)
let previousLocationSettings = locationSettingsHolder.getLocationSettings()
let newLocationSettings = LocationSettingsImpl(hintsEnabled: hintsEnabled)
let newLocationSettingsReceived = locationSettingsHolder.receiving(locationSettings: newLocationSettings)
if newLocationSettingsReceived {
locationSettingsChangeListener?.changed(locationSettings: previousLocationSettings,
to: newLocationSettings)
}
}
func onOnlineStatusChanged(to newOnlineStatus: OnlineStatusItem) {
let previousPublicOnlineStatus = publicState(ofOnlineStatus: onlineStatus)
let newPublicOnlineStatus = publicState(ofOnlineStatus: newOnlineStatus)
if onlineStatus != newOnlineStatus {
onlineStatusChangeListener?.changed(onlineStatus: previousPublicOnlineStatus,
to: newPublicOnlineStatus)
}
onlineStatus = newOnlineStatus
}
func onReceiving(departmentItemList: [DepartmentItem]) {
var departmentList = [Department]()
let departmentFactory = DepartmentFactory(serverURLString: serverURLString)
for departmentItem in departmentItemList {
let department = departmentFactory.convert(departmentItem: departmentItem)
departmentList.append(department)
}
self.departmentList = departmentList
departmentListChangeListener?.received(departmentList: departmentList)
}
func onReceived(surveyItem: SurveyItem) {
if let surveyController = surveyController,
let survey = surveyFactory.createSurveyFrom(surveyItem: surveyItem) {
surveyController.set(survey: survey)
surveyController.nextQuestion()
}
}
func onSurveyCancelled() {
if let surveyController = surveyController {
surveyController.cancelSurvey()
}
}
func handleHelloMessage(showHelloMessage: Bool?,
chatStartAfterMessage: Bool?,
currentChatEmpty: Bool?,
helloMessageDescr: String?) {
guard helloMessageListener != nil,
let showHelloMessage = showHelloMessage,
let chatStartAfterMessage = chatStartAfterMessage,
let currentChatEmpty = currentChatEmpty,
let helloMessageDescr = helloMessageDescr else {
return
}
if showHelloMessage && chatStartAfterMessage && currentChatEmpty && messageHolder.historyMessagesEmpty() {
helloMessageListener?.helloMessage(message: helloMessageDescr)
}
}
// MARK: Private methods
private func publicState(ofChatState chatState: ChatItem.ChatItemState) -> ChatState {
switch chatState {
case .queue:
return .queue
case .chatting:
return .chatting
case .chattingWithRobot:
return .chattingWithRobot
case .closed:
return .closed
case .closedByVisitor:
return .closedByVisitor
case .closedByOperator:
return .closedByOperator
case .invitation:
return .invitation
default:
return .unknown
}
}
private func publicState(ofOnlineStatus onlineStatus: OnlineStatusItem) -> OnlineStatus {
switch onlineStatus {
case .busyOffline:
return .busyOffline
case .busyOnline:
return .busyOnline
case .offline:
return .offline
case .online:
return .online
default:
return .unknown
}
}
private func publicState(ofVisitSessionState visitSessionState: VisitSessionStateItem) -> VisitSessionState {
switch visitSessionState {
case .chat:
return .chat
case .departmentSelection:
return .departmentSelection
case .idle:
return .idle
case .idleAfterChat:
return .idleAfterChat
case .offlineMessage:
return .offlineMessage
default:
return .unknown
}
}
}
// MARK: - MessageStream
extension MessageStreamImpl: MessageStream {
// MARK: - Methods
func getVisitSessionState() -> VisitSessionState {
return publicState(ofVisitSessionState: visitSessionState)
}
func getChatState() -> ChatState {
return publicState(ofChatState: lastChatState)
}
func getChatId() -> Int? {
return chat?.getId()
}
func getUnreadByOperatorTimestamp() -> Date? {
return unreadByOperatorTimestamp
}
func getUnreadByVisitorMessageCount() -> Int {
return (unreadByVisitorMessageCount > 0) ? unreadByVisitorMessageCount : 0
}
func getUnreadByVisitorTimestamp() -> Date? {
return unreadByVisitorTimestamp
}
func getDepartmentList() -> [Department]? {
return departmentList
}
func getLocationSettings() -> LocationSettings {
return locationSettingsHolder.getLocationSettings()
}
func getCurrentOperator() -> Operator? {
return currentOperator
}
func getLastRatingOfOperatorWith(id: String) -> Int {
// rating in [-2, 2]
let rating = chat?.getOperatorIDToRate()?[id]
// rating in [1, 5]
return (rating?.getRating() ?? -3) + 3
}
func rateOperatorWith(id: String?, byRating rating: Int, completionHandler: RateOperatorCompletionHandler?) throws {
try rateOperatorWith(id: id, note: nil, byRating: rating, completionHandler: completionHandler)
}
func rateOperatorWith(id: String?,
note: String?,
byRating rating: Int,
completionHandler: RateOperatorCompletionHandler?) throws {
guard rating >= 1,
rating <= 5 else {
WebimInternalLogger.shared.log(entry: "Rating must be within from 1 to 5 range. Passed value: \(rating)",
verbosityLevel: .warning)
return
}
try accessChecker.checkAccess()
webimActions.rateOperatorWith(id: id,
rating: (rating - 3), // Accepted range: (-2, -1, 0, 1, 2).
visitorNote: note,
completionHandler: completionHandler)
}
func respondSentryCall(id: String) throws {
try accessChecker.checkAccess()
webimActions.respondSentryCall(id: id)
}
func searchStreamMessagesBy(query: String, completionHandler: SearchMessagesCompletionHandler?) {
do {
try accessChecker.checkAccess()
webimActions.searchMessagesBy(query: query) { data in
let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any?]
if let data = json?["data"] as? [String: Any?] {
let itemsCount = data["count"] as? Int
if itemsCount == 0 {
completionHandler?.onSearchMessageSuccess(query: query, messages: [])
return
}
if let messages = data["items"] as? [[String: Any?]] {
var searchMessagesArray = [Message]()
for item in messages {
let messageItem = MessageItem(jsonDictionary: item)
if let message = self.currentChatMessageFactoriesMapper.map(message: messageItem) {
searchMessagesArray.append(message)
}
}
completionHandler?.onSearchMessageSuccess(query: query, messages: searchMessagesArray)
return
}
}
}
completionHandler?.onSearchMessageFailure(query: query)
} catch {
completionHandler?.onSearchMessageFailure(query: query)
}
}
func startChat() throws {
try startChat(departmentKey: nil,
firstQuestion: nil)
}
func startChat(firstQuestion: String?) throws {
try startChat(departmentKey: nil,
firstQuestion: firstQuestion)
}
func startChat(departmentKey: String?) throws {
try startChat(departmentKey: departmentKey,
firstQuestion: nil)
}
func startChat(customFields:String?) throws {
try startChat(departmentKey: nil, firstQuestion: nil, customFields: customFields)
}
func startChat(firstQuestion:String?, customFields: String?) throws {
try startChat(departmentKey: nil, firstQuestion: firstQuestion, customFields: customFields)
}
func startChat(departmentKey: String?, customFields: String?) throws {
try startChat(departmentKey: departmentKey, firstQuestion: nil, customFields: customFields)
}
func startChat(departmentKey: String?, firstQuestion: String?) throws {
try startChat(departmentKey: departmentKey, firstQuestion: firstQuestion, customFields: nil)
}
func startChat(departmentKey: String?,
firstQuestion: String?,
customFields: String?) throws {
try accessChecker.checkAccess()
if (lastChatState.isClosed()
|| (visitSessionState == .offlineMessage))
&& !isChatIsOpening {
webimActions.startChat(withClientSideID: ClientSideID.generateClientSideID(),
firstQuestion: firstQuestion,
departmentKey: departmentKey,
customFields: customFields)
}
}
func closeChat() throws {
try accessChecker.checkAccess()
if !lastChatState.isClosed() {
webimActions.closeChat()
}
}
func setVisitorTyping(draftMessage: String?) throws {
try accessChecker.checkAccess()
messageComposingHandler.setComposing(draft: draftMessage)
}
func send(message: String) throws -> String {
return try sendMessageInternally(messageText: message)
}
func send(message: String, completionHandler: SendMessageCompletionHandler?) throws -> String {
return try sendMessageInternally(messageText: message, sendMessageCompletionHandler: completionHandler)
}
func send(message: String,
data: [String: Any]?,
completionHandler: DataMessageCompletionHandler?) throws -> String {
if let data = data,
let jsonData = try? JSONSerialization.data(withJSONObject: data as Any,
options: []) {
let jsonString = String(data: jsonData,
encoding: .utf8)
return try sendMessageInternally(messageText: message,
dataJSONString: jsonString,
dataMessageCompletionHandler: completionHandler)
} else {
return try sendMessageInternally(messageText: message)
}
}
func send(message: String,
isHintQuestion: Bool?) throws -> String {
return try sendMessageInternally(messageText: message,
isHintQuestion: isHintQuestion)
}
func send(file: Data,
filename: String,
mimeType: String,
completionHandler: SendFileCompletionHandler?) throws -> String {
try accessChecker.checkAccess()
var file = file,
filename = filename,
mimeType = mimeType
try startChat()
let messageID = ClientSideID.generateClientSideID()
messageHolder.sending(message: sendingMessageFactory.createFileMessageToSendWith(id: messageID))
if mimeType == "image/heic" || mimeType == "image/heif" {
guard let image = UIImage(data: file),
let imageData = image.jpegData(compressionQuality: 0.5)
else {
print("Error with heic/heif"); return String()
}
mimeType = "image/jpeg"
file = imageData
var nameComponents = filename.components(separatedBy: ".")
if nameComponents.count > 1 {
nameComponents.removeLast()
filename = nameComponents.joined(separator: ".")
}
filename += ".jpeg"
}
webimActions.send(file: file,
filename: filename,
mimeType: mimeType,
clientSideID: messageID,
completionHandler: SendFileCompletionHandlerWrapper(sendFileCompletionHandler: completionHandler,
messageHolder: messageHolder),
uploadFileToServerCompletionHandler: nil)
return messageID
}
func send(uploadedFiles: [UploadedFile],
completionHandler: SendFilesCompletionHandler?) throws -> String {
try accessChecker.checkAccess()
try startChat()
let messageID = ClientSideID.generateClientSideID()
if uploadedFiles.isEmpty {
completionHandler?.onFailure(messageID: messageID, error: .fileNotFound)
return messageID
}
if uploadedFiles.count > 10 {
completionHandler?.onFailure(messageID: messageID, error: .maxFilesCountPerMessage)
return messageID
}
var message = "[\(uploadedFiles[0].description)"
for uploadFile in uploadedFiles.dropFirst() {
message += ", \(uploadFile.description)"
}
message += "]"
messageHolder.sending(message: sendingMessageFactory.createFileMessageToSendWith(id: messageID))
webimActions.sendFiles(message: message,
clientSideID: messageID,
isHintQuestion: false,
sendFilesCompletionHandler: completionHandler)
return messageID
}
func uploadFilesToServer(file: Data,
filename: String,
mimeType: String,
completionHandler: UploadFileToServerCompletionHandler?) throws -> String {
try accessChecker.checkAccess()
var file = file
var filename = filename
var mimeType = mimeType
try startChat()
let messageID = ClientSideID.generateClientSideID()
if mimeType == "image/heic" || mimeType == "image/heif" {
guard let image = UIImage(data: file),
let imageData = image.jpegData(compressionQuality: 0.5)
else {
print("Error with heic/heif"); return String()
}
mimeType = "image/jpeg"
file = imageData
var nameComponents = filename.components(separatedBy: ".")
if nameComponents.count > 1 {
nameComponents.removeLast()
filename = nameComponents.joined(separator: ".")
}
filename += ".jpeg"
}
webimActions.send(file: file,
filename: filename,
mimeType: mimeType,
clientSideID: messageID, completionHandler: nil,
uploadFileToServerCompletionHandler: completionHandler)
return messageID
}
func deleteUploadedFiles(fileGuid: String,
completionHandler: DeleteUploadedFileCompletionHandler?) throws {
try accessChecker.checkAccess()
webimActions.deleteUploadedFile(fileGuid: fileGuid,
completionHandler: completionHandler)
}
func sendKeyboardRequest(button: KeyboardButton,
message: Message,
completionHandler: SendKeyboardRequestCompletionHandler?) throws {
try accessChecker.checkAccess()
webimActions.sendKeyboardRequest(buttonId: button.getID(),
messageId: message.getCurrentChatID() ?? "",
completionHandler: completionHandler)
}
func sendKeyboardRequest(buttonID: String,
messageCurrentChatID: String,
completionHandler: SendKeyboardRequestCompletionHandler?) throws {
try accessChecker.checkAccess()
webimActions.sendKeyboardRequest(buttonId: buttonID,
messageId: messageCurrentChatID,
completionHandler: completionHandler)
}
func sendSticker(withId stickerId: Int, completionHandler: SendStickerCompletionHandler?) throws {
try accessChecker.checkAccess()
let messageID = ClientSideID.generateClientSideID()
messageHolder.sending(message: sendingMessageFactory.createStickerMessageToSendWith(id: messageID, stickerId: stickerId))
webimActions.sendSticker(stickerId: stickerId, clientSideId: messageID, completionHandler: completionHandler)
}
func getRawConfig(forLocation location: String, completionHandler: RawLocationConfigCompletionHandler?) throws {
try accessChecker.checkAccess()
webimActions.getRawConfig(forLocation: location) {
data in
if let data = data {
let json = try? JSONSerialization.jsonObject(with: data,
options: [])
if let locationSettingsResponseDictionary = json as? [String: Any?] {
let locationSettingsResponse = LocationSettingsResponse(jsonDictionary: locationSettingsResponseDictionary)
completionHandler?.onSuccess(rawLocationConfig: locationSettingsResponse.getLocationSettings())
}
} else {
completionHandler?.onFailure()
}
}
}
func updateWidgetStatus(data: String) throws {
try accessChecker.checkAccess()
webimActions.updateWidgetStatusWith(data: data)
}
func reply(message: String, repliedMessage: Message) throws -> String? {
try startChat()
guard repliedMessage.canBeReplied() else {
return nil
}
let messageID = ClientSideID.generateClientSideID()
messageHolder.sending(message: sendingMessageFactory.createTextMessageToSendWithQuoteWith(id: messageID,
text: message,
repliedMessage: repliedMessage))
webimActions.replay(message: message,
clientSideID: messageID,
quotedMessageID: repliedMessage.getCurrentChatID() ?? repliedMessage.getID())
return messageID
}
func edit(message: Message, text: String, completionHandler: EditMessageCompletionHandler?) throws -> Bool {
try accessChecker.checkAccess()
if !message.canBeEdited() {
return false
}
let id = message.getID()
let oldMessage = messageHolder.changing(messageID: id, message: text)
if let oldMessage = oldMessage {
webimActions.send(message: text,
clientSideID: id,
dataJSONString: nil,
isHintQuestion: false,
dataMessageCompletionHandler: nil, editMessageCompletionHandler: EditMessageCompletionHandlerWrapper(editMessageCompletionHandler: completionHandler,
messageHolder: messageHolder,
message: oldMessage), sendMessageCompletionHandler: nil)
return true
}
return false
}
func react(message: Message, reaction: ReactionString, completionHandler: ReactionCompletionHandler?) throws -> Bool {
try accessChecker.checkAccess()
if !message.canVisitorReact() || !(message.getVisitorReaction() == nil || message.canVisitorChangeReaction()) {
return false
}
let id = message.getID()
webimActions.sendReaction(reaction: reaction,
clientSideId: id,
completionHandler: completionHandler)
return true
}
func delete(message: Message, completionHandler: DeleteMessageCompletionHandler?) throws -> Bool {
try accessChecker.checkAccess()
if !message.canBeEdited() {
return false
}
let id = message.getID()
let oldMessage = messageHolder.changing(messageID: id, message: nil)
if let oldMessage = oldMessage {
webimActions.delete(clientSideID: id,
completionHandler: DeleteMessageCompletionHandlerWrapper(deleteMessageCompletionHandler: completionHandler,
messageHolder: messageHolder,
message: oldMessage))
return true
}
return false
}
func setChatRead() throws {
try accessChecker.checkAccess()
webimActions.setChatRead()
}
func sendDialogTo(emailAddress: String,
completionHandler: SendDialogToEmailAddressCompletionHandler?) throws {
try accessChecker.checkAccess()
if !lastChatState.isClosed() {
webimActions.sendDialogTo(emailAddress: emailAddress, completionHandler: completionHandler)
} else {
completionHandler?.onFailure(error: .noChat)
}
}
func set(prechatFields: String) throws {
try accessChecker.checkAccess()
webimActions.set(prechatFields: prechatFields)
}
func newMessageTracker(messageListener: MessageListener) throws -> MessageTracker {
try accessChecker.checkAccess()
return try messageHolder.newMessageTracker(withMessageListener: messageListener) as MessageTracker
}
func send(surveyAnswer: String, completionHandler: SendSurveyAnswerCompletionHandler?) throws {
try accessChecker.checkAccess()
guard let surveyController = surveyController,
let survey = surveyController.getSurvey() else { return }
let formID = surveyController.getCurrentFormID()
let questionID = surveyController.getCurrentQuestionPointer()
let surveyID = survey.getID()
webimActions.sendQuestionAnswer(surveyID: surveyID,
formID: formID,
questionID: questionID,
surveyAnswer: surveyAnswer,
sendSurveyAnswerCompletionHandler: SendSurveyAnswerCompletionHandlerWrapper(surveyController: surveyController,
sendSurveyAnswerCompletionHandler: completionHandler))
}
func closeSurvey(completionHandler: SurveyCloseCompletionHandler?) throws {
try accessChecker.checkAccess()
guard let surveyController = surveyController,
let survey = surveyController.getSurvey() else { return }
webimActions.closeSurvey(surveyID: survey.getID(),
surveyCloseCompletionHandler: completionHandler)
}
func sendGeolocation(latitude: Double, longitude: Double, completionHandler: GeolocationCompletionHandler?) throws {
try accessChecker.checkAccess()
webimActions.sendGeolocation(latitude: latitude, longitude: longitude, completionHandler: completionHandler)
}
func set(visitSessionStateListener: VisitSessionStateListener) {
self.visitSessionStateListener = visitSessionStateListener
}
func set(chatStateListener: ChatStateListener) {
self.chatStateListener = chatStateListener
}
func set(currentOperatorChangeListener: CurrentOperatorChangeListener) {
self.currentOperatorChangeListener = currentOperatorChangeListener
}
func set(operatorTypingListener: OperatorTypingListener) {
self.operatorTypingListener = operatorTypingListener
}
func set(departmentListChangeListener: DepartmentListChangeListener) {
self.departmentListChangeListener = departmentListChangeListener
}
func set(locationSettingsChangeListener: LocationSettingsChangeListener) {
self.locationSettingsChangeListener = locationSettingsChangeListener
}
func set(onlineStatusChangeListener: OnlineStatusChangeListener) {
self.onlineStatusChangeListener = onlineStatusChangeListener
}
func set(unreadByOperatorTimestampChangeListener: UnreadByOperatorTimestampChangeListener) {
self.unreadByOperatorTimestampChangeListener = unreadByOperatorTimestampChangeListener
}
func set(unreadByVisitorMessageCountChangeListener: UnreadByVisitorMessageCountChangeListener) {
self.unreadByVisitorMessageCountChangeListener = unreadByVisitorMessageCountChangeListener
}
func set(unreadByVisitorTimestampChangeListener: UnreadByVisitorTimestampChangeListener) {
self.unreadByVisitorTimestampChangeListener = unreadByVisitorTimestampChangeListener
}
func set(surveyListener: SurveyListener) {
self.surveyController = SurveyController(surveyListener: surveyListener)
}
func set(helloMessageListener: HelloMessageListener) {
self.helloMessageListener = helloMessageListener
}
func clearHistory() throws {
try accessChecker.checkAccess()
webimActions.clearHistory()
messageHolder.clearHistory()
}
// MARK: Private methods
private func sendMessageInternally(messageText: String,
dataJSONString: String? = nil,
isHintQuestion: Bool? = nil,
dataMessageCompletionHandler: DataMessageCompletionHandler? = nil,
sendMessageCompletionHandler: SendMessageCompletionHandler? = nil) throws -> String {
try startChat()
let messageID = ClientSideID.generateClientSideID()
messageHolder.sending(message: sendingMessageFactory.createTextMessageToSendWith(id: messageID,
text: messageText))
webimActions.send(message: messageText,
clientSideID: messageID,
dataJSONString: dataJSONString,
isHintQuestion: isHintQuestion,
dataMessageCompletionHandler: DataMessageCompletionHandlerWrapper(dataMessageCompletionHandler: dataMessageCompletionHandler,
messageHolder: messageHolder), editMessageCompletionHandler: nil,
sendMessageCompletionHandler: SendMessageCompletionHandlerWrapper(sendMessageCompletionHandler: sendMessageCompletionHandler, messageHolder: messageHolder))
return messageID
}
}
// MARK: -
fileprivate final class SendMessageCompletionHandlerWrapper: SendMessageCompletionHandler {
// MARK: - Properties
private let messageHolder: MessageHolder
private weak var sendMessageCompletionHandler: SendMessageCompletionHandler?
// MARK: - Initialization
init(sendMessageCompletionHandler: SendMessageCompletionHandler?,
messageHolder: MessageHolder) {
self.sendMessageCompletionHandler = sendMessageCompletionHandler
self.messageHolder = messageHolder
}
// MARK: - Methods
func onSuccess(messageID: String) {
sendMessageCompletionHandler?.onSuccess(messageID: messageID)
}
}
fileprivate final class SendFileCompletionHandlerWrapper: SendFileCompletionHandler {
// MARK: - Properties
private let messageHolder: MessageHolder
private weak var sendFileCompletionHandler: SendFileCompletionHandler?
// MARK: - Initialization
init(sendFileCompletionHandler: SendFileCompletionHandler?,
messageHolder: MessageHolder) {
self.sendFileCompletionHandler = sendFileCompletionHandler
self.messageHolder = messageHolder
}
// MARK: - Methods
func onSuccess(messageID: String) {
sendFileCompletionHandler?.onSuccess(messageID: messageID)
}
func onFailure(messageID: String,
error: SendFileError) {
messageHolder.sendingCancelledWith(messageID: messageID)
sendFileCompletionHandler?.onFailure(messageID: messageID,
error: error)
}
}
fileprivate final class DataMessageCompletionHandlerWrapper: DataMessageCompletionHandler {
// MARK: - Properties
private let messageHolder: MessageHolder
private weak var dataMessageCompletionHandler: DataMessageCompletionHandler?
// MARK: - Initialization
init(dataMessageCompletionHandler: DataMessageCompletionHandler?,
messageHolder: MessageHolder) {
self.dataMessageCompletionHandler = dataMessageCompletionHandler
self.messageHolder = messageHolder
}
// MARK: - Methods
func onSuccess(messageID: String) {
dataMessageCompletionHandler?.onSuccess(messageID : messageID)
}
func onFailure(messageID: String, error: DataMessageError) {
messageHolder.sendingCancelledWith(messageID: messageID)
dataMessageCompletionHandler?.onFailure(messageID: messageID, error: error)
}
}
fileprivate final class EditMessageCompletionHandlerWrapper: EditMessageCompletionHandler {
// MARK: - Properties
private let messageHolder: MessageHolder
private weak var editMessageCompletionHandler: EditMessageCompletionHandler?
private let message: String
// MARK: - Initialization
init(editMessageCompletionHandler: EditMessageCompletionHandler?,
messageHolder: MessageHolder,
message: String) {
self.editMessageCompletionHandler = editMessageCompletionHandler
self.messageHolder = messageHolder
self.message = message
}
// MARK: - Methods
func onSuccess(messageID: String) {
editMessageCompletionHandler?.onSuccess(messageID : messageID)
}
func onFailure(messageID: String, error: EditMessageError) {
messageHolder.changingCancelledWith(messageID: messageID, message: message)
editMessageCompletionHandler?.onFailure(messageID: messageID, error: error)
}
}
fileprivate final class DeleteMessageCompletionHandlerWrapper: DeleteMessageCompletionHandler {
// MARK: - Properties
private let messageHolder: MessageHolder
private weak var deleteMessageCompletionHandler: DeleteMessageCompletionHandler?
private let message: String
// MARK: - Initialization
init(deleteMessageCompletionHandler: DeleteMessageCompletionHandler?,
messageHolder: MessageHolder,
message: String) {
self.deleteMessageCompletionHandler = deleteMessageCompletionHandler
self.messageHolder = messageHolder
self.message = message
}
// MARK: - Methods
func onSuccess(messageID: String) {
deleteMessageCompletionHandler?.onSuccess(messageID : messageID)
}
func onFailure(messageID: String, error: DeleteMessageError) {
messageHolder.changingCancelledWith(messageID: messageID, message: message)
deleteMessageCompletionHandler?.onFailure(messageID: messageID, error: error)
}
}
| da3fcc81860d9d62ab5e881b3324ba7f | 39.638655 | 187 | 0.622185 | false | false | false | false |
Ivacker/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01101-swift-diagnosticengine-flushactivediagnostic.swift | apache-2.0 | 13 | // RUN: not %target-swift-frontend %s -parse
// 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 f<o>() -> (o, o -> o) -> o {
o m o.j = {
}
{
o) {
r }
}
p q) {
}
class m {
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
}
protocol A {
}
struct B<T : A> {
lett D : C {
func g<T where T.E == F>(f: B<T>) {
}
}
struct d<f : e, g: e where g.h == f.h> {
col P {
}
}
}
i struct c {
c a(b: Int0) {
}
protocol d : b { func b
func d(e: = { (g:A {
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
func g<T where T.E = {
}
struct D : C {
func g<T where T.E == F>(f:
| 7fcff7aa72815a19762eebfd6bef0934 | 14.152174 | 87 | 0.542324 | false | false | false | false |
i-schuetz/SwiftCharts | refs/heads/master | SwiftCharts/Layers/ChartPointsViewsLayer.swift | apache-2.0 | 1 | //
// ChartPointsViewsLayer.swift
// SwiftCharts
//
// Created by ischuetz on 27/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public enum ChartPointsViewsLayerMode {
case scaleAndTranslate, translate, custom
}
open class ChartPointsViewsLayer<T: ChartPoint, U: UIView>: ChartPointsLayer<T> {
public typealias ChartPointViewGenerator = (_ chartPointModel: ChartPointLayerModel<T>, _ layer: ChartPointsViewsLayer<T, U>, _ chart: Chart) -> U?
public typealias ViewWithChartPoint = (view: U, chartPointModel: ChartPointLayerModel<T>)
open internal(set) var viewsWithChartPoints: [ViewWithChartPoint] = []
fileprivate let delayBetweenItems: Float = 0
let viewGenerator: ChartPointViewGenerator
fileprivate var conflictSolver: ChartViewsConflictSolver<T, U>?
fileprivate let mode: ChartPointsViewsLayerMode
// For cases when layers behind re-add subviews on pan/zoom, ensure views of this layer stays on front
// TODO z ordering
fileprivate let keepOnFront: Bool
public let delayInit: Bool
public var customTransformer: ((ChartPointLayerModel<T>, UIView, ChartPointsViewsLayer<T, U>) -> Void)?
fileprivate let clipViews: Bool
public init(xAxis: ChartAxis, yAxis: ChartAxis, chartPoints:[T], viewGenerator: @escaping ChartPointViewGenerator, conflictSolver: ChartViewsConflictSolver<T, U>? = nil, displayDelay: Float = 0, delayBetweenItems: Float = 0, mode: ChartPointsViewsLayerMode = .scaleAndTranslate, keepOnFront: Bool = true, delayInit: Bool = false, clipViews: Bool = true) {
self.viewGenerator = viewGenerator
self.conflictSolver = conflictSolver
self.mode = mode
self.keepOnFront = keepOnFront
self.delayInit = delayInit
self.clipViews = clipViews
super.init(xAxis: xAxis, yAxis: yAxis, chartPoints: chartPoints, displayDelay: displayDelay)
}
override open func display(chart: Chart) {
super.display(chart: chart)
if !delayInit {
initViews(chart)
}
}
open func initViews(_ chart: Chart) {
viewsWithChartPoints = generateChartPointViews(chartPointModels: chartPointsModels, chart: chart)
if delayBetweenItems =~ 0 {
for v in viewsWithChartPoints {addSubview(chart, view: v.view)}
} else {
for viewWithChartPoint in viewsWithChartPoints {
let view = viewWithChartPoint.view
addSubview(chart, view: view)
}
}
}
func addSubview(_ chart: Chart, view: UIView) {
switch mode {
case .scaleAndTranslate:
chart.addSubview(view)
case .translate: fallthrough
case .custom:
if !clipViews {
chart.addSubviewNoTransformUnclipped(view)
} else {
chart.addSubviewNoTransform(view)
}
}
}
func reloadViews() {
guard let chart = chart else {return}
for v in viewsWithChartPoints {
v.view.removeFromSuperview()
}
display(chart: chart)
}
fileprivate func generateChartPointViews(chartPointModels: [ChartPointLayerModel<T>], chart: Chart) -> [ViewWithChartPoint] {
let viewsWithChartPoints: [ViewWithChartPoint] = chartPointsModels.compactMap {model in
if let view = viewGenerator(model, self, chart) {
return (view: view, chartPointModel: model)
} else {
return nil
}
}
conflictSolver?.solveConflicts(views: viewsWithChartPoints)
return viewsWithChartPoints
}
override open func chartPointsForScreenLoc(_ screenLoc: CGPoint) -> [T] {
return filterChartPoints{inXBounds(screenLoc.x, view: $0.view) && inYBounds(screenLoc.y, view: $0.view)}
}
override open func chartPointsForScreenLocX(_ x: CGFloat) -> [T] {
return filterChartPoints{inXBounds(x, view: $0.view)}
}
override open func chartPointsForScreenLocY(_ y: CGFloat) -> [T] {
return filterChartPoints{inYBounds(y, view: $0.view)}
}
fileprivate func filterChartPoints(_ filter: (ViewWithChartPoint) -> Bool) -> [T] {
return viewsWithChartPoints.reduce([]) {arr, viewWithChartPoint in
if filter(viewWithChartPoint) {
return arr + [viewWithChartPoint.chartPointModel.chartPoint]
} else {
return arr
}
}
}
fileprivate func inXBounds(_ x: CGFloat, view: UIView) -> Bool {
return (x > view.frame.origin.x) && (x < (view.frame.origin.x + view.frame.width))
}
fileprivate func inYBounds(_ y: CGFloat, view: UIView) -> Bool {
return (y > view.frame.origin.y) && (y < (view.frame.origin.y + view.frame.height))
}
open override func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) {
super.zoom(x, y: y, centerX: centerX, centerY: centerY)
updateForTransform()
}
open override func pan(_ deltaX: CGFloat, deltaY: CGFloat) {
super.pan(deltaX, deltaY: deltaY)
updateForTransform()
}
func updateForTransform() {
switch mode {
case .scaleAndTranslate:
updateChartPointsScreenLocations()
case .translate:
for i in 0..<viewsWithChartPoints.count {
viewsWithChartPoints[i].chartPointModel.screenLoc = modelLocToScreenLoc(x: viewsWithChartPoints[i].chartPointModel.chartPoint.x.scalar, y: viewsWithChartPoints[i].chartPointModel.chartPoint.y.scalar)
viewsWithChartPoints[i].view.center = viewsWithChartPoints[i].chartPointModel.screenLoc
}
case .custom:
for i in 0..<viewsWithChartPoints.count {
customTransformer?(viewsWithChartPoints[i].chartPointModel, viewsWithChartPoints[i].view, self)
}
}
if keepOnFront {
bringToFront()
}
}
open override func modelLocToScreenLoc(x: Double, y: Double) -> CGPoint {
switch mode {
case .scaleAndTranslate:
return super.modelLocToScreenLoc(x: x, y: y)
case .translate: fallthrough
case .custom:
return super.modelLocToContainerScreenLoc(x: x, y: y)
}
}
open func bringToFront() {
for (view, _) in viewsWithChartPoints {
view.superview?.bringSubviewToFront(view)
}
}
}
| 8856f309f5dc343fc1fa9bda5e87014f | 34.648936 | 359 | 0.622948 | false | false | false | false |
yeti/emojikeyboard | refs/heads/master | EmojiKeyboard/Classes/EKB.swift | mit | 1 | //
// EmojiKeyboard.swift
// GottaGo
//
// Created by Lee McDole on 1/30/16.
// Copyright © 2016 Yeti LLC. All rights reserved.
//
import Foundation
public protocol EKBDelegate {
func ekbButtonPressed(string: String)
}
public class EKB: NSObject, NSXMLParserDelegate, EKBInputViewDelegate {
// Views
public var ekbInputView: EKBInputView?
// Emojis
var emojiGroups: [EKBEmojiGroup]
var currentEmojiGroup: EKBEmojiGroup?
var modifiers = [String]()
private let screenSize:CGRect = UIScreen.mainScreen().bounds
public var ekbDelegate: EKBDelegate?
///////////////////////////
// Initialization functions
///////////////////////////
public override init() {
emojiGroups = [EKBEmojiGroup]()
currentEmojiGroup = nil
super.init()
processEmojiFile()
// Setup Emoji Keyboard
ekbInputView = UINib(nibName: "EKBInputView", bundle: EKBUtils.resourceBundle()).instantiateWithOwner(nil, options: nil)[0] as? EKBInputView
ekbInputView!.ekbInputViewDelegate = self
// Set our height
ekbInputView?.autoresizingMask = .None
ekbInputView?.frame = CGRectMake(0, 0, 0, 260)
}
private func processEmojiFile() {
let filename = "EmojiList"
var parser: NSXMLParser?
if let bundle = EKBUtils.resourceBundle() {
let path = bundle.pathForResource(filename, ofType: "xml")
if let path = path {
parser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: path))
}
} else {
print("Failed to find emoji list file")
}
if let parser = parser {
// Let's parse that xml!
parser.delegate = self
if !parser.parse() {
let parseError = parser.parserError!
print("Error parsing emoji list: \(parseError)")
}
if currentEmojiGroup != nil {
print("XML appeared malformed, an unclosed EmojiGroup was found")
}
}
}
func printEmojiListInfo() {
var emojiCount = 0
for group in emojiGroups {
emojiCount += group.emojis.count
}
print("Finished parsing EmojiList. Found \(emojiGroups.count) groups containing \(emojiCount) emojis")
print("Group Name Emoji Count")
var modifiableCount = 0
for group in emojiGroups {
print("\(group.name) \(group.emojis.count)")
for emoji in group.emojis {
if emoji.modifiers != nil {
modifiableCount++
}
}
}
print("Total with modifiers: \(modifiableCount)")
}
/////////////////////////////////////////
// NSXMLParserDelegate protocol functions
/////////////////////////////////////////
@objc public func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?,
qualifiedName qName: String?, attributes attributeDict: [String : String])
{
if elementName == "EmojiModifier" {
loadEmojiModifier(elementName, attributeDict: attributeDict)
} else if elementName == "EmojiGroup" {
if currentEmojiGroup != nil {
print("Unexpected new EmojiGroup found while parsing EmojiGroup")
}
currentEmojiGroup = EKBEmojiGroup(name: attributeDict["name"]!)
} else if elementName == "Emoji" {
loadEmoji(elementName, attributeDict: attributeDict)
}
}
@objc public func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?,
qualifiedName qName: String?)
{
if elementName == "EmojiGroup" {
if currentEmojiGroup == nil {
print("Unexpected end of EmojiGroup found")
}
emojiGroups.append(currentEmojiGroup!)
currentEmojiGroup = nil
}
}
///////////////////////////////
// XML Parsing Helper Functions
///////////////////////////////
private func loadEmojiModifier(elementName: String, attributeDict: [String : String]) {
let unicode = attributeDict["unicode"]
let emoji = attributeDict["emoji"]
verifyUnicodeEmojiMatch(unicode!, emoji: emoji!)
let newEmojiModifier = String(emoji!)
modifiers.append(newEmojiModifier)
}
private func loadEmoji(elementName: String, attributeDict: [String : String]) {
let unicode = attributeDict["unicode"]
let emoji = attributeDict["emoji"]
// Check if this emoji is even supported
let minVersion = attributeDict["minversion"] ?? ""
if !versionCheck(minVersion) {
return
}
verifyUnicodeEmojiMatch(unicode!, emoji: emoji!)
// Check if modifications are supported
var modifiable = false
let modifiableVersion = attributeDict["modifiableversion"] ?? "false"
if modifiableVersion != "false" {
// Might be modifiable. Check version
if versionCheck(modifiableVersion) {
modifiable = true
}
}
let newEmoji = EKBEmoji(character: emoji!, modifiers: (modifiable) ? modifiers : nil)
currentEmojiGroup!.appendEmoji(newEmoji)
}
private func versionCheck(minVersion: String) -> Bool {
var versionReqs: [Int] = minVersion.characters.split{$0 == "."}.map(String.init).map{Int($0)!} // Clean this up?
while versionReqs.count < 3 {
// Turn "8" and "8.0" into "8.0.0", for example
versionReqs.append(0)
}
let os = NSProcessInfo().operatingSystemVersion
// TODO: Maybe a more functional approach to solving this problem:
// Check major version
if versionReqs[0] < os.majorVersion {
return true
} else if versionReqs[0] > os.majorVersion {
return false
}
// Major version == requirement, must dig deeper
// Check minor version
if versionReqs[1] < os.minorVersion {
return true
} else if versionReqs[1] > os.minorVersion {
return false
}
// Minor version == requirement, must dig deeper
// Check patch version
if versionReqs[2] < os.patchVersion {
return true
} else if versionReqs[2] > os.patchVersion {
return false
}
// Major, Minor, and Patch version == requirement. We're good!
return true
}
private func verifyUnicodeEmojiMatch(unicode: String, emoji: String) -> Bool {
// Verify that the displayed emoji and the unicode value match
let unicodeStrings = unicode.characters.split{$0 == " "}.map(String.init)
var unicodeCharacters = [Character]()
for string in unicodeStrings {
// Convert unicodeStrings -> Ints -> UnicodeScalars -> Characters
let unicodeInt = Int(string, radix: 16)
unicodeCharacters.append(Character(UnicodeScalar(unicodeInt!)))
}
let unicodeEmoji = String(unicodeCharacters)
if unicodeEmoji != emoji {
print("Mismatched unicode and emoji values: \(unicode) \(emoji)")
return false
}
return true
}
//////////////////////////////////////////
// EKBInputViewDelegate protocol functions
//////////////////////////////////////////
// Action handler for whenever a button is pressed. Probably want to send a character to the UIResponder
public func buttonPressed(groupIndex: Int, index: Int) {
let emoji: String = emojiGroups[groupIndex].emojis[index].getModifiedString()
ekbDelegate?.ekbButtonPressed(emoji)
}
// Return the number of groups in this keyboard
public func getGroupCount() -> Int {
return emojiGroups.count
}
// Return the name of the specified group
public func getGroupName(groupIndex: Int) -> String {
if groupIndex >= 0 && groupIndex < emojiGroups.count {
return emojiGroups[groupIndex].name
}
return ""
}
// Return the number of items within this group
public func getItemCount(groupIndex: Int) -> Int {
if groupIndex >= 0 && groupIndex < emojiGroups.count {
return emojiGroups[groupIndex].emojis.count
}
return 0
}
// Get the emoji for a specified group and index
public func getEmojiAt(groupIndex: Int, index: Int) -> EKBEmoji? {
if groupIndex >= 0 && groupIndex < emojiGroups.count {
if index >= 0 && index < emojiGroups[groupIndex].emojis.count {
return emojiGroups[groupIndex].emojis[index]
}
}
return nil
}
}
| f51d655cbfef9e852f1083e8c88e624a | 28.911765 | 144 | 0.634464 | false | false | false | false |
harryworld/CocoaSwiftPlayer | refs/heads/master | CocoaSwiftPlayer/ViewControllers/PlaylistViewController/PlaylistViewController.swift | mit | 1 | //
// PlaylistViewController.swift
// CocoaSwiftPlayer
//
// Created by Harry Ng on 12/2/2016.
// Copyright © 2016 STAY REAL. All rights reserved.
//
import Cocoa
import RealmSwift
class PlaylistViewController: NSViewController {
var playlists = [Playlist]() {
didSet {
outlineView.reloadData()
outlineView.expandItem(nil, expandChildren: true)
}
}
@IBOutlet weak var outlineView: NSOutlineView!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
print("PlaylistViewController viewDidLoad")
outlineView.setDataSource(self)
outlineView.setDelegate(self)
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Delete", action: "deletePlaylist:", keyEquivalent: ""))
outlineView.menu = menu
let realm = try! Realm()
playlists = realm.objects(Playlist).map { playlist in return playlist }
outlineView.registerForDraggedTypes([NSPasteboardTypeString])
}
@IBAction func addPlaylist(sender: AnyObject) {
let playlist = Playlist()
let realm = try! Realm()
try! realm.write {
realm.add(playlist)
}
playlists.append(playlist)
}
func deletePlaylist(sender: AnyObject) {
let playlist = playlists[outlineView.clickedRow - 1]
playlists.removeAtIndex(outlineView.clickedRow - 1)
outlineView.reloadData()
playlist.delete()
}
// MARK: - Helper
func isHeader(item: AnyObject) -> Bool {
return item is String
}
}
extension PlaylistViewController: NSOutlineViewDataSource {
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
if item == nil {
return 1
} else {
return playlists.count
}
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
return isHeader(item)
}
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
if item == nil {
return "Library"
} else {
return playlists[index]
}
}
func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject? {
return item
}
func outlineView(outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: AnyObject?, proposedChildIndex index: Int) -> NSDragOperation {
let canDrag = item is Playlist && index < 0
if canDrag {
return .Move
} else {
return .None
}
}
func outlineView(outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: AnyObject?, childIndex index: Int) -> Bool {
guard let playlist = item as? Playlist else { return false }
let pb = info.draggingPasteboard()
let location = pb.stringForType(NSPasteboardTypeString)
let realm = try! Realm()
if let location = location {
if let song = realm.objects(Song).filter("location = '\(location)'").first {
let index = playlist.songs.indexOf { s in
return s.location == song.location
}
if index == nil {
try! realm.write {
playlist.songs.append(song)
}
outlineView.reloadData()
}
}
return true
}
return false
}
func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? {
if isHeader(item) {
return outlineView.makeViewWithIdentifier("HeaderCell", owner: self)
} else {
let view = outlineView.makeViewWithIdentifier("DataCell", owner: self) as? CustomTableCellView
if let playlist = item as? Playlist {
view?.textField?.stringValue = "\(playlist.name)"
view?.textField?.delegate = self
view?.songCount.stringValue = "(\(playlist.songs.count))"
}
return view
}
}
}
extension PlaylistViewController: NSOutlineViewDelegate {
func outlineView(outlineView: NSOutlineView, shouldSelectItem item: AnyObject) -> Bool {
return !isHeader(item)
}
func outlineView(outlineView: NSOutlineView, shouldShowOutlineCellForItem item: AnyObject) -> Bool {
return false
}
func outlineViewSelectionDidChange(notification: NSNotification) {
let playlist = playlists[outlineView.selectedRow - 1]
NSNotificationCenter.defaultCenter().postNotificationName(Constants.Notifications.SwitchPlaylist, object: self, userInfo: [Constants.NotificationUserInfos.Playlist: playlist])
}
}
extension PlaylistViewController: NSTextFieldDelegate {
override func controlTextDidEndEditing(obj: NSNotification) {
if let textField = obj.object as? NSTextField {
print(textField.stringValue)
let row = outlineView.rowForView(textField)
let playlist = playlists[row - 1]
let realm = try! Realm()
try! realm.write {
playlist.name = textField.stringValue
}
}
}
}
| f58255c971e983dd977f2b02aac2d1bb | 30.47191 | 183 | 0.598001 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/Sema/availability.swift | apache-2.0 | 30 | // RUN: %target-typecheck-verify-swift -module-name MyModule
// REQUIRES: OS=macosx
@available(*, unavailable)
func unavailable_foo() {} // expected-note {{'unavailable_foo()' has been explicitly marked unavailable here}}
func test() {
unavailable_foo() // expected-error {{'unavailable_foo()' is unavailable}}
}
@available(*,unavailable,message: "use 'Int' instead")
struct NSUInteger {} // expected-note 3 {{explicitly marked unavailable here}}
struct Outer {
@available(*,unavailable,message: "use 'UInt' instead")
struct NSUInteger {} // expected-note 2 {{explicitly marked unavailable here}}
}
func foo(x : NSUInteger) { // expected-error {{'NSUInteger' is unavailable: use 'Int' instead}}
let y : NSUInteger = 42 // expected-error {{'NSUInteger' is unavailable: use 'Int' instead}}
let z : MyModule.NSUInteger = 42 // expected-error {{'NSUInteger' is unavailable: use 'Int' instead}}
let z2 : Outer.NSUInteger = 42 // expected-error {{'NSUInteger' is unavailable: use 'UInt' instead}}
let z3 : MyModule.Outer.NSUInteger = 42 // expected-error {{'NSUInteger' is unavailable: use 'UInt' instead}}
}
// Test preventing overrides of unavailable methods.
class ClassWithUnavailable {
@available(*, unavailable)
func doNotOverride() {} // expected-note {{'doNotOverride()' has been explicitly marked unavailable here}}
// FIXME: extraneous diagnostic here
@available(*, unavailable)
init(int _: Int) {} // expected-note 2 {{'init(int:)' has been explicitly marked unavailable here}}
convenience init(otherInt: Int) {
self.init(int: otherInt) // expected-error {{'init(int:)' is unavailable}}
}
@available(*, unavailable)
subscript (i: Int) -> Int { // expected-note{{'subscript' has been explicitly marked unavailable here}}
return i
}
}
class ClassWithOverride : ClassWithUnavailable {
override func doNotOverride() {} // expected-error {{cannot override 'doNotOverride' which has been marked unavailable}}
}
func testInit() {
ClassWithUnavailable(int: 0) // expected-error {{'init(int:)' is unavailable}} // expected-warning{{unused}}
}
func testSubscript(cwu: ClassWithUnavailable) {
_ = cwu[5] // expected-error{{'subscript' is unavailable}}
}
/* FIXME 'nil == a' fails to type-check with a bogus error message
* <rdar://problem/17540796>
func markUsed<T>(t: T) {}
func testString() {
let a : String = "Hey"
if a == nil {
markUsed("nil")
} else if nil == a {
markUsed("nil")
}
else {
markUsed("not nil")
}
}
*/
// Test preventing protocol witnesses for unavailable requirements
@objc
protocol ProtocolWithRenamedRequirement {
@available(*, unavailable, renamed: "new(bar:)")
@objc optional func old(foo: Int) // expected-note{{'old(foo:)' has been explicitly marked unavailable here}}
func new(bar: Int)
}
class ClassWithGoodWitness : ProtocolWithRenamedRequirement {
@objc func new(bar: Int) {}
}
class ClassWithBadWitness : ProtocolWithRenamedRequirement {
@objc func old(foo: Int) {} // expected-error{{'old(foo:)' has been renamed to 'new(bar:)'}}
@objc func new(bar: Int) {}
}
@available(OSX, unavailable)
let unavailableOnOSX: Int = 0 // expected-note{{explicitly marked unavailable here}}
@available(iOS, unavailable)
let unavailableOniOS: Int = 0
@available(iOS, unavailable) @available(OSX, unavailable)
let unavailableOnBothA: Int = 0 // expected-note{{explicitly marked unavailable here}}
@available(OSX, unavailable) @available(iOS, unavailable)
let unavailableOnBothB: Int = 0 // expected-note{{explicitly marked unavailable here}}
@available(OSX, unavailable)
typealias UnavailableOnOSX = Int // expected-note{{explicitly marked unavailable here}}
@available(iOS, unavailable)
typealias UnavailableOniOS = Int
@available(iOS, unavailable) @available(OSX, unavailable)
typealias UnavailableOnBothA = Int // expected-note{{explicitly marked unavailable here}}
@available(OSX, unavailable) @available(iOS, unavailable)
typealias UnavailableOnBothB = Int // expected-note{{explicitly marked unavailable here}}
@available(macOS, unavailable)
let unavailableOnMacOS: Int = 0 // expected-note{{explicitly marked unavailable here}}
@available(macOS, unavailable)
typealias UnavailableOnMacOS = Int // expected-note{{explicitly marked unavailable here}}
@available(OSXApplicationExtension, unavailable)
let unavailableOnOSXAppExt: Int = 0
@available(macOSApplicationExtension, unavailable)
let unavailableOnMacOSAppExt: Int = 0
@available(OSXApplicationExtension, unavailable)
typealias UnavailableOnOSXAppExt = Int
@available(macOSApplicationExtension, unavailable)
typealias UnavailableOnMacOSAppExt = Int
func testPlatforms() {
_ = unavailableOnOSX // expected-error{{unavailable}}
_ = unavailableOniOS
_ = unavailableOnBothA // expected-error{{unavailable}}
_ = unavailableOnBothB // expected-error{{unavailable}}
_ = unavailableOnMacOS // expected-error{{unavailable}}
_ = unavailableOnOSXAppExt
_ = unavailableOnMacOSAppExt
let _: UnavailableOnOSX = 0 // expected-error{{unavailable}}
let _: UnavailableOniOS = 0
let _: UnavailableOnBothA = 0 // expected-error{{unavailable}}
let _: UnavailableOnBothB = 0 // expected-error{{unavailable}}
let _: UnavailableOnMacOS = 0 // expected-error{{unavailable}}
let _: UnavailableOnOSXAppExt = 0
let _: UnavailableOnMacOSAppExt = 0
}
struct VarToFunc {
@available(*, unavailable, renamed: "function()")
var variable: Int // expected-note 2 {{explicitly marked unavailable here}}
@available(*, unavailable, renamed: "function()")
func oldFunction() -> Int { return 42 } // expected-note 2 {{explicitly marked unavailable here}}
func function() -> Int {
_ = variable // expected-error{{'variable' has been renamed to 'function()'}}{{9-17=function()}}
_ = oldFunction() //expected-error{{'oldFunction()' has been renamed to 'function()'}}{{9-20=function}}
_ = oldFunction // expected-error{{'oldFunction()' has been renamed to 'function()'}} {{9-20=function}}
return 42
}
mutating func testAssignment() {
// This is nonsense, but someone shouldn't be using 'renamed' for this
// anyway. Just make sure we don't crash or anything.
variable = 2 // expected-error {{'variable' has been renamed to 'function()'}} {{5-13=function()}}
}
}
| 4e6cdf416763808c02cc1f8a0b4e97b0 | 36.849398 | 122 | 0.720038 | false | false | false | false |
antonio081014/Stanford-CS193p | refs/heads/master | Developing iOS 8 Apps with Swift/Calculator/Calculator/CalculatorBrain.swift | mit | 1 | //
// CalculatorBrain.swift
// Calculator
//
// Created by Antonio081014 on 6/2/15.
// Copyright (c) 2015 Antonio081014.com. All rights reserved.
//
import Foundation
class CalculatorBrain
{
private enum Op : Printable {
case Operand(Double)
case UnaryOperation(String, Double ->Double)
case BinaryOperation(String, (Double, Double) ->Double)
var description: String {
get {
switch self {
case .Operand(let operand): return "\(operand)"
case .UnaryOperation(let symbol, _): return symbol
case .BinaryOperation(let symbol, _): return symbol
}
}
}
}
private var knownOps = [String:Op]()
private var opStack = [Op]()
init() {
func learnOp(op: Op) {
knownOps[op.description] = op
}
learnOp(Op.BinaryOperation("+", +))
learnOp(Op.BinaryOperation("−") { $1 - $0 })
learnOp(Op.BinaryOperation("×", *))
learnOp(Op.BinaryOperation("÷") { $1 / $0 })
learnOp(Op.UnaryOperation("√") { $0 >= 0 ? sqrt($0) : 0 })
}
private func evalute(ops: [Op]) ->(result: Double?, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .Operand(let operand):
return (operand, remainingOps)
case .UnaryOperation(_, let operation):
let operandEvaluation = evalute(remainingOps)
if let operand = operandEvaluation.result {
return (operation(operand), operandEvaluation.remainingOps)
}
case .BinaryOperation(_, let operation):
let operand1Eval = evalute(remainingOps)
if let operand1 = operand1Eval.result {
let operand2Eval = evalute(operand1Eval.remainingOps)
if let operand2 = operand2Eval.result {
return (operation(operand1, operand2), operand2Eval.remainingOps)
}
}
}
}
return (nil, ops)
}
func evaluate() ->Double? {
let (result, remainder) = evalute(opStack)
println("\(opStack) = \(result) with \(remainder) left over")
return result
}
func performOperation(symbol: String) ->Double? {
if let operation = knownOps[symbol] {
opStack.append(operation)
} else {
}
return evaluate()
}
func performOperand(operand: Double) ->Double? {
opStack.append(Op.Operand(operand))
return evaluate()
}
} | 60f5d1f6bdba0797525ca01795c00a29 | 30.272727 | 89 | 0.533261 | false | false | false | false |
haijianhuo/TopStore | refs/heads/master | Pods/KRPullLoader/KRPullLoader/Classes/KRPullLoader.swift | mit | 1 | //
// KRPullLoader.swift
// KRPullLoader
//
// Copyright © 2017 Krimpedance. All rights reserved.
//
import UIKit
/**
Type of KRPullLoader's position.
- refresh: At the head of UIScrollView's scroll direction
- loadMore: At the tail of UIScrollView's scroll direction
*/
public enum KRPullLoaderType {
case refresh, loadMore
}
/**
State of KRPullLoader
- none: hides the view.
- pulling: Pulling.
`offset` is pull offset (always <= 0).
This state changes to `loading` when `offset` exceeded `threshold`.
- loading: Shows the view.
You should call `completionHandler` when some actions have been completed.
*/
public enum KRPullLoaderState: Equatable {
case none
case pulling(offset: CGPoint, threshold: CGFloat)
case loading(completionHandler: ()->Void)
public static func == (lhs: KRPullLoaderState, rhs: KRPullLoaderState) -> Bool {
switch (lhs, rhs) {
case (.none, .none), (.loading, .loading): return true
case let (.pulling(lOffset, lThreshold), .pulling(rOffset, rThreshold)):
return lOffset == rOffset && lThreshold == rThreshold
default: return false
}
}
}
/**
KRPullLoadable is a protocol for views added to UIScrollView.
*/
public protocol KRPullLoadable: class {
/**
Handler when KRPullLoaderState value changed.
- parameter state: New state.
- parameter type: KRPullLoaderType.
*/
func didChangeState(_ state: KRPullLoaderState, viewType type: KRPullLoaderType)
}
class KRPullLoader<T>: UIView where T: UIView, T: KRPullLoadable {
private lazy var setUpLayoutConstraints: Void = { self.adjustLayoutConstraints() }()
private var observations = [NSKeyValueObservation]()
private var defaultInset = UIEdgeInsets()
private var scrollDirectionPositionConstraint: NSLayoutConstraint?
let loadView: T
let type: KRPullLoaderType
var scrollView: UIScrollView? {
return superview as? UIScrollView
}
var scrollDirection: UICollectionViewScrollDirection {
return ((superview as? UICollectionView)?.collectionViewLayout as? UICollectionViewFlowLayout)?.scrollDirection ?? .vertical
}
var state = KRPullLoaderState.none {
didSet {
loadView.didChangeState(state, viewType: type)
}
}
init(loadView: T, type: KRPullLoaderType) {
self.loadView = loadView
self.type = type
super.init(frame: loadView.bounds)
addSubview(loadView)
}
required init?(coder aDecoder: NSCoder) { fatalError() }
override func layoutSubviews() {
super.layoutSubviews()
_ = setUpLayoutConstraints
}
override func willRemoveSubview(_ subview: UIView) {
guard subview == loadView else { return }
observations = []
}
}
// MARK: - Actions -------------------
extension KRPullLoader {
func setUp() {
checkScrollViewContentSize()
addObservers()
}
}
// MARK: - Private Actions -------------------
private extension KRPullLoader {
func addObservers() {
guard let scrollView = self.scrollView else { return }
let contentOffsetObservation = scrollView.observe(\.contentOffset) { _, _ in
if case .loading = self.state { return }
if self.isHidden { return }
self.updateState()
}
let contentSizeObservation = scrollView.observe(\.contentSize) { _, _ in
if case .loading = self.state { return }
self.checkScrollViewContentSize()
}
observations = [contentOffsetObservation, contentSizeObservation]
}
func updateState() {
guard let scrollView = scrollView else { return }
let offset = (type == .refresh) ? scrollView.distanceOffset : scrollView.distanceEndOffset
let offsetValue = (scrollDirection == .vertical) ? offset.y : offset.x
let threshold = (scrollDirection == .vertical) ? bounds.height : bounds.width
if scrollView.isDecelerating && offsetValue < -threshold {
state = .loading(completionHandler: endLoading)
startLoading()
} else if offsetValue < 0 {
state = .pulling(offset: offset, threshold: -(threshold + 12))
} else if state != .none {
state = .none
}
}
}
// MARK: - Layouts -------------------
private extension KRPullLoader {
func checkScrollViewContentSize() {
if type == .refresh { return }
guard let scrollView = scrollView, let constraint = scrollDirectionPositionConstraint else { return }
self.isHidden = scrollView.bounds.height > (scrollView.contentSize.height + scrollView.contentInset.top + scrollView.contentInset.bottom)
constraint.constant = (scrollDirection == .vertical) ?
scrollView.contentSize.height + scrollView.contentInset.bottom :
scrollView.contentSize.width + scrollView.contentInset.right
}
func adjustLayoutConstraints() {
clipsToBounds = true
translatesAutoresizingMaskIntoConstraints = false
loadView.translatesAutoresizingMaskIntoConstraints = false
let attributes: [NSLayoutAttribute] = [.top, .left, .right, .bottom]
addConstraints(attributes.map { NSLayoutConstraint(item: loadView, attribute: $0, toItem: self) })
scrollDirection == .vertical ? adjustVerticalScrollLayoutConstraints() : adjustHorizontalScrollLayoutConstraints()
}
func adjustVerticalScrollLayoutConstraints() {
guard let scrollView = scrollView else { return }
switch type {
case .refresh:
scrollDirectionPositionConstraint = NSLayoutConstraint(item: self, attribute: .bottom, toItem: scrollView, attribute: .top, constant: -scrollView.contentInset.top)
case .loadMore:
let constant = scrollView.contentSize.height + scrollView.contentInset.bottom
scrollDirectionPositionConstraint = NSLayoutConstraint(item: self, attribute: .top, toItem: scrollView, attribute: .top, constant: constant)
}
scrollView.addConstraints([
scrollDirectionPositionConstraint!,
NSLayoutConstraint(item: self, attribute: .centerX, toItem: scrollView),
NSLayoutConstraint(item: self, attribute: .width, toItem: scrollView)
])
}
func adjustHorizontalScrollLayoutConstraints() {
guard let scrollView = scrollView else { return }
switch type {
case .refresh:
let constant = -scrollView.contentInset.left
scrollDirectionPositionConstraint = NSLayoutConstraint(item: self, attribute: .right, toItem: scrollView, attribute: .left, constant: constant)
case .loadMore:
let constant = scrollView.contentSize.width + scrollView.contentInset.right
scrollDirectionPositionConstraint = NSLayoutConstraint(item: self, attribute: .left, toItem: scrollView, attribute: .left, constant: constant)
}
scrollView.addConstraints([
scrollDirectionPositionConstraint!,
NSLayoutConstraint(item: self, attribute: .centerY, toItem: scrollView),
NSLayoutConstraint(item: self, attribute: .height, toItem: scrollView)
])
}
}
// MARK: - Loading actions -------------------
private extension KRPullLoader {
func startLoading() {
guard case .loading = state, let scrollView = self.scrollView else { return }
defaultInset = scrollView.contentInset
animateScrollViewInset(isShow: true)
}
func endLoading() {
state = .none
animateScrollViewInset(isShow: false)
}
func animateScrollViewInset(isShow: Bool) {
guard let scrollView = self.scrollView else { return }
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
switch (self.scrollDirection, self.type) {
case (.vertical, .refresh):
scrollView.contentInset.top = self.defaultInset.top + (isShow ? self.bounds.height : 0)
case (.vertical, .loadMore):
scrollView.contentInset.bottom = self.defaultInset.bottom + (isShow ? self.bounds.height : 0)
case (.horizontal, .refresh):
scrollView.contentInset.left = self.defaultInset.left + (isShow ? self.bounds.width : 0)
case (.horizontal, .loadMore):
scrollView.contentInset.right = self.defaultInset.right + (isShow ? self.bounds.width : 0)
}
}, completion: nil)
}
}
| 0ae9850fbe01837db0c5a9a5dc9d5400 | 34.489627 | 175 | 0.656378 | false | false | false | false |
AlexHmelevski/AHContainerViewController | refs/heads/master | AHContainerViewController/Classes/DimmingViewModel.swift | mit | 1 | //
// DimmingViewModel.swift
// AHContainerViewController
//
// Created by Alex Hmelevski on 2017-07-12.
//
import Foundation
public enum DimmingViewType {
case defaultView
case defaultBlur(UIBlurEffect.Style)
case noDimming
}
public struct DimmingViewModel {
let view: UIView
let animation: (CGFloat) -> (() -> Void)
}
protocol DimmingViewFactory {
func view(for type: DimmingViewType) -> DimmingViewModel?
}
public class ALModalPresentationControllerDimmingViewFactory: DimmingViewFactory {
func view(for type: DimmingViewType) -> DimmingViewModel? {
switch type {
case let .defaultBlur(style): return defaultBlur(with: style)
case .defaultView: return defaultDimming
default: return nil
}
}
private var defaultDimming: DimmingViewModel {
let dimmingView = UIView()
dimmingView.backgroundColor = UIColor(white: 0, alpha: 0.7)
dimmingView.alpha = 0
let animationBlock: (CGFloat) -> ( () -> Void ) = { (alpha) in
return { dimmingView.alpha = alpha }
}
return DimmingViewModel(view: dimmingView, animation: animationBlock)
}
private func defaultBlur(with style: UIBlurEffect.Style) -> DimmingViewModel {
let view = UIVisualEffectView()
view.effect = nil
let animationBlock: (CGFloat) -> (() -> Void) = { (alpha) in
return { view.effect = alpha <= 0 ? nil : UIBlurEffect(style: style) }
}
return DimmingViewModel(view: view, animation: animationBlock)
}
private var defaultPropertyAnimator: UIViewPropertyAnimator {
let animator = UIViewPropertyAnimator()
return animator
}
}
| bc41554f7e8e7e9d46f6224b6e17656a | 27.31746 | 82 | 0.633969 | false | false | false | false |
VBVMI/VerseByVerse-iOS | refs/heads/master | VBVMI/TopicLayoutView.swift | mit | 1 | //
// TopicLayoutView.swift
// VBVMI
//
// Created by Thomas Carey on 31/03/16.
// Copyright © 2016 Tom Carey. All rights reserved.
//
import UIKit
protocol TopicLayoutViewDelegate: NSObjectProtocol {
func topicSelected(_ topic: Topic)
}
class TopicLayoutView: UIView {
var topics = [Topic]() {
didSet {
configureViews()
rearrangeViews(self.bounds.size)
}
}
var topicSelectedBlock : ((_ topic: Topic) -> ())?
fileprivate var topicViews = [TopicButton]()
fileprivate func configureViews() {
topicViews.forEach { (view) in
view.removeFromSuperview()
}
topicViews = []
topics.forEach { (topic) in
let view = TopicButton(frame: CGRect.zero)
view.topic = topic
addSubview(view)
topicViews.append(view)
view.addTarget(self, action: #selector(TopicLayoutView.tappedTopicButton(_:)), for: .touchUpInside)
}
self.invalidateIntrinsicContentSize()
// self.setContentHuggingPriority(400, forAxis: UILayoutConstraintAxis.Vertical)
}
@objc func tappedTopicButton(_ sender: TopicButton) {
if let topic = sender.topic {
topicSelectedBlock?(topic)
}
}
var lastLayoutSize: CGSize = CGSize.zero {
didSet {
if lastLayoutSize.height != oldValue.height {
// logger.info("🍕setting height to: \(lastLayoutSize)")
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
}
// self.snp.updateConstraints { (make) in
// make.height.equalTo(lastLayoutSize.height)
// }
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
rearrangeViews(size)
return CGSize(width: size.width, height: lastLayoutSize.height)
}
override var intrinsicContentSize : CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: lastLayoutSize.height)
}
func rearrangeViews(_ size: CGSize) {
var currentX : CGFloat = self.layoutMargins.left
var currentY : CGFloat = self.layoutMargins.top
let paddingH : CGFloat = 8
let paddingV : CGFloat = 8
let rightEdgeX = size.width - self.layoutMargins.left - self.layoutMargins.right
var lastSize: CGSize = CGSize.zero
var maxWidth : CGFloat = 0
for topicView in topicViews {
let size = topicView.intrinsicContentSize
if topicView.isHidden {
topicView.frame = CGRect.zero
continue
}
if size.width + currentX <= rightEdgeX {
topicView.frame = CGRect(x: currentX, y: currentY, width: size.width, height: size.height)
currentX += paddingH + size.width
} else {
currentX = self.layoutMargins.left
currentY += size.height + paddingV
topicView.frame = CGRect(x: currentX, y: currentY, width: size.width, height: size.height)
currentX += paddingH + size.width
}
if currentX > maxWidth {
maxWidth = currentX
}
lastSize = size
}
let totalHeight = currentY + lastSize.height + layoutMargins.bottom
let totalWidth = maxWidth + layoutMargins.right
lastLayoutSize = CGSize(width: totalWidth, height: totalHeight)
}
override func layoutSubviews() {
super.layoutSubviews()
rearrangeViews(self.bounds.size)
super.layoutSubviews()
}
}
| a28c34c858901b4c467334c0e7843527 | 32.108108 | 111 | 0.58585 | false | false | false | false |
hellogaojun/Swift-coding | refs/heads/master | Swifter/Swifter.playground/Pages/init.xcplaygroundpage/Contents.swift | apache-2.0 | 3 |
class Cat {
var name: String
init() {
name = "cat"
}
}
class Tiger: Cat {
let power: Int
override init() {
power = 10
super.init()
name = "tiger"
}
}
class Cat1 {
var name: String
init() {
name = "cat"
}
}
class Tiger1: Cat1 {
let power: Int
override init() {
power = 10
// 如果我们不需要打改变 name 的话,
// 虽然我们没有显式地对 super.init() 进行调用
// 不过由于这是初始化的最后了,Swift 替我们自动完成了
}
}
let cat = Cat1()
let tiger = Tiger1()
| 354e7080dd5b00f624b315c33b4e1bd5 | 12.868421 | 39 | 0.493359 | false | false | false | false |
jpush/aurora-imui | refs/heads/master | iOS/sample/sample/IMUIInputView/Controllers/IMUIGalleryDataManager.swift | mit | 1 | //
// IMUIGalleryDataManager.swift
// IMUIChat
//
// Created by oshumini on 2017/3/9.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import Photos
class IMUIGalleryDataManager: NSObject {
static var targetSize = CGSize(width: 200, height: 200)
private static var _allAssets = [PHAsset]()
static var allAssets : [PHAsset] {
get{
if _allAssets.count < 1 {
updateAssets()
}
return _allAssets
}
}
class func updateAssets(){
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let assetFetchResult = PHAsset.fetchAssets(with: options)
assetFetchResult.enumerateObjects({(asset, _, _) in
_allAssets.append(asset)
})
}
static var selectedAssets = [PHAsset]()
}
| 605741b3e6a74a1728ff81669cd87458 | 21.944444 | 87 | 0.663438 | false | false | false | false |
arietis/codility-swift | refs/heads/master | 9.3.swift | mit | 1 | public func solution(inout A : [Int]) -> Int {
// write your code in Swift 2.2
var maxEnding = 0, maxSlice = 0, maxValue = Int.min
for i in A {
maxEnding = max(0, maxEnding + i)
maxSlice = max(maxSlice, maxEnding)
maxValue = max(maxValue, i)
}
if maxSlice == 0 {
maxSlice = maxValue
}
return maxSlice
}
| 8b1c5361f7f2310da68bfecf0e76436c | 21.875 | 55 | 0.565574 | false | false | false | false |
htcna/ios | refs/heads/master | HTCNA/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// HTCNA
//
// Created by Ignatius Darren Gozali on 9/19/15.
// Copyright (c) 2015 Ignatius Darren Gozali. 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
}
}
| 8c0829e89ee72d7d1a4de669838c84d6 | 52.380952 | 285 | 0.751412 | false | false | false | false |
acrookston/SQLite.swift | refs/heads/master | SQLiteTests/SchemaTests.swift | mit | 1 | import XCTest
import SQLite
class SchemaTests : XCTestCase {
func test_drop_compilesDropTableExpression() {
XCTAssertEqual("DROP TABLE \"table\"", table.drop())
XCTAssertEqual("DROP TABLE IF EXISTS \"table\"", table.drop(ifExists: true))
}
func test_drop_compilesDropVirtualTableExpression() {
XCTAssertEqual("DROP TABLE \"virtual_table\"", virtualTable.drop())
XCTAssertEqual("DROP TABLE IF EXISTS \"virtual_table\"", virtualTable.drop(ifExists: true))
}
func test_drop_compilesDropViewExpression() {
XCTAssertEqual("DROP VIEW \"view\"", _view.drop())
XCTAssertEqual("DROP VIEW IF EXISTS \"view\"", _view.drop(ifExists: true))
}
func test_create_withBuilder_compilesCreateTableExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (" +
"\"blob\" BLOB NOT NULL, " +
"\"blobOptional\" BLOB, " +
"\"double\" REAL NOT NULL, " +
"\"doubleOptional\" REAL, " +
"\"int64\" INTEGER NOT NULL, " +
"\"int64Optional\" INTEGER, " +
"\"string\" TEXT NOT NULL, " +
"\"stringOptional\" TEXT" +
")",
table.create { t in
t.column(data)
t.column(dataOptional)
t.column(double)
t.column(doubleOptional)
t.column(int64)
t.column(int64Optional)
t.column(string)
t.column(stringOptional)
}
)
XCTAssertEqual(
"CREATE TEMPORARY TABLE \"table\" (\"int64\" INTEGER NOT NULL)",
table.create(temporary: true) { $0.column(int64) }
)
XCTAssertEqual(
"CREATE TABLE IF NOT EXISTS \"table\" (\"int64\" INTEGER NOT NULL)",
table.create(ifNotExists: true) { $0.column(int64) }
)
XCTAssertEqual(
"CREATE TEMPORARY TABLE IF NOT EXISTS \"table\" (\"int64\" INTEGER NOT NULL)",
table.create(temporary: true, ifNotExists: true) { $0.column(int64) }
)
}
func test_create_withQuery_compilesCreateTableExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" AS SELECT \"int64\" FROM \"view\"",
table.create(_view.select(int64))
)
}
// thoroughness test for ambiguity
func test_column_compilesColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL)",
table.create { t in t.column(int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE)",
table.create { t in t.column(int64, unique: true) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL DEFAULT (\"int64\"))",
table.create { t in t.column(int64, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL DEFAULT (0))",
table.create { t in t.column(int64, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE DEFAULT (\"int64\"))",
table.create { t in t.column(int64, unique: true, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE DEFAULT (0))",
table.create { t in t.column(int64, unique: true, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, unique: true, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, check: int64Optional > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL DEFAULT (\"int64\"))",
table.create { t in t.column(int64, primaryKey: true, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, primaryKey: true, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER)",
table.create { t in t.column(int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE)",
table.create { t in t.column(int64Optional, unique: true) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0))",
table.create { t in t.column(int64Optional, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64Optional, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (0))",
table.create { t in t.column(int64Optional, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, unique: true, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (0))",
table.create { t in t.column(int64Optional, unique: true, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: 0) }
)
}
func test_column_withIntegerExpression_compilesPrimaryKeyAutoincrementColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",
table.create { t in t.column(int64, primaryKey: .Autoincrement) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, primaryKey: .Autoincrement, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, primaryKey: .Autoincrement, check: int64Optional > 0) }
)
}
func test_column_withIntegerExpression_compilesReferentialColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, unique: true, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, check: int64Optional > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, references: table, int64) }
)
}
func test_column_withStringExpression_compilesCollatedColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL COLLATE RTRIM)",
table.create { t in t.column(string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL COLLATE RTRIM)",
table.create { t in t.column(stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
}
func test_primaryKey_compilesPrimaryKeyExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (PRIMARY KEY (\"int64\"))",
table.create { t in t.primaryKey(int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (PRIMARY KEY (\"int64\", \"string\"))",
table.create { t in t.primaryKey(int64, string) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (PRIMARY KEY (\"int64\", \"string\", \"double\"))",
table.create { t in t.primaryKey(int64, string, double) }
)
}
func test_unique_compilesUniqueExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (UNIQUE (\"int64\"))",
table.create { t in t.unique(int64) }
)
}
func test_check_compilesCheckExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (CHECK ((\"int64\" > 0)))",
table.create { t in t.check(int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (CHECK ((\"int64Optional\" > 0)))",
table.create { t in t.check(int64Optional > 0) }
)
}
func test_foreignKey_compilesForeignKeyExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\") REFERENCES \"table\" (\"string\"))",
table.create { t in t.foreignKey(string, references: table, string) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"stringOptional\") REFERENCES \"table\" (\"string\"))",
table.create { t in t.foreignKey(stringOptional, references: table, string) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\") REFERENCES \"table\" (\"string\") ON UPDATE CASCADE ON DELETE SET NULL)",
table.create { t in t.foreignKey(string, references: table, string, update: .Cascade, delete: .SetNull) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\", \"string\") REFERENCES \"table\" (\"string\", \"string\"))",
table.create { t in t.foreignKey((string, string), references: table, (string, string)) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\", \"string\", \"string\") REFERENCES \"table\" (\"string\", \"string\", \"string\"))",
table.create { t in t.foreignKey((string, string, string), references: table, (string, string, string)) }
)
}
func test_addColumn_compilesAlterTableExpression() {
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL DEFAULT (1)",
table.addColumn(int64, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (1)",
table.addColumn(int64, check: int64 > 0, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (1)",
table.addColumn(int64, check: int64Optional > 0, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER",
table.addColumn(int64Optional)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0)",
table.addColumn(int64Optional, check: int64 > 0)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0)",
table.addColumn(int64Optional, check: int64Optional > 0)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER DEFAULT (1)",
table.addColumn(int64Optional, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (1)",
table.addColumn(int64Optional, check: int64 > 0, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (1)",
table.addColumn(int64Optional, check: int64Optional > 0, defaultValue: 1)
)
}
func test_addColumn_withIntegerExpression_compilesReferentialAlterTableExpression() {
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, unique: true, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, check: int64Optional > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, unique: true, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, unique: true, check: int64Optional > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, unique: true, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, check: int64Optional > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, unique: true, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, unique: true, check: int64Optional > 0, references: table, int64)
)
}
func test_addColumn_withStringExpression_compilesCollatedAlterTableExpression() {
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM",
table.addColumn(string, defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(string, check: string != "", defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(string, check: stringOptional != "", defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT COLLATE RTRIM",
table.addColumn(stringOptional, collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"string\" != '') COLLATE RTRIM",
table.addColumn(stringOptional, check: string != "", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"stringOptional\" != '') COLLATE RTRIM",
table.addColumn(stringOptional, check: stringOptional != "", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(stringOptional, check: string != "", defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(stringOptional, check: stringOptional != "", defaultValue: "string", collate: .Rtrim)
)
}
func test_rename_compilesAlterTableRenameToExpression() {
XCTAssertEqual("ALTER TABLE \"old\" RENAME TO \"table\"", Table("old").rename(table))
}
func test_createIndex_compilesCreateIndexExpression() {
XCTAssertEqual("CREATE INDEX \"index_table_on_int64\" ON \"table\" (\"int64\")", table.createIndex(int64))
XCTAssertEqual(
"CREATE UNIQUE INDEX \"index_table_on_int64\" ON \"table\" (\"int64\")",
table.createIndex([int64], unique: true)
)
XCTAssertEqual(
"CREATE INDEX IF NOT EXISTS \"index_table_on_int64\" ON \"table\" (\"int64\")",
table.createIndex([int64], ifNotExists: true)
)
XCTAssertEqual(
"CREATE UNIQUE INDEX IF NOT EXISTS \"index_table_on_int64\" ON \"table\" (\"int64\")",
table.createIndex([int64], unique: true, ifNotExists: true)
)
}
func test_dropIndex_compilesCreateIndexExpression() {
XCTAssertEqual("DROP INDEX \"index_table_on_int64\"", table.dropIndex(int64))
XCTAssertEqual("DROP INDEX IF EXISTS \"index_table_on_int64\"", table.dropIndex([int64], ifExists: true))
}
func test_create_onView_compilesCreateViewExpression() {
XCTAssertEqual(
"CREATE VIEW \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64))
)
XCTAssertEqual(
"CREATE TEMPORARY VIEW \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64), temporary: true)
)
XCTAssertEqual(
"CREATE VIEW IF NOT EXISTS \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64), ifNotExists: true)
)
XCTAssertEqual(
"CREATE TEMPORARY VIEW IF NOT EXISTS \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64), temporary: true, ifNotExists: true)
)
}
func test_create_onVirtualTable_compilesCreateVirtualTableExpression() {
XCTAssertEqual(
"CREATE VIRTUAL TABLE \"virtual_table\" USING \"custom\"('foo', 'bar')",
virtualTable.create(Module("custom", ["foo", "bar"]))
)
}
func test_rename_onVirtualTable_compilesAlterTableRenameToExpression() {
XCTAssertEqual(
"ALTER TABLE \"old\" RENAME TO \"virtual_table\"",
VirtualTable("old").rename(virtualTable)
)
}
}
| 1af07b70e3ac254c6656db8b729fa9c9 | 53.670143 | 155 | 0.582681 | false | false | false | false |
PANDA-Guide/PandaGuideApp | refs/heads/master | PandaGuide/UIColor+Variants.swift | gpl-3.0 | 1 | //
// UIColor+Variants.swift
// TAZ
//
// Created by Pierre Dulac on 13/08/2014.
// Copyright (c) 2014 Amande&Pierre. All rights reserved.
//
import UIKit
extension UIColor {
/**
Create a ligher color
*/
func lighter(by percentage: CGFloat = 30.0) -> UIColor {
return adjustBrightness(by: abs(percentage))
}
/**
Create a darker color
*/
func darker(by percentage: CGFloat = 30.0) -> UIColor {
return adjustBrightness(by: -abs(percentage))
}
/**
Try to increase brightness or decrease saturation
*/
func adjustBrightness(by percentage: CGFloat = 30.0) -> UIColor {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
if getHue(&h, saturation: &s, brightness: &b, alpha: &a) {
if b < 1.0 {
let newB: CGFloat = max(min(b + (percentage/100.0)*b, 1.0), 0,0)
return UIColor(hue: h, saturation: s, brightness: newB, alpha: a)
} else {
let newS: CGFloat = min(max(s - (percentage/100.0)*s, 0.0), 1.0)
return UIColor(hue: h, saturation: newS, brightness: b, alpha: a)
}
}
return self
}
}
| e8efa11118c5cc1a553ef815f3e6204f | 26.863636 | 81 | 0.550571 | false | false | false | false |
ggu/Pathfinder | refs/heads/master | Pathfinder/Menu.swift | mit | 1 | //
// Menu.swift
// Pathfinder
//
// Created by Gabriel Uribe on 1/25/16.
//
import UIKit
internal protocol MenuDelegate {
func startTapped()
func targetTapped()
func runTapped()
}
internal class Menu: UIView {
@IBOutlet weak var setStartButton: UIButton!
@IBOutlet weak var setTargetButton: UIButton!
@IBOutlet var view: UIView!
var delegate: MenuDelegate?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
UINib(nibName: "Menu", bundle: nil).instantiateWithOwner(self, options: nil)
addSubview(view)
view.frame = self.bounds
setStartAction(self)
}
@IBAction func setStartAction(sender: AnyObject) {
setStartButtonActive()
delegate?.startTapped()
}
@IBAction func setTargetAction(sender: AnyObject) {
setTargetButtonActive()
delegate?.targetTapped()
}
@IBAction func runAction(sender: AnyObject) {
delegate?.runTapped()
}
func setTargetButtonActive() {
setTargetButton.backgroundColor = Color.targetColor
setStartButton.backgroundColor = UIColor.whiteColor()
}
func setStartButtonActive() {
setStartButton.backgroundColor = Color.startColor
setTargetButton.backgroundColor = UIColor.whiteColor()
}
}
| bb60fe87f71ae45156770bef9ab5b708 | 22.377358 | 80 | 0.713479 | false | false | false | false |
acort3255/Emby.ApiClient.Swift | refs/heads/master | Emby.ApiClient/model/dto/BaseItemPerson.swift | mit | 1 | //
// BaseItemPersonDto.swift
// Emby.ApiClient
//
import Foundation
public class BaseItemPerson: Codable {
public let name: String
public var id: String?
public let role: String?
public let type: String
public var primaryImageTag: String?
public var hasPrimaryImage: Bool {
get {
return primaryImageTag != nil
}
}
init (name: String, role: String, type: String) {
self.name = name
self.role = role
self.type = type
}
enum CodingKeys: String, CodingKey
{
case name = "Name"
case id = "Id"
case role = "Role"
case type = "Type"
case primaryImageTag = "PrimaryImageTag"
}
}
| 3501c4abade831013d9fcffb62041439 | 20.352941 | 53 | 0.577135 | false | false | false | false |
badoo/Chatto | refs/heads/master | ChattoAdditions/sources/Input/Photos/PhotosInputPermissionsRequester.swift | mit | 1 | //
// The MIT License (MIT)
//
// Copyright (c) 2015-present Badoo Trading Limited.
//
// 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 AVFoundation
import Photos
public protocol PhotosInputPermissionsRequesterDelegate: AnyObject {
func requester(_ requester: PhotosInputPermissionsRequesterProtocol, didReceiveUpdatedCameraPermissionStatus status: AVAuthorizationStatus)
func requester(_ requester: PhotosInputPermissionsRequesterProtocol, didReceiveUpdatedPhotosPermissionStatus status: PHAuthorizationStatus)
}
public protocol PhotosInputPermissionsRequesterProtocol: AnyObject {
var delegate: PhotosInputPermissionsRequesterDelegate? { get set }
var cameraAuthorizationStatus: AVAuthorizationStatus { get }
var photoLibraryAuthorizationStatus: PHAuthorizationStatus { get }
func requestAccessToCamera()
func requestAccessToPhotos()
}
final class PhotosInputPermissionsRequester: PhotosInputPermissionsRequesterProtocol {
// MARK: - PhotosInputPermissionsRequesterProtocol
weak var delegate: PhotosInputPermissionsRequesterDelegate?
var cameraAuthorizationStatus: AVAuthorizationStatus {
return AVCaptureDevice.authorizationStatus(for: .video)
}
var photoLibraryAuthorizationStatus: PHAuthorizationStatus {
return PHPhotoLibrary.authorizationStatus()
}
func requestAccessToCamera() {
self.needsToRequestVideoPermission = true
self.requestNeededPermissions()
}
func requestAccessToPhotos() {
self.needsToRequestPhotosPermission = true
self.requestNeededPermissions()
}
// MARK: - Private properties
private var needsToRequestVideoPermission: Bool = false
private var needsToRequestPhotosPermission: Bool = false
private var isRequestingPermission: Bool = false
// MARK: - Private methods
private func requestNeededPermissions() {
guard self.isRequestingPermission == false else { return }
if self.needsToRequestPhotosPermission {
self.requestPhotosPermission()
}
if self.needsToRequestVideoPermission {
self.requestVideoPermission()
}
}
private func requestVideoPermission() {
guard self.needsToRequestVideoPermission else { return }
self.needsToRequestVideoPermission = false
self.isRequestingPermission = true
AVCaptureDevice.requestAccess(for: .video) { (_) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
self.isRequestingPermission = false
self.delegate?.requester(self, didReceiveUpdatedCameraPermissionStatus: self.cameraAuthorizationStatus)
self.requestNeededPermissions()
})
}
}
private func requestPhotosPermission() {
guard self.needsToRequestPhotosPermission else { return }
self.needsToRequestPhotosPermission = false
self.isRequestingPermission = true
PHPhotoLibrary.requestAuthorization { (status: PHAuthorizationStatus) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
self.isRequestingPermission = false
self.delegate?.requester(self, didReceiveUpdatedPhotosPermissionStatus: status)
self.requestNeededPermissions()
})
}
}
}
| 93815abc5d1643cbbe8f4cb82826e7d5 | 38.495495 | 143 | 0.73312 | false | false | false | false |
sheepy1/SelectionOfZhihu | refs/heads/master | SelectionOfZhihu/ArticleViewController.swift | mit | 1 | //
// ArticleViewController.swift
// SelectionOfZhihu
//
// Created by 杨洋 on 16/1/10.
// Copyright © 2016年 Sheepy. All rights reserved.
//
import UIKit
//enum ScrollDirection {
// case Up
// case Down
// case None
//}
class ArticleViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var loadingView: UIActivityIndicatorView!
var urlString: String!
//var oldY: CGFloat = 0
//var newY: CGFloat = 0
//var scrollDirection: ScrollDirection = .None
func loadUrl() {
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
}
override func viewDidLoad() {
super.viewDidLoad()
loadUrl()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
extension ArticleViewController: UIWebViewDelegate {
func webViewDidStartLoad(webView: UIWebView) {
loadingView.startAnimating()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
loadingView.stopAnimating()
}
func webViewDidFinishLoad(webView: UIWebView) {
loadingView.stopAnimating()
}
}
//extension ArticleViewController: UIScrollViewDelegate {
// //判断当前是向上还是向下滑动
// func scrollViewDidScroll(scrollView: UIScrollView) {
// newY = scrollView.contentOffset.y
// if newY > oldY {
// scrollDirection = .Up
// } else if oldY > newY {
// scrollDirection = .Down
// }
// oldY = newY
// }
//}
| 122f580f0327444e112b681b974743ce | 22.310811 | 79 | 0.627246 | false | false | false | false |
googlearchive/science-journal-ios | refs/heads/master | ScienceJournal/UI/NotesViewController.swift | apache-2.0 | 1 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
/// Delegate protocol for NotesViewController to communicate when text has been created for a note.
protocol NotesViewControllerDelegate: class {
/// Tells the delegate when text has been created for a note.
func notesViewController(_ notesViewController: NotesViewController,
didCreateTextForNote text: String)
}
/// Manages the view that lets a user take notes.
open class NotesViewController: ScienceJournalViewController, DrawerItemViewController,
DrawerPositionListener, UITextViewDelegate {
// MARK: - Properties
/// The delegate.
weak var delegate: NotesViewControllerDelegate?
var notesView: NotesView {
// swiftlint:disable force_cast
return view as! NotesView
// swiftlint:enable force_cast
}
// Cached text height, to only pan the drawer up or down if the text height has changed.
private var textHeight: CGFloat = 0
// Cached notes view keyboard offset, to only update the drawer position if it has changed. As
// well as for calculating visible notes height.
private var notesViewKeyboardOffset: CGFloat = 0
private var drawerPanner: DrawerPanner?
private var visibleNotesHeight: CGFloat? {
guard let drawerViewController = drawerViewController else { return nil }
return drawerViewController.drawerView.visibleContentHeight - notesViewKeyboardOffset
}
// MARK: - Public
override open func loadView() {
view = NotesView()
notesView.textView.delegate = self
notesView.sendButtonActionBar.button.addTarget(self,
action: #selector(sendButtonPressed),
for: .touchUpInside)
notesView.sendButtonActionBar.button.isEnabled = false
notesView.sendButtonView.sendButton.addTarget(self,
action: #selector(sendButtonPressed),
for: .touchUpInside)
notesView.sendButtonView.sendButton.isEnabled = false
notesView.sendFAB.addTarget(self,
action: #selector(sendButtonPressed),
for: .touchUpInside)
notesView.sendFAB.isEnabled = false
}
override open func viewDidLoad() {
super.viewDidLoad()
// Don't allow the custom position until editing begins.
drawerViewController?.drawerView.canOpenToCustomPosition = false
NotificationCenter.default.addObserver(self,
selector: #selector(handleKeyboardNotification(_:)),
name: .keyboardObserverWillShow,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(handleKeyboardDidShowNotification(_:)),
name: .keyboardObserverDidShow,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(handleKeyboardNotification(_:)),
name: .keyboardObserverWillHide,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(handleKeyboardNotification(_:)),
name: .keyboardObserverWillChangeFrame,
object: nil)
notesView.textView.panGestureRecognizer.addTarget(
self,
action: #selector(handleTextViewPanGesture(_:)))
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let drawerViewController = drawerViewController {
// Set the custom notes drawer position.
let drawerPosition = DrawerPosition(canShowKeyboard: true) {
// The text view height, not to exceed the maximum, plus half drawer height.
let textHeight = min(self.notesView.maximumCustomTextHeight,
self.notesView.heightFittingText)
let convertedKeyboardFrame =
self.notesView.convert(KeyboardObserver.shared.currentKeyboardFrame, from: nil)
let customDrawerHeight =
self.notesView.bounds.intersection(convertedKeyboardFrame).height + textHeight
return max(customDrawerHeight,
drawerViewController.drawerView.openHalfPosition.contentHeight)
}
drawerViewController.drawerView.setCustomPosition(drawerPosition)
updateSendButtonStyle(forDrawerPosition: drawerViewController.drawerView.currentPosition)
}
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// If the drawer is open full, show the keyboard.
guard let drawerViewController = drawerViewController else { return }
if drawerViewController.isOpenFull {
notesView.textView.becomeFirstResponder()
}
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// If the drawer is in the custom position when leaving this view, set it to half since other
// views might not support custom positions. Then remove notes' custom position.
guard let drawerViewController = drawerViewController else { return }
drawerViewController.setPositionToHalfIfCustom()
drawerViewController.drawerView.removeCustomPosition()
// This view controller is only created once in the drawer, and the instance is used for every
// experiment. End editing so the text view does not retain first responder between view
// appearances.
view.endEditing(true)
}
override func setCustomTint(_ customTint: CustomTint) {
super.setCustomTint(customTint)
notesView.sendFAB.imageView?.tintColor = customTint.primary
notesView.sendFAB.backgroundColor = customTint.secondary
}
// MARK: - Private
// Whether or not there is text not including whitespace and newlines.
private var textViewHasTextToSave: Bool {
guard let noteTextTrimmed = notesView.textView.text.trimmedOrNil else { return false }
return noteTextTrimmed.count > 0
}
// Adjusts the text view height to show between 1 and 3 lines of text in the text view, depending
// on how many lines of text there are currently.
private func updateDrawerPositionToFitText(ifTextHeightChanged: Bool = true) {
guard let drawerViewController = drawerViewController else { return }
let previousTextHeight = textHeight
textHeight = min(notesView.heightFittingText, notesView.maximumCustomTextHeight)
// If the drawer is in the custom position and the text height changed, or an update is
// requested, update the drawer position to change the text view visible height.
if drawerViewController.isCustomPosition &&
(!ifTextHeightChanged || previousTextHeight != textHeight) {
drawerViewController.setPositionToCustom(animated: false)
}
}
// Updates the send button enabled state.
private func updateSendButton() {
// If the text view has text, enable the send buttons, otherwise disable them.
notesView.sendButtonActionBar.button.isEnabled = textViewHasTextToSave
notesView.sendButtonView.sendButton.isEnabled = textViewHasTextToSave
notesView.sendFAB.isEnabled = textViewHasTextToSave
}
private func updateSendButtonStyle(forDrawerPosition drawerPosition: DrawerPosition) {
guard let drawerViewController = drawerViewController else { return }
let sendButtonStyle: NotesView.SendButtonStyle =
traitCollection.verticalSizeClass == .compact ||
drawerViewController.isPositionCustom(drawerPosition) ? .button : .toolbar
notesView.setSendButtonStyle(sendButtonStyle, animated: true)
}
private func updatePlaceholder() {
// Show the placeholder when there is no text. It should also not show if there is a newline or
// whitespace.
notesView.placeholderLabel.isHidden = notesView.textView.text.count > 0
}
private func animateForKeyboardNotification(_ notification: Notification) {
guard let duration = KeyboardObserver.animationDuration(fromKeyboardNotification: notification),
let options =
KeyboardObserver.animationCurve(fromKeyboardNotification: notification) else { return }
UIView.animate(withDuration: duration,
delay: 0,
options: options,
animations: {
self.updateDrawerPositionToFitText(ifTextHeightChanged: false)
self.notesView.updateActionBarHeight()
})
}
/// Clears the text from the text view, and updates the send button and placeholder.
private func clearText() {
notesView.textView.text = ""
updateSendButton()
updatePlaceholder()
}
// MARK: - User actions
@objc private func sendButtonPressed() {
notesView.textView.commitPendingAutocomplete()
guard textViewHasTextToSave, let text = notesView.textView.text else { return }
clearText()
let saveText: () -> Void = {
self.delegate?.notesViewController(self, didCreateTextForNote: text)
}
if let drawerViewController = drawerViewController {
if drawerViewController.drawerView.hasCustomPosition &&
drawerViewController.canOpenPartially {
drawerViewController.setToCustomPositionIfFull(completion: saveText)
} else {
drawerViewController.minimizeFromFull(completion: saveText)
}
} else {
saveText()
}
}
// MARK: - DrawerItemViewController
public func setUpDrawerPanner(with drawerViewController: DrawerViewController) {
drawerPanner = DrawerPanner(drawerViewController: drawerViewController,
scrollView: notesView.textView,
allowsPanningUp: true)
}
public func reset() {
clearText()
}
// MARK: - DrawerPositionListener
public func drawerViewController(_ drawerViewController: DrawerViewController,
willChangeDrawerPosition position: DrawerPosition) {
updateSendButtonStyle(forDrawerPosition: position)
if !drawerViewController.isPositionOpenFull(position) {
notesView.textView.setContentOffset(.zero, animated: true)
}
}
public func drawerViewController(_ drawerViewController: DrawerViewController,
didChangeDrawerPosition position: DrawerPosition) {
if isDisplayedInDrawer {
// If opening the drawer to a position that allows showing the keyboard, show it. Otherwise
// hide the keyboard.
if position.canShowKeyboard {
if !drawerViewController.isDisplayedAsSidebar {
notesView.textView.becomeFirstResponder()
}
} else {
notesView.textView.resignFirstResponder()
}
}
notesView.updateActionBarHeight()
}
public func drawerViewController(_ drawerViewController: DrawerViewController,
isPanningDrawerView drawerView: DrawerView) {
guard KeyboardObserver.shared.isKeyboardVisible &&
KeyboardObserver.shared.currentKeyboardFrame != .zero else { return }
let convertedKeyboardFrame = drawerView.convert(KeyboardObserver.shared.currentKeyboardFrame,
from: nil)
let keyboardOffset = drawerView.bounds.maxY - convertedKeyboardFrame.minY
if drawerView.visibleHeight < keyboardOffset {
drawerViewController.setPositionToPeeking(animated: true)
}
}
public func drawerViewController(_ drawerViewController: DrawerViewController,
didPanBeyondBounds panDistance: CGFloat) {}
// MARK: - UITextViewDelegate
public func textViewDidBeginEditing(_ textView: UITextView) {
guard let drawerViewController = drawerViewController else { return }
// While editing on a device that is not full screen iPad, allow opening the drawer to the
// custom notes position. Do not let the drawer open halfway.
if !(traitCollection.horizontalSizeClass == .regular &&
traitCollection.verticalSizeClass == .regular) {
drawerViewController.drawerView.canOpenToCustomPosition =
drawerViewController.canOpenPartially
drawerViewController.drawerView.canOpenHalf = false
}
// If the drawer is peeking or open half, open the drawer to the custom position if it is
// allowed, otherwise open it to full.
if drawerViewController.isPeeking || drawerViewController.isOpenHalf {
if drawerViewController.drawerView.canOpenToCustomPosition {
drawerViewController.setPositionToCustom()
} else {
drawerViewController.setPositionToFull()
}
}
}
public func textViewDidEndEditing(_ textView: UITextView) {
// When ending editing on a device that is not full screen iPad, do not let the drawer open to
// the custom notes position. Let it open halfway.
if !(traitCollection.horizontalSizeClass == .regular &&
traitCollection.verticalSizeClass == .regular),
let drawerViewController = drawerViewController {
drawerViewController.drawerView.canOpenToCustomPosition = false
drawerViewController.drawerView.canOpenHalf = drawerViewController.canOpenPartially
}
// When ending editing, if the position was custom, switch to open half.
if let drawerViewController = drawerViewController {
drawerViewController.setPositionToHalfIfCustom()
}
}
public func textViewDidChange(_ textView: UITextView) {
updateSendButton()
updatePlaceholder()
updateDrawerPositionToFitText()
}
// MARK: - UIScrollViewDelegate
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
drawerPanner?.scrollViewWillBeginDragging(scrollView)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView,
willDecelerate decelerate: Bool) {
drawerPanner?.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
}
// MARK: - Gesture recognizer
@objc func handleTextViewPanGesture(_ panGestureRecognizer: UIPanGestureRecognizer) {
drawerPanner?.handlePanGesture(panGestureRecognizer)
}
// MARK: - Notifications
@objc func handleKeyboardNotification(_ notification: Notification) {
// Did the keyboard height change?
let convertedKeyboardFrame = notesView.convert(KeyboardObserver.shared.currentKeyboardFrame,
from: nil)
let previousNotesViewKeyboardOffset = notesViewKeyboardOffset
notesViewKeyboardOffset = notesView.bounds.maxY - convertedKeyboardFrame.minY
guard previousNotesViewKeyboardOffset != notesViewKeyboardOffset else { return }
animateForKeyboardNotification(notification)
}
@objc func handleKeyboardDidShowNotification(_ notification: Notification) {
animateForKeyboardNotification(notification)
}
}
| 607e80388b402a4834ae753026e4086d | 39.848168 | 100 | 0.696616 | false | false | false | false |
coach-plus/ios | refs/heads/master | Example/Pods/PromiseKit/Sources/Catchable.swift | apache-2.0 | 7 | import Dispatch
/// Provides `catch` and `recover` to your object that conforms to `Thenable`
public protocol CatchMixin: Thenable
{}
public extension CatchMixin {
/**
The provided closure executes when this promise rejects.
Rejecting a promise cascades: rejecting all subsequent promises (unless
recover is invoked) thus you will typically place your catch at the end
of a chain. Often utility promises will not have a catch, instead
delegating the error handling to the caller.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- Returns: A promise finalizer.
- SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation)
*/
@discardableResult
func `catch`(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) -> Void) -> PMKFinalizer {
let finalizer = PMKFinalizer()
pipe {
switch $0 {
case .rejected(let error):
guard policy == .allErrors || !error.isCancelled else {
fallthrough
}
on.async(flags: flags) {
body(error)
finalizer.pending.resolve(())
}
case .fulfilled:
finalizer.pending.resolve(())
}
}
return finalizer
}
}
public class PMKFinalizer {
let pending = Guarantee<Void>.pending()
/// `finally` is the same as `ensure`, but it is not chainable
public func finally(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Void) {
pending.guarantee.done(on: on, flags: flags) {
body()
}
}
}
public extension CatchMixin {
/**
The provided closure executes when this promise rejects.
Unlike `catch`, `recover` continues the chain.
Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example:
firstly {
CLLocationManager.requestLocation()
}.recover { error in
guard error == CLError.unknownLocation else { throw error }
return .value(CLLocation.chicago)
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation)
*/
func recover<U: Thenable>(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> U) -> Promise<T> where U.T == T {
let rp = Promise<U.T>(.pending)
pipe {
switch $0 {
case .fulfilled(let value):
rp.box.seal(.fulfilled(value))
case .rejected(let error):
if policy == .allErrors || !error.isCancelled {
on.async(flags: flags) {
do {
let rv = try body(error)
guard rv !== rp else { throw PMKError.returnedSelf }
rv.pipe(to: rp.box.seal)
} catch {
rp.box.seal(.rejected(error))
}
}
} else {
rp.box.seal(.rejected(error))
}
}
}
return rp
}
/**
The provided closure executes when this promise rejects.
This variant of `recover` requires the handler to return a Guarantee, thus it returns a Guarantee itself and your closure cannot `throw`.
- Note it is logically impossible for this to take a `catchPolicy`, thus `allErrors` are handled.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation)
*/
@discardableResult
func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Error) -> Guarantee<T>) -> Guarantee<T> {
let rg = Guarantee<T>(.pending)
pipe {
switch $0 {
case .fulfilled(let value):
rg.box.seal(value)
case .rejected(let error):
on.async(flags: flags) {
body(error).pipe(to: rg.box.seal)
}
}
}
return rg
}
/**
The provided closure executes when this promise resolves, whether it rejects or not.
firstly {
UIApplication.shared.networkActivityIndicatorVisible = true
}.done {
//…
}.ensure {
UIApplication.shared.networkActivityIndicatorVisible = false
}.catch {
//…
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
func ensure(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Void) -> Promise<T> {
let rp = Promise<T>(.pending)
pipe { result in
on.async(flags: flags) {
body()
rp.box.seal(result)
}
}
return rp
}
/**
The provided closure executes when this promise resolves, whether it rejects or not.
The chain waits on the returned `Guarantee<Void>`.
firstly {
setup()
}.done {
//…
}.ensureThen {
teardown() // -> Guarante<Void>
}.catch {
//…
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
func ensureThen(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Guarantee<Void>) -> Promise<T> {
let rp = Promise<T>(.pending)
pipe { result in
on.async(flags: flags) {
body().done {
rp.box.seal(result)
}
}
}
return rp
}
/**
Consumes the Swift unused-result warning.
- Note: You should `catch`, but in situations where you know you don’t need a `catch`, `cauterize` makes your intentions clear.
*/
@discardableResult
func cauterize() -> PMKFinalizer {
return self.catch {
conf.logHandler(.cauterized($0))
}
}
}
public extension CatchMixin where T == Void {
/**
The provided closure executes when this promise rejects.
This variant of `recover` is specialized for `Void` promises and de-errors your chain returning a `Guarantee`, thus you cannot `throw` and you must handle all errors including cancellation.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation)
*/
@discardableResult
func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Error) -> Void) -> Guarantee<Void> {
let rg = Guarantee<Void>(.pending)
pipe {
switch $0 {
case .fulfilled:
rg.box.seal(())
case .rejected(let error):
on.async(flags: flags) {
body(error)
rg.box.seal(())
}
}
}
return rg
}
/**
The provided closure executes when this promise rejects.
This variant of `recover` ensures that no error is thrown from the handler and allows specifying a catch policy.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation)
*/
func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> Void) -> Promise<Void> {
let rg = Promise<Void>(.pending)
pipe {
switch $0 {
case .fulfilled:
rg.box.seal(.fulfilled(()))
case .rejected(let error):
if policy == .allErrors || !error.isCancelled {
on.async(flags: flags) {
do {
rg.box.seal(.fulfilled(try body(error)))
} catch {
rg.box.seal(.rejected(error))
}
}
} else {
rg.box.seal(.rejected(error))
}
}
}
return rg
}
}
| 5120d58b4e9d57f5af8a47e8e1d94a47 | 36.9375 | 208 | 0.571458 | false | false | false | false |
bvankuik/sevendayrogue | refs/heads/master | sevendayrogue/Area.swift | mit | 1 | //
// Area.swift
// sevendayrogue
//
// Created by Bart van Kuik on 13/09/2017.
// Copyright © 2017 DutchVirtual. All rights reserved.
//
import Foundation
struct Area {
let origin: Location
let radius: Int
func contains(location: Location) -> Bool {
let containsX: Bool
let containsY: Bool
if (self.origin.x - radius) <= location.x && (self.origin.x + radius) >= location.x {
containsX = true
} else {
containsX = false
}
if (self.origin.y - radius) <= location.y && (self.origin.y + radius) >= location.y {
containsY = true
} else {
containsY = false
}
let containsXY = (containsX && containsY)
return containsXY
}
}
| af865c1988f88b5c4ceb87b83fad4512 | 21.114286 | 93 | 0.555556 | false | false | false | false |
insidegui/AppleEvents | refs/heads/master | Dependencies/swift-protobuf/Sources/SwiftProtobuf/Visitor.swift | bsd-2-clause | 1 | // Sources/SwiftProtobuf/Visitor.swift - Basic serialization machinery
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Protocol for traversing the object tree.
///
/// This is used by:
/// = Protobuf serialization
/// = JSON serialization (with some twists to account for specialty JSON
/// encodings)
/// = Protobuf text serialization
/// = hashValue computation
///
/// Conceptually, serializers create visitor objects that are
/// then passed recursively to every message and field via generated
/// 'traverse' methods. The details get a little involved due to
/// the need to allow particular messages to override particular
/// behaviors for specific encodings, but the general idea is quite simple.
///
// -----------------------------------------------------------------------------
import Foundation
/// This is the key interface used by the generated `traverse()` methods
/// used for serialization. It is implemented by each serialization protocol:
/// Protobuf Binary, Protobuf Text, JSON, and the Hash encoder.
public protocol Visitor {
/// Called for each non-repeated float field
///
/// A default implementation is provided that just widens the value
/// and calls `visitSingularDoubleField`
mutating func visitSingularFloatField(value: Float, fieldNumber: Int) throws
/// Called for each non-repeated double field
///
/// There is no default implementation. This must be implemented.
mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws
/// Called for each non-repeated int32 field
///
/// A default implementation is provided that just widens the value
/// and calls `visitSingularInt64Field`
mutating func visitSingularInt32Field(value: Int32, fieldNumber: Int) throws
/// Called for each non-repeated int64 field
///
/// There is no default implementation. This must be implemented.
mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws
/// Called for each non-repeated uint32 field
///
/// A default implementation is provided that just widens the value
/// and calls `visitSingularUInt64Field`
mutating func visitSingularUInt32Field(value: UInt32, fieldNumber: Int) throws
/// Called for each non-repeated uint64 field
///
/// There is no default implementation. This must be implemented.
mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws
/// Called for each non-repeated sint32 field
///
/// A default implementation is provided that just forwards to
/// `visitSingularInt32Field`
mutating func visitSingularSInt32Field(value: Int32, fieldNumber: Int) throws
/// Called for each non-repeated sint64 field
///
/// A default implementation is provided that just forwards to
/// `visitSingularInt64Field`
mutating func visitSingularSInt64Field(value: Int64, fieldNumber: Int) throws
/// Called for each non-repeated fixed32 field
///
/// A default implementation is provided that just forwards to
/// `visitSingularUInt32Field`
mutating func visitSingularFixed32Field(value: UInt32, fieldNumber: Int) throws
/// Called for each non-repeated fixed64 field
///
/// A default implementation is provided that just forwards to
/// `visitSingularUInt64Field`
mutating func visitSingularFixed64Field(value: UInt64, fieldNumber: Int) throws
/// Called for each non-repeated sfixed32 field
///
/// A default implementation is provided that just forwards to
/// `visitSingularInt32Field`
mutating func visitSingularSFixed32Field(value: Int32, fieldNumber: Int) throws
/// Called for each non-repeated sfixed64 field
///
/// A default implementation is provided that just forwards to
/// `visitSingularInt64Field`
mutating func visitSingularSFixed64Field(value: Int64, fieldNumber: Int) throws
/// Called for each non-repeated bool field
///
/// There is no default implementation. This must be implemented.
mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws
/// Called for each non-repeated string field
///
/// There is no default implementation. This must be implemented.
mutating func visitSingularStringField(value: String, fieldNumber: Int) throws
/// Called for each non-repeated bytes field
///
/// There is no default implementation. This must be implemented.
mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws
/// Called for each non-repeated enum field
///
/// There is no default implementation. This must be implemented.
mutating func visitSingularEnumField<E: Enum>(value: E, fieldNumber: Int) throws
/// Called for each non-repeated nested message field.
///
/// There is no default implementation. This must be implemented.
mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws
/// Called for each non-repeated proto2 group field.
///
/// A default implementation is provided that simply forwards to
/// `visitSingularMessageField`. Implementors who need to handle groups
/// differently than nested messages can override this and provide distinct
/// implementations.
mutating func visitSingularGroupField<G: Message>(value: G, fieldNumber: Int) throws
// Called for each non-packed repeated float field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularFloatField` once for each item in the array.
mutating func visitRepeatedFloatField(value: [Float], fieldNumber: Int) throws
// Called for each non-packed repeated double field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularDoubleField` once for each item in the array.
mutating func visitRepeatedDoubleField(value: [Double], fieldNumber: Int) throws
// Called for each non-packed repeated int32 field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularInt32Field` once for each item in the array.
mutating func visitRepeatedInt32Field(value: [Int32], fieldNumber: Int) throws
// Called for each non-packed repeated int64 field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularInt64Field` once for each item in the array.
mutating func visitRepeatedInt64Field(value: [Int64], fieldNumber: Int) throws
// Called for each non-packed repeated uint32 field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularUInt32Field` once for each item in the array.
mutating func visitRepeatedUInt32Field(value: [UInt32], fieldNumber: Int) throws
// Called for each non-packed repeated uint64 field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularUInt64Field` once for each item in the array.
mutating func visitRepeatedUInt64Field(value: [UInt64], fieldNumber: Int) throws
// Called for each non-packed repeated sint32 field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularSInt32Field` once for each item in the array.
mutating func visitRepeatedSInt32Field(value: [Int32], fieldNumber: Int) throws
// Called for each non-packed repeated sint64 field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularSInt64Field` once for each item in the array.
mutating func visitRepeatedSInt64Field(value: [Int64], fieldNumber: Int) throws
// Called for each non-packed repeated fixed32 field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularFixed32Field` once for each item in the array.
mutating func visitRepeatedFixed32Field(value: [UInt32], fieldNumber: Int) throws
// Called for each non-packed repeated fixed64 field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularFixed64Field` once for each item in the array.
mutating func visitRepeatedFixed64Field(value: [UInt64], fieldNumber: Int) throws
// Called for each non-packed repeated sfixed32 field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularSFixed32Field` once for each item in the array.
mutating func visitRepeatedSFixed32Field(value: [Int32], fieldNumber: Int) throws
// Called for each non-packed repeated sfixed64 field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularSFixed64Field` once for each item in the array.
mutating func visitRepeatedSFixed64Field(value: [Int64], fieldNumber: Int) throws
// Called for each non-packed repeated bool field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularBoolField` once for each item in the array.
mutating func visitRepeatedBoolField(value: [Bool], fieldNumber: Int) throws
// Called for each non-packed repeated string field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularStringField` once for each item in the array.
mutating func visitRepeatedStringField(value: [String], fieldNumber: Int) throws
// Called for each non-packed repeated bytes field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularBytesField` once for each item in the array.
mutating func visitRepeatedBytesField(value: [Data], fieldNumber: Int) throws
/// Called for each repeated, unpacked enum field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularEnumField` once for each item in the array.
mutating func visitRepeatedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws
/// Called for each repeated nested message field. The method is called once
/// with the complete array of values for the field.
///
/// A default implementation is provided that simply calls
/// `visitSingularMessageField` once for each item in the array.
mutating func visitRepeatedMessageField<M: Message>(value: [M],
fieldNumber: Int) throws
/// Called for each repeated proto2 group field.
///
/// A default implementation is provided that simply calls
/// `visitSingularGroupField` once for each item in the array.
mutating func visitRepeatedGroupField<G: Message>(value: [G], fieldNumber: Int) throws
// Called for each packed, repeated float field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedFloatField(value: [Float], fieldNumber: Int) throws
// Called for each packed, repeated double field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedDoubleField(value: [Double], fieldNumber: Int) throws
// Called for each packed, repeated int32 field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedInt32Field(value: [Int32], fieldNumber: Int) throws
// Called for each packed, repeated int64 field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedInt64Field(value: [Int64], fieldNumber: Int) throws
// Called for each packed, repeated uint32 field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedUInt32Field(value: [UInt32], fieldNumber: Int) throws
// Called for each packed, repeated uint64 field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedUInt64Field(value: [UInt64], fieldNumber: Int) throws
// Called for each packed, repeated sint32 field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedSInt32Field(value: [Int32], fieldNumber: Int) throws
// Called for each packed, repeated sint64 field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedSInt64Field(value: [Int64], fieldNumber: Int) throws
// Called for each packed, repeated fixed32 field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedFixed32Field(value: [UInt32], fieldNumber: Int) throws
// Called for each packed, repeated fixed64 field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedFixed64Field(value: [UInt64], fieldNumber: Int) throws
// Called for each packed, repeated sfixed32 field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedSFixed32Field(value: [Int32], fieldNumber: Int) throws
// Called for each packed, repeated sfixed64 field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedSFixed64Field(value: [Int64], fieldNumber: Int) throws
// Called for each packed, repeated bool field.
///
/// This is called once with the complete array of values for
/// the field.
///
/// There is a default implementation that forwards to the non-packed
/// function.
mutating func visitPackedBoolField(value: [Bool], fieldNumber: Int) throws
/// Called for each repeated, packed enum field.
/// The method is called once with the complete array of values for
/// the field.
///
/// A default implementation is provided that simply forwards to
/// `visitRepeatedEnumField`. Implementors who need to handle packed fields
/// differently than unpacked fields can override this and provide distinct
/// implementations.
mutating func visitPackedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws
/// Called for each map field with primitive values. The method is
/// called once with the complete dictionary of keys/values for the
/// field.
///
/// There is no default implementation. This must be implemented.
mutating func visitMapField<KeyType, ValueType: MapValueType>(
fieldType: _ProtobufMap<KeyType, ValueType>.Type,
value: _ProtobufMap<KeyType, ValueType>.BaseType,
fieldNumber: Int) throws
/// Called for each map field with enum values. The method is called
/// once with the complete dictionary of keys/values for the field.
///
/// There is no default implementation. This must be implemented.
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type,
value: _ProtobufEnumMap<KeyType, ValueType>.BaseType,
fieldNumber: Int) throws where ValueType.RawValue == Int
/// Called for each map field with message values. The method is
/// called once with the complete dictionary of keys/values for the
/// field.
///
/// There is no default implementation. This must be implemented.
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type,
value: _ProtobufMessageMap<KeyType, ValueType>.BaseType,
fieldNumber: Int) throws
/// Called for each extension range.
mutating func visitExtensionFields(fields: ExtensionFieldValueSet, start: Int, end: Int) throws
/// Called for each extension range.
mutating func visitExtensionFieldsAsMessageSet(
fields: ExtensionFieldValueSet,
start: Int,
end: Int) throws
/// Called with the raw bytes that represent any unknown fields.
mutating func visitUnknown(bytes: Data) throws
}
/// Forwarding default implementations of some visitor methods, for convenience.
extension Visitor {
// Default definitions of numeric serializations.
//
// The 32-bit versions widen and delegate to 64-bit versions.
// The specialized integer codings delegate to standard Int/UInt.
//
// These "just work" for Hash and Text formats. Most of these work
// for JSON (32-bit integers are overridden to suppress quoting),
// and a few even work for Protobuf Binary (thanks to varint coding
// which erases the size difference between 32-bit and 64-bit ints).
public mutating func visitSingularFloatField(value: Float, fieldNumber: Int) throws {
try visitSingularDoubleField(value: Double(value), fieldNumber: fieldNumber)
}
public mutating func visitSingularInt32Field(value: Int32, fieldNumber: Int) throws {
try visitSingularInt64Field(value: Int64(value), fieldNumber: fieldNumber)
}
public mutating func visitSingularUInt32Field(value: UInt32, fieldNumber: Int) throws {
try visitSingularUInt64Field(value: UInt64(value), fieldNumber: fieldNumber)
}
public mutating func visitSingularSInt32Field(value: Int32, fieldNumber: Int) throws {
try visitSingularInt32Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitSingularSInt64Field(value: Int64, fieldNumber: Int) throws {
try visitSingularInt64Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitSingularFixed32Field(value: UInt32, fieldNumber: Int) throws {
try visitSingularUInt32Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitSingularFixed64Field(value: UInt64, fieldNumber: Int) throws {
try visitSingularUInt64Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitSingularSFixed32Field(value: Int32, fieldNumber: Int) throws {
try visitSingularInt32Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitSingularSFixed64Field(value: Int64, fieldNumber: Int) throws {
try visitSingularInt64Field(value: value, fieldNumber: fieldNumber)
}
// Default definitions of repeated serializations that just iterate and
// invoke the singular encoding. These "just work" for Protobuf Binary (encoder
// and size visitor), Protobuf Text, and Hash visitors. JSON format stores
// repeated values differently from singular, so overrides these.
public mutating func visitRepeatedFloatField(value: [Float], fieldNumber: Int) throws {
for v in value {
try visitSingularFloatField(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedDoubleField(value: [Double], fieldNumber: Int) throws {
for v in value {
try visitSingularDoubleField(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedInt32Field(value: [Int32], fieldNumber: Int) throws {
for v in value {
try visitSingularInt32Field(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedInt64Field(value: [Int64], fieldNumber: Int) throws {
for v in value {
try visitSingularInt64Field(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedUInt32Field(value: [UInt32], fieldNumber: Int) throws {
for v in value {
try visitSingularUInt32Field(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedUInt64Field(value: [UInt64], fieldNumber: Int) throws {
for v in value {
try visitSingularUInt64Field(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedSInt32Field(value: [Int32], fieldNumber: Int) throws {
for v in value {
try visitSingularSInt32Field(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedSInt64Field(value: [Int64], fieldNumber: Int) throws {
for v in value {
try visitSingularSInt64Field(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedFixed32Field(value: [UInt32], fieldNumber: Int) throws {
for v in value {
try visitSingularFixed32Field(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedFixed64Field(value: [UInt64], fieldNumber: Int) throws {
for v in value {
try visitSingularFixed64Field(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedSFixed32Field(value: [Int32], fieldNumber: Int) throws {
for v in value {
try visitSingularSFixed32Field(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedSFixed64Field(value: [Int64], fieldNumber: Int) throws {
for v in value {
try visitSingularSFixed64Field(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedBoolField(value: [Bool], fieldNumber: Int) throws {
for v in value {
try visitSingularBoolField(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedStringField(value: [String], fieldNumber: Int) throws {
for v in value {
try visitSingularStringField(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedBytesField(value: [Data], fieldNumber: Int) throws {
for v in value {
try visitSingularBytesField(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws {
for v in value {
try visitSingularEnumField(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedMessageField<M: Message>(value: [M], fieldNumber: Int) throws {
for v in value {
try visitSingularMessageField(value: v, fieldNumber: fieldNumber)
}
}
public mutating func visitRepeatedGroupField<G: Message>(value: [G], fieldNumber: Int) throws {
for v in value {
try visitSingularGroupField(value: v, fieldNumber: fieldNumber)
}
}
// Default definitions of packed serialization just defer to the
// repeated implementation. This works for Hash and JSON visitors
// (which do not distinguish packed vs. non-packed) but are
// overridden by Protobuf Binary and Text.
public mutating func visitPackedFloatField(value: [Float], fieldNumber: Int) throws {
try visitRepeatedFloatField(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedDoubleField(value: [Double], fieldNumber: Int) throws {
try visitRepeatedDoubleField(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedInt32Field(value: [Int32], fieldNumber: Int) throws {
try visitRepeatedInt32Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedInt64Field(value: [Int64], fieldNumber: Int) throws {
try visitRepeatedInt64Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedUInt32Field(value: [UInt32], fieldNumber: Int) throws {
try visitRepeatedUInt32Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedUInt64Field(value: [UInt64], fieldNumber: Int) throws {
try visitRepeatedUInt64Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedSInt32Field(value: [Int32], fieldNumber: Int) throws {
try visitPackedInt32Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedSInt64Field(value: [Int64], fieldNumber: Int) throws {
try visitPackedInt64Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedFixed32Field(value: [UInt32], fieldNumber: Int) throws {
try visitPackedUInt32Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedFixed64Field(value: [UInt64], fieldNumber: Int) throws {
try visitPackedUInt64Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedSFixed32Field(value: [Int32], fieldNumber: Int) throws {
try visitPackedInt32Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedSFixed64Field(value: [Int64], fieldNumber: Int) throws {
try visitPackedInt64Field(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedBoolField(value: [Bool], fieldNumber: Int) throws {
try visitRepeatedBoolField(value: value, fieldNumber: fieldNumber)
}
public mutating func visitPackedEnumField<E: Enum>(value: [E],
fieldNumber: Int) throws {
try visitRepeatedEnumField(value: value, fieldNumber: fieldNumber)
}
// Default handling for Groups is to treat them just like messages.
// This works for Text and Hash, but is overridden by Protobuf Binary
// format (which has a different encoding for groups) and JSON
// (which explicitly ignores all groups).
public mutating func visitSingularGroupField<G: Message>(value: G,
fieldNumber: Int) throws {
try visitSingularMessageField(value: value, fieldNumber: fieldNumber)
}
// Default handling of Extensions as a MessageSet to handing them just
// as plain extensions. Formats that what custom behavior can override
// it.
public mutating func visitExtensionFieldsAsMessageSet(
fields: ExtensionFieldValueSet,
start: Int,
end: Int) throws {
try visitExtensionFields(fields: fields, start: start, end: end)
}
// Default handling for Extensions is to forward the traverse to
// the ExtensionFieldValueSet. Formats that don't care about extensions
// can override to avoid it.
/// Called for each extension range.
public mutating func visitExtensionFields(fields: ExtensionFieldValueSet, start: Int, end: Int) throws {
try fields.traverse(visitor: &self, start: start, end: end)
}
}
| e27f3b6d8d5d1ac7c0a79b011a40b372 | 39.458874 | 106 | 0.72655 | false | false | false | false |
superpeteblaze/SwiftyClusters | refs/heads/master | SwiftyClusters/Annotation/MapAnnotation.swift | mit | 1 | //
// SingleAnnotation.swift
// SwiftyClusters
//
// Created by Peter Smith on 06/10/2015.
// Copyright © 2015 PeteSmith. All rights reserved.
//
import MapKit
public class MapAnnotation: NSObject, MKAnnotation {
public var title :String? = ""
public var subtitle :String? = ""
public var coordinate:CLLocationCoordinate2D
override public var hashValue: Int {
get {
return self.calculateHashValue()
}
}
public init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
super.init()
}
private func calculateHashValue() -> Int {
let prime:Int = 7
var result:Int = 1
let toHash = NSString(format: "c[%.8f,%.8f]", coordinate.latitude, coordinate.longitude)
result = prime * result + toHash.hashValue
return result
}
}
func ==(lhs: MapAnnotation, rhs: MapAnnotation) -> Bool {
return lhs.coordinate.isEqual(rhs.coordinate)
}
public extension CLLocationCoordinate2D {
public func isEqual(rhs:CLLocationCoordinate2D) -> Bool {
return self.latitude == rhs.latitude && self.longitude == rhs.longitude
}
} | 411d15e69517cc6385552449292ca40c | 25.636364 | 96 | 0.649018 | false | false | false | false |
suzp1984/IOS-ApiDemo | refs/heads/master | ApiDemo-Swift/ApiDemo-Swift/LayerSampleController.swift | apache-2.0 | 1 | //
// LayerSampleController.swift
// ApiDemo-Swift
//
// Created by Jacob su on 5/26/16.
// Copyright © 2016 iboxpay. All rights reserved.
//
import UIKit
class LayerSampleController: UIViewController, UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource {
let cellIdentifier = "Heriarchy layer"
let demos = ["layer heriarchy", "Drawing into Layers", "Compass", "layer mask", "layer mask2"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Layers"
let table = UITableView(frame: self.view.bounds)
table.delegate = self
table.dataSource = self
table.backgroundColor = UIColor.cyan
self.view.addSubview(table)
self.navigationItem.leftItemsSupplementBackButton = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return demos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style:.default, reuseIdentifier:cellIdentifier)
cell.textLabel!.textColor = UIColor.white
let v2 = UIView() // no need to set frame
v2.backgroundColor = UIColor.blue.withAlphaComponent(0.2)
cell.selectedBackgroundView = v2
// next line no longer necessary in iOS 7!
// cell.textLabel.backgroundColor = UIColor.clearColor()
// next line didn't work until iOS 7!
cell.backgroundColor = UIColor.red
}
cell.textLabel!.text = demos[(indexPath as NSIndexPath).row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch demos[(indexPath as NSIndexPath).row] {
case demos[0]:
self.navigationController!.pushViewController(LayerHierarchyViewController(), animated: true)
case demos[1]:
self.navigationController!.pushViewController(DrawingIntoLayerViewController(), animated: true)
case demos[2]:
self.navigationController!.pushViewController(CompassViewController(), animated: true)
case demos[3]:
self.navigationController!.pushViewController(LayerMaskViewController(), animated: true)
case demos[4]:
self.navigationController!.pushViewController(Layermask2ViewController(), animated: true)
default:
break
}
}
}
| 2eeea53dcf03a6f3173870f1947cc331 | 35.390244 | 123 | 0.648458 | false | false | false | false |
savelii/Swift-cfenv | refs/heads/master | Sources/CloudFoundryEnv/AppEnv.swift | apache-2.0 | 1 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import SwiftyJSON
public struct AppEnv {
public let isLocal: Bool
public let port: Int
public let name: String?
public let bind: String
public let urls: [String]
public let url: String
public let app: JSON
public let services: JSON
/**
* The vcap option property is ignored if not running locally.
*/
public init(options: JSON) throws {
// NSProcessInfo.processInfo().environment returns [String : String]
#if os(Linux)
let environmentVars = ProcessInfo.processInfo().environment
#else
let environmentVars = ProcessInfo.processInfo.environment
#endif
let vcapApplication = environmentVars["VCAP_APPLICATION"]
isLocal = (vcapApplication == nil)
// Get app
app = try AppEnv.parseEnvVariable(isLocal: isLocal, environmentVars: environmentVars,
variableName: "VCAP_APPLICATION", varibleType: "application", options: options)
// Get services
services = try AppEnv.parseEnvVariable(isLocal: isLocal, environmentVars: environmentVars,
variableName: "VCAP_SERVICES", varibleType: "services", options: options)
// Get port
port = try AppEnv.parsePort(environmentVars: environmentVars, app: app)
// Get name
name = AppEnv.parseName(app: app, options: options)
// Get bind (IP address of the application instance)
bind = app["host"].string ?? "0.0.0.0"
// Get urls
urls = AppEnv.parseURLs(isLocal: isLocal, app: app, port: port, options: options)
url = urls[0]
}
/**
* Returns an App object.
*/
public func getApp() -> App? {
// Get limits
let limits: App.Limits
if let memory = app["limits"]["mem"].int,
let disk = app["limits"]["disk"].int,
let fds = app["limits"]["fds"].int {
limits = App.Limits(memory: memory, disk: disk, fds: fds)
} else {
return nil
}
// Get uris
let uris = JSONUtils.convertJSONArrayToStringArray(json: app, fieldName: "uris")
// Create DateUtils instance
let dateUtils = DateUtils()
guard
let name = app["application_name"].string,
let id = app["application_id"].string,
let version = app["version"].string,
let instanceId = app["instance_id"].string,
let instanceIndex = app["instance_index"].int,
let port = app["port"].int,
let startedAt = dateUtils.convertStringToDate(dateString: app["started_at"].string),
let spaceId = app["space_id"].string else {
return nil
}
let startedAtTs = startedAt.timeIntervalSince1970
// App instance should only be created if all required variables exist
let appObj = App(id: id, name: name, uris: uris, version: version,
instanceId: instanceId, instanceIndex: instanceIndex,
limits: limits, port: port, spaceId: spaceId,
startedAtTs: startedAtTs, startedAt: startedAt)
return appObj
}
/**
* Returns all services bound to the application in a dictionary. The key in
* the dictionary is the name of the service, while the value is a Service
* object that contains all the properties for the service.
*/
public func getServices() -> [String:Service] {
var results: [String:Service] = [:]
for (_, servs) in services {
for service in servs.arrayValue { // as! [[String:AnyObject]] {
// A service must have a name and a label
if let name: String = service["name"].string,
let label: String = service["label"].string {
let tags = JSONUtils.convertJSONArrayToStringArray(json: service, fieldName: "tags")
results[name] =
Service(name: name, label: label, plan: service["plan"].string, tags: tags, credentials: service["credentials"])
}
}
}
return results
}
/**
* Returns a Service object with the properties for the specified Cloud Foundry
* service. The spec parameter should be the name of the service
* or a regex to look up the service. If there is no service that matches the
* spec parameter, this method returns nil.
*/
public func getService(spec: String) -> Service? {
let services = getServices()
if let service = services[spec] {
return service
}
do {
#if os(Linux)
let regex = try RegularExpression(pattern: spec, options: RegularExpression.Options.caseInsensitive)
#else
let regex = try NSRegularExpression(pattern: spec, options: NSRegularExpression.Options.caseInsensitive)
#endif
for (name, serv) in services {
let numberOfMatches = regex.numberOfMatches(in: name, options: [], range: NSMakeRange(0, name.characters.count))
if numberOfMatches > 0 {
return serv
}
}
} catch let error as NSError {
print("Error code: \(error.code)")
}
return nil
}
/**
* Returns a URL generated from VCAP_SERVICES for the specified service or nil
* if service is not found. The spec parameter should be the name of the
* service or a regex to look up the service.
*
* The replacements parameter is a JSON object with the properties found in
* Foundation's NSURLComponents class.
*/
public func getServiceURL(spec: String, replacements: JSON?) -> String? {
var substitutions: JSON = replacements ?? [:]
let service = getService(spec: spec)
guard let credentials = service?.credentials else {
return nil
}
guard let url: String =
credentials[substitutions["url"].string ?? "url"].string ?? credentials["uri"].string
else {
return nil
}
substitutions.dictionaryObject?["url"] = nil
guard let parsedURL = NSURLComponents(string: url) else {
return nil
}
// Set replacements in a predefined order
// Before, we were just iterating over the keys in the JSON object,
// but unfortunately the order of the keys returned were different on
// OS X and Linux, which resulted in different outcomes.
if let user = substitutions["user"].string {
parsedURL.user = user
}
if let password = substitutions["password"].string {
parsedURL.password = password
}
if let port = substitutions["port"].number {
parsedURL.port = port
}
if let host = substitutions["host"].string {
parsedURL.host = host
}
if let scheme = substitutions["scheme"].string {
parsedURL.scheme = scheme
}
if let query = substitutions["query"].string {
parsedURL.query = query
}
if let queryItems = substitutions["queryItems"].array {
var urlQueryItems: [URLQueryItem] = []
for queryItem in queryItems {
if let name = queryItem["name"].string {
let urlQueryItem = URLQueryItem(name: name, value: queryItem["value"].string)
urlQueryItems.append(urlQueryItem)
}
}
if urlQueryItems.count > 0 {
parsedURL.queryItems = urlQueryItems
}
}
// These are being ignored at the moment
// if let fragment = substitutions["fragment"].string {
// parsedURL.fragment = fragment
// }
// if let path = substitutions["path"].string {
// parsedURL.path = path
// }
return parsedURL.string
}
/**
* Returns a JSON object that contains the credentials for the specified
* Cloud Foundry service. The spec parameter should be the name of the service
* or a regex to look up the service. If there is no service that matches the
* spec parameter, this method returns nil. In the case there is no credentials
* property for the specified service, an empty JSON is returned.
*/
public func getServiceCreds(spec: String) -> JSON? {
guard let service = getService(spec: spec) else {
return nil
}
if let credentials = service.credentials {
return credentials
} else {
return [:]
}
}
/**
* Static method for parsing VCAP_APPLICATION and VCAP_SERVICES.
*/
private static func parseEnvVariable(isLocal: Bool, environmentVars: [String:String],
variableName: String, varibleType: String, options: JSON) throws
-> JSON {
if isLocal {
let envVariable = options["vcap"][varibleType]
if envVariable.null != nil {
return [:]
}
return envVariable
} else {
if let json = JSONUtils.convertStringToJSON(text: environmentVars[variableName]) {
return json
}
throw CloudFoundryEnvError.InvalidValue("Environment variable \(variableName) is not a valid JSON string!")
}
}
/**
* Static method for parsing the port number.
*/
private static func parsePort(environmentVars: [String:String], app: JSON) throws -> Int {
let portString: String = environmentVars["PORT"] ?? environmentVars["CF_INSTANCE_PORT"] ??
environmentVars["VCAP_APP_PORT"] ?? "8090"
// TODO: Are there any benefits in implementing logic similar to ports.getPort() (npm module)...?
// if portString == nil {
// if app["name"].string == nil {
// portString = "8090"
// }
// //portString = "" + (ports.getPort(appEnv.name));
// portString = "8090"
// }
//let number: Int? = (portString != nil) ? Int(portString!) : nil
if let number = Int(portString) {
return number
} else {
throw CloudFoundryEnvError.InvalidValue("Invalid PORT value: \(portString)")
}
}
/**
* Static method for parsing the name for the application.
*/
private static func parseName(app: JSON, options: JSON) -> String? {
let name: String? = options["name"].string ?? app["name"].string
// TODO: Add logic for parsing manifest.yml to get name
// https://github.com/behrang/YamlSwift
// http://stackoverflow.com/questions/24097826/read-and-write-data-from-text-file
return name
}
/**
* Static method for parsing the URLs for the application.
*/
private static func parseURLs(isLocal: Bool, app: JSON, port: Int,
options: JSON) -> [String] {
var uris: [String] = JSONUtils.convertJSONArrayToStringArray(json: app, fieldName: "uris")
if isLocal {
uris = ["localhost:\(port)"]
} else {
if (uris.count == 0) {
uris = ["localhost"]
}
}
let scheme: String = options["protocol"].string ?? (isLocal ? "http" : "https")
var urls: [String] = []
for uri in uris {
urls.append("\(scheme)://\(uri)");
}
return urls
}
}
| 1bdc1c731394ee6089faf3b2569acad1 | 32.931677 | 124 | 0.653945 | false | false | false | false |
beeth0ven/LTMorphingLabel | refs/heads/master | LTMorphingLabel/LTMorphingLabel+Burn.swift | mit | 5 | //
// LTMorphingLabel+Burn.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2015 Lex Tang, http://lexrus.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
extension LTMorphingLabel {
private func burningImageForCharLimbo(charLimbo: LTCharacterLimbo, withProgress progress: CGFloat) -> (UIImage, CGRect) {
let maskedHeight = charLimbo.rect.size.height * max(0.01, progress)
let maskedSize = CGSizeMake( charLimbo.rect.size.width, maskedHeight)
UIGraphicsBeginImageContextWithOptions(maskedSize, false, UIScreen.mainScreen().scale)
let rect = CGRectMake(0, 0, charLimbo.rect.size.width, maskedHeight)
String(charLimbo.char).drawInRect(rect, withAttributes: [
NSFontAttributeName: self.font,
NSForegroundColorAttributeName: self.textColor
])
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
let newRect = CGRectMake(
charLimbo.rect.origin.x,
charLimbo.rect.origin.y,
charLimbo.rect.size.width,
maskedHeight)
return (newImage, newRect)
}
func BurnLoad() {
startClosures["Burn\(LTMorphingPhaseStart)"] = {
self.emitterView.removeAllEmitters()
}
progressClosures["Burn\(LTMorphingPhaseManipulateProgress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
if !isNewChar {
return min(1.0, max(0.0, progress))
}
let j = Float(sin(Float(index))) * 1.5
return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j))
}
effectClosures["Burn\(LTMorphingPhaseDisappear)"] = {
(char:Character, index: Int, progress: Float) in
return LTCharacterLimbo(
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: 0.0
)
}
effectClosures["Burn\(LTMorphingPhaseAppear)"] = {
(char:Character, index: Int, progress: Float) in
if char != " " {
let rect = self.newRects[index]
let emitterPosition = CGPointMake(
rect.origin.x + rect.size.width / 2.0,
CGFloat(progress) * rect.size.height / 1.2 + rect.origin.y)
self.emitterView.createEmitter("c\(index)", duration: self.morphingDuration) {
(layer, cell) in
layer.emitterSize = CGSizeMake(rect.size.width , 1)
layer.renderMode = kCAEmitterLayerAdditive
layer.emitterMode = kCAEmitterLayerOutline
cell.emissionLongitude = CGFloat(M_PI / 2.0)
cell.scale = self.font.pointSize / 160.0
cell.scaleSpeed = self.font.pointSize / 100.0
cell.birthRate = Float(self.font.pointSize)
cell.contents = UIImage(named: "Fire")!.CGImage
cell.emissionLongitude = CGFloat(arc4random_uniform(30))
cell.emissionRange = CGFloat(M_PI_4)
cell.alphaSpeed = self.morphingDuration * -3.0
cell.yAcceleration = 10
cell.velocity = CGFloat(10 + Int(arc4random_uniform(3)))
cell.velocityRange = 10
cell.spin = 0
cell.spinRange = 0
cell.lifetime = self.morphingDuration / 3.0
}.update {
(layer, cell) in
layer.emitterPosition = emitterPosition
}.play()
self.emitterView.createEmitter("s\(index)", duration: self.morphingDuration) {
(layer, cell) in
layer.emitterSize = CGSizeMake(rect.size.width , 10)
layer.renderMode = kCAEmitterLayerAdditive
layer.emitterMode = kCAEmitterLayerVolume
cell.emissionLongitude = CGFloat(M_PI / 2.0)
cell.scale = self.font.pointSize / 40.0
cell.scaleSpeed = self.font.pointSize / 100.0
cell.birthRate = Float(self.font.pointSize) / Float(arc4random_uniform(10) + 10)
cell.contents = UIImage(named: "Smoke")!.CGImage
cell.emissionLongitude = 0
cell.emissionRange = CGFloat(M_PI_4)
cell.alphaSpeed = self.morphingDuration * -3
cell.yAcceleration = -5
cell.velocity = CGFloat(20 + Int(arc4random_uniform(15)))
cell.velocityRange = 20
cell.spin = CGFloat(Float(arc4random_uniform(30)) / 10.0)
cell.spinRange = 3
cell.lifetime = self.morphingDuration
}.update {
(layer, cell) in
layer.emitterPosition = emitterPosition
}.play()
}
return LTCharacterLimbo(
char: char,
rect: self.newRects[index],
alpha: 1.0,
size: self.font.pointSize,
drawingProgress: CGFloat(progress)
)
}
drawingClosures["Burn\(LTMorphingPhaseDraw)"] = {
(charLimbo: LTCharacterLimbo) in
if charLimbo.drawingProgress > 0.0 {
let (charImage, rect) = self.burningImageForCharLimbo(charLimbo, withProgress: charLimbo.drawingProgress)
charImage.drawInRect(rect)
return true
}
return false
}
skipFramesClosures["Burn\(LTMorphingPhaseSkipFrames)"] = {
return 1
}
}
}
| a4799b5394eca2850bf71676522e25f2 | 42.347305 | 125 | 0.557812 | false | false | false | false |
OMTS/NavigationAppRouter | refs/heads/master | Pod/Classes/NavigationAppRouter.swift | mit | 1 | //
// NavigationAppRouter.swift
// Pods
//
// Created by Florent Poisson on 11/01/2016.
//
//
import UIKit
import MapKit
import AddressBook
/// Third party navigation app list
extension String {
func getAddressUrlEncoded(usePlusSign: Bool) -> String? {
if usePlusSign {
let arrayOfComponents = self.split(separator: " ")
let escapedAddress = arrayOfComponents.joined(separator: "+")
return escapedAddress.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
} else {
return self.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
}
}
}
private enum ThirdPartyNavigationApp {
case googleMaps
case waze
case cityMapper
/**
Get name string of third party navigation app.
*/
func getName() -> String {
switch self {
case .googleMaps:
return "Google Maps"
case .waze:
return "Waze"
case .cityMapper:
return "CityMapper"
}
}
/**
Get third party navigation app URL scheme
*/
func getUrlScheme() -> String {
switch self {
case .googleMaps:
return "comgooglemaps://"
case .waze:
return "waze://"
case .cityMapper:
return "citymapper://"
}
}
/**
Get third party navigation app URL scheme parameters requesting routing to a place.
- Parameters:
- location: the coordinates of the place to go (i.e. latitude & longitude)
- Returns: the location parameters formated string
*/
func getURLSchemeParametersForLocation(_ location: CLLocationCoordinate2D) -> String {
switch self {
case .googleMaps:
return "?daddr=\(location.latitude),\(location.longitude)&directionsmode=driving"
case .waze:
return "?ll=\(location.latitude),\(location.longitude)&navigate=yes"
case .cityMapper:
return "directions?endcoord=\(location.latitude),\(location.longitude)"
}
}
func getURLSchemeParametersForAddress(_ address: String) -> String {
switch self {
case .googleMaps:
return "?q=" + (address.getAddressUrlEncoded(usePlusSign: true) ?? "")
case .waze:
return "?q=" + (address.getAddressUrlEncoded(usePlusSign: false) ?? "")
default:
return ""
}
}
/**
Check if the third party app can be opened by the app.
- Returns: true or false
*/
func canOpen() -> Bool {
return UIApplication.shared.canOpenURL(URL(string: self.getUrlScheme())!)
}
/**
Open the correponding third party navigation requesting routing to a place.
- Parameter place: destination as a placemark.
*/
func goToPlace(_ place: MKPlacemark) {
let urlStr = self.getUrlScheme() + self.getURLSchemeParametersForLocation(CLLocationCoordinate2D(latitude: place.coordinate.latitude, longitude: place.coordinate.longitude))
if let deepLinkUrl = URL(string: urlStr) {
UIApplication.shared.openURL(deepLinkUrl)
}
}
/**
Open the correponding third party navigation requesting searching for an address.
- Parameter address: destination as an address.
*/
func goToAddress(_ address: String) {
let urlStr = self.getUrlScheme() + self.getURLSchemeParametersForAddress(address)
if let deepLinkUrl = URL(string: urlStr) {
UIApplication.shared.openURL(deepLinkUrl)
}
}
/**
Get supported third party navigation apps installed on the device.
- Returns: an array of the supported third party navigation apps.
*/
static func getThirdPartyApplications() -> [ThirdPartyNavigationApp] {
return [ThirdPartyNavigationApp.googleMaps, ThirdPartyNavigationApp.waze, ThirdPartyNavigationApp.cityMapper]
}
/**
Get supported third party navigation apps installation count.
- Returns: installation count
*/
static func getThirdPartyApplicationInstallations() -> Int {
var count = 0
for thirdPartyApp in ThirdPartyNavigationApp.getThirdPartyApplications() {
if thirdPartyApp.canOpen() {
count += 1
}
}
return count
}
}
/// Navigation app router
public class NavigationAppRouter {
/**
Open navigation app selection menu.
- Note: if no supported navigation app is installed, routing request is immediately handled by Maps.
- Parameters:
- place: destination as a placemark,
- fromViewController: view controller presenting the navigation apps if needed.
*/
public static func goToPlace(_ place: MKPlacemark, fromViewController viewController: UIViewController) {
let thirdPartyApplicationInstallations = ThirdPartyNavigationApp.getThirdPartyApplicationInstallations()
if thirdPartyApplicationInstallations > 0 {
// Get bundle for localization strings
let bundlePath: String! = Bundle(for: NavigationAppRouter.self).path(forResource: "NavigationAppRouter", ofType: "bundle")
let bundle: Bundle! = Bundle(path: bundlePath)
// Display action sheet
let alertController = UIAlertController(title: NSLocalizedString("NavigationAppRouter.sheet.title", tableName: nil, bundle: bundle, comment: ""), message: nil, preferredStyle: .actionSheet)
// Default app navigation with Apple Plans
let goWithPlans = UIAlertAction(title: "Plans", style: UIAlertActionStyle.default) { (_) -> Void in
NavigationAppRouter.goWithAppleMapsToPlace(place)
}
alertController.addAction(goWithPlans)
// Third party navigation app management
for thirdPartyApp in ThirdPartyNavigationApp.getThirdPartyApplications() {
if thirdPartyApp.canOpen() {
let goWithThirdPartyApp = UIAlertAction(title: thirdPartyApp.getName(), style: UIAlertActionStyle.default) { (_) -> Void in
thirdPartyApp.goToPlace(place)
}
alertController.addAction(goWithThirdPartyApp)
}
}
let cancel = UIAlertAction(title: NSLocalizedString("NavigationAppRouter.button.title.cancel", tableName: nil, bundle: bundle, comment: ""), style: .cancel, handler: nil)
alertController.addAction(cancel)
viewController.present(alertController, animated: true, completion: nil)
}
else {
NavigationAppRouter.goWithAppleMapsToPlace(place)
}
}
public static func goToPlacefromASimpleAddress(address: String, fromViewController viewController: UIViewController) {
let thirdPartyApplicationInstallations = ThirdPartyNavigationApp.getThirdPartyApplicationInstallations()
if thirdPartyApplicationInstallations > 0 {
let bundlePath: String! = Bundle(for: NavigationAppRouter.self).path(forResource: "NavigationAppRouter", ofType: "bundle")
let bundle: Bundle! = Bundle(path: bundlePath)
// Display action sheet
let alertController = UIAlertController(title: NSLocalizedString("NavigationAppRouter.sheet.title", tableName: nil, bundle: bundle, comment: ""), message: nil, preferredStyle: .actionSheet)
// Default app navigation with Apple Plans
let goWithPlans = UIAlertAction(title: "Plans", style: UIAlertActionStyle.default) { (_) -> Void in
NavigationAppRouter.goWithAppleMapsToAddress(address)
}
alertController.addAction(goWithPlans)
for thirdPartyApp in ThirdPartyNavigationApp.getThirdPartyApplications() {
if thirdPartyApp.canOpen() {
let goWithThirdPartyApp = UIAlertAction(title: thirdPartyApp.getName(), style: UIAlertActionStyle.default) { (_) -> Void in
thirdPartyApp.goToAddress(address)
}
alertController.addAction(goWithThirdPartyApp)
}
}
let cancel = UIAlertAction(title: NSLocalizedString("NavigationAppRouter.button.title.cancel", tableName: nil, bundle: bundle, comment: ""), style: .cancel, handler: nil)
alertController.addAction(cancel)
viewController.present(alertController, animated: true, completion: nil)
} else {
NavigationAppRouter.goWithAppleMapsToAddress(address)
}
}
/**
Open Maps requesting routing to the place.
- Parameter place: the place to go.
*/
private static func goWithAppleMapsToPlace(_ place: MKPlacemark) {
// Current user location
let itemUser = MKMapItem.forCurrentLocation()
// Destination
let itemPlace = MKMapItem(placemark: place)
itemPlace.name = place.name
let mapItems = [itemUser, itemPlace]
let options: [String : Any] = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey: true]
MKMapItem.openMaps(with: mapItems, launchOptions: options)
}
private static func goWithAppleMapsToAddress(_ address: String) {
guard let urlEscapedAddress = address.getAddressUrlEncoded(usePlusSign: true),
let url = URL(string: "http://maps.apple.com/?address=" + urlEscapedAddress),
UIApplication.shared.canOpenURL(url) else {
return
}
UIApplication.shared.openURL(url)
}
}
| 448e3b0a9acdef5a4dd2035c9a05be75 | 34.797101 | 201 | 0.631883 | false | false | false | false |
CartoDB/mobile-ios-samples | refs/heads/master | AdvancedMap.Swift/Feature Demo/Languages.swift | bsd-2-clause | 1 | //
// Languages.swift
// Feature Demo
//
// Created by Aare Undo on 20/06/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
import UIKit
class Languages {
static var list = [Language]()
static func initialize() {
var language = Language()
language.name = "Local"
language.value = ""
list.append(language)
language = Language()
language.name = "English"
language.value = "en"
list.append(language)
language = Language()
language.name = "German"
language.value = "de"
list.append(language)
language = Language()
language.name = "Spanish"
language.value = "es"
list.append(language)
language = Language()
language.name = "Italian"
language.value = "it"
list.append(language)
language = Language()
language.name = "French"
language.value = "fr"
list.append(language)
language = Language()
language.name = "Russian"
language.value = "ru"
list.append(language)
}
}
class Language : NSObject {
var name: String!
var value: String!
}
| 4be2ace9b355ef3bd81341109a532f23 | 19.119403 | 48 | 0.511869 | false | false | false | false |
Zewo/Examples | refs/heads/master | HTTP/Source/ServerMiddleware/main.swift | mit | 1 | import Zewo
let log = Log()
let logger = LogMiddleware(log: log)
let parsers = MediaTypeParserCollection()
parsers.add(JSONMediaType, parser: JSONInterchangeDataParser())
parsers.add(URLEncodedFormMediaType, parser: URLEncodedFormInterchangeDataParser())
let serializers = MediaTypeSerializerCollection()
serializers.add(JSONMediaType, serializer: JSONInterchangeDataSerializer())
serializers.add(URLEncodedFormMediaType, serializer: URLEncodedFormInterchangeDataSerializer())
let contentNegotiation = ServerContentNegotiationMiddleware(
parsers: parsers,
serializers: serializers
)
try Server(middleware: logger, contentNegotiation) { _ in
let content: InterchangeData = [
"foo": "bar",
"hello": "world"
]
return Response(content: content)
}.start() | 3c3b27cb2f42c3f2af1ca0b72ada0576 | 29.5 | 95 | 0.776515 | false | false | false | false |
alblue/swift | refs/heads/master | test/IRGen/witness_table_indirect_conformances.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module -swift-version 4 | %FileCheck %s -DINT=i%target-ptrsize
protocol P1 {
associatedtype AssocP1
}
protocol P2 {
associatedtype AssocP2: P1
func getAssocP2() -> AssocP2
}
protocol P3 {
associatedtype AssocP3: P2 where AssocP3.AssocP2: Q
func getAssocP3() -> AssocP3
}
protocol Q { }
struct X { }
struct Y: P1, Q {
typealias AssocP1 = X
}
struct Z: P2 {
typealias AssocP2 = Y
func getAssocP2() -> Y { return Y() }
}
// CHECK: @"$s35witness_table_indirect_conformances1WVAA2P3AAWP" = hidden global [5 x i8*] [
// CHECK-SAME: @"$s35witness_table_indirect_conformances1WVAA2P3AAMc"
// CHECK-SAME: i8* bitcast (i8** ()* @"$s35witness_table_indirect_conformances1ZVAcA2P2AAWl
// CHECK-SAME: @"symbolic 35witness_table_indirect_conformances1ZV"
// CHECK-SAME: i8* bitcast (void (%T35witness_table_indirect_conformances1ZV*, %T35witness_table_indirect_conformances1WV*, %swift.type*, i8**)* @"$s35witness_table_indirect_conformances1WVAA2P3A2aDP08getAssocE00gE0QzyFTW" to i8*)]
struct W: P3 {
typealias AssocP3 = Z
func getAssocP3() -> Z { return Z() }
}
// CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s35witness_table_indirect_conformances1ZVMa"
// CHECK-SAME: ([[INT]])
// CHECK-NEXT: entry:
// CHECK-NEXT: ret %swift.metadata_response { %swift.type* bitcast {{.*}} @"$s35witness_table_indirect_conformances1ZVMf", i32 0, i32 1) to %swift.type*), [[INT]] 0 }
| ddbfe682869433c12d57928336a4278a | 31.744681 | 231 | 0.721897 | false | false | false | false |
devno/TouchID-Demo | refs/heads/master | TouchID-Demo/ViewController.swift | mit | 1 | //
// ViewController.swift
// TouchID-Demo
//
// Created by Roman Voglhuber on 16/07/15.
// Copyright (c) 2015 Voglhuber. All rights reserved.
//
import UIKit
import LocalAuthentication
class ViewController: UIViewController, UIAlertViewDelegate {
@IBOutlet weak var touchIDButton: UIButton!
@IBOutlet weak var authorizeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func touchIDPressed(sender: AnyObject) {
checkTouchID()
}
func checkTouchID(){
let context = LAContext()
var error: NSError?
let reason = "Authenticate to use this app"
//Check if the device has Touch ID and it is enabled
if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error){
context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply: { (success, evalPolicyError) -> Void in
if success{
//Successfully authenticated
NSLog("User authenticated by Touch ID")
//Update UI in main queue
dispatch_async(dispatch_get_main_queue()) {
self.authorizeLabel.text = "Authenticated by Touch ID"
}
}
else{
NSLog("Touch ID authentication failed: %@", evalPolicyError.localizedDescription)
dispatch_async(dispatch_get_main_queue()) {
self.authorizeLabel.text = "Authentication failed by Touch ID"
}
switch evalPolicyError!.code{
case LAError.SystemCancel.rawValue:
NSLog("Touch ID canceld by system")
case LAError.UserCancel.rawValue:
NSLog("Touch ID canceld by user")
//Fallback "Password" is shown if Touch ID doesn't recognize the first fingerprint
case LAError.UserFallback.rawValue:
NSLog("Password selected")
dispatch_async(dispatch_get_main_queue()) {
self.showPasswordInput()
}
default:
NSLog("Authentication failed")
dispatch_async(dispatch_get_main_queue()) {
self.showPasswordInput()
}
}
}
})
}
else{
NSLog("Touch ID not available")
self.showPasswordInput()
}
}
func showPasswordInput(){
var passwordAlert : UIAlertView = UIAlertView(title: "Password input", message: "Please enter your password: \"password\"", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
passwordAlert.alertViewStyle = UIAlertViewStyle.SecureTextInput
passwordAlert.show()
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 1 && alertView.textFieldAtIndex(0)?.text == "password"{
NSLog("User authenticated by password")
authorizeLabel.text = "Authenticated by password"
}
else{
NSLog("Authentication failed by password")
authorizeLabel.text = "Authentication failed by password"
}
}
}
| 480fa19d9f38eeed6fc32577196d82b7 | 36.413462 | 201 | 0.545875 | false | false | false | false |
YPaul/YXMusicPlayer | refs/heads/master | YXMusic音乐播放器/AudioTool.swift | apache-2.0 | 1 |
//
// AudioTool.swift
// bluetooth
//
// Created by paul-y on 16/2/1.
// Copyright © 2016年 YinQiXing. All rights reserved.
//
import Foundation
import AVFoundation
class AudioTool: NSObject {
static private var soundIDs = [String:SystemSoundID]()
static private var players = [String:AVAudioPlayer]()
/**
播放音效
*/
class func playAudioWith(filename : String){
let soundID = soundIDs[filename]
if soundID == nil{
var mysoundID :SystemSoundID = 0
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if url == nil{
return
}
AudioServicesCreateSystemSoundID(url!, &mysoundID)
self.soundIDs[filename] = mysoundID
}
AudioServicesPlaySystemSound(soundIDs[filename]!)
}
/**
销毁音效
*/
class func disposeAudioWithFilename(filename:String){
if let soundId = soundIDs[filename]{
AudioServicesDisposeSystemSoundID(soundId)
self.soundIDs.removeValueForKey(filename)
}
}
/**
根据音乐文件名称播放音乐
*/
class func playMusicWith(filename:String)->AVAudioPlayer?{
var player = self.players[filename]
if player == nil{
// 2.1根据文件名称加载音效URL
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if url == nil{
return nil
}
do{
player = try AVAudioPlayer(contentsOfURL: url!)
} catch{
}
if !player!.prepareToPlay(){
return player
}
// // 允许快进
// player!.enableRate = true
// player!.rate = 3
self.players[filename] = player!
}
// 3.播放音乐
if !player!.playing{
player!.play()
}
return player
}
/**
根据音乐文件名称暂停音乐
*/
class func pauseMusicWith(filename:String){
if let player = self.players[filename] {
if player.playing{
player.pause()
}
}
}
/**
根据音乐文件名称停止音乐
*/
class func stopMusicWith(filename:String){
if let player = self.players[filename] {
player.stop()
self.players.removeValueForKey(filename)
}
}
}
| c3314f965f795d4423a425cb0e574f66 | 19.570248 | 88 | 0.514263 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.