repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
WilliamHester/Breadit-iOS | Pods/Fuzi/Fuzi/Helpers.swift | 2 | 3632 | // Helpers.swift
// Copyright (c) 2015 Ce Zheng
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import libxml2
// Public Helpers
/// For printing an `XMLNode`
extension XMLNode: CustomStringConvertible, CustomDebugStringConvertible {
/// String printed by `print` function
public var description: String {
return self.rawXML
}
/// String printed by `debugPrint` function
public var debugDescription: String {
return self.rawXML
}
}
/// For printing an `XMLDocument`
extension XMLDocument: CustomStringConvertible, CustomDebugStringConvertible {
/// String printed by `print` function
public var description: String {
return self.root?.rawXML ?? ""
}
/// String printed by `debugPrint` function
public var debugDescription: String {
return self.root?.rawXML ?? ""
}
}
// Internal Helpers
internal extension String {
subscript (nsrange: NSRange) -> String {
let start = startIndex.advancedBy(nsrange.location)
let end = start.advancedBy(nsrange.length)
return self[start..<end]
}
}
// Just a smiling helper operator making frequent UnsafePointer -> String cast
prefix operator ^-^ {}
internal prefix func ^-^ <T> (ptr: UnsafePointer<T>) -> String? {
return String.fromCString(UnsafePointer(ptr))
}
internal prefix func ^-^ <T> (ptr: UnsafeMutablePointer<T>) -> String? {
return String.fromCString(UnsafeMutablePointer(ptr))
}
internal struct LinkedCNodes: SequenceType {
typealias Generator = AnyGenerator<xmlNodePtr>
static let end: xmlNodePtr? = nil
internal var types: [xmlElementType]
func generate() -> Generator {
var node = head
// TODO: change to AnyGenerator when swift 2.1 gets out of the way
return anyGenerator {
var ret = node
while ret != nil && !self.types.contains({ $0 == ret.memory.type }) {
ret = ret.memory.next
}
node = ret != nil ?ret.memory.next :nil
return ret != nil ?ret :LinkedCNodes.end
}
}
let head: xmlNodePtr
init(head: xmlNodePtr, types: [xmlElementType] = [XML_ELEMENT_NODE]) {
self.head = head
self.types = types
}
}
internal func cXMLNodeMatchesTagInNamespace(node: xmlNodePtr, tag: String, ns: String?) -> Bool {
let name = ^-^node.memory.name
var matches = name?.compare(tag, options: .CaseInsensitiveSearch) == .OrderedSame
if let ns = ns {
let cNS = node.memory.ns
if cNS != nil && cNS.memory.prefix != nil {
let prefix = ^-^cNS.memory.prefix
matches = matches && (prefix?.compare(ns, options: .CaseInsensitiveSearch) == .OrderedSame)
}
}
return matches
} | apache-2.0 | a6b48c1175d9d305baf60949d41a8099 | 32.027273 | 97 | 0.708976 | 4.203704 | false | false | false | false |
yyny1789/KrMediumKit | Source/Base/KrBaseTableViewController.swift | 1 | 4947 | //
// BaseTableViewController.swift
// Client
//
// Created by paul on 16/8/1.
// Copyright © 2016年 36Kr. All rights reserved.
//
import UIKit
import Moya
import ObjectMapper
fileprivate var BaseTableViewControllerContext = 0
open class KrBaseTableViewController: KrBaseViewController, UITableViewDelegate, UITableViewDataSource {
open var tableView: UITableView!
open var reloadEnabled: Bool {
return true
}
open var loadMoreEnabled: Bool {
return true
}
// MARK: Lifecycle
deinit {
tableView.delegate = nil
tableView.dataSource = nil
tableView.removeLoadmore()
tableView.removePullToRefresh()
tableView.removeObserver(self, forKeyPath: "contentSize", context: &BaseTableViewControllerContext)
}
init(tableView: UITableView) {
super.init(nibName: nil, bundle: nil)
commonInit(tableView)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
commonInit(nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func commonInit(_ tableView: UITableView?) {
if tableView == nil {
self.tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
} else {
self.tableView = tableView
}
self.tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: &BaseTableViewControllerContext)
}
override open func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .singleLine
tableView.separatorColor = UIColor(hex: 0xf0f0f0)
tableView.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20)
tableView.tableFooterView = UIView()
if reloadEnabled {
tableView.setupPullToRefresh { [weak self] in
self?.refreshData()
}
}
registerCell()
loadingState = .loading
loadingData()
}
// MARK: Layout
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &BaseTableViewControllerContext {
if keyPath == "contentSize" &&
loadMoreEnabled &&
tableView.loadmore == nil &&
tableView.contentSize.height > (tableView.height - tableView.contentInset.top) && tableView.height > 0 &&
tableView.refresher?.state != .loading {
tableView.setupLoadmore(action: { [weak self] in
self?.loadMoreData()
})
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
override open func loadingData() {
refreshData()
}
open func refreshData() {
assertionFailure("must override this")
}
open func loadMoreData() {
assertionFailure("must override this")
}
open func reloadTableView() {
tableView.reloadData()
}
open func registerCell() {
assertionFailure("must override this")
}
open func triggerRefresh() {
self.tableView.refresher?.startRefreshing()
}
// MARK: UITableViewDataSource
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
public func requestList<T: TargetType, O: Mappable>(_ target: T, stub: Bool = false, log: Bool = false, success: @escaping (_ result: ListResponse<O>) -> Void, failure: @escaping (_ error: MoyaError) -> Void) {
_ = NetworkManager.manager.request(target, stub: stub, log: log, success: { (aResult: ListResponse<O>) in
if self.loadMoreEnabled {
if let count = aResult.data?.count {
if count > 0 {
self.tableView.endLoadmore(hasMore: true)
} else {
self.tableView.endLoadmore(hasMore: false)
}
} else {
self.tableView.endLoadmore(hasMore: false)
}
}
success(aResult)
}) { (error) in
failure(error)
}
}
}
| mit | 58120ad7e489bef326f73c2c4d527f82 | 30.291139 | 214 | 0.596481 | 5.144641 | false | false | false | false |
fiveagency/ios-five-ui-components | FiveUIComponents/Classes/Views/SmoothPageControl.swift | 1 | 7757 | //
// SmoothPageControl.swift
// FiveUIComponents
//
// Created by Denis Mendica on 2/21/17.
// Copyright © 2017 Five Agency. All rights reserved.
//
import UIKit
/**
Page control that enables the current page to be a floating point number.
Size and color of neighboring page indicators are interpolated accordingly.
*/
@IBDesignable
public class SmoothPageControl: UIControl {
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/**
Number of page indicators.
*/
@IBInspectable public var numberOfPages: Int = 4 {
didSet {
refreshNumberOfPages()
}
}
/**
Spacing between page indicators.
*/
@IBInspectable public var pageIndicatorSpacing: CGFloat = 20 {
didSet {
refreshSpacing()
}
}
/**
Radius of page indicators that do not represent the current page.
*/
@IBInspectable public var pageIndicatorRadius: CGFloat = 5 {
didSet {
refreshPageIndicatorRadii()
}
}
/**
Color of page indicators that do not represent the current page.
*/
@IBInspectable public var pageIndicatorColor: UIColor = UIColor(white: 220.0 / 255.0, alpha: 1.0) {
didSet {
refreshPageIndicatorColors()
}
}
/**
Index of the page indicator that is highlighted.
If this number if not an integer, size and color of two neighboring indicators
are interpolated accordingly to represent the page.
*/
@IBInspectable public var currentPage: CGFloat = 0 {
didSet {
refreshCurrentPage()
}
}
/**
Radius of page indicator that represents the current page.
*/
@IBInspectable public var currentPageIndicatorRadius: CGFloat = 7 {
didSet {
refreshPageIndicatorRadii()
}
}
/**
Color of page indicator that represents the current page.
*/
@IBInspectable public var currentPageIndicatorColor: UIColor = .fiveRed {
didSet {
refreshPageIndicatorColors()
}
}
/**
Duration of the animation that updates the current page once the control was tapped.
*/
public var animationDuration: TimeInterval = 0.15
private var stackView: UIStackView!
private func setup() {
stackView = UIStackView()
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
matchAttribute(.centerX, of: stackView, toSameAttributeOf: self)
matchAttribute(.centerY, of: stackView, toSameAttributeOf: self)
stackView.axis = .horizontal
stackView.distribution = .equalCentering
stackView.alignment = .center
refreshNumberOfPages()
refreshSpacing()
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
addGestureRecognizer(gestureRecognizer)
}
private func refreshNumberOfPages() {
let currentNumberOfPages = stackView.arrangedSubviews.count
let offset = numberOfPages - currentNumberOfPages
guard offset != 0 else { return }
if offset > 0 {
for _ in 0..<offset {
let pageIndicator = PageIndicatorView()
stackView.addArrangedSubview(pageIndicator)
}
} else {
let firstPageIndicatorToRemove = currentNumberOfPages + offset
let lastPageIndicatorToRemove = currentNumberOfPages - 1
let pageIndicatorsToRemove = stackView.arrangedSubviews[firstPageIndicatorToRemove...lastPageIndicatorToRemove]
pageIndicatorsToRemove.forEach { $0.removeFromSuperview() }
}
refreshCurrentPage()
}
private func refreshCurrentPage() {
refreshPageIndicatorRadii()
refreshPageIndicatorColors()
}
private func refreshPageIndicatorRadii() {
let pageIndicators = stackView.arrangedSubviews.flatMap { $0 as? PageIndicatorView }
pageIndicators.forEach { $0.radius = self.pageIndicatorRadius }
for (index, pageIndicator) in pageIndicators.enumerated() {
let t = interpolationParameter(forPageIndicatorAtIndex: index)
let radius = currentPageIndicatorRadius - t * (currentPageIndicatorRadius - pageIndicatorRadius)
pageIndicator.scale = radius / pageIndicator.radius
}
}
private func refreshPageIndicatorColors() {
let pageIndicators = stackView.arrangedSubviews.flatMap { $0 as? PageIndicatorView }
for (index, pageIndicator) in pageIndicators.enumerated() {
let t = interpolationParameter(forPageIndicatorAtIndex: index)
let color = interpolate(from: currentPageIndicatorColor, to: pageIndicatorColor, t: t)
pageIndicator.backgroundColor = color
}
}
private func refreshSpacing() {
stackView.spacing = pageIndicatorSpacing
}
private func interpolationParameter(forPageIndicatorAtIndex index: Int) -> CGFloat {
return min(1, abs(CGFloat(index) - currentPage))
}
private func matchAttribute(_ attribute: NSLayoutAttribute, of view1: UIView, toSameAttributeOf view2: UIView) {
let constraint = NSLayoutConstraint(item: view1, attribute: attribute, relatedBy: .equal, toItem: view2, attribute: attribute, multiplier: 1, constant: 0)
addConstraint(constraint)
}
private func interpolate(from color1: UIColor, to color2: UIColor, t: CGFloat) -> UIColor {
let rgbaComponents1 = color1.rgbaComponents
let rgbaComponents2 = color2.rgbaComponents
let color = UIColor(red: rgbaComponents1.red + t * (rgbaComponents2.red - rgbaComponents1.red),
green: rgbaComponents1.green + t * (rgbaComponents2.green - rgbaComponents1.green),
blue: rgbaComponents1.blue + t * (rgbaComponents2.blue - rgbaComponents1.blue),
alpha: rgbaComponents1.alpha + t * (rgbaComponents2.alpha - rgbaComponents1.alpha))
return color
}
@objc private func handleTap(_ gestureRecognizer: UITapGestureRecognizer) {
let leftMargin = (bounds.width - stackView.bounds.width) / 2
let normalizedCurrentPageLocation = currentPage / CGFloat(numberOfPages - 1)
let controlWidth = (stackView.bounds.width - 2 * pageIndicatorRadius)
let currentPageLocationX = leftMargin + pageIndicatorRadius + normalizedCurrentPageLocation * controlWidth
let tapLocationX = gestureRecognizer.location(in: self).x
guard tapLocationX != currentPageLocationX else { return }
let nextPage = Int(currentPage) + (tapLocationX > currentPageLocationX ? 1 : -1)
guard nextPage >= 0 && nextPage < numberOfPages else { return }
UIView.animate(withDuration: animationDuration) { [weak self] in
self?.currentPage = CGFloat(nextPage)
}
sendActions(for: .valueChanged)
}
}
private class PageIndicatorView: UIView {
var radius: CGFloat = 0 {
didSet {
layer.cornerRadius = radius
invalidateIntrinsicContentSize()
}
}
var scale: CGFloat = 1 {
didSet {
transform = CGAffineTransform(scaleX: scale, y: scale)
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 2 * radius, height: 2 * radius)
}
}
| mit | 18d3ef541271292fb2e5f4648d986113 | 33.167401 | 162 | 0.63886 | 5.323267 | false | false | false | false |
kentaiwami/masamon | masamon/masamon/HourlyWageSetting.swift | 1 | 10555 | //
// HourlyWageSetting.swift
// masamon
//
// Created by 岩見建汰 on 2015/10/28.
// Copyright © 2015年 Kenta. All rights reserved.
//
import UIKit
import Eureka
class HourlyWageSetting: FormViewController {
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
var timeUIPicker: UIPickerView = UIPickerView()
let time = Utility().GetTime()
var default_daytime_s = ""
var default_daytime_e = ""
var default_daytime_wage = 0
var default_nighttime_s = ""
var default_nighttime_e = ""
var default_nighttime_wage = 0
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black
CreateForm()
}
func CreateForm() {
let RuleRequired_M = "必須項目です"
LabelRow.defaultCellUpdate = { cell, row in
cell.contentView.backgroundColor = .red
cell.textLabel?.textColor = .white
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 13)
cell.textLabel?.textAlignment = .right
}
default_daytime_s = time[0]
default_daytime_e = time[0]
default_daytime_wage = 0
default_nighttime_s = time[0]
default_nighttime_e = time[0]
default_nighttime_wage = 0
if DBmethod().DBRecordCount(HourlyPayDB.self) != 0 {
let hourlypayarray = DBmethod().HourlyPayRecordGet()
default_daytime_s = time[Int(hourlypayarray[0].timefrom * 2) - 2]
default_daytime_e = time[Int(hourlypayarray[0].timeto * 2) - 2]
default_nighttime_s = time[Int(hourlypayarray[1].timefrom * 2) - 2]
default_nighttime_e = time[Int(hourlypayarray[1].timeto * 2) - 2]
default_daytime_wage = hourlypayarray[0].pay
default_nighttime_wage = hourlypayarray[1].pay
}
form +++ Section("日中")
<<< PickerInputRow<String>(""){
$0.title = "開始時間"
$0.options = time
$0.value = default_daytime_s
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
$0.tag = "daytime_s"
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, _) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = RuleRequired_M
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
<<< PickerInputRow<String>(""){
$0.title = "終了時間"
$0.options = time
$0.value = default_daytime_e
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
$0.tag = "daytime_e"
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, _) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = RuleRequired_M
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
<<< IntRow(){
$0.title = "時給"
$0.value = default_daytime_wage
$0.tag = "daytime_wage"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, _) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = RuleRequired_M
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
form +++ Section(header: "深夜", footer: "値を全て入力しないと値が保存されません")
<<< PickerInputRow<String>(""){
$0.title = "開始時間"
$0.options = time
$0.value = default_nighttime_s
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
$0.tag = "nighttime_s"
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, _) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = RuleRequired_M
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
<<< PickerInputRow<String>(""){
$0.title = "終了時間"
$0.options = time
$0.value = default_nighttime_e
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
$0.tag = "nighttime_e"
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, _) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = RuleRequired_M
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
<<< IntRow(){
$0.title = "時給"
$0.value = default_nighttime_wage
$0.tag = "nighttime_wage"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, _) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = RuleRequired_M
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
var validate_err_count = 0
for row in form.allRows {
validate_err_count += row.validate().count
}
if validate_err_count == 0 {
let daytime_s = form.values()["daytime_s"] as! String
let daytime_e = form.values()["daytime_e"] as! String
let daytime_wage = form.values()["daytime_wage"] as! Int
let nighttime_s = form.values()["nighttime_s"] as! String
let nighttime_e = form.values()["nighttime_e"] as! String
let nighttime_wage = form.values()["nighttime_wage"] as! Int
let hourlypayrecord_daytime = HourlyPayDB()
let hourlypayrecord_nighttime = HourlyPayDB()
hourlypayrecord_daytime.id = 1
hourlypayrecord_daytime.timefrom = Double(time.index(of: daytime_s)!) - (Double(time.index(of: daytime_s)!)*0.5) + 1.0
hourlypayrecord_daytime.timeto = Double(time.index(of: daytime_e)!)-(Double(time.index(of: daytime_e)!)*0.5) + 1.0
hourlypayrecord_daytime.pay = daytime_wage
hourlypayrecord_nighttime.id = 2
hourlypayrecord_nighttime.timefrom = Double(time.index(of: nighttime_s)!)-(Double(time.index(of: nighttime_s)!)*0.5) + 1.0
hourlypayrecord_nighttime.timeto = Double(time.index(of: nighttime_e)!)-(Double(time.index(of: nighttime_e)!)*0.5) + 1.0
hourlypayrecord_nighttime.pay = nighttime_wage
DBmethod().AddandUpdate(hourlypayrecord_daytime,update: true)
DBmethod().AddandUpdate(hourlypayrecord_nighttime,update: true)
}else {
present(Utility().GetStandardAlert(title: "エラー", message: "入力されていない項目があるため保存できませんでした", b_title: "OK"),animated: false, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 559d1a96e0992c17a047314973e5ad07 | 41.757202 | 147 | 0.478633 | 4.41189 | false | false | false | false |
SakuragiYoshimasa/FluctuateViewController | FluctuateViewController/FluctuateView.swift | 1 | 14052 | //
// FluctuateView.swift
// Demo
//
// Created by Yoshimasa Sakuragi on 2017/09/24.
// Copyright © 2017年 Yoshimasa Sakuragi. All rights reserved.
//
import UIKit
public enum FluctuateViewState {
case fullCovered
case noContent
case fixedContent
case fullContent
case fullByFix
}
public struct FluctuateViewPropaties {
public var duration: CGFloat
public var menuHeight: CGFloat
public var menuOffsetOnNocontentMode: CGFloat
public var menuOffsetOnFixedContentMode: CGFloat
public var fullCoveredOffset: CGFloat
public init(animationDuration: CGFloat,
menuHeight: CGFloat,
offsetOnNocontent: CGFloat,
offsetOnFixedContent: CGFloat,
fullCoveredOffset: CGFloat ){
self.duration = animationDuration
self.menuHeight = menuHeight
self.menuOffsetOnNocontentMode = offsetOnNocontent
self.menuOffsetOnFixedContentMode = offsetOnFixedContent
self.fullCoveredOffset = fullCoveredOffset
}
public static func defaultPropaties() -> FluctuateViewPropaties {
return FluctuateViewPropaties(animationDuration: 0.3, menuHeight: 100, offsetOnNocontent: 400, offsetOnFixedContent: 300, fullCoveredOffset: 100)
}
}
open class FluctuateView : UIView {
open weak var dataSource: FluctuateViewDataSource? {
didSet {
guard let _ = dataSource else { return }
self.updateData()
}
}
open weak var delegate: FluctuateViewDelegate?
open var state: FluctuateViewState = .fullCovered
open var cover: CoverView?
open var menu: MenuView?
open var content: ContentView?
open var nocontent: NoContentView?
open var propaties: FluctuateViewPropaties
open weak var fullByFixContent: UIView?
private var isAnimation: Bool = false
public convenience init(frame: CGRect, propaties: FluctuateViewPropaties) {
self.init(frame: frame)
self.propaties = propaties
initialize()
}
public override init(frame: CGRect){
propaties = .defaultPropaties()
super.init(frame: frame)
initialize()
}
required public init?(coder aDecoder: NSCoder) {
propaties = .defaultPropaties()
super.init(coder: aDecoder)
initialize()
}
public func setPropaties(propaties: FluctuateViewPropaties){
self.propaties = propaties
}
fileprivate func initialize(){
state = .fullCovered
}
fileprivate func update(_ nextState: FluctuateViewState, content contentIndex: Int?){
if isAnimation { return }
isAnimation = true
UIApplication.shared.beginIgnoringInteractionEvents()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(propaties.duration + 0.4)) {
UIApplication.shared.endIgnoringInteractionEvents()
self.isAnimation = false
}
if let contIndex = contentIndex {
if nextState != .fullContent {
content?.show(contIndex)
transition(prev: state, next: nextState, completion: {
self.state = nextState
self.delegate?.onStateChage(self.state)
self.isUserInteractionEnabled = true
})()
} else {
transition(prev: state, next: .noContent, completion: {
self.state = .noContent
self.content?.show(contIndex)
self.transition(prev: .noContent, next: nextState, completion: {
self.state = nextState
self.delegate?.onStateChage(self.state)
self.isUserInteractionEnabled = true
})()
})()
}
} else {
transition(prev: state, next: nextState, completion: {
self.state = nextState
self.delegate?.onStateChage(self.state)
self.isUserInteractionEnabled = true
})()
}
}
open func updateData(){
clear()
content = ContentView(frame: self.frame)
content?.clearContents()
content?.setOffset(0, self.frame.height)
content?.delegate = self
content?.registerHeader(header: dataSource!.fullContentHeader())
content?.registerHeaderByFixed(header: dataSource!.fullContentHeaderByFixed())
for i in 0..<(dataSource!.contentsCount()) {
content?.registerContent(content: (dataSource?.fluctuateView(self, contentByIndex: i).view)!,
type: (dataSource?.fluctuateView(self, contentTypeByIndex: i))!,
title: (dataSource?.fluctuateView(self, contentTitle: i))!)
}
addSubview(content!)
nocontent = dataSource?.noContentView()
nocontent?.setOffset(propaties.menuOffsetOnNocontentMode + propaties.menuHeight)
addSubview(nocontent!)
menu = dataSource?.menuView()
menu?.setOffset(propaties.menuOffsetOnNocontentMode)
menu?.delegate = self
menu?.recreateMenuViewByContents(dataSource: self.dataSource!)
addSubview(menu!)
cover = dataSource?.coverView()
cover?.setUnchor(self.frame.height)
cover?.delegate = self
addSubview(cover!)
}
fileprivate func clear(){
menu?.removeFromSuperview()
cover?.removeFromSuperview()
content?.removeFromSuperview()
nocontent?.removeFromSuperview()
}
}
extension FluctuateView : FluctuateCoverViewDelegate {
public func coverUp() { update(.noContent, content: nil) }
public func coverDown() {
switch state {
case .fullCovered:
break
case .noContent:
update(.fullCovered, content: nil)
break
default:
update(.noContent, content: nil)
break
}
}
}
extension FluctuateView : FluctuateMenuViewDelegate {
public func selectContent(_ contentIndex: Int) {
if contentIndex > dataSource!.contentsCount() { return }
delegate?.onCotentSelected(contentIndex)
update(dataSource!.fluctuateView(self, contentTypeByIndex: contentIndex) == .fixed ? .fixedContent : .fullContent, content: contentIndex)
}
}
extension FluctuateView : FluctuateContentViewDelegate {
public func backToNoContent() {
update(.noContent, content: nil)
}
public func transitionToFullFromFixed(fullView: UIView){
self.fullByFixContent = fullView
update(.fullByFix, content: nil)
}
public func backToFixeContentFromFull(contentIndex: Int) {
update(.fixedContent, content: nil)
}
}
//Animations
extension FluctuateView {
fileprivate func transition(prev prevState: FluctuateViewState, next nextState: FluctuateViewState, completion: @escaping () -> ()) -> () -> () {
switch nextState {
case .fullCovered:
return {
UIView.animate(withDuration: TimeInterval(self.propaties.duration), animations: {
self.cover?.setUnchor(self.frame.height)
}, completion: { _ in
completion()
})
}
case .noContent:
if prevState == .fullContent {
return {
self.frame.origin = CGPoint(x: -self.frame.width, y: 0)
self.nocontent?.setOffset(self.propaties.menuOffsetOnNocontentMode + self.propaties.menuHeight)
self.menu?.setOffset(self.propaties.menuOffsetOnNocontentMode)
self.cover?.setUnchor(self.propaties.menuOffsetOnNocontentMode)
self.content?.setOffset(self.frame.width, 0)
UIView.animate(withDuration: TimeInterval(self.propaties.duration), delay:0, options: [.curveEaseInOut], animations: {
self.frame.origin = CGPoint(x: 0, y: 0)
self.content?.setOffset(0 , 0)
}, completion: { _ in
self.content?.setOffset( 0, self.frame.height)
completion()
})
}
}else{
return {
let tempState = self.state
UIView.animate(withDuration: TimeInterval(self.propaties.duration), delay:0, options: [.curveEaseInOut], animations: {
self.cover?.setUnchor(nextState != .fullContent ? self.propaties.menuOffsetOnNocontentMode : self.propaties.fullCoveredOffset)
self.menu?.setOffset(self.propaties.menuOffsetOnNocontentMode)
self.content?.setOffset(self.frame.height)
self.nocontent?.setOffset(self.propaties.menuOffsetOnNocontentMode + self.propaties.menuHeight)
}, completion: { _ in
if tempState == .fixedContent {
self.exchangeSubview(at: 0, withSubviewAt: 1)
}
completion()
})
}
}
case .fixedContent:
if prevState != .fixedContent && prevState != .fullByFix {
return {
self.exchangeSubview(at: 0, withSubviewAt: 1)
UIView.animate(withDuration: TimeInterval(self.propaties.duration), delay:0, options: [.curveEaseInOut], animations: {
self.content?.setOffset(self.propaties.menuOffsetOnNocontentMode + self.propaties.menuHeight)
}, completion: { _ in
UIView.animate(withDuration: TimeInterval(self.propaties.duration), delay:0, options: [.curveEaseInOut], animations: {
self.cover?.setUnchor(nextState != .fullContent ? self.propaties.menuOffsetOnFixedContentMode : self.propaties.fullCoveredOffset)
self.menu?.setOffset(self.propaties.menuOffsetOnFixedContentMode)
self.content?.setOffset(self.propaties.menuOffsetOnFixedContentMode + self.propaties.menuHeight)
}, completion: { _ in
self.nocontent?.setOffset(self.propaties.menuOffsetOnFixedContentMode + self.propaties.menuHeight)
completion()
})
})
}
}
if prevState == .fullByFix {
return {
self.sendSubview(toBack: self.fullByFixContent!)
UIView.animate(withDuration: TimeInterval(self.propaties.duration), delay:0, options: [.curveEaseInOut], animations: {
self.menu?.setOffset(0 ,self.propaties.menuOffsetOnFixedContentMode)
self.cover?.setUnchor(withOffsetX: 0, self.propaties.menuOffsetOnFixedContentMode)
self.content?.setOffset(0, self.propaties.menuOffsetOnFixedContentMode + self.propaties.menuHeight)
self.nocontent?.setOffset(0, self.propaties.menuOffsetOnFixedContentMode + self.propaties.menuHeight)
}, completion: { _ in
self.fullByFixContent?.removeFromSuperview()
self.content?.showOtherContent()
completion()
})
}
}
case .fullContent:
return {
self.content?.setOffset(0)
UIView.animate(withDuration: TimeInterval(self.propaties.duration), delay:0, options: [.curveEaseInOut], animations: {
self.cover?.setUnchor(withOffsetX: -self.frame.width, self.propaties.menuOffsetOnNocontentMode)
self.menu?.setOffset(-self.frame.width, self.propaties.menuOffsetOnNocontentMode)
self.nocontent?.setOffset(-self.frame.width, self.propaties.menuOffsetOnNocontentMode + self.propaties.menuHeight)
}, completion: { _ in
completion()
})
}
case .fullByFix:
return {
self.addSubview(self.fullByFixContent!)
self.sendSubview(toBack: self.fullByFixContent!)
self.fullByFixContent?.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
self.content?.hideOtherContent()
UIView.animate(withDuration: TimeInterval(self.propaties.duration), delay:0, options: [.curveEaseInOut], animations: {
self.cover?.setUnchor(withOffsetX: -self.frame.width, self.propaties.menuOffsetOnFixedContentMode)
self.menu?.setOffset(-self.frame.width, self.propaties.menuOffsetOnFixedContentMode)
self.content?.setOffset(-self.frame.width , self.propaties.menuHeight + self.propaties.menuOffsetOnFixedContentMode)
self.nocontent?.setOffset(-self.frame.width, self.propaties.menuOffsetOnFixedContentMode + self.propaties.menuHeight)
//self.fullByFixContent?.frame.origin = CGPoint(x: 0, y: 0)
}, completion: { _ in
self.bringSubview(toFront: self.fullByFixContent!)
completion()
})
}
}
return {}
}
}
| mit | 9fcf614a3a6593fb483b3817a0d94dca | 39.604046 | 157 | 0.571073 | 4.844483 | false | false | false | false |
Jubilant-Appstudio/Scuba | Pods/SwifterSwift/Sources/Extensions/SwiftStdlib/SignedIntegerExtensions.swift | 1 | 1986 | //
// SignedIntegerExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/15/17.
//
//
import Foundation
// MARK: - Properties
public extension SignedInteger {
/// SwifterSwift: Absolute value of integer number.
public var abs: Self {
return Swift.abs(self)
}
/// SwifterSwift: Check if integer is positive.
public var isPositive: Bool {
return self > 0
}
/// SwifterSwift: Check if integer is negative.
public var isNegative: Bool {
return self < 0
}
/// SwifterSwift: Check if integer is even.
public var isEven: Bool {
return (self % 2) == 0
}
/// SwifterSwift: Check if integer is odd.
public var isOdd: Bool {
return (self % 2) != 0
}
/// SwifterSwift: Array of digits of integer value.
public var digits: [Self] {
let intsArray = description.flatMap({Int(String($0))})
return intsArray.map({Self($0)})
}
/// SwifterSwift: Number of digits of integer value.
public var digitsCount: Int {
return description.flatMap({Int(String($0))}).count
}
/// SwifterSwift: String of format (XXh XXm) from seconds Int.
public var timeString: String {
guard self > 0 else {
return "0 sec"
}
if self < 60 {
return "\(self) sec"
}
if self < 3600 {
return "\(self / 60) min"
}
let hours = self / 3600
let mins = (self % 3600) / 60
if hours != 0 && mins == 0 {
return "\(hours)h"
}
return "\(hours)h \(mins)m"
}
}
// MARK: - Methods
public extension SignedInteger {
/// SwifterSwift: Greatest common divisor of integer value and n.
///
/// - Parameter n: integer value to find gcd with.
/// - Returns: greatest common divisor of self and n.
public func gcd(of n: Self) -> Self {
return n == 0 ? self : n.gcd(of: self % n)
}
/// SwifterSwift: Least common multiple of integer and n.
///
/// - Parameter n: integer value to find lcm with.
/// - Returns: least common multiple of self and n.
public func lcm(of n: Self) -> Self {
return (self * n).abs / gcd(of: n)
}
}
| mit | 87229b042d94caf6ade13040e4e7f276 | 20.824176 | 66 | 0.639476 | 3.261084 | false | false | false | false |
Moya/ReactiveMoya | ReactiveMoya/Moya+ReactiveCocoa.swift | 2 | 8255 | import Foundation
import ReactiveCocoa
import Result
/// Subclass of MoyaProvider that returns SignalProducer<MoyaResponse, NSError> instances when requests are made. Much better than using completion closures.
public class ReactiveCocoaMoyaProvider<T where T: MoyaTarget>: MoyaProvider<T> {
/// Current requests that have not completed or errored yet.
/// Note: Do not access this directly. It is public only for unit-testing purposes (sigh).
public var inflightRequests = Dictionary<Endpoint<T>, Signal<MoyaResponse, NSError>>()
/// Initializes a reactive provider.
override public init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil) {
super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure)
}
public func request(token: T) -> SignalProducer<MoyaResponse, NSError> {
let endpoint = self.endpoint(token)
if let existingSignal = inflightRequests[endpoint] {
/// returns a new producer which forwards all events of the already existing request signal
return SignalProducer { sink, disposable in
/// connect all events of the existing signal to the observer of this signal producer
existingSignal.observe(sink)
}
}
else {
/// returns a new producer which starts a new producer which invokes the requests. The created signal of the inner producer is saved for inflight request
return SignalProducer { [weak self] sink, _ in
let producer: SignalProducer<MoyaResponse, NSError> = SignalProducer { [weak self] sink, disposable in
let cancellableToken = self?.request(token) { data, statusCode, response, error in
if let error = error {
if let statusCode = statusCode {
sendError(sink, NSError(domain: error.domain, code: statusCode, userInfo: error.userInfo))
} else {
sendError(sink, error)
}
} else {
if let data = data {
sendNext(sink, MoyaResponse(statusCode: statusCode!, data: data, response: response))
}
}
sendCompleted(sink)
}
disposable.addDisposable {
if let weakSelf = self {
objc_sync_enter(weakSelf)
// Clear the inflight request
weakSelf.inflightRequests[endpoint] = nil
objc_sync_exit(weakSelf)
// Cancel the request
cancellableToken?.cancel()
}
}
}
/// starts the inner signal producer and store the created signal.
producer |> startWithSignal { [weak self] signal, _ in
objc_sync_enter(self)
self?.inflightRequests[endpoint] = signal
objc_sync_exit(self)
/// connect all events of the signal to the observer of this signal producer
signal.observe(sink)
}
}
}
}
public func request(token: T) -> RACSignal {
return toRACSignal(self.request(token))
}
}
/// Extension for mapping to a certain response type
public extension ReactiveCocoaMoyaProvider {
public func requestJSON(token: T) -> SignalProducer<AnyObject, NSError> {
return request(token) |> mapJSON()
}
public func requestJSONArray(token: T) -> SignalProducer<NSArray, NSError> {
return requestJSON(token) |> mapJSONArray()
}
public func requestJSONDictionary(token: T) -> SignalProducer<NSDictionary, NSError> {
return requestJSON(token) |> mapJSONDictionary()
}
public func requestImage(token: T) -> SignalProducer<UIImage, NSError> {
return request(token) |> mapImage()
}
public func requestString(token: T) -> SignalProducer<String, NSError> {
return request(token) |> mapString()
}
}
/// MoyaResponse free functions
public func filterStatusCode(range: ClosedInterval<Int>) -> SignalProducer<MoyaResponse, NSError> -> SignalProducer<MoyaResponse, NSError> {
return { producer in
return producer |> flatMap(.Latest, { response in
if range.contains(response.statusCode) {
return SignalProducer(value: response)
} else {
return SignalProducer(error: ReactiveMoyaError.StatusCode(response).toError())
}
})
}
}
public func filterStatusCode(code: Int) -> SignalProducer<MoyaResponse, NSError> -> SignalProducer<MoyaResponse, NSError> {
return filterStatusCode(code...code)
}
public func filterSuccessfulStatusCodes() -> SignalProducer<MoyaResponse, NSError> -> SignalProducer<MoyaResponse, NSError> {
return filterStatusCode(200...299)
}
public func filterSuccessfulAndRedirectCodes() -> SignalProducer<MoyaResponse, NSError> -> SignalProducer<MoyaResponse, NSError> {
return filterStatusCode(200...399)
}
/// Maps the `MoyaResponse` to a `UIImage`
public func mapImage() -> SignalProducer<MoyaResponse, NSError> -> SignalProducer<UIImage, NSError> {
return { producer in
return producer |> flatMap(.Latest, { response in
if let image = UIImage(data: response.data) {
return SignalProducer(value: image)
} else {
return SignalProducer(error: ReactiveMoyaError.ImageMapping(response).toError())
}
})
}
}
/// Maps the `MoyaResponse` to JSON
public func mapJSON() -> SignalProducer<MoyaResponse, NSError> -> SignalProducer<AnyObject, NSError> {
return { producer in
return producer |> flatMap(.Latest, { response in
var error: NSError?
if let json: AnyObject = NSJSONSerialization.JSONObjectWithData(response.data, options: .AllowFragments, error: &error) {
return SignalProducer(value: json)
} else {
return SignalProducer(error: ReactiveMoyaError.JSONMapping(response).toError())
}
})
}
}
/// Maps a JSON object to an NSArray
public func mapJSONArray() -> SignalProducer<AnyObject, NSError> -> SignalProducer<NSArray, NSError> {
return { producer in
return producer |> flatMap(.Latest, { json in
if let json = json as? NSArray {
return SignalProducer(value: json)
} else {
return SignalProducer(error: ReactiveMoyaError.JSONMapping(json).toError())
}
})
}
}
/// Maps a JSON object to an NSDictionary
public func mapJSONDictionary() -> SignalProducer<AnyObject, NSError> -> SignalProducer<NSDictionary, NSError> {
return { producer in
return producer |> flatMap(.Latest, { json in
if let json = json as? NSDictionary {
return SignalProducer(value: json)
} else {
return SignalProducer(error: ReactiveMoyaError.JSONMapping(json).toError())
}
})
}
}
/// Maps the `MoyaResponse` to a String
public func mapString() -> SignalProducer<MoyaResponse, NSError> -> SignalProducer<String, NSError> {
return { producer in
return producer |> flatMap(.Latest, { response in
if let string = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String {
return SignalProducer(value: string)
} else {
return SignalProducer(error: ReactiveMoyaError.StringMapping(response).toError())
}
})
}
}
| mit | 6061d710b114586871140c47dd1bf425 | 43.144385 | 314 | 0.611387 | 5.532842 | false | false | false | false |
lfaoro/Cast | Carthage/Checkouts/RxSwift/RxDataSourceStarterKit/DataSources/RxCollectionViewSectionedAnimatedDataSource.swift | 1 | 1481 | //
// RxCollectionViewSectionedAnimatedDataSource.swift
// RxExample
//
// Created by Krunoslav Zaher on 7/2/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class RxCollectionViewSectionedAnimatedDataSource<S: SectionModelType> : RxCollectionViewSectionedDataSource<S>
, RxCollectionViewDataSourceType {
typealias Element = [Changeset<S>]
// For some inexplicable reason, when doing animated updates first time
// it crashes. Still need to figure out that one.
var set = false
func collectionView(collectionView: UICollectionView, observedEvent: Event<Element>) {
switch observedEvent {
case .Next(let element):
for c in element {
//print("Animating ==============================\n\(c)\n===============================\n")
if !set {
setSections(c.finalSections)
collectionView.reloadData()
set = true
return
}
setSections(c.finalSections)
collectionView.performBatchUpdates(c)
}
case .Error:
#if DEBUG
fatalError("Binding error to UI")
#endif
case .Completed:
break
}
}
} | mit | bf27a1df57a06d58d271858538a0a4ee | 30.531915 | 111 | 0.536799 | 5.652672 | false | false | false | false |
pkrawat1/TravelApp-ios | TravelApp/View/SearchTripCell.swift | 1 | 6488 | //
// SearchTripCell.swift
// TravelApp
//
// Created by Nitesh on 03/02/17.
// Copyright © 2017 Pankaj Rawat. All rights reserved.
//
import UIKit
class SearchTripCell: BaseCell {
var trip: Trip? {
didSet {
print(trip!)
userNameLabel.text = trip?.user?.name
durationLabel.text = trip?.created_at?.relativeDate()
tripNameLabel.text = trip?.name
setupThumbnailImage()
setupProfileImage()
}
}
func setupThumbnailImage() {
if let thumbnailImageUrl = trip?.thumbnail_image_url {
thumbnailImageView.loadImageUsingUrlString(urlString: thumbnailImageUrl, width: Float(thumbnailImageView.frame.width))
}
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(showTripDetail))
thumbnailImageView.isUserInteractionEnabled = true
thumbnailImageView.addGestureRecognizer(tapGestureRecognizer)
}
func showTripDetail() {
let tripDetailViewCtrl = TripDetailViewController()
store.dispatch(SelectTrip(tripId: (trip?.id!)!))
SharedData.sharedInstance.homeController?.present(tripDetailViewCtrl, animated: true, completion: nil)
}
func setupProfileImage() {
if let profileImageURL = trip?.user?.profile_pic?.url {
userProfileImageView.loadImageUsingUrlString(urlString: profileImageURL, width: Float(userProfileImageView.frame.width))
}
}
let thumbnailImageView: CustomImageView = {
let imageView = CustomImageView()
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.image = UIImage(named: "")
imageView.backgroundColor = UIColor.black
imageView.alpha = 0.5
return imageView
}()
let userProfileImageView: CustomImageView = {
let imageView = CustomImageView()
imageView.image = UIImage(named: "")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.layer.cornerRadius = 22
imageView.layer.masksToBounds = true
// imageView.backgroundColor = UIColor.blue
return imageView
}()
let likeButton: UIButton = {
let ub = UIButton(type: .system)
ub.setImage(UIImage(named: "like"), for: .normal)
ub.tintColor = UIColor.gray
ub.translatesAutoresizingMaskIntoConstraints = false
// ub.backgroundColor = UIColor.red
return ub
}()
let userNameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = ""
label.numberOfLines = 1
label.font = label.font.withSize(14)
label.textColor = UIColor.white
// label.backgroundColor = UIColor.green
return label
}()
let durationLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = ""
label.numberOfLines = 1
label.textColor = UIColor.white
// label.backgroundColor = UIColor.yellow
label.font = label.font.withSize(10)
return label
}()
let tripNameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = ""
label.font = label.font.withSize(25)
label.numberOfLines = 2
label.textColor = UIColor.white
label.textAlignment = .center
// label.backgroundColor = UIColor.green
return label
}()
override func setupViews() {
addSubview(thumbnailImageView)
addSubview(userProfileImageView)
addSubview(userNameLabel)
addSubview(durationLabel)
addSubview(likeButton)
addSubview(tripNameLabel)
thumbnailImageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
thumbnailImageView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
thumbnailImageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
userProfileImageView.bottomAnchor.constraint(equalTo: thumbnailImageView.bottomAnchor, constant: -10).isActive = true
userProfileImageView.widthAnchor.constraint(equalToConstant: 44).isActive = true
userProfileImageView.leftAnchor.constraint(equalTo: thumbnailImageView.leftAnchor, constant: 10).isActive = true
userProfileImageView.heightAnchor.constraint(equalToConstant: 44).isActive = true
userNameLabel.topAnchor.constraint(equalTo: userProfileImageView.topAnchor).isActive = true
userNameLabel.leftAnchor.constraint(equalTo: userProfileImageView.rightAnchor, constant: 10).isActive = true
userNameLabel.rightAnchor.constraint(equalTo: likeButton.leftAnchor, constant: -10).isActive = true
userNameLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
durationLabel.topAnchor.constraint(equalTo: userNameLabel.bottomAnchor, constant: 4).isActive = true
durationLabel.leftAnchor.constraint(equalTo: userProfileImageView.rightAnchor, constant: 10).isActive = true
durationLabel.rightAnchor.constraint(equalTo: likeButton.leftAnchor, constant: -10).isActive = true
durationLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
likeButton.bottomAnchor.constraint(equalTo: thumbnailImageView.bottomAnchor, constant: -10).isActive = true
likeButton.widthAnchor.constraint(equalToConstant: 44).isActive = true
likeButton.rightAnchor.constraint(equalTo: thumbnailImageView.rightAnchor, constant: -10).isActive = true
likeButton.heightAnchor.constraint(equalToConstant: 44).isActive = true
tripNameLabel.widthAnchor.constraint(equalTo: thumbnailImageView.widthAnchor, constant: -20).isActive = true
tripNameLabel.centerYAnchor.constraint(equalTo: thumbnailImageView.centerYAnchor).isActive = true
tripNameLabel.centerXAnchor.constraint(equalTo: thumbnailImageView.centerXAnchor).isActive = true
tripNameLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
}
}
| mit | 274b78d90a0bef12e0ed7a32655a9c48 | 40.056962 | 132 | 0.683675 | 5.582616 | false | false | false | false |
huonw/swift | test/expr/cast/set_coerce.swift | 32 | 339 | // RUN: %target-typecheck-verify-swift
class C : Hashable {
var x = 0
var hashValue: Int {
return x
}
}
func == (x: C, y: C) -> Bool { return true }
class D : C {}
var setC = Set<C>()
var setD = Set<D>()
// Test set upcasts
setC = setD
setD = setC // expected-error{{cannot assign value of type 'Set<C>' to type 'Set<D>'}}
| apache-2.0 | 0ce8823f1b5069ba5f6684451ed45fc6 | 15.142857 | 86 | 0.59292 | 2.756098 | false | false | false | false |
LeeCenY/iRent | Sources/iRent/Handlers/RentList.swift | 1 | 20230 |
import Foundation
import PerfectLib
import PerfectHTTP
import PerfectCRUD
import DateToolsSwift
import PerfectQiniu
/// 收租信息列表
public class RentList: BaseHandler {
/// 收租信息列表
///
/// - Parameters:
/// - request: 请求
/// - response: 响应
open static func rentlist() -> RequestHandler {
return {
request, response in
do {
var offset = 0
var limit = 20
if let page = request.param(name: "page") {
offset = Int(page)!
offset = (offset - 1) * 2
}
var listType = "all"
if let type = request.param(name: "type") {
listType = type
}
if listType == "expire" {
offset = 0
limit = 20
}
var roomArray: [[String: Any]] = []
if (listType == "all") {
let roomTable = db().table(Room.self)
let query = try roomTable
.limit(limit, skip: offset)
.join(\.payments, on: \.id, equals: \.room_id)
.where(\Room.state == false)
.select().map{ $0 }
for row in query {
var roomDict:[String: Any] = [String: Any]()
roomDict["id"] = row.id.uuidString
roomDict["state"] = row.state
roomDict["room_no"] = row.room_no
roomDict["rent_money"] = row.rent_money
roomDict["deposit"] = row.deposit
roomDict["lease_term"] = row.lease_term
roomDict["rent_date"] = row.rent_date
roomDict["network"] = row.network
roomDict["trash_fee"] = row.trash_fee
roomDict["create_at"] = row.create_at
roomDict["updated_at"] = row.updated_at
guard let payments = row.payments else {
continue
}
var paymentDict:[String: Any] = [String: Any]()
for (index, payment) in payments.enumerated() {
if (index == 0) {
paymentDict["water"] = payment.water
paymentDict["electricity"] = payment.electricity
paymentDict["last_Water"] = payment.water
paymentDict["lase_Electricity"] = payment.electricity
paymentDict["rent_date"] = payment.rent_date
}
if (index == 1) {
paymentDict["last_Water"] = payment.water
paymentDict["lase_Electricity"] = payment.electricity
}
paymentDict["id"] = payment.id.uuidString
paymentDict["room_id"] = payment.room_id.uuidString
paymentDict["state"] = payment.state
paymentDict["rent_money"] = payment.rent_money
paymentDict["network"] = payment.network
paymentDict["trash_fee"] = payment.trash_fee
paymentDict["create_at"] = payment.create_at
paymentDict["updated_at"] = payment.updated_at
}
roomDict["payments"] = paymentDict
roomArray.append(roomDict as [String: Any])
}
}else {
var timeChunk = TimeChunk.init()
timeChunk.months = 1
var startTimeChunk = TimeChunk.init()
startTimeChunk.months = 1
startTimeChunk.days = 5
var endTimeChunk = TimeChunk.init()
endTimeChunk.months = 1
endTimeChunk.days = -5
let startDate = Date().subtract(startTimeChunk).toDateString()
let endDate = Date().subtract(endTimeChunk).toDateString()
//根据上月的时间来查询快到期和未交
let paymentTable = db().table(Payment.self)
//查询快到期
let query = try paymentTable
.order(by: \.rent_date)
.where(\Payment.rent_date >= startDate && \Payment.rent_date <= endDate)
.select()
for row in query {
var paymentDict:[String: Any] = [String: Any]()
let roomTable = db().table(Room.self)
let rowQuery = try roomTable
.where(\Room.id == row.room_id)
.select().map{ $0 }
//查询房间信息
for roomRow in rowQuery {
if(roomRow.state == true) {
continue
}
paymentDict["room_no"] = roomRow.room_no
paymentDict["rent_money"] = roomRow.rent_money
paymentDict["deposit"] = roomRow.deposit
paymentDict["lease_term"] = roomRow.lease_term
paymentDict["network"] = roomRow.network
paymentDict["trash_fee"] = roomRow.trash_fee
paymentDict["water_max"] = roomRow.water_max
paymentDict["electricity_max"] = roomRow.electricity_max
paymentDict["id"] = row.id.uuidString
paymentDict["room_id"] = row.room_id.uuidString
paymentDict["state"] = false
paymentDict["water"] = row.water
paymentDict["electricity"] = row.electricity
paymentDict["rent_date"] = Date.init(dateString: row.rent_date, .Date).add(timeChunk).toDateString()
paymentDict["updated_at"] = row.updated_at
paymentDict["last_water"] = row.water
paymentDict["last_electricity"] = row.electricity
paymentDict["is_rang"] = true
guard let rent_date = row.rent_date.toDate()?.add(timeChunk).toDateString() else {
resError(request, response, error: "rent_date 错误")
return
}
//查询本月信息
let lastQuery = try paymentTable
.where(\Payment.room_id == row.room_id && \Payment.rent_date == rent_date)
.select().map{ $0 }
for last in lastQuery {
paymentDict["id"] = last.id.uuidString
paymentDict["state"] = last.state
paymentDict["water"] = last.water
paymentDict["electricity"] = last.electricity
paymentDict["rent_date"] = last.rent_date
paymentDict["updated_at"] = last.updated_at
}
roomArray.append(paymentDict)
}
}
}
try response.setBody(json: ["success": true, "status": 200, "data": roomArray] as [String: Any])
response.setHeader(.contentType, value: "application/json")
response.completed()
return
} catch {
serverErrorHandler(request, response)
Log.error(message: "rentlist : \(error)")
}
}
}
//账单状态
open static func receive() -> RequestHandler {
return {
request, response in
do {
let userReq = try request.decode(UploadFile.self)
//收租时间
guard !userReq.rentDate.isEmpty, userReq.rentDate.toDate() != nil else {
resError(request, response, error: "收租时间 rentdate 请求参数不正确")
return
}
//总数
guard userReq.money >= 0 else {
resError(request, response, error: "总数 money 请求参数不正确")
return
}
//收款人
guard !userReq.payee.isEmpty else {
resError(request, response, error: "收款人 payee 请求参数不正确")
return
}
//推送token
guard !userReq.token.isEmpty else {
resError(request, response, error: "推送 token 请求参数不正确")
return
}
let roomTable = db().table(Room.self)
let queryID = roomTable.where(\Room.id == userReq.id && \Room.state == false)
guard try queryID.count() != 0,
let room_no = try queryID.first()?.room_no else {
resError(request, response, error: "房间 id 不存在")
return
}
guard let uploads = request.postFileUploads,
!uploads.isEmpty,
let uploadsLast = uploads.last else {
resError(request, response, error: "文件数据有误")
return
}
let fileName = uploadsLast.fileName //文件名
let tmpFileName = uploadsLast.tmpFileName //上载后的临时文件名
let qiniuConfig = QiniuConfig().ProjectScope()
let upload = try Qiniu.upload(fileName: fileName, file: tmpFileName, config: qiniuConfig)
guard let uploadkey = upload["key"] as? String else {
resError(request, response, error: "上传失败")
return
}
let payment = Payment.init(room_id: UUID(), state: userReq.state, payee: userReq.payee, rent_date: userReq.rentDate, money: userReq.money, rent_money: nil, water: nil, electricity: nil, network: nil, trash_fee: nil, image_url: uploadkey, arrears: nil, remark: nil)
let paymentTable = db().table(Payment.self)
let query = try paymentTable
.where(\Payment.room_id == userReq.id && \Payment.rent_date == userReq.rentDate && \Payment.state == true)
.count()
if (query > 0) {
try response.setBody(json: ["success": true, "status": 200, "data": "已经到账"])
response.completed()
return
}
try paymentTable
.where(\Payment.room_id == userReq.id && \Payment.rent_date == userReq.rentDate)
.update(payment, setKeys: \.state, \.payee, \.money, \.image_url, \.updated_at)
let userDB = db().table(User.self)
let userToKen = try userDB
.where(\User.token != userReq.token)
.select().map { $0.token }
if userToKen.count != 0 {
Pusher().pushAPNS(
deviceTokens: userToKen,
notificationItems: [.alertTitle(userReq.payee), .alertBody("\(room_no) 已收")]) {
responses in
print("\(responses)")
}
}
try response.setBody(json: ["success": true, "status": 200, "data": ["state": true]])
response.completed()
} catch DecodingError.dataCorrupted(let context) {
resError(request, response, error: "\(context.debugDescription) 请求参数值不正确")
Log.error(message: "details : \(context.debugDescription) 请求参数值不正确")
} catch DecodingError.keyNotFound(let key, _) {
resError(request, response, error: "\(key.stringValue) 请求参数缺少")
Log.error(message: "details : \(key.stringValue) 请求参数缺少")
} catch DecodingError.typeMismatch(let type, _) {
resError(request, response, error: "\(type) 的参数值不匹配")
Log.error(message: "details : \(type) 的参数值不匹配")
} catch DecodingError.valueNotFound(let type, _) {
resError(request, response, error: "\(type) 不存在的值")
Log.error(message: "details : \(type) 不存在的值")
} catch {
resError(request, response, error: "不知错误原因")
Log.error(message: "details : 不知错误原因")
}
}
}
// 获取详情信息
open static func details() -> RequestHandler {
return {
request, response in
do {
guard let room_id = UUID.init(uuidString: request.param(name: "room_id")!) else {
resError(request, response, error: "room_id 参数不正确")
return
}
//收租时间
guard let rentdate = request.param(name: "rent_date") else {
resError(request, response, error: "收租时间 rentdate 请求参数不正确")
return
}
var lastTimeChunk = TimeChunk.init()
lastTimeChunk.months = 1
//收租时间
guard let lastDate = rentdate.toDate()?.subtract(lastTimeChunk).toDateString() else {
resError(request, response, error: "上月时间 lastDate 转换出错")
return
}
//查询本月
let paymentTable = db().table(Payment.self)
let query = try paymentTable
.where(\Payment.room_id == room_id && \Payment.rent_date == lastDate)
.select()
var paymentDict:[String: Any] = [String: Any]()
for row in query {
paymentDict["id"] = row.id.uuidString
paymentDict["room_id"] = row.room_id.uuidString
paymentDict["state"] = false
paymentDict["water"] = row.water
paymentDict["electricity"] = row.electricity
paymentDict["rent_date"] = Date.init(dateString: row.rent_date, .Date).add(lastTimeChunk).toDateString()
paymentDict["network"] = row.network
paymentDict["last_water"] = row.water
paymentDict["last_electricity"] = row.electricity
let roomTable = db().table(Room.self)
let roomQuery = try roomTable
.where(\Room.id == row.room_id)
.select()
//查询房间信息
for room in roomQuery {
paymentDict["room_no"] = room.room_no
paymentDict["rent_money"] = room.rent_money
paymentDict["deposit"] = room.deposit
paymentDict["lease_term"] = room.lease_term
paymentDict["network"] = room.network
paymentDict["trash_fee"] = room.trash_fee
paymentDict["water_max"] = room.water_max
paymentDict["electricity_max"] = room.electricity_max
}
//查询上月
let lastQuery = try paymentTable
.where(\Payment.room_id == room_id && \Payment.rent_date == rentdate)
.select()
for last in lastQuery {
paymentDict["water"] = last.water
paymentDict["electricity"] = last.electricity
paymentDict["state"] = last.state
paymentDict["rent_date"] = last.rent_date
}
}
try response.setBody(json: ["success": true, "status": 200, "data": paymentDict])
response.completed()
} catch {
serverErrorHandler(request, response)
Log.error(message: "details : \(error)")
}
}
}
// 退房
open static func checkOut() -> RequestHandler {
return {
request, response in
do {
//id
guard let room_id = UUID.init(uuidString: request.param(name: "room_id")!) else {
resError(request, response, error: "room_id 参数不正确")
return
}
//TODO 还需要根据多种情况操作退房
let room = Room.init(state: true, room_no: "", rent_money: 0, deposit: 0, lease_term: 0, rent_date: "", network: 0, trash_fee: 0)
let tenant = Tenant.init(room_id: UUID(), state: true, name: "", idcard: "", phone: "")
let tenantTable = db().table(Tenant.self)
let roomTable = db().table(Room.self)
if try roomTable.where(\Room.id == room_id).count() == 0 {
resError(request, response, error: "room_id 不存在")
}
do {
try roomTable.where(\Room.id == room_id).update(room, setKeys: \.state, \.updated_at)
try tenantTable.where(\Tenant.room_id == room_id).update(tenant, setKeys: \.state, \.updated_at)
} catch {
resError(request, response, error: "退房失败")
}
try response.setBody(json: ["success": true, "status": 200, "data": "退房成功"])
response.completed()
} catch {
serverErrorHandler(request, response)
Log.error(message: "details : \(error)")
}
}
}
}
enum ListType {
case All
case Range
}
func isDateCompareRange(date: Date, leasedTime: Int, rangeDay: Int)-> Bool{
let dateFrom = calculateDate(day: -rangeDay)
let dateTo = calculateDate(day: rangeDay)
let currentDate = calculateDate(date: date, month: leasedTime)
return (currentDate?.compare(dateFrom!) == .orderedDescending && currentDate?.compare(dateTo!) == .orderedAscending);
}
| mit | b16cbb969a3b5d78a89443fc6db53c80 | 44.72093 | 280 | 0.433266 | 5.255279 | false | false | false | false |
jpush/jchat-swift | JChat/Src/ChatModule/Input/InputView/Emoticon/JCEmoticonInputView.swift | 1 | 16403 | //
// JCEmoticonInputView.swift
// JChat
//
// Created by JIGUANG on 2017/3/9.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
@objc public protocol JCEmoticonInputViewDataSource: NSObjectProtocol {
func numberOfEmotionGroups(in emoticon: JCEmoticonInputView) -> Int
func emoticon(_ emoticon: JCEmoticonInputView, emotionGroupForItemAt index: Int) -> JCEmoticonGroup
@objc optional func emoticon(_ emoticon: JCEmoticonInputView, numberOfRowsForGroupAt index: Int) -> Int
@objc optional func emoticon(_ emoticon: JCEmoticonInputView, numberOfColumnsForGroupAt index: Int) -> Int
@objc optional func emoticon(_ emoticon: JCEmoticonInputView, moreViewForGroupAt index: Int) -> UIView?
}
@objc public protocol JCEmoticonInputViewDelegate: NSObjectProtocol {
@objc optional func inputViewContentSize(_ inputView: UIView) -> CGSize
@objc optional func emoticon(_ emoticon: JCEmoticonInputView, insetForGroupAt index: Int) -> UIEdgeInsets
@objc optional func emoticon(_ emoticon: JCEmoticonInputView, shouldSelectFor item: JCEmoticon) -> Bool
@objc optional func emoticon(_ emoticon: JCEmoticonInputView, didSelectFor item: JCEmoticon)
@objc optional func emoticon(_ emoticon: JCEmoticonInputView, shouldPreviewFor item: JCEmoticon?) -> Bool
@objc optional func emoticon(_ emoticon: JCEmoticonInputView, didPreviewFor item: JCEmoticon?)
}
open class JCEmoticonInputView: UIView {
private var _cacheBounds: CGRect?
fileprivate var _color: UIColor?
fileprivate var _currentGroup: Int?
fileprivate var _contentViewIsInit: Bool = false
fileprivate var _currentMoreView: UIView?
fileprivate var _currentMoreViewConstraints: [NSLayoutConstraint]?
fileprivate lazy var _tabbarLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
fileprivate lazy var _tabbar: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: self._tabbarLayout)
fileprivate lazy var _previewer: JCEmoticonPreviewer = JCEmoticonPreviewer()
fileprivate lazy var _pageControl: UIPageControl = UIPageControl()
fileprivate lazy var _contentViewLayout: JCEmoticonInputViewLayout = JCEmoticonInputViewLayout()
fileprivate lazy var _contentView: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: self._contentViewLayout)
public override init(frame: CGRect) {
super.init(frame: frame)
_init()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_init()
}
open override func layoutSubviews() {
super.layoutSubviews()
if _cacheBounds?.width != bounds.width {
_cacheBounds = bounds
if let idx = _contentView.indexPathsForVisibleItems.first {
_contentView.reloadData()
_restoreContentOffset(at: idx)
}
}
}
open override var intrinsicContentSize: CGSize {
return delegate?.inputViewContentSize?(self) ?? CGSize(width: frame.width, height: 253)
}
open weak var dataSource: JCEmoticonInputViewDataSource?
open weak var delegate: JCEmoticonInputViewDelegate?
// MARK: Private Method
private func _restoreContentOffset(at indexPath: IndexPath) {
let section = indexPath.section
let count = _contentView.numberOfItems(inSection: section)
let item = min(indexPath.item, count - 1)
let nidx = IndexPath(item: item, section: section)
let mcount = (0 ..< section).reduce(0) {
return $0 + _contentView.numberOfItems(inSection: $1)
}
let x = CGFloat(mcount + item) * _contentView.frame.width
_contentView.contentOffset = CGPoint(x: x, y: 0)
_updatePageNumber(at: nidx)
}
private func _init() {
//_color = UIColor(colorLiteralRed: 0xec / 0xff, green: 0xed / 0xff, blue: 0xf1 / 0xff, alpha: 1)
_color = UIColor(red: 0xec / 0xff, green: 0xed / 0xff, blue: 0xf1 / 0xff, alpha: 1)
_pageControl.numberOfPages = 8
_pageControl.hidesForSinglePage = true
_pageControl.pageIndicatorTintColor = UIColor.gray
_pageControl.currentPageIndicatorTintColor = UIColor.darkGray
_pageControl.translatesAutoresizingMaskIntoConstraints = false
_pageControl.backgroundColor = .clear
_pageControl.isUserInteractionEnabled = false
_contentView.delegate = self
_contentView.dataSource = self
_contentView.scrollsToTop = false
_contentView.isPagingEnabled = true
_contentView.delaysContentTouches = true
_contentView.showsVerticalScrollIndicator = false
_contentView.showsHorizontalScrollIndicator = false
_contentView.register(JCEmoticonPageView.self, forCellWithReuseIdentifier: "Page")
_contentView.translatesAutoresizingMaskIntoConstraints = false
_contentView.backgroundColor = .clear
_previewer.isHidden = true
_previewer.isUserInteractionEnabled = false
_tabbarLayout.scrollDirection = .horizontal
_tabbarLayout.minimumLineSpacing = 0
_tabbarLayout.minimumInteritemSpacing = 0
_tabbar.register(JCEmoticonTabItemView.self, forCellWithReuseIdentifier: "Page")
_tabbar.translatesAutoresizingMaskIntoConstraints = false
_tabbar.dataSource = self
_tabbar.backgroundColor = .white
_tabbar.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
_tabbar.delegate = self
_tabbar.scrollsToTop = false
_tabbar.showsVerticalScrollIndicator = false
_tabbar.showsHorizontalScrollIndicator = false
backgroundColor = _color
// add views
addSubview(_contentView)
addSubview(_tabbar)
addSubview(_pageControl)
addSubview(_previewer)
// add constraints
addConstraint(_JCEmoticonLayoutConstraintMake(_contentView, .top, .equal, self, .top))
addConstraint(_JCEmoticonLayoutConstraintMake(_contentView, .left, .equal, self, .left))
addConstraint(_JCEmoticonLayoutConstraintMake(_contentView, .right, .equal, self, .right))
addConstraint(_JCEmoticonLayoutConstraintMake(_pageControl, .left, .equal, self, .left))
addConstraint(_JCEmoticonLayoutConstraintMake(_pageControl, .right, .equal, self, .right))
addConstraint(_JCEmoticonLayoutConstraintMake(_pageControl, .bottom, .equal, _contentView, .bottom, -4))
addConstraint(_JCEmoticonLayoutConstraintMake(_tabbar, .top, .equal, _contentView, .bottom))
addConstraint(_JCEmoticonLayoutConstraintMake(_tabbar, .left, .equal, self, .left))
addConstraint(_JCEmoticonLayoutConstraintMake(_tabbar, .right, .equal, self, .right))
addConstraint(_JCEmoticonLayoutConstraintMake(_tabbar, .bottom, .equal, self, .bottom))
addConstraint(_JCEmoticonLayoutConstraintMake(_tabbar, .height, .equal, nil, .notAnAttribute, 37))
addConstraint(_JCEmoticonLayoutConstraintMake(_pageControl, .height, .equal, nil, .notAnAttribute, 20))
}
}
// MARK: - JCEmoticonDelegate(Forwarding)
extension JCEmoticonInputView: JCEmoticonDelegate {
open func emoticon(shouldSelectFor emoticon: JCEmoticon) -> Bool {
return delegate?.emoticon?(self, shouldSelectFor: emoticon) ?? true
}
open func emoticon(shouldPreviewFor emoticon: JCEmoticon?) -> Bool {
return delegate?.emoticon?(self, shouldPreviewFor: emoticon) ?? false
}
open func emoticon(didSelectFor emoticon: JCEmoticon) {
delegate?.emoticon?(self, didSelectFor: emoticon)
}
open func emoticon(didPreviewFor emoticon: JCEmoticon?) {
delegate?.emoticon?(self, didPreviewFor: emoticon)
}
}
// MARK: - UICollectionViewDataSource & UICollectionViewDelegateFlowLayout & JCEmoticonInputViewDelegateLayout
extension JCEmoticonInputView: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, JCEmoticonInputViewDelegateLayout {
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if scrollView === _tabbar {
return
}
if scrollView === _contentView {
guard let idx = _contentView.indexPathForItem(at: targetContentOffset.move()) else {
return
}
_updateMoreView(at: idx)
_updatePageNumber(at: idx)
}
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
if collectionView === _tabbar {
return 1
}
if collectionView === _contentView {
return dataSource?.numberOfEmotionGroups(in: self) ?? 0
}
return 0
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView === _tabbar {
return dataSource?.numberOfEmotionGroups(in: self) ?? 0
}
if collectionView === _contentView {
let pageCount = _contentViewLayout.numberOfPages(in: section)
if !_contentViewIsInit {
_contentViewIsInit = true
let idx = IndexPath(item: 0, section: 0)
_updateMoreView(at: idx)
_updatePageNumber(at: idx)
}
return pageCount
}
return 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(withReuseIdentifier: "Page", for: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let cell = cell as? JCEmoticonPageView {
cell.page = _contentViewLayout.page(at: indexPath)
cell.delegate = self
cell.previewer = _previewer
return
}
if let cell = cell as? JCEmoticonTabItemView {
cell.group = dataSource?.emoticon(self, emotionGroupForItemAt: indexPath.item)
cell.selectedBackgroundView?.backgroundColor = _color
return
}
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView === _tabbar {
let nidx = IndexPath(item: 0, section: indexPath.item)
guard _contentView.indexPathsForVisibleItems.first?.section != nidx.section else {
return // no change
}
_contentView.scrollToItem(at: nidx, at: .left, animated: false)
_updateMoreView(at: nidx)
_updatePageNumber(at: nidx)
}
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if collectionView === _tabbar {
return CGSize(width: 45, height: collectionView.frame.height)
}
if collectionView === _contentView {
return collectionView.frame.size
}
return .zero
}
internal func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: JCEmoticonInputViewLayout, groupAt index: Int) -> JCEmoticonGroup? {
return dataSource?.emoticon(self, emotionGroupForItemAt: index)
}
internal func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: JCEmoticonInputViewLayout, numberOfRowsForGroupAt index: Int) -> Int {
return dataSource?.emoticon?(self, numberOfRowsForGroupAt: index) ?? 3
}
internal func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: JCEmoticonInputViewLayout, numberOfColumnsForGroupAt index: Int) -> Int {
return dataSource?.emoticon?(self, numberOfColumnsForGroupAt: index) ?? 7
}
internal func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: JCEmoticonInputViewLayout, insetForGroupAt index: Int) -> UIEdgeInsets {
return delegate?.emoticon?(self, insetForGroupAt: index) ?? UIEdgeInsets.init(top: 12, left: 10, bottom: 12 + 30, right: 10)
}
fileprivate func _updateMoreView(at indexPath: IndexPath) {
guard _currentGroup != indexPath.section else {
return
}
let moreView = dataSource?.emoticon?(self, moreViewForGroupAt: indexPath.section)
if _currentMoreView != moreView {
var newValue: UIView?
var newValueCs: [NSLayoutConstraint]?
let oldValue = _currentMoreView
let oldValueCs = _currentMoreViewConstraints
if let view = moreView {
view.translatesAutoresizingMaskIntoConstraints = false
insertSubview(view, belowSubview: _previewer)
let constraints = [
_JCEmoticonLayoutConstraintMake(view, .top, .equal, _tabbar, .top),
_JCEmoticonLayoutConstraintMake(view, .right, .equal, _tabbar, .right),
_JCEmoticonLayoutConstraintMake(view, .bottom, .equal, _tabbar, .bottom),
]
addConstraints(constraints)
newValue = view
newValueCs = constraints
}
newValue?.layoutIfNeeded()
newValue?.transform = CGAffineTransform(translationX: newValue?.frame.width ?? 0, y: 0)
UIView.animate(withDuration: 0.25, animations: {
self._tabbar.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: newValue?.frame.width ?? 0)
newValue?.transform = CGAffineTransform(translationX: 0, y: 0)
oldValue?.transform = CGAffineTransform(translationX: oldValue?.frame.width ?? 0, y: 0)
}, completion: { f in
if let view = oldValue, let cs = oldValueCs {
guard view !== self._currentMoreView else {
self.removeConstraints(cs)
return
}
self.removeConstraints(cs)
view.removeFromSuperview()
}
})
_currentMoreView = newValue
_currentMoreViewConstraints = newValueCs
}
_currentGroup = indexPath.section
}
fileprivate func _updatePageNumber(at indexPath: IndexPath) {
_pageControl.numberOfPages = _contentView.numberOfItems(inSection: indexPath.section)
_pageControl.currentPage = indexPath.item
let nidx = IndexPath(item: indexPath.section, section: 0)
guard _tabbar.indexPathsForSelectedItems?.first?.item != nidx.item else {
return
}
_tabbar.selectItem(at: nidx, animated: true, scrollPosition: .centeredHorizontally)
}
}
internal func _SAEmoticonLoadImage(base64Encoded base64String: String, scale: CGFloat) -> UIImage? {
guard let data = Data(base64Encoded: base64String, options: .ignoreUnknownCharacters) else {
return nil
}
return UIImage(data: data, scale: scale)
}
@inline(__always)
internal func _JCEmoticonLayoutConstraintMake(_ item: AnyObject, _ attr1: NSLayoutConstraint.Attribute, _ related: NSLayoutConstraint.Relation, _ toItem: AnyObject? = nil, _ attr2: NSLayoutConstraint.Attribute = .notAnAttribute, _ constant: CGFloat = 0, priority: UILayoutPriority = UILayoutPriority(1000), multiplier: CGFloat = 1, output: UnsafeMutablePointer<NSLayoutConstraint?>? = nil) -> NSLayoutConstraint {
let c = NSLayoutConstraint(item:item, attribute:attr1, relatedBy:related, toItem:toItem, attribute:attr2, multiplier:multiplier, constant:constant)
c.priority = priority
if output != nil {
output?.pointee = c
}
return c
}
| mit | 320d36d7eed2bf57f42ed1358bc0f509 | 43.444444 | 413 | 0.65622 | 5.297158 | false | false | false | false |
valnoc/Mirage | Source/Mirage/Stub.swift | 1 | 2850 | //
// MIT License
//
// Copyright (c) 2019 Valeriy Bezuglyy
//
// 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
/// An object to alternate function behavour.
public class Stub<TArgs, TReturn> {
public typealias Me = Stub<TArgs, TReturn>
public typealias Action = (_ args: TArgs) -> TReturn
fileprivate var actions: [Action] = []
fileprivate var nextIndex: Int = 0
fileprivate let callRealFunc: Action?
init(callRealFunc: Action? = nil) {
self.callRealFunc = callRealFunc
}
//MARK: result
/// Return given result on next call.
///
/// - Parameter result: New result.
/// - Returns: Stub for chained call.
@discardableResult
public func thenReturn(_ result: TReturn) -> Me {
actions.append({ (_ args) -> TReturn in
return result
})
return self
}
/// Execute closure instead of called function.
///
/// - Parameter closure: A closure to execute.
/// - Returns: Stub for chained call.
@discardableResult
public func thenDo(_ closure: @escaping Action) -> Me {
actions.append({ (_ args) -> TReturn in
return closure(args)
})
return self
}
/// Call real func implementation.
///
/// - Returns: Stub for chained call.
@discardableResult
public func thenCallRealFunc() -> Me {
if let callRealFunc = callRealFunc {
actions.append(callRealFunc)
}
return self
}
//MARK: execute
func execute(_ args: TArgs) -> TReturn {
var index = actions.count - 1
if nextIndex < index {
index = nextIndex
nextIndex += 1
}
return actions[index](args)
}
}
| mit | 7edd2602af56f6b392cc858a588d50e2 | 31.386364 | 84 | 0.639649 | 4.460094 | false | false | false | false |
SmallElephant/FEAlgorithm-Swift | 11-GoldenInterview/11-GoldenInterview/Other/Factor.swift | 1 | 2910 | //
// Factor.swift
// 11-GoldenInterview
//
// Created by keso on 2017/5/29.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import Foundation
class Factor {
func getKthFactorNumber(k:Int) -> Int {
if k < 0 {
return 0
}
var val:Int = 1
var arr:[Int] = []
addProducts(arr: &arr, num: 1)
for _ in 0..<k {
val = removeMin(arr: &arr)
addProducts(arr: &arr, num: val)
}
return val
}
func removeMin(arr:inout [Int]) -> Int {
if arr.count == 0 {
return 1
}
var min:Int = arr.first!
for num in arr {
if min > num {
min = num
}
}
while arr.contains(min) {
for i in 0..<arr.count {
if arr[i] == min {
arr.remove(at: i)
break
}
}
}
return min
}
func addProducts(arr:inout [Int],num:Int) {
arr.append(3 * num)
arr.append(5 * num)
arr.append(7 * num)
}
func getKthFactorNumber2(k:Int) -> Int {
if k < 0 {
return 0
}
var val:Int = 0
var arr3:[Int] = [1]
var arr5:[Int] = []
var arr7:[Int] = []
for _ in 0...k {
let num3:Int = arr3.count > 0 ? arr3.first! : Int.max
let num5:Int = arr5.count > 0 ? arr5.first! : Int.max
let num7:Int = arr7.count > 0 ? arr7.first! : Int.max
val = min(num3, min(num5, num7))
if num3 == val {
arr3.removeFirst()
arr3.append(val * 3)
arr5.append(val * 5)
} else if num5 == val {
arr5.removeFirst()
arr5.append(val * 5)
} else if num7 == val {
arr7.removeFirst()
}
arr7.append(val * 7)
}
return val
}
func getKthFactorNumber3(k:Int) -> Int {
if k < 0 {
return 0
}
var index3:Int = 0
var index5:Int = 0
var index7:Int = 0
var arr:[Int] = [1]
var val:Int = 0
for _ in 0...k {
val = min(arr[index3] * 3, min(arr[index5] * 5, arr[index7] * 7))
if arr[index3] * 3 == val {
index3 += 1
}
if arr[index5] * 5 == val {
index5 += 1
}
if arr[index7] * 7 == val {
index7 += 1
}
arr.append(val)
}
return arr[arr.count - 2]
}
}
| mit | 76548faf117013ceec7f674b0be1ff8e | 21.534884 | 77 | 0.373237 | 3.965894 | false | false | false | false |
DonMag/ScratchPad | Swift3/scratchy/XC8.playground/Pages/strings2.xcplaygroundpage/Contents.swift | 1 | 626 | //: [Previous](@previous)
import Foundation
//: [Next](@next)
func ssplit(aString: String, byCount: Int = 2, includeRemainder: Bool = false) -> [String] {
var rtn = [String]()
var j = aString.startIndex
while (j.distanceTo(aString.endIndex) >= byCount) {
let i = j
j = j.advancedBy(byCount)
rtn.append(aString.substringWithRange(i..<j))
}
if includeRemainder && j < aString.endIndex {
rtn.append(aString.substringFromIndex(j))
}
return rtn
}
var str = "aabbccddeeffg"
var a1 = ssplit(str, byCount: 2, includeRemainder: false)
var a2 = ssplit(str, byCount: 2, includeRemainder: true)
| mit | f6186ee1bbf985d36811af9598e68774 | 17.411765 | 92 | 0.667732 | 3.038835 | false | false | false | false |
austinzheng/swift | test/SILOptimizer/definite_init_cross_module.swift | 8 | 7983 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path=%t/OtherModule.swiftmodule %S/Inputs/definite_init_cross_module/OtherModule.swift
// RUN: %target-swift-frontend -emit-sil -verify -I %t -swift-version 5 %s > /dev/null -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/definite_init_cross_module/BridgingHeader.h
import OtherModule
extension Point {
init(xx: Double, yy: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: Point) {
// This is OK
self = other
}
init(other: Point, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: Point, xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self = other
}
init(other: Point, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: Point, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = 0 // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension GenericPoint {
init(xx: T, yy: T) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: T, yyy: T) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: GenericPoint<T>) {
// This is OK
self = other
}
init(other: GenericPoint<T>, x: T) {
// This is OK
self = other
self.x = x
}
init(other: GenericPoint<T>, xx: T) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self = other
}
init(other: GenericPoint<T>, x: T, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: GenericPoint<T>, xx: T, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension GenericPoint where T == Double {
init(xx: Double, yy: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: GenericPoint<Double>) {
// This is OK
self = other
}
init(other: GenericPoint<Double>, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: GenericPoint<Double>, xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self = other
}
init(other: GenericPoint<Double>, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: GenericPoint<Double>, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = 0 // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
typealias MyGenericPoint<Q> = GenericPoint<Q>
extension MyGenericPoint {
init(myX: T, myY: T) {
self.x = myX // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = myY // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension CPoint {
init(xx: Double, yy: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}} expected-note {{use "self.init()" to initialize the struct with zero values}} {{5-5=self.init()\n}}
self.y = yy // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: CPoint) {
// This is OK
self = other
}
init(other: CPoint, x: Double) {
// This is OK
self = other
self.x = x
}
init(other: CPoint, xx: Double) {
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}} expected-note {{use "self.init()" to initialize the struct with zero values}} {{5-5=self.init()\n}}
self = other
}
init(other: CPoint, x: Double, cond: Bool) {
// This is OK
self = other
if cond { self.x = x }
}
init(other: CPoint, xx: Double, cond: Bool) {
if cond { self = other }
self.x = xx // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
self.y = 0 // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension NonnullWrapper {
init(p: UnsafeMutableRawPointer) {
self.ptr = p // expected-error {{'self' used before 'self.init' call or assignment to 'self'}}
// No suggestion for "self.init()" because this struct does not support a
// zeroing initializer.
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension PrivatePoint {
init(xxx: Double, yyy: Double) {
// This is OK
self.init(x: xxx, y: yyy)
}
init(other: PrivatePoint) {
// This is OK
self = other
}
init(other: PrivatePoint, cond: Bool) {
if cond { self = other }
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init() {
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension Empty {
init(x: Double) {
// This is OK
self.init()
}
init(other: Empty) {
// This is okay
self = other
}
init(other: Empty, cond: Bool) {
if cond { self = other }
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xx: Double) {
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
extension GenericEmpty {
init(x: Double) {
// This is OK
self.init()
}
init(other: GenericEmpty<T>) {
// This is okay
self = other
}
init(other: GenericEmpty<T>, cond: Bool) {
if cond { self = other }
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
init(xx: Double) {
} // expected-error {{'self.init' isn't called on all paths before returning from initializer}}
}
| apache-2.0 | dedf0d5958a6e1599b043e534514a626 | 31.583673 | 227 | 0.63748 | 3.486026 | false | false | false | false |
kzaher/RxSwift | RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift | 2 | 7126 | //
// TableViewWithEditingCommandsViewController.swift
// RxExample
//
// Created by carlos on 26/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
/**
Another way to do "MVVM". There are different ideas what does MVVM mean depending on your background.
It's kind of similar like FRP.
In the end, it doesn't really matter what jargon are you using.
This would be the ideal case, but it's really hard to model complex views this way
because it's not possible to observe partial model changes.
*/
struct TableViewEditingCommandsViewModel {
let favoriteUsers: [User]
let users: [User]
static func executeCommand(state: TableViewEditingCommandsViewModel, _ command: TableViewEditingCommand) -> TableViewEditingCommandsViewModel {
switch command {
case let .setUsers(users):
return TableViewEditingCommandsViewModel(favoriteUsers: state.favoriteUsers, users: users)
case let .setFavoriteUsers(favoriteUsers):
return TableViewEditingCommandsViewModel(favoriteUsers: favoriteUsers, users: state.users)
case let .deleteUser(indexPath):
var all = [state.favoriteUsers, state.users]
all[indexPath.section].remove(at: indexPath.row)
return TableViewEditingCommandsViewModel(favoriteUsers: all[0], users: all[1])
case let .moveUser(from, to):
var all = [state.favoriteUsers, state.users]
let user = all[from.section][from.row]
all[from.section].remove(at: from.row)
all[to.section].insert(user, at: to.row)
return TableViewEditingCommandsViewModel(favoriteUsers: all[0], users: all[1])
}
}
}
enum TableViewEditingCommand {
case setUsers(users: [User])
case setFavoriteUsers(favoriteUsers: [User])
case deleteUser(indexPath: IndexPath)
case moveUser(from: IndexPath, to: IndexPath)
}
class TableViewWithEditingCommandsViewController: ViewController, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let dataSource = TableViewWithEditingCommandsViewController.configureDataSource()
override func viewDidLoad() {
super.viewDidLoad()
typealias Feedback = (ObservableSchedulerContext<TableViewEditingCommandsViewModel>) -> Observable<TableViewEditingCommand>
self.navigationItem.rightBarButtonItem = self.editButtonItem
let superMan = User(
firstName: "Super",
lastName: "Man",
imageURL: "http://nerdreactor.com/wp-content/uploads/2015/02/Superman1.jpg"
)
let watMan = User(firstName: "Wat",
lastName: "Man",
imageURL: "http://www.iri.upc.edu/files/project/98/main.GIF"
)
let loadFavoriteUsers = RandomUserAPI.sharedAPI
.getExampleUserResultSet()
.map(TableViewEditingCommand.setUsers)
.catchAndReturn(TableViewEditingCommand.setUsers(users: []))
let initialLoadCommand = Observable.just(TableViewEditingCommand.setFavoriteUsers(favoriteUsers: [superMan, watMan]))
.concat(loadFavoriteUsers)
.observe(on:MainScheduler.instance)
let uiFeedback: Feedback = bind(self) { this, state in
let subscriptions = [
state.map {
[
SectionModel(model: "Favorite Users", items: $0.favoriteUsers),
SectionModel(model: "Normal Users", items: $0.users)
]
}
.bind(to: this.tableView.rx.items(dataSource: this.dataSource)),
this.tableView.rx.itemSelected
.withLatestFrom(state) { i, latestState in
let all = [latestState.favoriteUsers, latestState.users]
return all[i.section][i.row]
}
.subscribe(onNext: { [weak this] user in
this?.showDetailsForUser(user)
}),
]
let events: [Observable<TableViewEditingCommand>] = [
this.tableView.rx.itemDeleted.map(TableViewEditingCommand.deleteUser),
this.tableView .rx.itemMoved.map({ val in return TableViewEditingCommand.moveUser(from: val.0, to: val.1) })
]
return Bindings(subscriptions: subscriptions, events: events)
}
let initialLoadFeedback: Feedback = { _ in initialLoadCommand }
Observable.system(
initialState: TableViewEditingCommandsViewModel(favoriteUsers: [], users: []),
reduce: TableViewEditingCommandsViewModel.executeCommand,
scheduler: MainScheduler.instance,
scheduledFeedback: uiFeedback, initialLoadFeedback
)
.subscribe()
.disposed(by: disposeBag)
// customization using delegate
// RxTableViewDelegateBridge will forward correct messages
tableView.rx.setDelegate(self)
.disposed(by: disposeBag)
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.isEditing = editing
}
// MARK: Table view delegate ;)
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let title = dataSource[section]
let label = UILabel(frame: CGRect.zero)
// hacky I know :)
label.text = " \(title)"
label.textColor = UIColor.white
label.backgroundColor = UIColor.darkGray
label.alpha = 0.9
return label
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
40
}
// MARK: Navigation
private func showDetailsForUser(_ user: User) {
let storyboard = UIStoryboard(name: "TableViewWithEditingCommands", bundle: Bundle(identifier: "RxExample-iOS"))
let viewController = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
viewController.user = user
self.navigationController?.pushViewController(viewController, animated: true)
}
// MARK: Work over Variable
static func configureDataSource() -> RxTableViewSectionedReloadDataSource<SectionModel<String, User>> {
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, User>>(
configureCell: { (_, tv, ip, user: User) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = user.firstName + " " + user.lastName
return cell
},
titleForHeaderInSection: { dataSource, sectionIndex in
return dataSource[sectionIndex].model
},
canEditRowAtIndexPath: { (ds, ip) in
return true
},
canMoveRowAtIndexPath: { _, _ in
return true
}
)
return dataSource
}
}
| mit | 6396b3a8a5ba5bc86281f94bb7cee3c2 | 36.898936 | 147 | 0.635789 | 5 | false | false | false | false |
nathankot/Alamofire | Source/ParameterEncoding.swift | 6 | 9038 | // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
// MARK: - ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) {
var mutableURLRequest: NSMutableURLRequest = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
if parameters == nil {
return (mutableURLRequest, nil)
}
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += queryComponents(key, value)
}
return join("&", components.map { "\($0)=\($1)" } as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
(mutableURLRequest, error) = closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/**
Returns a percent escaped string following RFC 3986 for query string formatting.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
Core Foundation interprets RFC 3986 in terms of legal and illegal characters.
- Legal Numbers: "0123456789"
- Legal Letters: "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- Legal Characters: "!", "$", "&", "'", "(", ")", "*", "+", ",", "-",
".", "/", ":", ";", "=", "?", "@", "_", "~", "\""
- Illegal Characters: All characters not listed as Legal
While the Core Foundation `CFURLCreateStringByAddingPercentEscapes` documentation states
that it follows RFC 3986, the headers actually point out that it follows RFC 2396. This
explains why it does not consider "[", "]" and "#" to be "legal" characters even though
they are specified as "reserved" characters in RFC 3986. The following rdar has been filed
to hopefully get the documentation updated.
- https://openradar.appspot.com/radar?id=5058257274011648
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent escaped in the query string.
:param: string The string to be percent escaped.
:returns: The percent escaped string.
*/
func escape(string: String) -> String {
let generalDelimiters = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimiters = "!$&'()*+,;="
let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
}
| mit | 90b4dbfa6f0e192531dacedf2eab2ec9 | 45.57732 | 555 | 0.643316 | 5.184165 | false | false | false | false |
MitchellPhillips22/TIY-Assignments | Day 2/Tip Calc Assignment.playground/Contents.swift | 1 | 1484 | /* ###Tip Calculator
Create a new playgound file called "TipCalculator".
1. Create a function to calculate the tip amount. It should accept two values - totalAmount and percentage and return the total amount of the tip as well as the final total for the customer. Hint: *use tuples*
2. Create a Class called TipCalculator with one property called dollarAmount.
- It should have an *initializer* that accepts the dollarAmount
- It should have a function that calculates a tip it should accept a tipPercentage that is of type Double and returns the tipAmount of type Double.
- It should have a method called printPossibleTips() that calculates and prints the tip amount for three values 15%, 18% and 20%.
HARD MODE:
Write an App that uses a textField for the dollarAmount and tipPercentage and a button that calculates the final dollar amount to be paid.
*/
import UIKit
class TipCalculator {
var dollarAmount: Double
init(dollarAmount: Double) {
self.dollarAmount = dollarAmount
}
func calculate(percent: Double) -> Double {
return self.dollarAmount * percent
}
func printPossibleTips() {
let tip15 = calculate(0.15)
let tip18 = calculate(0.18)
let tip20 = calculate(0.20)
print("For 15% of \(self.dollarAmount), \(tip15), for 18%, \(tip18), for 20%, \(tip20).")
}
}
let myTip = TipCalculator(dollarAmount: 54.00)
myTip.printPossibleTips()
| cc0-1.0 | df766d1b5d9b666ce6f7051572c5fde8 | 27 | 209 | 0.694744 | 4.351906 | false | false | false | false |
brentdax/swift | test/IRGen/generic_casts.swift | 2 | 6021 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -enable-objc-interop -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
import gizmo
// -- Protocol records for cast-to ObjC protocols
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ = private constant
// CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section "__DATA,__objc_protolist,coalesced,no_dead_strip"
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section "__DATA,__objc_protorefs,coalesced,no_dead_strip"
// CHECK: @_PROTOCOL_NSRuncing = private constant
// CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section "__DATA,__objc_protolist,coalesced,no_dead_strip"
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section "__DATA,__objc_protorefs,coalesced,no_dead_strip"
// CHECK: @_PROTOCOLS__TtC13generic_casts10ObjCClass2 = private constant { i64, [1 x i8*] } {
// CHECK: i64 1,
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto2_
// CHECK: }
// CHECK: @_DATA__TtC13generic_casts10ObjCClass2 = private constant {{.*}} @_PROTOCOLS__TtC13generic_casts10ObjCClass2
// CHECK: @_PROTOCOL_PROTOCOLS__TtP13generic_casts10ObjCProto2_ = private constant { i64, [1 x i8*] } {
// CHECK: i64 1,
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_
// CHECK: }
// CHECK: define hidden swiftcc i64 @"$s13generic_casts8allToIntySixlF"(%swift.opaque* noalias nocapture, %swift.type* %T)
func allToInt<T>(_ x: T) -> Int {
return x as! Int
// CHECK: [[INT_TEMP:%.*]] = alloca %TSi,
// CHECK: [[TYPE_ADDR:%.*]] = bitcast %swift.type* %T to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[TYPE_ADDR]], i64 -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[SIZE_WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 8
// CHECK: [[SIZE_WITNESS:%.*]] = load i8*, i8** [[SIZE_WITNESS_ADDR]]
// CHECK: [[SIZE:%.*]] = ptrtoint i8* [[SIZE_WITNESS]]
// CHECK: [[T_ALLOCA:%.*]] = alloca i8, {{.*}} [[SIZE]], align 16
// CHECK: [[T_TMP:%.*]] = bitcast i8* [[T_ALLOCA]] to %swift.opaque*
// CHECK: [[TEMP:%.*]] = call %swift.opaque* {{.*}}(%swift.opaque* noalias [[T_TMP]], %swift.opaque* noalias %0, %swift.type* %T)
// CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque*
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* [[T0]], %swift.opaque* [[T_TMP]], %swift.type* %T, %swift.type* @"$sSiN", i64 7)
// CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0
// CHECK: [[INT_RESULT:%.*]] = load i64, i64* [[T0]],
// CHECK: ret i64 [[INT_RESULT]]
}
// CHECK: define hidden swiftcc void @"$s13generic_casts8intToAllyxSilF"(%swift.opaque* noalias nocapture sret, i64, %swift.type* %T) {{.*}} {
func intToAll<T>(_ x: Int) -> T {
// CHECK: [[INT_TEMP:%.*]] = alloca %TSi,
// CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0
// CHECK: store i64 %1, i64* [[T0]],
// CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque*
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[T0]], %swift.type* @"$sSiN", %swift.type* %T, i64 7)
return x as! T
}
// CHECK: define hidden swiftcc i64 @"$s13generic_casts8anyToIntySiypF"(%Any* noalias nocapture dereferenceable({{.*}})) {{.*}} {
func anyToInt(_ x: Any) -> Int {
return x as! Int
}
@objc protocol ObjCProto1 {
static func forClass()
static func forInstance()
var prop: NSObject { get }
}
@objc protocol ObjCProto2 : ObjCProto1 {}
@objc class ObjCClass {}
// CHECK: define hidden swiftcc %objc_object* @"$s13generic_casts9protoCastyAA10ObjCProto1_So9NSRuncingpAA0E6CClassCF"(%T13generic_casts9ObjCClassC*) {{.*}} {
func protoCast(_ x: ObjCClass) -> ObjCProto1 & NSRuncing {
// CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_"
// CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing"
// CHECK: call %objc_object* @swift_dynamicCastObjCProtocolUnconditional(%objc_object* {{%.*}}, i64 2, i8** {{%.*}})
return x as! ObjCProto1 & NSRuncing
}
@objc class ObjCClass2 : NSObject, ObjCProto2 {
class func forClass() {}
class func forInstance() {}
var prop: NSObject { return self }
}
// <rdar://problem/15313840>
// Class existential to opaque archetype cast
// CHECK: define hidden swiftcc void @"$s13generic_casts33classExistentialToOpaqueArchetypeyxAA10ObjCProto1_plF"(%swift.opaque* noalias nocapture sret, %objc_object*, %swift.type* %T)
func classExistentialToOpaqueArchetype<T>(_ x: ObjCProto1) -> T {
var x = x
// CHECK: [[X:%.*]] = alloca %T13generic_casts10ObjCProto1P
// CHECK: [[LOCAL:%.*]] = alloca %T13generic_casts10ObjCProto1P
// CHECK: [[LOCAL_OPAQUE:%.*]] = bitcast %T13generic_casts10ObjCProto1P* [[LOCAL]] to %swift.opaque*
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s13generic_casts10ObjCProto1_pMa"(i64 0)
// CHECK: [[PROTO_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[LOCAL_OPAQUE]], %swift.type* [[PROTO_TYPE]], %swift.type* %T, i64 7)
return x as! T
}
protocol P {}
protocol Q {}
// CHECK: define hidden swiftcc void @"$s13generic_casts19compositionToMemberyAA1P_pAaC_AA1QpF{{.*}}"(%T13generic_casts1PP* noalias nocapture sret, %T13generic_casts1P_AA1Qp* noalias nocapture dereferenceable({{.*}})) {{.*}} {
func compositionToMember(_ a: P & Q) -> P {
return a
}
| apache-2.0 | b96a9e751832921d86d470aa1349b1e5 | 50.905172 | 228 | 0.662016 | 3.270505 | false | false | false | false |
ParsifalC/CPCollectionViewWheelLayoutSwift | Example/CPCollectionViewWheelLayoutSwift/CPTableViewController.swift | 1 | 1370 | //
// CPTableViewController.swift
// CPCollectionViewWheelLayout-Swift
//
// Created by Parsifal on 2017/1/7.
// Copyright © 2017年 Parsifal. All rights reserved.
//
import UIKit
import CPCollectionViewWheelLayoutSwift
class CPTableViewController:UITableViewController {
let wheelTypes = ["leftBottom", "rightBottom",
"leftTop", "rightTop",
"leftCenter", "rightCenter",
"topCenter", "bottomCenter"]
var selectType = CPWheelLayoutType.leftBottom
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell",
for: indexPath)
cell.textLabel?.text = wheelTypes[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wheelTypes.count
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let indexPath = tableView.indexPath(for: sender as! UITableViewCell)
let vc = segue.destination as! CPViewController
vc.wheelType = CPWheelLayoutType(rawValue: (indexPath?.row)!)!
}
}
| mit | c598e306acfd61031d18f10b6217340d | 34.051282 | 109 | 0.651792 | 5.197719 | false | false | false | false |
mahuiying0126/MDemo | BangDemo/BangDemo/Modules/HomeDetail/view/DetailCommentView.swift | 1 | 4151 | //
// DetailCommentView.swift
// BangDemo
//
// Created by yizhilu on 2017/5/25.
// Copyright © 2017年 Magic. All rights reserved.
//
import UIKit
@objc protocol addCommentCompleteDelegate {
func addCommentComplete()
}
class DetailCommentView: UITableView ,UITableViewDelegate,UITableViewDataSource{
/** *发送视图 */
var commentHead : MCommentHeadView?
private var courseId : String?
private var pointId : String?
/** *课程评论数据 */
var commentData = Array<Any>()
private let cellID = "CommentID"
///提交评论的代理
weak var commentCompleteDelegate : addCommentCompleteDelegate?
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
commentHead = MCommentHeadView.init(frame:.init(x: 0, y: 0, width: Screen_width, height: 130))
self.tableHeaderView = commentHead
commentHead?.addCommentButton?.addTarget(self, action: #selector(addComment), for: .touchUpInside)
self.delegate = self
self.dataSource = self
self.separatorStyle = .none
self.showsVerticalScrollIndicator = false
self.showsHorizontalScrollIndicator = false
self.register(MCommentTableViewCell.self, forCellReuseIdentifier: cellID)
}
/// 课程评论数据接口
///
/// - Parameters:
/// - data: 课程评论
/// - courseID: 课程 ID
/// - pointID: 节点 ID
func commentData(_ data : Array<Any>,courseID:String,pointID:String) {
self.courseId = courseID
self.pointId = pointID
self.commentData.removeAll()
for model in data {
let cellFrame = CommentCellFrameModel().cellFrameModel(model as! CommentUserModel)
self.commentData.append(cellFrame)
}
self.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.commentData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as! MCommentTableViewCell
// let cell = MCommentTableViewCell.init(style: .default, reuseIdentifier: cellID)
let cellFrame = self.commentData[indexPath.row] as!CommentCellFrameModel
cell.updatCellFrame(model: cellFrame)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cellFrameModel = self.commentData[indexPath.row] as! CommentCellFrameModel
return cellFrameModel.cellHeight!
}
@objc func addComment() {
commentHead?.addCommentTextView?.resignFirstResponder()
if Int(USERID)! > 0 {
if self.courseId != nil && self.pointId != nil {
let addComment = MNetRequestSeting()
addComment.hostUrl = Courseassessadd()
addComment.paramet = ["courseAssess.courseId":self.courseId!,"courseAssess.kpointId":self.pointId!,"userId":USERID,"courseAssess.content":commentHead!.addCommentTextView!.text!]
addComment.requestDataFromNetSet(seting: addComment, successBlock: { [weak self] (responseData) in
if responseData["success"].boolValue {
self?.commentCompleteDelegate?.addCommentComplete()
self?.commentHead?.addCommentTextView?.text = ""
MBProgressHUD.showSuccess(responseData["message"].string)
}
}) { (merror) in
MBProgressHUD.showError("添加评论失败!")
}
}else{
MBProgressHUD.showError("添加评论失败!")
}
}else{
MBProgressHUD.showMBPAlertView("您还没有登录!", withSecond: 1.5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | d84a317dde5f1a50e210a0c3cd9d5f16 | 34.491228 | 193 | 0.620366 | 4.822408 | false | false | false | false |
Zewo/MediaTypeSerializerCollection | Source/MediaTypeSerializerCollection.swift | 1 | 3272 | // MediaTypeParserCollection.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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.
@_exported import MediaType
@_exported import InterchangeData
public enum MediaTypeSerializerCollectionError: ErrorProtocol {
case NoSuitableSerializer
case MediaTypeNotFound
}
public final class MediaTypeSerializerCollection {
public var serializers: [(MediaType, InterchangeDataSerializer)] = []
public var mediaTypes: [MediaType] {
return serializers.map({$0.0})
}
public init() {}
public func setPriority(mediaTypes: MediaType...) throws {
for mediaType in mediaTypes.reversed() {
try setTopPriority(mediaType)
}
}
public func setTopPriority(mediaType: MediaType) throws {
for index in 0 ..< serializers.count {
let tuple = serializers[index]
if tuple.0 == mediaType {
serializers.remove(at: index)
serializers.insert(tuple, at: 0)
return
}
}
throw MediaTypeSerializerCollectionError.MediaTypeNotFound
}
public func add(mediaType: MediaType, serializer: InterchangeDataSerializer) {
serializers.append(mediaType, serializer)
}
public func serializersFor(mediaType: MediaType) -> [(MediaType, InterchangeDataSerializer)] {
return serializers.reduce([]) {
if $1.0.matches(mediaType) {
return $0 + [($1.0, $1.1)]
} else {
return $0
}
}
}
public func serialize(data: InterchangeData, mediaTypes: [MediaType]) throws -> (MediaType, Data) {
var lastError: ErrorProtocol?
for acceptedType in mediaTypes {
for (mediaType, serializer) in serializersFor(acceptedType) {
do {
return try (mediaType, serializer.serialize(data))
} catch {
lastError = error
continue
}
}
}
if let lastError = lastError {
throw lastError
} else {
throw MediaTypeSerializerCollectionError.NoSuitableSerializer
}
}
}
| mit | f996ce62da629474ce1c9b545f6843c8 | 33.442105 | 103 | 0.64945 | 4.957576 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Stats/Insights/Posting Activity/PostingActivityDay.swift | 2 | 1540 | import UIKit
protocol PostingActivityDayDelegate: AnyObject {
func daySelected(_ day: PostingActivityDay)
}
class PostingActivityDay: UIView, NibLoadable {
// MARK: - Properties
@IBOutlet weak var dayButton: UIButton!
private weak var delegate: PostingActivityDayDelegate?
private var visible = true
private var active = true
private(set) var dayData: PostingStreakEvent?
// MARK: - Configure
func configure(dayData: PostingStreakEvent? = nil, delegate: PostingActivityDayDelegate? = nil) {
self.dayData = dayData
visible = dayData != nil
active = delegate != nil
self.delegate = delegate
backgroundColor = .clear
configureButton()
}
func unselect() {
dayButton.backgroundColor = colorForCount()
}
}
// MARK: - Private Extension
private extension PostingActivityDay {
func configureButton() {
dayButton.isGhostableDisabled = !visible
dayButton.isEnabled = visible && active
dayButton.backgroundColor = visible ? colorForCount() : .clear
}
func colorForCount() -> UIColor? {
guard let dayData = dayData else {
return .clear
}
return PostingActivityLegend.colorForCount(dayData.postCount)
}
@IBAction func dayButtonPressed(_ sender: UIButton) {
WPAppAnalytics.track(.statsItemTappedPostingActivityDay)
dayButton.backgroundColor = WPStyleGuide.Stats.PostingActivityColors.selectedDay
delegate?.daySelected(self)
}
}
| gpl-2.0 | 4b6c6276ec1ccbe3a894a28d199fb841 | 25.551724 | 101 | 0.678571 | 5.03268 | false | true | false | false |
felipedemetrius/AppSwift3 | AppSwift3/CommentsTaskDetailTableViewCell.swift | 1 | 2345 | //
// CommentsTaskDetailTableViewCell.swift
// AppSwift3
//
// Created by Felipe Silva on 2/15/17.
// Copyright © 2017 Felipe Silva . All rights reserved.
//
import UIKit
import Kingfisher
/// Cell with the comments of a task. Used by the TaskDetailViewController class.
class CommentsTaskDetailTableViewCell: UITableViewCell {
@IBOutlet weak var imagePhoto: UIImageView!
@IBOutlet weak var lblName: UILabel!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblText: UILabel!
@IBOutlet weak var star1: UIImageView!
@IBOutlet weak var star2: UIImageView!
@IBOutlet weak var star3: UIImageView!
@IBOutlet weak var star4: UIImageView!
@IBOutlet weak var star5: UIImageView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
/// ViewModel for this ViewCell
var viewModel: CommentsTaskDetailDataSource?
private var note : Int?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
/// Set the cell
/// - parameter comment: An CommentModel
func configure(){
lblName.text = viewModel?.comment?.name
lblTitle.text = viewModel?.comment?.title
lblText.text = viewModel?.comment?.text
imagePhoto.kf.setImage(with: URL(string: viewModel?.comment?.urlPhoto ?? ""))
imagePhoto.kf.setImage(with: URL(string: viewModel?.comment?.urlPhoto ?? ""), placeholder: nil, options: nil, progressBlock: nil) { [weak self] image in
self?.activityIndicator.stopAnimating()
}
imagePhoto.layer.cornerRadius = imagePhoto.frame.width / 2
imagePhoto.layer.masksToBounds = true
setStars(note: viewModel?.comment?.note ?? 1)
}
/// Fill in the number of stars according to the comment note
/// - parameter note: Note of comment (Int)
private func setStars(note: Int){
var stars = [star1, star2, star3, star4, star5]
for index in 1...note {
stars[index - 1]?.image = UIImage(named: "starfull_icon")
}
}
}
| mit | be002acb8f78bf33603f87f1ed87aec7 | 29.441558 | 160 | 0.642065 | 4.66004 | false | false | false | false |
kickstarter/ios-oss | Library/ApplePayCapabilities.swift | 1 | 3404 | import Foundation
import KsApi
import PassKit
public protocol ApplePayCapabilitiesType {
/*
Returns an array of all KSR supported networks
*/
func allSupportedNetworks() -> [PKPaymentNetwork]
/*
Returns whether the current device is capable of making payments using the list of allSupportedNetworks()
*/
func applePayCapable() -> Bool
/*
Returns whether the current device is capable of making Apple Pay payments with any network
*/
func applePayDevice() -> Bool
/*
Returns whether the current device is capable of making
Apple Pay payments with the networks defined by the project's availableCardTypes
parameters:
- project: the project to use for determining supported card types
*/
func applePayCapable(for project: Project) -> Bool
/*
Returns an array of supported PKPaymentNetworks
determined from the project's list of availableCardTypes
If the project does not have a list of availableCardTypes,
allSupportedNetworks() is used
parameters:
- project: the project to use for determining supported card types
*/
func supportedNetworks(for project: Project) -> [PKPaymentNetwork]
}
public struct ApplePayCapabilities: ApplePayCapabilitiesType {
public init() {}
public func allSupportedNetworks() -> [PKPaymentNetwork] {
return [
.amex,
.masterCard,
.visa,
.discover,
.JCB,
.chinaUnionPay
]
}
public func applePayCapable() -> Bool {
return PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: self.allSupportedNetworks())
}
public func applePayDevice() -> Bool {
return PKPaymentAuthorizationViewController.canMakePayments()
}
public func applePayCapable(for project: Project) -> Bool {
return PKPaymentAuthorizationViewController.canMakePayments(
usingNetworks: self.supportedNetworks(for: project)
)
}
public func supportedNetworks(for project: Project) -> [PKPaymentNetwork] {
guard let availableCardTypes = project.availableCardTypes else {
let projectCountryCurrency = projectCountry(forCurrency: project.stats.currency) ?? project.country
return self.supportedNetworks(projectCountry: projectCountryCurrency)
}
return availableCardTypes
.compactMap(CreditCardType.init(rawValue:))
.compactMap(ApplePayCapabilities.pkPaymentNetwork(for:))
}
internal func supportedNetworks(projectCountry: Project.Country) -> [PKPaymentNetwork] {
let allSupportedNetworks = self.allSupportedNetworks()
if projectCountry == Project.Country.us {
return allSupportedNetworks
} else {
let unsupportedNetworks: Set<PKPaymentNetwork> = [.chinaUnionPay, .discover]
let supportedNetworks: Set<PKPaymentNetwork> = Set.init(allSupportedNetworks)
return Array(supportedNetworks.subtracting(unsupportedNetworks))
}
}
private static func pkPaymentNetwork(for graphCreditCardType: CreditCardType)
-> PKPaymentNetwork? {
switch graphCreditCardType {
case .amex:
return PKPaymentNetwork.amex
case .discover:
return PKPaymentNetwork.discover
case .jcb:
return PKPaymentNetwork.JCB
case .mastercard:
return PKPaymentNetwork.masterCard
case .unionPay:
return PKPaymentNetwork.chinaUnionPay
case .visa:
return PKPaymentNetwork.visa
case .diners, .generic:
return nil
}
}
}
| apache-2.0 | 6649553ffe241f11683ac76ba9804703 | 29.392857 | 108 | 0.733255 | 4.947674 | false | false | false | false |
uasys/swift | test/TBD/protocol.swift | 10 | 3392 | // RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s
public protocol Public {
func publicMethod()
associatedtype PublicAT
var publicVarGet: Int { get }
var publicVarGetSet: Int { get set }
}
protocol Internal {
func internalMethod()
associatedtype InternalAT
var internalVarGet: Int { get }
var internalVarGetSet: Int { get set }
}
private protocol Private {
func privateMethod()
associatedtype PrivateAT
var privateVarGet: Int { get }
var privateVarGetSet: Int { get set }
}
// Naming scheme: type access, protocol access, witness access, type kind
public struct PublicPublicPublicStruct: Public {
public func publicMethod() {}
public typealias PublicAT = Int
public let publicVarGet: Int = 0
public var publicVarGetSet: Int = 0
}
public struct PublicInternalPublicStruct: Internal {
public func internalMethod() {}
public typealias InternalAT = Int
public let internalVarGet: Int = 0
public var internalVarGetSet: Int = 0
}
public struct PublicPrivatePublicStruct: Private {
public func privateMethod() {}
public typealias PrivateAT = Int
public let privateVarGet: Int = 0
public var privateVarGetSet: Int = 0
}
public struct PublicInternalInternalStruct: Internal {
func internalMethod() {}
typealias InternalAT = Int
let internalVarGet: Int = 0
var internalVarGetSet: Int = 0
}
public struct PublicPrivateInternalStruct: Private {
func privateMethod() {}
typealias PrivateAT = Int
let privateVarGet: Int = 0
var privateVarGetSet: Int = 0
}
public struct PublicPrivateFileprivateStruct: Private {
fileprivate func privateMethod() {}
fileprivate typealias PrivateAT = Int
fileprivate let privateVarGet: Int = 0
fileprivate var privateVarGetSet: Int = 0
}
struct InternalPublicInternalStruct: Public {
func publicMethod() {}
typealias PublicAT = Int
let publicVarGet: Int = 0
var publicVarGetSet: Int = 0
}
struct InternalInternalInternalStruct: Internal {
func internalMethod() {}
typealias InternalAT = Int
let internalVarGet: Int = 0
var internalVarGetSet: Int = 0
}
struct InternalPrivateInternalStruct: Private {
func privateMethod() {}
typealias PrivateAT = Int
let privateVarGet: Int = 0
var privateVarGetSet: Int = 0
}
struct InternalPrivateFileprivateStruct: Private {
fileprivate func privateMethod() {}
fileprivate typealias PrivateAT = Int
fileprivate let privateVarGet: Int = 0
fileprivate var privateVarGetSet: Int = 0
}
private struct PrivatePublicInternalStruct: Public {
func publicMethod() {}
typealias PublicAT = Int
let publicVarGet: Int = 0
var publicVarGetSet: Int = 0
}
private struct PrivateInternalInternalStruct: Internal {
func internalMethod() {}
typealias InternalAT = Int
let internalVarGet: Int = 0
var internalVarGetSet: Int = 0
}
private struct PrivatePrivateInternalStruct: Private {
func privateMethod() {}
typealias PrivateAT = Int
let privateVarGet: Int = 0
var privateVarGetSet: Int = 0
}
private struct PrivatePrivateFileprivateStruct: Private {
fileprivate func privateMethod() {}
fileprivate typealias PrivateAT = Int
fileprivate let privateVarGet: Int = 0
fileprivate var privateVarGetSet: Int = 0
}
| apache-2.0 | d3eedd67397303d69b27fdc20af8b5f7 | 27.745763 | 115 | 0.723172 | 5.017751 | false | false | false | false |
zerdzhong/LeetCode | swift/LeetCode.playground/Pages/19_Remove Nth Node From End of List.xcplaygroundpage/Contents.swift | 1 | 1490 | //: [Previous](@previous)
//https://leetcode.com/problems/remove-nth-node-from-end-of-list/
import Foundation
// Definition for singly-linked list.
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
public func message() -> String{
var msg = "\(self.val)"
var nextNode = self
while nextNode.next != nil {
nextNode = nextNode.next!
msg += "->\(nextNode.val)"
}
return msg
}
}
class Solution {
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
var preTargetNode = head!
var endNode = head!
var preTargetDistance = 0
while endNode.next != nil {
endNode = endNode.next!
if preTargetDistance < n {
preTargetDistance += 1
} else {
preTargetNode = preTargetNode.next!
}
}
if let tagetNode = preTargetNode.next, preTargetDistance == n {
preTargetNode.next = tagetNode.next
return head
} else if preTargetDistance == n - 1 {
return head?.next
}
return nil
}
}
let list = ListNode(1)
list.next = ListNode(2)
//list.next?.next = ListNode(3)
list.message()
Solution().removeNthFromEnd(list, 2)?.message()
//: [Next](@next)
| mit | 9e560862d1a062cd743a24c2b2fe7d77 | 22.28125 | 71 | 0.526174 | 4.138889 | false | false | false | false |
chenchangqing/learniosanimation | example04/example04/ViewController04.swift | 1 | 2265 | //
// ViewController04.swift
// example04
//
// Created by green on 15/8/14.
// Copyright (c) 2015年 com.chenchangqing. All rights reserved.
//
import UIKit
class ViewController04: UIViewController {
private var gradientLayer : CAGradientLayer!
private var timer : NSTimer!
private var imageView01 : UIImageView!
private var imageView02 : UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
setup()
// 添加定时器
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("timerEvent"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - SETUP
private func setup() {
setup01()
setup02()
}
/**
* 设置图片
*/
private func setup01() {
imageView01 = UIImageView(frame: view.bounds)
imageView01.image = UIImage(named: "bg")
view.addSubview(imageView01)
imageView02 = UIImageView(frame: view.bounds)
imageView02.image = UIImage(named: "bg2")
view.addSubview(imageView02)
}
/**
* 设置渐变mask
*/
private func setup02() {
// 渐变图层
gradientLayer = CAGradientLayer()
gradientLayer.frame = view.bounds
// 设置颜色
gradientLayer.colors = [UIColor.clearColor().colorWithAlphaComponent(0).CGColor, UIColor.redColor().colorWithAlphaComponent(1).CGColor]
gradientLayer.locations = [NSNumber(float: 0.7),NSNumber(float: 1)]
// 设置渐变图层mask
imageView02.layer.mask = gradientLayer
}
func timerEvent() {
gradientLayer.locations = [NSNumber(float: Float(arc4random()%100)/100),1]
gradientLayer.colors = [UIColor.clearColor().colorWithAlphaComponent(0).CGColor, UIColor(red: CGFloat(arc4random() % 255)/255, green: CGFloat(arc4random() % 255)/255, blue: CGFloat(arc4random() % 255)/255, alpha: 1).colorWithAlphaComponent(1).CGColor]
}
}
| apache-2.0 | 8b9e0303296ec0c73fcc228cacb3b9c1 | 26.962025 | 260 | 0.60163 | 4.573499 | false | false | false | false |
shmidt/ContactsPro | ContactsPro/AppDelegate.swift | 1 | 3842 | //
// AppDelegate.swift
// ContactsPro
//
// Created by Dmitry Shmidt on 16/02/15.
// Copyright (c) 2015 Dmitry Shmidt. All rights reserved.
//
import UIKit
import RealmSwift
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Fabric.with([Crashlytics()])
setupRealmInAppGroup()
enableRealmEncryption()
setupAppearance()
// Override point for customization after application launch.
return true
}
func setupRealmInAppGroup(){
let directory = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.shmidt.ContactsPro")
if directory == nil {
fatalError("The shared application group container is unavailable. Check your entitlements and provisioning profiles for this target.")
}else{
let realmPath = directory!.path!.stringByAppendingPathComponent("db.realm")
Realm.defaultPath = realmPath
}
}
func enableRealmEncryption(){
// Realms are used to group data together
let realm = Realm() // Create realm pointing to default file
// Encrypt realm file
var error: NSError?
let success = NSFileManager.defaultManager().setAttributes([NSFileProtectionKey: NSFileProtectionComplete],
ofItemAtPath: Realm().path, error: &error)
if !success {
println("encryption attribute was not successfully set on realm file")
println("error: \(error?.localizedDescription)")
}
}
func setupAppearance(){
window?.tintColor = UIColor(red: 0.095, green: 0.757, blue: 0.997, alpha: 1.000)
let font = UIFont(name: "Avenir-Medium", size: 18.0)
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName:font!]
// UITabBar.appearance().selectedImageTintColor = UIColor(red: 0.986, green: 0.120, blue: 0.432, alpha: 1.000)
}
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:.
}
}
| mit | 9a29cab8d497735585f06a8e9946343e | 43.16092 | 285 | 0.707704 | 5.449645 | false | false | false | false |
timelessg/TLStoryCamera | TLStoryCameraFramework/TLStoryCameraFramework/Class/Views/TLStoryOverlayEditView.swift | 1 | 8411 | //
// TLStoryOverlayEditView.swift
// TLStoryCamera
//
// Created by garry on 2017/5/31.
// Copyright © 2017年 com.garry. All rights reserved.
//
import UIKit
protocol TLStoryOverlayEditViewDelegate: NSObjectProtocol {
func storyOverlayEditClose()
func storyOverlayEditDoodleEditable()
func storyOverlayEditStickerPickerDisplay()
func storyOverlayEditTextEditerDisplay()
func storyOverlayEditAudio(enable:Bool)
func storyOverlayEditSave()
func storyOverlayEditPublish()
}
extension TLStoryOverlayEditViewDelegate {
func storyOverlayEditAudioEnable() {
}
}
class TLStoryOverlayEditView: UIView {
public weak var delegate:TLStoryOverlayEditViewDelegate?
fileprivate var topGradientView:TLStoryFullScreenDarkGradientView?
fileprivate var bottomGradientView:TLStoryFullScreenDarkGradientView?
fileprivate lazy var closeBtn:UIButton = {
let btn = UIButton.init(type: UIButtonType.custom)
btn.showsTouchWhenHighlighted = true
btn.setImage(UIImage.tl_imageWithNamed(named: "story_icon_close"), for: .normal)
btn.addTarget(self, action: #selector(closeAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var doodleBtn:UIButton = {
let btn = UIButton.init(type: UIButtonType.custom)
btn.showsTouchWhenHighlighted = true
btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_drawing_tool"), for: .normal)
btn.addTarget(self, action: #selector(doodleAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var tagsBtn:UIButton = {
let btn = UIButton.init(type: UIButtonType.custom)
btn.showsTouchWhenHighlighted = true
btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_tags"), for: .normal)
btn.addTarget(self, action: #selector(addTagsAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var textBtn:UIButton = {
let btn = UIButton.init(type: UIButtonType.custom)
btn.showsTouchWhenHighlighted = true
btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_text"), for: .normal)
btn.addTarget(self, action: #selector(addTextAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var audioEnableBtn:UIButton = {
let btn = UIButton.init(type: UIButtonType.custom)
btn.showsTouchWhenHighlighted = true
btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_voice_on"), for: .normal)
btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_voice_off"), for: .selected)
btn.addTarget(self, action: #selector(audioEnableAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var saveBtn:UIButton = {
let btn = UIButton.init(type: UIButtonType.custom)
btn.showsTouchWhenHighlighted = true
btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_download"), for: .normal)
btn.addTarget(self, action: #selector(saveAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var publishBtn:UIButton = {
let btn = UIButton.init(type: UIButtonType.custom)
btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_publish"), for: .normal)
btn.addTarget(self, action: #selector(publishAction), for: .touchUpInside)
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
topGradientView = TLStoryFullScreenDarkGradientView.init(frame: CGRect.init(x: 0, y: 0, width: self.width, height: 85), direction: .top)
self.addSubview(topGradientView!)
bottomGradientView = TLStoryFullScreenDarkGradientView.init(frame: CGRect.init(x: 0, y: self.height - 85, width: self.width, height: 85), direction: .bottom)
self.addSubview(bottomGradientView!)
addSubview(closeBtn)
closeBtn.bounds = CGRect.init(x: 0, y: 0, width: 45, height: 45)
closeBtn.origin = CGPoint.init(x: 0, y: 0)
addSubview(doodleBtn)
doodleBtn.bounds = CGRect.init(x: 0, y: 0, width: 45, height: 45)
doodleBtn.origin = CGPoint.init(x: self.width - doodleBtn.width, y: 0)
addSubview(textBtn)
textBtn.bounds = CGRect.init(x: 0, y: 0, width: 45, height: 45)
textBtn.center = CGPoint.init(x: doodleBtn.centerX - 45, y: doodleBtn.centerY)
addSubview(tagsBtn)
tagsBtn.bounds = CGRect.init(x: 0, y: 0, width: 45, height: 45)
tagsBtn.center = CGPoint.init(x: textBtn.centerX - 45, y: closeBtn.centerY)
addSubview(audioEnableBtn)
audioEnableBtn.bounds = CGRect.init(x: 0, y: 0, width: 45, height: 45)
audioEnableBtn.center = CGPoint.init(x: tagsBtn.centerX - 45, y: closeBtn.centerY)
addSubview(publishBtn)
publishBtn.sizeToFit()
publishBtn.origin = CGPoint.init(x: self.width - publishBtn.width - 15, y: self.height - publishBtn.height - 15)
addSubview(saveBtn)
saveBtn.bounds = CGRect.init(x: 0, y: 0, width: 45, height: 45)
saveBtn.center = CGPoint.init(x: closeBtn.centerX, y: publishBtn.centerY)
}
@objc fileprivate func closeAction() {
self.dismiss()
self.delegate?.storyOverlayEditClose()
}
@objc fileprivate func doodleAction() {
self.dismiss()
self.delegate?.storyOverlayEditDoodleEditable()
}
@objc fileprivate func addTagsAction() {
self.dismiss()
self.delegate?.storyOverlayEditStickerPickerDisplay()
}
@objc fileprivate func addTextAction() {
self.dismiss()
self.delegate?.storyOverlayEditTextEditerDisplay()
}
@objc fileprivate func audioEnableAction(sender:TLButton) {
sender.isSelected = !sender.isSelected
self.delegate?.storyOverlayEditAudio(enable: !sender.isSelected)
}
@objc fileprivate func saveAction() {
self.delegate?.storyOverlayEditSave()
}
@objc fileprivate func publishAction() {
self.delegate?.storyOverlayEditPublish()
}
public func dismiss() {
UIView.animate(withDuration: 0.3, animations: {
self.alpha = 0
}) { (x) in
if x {
self.isHidden = true
}
}
}
public func dispaly() {
self.layer.removeAllAnimations()
self.isHidden = false
UIView.animate(withDuration: 0.3) {
self.alpha = 1
}
}
public func setAudioEnableBtn(hidden:Bool) {
self.audioEnableBtn.isHidden = hidden
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if self.closeBtn.frame.contains(point) || self.audioEnableBtn.frame.contains(point) || self.tagsBtn.frame.contains(point) || self.textBtn.frame.contains(point) || self.doodleBtn.frame.contains(point) || self.saveBtn.frame.contains(point) || self.publishBtn.frame.contains(point) {
return true
}
return false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TLStoryFullScreenDarkGradientView: UIView {
public enum Direction {
case top
case bottom
}
fileprivate lazy var gradientLayer:CAGradientLayer = {
var gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.init(colorHex: 0x000000, alpha: 0.3).cgColor, UIColor.init(colorHex: 0x000000, alpha: 0.1).cgColor,UIColor.init(colorHex: 0x000000, alpha: 0).cgColor]
return gradientLayer
}()
init(frame: CGRect, direction:Direction) {
super.init(frame: frame)
gradientLayer.frame = self.bounds
if direction == .top {
gradientLayer.startPoint = CGPoint.init(x: 0.5, y: 0)
gradientLayer.endPoint = CGPoint.init(x: 0.5, y: 1)
}else {
gradientLayer.startPoint = CGPoint.init(x: 0.5, y: 1)
gradientLayer.endPoint = CGPoint.init(x: 0.5, y: 0)
}
self.layer.addSublayer(gradientLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 888609fa118810baa51aaf5fdc703faa | 36.20354 | 288 | 0.6495 | 4.17685 | false | false | false | false |
dmitryrybakov/hubchatsample | hubchatTestapp/UtilsExtensions/DictionaryDeeplyNestedExtension.swift | 1 | 649 | //
// DictionaryDeeplyNestedExtension.swift
// hubchatTestapp
//
// Created by Dmitry on 05.02.17.
// Copyright © 2017 hubchat. All rights reserved.
//
import Foundation
extension Dictionary where Key: Hashable, Value: Any {
func getValue(forKeyPath components : Array<Any>) -> Any? {
var comps = components;
let key = comps.remove(at: 0)
if let k = key as? Key {
if(comps.count == 0) {
return self[k]
}
if let v = self[k] as? Dictionary<AnyHashable,Any> {
return v.getValue(forKeyPath : comps)
}
}
return nil
}
}
| mit | c11aa0aa886d7d7f25c1f72a7814b448 | 24.92 | 64 | 0.561728 | 3.927273 | false | false | false | false |
yunuserenguzel/road-game | Generator/GeneratorUnitTests/CellUnitTests.swift | 1 | 3960 | //
// GeneratorUnitTests.swift
// GeneratorUnitTests
//
// Created by Yunus Eren Guzel on 21/09/16.
// Copyright © 2016 yeg. All rights reserved.
//
import XCTest
class CellUnitTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testCell() {
let point = Point(x: 0, y: 0)
let cellType: CellType = .active
let cell = Cell(point: point, cellType: cellType)
XCTAssertNotNil(cell)
}
// cell.direction(ofCell:)
func testCellLocationVerticalNeighbor() {
let cell1 = Cell(point: Point(x: 0, y: 0), cellType: .active)
let cell2 = Cell(point: Point(x: 0, y: 1), cellType: .active)
XCTAssertEqual(cell1.direction(ofCell: cell2), .south)
XCTAssertEqual(cell2.direction(ofCell: cell1), .north)
}
func testCellLocationHorizontalNeighbor() {
let cell1 = Cell(point: Point(x: 0, y: 0), cellType: .active)
let cell2 = Cell(point: Point(x: 1, y: 0), cellType: .active)
XCTAssertEqual(cell1.direction(ofCell: cell2), .east)
XCTAssertEqual(cell2.direction(ofCell: cell1), .west)
}
func testCellLocationCross() {
let cell1 = Cell(point: Point(x: 0, y: 1), cellType: .active)
let cell2 = Cell(point: Point(x: 1, y: 0), cellType: .active)
XCTAssertEqual(cell1.direction(ofCell: cell2), nil)
XCTAssertEqual(cell2.direction(ofCell: cell1), nil)
}
func testCellLocationCrossReverse() {
let cell1 = Cell(point: Point(x: 1, y: 0), cellType: .active)
let cell2 = Cell(point: Point(x: 0, y: 1), cellType: .active)
XCTAssertEqual(cell1.direction(ofCell: cell2), nil)
XCTAssertEqual(cell2.direction(ofCell: cell1), nil)
}
func testCellLocationHorizontalDistant() {
let cell1 = Cell(point: Point(x: 2, y: 0), cellType: .active)
let cell2 = Cell(point: Point(x: 0, y: 0), cellType: .active)
XCTAssertEqual(cell1.direction(ofCell: cell2), nil)
XCTAssertEqual(cell2.direction(ofCell: cell1), nil)
}
func testCellLocationVerticalDistant() {
let cell1 = Cell(point: Point(x: 1, y: 10), cellType: .active)
let cell2 = Cell(point: Point(x: 1, y: 5), cellType: .active)
XCTAssertEqual(cell1.direction(ofCell: cell2), nil)
XCTAssertEqual(cell2.direction(ofCell: cell1), nil)
}
func testCellDisconnectShouldDeleteConnection() {
let cell1 = Cell(point: Point(x: 1, y: 0), cellType: .active)
let cell2 = Cell(point: Point(x: 1, y: 1), cellType: .active)
cell1.connection.south = cell2
cell2.connection.north = cell1
cell1.disconnect(fromCell: cell2)
XCTAssertNil(cell1.connection.south)
XCTAssertNil(cell2.connection.north)
}
func testCellConnectToAnotherCell() {
let cell1 = Cell(point: Point(x: 1, y: 0), cellType: .active)
let cell2 = Cell(point: Point(x: 1, y: 1), cellType: .active)
let result = cell1.connect(toCell: cell2)
XCTAssertEqual(result, true)
XCTAssertEqual(cell1.connection.south, cell2)
XCTAssertEqual(cell2.connection.north, cell1)
XCTAssertEqual(cell1.connection.count, 1)
XCTAssertEqual(cell2.connection.count, 1)
}
func testCellCanConnectReturnsFalseAfterConnect() {
let cell1 = Cell(point: Point(x: 3, y: 2), cellType: .active)
let cell2 = Cell(point: Point(x: 2, y: 2), cellType: .active)
XCTAssert(cell1.canConnect(toCell: cell2))
XCTAssert(cell1.connect(toCell: cell2))
XCTAssertFalse(cell1.canConnect(toCell: cell2))
}
}
| mit | 6274944e63530abdaf3d3c99ca0da4ca | 36.349057 | 111 | 0.63223 | 3.658965 | false | true | false | false |
jeannustre/HomeComics | HomeComics/BookCollectionViewCell.swift | 1 | 1109 | //
// BookCollectionViewCell.swift
// HomeComics
//
// Created by Jean Sarda on 07/05/2017.
// Copyright © 2017 Jean Sarda. All rights reserved.
//
import UIKit
import Chameleon
class BookCollectionViewCell: UICollectionViewCell {
@IBOutlet var imageView: UIImageView!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var authorLabel: UILabel!
var imageURL: String?
func configureWith(book: Book, authors: [Author], background: UIColor) {
titleLabel.text = book.title
authorLabel.text = ""
backgroundColor = background
for authorID in book.authors! { // for each author id in the book
if !((authorLabel.text?.isEmpty)!) { // if it's the second author or more,
authorLabel.text = authorLabel.text! + ", " // we separate them
}
let author = authors.filter { $0.id == authorID } // get the Author that matches the current book.author id
if author.count > 0 {
authorLabel.text = authorLabel.text! + author[0].name!
}
}
}
}
| gpl-3.0 | 17c4a812beff2132418130d3d1c22586 | 28.157895 | 119 | 0.609206 | 4.559671 | false | false | false | false |
Tnecniv/zenith | zenith/Plumber.swift | 1 | 18016 | //
// Plumber.swift
// macme
//
// Created by Vincent Pacelli on 7/5/15.
// Copyright (c) 2015 tnecniv. All rights reserved.
//
import Cocoa
import Foundation
struct PlumberMessage {
var src: String = ""
var dst: String = ""
var wdir: String = ""
var type: String = ""
var attr: Dictionary<String, String> = Dictionary()
var data: [UInt8] = []
}
enum PlumberLexResult {
case Definition(String, String)
case Rule(String, String, String)
case Include(String)
case Error(String?)
}
enum PlumbResult {
case Error(String?)
case Start(String, [String: String])
case Client(String, [String: String])
case None
}
func ==(a: PlumbResult, b: PlumbResult) -> Bool {
switch (a, b) {
case (.Error(let s1), .Error(let s2)):
return s1 == s2
case (.Start(let s1, let d1), .Start(let s2, let d2)):
return s1 == s2 && d1 == d2
case (.Client(let s1, let d1), .Client(let s2, let d2)):
return s1 == s2 && d1 == d2
case (.None, .None):
return true
default:
return false
}
}
func !=(a: PlumbResult, b: PlumbResult) -> Bool {
return !(a == b)
}
class Plumber {
var plumbFileContent: String = "";
var lines: [String] = []
var fileMgr: NSFileManager = NSFileManager()
var lastCaptureGroup: Int = 0
init() {
}
init(path: String) {
loadFile(path)
}
func loadFile(path: String) {
var error: NSError?
var content: String = NSString(contentsOfFile: path.stringByExpandingTildeInPath, encoding: NSASCIIStringEncoding, error: nil) as! String
lines = split(content, allowEmptySlices: true, isSeparator: {(c: Character) -> Bool in return c == "\n" })
}
func lex(line: String) -> PlumberLexResult {
var first: String = ""
var second: String = ""
var rest: String = ""
var mode: Int = 0;
var eatWhitespace: Bool = true
var error: String = ""
for c in Range(start: line.unicodeScalars.startIndex, end: line.unicodeScalars.endIndex) {
switch mode {
case 0:
if NSCharacterSet.whitespaceCharacterSet().longCharacterIsMember(line.unicodeScalars[c].value) {
if eatWhitespace {
continue
} else {
eatWhitespace = true
mode = 1;
}
} else if line.unicodeScalars[c] == "=" {
var value: String = ""
for x in Range(start: c.successor(), end: line.unicodeScalars.endIndex) {
value.append(line.unicodeScalars[x])
}
return .Definition(first, value.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()))
} else {
eatWhitespace = false
first.append(line.unicodeScalars[c])
}
case 1:
if NSCharacterSet.whitespaceCharacterSet().longCharacterIsMember(line.unicodeScalars[c].value) {
if eatWhitespace {
continue
} else {
eatWhitespace = true
mode = 2
}
} else {
eatWhitespace = false
second.append(line.unicodeScalars[c])
}
case 2:
rest.append(line.unicodeScalars[c])
default:
return .Error(error)
}
}
if first == "" || second == "" {
return .Error("Line incomplete")
} else if first == "include" {
return .Include(second + rest)
} else if rest == "" {
return .Error("Expected argument")
} else {
return .Rule(first, second, rest)
}
}
func evalArg(s: String, defs: Dictionary<String, String>) -> String {
var singleQuote: Bool = false
var doubleQuote: Bool = false
var variable: Bool = false
var escape: Bool = false
var ret: String = ""
var variableName: String = ""
var alphanum = NSCharacterSet.alphanumericCharacterSet();
for c in s.unicodeScalars {
if c == "'" {
if doubleQuote {
ret.append(c)
} else if escape {
ret.append(c)
escape = false
} else {
singleQuote = !singleQuote
}
} else if c == "\"" {
if singleQuote {
ret.append(c)
} else if escape {
ret.append(c)
escape = false
} else {
doubleQuote = !doubleQuote
}
} else if c == "\\" {
if escape {
ret.append(c)
escape = false
} else if singleQuote {
ret.append(c)
} else {
escape = true
}
} else if c == "$" {
if escape {
ret.append(c)
} else if singleQuote {
ret.append(c)
} else if variable {
if let val = defs[variableName] {
ret += val
} else {
}
variableName = String(c);
} else {
variable = true;
variableName = String(c);
}
} else {
if variable && alphanum.longCharacterIsMember(c.value) {
variableName.append(c)
} else if variable && !alphanum.longCharacterIsMember(c.value) {
variable = false
if let val = defs[variableName] {
ret += val
} else {
ret += "" // Shell doesnt error on undefs, they are just empty
}
ret.append(c)
} else {
ret.append(c)
}
}
}
if (variable) {
if let val = defs[variableName] {
ret += val
} else {
}
}
return ret;
}
func parseKeyValueList(str: String, defs: Dictionary<String, String>) -> Dictionary<String, String>? {
var ret: Dictionary<String, String> = Dictionary<String, String>()
var lexingKey: Bool = true
var key: String = ""
var value: String = ""
var singleQuote: Bool = false
var doubleQuote: Bool = false
var escape: Bool = false
for c in str.unicodeScalars {
if (lexingKey) {
if NSCharacterSet.alphanumericCharacterSet().longCharacterIsMember(c.value) {
key.append(c)
} else if c == "=" {
lexingKey = false
} else if NSCharacterSet.whitespaceCharacterSet().longCharacterIsMember(c.value) {
// Do nothing!!
} else {
return nil
}
} else {
if c == "\\" {
if (escape) { value.append(c); escape = false }
else { escape = true }
} else if c == "'" {
if (escape) { value.append(c); escape = false }
else if doubleQuote { value.append(c) }
else { singleQuote = !singleQuote }
} else if c == "\"" {
if (escape) { value.append(c); escape = false }
else if singleQuote { value.append(c) }
else { doubleQuote = !singleQuote }
} else if !singleQuote && !doubleQuote
&& NSCharacterSet.whitespaceCharacterSet().longCharacterIsMember(c.value) {
ret[key] = evalArg(value, defs: defs)
key = ""
value = ""
lexingKey = true
} else {
value.append(c)
}
}
}
ret[key] = evalArg(value, defs: defs)
return ret
}
func plumb(message: PlumberMessage) -> PlumbResult {
var defs: Dictionary<String, String> = Dictionary<String, String>()
var badParse: Bool = false
var skipRule: Bool = false
var lineNum: Int = 0
var action: PlumbResult = .None
var msg = message
for line in lines {
lineNum = lineNum + 1
if line.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) == ""
|| line[line.startIndex] == "#" {
if !skipRule && action != .None {
return action
} else {
skipRule = false
msg = message // Reset for next rule
action = .None
continue
}
}
var lexResult = lex(line)
switch (lexResult) {
case .Definition(let name, let value):
defs["$" + name] = evalArg(value, defs: defs)
case .Include(let path):
print("nop")
case .Rule(let first, let second, let third):
var eThird = evalArg(third, defs: defs)
if second == "add" {
if first != "attr" { return .Error(String(lineNum) + ": Expected `attr' as object") }
else {
if let list = parseKeyValueList(third, defs: defs) {
for key in list.keys {
msg.attr[key] = list[key]
}
} else {
return .Error(String(lineNum) + ": Error parsing key-value list")
}
}
} else if second == "delete" {
if first != "attr" { return .Error(String(lineNum) + ": Expected `attr' as object") }
else {
msg.attr.removeValueForKey(eThird)
}
} else if second == "is" {
if first == "src" {
skipRule = !(msg.src == eThird)
} else if first == "dst" {
skipRule = !(msg.dst == eThird)
} else if first == "wdir" {
skipRule = !(msg.wdir == eThird)
} else if first == "type" {
skipRule = !(msg.type == eThird)
} else if first == "ndata" {
skipRule = !(count(msg.data) == eThird.toInt())
} else if first == "data" {
skipRule = !(msg.data == ([UInt8](eThird.utf8)))
} else {
return .Error(String(lineNum) + ": Expected object as first word")
}
} else if second == "isdir" {
var isDir: ObjCBool = false
var dir: String = ""
var exists: Bool = false
if first == "src" {
dir = msg.src
} else if first == "dst" {
dir = msg.dst
} else if first == "wdir" {
dir = msg.wdir
} else if first == "type" {
dir = msg.type
} else if first == "ndata" {
dir = String(count(msg.data))
} else if first == "data" {
dir = NSString(bytes: msg.data, length: count(msg.data), encoding: NSUTF8StringEncoding) as! String
} else if first == "arg" {
dir = eThird
} else {
return .Error(String(lineNum) + ": Expected object as first word")
}
if first == "arg" {
exists = fileMgr.fileExistsAtPath(dir.stringByExpandingTildeInPath, isDirectory: &isDir)
} else {
exists = fileMgr.fileExistsAtPath(eThird + "/" + dir.stringByExpandingTildeInPath, isDirectory: &isDir)
}
skipRule = !(exists && isDir)
if !skipRule {
defs["$dir"] = eThird
}
} else if second == "isfile" {
var file: String = ""
var exists: Bool = false
var isDir: ObjCBool = false
if first == "src" {
file = msg.src
} else if first == "dst" {
file = msg.dst
} else if first == "wdir" {
file = msg.wdir
} else if first == "type" {
file = msg.type
} else if first == "ndata" {
file = String(count(msg.data))
} else if first == "data" {
file = NSString(bytes: msg.data, length: count(msg.data), encoding: NSUTF8StringEncoding) as! String
} else if first == "arg" {
file = eThird
} else {
return .Error(String(lineNum) + ": Expected object as first word")
}
if first == "arg" {
exists = fileMgr.fileExistsAtPath(file.stringByExpandingTildeInPath, isDirectory: &isDir)
} else {
exists = fileMgr.fileExistsAtPath(eThird + "/" + file.stringByExpandingTildeInPath, isDirectory: &isDir)
}
skipRule = !(exists && !isDir)
if !skipRule {
defs["$file"] = eThird
}
} else if second == "matches" {
var str: String = ""
if first == "src" {
str = msg.src
} else if first == "dst" {
str = msg.dst
} else if first == "wdir" {
str = msg.wdir
} else if first == "type" {
str = msg.type
} else if first == "ndata" {
str = String(count(msg.data))
} else if first == "data" {
str = NSString(bytes: msg.data, length: count(msg.data), encoding: NSUTF8StringEncoding) as! String
} else {
return .Error(String(lineNum) + ": Expected object as first word")
}
var r = Regex(eThird)
skipRule = !r.test(str)
if !skipRule {
lastCaptureGroup = count(r.captureGroups) - 1
for i in 0...lastCaptureGroup {
defs["$" + String(i)] = r.captureGroups[i]
}
}
} else if second == "set" {
if first == "src" {
msg.src = eThird
} else if first == "dst" {
msg.dst = eThird
} else if first == "wdir" {
msg.dst = eThird
} else if first == "type" {
msg.dst = eThird
} else if first == "data" {
msg.data = [UInt8](eThird.utf8)
} else {
return .Error(String(lineNum) + ": Expected object as first word")
}
} else if second == "to" {
if first != "plumb" { return .Error(String(lineNum) + ": Expected `plumb' as first word") }
else if msg.dst != eThird { skipRule = true }
} else if second == "client" {
if first != "plumb" { return .Error(String(lineNum) + ": Expected `plumb' as first word") }
else if action != PlumbResult.None { return .Error(String(lineNum) + ": Cannont have a second action in rule") }
else { action = .Client(eThird, msg.attr) }
} else if second == "start" {
if first != "plumb" { return .Error(String(lineNum) + ": Expected `plumb' as first word") }
else if action != PlumbResult.None { return .Error(String(lineNum) + ": Cannont have a second action in rule") }
else { action = .Start(eThird, msg.attr) }
} else {
return .Error(String(lineNum) + ": Expected action as second word")
}
case .Error(let errorText):
return .Error(errorText)
}
}
return action
}
}
| gpl-3.0 | 1a096cc418d2f2b29bec602877b2ff3c | 37.660944 | 145 | 0.412855 | 5.215981 | false | false | false | false |
uber/RIBs | ios/tutorials/tutorial4/TicTacToe/TicTacToe/TicTacToeViewController.swift | 3 | 5105 | //
// Copyright (c) 2017. Uber Technologies
//
// 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 RIBs
import SnapKit
import UIKit
protocol TicTacToePresentableListener: AnyObject {
func placeCurrentPlayerMark(atRow row: Int, col: Int)
}
final class TicTacToeViewController: UIViewController, TicTacToePresentable, TicTacToeViewControllable {
weak var listener: TicTacToePresentableListener?
init(player1Name: String,
player2Name: String) {
self.player1Name = player1Name
self.player2Name = player2Name
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Method is not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.yellow
buildCollectionView()
}
// MARK: - TicTacToePresentable
func setCell(atRow row: Int, col: Int, withPlayerType playerType: PlayerType) {
let indexPathRow = row * GameConstants.colCount + col
let cell = collectionView.cellForItem(at: IndexPath(row: indexPathRow, section: Constants.sectionCount - 1))
cell?.backgroundColor = playerType.color
}
func announce(winner: PlayerType?, withCompletionHandler handler: @escaping () -> ()) {
let winnerString: String = {
if let winner = winner {
switch winner {
case .player1:
return "\(player1Name) Won!"
case .player2:
return "\(player2Name) Won!"
}
} else {
return "It's a Tie"
}
}()
let alert = UIAlertController(title: winnerString, message: nil, preferredStyle: .alert)
let closeAction = UIAlertAction(title: "Close Game", style: UIAlertActionStyle.default) { _ in
handler()
}
alert.addAction(closeAction)
present(alert, animated: true, completion: nil)
}
// MARK: - Private
private let player2Name: String
private let player1Name: String
private lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.itemSize = CGSize(width: Constants.cellSize, height: Constants.cellSize)
return UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
}()
private func buildCollectionView() {
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: Constants.cellIdentifier)
view.addSubview(collectionView)
collectionView.snp.makeConstraints { (maker: ConstraintMaker) in
maker.center.equalTo(self.view.snp.center)
maker.size.equalTo(CGSize(width: CGFloat(GameConstants.colCount) * Constants.cellSize, height: CGFloat(GameConstants.rowCount) * Constants.cellSize))
}
}
}
fileprivate struct Constants {
static let sectionCount = 1
static let cellSize: CGFloat = UIScreen.main.bounds.width / CGFloat(GameConstants.colCount)
static let cellIdentifier = "TicTacToeCell"
static let defaultColor = UIColor.white
}
extension TicTacToeViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return Constants.sectionCount
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return GameConstants.rowCount * GameConstants.colCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let reusedCell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.cellIdentifier, for: indexPath)
reset(cell: reusedCell)
return reusedCell
}
private func reset(cell: UICollectionViewCell) {
cell.backgroundColor = Constants.defaultColor
cell.contentView.layer.borderWidth = 2
cell.contentView.layer.borderColor = UIColor.lightGray.cgColor
}
}
// MARK: - UICollectionViewDelegate
extension TicTacToeViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let row = indexPath.row / GameConstants.colCount
let col = indexPath.row - row * GameConstants.rowCount
listener?.placeCurrentPlayerMark(atRow: row, col: col)
}
}
| apache-2.0 | 843468acc4937aae5f64ea9ddb4a3996 | 35.464286 | 161 | 0.691283 | 5.004902 | false | false | false | false |
dduan/swift | stdlib/public/SDK/CoreImage/CoreImage.swift | 1 | 1932 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
@_exported import CoreImage // Clang module
#if os(OSX)
import QuartzCore
#endif
extension CIFilter {
#if os(OSX)
// - (CIImage *)apply:(CIKernel *)k, ...
// @objc(apply:arguments:options:)
// func apply(k: CIKernel,
// arguments args: [AnyObject]?,
// options dict: Dictionary<NSObject, AnyObject>?) -> CIImage?
func apply(k: CIKernel, args: [AnyObject], options: (String, AnyObject)...) -> CIImage? {
var dict: [String : AnyObject] = [:]
for (key, value) in options {
dict[key] = value
}
return self.apply(k, arguments: args, options: dict)
}
#endif
@available(iOS, introduced: 8.0)
@available(OSX, introduced: 10.10)
convenience init?(
name: String!, elements: (String, AnyObject)...
) {
var dict: [String : AnyObject] = [:]
for (key, value) in elements {
dict[key] = value
}
self.init(name: name, withInputParameters: dict)
}
}
#if os(OSX)
extension CISampler {
// - (id)initWithImage:(CIImage *)im keysAndValues:key0, ...;
convenience init(im: CIImage!, elements: (NSCopying, AnyObject)...) {
let dict = NSMutableDictionary()
for (key, value) in elements {
dict[key] = value
}
// @objc(initWithImage:options:)
// init(image im: CIImage!,
// options dict: NSDictionary!)
self.init(image: im, options: dict as [NSObject: AnyObject])
}
}
#endif
| apache-2.0 | 786e23fab3033d63465e6c8be21d5698 | 29.1875 | 91 | 0.589027 | 4.025 | false | false | false | false |
mrchenhao/VPNOn | TodayWidget/TodayViewController.swift | 1 | 7914 | //
// TodayViewController.swift
// TodayWidget
//
// Created by Lex Tang on 12/10/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import UIKit
import NotificationCenter
import NetworkExtension
import VPNOnKit
import CoreData
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet weak var VPNSwitch: UISwitch!
@IBOutlet weak var VPNLabel: UILabel!
@IBOutlet weak var VPNStatusLabel: UILabel!
@IBOutlet weak var tagLabel: UIView!
@IBOutlet weak var contentArea: UIView!
@IBOutlet weak var switchArea: UIView!
var typeTag: VPNTypeTag {
get {
if tagLabel.subviews.first == nil {
let effect = UIVibrancyEffect()
let tagEffectView = UIVisualEffectView(effect: UIVibrancyEffect.notificationCenterVibrancyEffect())
tagEffectView.frame = tagLabel.bounds
let tagView = VPNTypeTag(frame: tagEffectView.bounds)
tagLabel.addSubview(tagEffectView)
tagEffectView.contentView.addSubview(tagView)
}
return tagLabel.subviews.first!.contentView.subviews.first! as VPNTypeTag
}
}
override func viewDidLoad() {
super.viewDidLoad()
preferredContentSize = CGSizeMake(0, 60)
var labelTapGesture = UITapGestureRecognizer(target: self, action: Selector("didTapLabel:"))
labelTapGesture.numberOfTapsRequired = 1
labelTapGesture.numberOfTouchesRequired = 1
contentArea.userInteractionEnabled = true
contentArea.addGestureRecognizer(labelTapGesture)
var switchTapGesture = UITapGestureRecognizer(target: self, action: Selector("didTapSwitch:"))
switchTapGesture.numberOfTapsRequired = 1
switchTapGesture.numberOfTouchesRequired = 1
switchArea.userInteractionEnabled = true
switchArea.addGestureRecognizer(switchTapGesture)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("coreDataDidSave:"),
name: NSManagedObjectContextDidSaveNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("VPNStatusDidChange:"),
name: NEVPNStatusDidChangeNotification,
object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: NEVPNStatusDidChangeNotification,
object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateContent()
}
func updateContent() {
// Note: In order to get the latest data.
// @see: http://stackoverflow.com/questions/25924223/core-data-ios-8-today-widget-issue
VPNDataManager.sharedManager.managedObjectContext?.reset()
if let vpn = VPNDataManager.sharedManager.activatedVPN {
VPNLabel.text = vpn.title
typeTag.type = vpn.ikev2 ? .IKEv2 : .IKEv1
typeTag.hidden = false
VPNSwitch.enabled = true
switchArea.userInteractionEnabled = true
VPNStatusDidChange(nil)
} else {
VPNLabel.text = NSLocalizedString("No VPN configured.", comment: "Today Widget - Default text")
VPNStatusLabel.text = NSLocalizedString("Please add a VPN.", comment: "Today Widget - Add VPN")
typeTag.hidden = true
VPNSwitch.setOn(false, animated: false)
VPNSwitch.enabled = false
switchArea.userInteractionEnabled = false
}
// self.VPNSwitch.setNeedsUpdateConstraints()
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.NewData)
}
// MARK: - Layout
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets
{
var edgeInsets = defaultMarginInsets
edgeInsets.bottom = 0
edgeInsets.right = 0
return edgeInsets
}
// MARK: - User actions
func toggleVPN() {
if VPNSwitch.on {
if let vpn = VPNDataManager.sharedManager.activatedVPN {
let passwordRef = VPNKeychainWrapper.passwordForVPNID(vpn.ID)
let secretRef = VPNKeychainWrapper.secretForVPNID(vpn.ID)
let certificate = VPNKeychainWrapper.certificateForVPNID(vpn.ID)
let titleWithSubfix = "Widget - \(vpn.title)"
if vpn.ikev2 {
VPNManager.sharedManager.connectIKEv2(titleWithSubfix,
server: vpn.server,
account: vpn.account,
group: vpn.group,
alwaysOn: vpn.alwaysOn,
passwordRef: passwordRef,
secretRef: secretRef,
certificate: certificate)
} else {
VPNManager.sharedManager.connectIPSec(titleWithSubfix,
server: vpn.server,
account: vpn.account,
group: vpn.group,
alwaysOn: vpn.alwaysOn,
passwordRef: passwordRef,
secretRef: secretRef,
certificate: certificate)
}
}
} else {
VPNManager.sharedManager.disconnect()
}
}
func didTapLabel(gesture: UITapGestureRecognizer) {
let appURL = NSURL(string: "vpnon://")
extensionContext!.openURL(appURL!, completionHandler: {
(complete: Bool) -> Void in
})
}
func didTapSwitch(gesture: UITapGestureRecognizer) {
VPNSwitch.setOn(!VPNSwitch.on, animated: true)
toggleVPN()
}
// MARK: - Notification
func coreDataDidSave(notification: NSNotification) {
VPNDataManager.sharedManager.managedObjectContext?.mergeChangesFromContextDidSaveNotification(notification)
updateContent()
}
func VPNStatusDidChange(notification: NSNotification?) {
switch VPNManager.sharedManager.status
{
case NEVPNStatus.Connecting:
VPNStatusLabel.text = NSLocalizedString("Connecting...", comment: "Today Widget - Status")
VPNStatusLabel.textColor = UIColor.lightGrayColor()
VPNLabel.textColor = UIColor.lightGrayColor()
break
case NEVPNStatus.Connected:
VPNStatusLabel.text = NSLocalizedString("Connected", comment: "Today Widget - Status")
VPNSwitch.setOn(true, animated: false)
VPNStatusLabel.textColor = UIColor.whiteColor()
VPNLabel.textColor = UIColor.whiteColor()
break
case NEVPNStatus.Disconnecting:
VPNStatusLabel.text = NSLocalizedString("Disconnecting...", comment: "Today Widget - Status")
VPNStatusLabel.textColor = UIColor.whiteColor()
VPNLabel.textColor = UIColor.whiteColor()
break
default:
VPNSwitch.setOn(false, animated: false)
VPNStatusLabel.textColor = UIColor.lightGrayColor()
VPNLabel.textColor = UIColor.lightGrayColor()
VPNStatusLabel.text = NSLocalizedString("Not Connected", comment: "Today Widget - Status")
}
}
}
| mit | 6cceeac20b47dcb53f12e5f5c86e57b8 | 36.685714 | 115 | 0.610058 | 5.569317 | false | false | false | false |
crescentflare/UniLayout | UniLayoutIOS/UniLayout/Classes/views/UniButtonView.swift | 1 | 8867 | //
// UniButtonView.swift
// UniLayout Pod
//
// Library view: a simple button
// Extends UIButton to support properties for UniLayout containers and more control over padding
//
import UIKit
/// A UniLayout enabled UIButton, adding padding and layout properties
open class UniButtonView: UIButton, UniLayoutView, UniLayoutPaddedView {
// ---
// MARK: Layout integration
// ---
public var layoutProperties = UniLayoutProperties()
public var visibility: UniVisibility {
set {
isHidden = newValue != .visible
layoutProperties.hiddenTakesSpace = newValue == .invisible
}
get {
if isHidden {
return layoutProperties.hiddenTakesSpace ? .invisible : .hidden
}
return .visible
}
}
// ---
// MARK: Members
// ---
private var backgroundColorNormalState: UIColor?
private var backgroundColorHighlightedState: UIColor?
private var backgroundColorDisabledState: UIColor?
private var borderColorNormalState: UIColor?
private var borderColorHighlightedState: UIColor?
private var borderColorDisabledState: UIColor?
// ---
// MARK: Change padding
// ---
public var padding: UIEdgeInsets {
get { return contentEdgeInsets }
set {
contentEdgeInsets = newValue
if contentEdgeInsets.top == 0 {
contentEdgeInsets.top = 0.01 // Prevents UIKIT to apply automatic sizing when using a zero value
}
if contentEdgeInsets.bottom == 0 {
contentEdgeInsets.bottom = 0.01
}
}
}
// ---
// MARK: Initialization
// ---
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
padding = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
}
// ---
// MARK: Override variables to update the layout
// ---
open override var contentEdgeInsets: UIEdgeInsets {
didSet {
UniLayout.setNeedsLayout(view: self)
}
}
open override var titleEdgeInsets: UIEdgeInsets {
didSet {
UniLayout.setNeedsLayout(view: self)
}
}
open override var imageEdgeInsets: UIEdgeInsets {
didSet {
UniLayout.setNeedsLayout(view: self)
}
}
open override var isHidden: Bool {
didSet {
UniLayout.setNeedsLayout(view: self)
}
}
// ---
// MARK: Override functions to update the layout
// ---
open override func setTitle(_ title: String?, for state: UIControl.State) {
super.setTitle(title, for: state)
UniLayout.setNeedsLayout(view: self)
}
open override func setImage(_ image: UIImage?, for state: UIControl.State) {
super.setImage(image, for: state)
UniLayout.setNeedsLayout(view: self)
}
open override func setBackgroundImage(_ image: UIImage?, for state: UIControl.State) {
super.setBackgroundImage(image, for: state)
UniLayout.setNeedsLayout(view: self)
}
open override func setAttributedTitle(_ title: NSAttributedString?, for state: UIControl.State) {
super.setAttributedTitle(title, for: state)
UniLayout.setNeedsLayout(view: self)
}
// ---
// MARK: Add more state support
// ---
open override var isHighlighted: Bool {
didSet {
refreshStateBackground()
if borderColorNormalState != nil || borderColorHighlightedState != nil || borderColorDisabledState != nil {
refreshStateBorder()
}
if adjustsTintColorToMatchTitle {
refreshTintColor()
}
}
}
open override var isEnabled: Bool {
didSet {
refreshStateBackground()
if borderColorNormalState != nil || borderColorHighlightedState != nil || borderColorDisabledState != nil {
refreshStateBorder()
}
if adjustsTintColorToMatchTitle {
refreshTintColor()
}
}
}
open var adjustsTintColorToMatchTitle: Bool = false {
didSet {
refreshTintColor()
}
}
open override func setTitleColor(_ color: UIColor?, for state: UIControl.State) {
super.setTitleColor(color, for: state)
if adjustsTintColorToMatchTitle {
refreshTintColor()
}
}
open override var backgroundColor: UIColor? {
get { return backgroundColorNormalState }
set { setBackgroundColor(newValue, for: .normal) }
}
public func setBackgroundColor(_ color: UIColor?, for state: UIControl.State) {
let currentState = !isEnabled ? UIControl.State.disabled : (isHighlighted ? UIControl.State.highlighted : UIControl.State.normal)
if state == .normal {
backgroundColorNormalState = color
} else if state == .highlighted {
backgroundColorHighlightedState = color
} else if state == .disabled {
backgroundColorDisabledState = color
}
if state == .normal || state == currentState {
refreshStateBackground()
}
}
public func setBorderColor(_ color: UIColor?, for state: UIControl.State) {
let currentState = !isEnabled ? UIControl.State.disabled : (isHighlighted ? UIControl.State.highlighted : UIControl.State.normal)
if state == .normal {
borderColorNormalState = color
} else if state == .highlighted {
borderColorHighlightedState = color
} else if state == .disabled {
borderColorDisabledState = color
}
if state == .normal || state == currentState {
refreshStateBorder()
}
}
private func refreshTintColor() {
if adjustsTintColorToMatchTitle {
tintColor = titleColor(for: state)
} else {
tintColor = nil
}
}
private func refreshStateBackground() {
var backgroundWasSet = false
if !isEnabled && backgroundColorDisabledState != nil {
super.backgroundColor = backgroundColorDisabledState
backgroundWasSet = true
}
if isEnabled && isHighlighted && backgroundColorHighlightedState != nil {
super.backgroundColor = backgroundColorHighlightedState
backgroundWasSet = true
}
if !backgroundWasSet {
super.backgroundColor = backgroundColorNormalState
}
}
private func refreshStateBorder() {
var borderWasSet = false
if !isEnabled && borderColorDisabledState != nil {
layer.borderColor = borderColorDisabledState?.cgColor
borderWasSet = true
}
if isEnabled && isHighlighted && borderColorHighlightedState != nil {
layer.borderColor = borderColorHighlightedState?.cgColor
borderWasSet = true
}
if !borderWasSet {
layer.borderColor = borderColorNormalState?.cgColor
}
}
// ---
// MARK: Custom layout
// ---
open func measuredSize(sizeSpec: CGSize, widthSpec: UniMeasureSpec, heightSpec: UniMeasureSpec) -> CGSize {
let limitedSize = CGSize(width: max(0, sizeSpec.width), height: max(0, sizeSpec.height))
var result = super.systemLayoutSizeFitting(limitedSize, withHorizontalFittingPriority: widthSpec == .unspecified ? UILayoutPriority.fittingSizeLevel : UILayoutPriority.required, verticalFittingPriority: heightSpec == .unspecified ? UILayoutPriority.fittingSizeLevel : UILayoutPriority.required)
if widthSpec == .exactSize {
result.width = sizeSpec.width
} else if widthSpec == .limitSize {
result.width = min(result.width, sizeSpec.width)
}
if heightSpec == .exactSize {
result.height = sizeSpec.height
} else if heightSpec == .limitSize {
result.height = min(result.height, sizeSpec.height)
}
return result
}
open override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
return measuredSize(sizeSpec: targetSize, widthSpec: horizontalFittingPriority == UILayoutPriority.required ? UniMeasureSpec.limitSize : UniMeasureSpec.unspecified, heightSpec: verticalFittingPriority == UILayoutPriority.required ? UniMeasureSpec.limitSize : UniMeasureSpec.unspecified)
}
}
| mit | 3d6fd97c8a7d184b248d930e9ee3b0f8 | 31.361314 | 302 | 0.615541 | 5.396835 | false | false | false | false |
maxbritto/cours-ios11-swift4 | Maitriser/objectif_mapkit/Busbus/Busbus/BusStop.swift | 1 | 925 | //
// BusStop.swift
// Busbus
//
// Created by Maxime Britto on 21/03/2018.
// Copyright © 2018 Maxime Britto. All rights reserved.
//
import MapKit
import GEOSwift
class BusStop: MKPointAnnotation {
enum StopType : String {
case shelter = "ABRI"
case post = "POTEAU"
}
let stopType:StopType
init?(feature:Feature) {
guard let point = feature.geometries?.first as? Waypoint,
let properties = feature.properties,
let name = properties["nom"] as? String,
let lines = properties["lignes"] as? String,
let typeStr = properties["mobilier"] as? String,
let type = StopType(rawValue: typeStr)
else { return nil }
stopType = type
super.init()
self.title = name
self.subtitle = lines
self.coordinate = CLLocationCoordinate2DFromCoordinate(point.coordinate)
}
}
| apache-2.0 | 3c3443a39f5791d5b88bf40ceb60b171 | 26.176471 | 80 | 0.606061 | 4.180995 | false | false | false | false |
stoner30/Moya | Demo/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Event.swift | 10 | 3753 | //
// Event.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2015-01-16.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import Box
import Result
/// Represents a signal event.
///
/// Signals must conform to the grammar:
/// `Next* (Error | Completed | Interrupted)?`
public enum Event<T, E: ErrorType> {
/// A value provided by the signal.
case Next(Box<T>)
/// The signal terminated because of an error. No further events will be
/// received.
case Error(Box<E>)
/// The signal successfully terminated. No further events will be received.
case Completed
/// Event production on the signal has been interrupted. No further events
/// will be received.
case Interrupted
/// Whether this event indicates signal termination (i.e., that no further
/// events will be received).
public var isTerminating: Bool {
switch self {
case .Next:
return false
case .Error:
return true
case .Completed:
return true
case .Interrupted:
return true
}
}
/// Lifts the given function over the event's value.
public func map<U>(f: T -> U) -> Event<U, E> {
switch self {
case let .Next(value):
return .Next(value.map(f))
case let .Error(error):
return .Error(error)
case .Completed:
return .Completed
case .Interrupted:
return .Interrupted
}
}
/// Lifts the given function over the event's error.
public func mapError<F>(f: E -> F) -> Event<T, F> {
switch self {
case let .Next(value):
return .Next(value)
case let .Error(error):
return .Error(error.map(f))
case .Completed:
return .Completed
case .Interrupted:
return .Interrupted
}
}
/// Unwraps the contained `Next` value.
public var value: T? {
switch self {
case let .Next(value):
return value.value
default:
return nil
}
}
/// Unwraps the contained `Error` value.
public var error: E? {
switch self {
case let .Error(error):
return error.value
default:
return nil
}
}
/// Creates a sink that can receive events of this type, then invoke the
/// given handlers based on the kind of event received.
public static func sink(error: (E -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, next: (T -> ())? = nil) -> SinkOf<Event> {
return SinkOf { event in
switch event {
case let .Next(value):
next?(value.value)
case let .Error(err):
error?(err.value)
case .Completed:
completed?()
case .Interrupted:
interrupted?()
}
}
}
}
public func == <T: Equatable, E: Equatable> (lhs: Event<T, E>, rhs: Event<T, E>) -> Bool {
switch (lhs, rhs) {
case let (.Next(left), .Next(right)):
return left.value == right.value
case let (.Error(left), .Error(right)):
return left.value == right.value
case (.Completed, .Completed):
return true
case (.Interrupted, .Interrupted):
return true
default:
return false
}
}
extension Event: Printable {
public var description: String {
switch self {
case let .Next(value):
return "NEXT \(value.value)"
case let .Error(error):
return "ERROR \(error.value)"
case .Completed:
return "COMPLETED"
case .Interrupted:
return "INTERRUPTED"
}
}
}
/// Puts a `Next` event into the given sink.
public func sendNext<T, E>(sink: SinkOf<Event<T, E>>, value: T) {
sink.put(.Next(Box(value)))
}
/// Puts an `Error` event into the given sink.
public func sendError<T, E>(sink: SinkOf<Event<T, E>>, error: E) {
sink.put(.Error(Box(error)))
}
/// Puts a `Completed` event into the given sink.
public func sendCompleted<T, E>(sink: SinkOf<Event<T, E>>) {
sink.put(.Completed)
}
/// Puts a `Interrupted` event into the given sink.
public func sendInterrupted<T, E>(sink: SinkOf<Event<T, E>>) {
sink.put(.Interrupted)
}
| mit | e7a60d974119035f313b94aaef3370bc | 19.96648 | 154 | 0.650679 | 3.199488 | false | false | false | false |
PJayRushton/TeacherTools | TeacherTools/TTProducts.swift | 1 | 1880 | //
// TTProducts.swift
// TeacherTools
//
// Created by Parker Rushton on 12/2/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import Foundation
import Firebase
import Marshal
struct TTProducts {
static let proUpgrade = "com.PJayRushton.TeacherTools.ProUpgrade"
fileprivate static let productIdentifiers: Set<ProductIdentifier> = [TTProducts.proUpgrade]
static let store = IAPHelper(productIds: TTProducts.productIdentifiers)
}
func resourceNameForProductIdentifier(_ productIdentifier: String) -> String? {
return productIdentifier.components(separatedBy: ".").last
}
struct TTPurchase: JSONMarshaling {
var id: String
var productId: ProductIdentifier
var purchaseDate: Date
}
// MARK: - Unmarshaling
extension TTPurchase: Unmarshaling {
init(object: MarshaledObject) throws {
id = try object.value(for: Keys.id)
productId = try object.value(for: Keys.productId)
purchaseDate = try object.value(for: Keys.date)
}
}
// MARK: - Marshaling
extension TTPurchase {
func jsonObject() -> JSONObject {
var object = JSONObject()
object[Keys.id] = id
object[Keys.productId] = productId
object[Keys.date] = purchaseDate.iso8601String
return object
}
}
// MARK: - Equatable
extension TTPurchase: Equatable { }
func ==(lhs: TTPurchase, rhs: TTPurchase) -> Bool {
return lhs.productId == rhs.productId
}
// MARK: - Hashable
extension TTPurchase: Hashable {
var hashValue: Int {
return productId.hashValue
}
}
// MARK: - Identifiable {
extension TTPurchase: Identifiable {
var ref: DatabaseReference {
let userId = App.core.state.currentUser?.id
return FirebaseNetworkAccess.sharedInstance.usersRef.child(userId!).child("purchases").child(id)
}
}
| mit | cad21745b4f8e8d81943a60eec2c954f | 19.648352 | 104 | 0.67323 | 4.147903 | false | false | false | false |
svdo/swift-RichString | Pods/Quick/Sources/Quick/Example.swift | 11 | 4372 | import Foundation
#if canImport(Darwin)
// swiftlint:disable type_name
@objcMembers
public class _ExampleBase: NSObject {}
#else
public class _ExampleBase: NSObject {}
// swiftlint:enable type_name
#endif
/**
Examples, defined with the `it` function, use assertions to
demonstrate how code should behave. These are like "tests" in XCTest.
*/
final public class Example: _ExampleBase {
/**
A boolean indicating whether the example is a shared example;
i.e.: whether it is an example defined with `itBehavesLike`.
*/
public var isSharedExample = false
/**
The site at which the example is defined.
This must be set correctly in order for Xcode to highlight
the correct line in red when reporting a failure.
*/
public var callsite: Callsite
weak internal var group: ExampleGroup?
private let internalDescription: String
private let closure: () throws -> Void
private let flags: FilterFlags
internal init(description: String, callsite: Callsite, flags: FilterFlags, closure: @escaping () throws -> Void) {
self.internalDescription = description
self.closure = closure
self.callsite = callsite
self.flags = flags
}
public override var description: String {
return internalDescription
}
/**
The example name. A name is a concatenation of the name of
the example group the example belongs to, followed by the
description of the example itself.
The example name is used to generate a test method selector
to be displayed in Xcode's test navigator.
*/
public var name: String {
guard let groupName = group?.name else { return description }
return "\(groupName), \(description)"
}
/**
Executes the example closure, as well as all before and after
closures defined in the its surrounding example groups.
*/
public func run() {
let world = World.sharedWorld
if world.numberOfExamplesRun == 0 {
world.suiteHooks.executeBefores()
}
let exampleMetadata = ExampleMetadata(example: self, exampleIndex: world.numberOfExamplesRun)
world.currentExampleMetadata = exampleMetadata
defer {
world.currentExampleMetadata = nil
}
world.exampleHooks.executeBefores(exampleMetadata)
group!.phase = .beforesExecuting
for before in group!.befores {
before(exampleMetadata)
}
group!.phase = .beforesFinished
do {
try closure()
} catch {
let description = "Test \(name) threw unexpected error: \(error.localizedDescription)"
#if SWIFT_PACKAGE
let file = callsite.file.description
#else
let file = callsite.file
#endif
QuickSpec.current.recordFailure(
withDescription: description,
inFile: file,
atLine: Int(callsite.line),
expected: false
)
}
group!.phase = .aftersExecuting
for after in group!.afters {
after(exampleMetadata)
}
group!.phase = .aftersFinished
world.exampleHooks.executeAfters(exampleMetadata)
world.numberOfExamplesRun += 1
if !world.isRunningAdditionalSuites && world.numberOfExamplesRun >= world.cachedIncludedExampleCount {
world.suiteHooks.executeAfters()
}
}
/**
Evaluates the filter flags set on this example and on the example groups
this example belongs to. Flags set on the example are trumped by flags on
the example group it belongs to. Flags on inner example groups are trumped
by flags on outer example groups.
*/
internal var filterFlags: FilterFlags {
var aggregateFlags = flags
for (key, value) in group!.filterFlags {
aggregateFlags[key] = value
}
return aggregateFlags
}
}
extension Example {
/**
Returns a boolean indicating whether two Example objects are equal.
If two examples are defined at the exact same callsite, they must be equal.
*/
@nonobjc public static func == (lhs: Example, rhs: Example) -> Bool {
return lhs.callsite == rhs.callsite
}
}
| mit | 5373a9a94049563ea6b251f3c5f156da | 30.681159 | 118 | 0.634721 | 5.048499 | false | false | false | false |
Lickability/PinpointKit | PinpointKit/PinpointKit/Sources/Core/BlurAnnotationView.swift | 2 | 5502 | //
// BlurAnnotationView.swift
// Pinpoint
//
// Created by Caleb Davenport on 3/30/15.
// Copyright (c) 2015 Lickability. All rights reserved.
//
import UIKit
import GLKit
import CoreImage
/// The default blur annotation view.
open class BlurAnnotationView: AnnotationView, GLKViewDelegate {
// MARK: - Properties
private let EAGLContext: OpenGLES.EAGLContext?
private let GLKView: GLKit.GLKView?
private let CIContext: CoreImage.CIContext?
/// The corresponding annotation.
var annotation: BlurAnnotation? {
didSet {
setNeedsDisplay()
let layer = CAShapeLayer()
if let annotationFrame = annotationFrame {
layer.path = UIBezierPath(rect: annotationFrame).cgPath
}
GLKView?.layer.mask = layer
}
}
/// Whether to draw a border on the blur view.
var drawsBorder = false {
didSet {
if drawsBorder != oldValue {
setNeedsDisplay()
}
}
}
override var annotationFrame: CGRect? {
return annotation?.frame
}
private var touchTargetFrame: CGRect? {
guard let annotationFrame = annotationFrame else { return nil }
let size = frame.size
let maximumWidth = max(4.0, min(size.width, size.height) * 0.075)
let outsideStrokeWidth = min(maximumWidth, 14.0) * 1.5
return annotationFrame.inset(by: UIEdgeInsets(top: -outsideStrokeWidth, left: -outsideStrokeWidth, bottom: -outsideStrokeWidth, right: -outsideStrokeWidth))
}
// MARK: - Initializers
public convenience init() {
self.init(frame: CGRect.zero)
}
public override init(frame: CGRect) {
let bounds = CGRect(origin: CGPoint.zero, size: frame.size)
if let EAGLContext = OpenGLES.EAGLContext(api: .openGLES2) {
self.EAGLContext = EAGLContext
GLKView = GLKit.GLKView(frame: bounds, context: EAGLContext)
CIContext = CoreImage.CIContext(eaglContext: EAGLContext, options: [.useSoftwareRenderer: false])
} else {
EAGLContext = nil
GLKView = nil
CIContext = nil
}
super.init(frame: frame)
isOpaque = false
GLKView?.isUserInteractionEnabled = false
GLKView?.delegate = self
GLKView?.contentMode = .redraw
if let glkView = GLKView {
addSubview(glkView)
}
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UIView
override open func layoutSubviews() {
super.layoutSubviews()
GLKView?.frame = bounds
}
override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return touchTargetFrame?.contains(point) ?? false
}
override open func draw(_ rect: CGRect) {
super.draw(rect)
if drawsBorder {
guard let context = UIGraphicsGetCurrentContext() else { return }
tintColor?.withAlphaComponent(type(of: self).BorderAlpha).setStroke()
// Since this draws under the GLKView, and strokes extend both inside and outside, we have to double the intended width.
let strokeWidth: CGFloat = 1.0
context.setLineWidth(strokeWidth * 2.0)
let rect = annotationFrame ?? CGRect.zero
context.stroke(rect)
}
}
// MARK: - AnnotationView
override func setSecondControlPoint(_ point: CGPoint) {
guard let previousAnnotation = annotation else { return }
annotation = BlurAnnotation(startLocation: previousAnnotation.startLocation, endLocation: point, image: previousAnnotation.image)
}
override func move(controlPointsBy translationAmount: CGPoint) {
guard let previousAnnotation = annotation else { return }
let startLocation = CGPoint(x: previousAnnotation.startLocation.x + translationAmount.x, y: previousAnnotation.startLocation.y + translationAmount.y)
let endLocation = CGPoint(x: previousAnnotation.endLocation.x + translationAmount.x, y: previousAnnotation.endLocation.y + translationAmount.y)
annotation = BlurAnnotation(startLocation: startLocation, endLocation: endLocation, image: previousAnnotation.image)
}
override func scale(controlPointsBy scaleFactor: CGFloat) {
guard let previousAnnotation = annotation else { return }
let startLocation = previousAnnotation.scaledPoint(previousAnnotation.startLocation, scale: scaleFactor)
let endLocation = previousAnnotation.scaledPoint(previousAnnotation.endLocation, scale: scaleFactor)
annotation = BlurAnnotation(startLocation: startLocation, endLocation: endLocation, image: previousAnnotation.image)
}
// MARK: - GLKViewDelegate
open func glkView(_ view: GLKit.GLKView, drawIn rect: CGRect) {
glClearColor(0, 0, 0, 0)
glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
guard let CIContext = self.CIContext else { return }
guard let image = annotation?.blurredImage else { return }
let drawableRect = CGRect(x: 0, y: 0, width: view.drawableWidth, height: view.drawableHeight)
CIContext.draw(image, in: drawableRect, from: image.extent)
}
}
| mit | 152f3e7ea73c8f1e38ee5af259de16ca | 33.173913 | 164 | 0.635224 | 4.930108 | false | false | false | false |
gregomni/swift | test/Constraints/type_sequence.swift | 5 | 5004 | // RUN: %target-typecheck-verify-swift -enable-experimental-variadic-generics
struct TupleStruct<First, @_typeSequence Rest> {
var first: First
var rest: (Rest...)
}
func debugPrint<@_typeSequence T>(_ items: T...)
where T: CustomDebugStringConvertible
{
/*for (item: T) in items {
stdout.write(item.debugDescription)
}*/
}
func max<@_typeSequence T>(_ values: T...) -> T?
where T: Comparable
{
return nil
}
func min<@_typeSequence T: Comparable>(_ values: T...) -> T? {
return nil
}
func badParameter<T>(_ : @_typeSequence T) {} // expected-error {{attribute does not apply to type}}
func directAliases() {
typealias Tuple<@_typeSequence Ts> = (Ts...)
typealias Many<T, U, V, @_typeSequence Ws> = Tuple<T, U, V, Ws>
let _: Many<Int, String, Double, Void, Void, Void, Void> = 42 // expected-error {{cannot convert value of type 'Int' to specified type}}
}
func bindPrefix() {
struct Bind<Prefix, @_typeSequence U> {}
typealias TooFew0 = Bind<> // expected-error {{expected type}}
typealias TooFew1 = Bind<String> // OK
typealias TooFew2 = Bind<String, String> // OK
typealias JustRight = Bind<String, String, String> // OK
typealias Oversaturated = Bind<String, String, String, String, String, String, String, String> // OK
}
func bindSuffix() {
struct Bind<@_typeSequence U, Suffix> {}
typealias TooFew0 = Bind<> // expected-error {{expected type}}
typealias TooFew1 = Bind<String> // OK
typealias TooFew2 = Bind<String, String> // OK
typealias JustRight = Bind<String, String, String> // OK
typealias Oversaturated = Bind<String, String, String, String, String, String, String, String> // OK
}
func bindPrefixAndSuffix() {
struct Bind<Prefix, @_typeSequence U, Suffix> {} // expected-note {{generic type 'Bind' declared here}}
typealias TooFew0 = Bind<> // expected-error {{expected type}}
typealias TooFew1 = Bind<String> // expected-error {{generic type 'Bind' specialized with too few type parameters (got 1, but expected at least 2)}}
typealias TooFew2 = Bind<String, String> // OK
typealias JustRight = Bind<String, String, String> // OK
typealias Oversaturated = Bind<String, String, String, String, String, String, String, String> // OK
}
func invalidPacks() {
func monovariadic1() -> (String...) {} // expected-error {{cannot create expansion with non-variadic type 'String'}}
func monovariadic2<T>() -> (T...) {} // expected-error 2 {{cannot create expansion with non-variadic type 'T'}}
func monovariadic3<T, U>() -> (T, U...) {} // expected-error {{cannot create a variadic tuple}}
}
func call() {
func multipleParameters<@_typeSequence T>(xs: T..., ys: T...) -> (T...) { return xs }
// expected-note@-1 {{in call to function 'multipleParameters(xs:ys:)'}}
_ = multipleParameters()
// expected-error@-1 2 {{generic parameter 'T' could not be inferred}}
let x: (String) = multipleParameters(xs: "", ys: "")
let (one, two) = multipleParameters(xs: "", 5.0, ys: "", 5.0)
multipleParameters(xs: "", 5.0, ys: 5.0, "") // expected-error {{type of expression is ambiguous without more context}}
func multipleSequences<@_typeSequence T, @_typeSequence U>(xs: T..., ys: U...) -> (T...) { return ys }
// expected-note@-1 {{in call to function 'multipleSequences(xs:ys:)'}}
// expected-error@-2 {{cannot convert return expression of type 'U' to return type 'T'}}
_ = multipleSequences()
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// expected-error@-2 {{generic parameter 'U' could not be inferred}}
_ = multipleSequences(xs: "", ys: "")
_ = multipleSequences(xs: "", 5.0, ys: 5.0, "")
}
func contextualTyping() {
func firsts<@_typeSequence T>(_ seqs: [T]...) -> (T?...) {
fatalError()
}
let (_, _): (Int?, String?) = firsts([42], [""]) // OK
let (_, _): (String?, String?) = firsts([42], [""]) // expected-error {{cannot convert value of type '(Int?, String?)' to specified type '(String?, String?)'}}
let (_, _): ([Int], String?) = firsts([42], [""]) // expected-error {{cannot convert value of type '(Int?, String?)' to specified type '([Int], String?)'}}
let (_, _, _): (String?, String?, Int) = firsts([42], [""]) // expected-error {{'(Int?, String?)' is not convertible to '(String?, String?, Int)', tuples have a different number of elements}}
func dependent<@_typeSequence T>(_ seqs: Array<T>...) -> (Array<T>.Element?...) {
fatalError()
}
let (_, _): (Int?, String?) = dependent([42], [""]) // OK
let (_, _): (String?, String?) = dependent([42], [""]) // expected-error {{cannot convert value of type '(Int?, String?)' to specified type '(String?, String?)'}}
let (_, _): ([Int], String?) = dependent([42], [""]) // expected-error {{cannot convert value of type '(Int?, String?)' to specified type '([Int], String?)'}}
let (_, _, _): (String?, String?, Int) = dependent([42], [""]) // expected-error {{'(Int?, String?)' is not convertible to '(String?, String?, Int)', tuples have a different number of elements}}
}
| apache-2.0 | 11f073a59596cdea16477674280c18b1 | 44.490909 | 196 | 0.641087 | 3.665934 | false | false | false | false |
Scorocode/scorocode-SDK-swift | todolist/LoginVC.swift | 1 | 3487 | //
// LoginVC.swift
// todolist
//
// Created by Alexey Kuznetsov on 30/10/2016.
// Copyright © 2016 ProfIT. All rights reserved.
//
import UIKit
class LoginVC : UIViewController {
//Mark: outlets
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var textFieldPassword: UITextField!
@IBOutlet weak var buttonRegister: UIButton!
@IBOutlet weak var textFieldEmail: UITextField!
@IBOutlet weak var buttonLogin: UIButton!
@IBOutlet weak var constraintLabelEmailTop: NSLayoutConstraint!
//Mark: vars
let user = User.sharedInstance
//Mark: override VC functions
override func viewDidLoad() {
super.viewDidLoad()
// keyboard show-hide, resize window.
setupViewResizerOnKeyboardShown()
hideKeyboardWhenTappedAround()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
setupUI()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if user.getCredentials() {
textFieldPassword.text = user.password
textFieldEmail.text = user.email
login(email: user.email, password: user.password)
}
}
//MARK: setupUI
func setupUI() {
textFieldEmail.text = ""
textFieldPassword.text = ""
//round buttons
buttonLogin.layer.cornerRadius = 5.0;
buttonLogin.layer.masksToBounds = true;
buttonRegister.layer.cornerRadius = 5.0;
buttonRegister.layer.masksToBounds = true;
}
func login(email: String, password: String) {
let scUser = SCUser()
scUser.login(email, password: password) {
success, error, result in
if success {
self.user.saveCredentials(email: email, password: password)
self.user.parseUser(userDictionary: result?["user"] as? [String: Any])
self.user.saveTokenToServer()
self.showAlert(title: "Вход выполнен", message: "Добро пожаловать \(self.user.name) !") {
let taskListVC = self.storyboard?.instantiateViewController(withIdentifier: "TaskListVC") as! TaskListVC
self.navigationController?.show(taskListVC, sender: self)
}
} else {
self.showAlert(title: "Вход не выполнен!", message: "проверьте email и пароль.", completion: nil)
}
}
}
//MARK: button actions
@IBAction func buttonLoginTapped(_ sender: AnyObject) {
guard let email = textFieldEmail.text, email != "", let password = textFieldPassword.text, password != "" else {
showAlert(title: "Вход не выполнен!", message: "проверьте email и пароль.", completion: nil)
return
}
login(email: email, password: password)
}
@IBAction func buttonRegisterTapped(_ sender: Any) {
let registerVC = storyboard?.instantiateViewController(withIdentifier: "RegisterVC") as! RegisterVC
navigationController?.pushViewController(registerVC, animated: true)
}
}
| mit | 6ada4973b90add82677908efd4867ef6 | 35.945652 | 124 | 0.638129 | 4.773876 | false | false | false | false |
rwash8347/desktop-apod | DesktopAPOD/DesktopAPOD/ErrorView.swift | 1 | 968 | //
// ErrorView.swift
// DesktopAPOD
//
// Created by Richard Ash on 5/15/17.
// Copyright © 2017 Richard. All rights reserved.
//
import Cocoa
class ErrorView: NSView {
// MARK: - IBOutlet Properties
@IBOutlet weak var errorLabel: NSTextField!
// MARK: - Overridden Methods
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
layer?.opacity = 1.0
layer?.cornerRadius = 5.0
layer?.backgroundColor = NSColor.red.cgColor
}
// MARK: - Methods
func animate(with error: APIClient.APIError, completion: @escaping () -> Void) {
isHidden = false
switch error {
case .noImage:
errorLabel.stringValue = "Looks like there's a video today...\nCheck again tomorrow for the updated APOD"
default:
errorLabel.stringValue = "Can't refresh image 😨"
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
self.isHidden = true
completion()
}
}
}
| mit | 7aa2001e986ce06fb592a41bfdf9d1a6 | 21.418605 | 111 | 0.644191 | 4.033473 | false | false | false | false |
AnthonyMDev/QueryGenie | QueryGenie/Realm/Results+ResultsProtocol.swift | 1 | 1219 | //
// Results+ResultsProtocol.swift
//
// Created by Anthony Miller on 12/29/16.
//
import Foundation
import ObjectiveC
import RealmSwift
private var _sortDescriptorsKey = "QueryGenie.sortDescriptors"
extension Results: ResultsProtocol {
public func first() -> T? {
return self.first
}
/*
* MARK: - GenericQueryable
*/
public final func objects() -> AnyCollection<Element> {
return AnyCollection(self)
}
public func sorted(by keyPath: String, ascending: Bool) -> Results<T> {
let newSort = SortDescriptor(keyPath: keyPath, ascending: ascending)
var sortDescriptors: [SortDescriptor] = self.sortDescriptors ?? []
sortDescriptors.append(newSort)
let newResults = self.sorted(by: sortDescriptors)
newResults.sortDescriptors = sortDescriptors
return newResults
}
private var sortDescriptors: [SortDescriptor]? {
get {
return objc_getAssociatedObject(self, &_sortDescriptorsKey) as? [SortDescriptor]
}
set {
objc_setAssociatedObject(self, &_sortDescriptorsKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
}
| mit | ad154f70e658ca2fc68505233f1d7eff | 24.395833 | 100 | 0.634947 | 4.856574 | false | false | false | false |
ifels/swiftDemo | RealmDemo/RealmDemo/AppDelegate.swift | 1 | 4589 | //
// AppDelegate.swift
// RealmDemo
//
// Created by 聂鑫鑫 on 16/11/14.
// Copyright © 2016年 ifels. 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: "RealmDemo")
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)")
}
}
}
}
| apache-2.0 | d6639ed8e48b93cf36fe6a7abe27f833 | 48.247312 | 285 | 0.685371 | 5.819568 | false | false | false | false |
buyiyang/iosstar | iOSStar/Scenes/Discover/Controllers/VoiceQuestionVC.swift | 3 | 8440 | //
// VoiceQuestionVC.swift
// iOSStar
//
// Created by mu on 2017/8/16.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import SVProgressHUD
class VoiceQuestionCell: OEZTableViewCell{
@IBOutlet weak var iconImage: UIImageView!
@IBOutlet weak var voiceImg: UIImageView!
@IBOutlet weak var voiceBtn: UIButton!
@IBOutlet weak var voiceIcon: UIImageView!
@IBOutlet weak var voiceCountLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var title: UILabel!
var isplay = false
@IBOutlet weak var nameLabel: UILabel!
override func awakeFromNib() {
self.selectionStyle = .none
iconImage.image = UIImage.imageWith("\u{e655}", fontSize: CGSize.init(width: 26, height: 26), fontColor: UIColor.init(rgbHex: AppConst.ColorKey.main.rawValue))
}
override func update(_ data: Any!) {
if let response = data as? UserAskDetailList{
contentLabel.text = response.uask
iconImage.kf.setImage(with: URL(string : response.headUrl), placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil)
nameLabel.text = response.nickName
timeLabel.text = Date.yt_convertDateStrWithTimestempWithSecond(Int(response.answer_t), format: "YYYY-MM-dd")
if response.purchased == 1{
let attr = NSMutableAttributedString.init(string: "点击播放")
title.attributedText = attr
}
else if response.purchased == 0{
let attr = NSMutableAttributedString.init(string: "花费\((response.c_type + 1) * 15)秒偷听")
attr.addAttributes([NSForegroundColorAttributeName: UIColor.init(rgbHex: 0xfb9938)], range: NSRange.init(location: 2, length: "\((response.c_type + 1) * 15)".length()))
title.attributedText = attr
}
if !response.isplay{
voiceImg.image = UIImage(named: String.init(format: "listion"))
}
voiceBtn.addTarget(self, action: #selector(dopeep), for: .touchUpInside)
voiceCountLabel.text = "听过\(response.s_total)"
}
}
@IBAction func dopeep(_ sender: Any) {
didSelectRowAction(3, data: nil)
}
}
class VoiceQuestionVC: BasePageListTableViewController ,OEZTableViewDelegate {
var starModel: StarSortListModel = StarSortListModel()
var voiceimg: UIImageView!
var selectRow = 99999999
var height = UIScreen.main.bounds.size.height - 64
override func viewDidLoad() {
super.viewDidLoad()
title = starModel.name
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let model = dataSource?[indexPath.row] as? UserAskDetailList{
return model.cellHeight
}
return 210
}
func tableView(_ tableView: UITableView!, rowAt indexPath: IndexPath!, didAction action: Int, data: Any!){
if let model = self.dataSource?[indexPath.row] as? UserAskDetailList{
if PLPlayerHelper.shared().player.isPlaying{
PLPlayerHelper.shared().player.stop()
}
if voiceimg != nil{
self.voiceimg.image = UIImage.init(named: String.init(format: "listion"))
}
if let cell = tableView.cellForRow(at: indexPath) as? VoiceQuestionCell{
voiceimg = cell.voiceImg
}
selectRow = indexPath.row
if model.purchased == 1{
model.isplay = true
doplay(model)
}else{
let request = PeepVideoOrvoice()
request.qid = Int(model.id)
request.starcode = starModel.symbol
request.cType = model.c_type
request.askUid = model.uid
AppAPIHelper.discoverAPI().peepAnswer(requestModel: request, complete: { (result) in
if let response = result as? ResultModel{
if response.result == 0{
model.purchased = 1
model.isplay = true
tableView.reloadRows(at: [indexPath], with: .none)
if let cell = tableView.cellForRow(at: indexPath) as? VoiceQuestionCell{
self.voiceimg = cell.voiceImg
}
self.doplay(model)
}else{
SVProgressHUD.showWainningMessage(WainningMessage: "您持有的时间不足", ForDuration: 1, completion: nil)
}
}
}, error: { (error) in
self.didRequestError(error)
})
}
}
}
func rightItemTapped(_ sender: Any) {
if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: VoiceHistoryVC.className()) as? VoiceHistoryVC{
vc.starModel = starModel
_ = self.navigationController?.pushViewController(vc, animated: true)
}
}
override func didRequest(_ pageIndex: Int) {
let model = StarAskRequestModel()
model.pos = pageIndex == 1 ? 1 : dataSource?.count ?? 0
model.starcode = starModel.symbol
model.aType = 2
model.pType = 1
AppAPIHelper.discoverAPI().staraskQuestion(requestModel: model, complete: { [weak self](result) in
if let response = result as? UserAskList {
for model in response.circle_list!{
model.calculateCellHeight()
}
self?.didRequestComplete(response.circle_list as AnyObject )
}
}) { (error) in
self.didRequestComplete(nil)
}
}
override func tableView(_ tableView: UITableView, cellIdentifierForRowAtIndexPath indexPath: IndexPath) -> String? {
return VoiceQuestionCell.className()
}
}
extension VoiceQuestionVC{
func doplay(_ model : UserAskDetailList){
let url = URL(string: ShareDataModel.share().qiniuHeader + model.sanswer)
PLPlayerHelper.shared().player.play(with: url)
PLPlayerHelper.shared().play(isRecord: false)
PLPlayerHelper.shared().player.play()
PLPlayerHelper.shared().resultBlock = { [weak self] (result) in
if let status = result as? PLPlayerStatus{
if status == .statusStopped{
if let arr = self?.dataSource?[0] as? Array<AnyObject>{
if let model = arr[(self?.selectRow)!] as? UserAskDetailList{
model.isplay = false
}
}
PLPlayerHelper.shared().doChanggeStatus(4)
self?.voiceimg.image = UIImage.init(named: String.init(format: "listion"))
}
if status == .statusPaused{
if let arr = self?.dataSource?[0] as? Array<AnyObject>{
if let model = arr[(self?.selectRow)!] as? UserAskDetailList{
model.isplay = false
}
}
PLPlayerHelper.shared().doChanggeStatus(4)
self?.voiceimg.image = UIImage.init(named: String.init(format: "listion"))
}
if status == .statusPreparing{
PLPlayerHelper.shared().doChanggeStatus(0)
PLPlayerHelper.shared().resultCountDown = {[weak self] (result) in
if let response = result as? Int{
self?.voiceimg.image = UIImage.init(named: String.init(format: "voice_%d",response))
}
}
}
if status == .statusError{
PLPlayerHelper.shared().doChanggeStatus(4)
self?.voiceimg.image = UIImage.init(named: String.init(format: "listion"))
}
}
}
}
}
| gpl-3.0 | d3ea2dae7f73ef799d960707ab36c3fc | 41.634518 | 184 | 0.548518 | 4.88598 | false | false | false | false |
WeHUD/app | weHub-ios/Gzone_App/Gzone_App/WBComment.swift | 1 | 7634 | //
// WBComment.swift
// Gzone_App
//
// Created by Lyes Atek on 19/06/2017.
// Copyright © 2017 Tracy Sablon. All rights reserved.
//
import Foundation
class WBComment: NSObject {
func addComment(userId : String,postId : String,text : String,accessToken : String,_ completion: @escaping (_ result: Bool) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments?access_token="+accessToken
let url: NSURL = NSURL(string: urlPath)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request.setValue("application/json", forHTTPHeaderField: "Content-type")
let params = ["userId":userId,"postId" : postId,"text" : text]
let options : JSONSerialization.WritingOptions = JSONSerialization.WritingOptions();
do{
let requestBody = try JSONSerialization.data(withJSONObject: params, options: options)
request.httpBody = requestBody
let session = URLSession.shared
_ = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
completion( false)
}
completion(true)
}).resume()
}
catch{
print("error")
completion(false)
}
}
func deleteComment(commentId : String,accessToken : String, _ completion: @escaping (_ result: Void) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments/"+commentId+"?access_token="+accessToken
let url: URL = URL(string: urlPath)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "DELETE"
let session = URLSession.shared
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
})
task.resume()
}
func getCommentByUserId(userId : String,accessToken : String,_ completion: @escaping (_ result: [Comment]) -> Void){
var comments : [Comment] = []
let urlPath :String = "https://g-zone.herokuapp.com/comments/user/"+userId+"?access_token="+accessToken
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
print(jsonResult)
comments = self.JSONToCommentArray(jsonResult)
completion(comments)
}
catch{
print("error")
}
})
task.resume()
}
func getCommentByPostId(postId : String,accessToken : String ,offset : String,_ completion: @escaping (_ result: [Comment]) -> Void){
var comments : [Comment] = []
let urlPath :String = "https://g-zone.herokuapp.com/comments/post/"+postId+"?access_token="+accessToken+"&offset="+offset
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
print(jsonResult)
comments = self.JSONToCommentArray(jsonResult)
completion(comments)
}
catch{
print("error")
}
})
task.resume()
}
func getCommentById(commentId : String,accessToken : String,_ completion: @escaping (_ result: Comment) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments/"+commentId+"&access_token="+accessToken
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let comment : Comment = self.JSONToComment(json: jsonResult)!
completion(comment)
}
catch{
print("error")
}
})
task.resume()
}
func JSONToCommentArray(_ jsonEvents : NSArray) -> [Comment]{
print (jsonEvents)
var commentsTab : [Comment] = []
for object in jsonEvents{
let _id = (object as AnyObject).object(forKey: "_id") as! String
let userId = (object as AnyObject).object(forKey: "userId") as! String
let text = (object as AnyObject).object(forKey: "text") as! String
var video : String
if((object as AnyObject).object(forKey: "videos") != nil){
video = (object as AnyObject).object(forKey: "video") as! String
}else{
video = ""
}
let datetimeCreated = (object as AnyObject).object(forKey: "datetimeCreated") as! String
let comment : Comment = Comment(_id: _id, userId: userId, text: text, video: video, datetimeCreated: datetimeCreated)
commentsTab.append(comment);
}
return commentsTab;
}
func JSONToComment(json : NSDictionary) ->Comment?{
let _id = json.object(forKey: "_id") as! String
let userId = json.object(forKey: "userId") as! String
let text = json.object(forKey: "text") as! String
var video : String
if(json.object(forKey: "videos") != nil){
video = json.object(forKey: "video") as! String
}else{
video = ""
}
let datetimeCreated = json.object(forKey: "datetimeCreated") as! String
let comment : Comment = Comment(_id: _id, userId: userId, text: text, video: video, datetimeCreated: datetimeCreated)
return comment
}
}
| bsd-3-clause | f1976166db4ad8c6cbc54ad1b452fde2 | 37.550505 | 156 | 0.555221 | 5.005246 | false | false | false | false |
clappr/clappr-ios | Tests/Clappr_Tests/Classes/Plugin/Core/MediaControl/MediaControlTests.swift | 1 | 32821 | import Quick
import Nimble
@testable import Clappr
class MediaControlTests: QuickSpec {
override func spec() {
describe(".MediaControl") {
var coreStub: CoreStub!
var mediaControl: MediaControl!
beforeEach {
coreStub = CoreStub()
mediaControl = MediaControl(context: coreStub)
}
describe("pluginName") {
it("returns the pluginName") {
expect(mediaControl.pluginName).to(equal("MediaControl"))
}
}
describe("#animationDuration") {
it("is 0.3 seconds") {
expect(ClapprAnimationDuration.mediaControlHide).to(equal(0.3))
expect(ClapprAnimationDuration.mediaControlShow).to(equal(0.3))
}
}
describe("#shortTimeToHideMediaControl") {
it("is 0.3 seconds") {
expect(mediaControl.shortTimeToHideMediaControl).to(equal(0.3))
}
}
describe("#longTimeToHideMediaControl") {
it("is 3 seconds") {
expect(mediaControl.longTimeToHideMediaControl).to(equal(3))
}
}
describe("#view") {
it("has 1 gesture recognizer") {
mediaControl.render()
expect(mediaControl.view.gestureRecognizers?.count).to(equal(1))
}
}
describe("#hideAndStopTimer") {
it("hides the mediacontrol and stop timer") {
mediaControl.render()
mediaControl.hideAndStopTimer()
expect(mediaControl.hideControlsTimer?.isValid).to(beNil())
expect(mediaControl.view.isHidden).to(beTrue())
}
}
describe("#render") {
it("starts hidden") {
mediaControl.render()
expect(mediaControl.view.isHidden).to(beTrue())
}
it("has clear background") {
mediaControl.render()
expect(mediaControl.view.backgroundColor).to(equal(UIColor.clear))
}
it("has constrastView with black background with 60% of opacity") {
mediaControl.render()
expect(mediaControl.mediaControlView.contrastView.backgroundColor).to(equal(UIColor.clapprBlack60Color()))
}
it("fills the superview") {
let frame = CGRect(x: 0, y: 0, width: 100, height: 100)
let superview = UIView(frame: frame)
superview.addSubview(mediaControl.view)
mediaControl.render()
expect(superview.constraints.count).to(equal(4))
}
it("inflates the MediaControl xib in the view") {
mediaControl.render()
expect(mediaControl.mediaControlView).to(beAKindOf(MediaControlView.self))
expect(mediaControl.view.subviews).to(contain(mediaControl.mediaControlView))
}
}
describe("options") {
context("when kMediaControlAlwaysVisible is true") {
it("keeps itself visible without timer") {
let options: Options = [kMediaControlAlwaysVisible: true]
coreStub.options = options
let mediaControl = MediaControl(context: coreStub)
mediaControl.render()
coreStub.activePlayback?.trigger(.playing)
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beNil())
expect(mediaControl.view.isHidden).toEventually(beFalse())
}
}
it("has the same options as the Core") {
let options: Options = ["foo": "bar"]
coreStub.options = options
let mediaControl = MediaControl(context: coreStub)
expect(mediaControl.options).toNot(beNil())
expect(mediaControl.options?["foo"] as? String).to(equal("bar"))
}
}
describe("Events") {
beforeEach {
mediaControl.showDuration = 0.1
mediaControl.hideDuration = 0.1
mediaControl.shortTimeToHideMediaControl = 0.1
mediaControl.longTimeToHideMediaControl = 0.1
mediaControl.render()
}
context("requestPadding") {
it("applies padding") {
mediaControl.render()
coreStub.trigger(.requestPadding, userInfo: ["padding": CGFloat(32)])
expect(mediaControl.mediaControlView.bottomPadding?.constant).toEventually(equal(32.0))
}
}
context("playing") {
context("after a pause") {
it("hides itself after some time and stop timer") {
showMediaControl()
coreStub.activePlayback?.trigger(.didPause)
coreStub.activePlayback?.trigger(.playing)
expect(mediaControl.view.isHidden).toEventually(beTrue())
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
context("after a complete") {
it("hides itself after some time and stop timer") {
showMediaControl()
coreStub.activePlayback?.trigger(.didComplete)
coreStub.activePlayback?.trigger(.playing)
expect(mediaControl.view.isHidden).toEventually(beTrue())
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
}
context("didComplete") {
it("shows itself") {
hideMediaControl()
coreStub.activePlayback?.trigger(.didComplete)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
}
}
context("didTappedCore") {
it("shows itself and start the timer to hide") {
hideMediaControl()
coreStub.trigger(InternalEvent.didTappedCore.rawValue)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beTrue())
}
}
context("didPause") {
it("keeps itself on the screen and visible") {
mediaControl.hideControlsTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in return })
showMediaControl()
coreStub.activePlayback?.trigger(.didPause)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
context("willBeginScrubbing") {
it("keeps itself on the screen and visible") {
mediaControl.hideControlsTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in return })
showMediaControl()
coreStub.trigger(InternalEvent.willBeginScrubbing.rawValue)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
context("didFinishScrubbing") {
beforeEach {
mediaControl.hideControlsTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in return })
showMediaControl()
}
context("and the playback is playing") {
it("hides itself after some time") {
coreStub.playbackMock?.set(state: .playing)
coreStub.trigger(InternalEvent.didFinishScrubbing.rawValue)
expect(mediaControl.view.isHidden).toEventually(beTrue())
expect(mediaControl.view.alpha).toEventually(equal(0))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
context("and the playback is paused") {
it("keeps itself on the screen and visible") {
coreStub.playbackMock?.set(state: .paused)
coreStub.activePlayback?.trigger(.didPause)
coreStub.trigger(InternalEvent.didFinishScrubbing.rawValue)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
context("and the playback is idle") {
it("keeps itself on the screen and visible") {
coreStub.playbackMock?.set(state: .idle)
coreStub.activePlayback?.trigger(.didComplete)
coreStub.trigger(InternalEvent.didFinishScrubbing.rawValue)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
}
context("didEnterFullscreen") {
beforeEach {
mediaControl.hideControlsTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in return })
showMediaControl()
}
context("and the playback is playing") {
it("hides itself after some time") {
coreStub.playbackMock?.set(state: .playing)
coreStub.trigger(.didEnterFullscreen)
expect(mediaControl.view.isHidden).toEventually(beTrue())
expect(mediaControl.view.alpha).toEventually(equal(0))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
context("and the playback is paused") {
it("keeps itself on the screen and visible") {
coreStub.playbackMock?.set(state: .paused)
coreStub.activePlayback?.trigger(.didPause)
coreStub.trigger(.didEnterFullscreen)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
context("and the playback is idle") {
it("keeps itself on the screen and visible") {
coreStub.playbackMock?.set(state: .idle)
coreStub.activePlayback?.trigger(.didComplete)
coreStub.trigger(.didEnterFullscreen)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
}
context("didExitFullscreen") {
beforeEach {
mediaControl.hideControlsTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in return })
showMediaControl()
}
context("and the playback is playing") {
it("hides itself after some time") {
coreStub.playbackMock?.set(state: .playing)
coreStub.trigger(.didExitFullscreen)
expect(mediaControl.view.isHidden).toEventually(beTrue())
expect(mediaControl.view.alpha).toEventually(equal(0))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
context("and the playback is paused") {
it("keeps itself visible") {
coreStub.playbackMock?.set(state: .paused)
coreStub.activePlayback?.trigger(.didPause)
coreStub.trigger(.didExitFullscreen)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
context("and the playback is idle") {
it("keeps itself on the screen and visible") {
coreStub.playbackMock?.set(state: .idle)
coreStub.activePlayback?.trigger(.didComplete)
coreStub.trigger(.didExitFullscreen)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
}
context("disableMediaControl") {
it("hides itself immediately") {
showMediaControl()
coreStub.activeContainer?.trigger(.disableMediaControl)
expect(mediaControl.view.isHidden).toEventually(beTrue())
expect(mediaControl.view.alpha).toEventually(equal(0))
}
}
context("enableMediaControl") {
it("shows itself immediately") {
hideMediaControl()
coreStub.activeContainer?.trigger(.enableMediaControl)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
}
}
context("didDragDrawer") {
it("changes its alpha") {
showMediaControl()
let info = ["alpha": CGFloat(0.5)]
coreStub.trigger(InternalEvent.didDragDrawer.rawValue, userInfo: info)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(0.5))
}
}
context("didShowDrawerPlugin") {
it("hides itself") {
showMediaControl()
coreStub.trigger(.didShowDrawerPlugin)
expect(mediaControl.view.isHidden).toEventually(beTrue())
expect(mediaControl.view.alpha).toEventually(equal(0))
}
}
context("didHideDrawerPlugin") {
beforeEach {
mediaControl.hideControlsTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in return })
showMediaControl()
}
context("and the playback is playing") {
it("shows itself and starts the timer to hide") {
coreStub.playbackMock?.set(state: .playing)
coreStub.trigger(.didHideDrawerPlugin)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beTrue())
}
}
context("and the playback is paused") {
it("shows itself and keeps visible") {
coreStub.playbackMock?.set(state: .paused)
coreStub.trigger(.didHideDrawerPlugin)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
context("and the playback is idle") {
it("shows itself and keeps visible") {
coreStub.playbackMock?.set(state: .idle)
coreStub.trigger(.didHideDrawerPlugin)
expect(mediaControl.view.isHidden).toEventually(beFalse())
expect(mediaControl.view.alpha).toEventually(equal(1))
expect(mediaControl.hideControlsTimer?.isValid).toEventually(beFalse())
}
}
}
func hideMediaControl() {
mediaControl.view.isHidden = true
mediaControl.view.alpha = 0
}
func showMediaControl() {
mediaControl.view.isHidden = false
mediaControl.view.alpha = 1
}
}
describe("show") {
it("triggers willShowMediaControl before showing the view") {
var eventTriggered = false
var viewWasVisible = false
mediaControl.render()
coreStub.on(Event.willShowMediaControl.rawValue) { _ in
eventTriggered = true
viewWasVisible = !mediaControl.view.isHidden
}
mediaControl.show()
expect(eventTriggered).toEventually(beTrue())
expect(viewWasVisible).to(beFalse())
}
it("triggers didShowMediaControl after showing the view") {
var eventTriggered = false
mediaControl.view.isHidden = true
coreStub.on(Event.didShowMediaControl.rawValue) { _ in
eventTriggered = true
}
mediaControl.show()
expect(eventTriggered).toEventually(beTrue())
expect(mediaControl.view.isHidden).to(beFalse())
}
}
describe("hide") {
it("triggers willHideMediaControl before hiding the view") {
var eventTriggered = false
var viewWasVisible = false
mediaControl.view.isHidden = false
coreStub.on(Event.willHideMediaControl.rawValue) { _ in
eventTriggered = true
viewWasVisible = !mediaControl.view.isHidden
}
mediaControl.hide()
expect(eventTriggered).toEventually(beTrue())
expect(viewWasVisible).to(beTrue())
}
it("triggers didHideMediaControl after showing the view") {
var eventTriggered = false
coreStub.on(Event.didHideMediaControl.rawValue) { _ in
eventTriggered = true
}
mediaControl.hide()
expect(eventTriggered).toEventually(beTrue())
expect(mediaControl.view.isHidden).to(beTrue())
}
}
describe("renderElements") {
var elements: [MediaControl.Element]!
var mediaControlViewMock: MediaControlViewMock!
beforeEach {
elements = [MediaControlElementMock(context: coreStub)]
mediaControlViewMock = MediaControlViewMock()
MediaControlElementMock.reset()
}
context("for any element configuration") {
it("adds the element view as subview of MediaControlView") {
let mediaControl = MediaControl(context: coreStub)
mediaControl.mediaControlView = mediaControlViewMock
mediaControl.render()
mediaControl.render(elements)
expect(mediaControlViewMock.didCallAddSubview).to(beTrue())
}
it("passes the element's view") {
mediaControl.mediaControlView = mediaControlViewMock
mediaControl.render()
mediaControl.render(elements)
expect(mediaControlViewMock.didCallAddSubviewWithView).to(equal(elements.first?.view))
}
it("passes the element's panel") {
MediaControlElementMock._panel = .center
mediaControl.mediaControlView = mediaControlViewMock
mediaControl.render()
mediaControl.render(elements)
expect(mediaControlViewMock.didCallAddSubviewWithPanel).to(equal(MediaControlPanel.center))
}
it("passes the element's position") {
MediaControlElementMock._position = .left
mediaControl.mediaControlView = mediaControlViewMock
mediaControl.render()
mediaControl.render(elements)
expect(mediaControlViewMock.didCallAddSubviewWithPosition).to(equal(MediaControlPosition.left))
}
it("calls the element's render method") {
MediaControlElementMock._panel = .top
mediaControl.render()
mediaControl.render(elements)
expect(MediaControlElementMock.didCallRender).to(beTrue())
}
it("protects the main thread when element crashes in render") {
MediaControlElementMock.crashOnRender = true
mediaControl.render()
mediaControl.render(elements)
expect(mediaControl).to(beAKindOf(MediaControl.self))
}
}
context("when kMediaControlElementsOrder is passed") {
it("renders the elements following the kMediaControlElementsOrder with all elements specified in the option") {
let core = Core()
core.options[kMediaControlElementsOrder] = ["FullscreenButton", "TimeIndicatorElementMock", "SecondElement", "FirstElement"]
let elements = [FirstElement(context: core), SecondElement(context: core), TimeIndicatorElementMock(context: core), FullscreenButton(context: core)]
let mediaControl = MediaControl(context: core)
mediaControl.render()
let bottomRightView = mediaControl.mediaControlView.bottomRight
mediaControl.render(elements)
expect(bottomRightView?.subviews[0].subviews.first?.accessibilityIdentifier).to(equal("FullscreenButton"))
expect(bottomRightView?.subviews[1].subviews.first?.accessibilityIdentifier).to(equal("timeIndicator"))
expect(bottomRightView?.subviews[2].subviews.first?.accessibilityIdentifier).to(equal("SecondElement"))
expect(bottomRightView?.subviews[3].subviews.first?.accessibilityIdentifier).to(equal("FirstElement"))
}
it("renders the elements following the kMediaControlElementsOrder with only two elements specified in the option") {
let core = Core()
core.options[kMediaControlElementsOrder] = ["FullscreenButton", "TimeIndicatorElementMock"]
let elements = [FirstElement(context: core), SecondElement(context: core), TimeIndicatorElementMock(context: core), FullscreenButton(context: core), ]
let mediaControl = MediaControl(context: core)
mediaControl.render()
mediaControl.render(elements)
let bottomRightView = mediaControl.mediaControlView.bottomRight
expect(bottomRightView?.subviews[0].subviews.first?.accessibilityIdentifier).to(equal("FullscreenButton"))
expect(bottomRightView?.subviews[1].subviews.first?.accessibilityIdentifier).to(equal("timeIndicator"))
expect(bottomRightView?.subviews[2].subviews.first?.accessibilityIdentifier).to(equal("FirstElement"))
expect(bottomRightView?.subviews[3].subviews.first?.accessibilityIdentifier).to(equal("SecondElement"))
}
}
}
describe("#gestureRecognizer") {
context("when the touch occurs in seekbar view") {
it("should not receive touch") {
let core = CoreStub()
let mediaControl = MediaControl(context: core)
let seekbar = Seekbar(context: core)
let touch = UITouchStub()
core.addPlugin(seekbar)
seekbar.view.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
let shouldReceiveTouch = mediaControl.gestureRecognizer(UITapGestureRecognizer(), shouldReceive: touch)
expect(shouldReceiveTouch).to(beFalse())
}
}
context("when the touch occurs in seekbar view") {
it("should receives touch") {
let core = CoreStub()
let mediaControl = MediaControl(context: core)
let seekbar = Seekbar(context: core)
let touch = UITouchStub()
core.addPlugin(seekbar)
seekbar.view.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
touch.x = 100
touch.y = 100
let shouldReceiveTouch = mediaControl.gestureRecognizer(UITapGestureRecognizer(), shouldReceive: touch)
expect(shouldReceiveTouch).to(beTrue())
}
}
}
}
}
}
class MediaControlViewMock: MediaControlView {
var didCallAddSubview = false
var didCallAddSubviewWithView: UIView?
var didCallAddSubviewWithPanel: MediaControlPanel?
var didCallAddSubviewWithPosition: MediaControlPosition?
override func addSubview(_ view: UIView, in panel: MediaControlPanel, at position: MediaControlPosition) {
didCallAddSubviewWithView = view
didCallAddSubviewWithPanel = panel
didCallAddSubviewWithPosition = position
didCallAddSubview = true
}
}
class MediaControlElementMock: MediaControl.Element {
static var _panel: MediaControlPanel = .top
static var _position: MediaControlPosition = .left
static var didCallRender = false
static var crashOnRender = false
override class var name: String {
return "MediaControlElementMock"
}
open override var panel: MediaControlPanel {
return MediaControlElementMock._panel
}
open override var position: MediaControlPosition {
return MediaControlElementMock._position
}
override func bindEvents() { }
override func render() {
MediaControlElementMock.didCallRender = true
if MediaControlElementMock.crashOnRender {
codeThatCrashes()
}
trigger("render")
}
static func reset() {
MediaControlElementMock.didCallRender = false
}
private func codeThatCrashes() {
NSException(name:NSExceptionName(rawValue: "TestError"), reason:"Test Error", userInfo:nil).raise()
}
}
class TimeIndicatorElementMock: TimeIndicator {
override class var name: String {
return "TimeIndicatorElementMock"
}
open override var panel: MediaControlPanel {
return .bottom
}
open override var position: MediaControlPosition {
return .right
}
}
class FirstElement: MediaControl.Element {
override class var name: String {
return "FirstElement"
}
var button: UIButton! {
didSet {
button.accessibilityIdentifier = pluginName
view.addSubview(button)
}
}
override func bindEvents() { }
override open func render() {
button = UIButton(type: .custom)
}
open override var panel: MediaControlPanel {
return .bottom
}
open override var position: MediaControlPosition {
return .right
}
}
class SecondElement: MediaControl.Element {
override class var name: String {
return "SecondElement"
}
var button: UIButton! {
didSet {
button.accessibilityIdentifier = pluginName
view.addSubview(button)
}
}
override func bindEvents() { }
override open func render() {
button = UIButton(type: .custom)
}
open override var panel: MediaControlPanel {
return .bottom
}
open override var position: MediaControlPosition {
return .right
}
}
| bsd-3-clause | aea9095a5226e7e9aeccfbe0c0d91cdc | 41.295103 | 174 | 0.498949 | 6.289958 | false | false | false | false |
ryanipete/AmericanChronicle | Tests/UnitTests/OCRCoordinatesWebServiceTests.swift | 1 | 4414 | import XCTest
@testable import AmericanChronicle
import Alamofire
class OCRCoordinatesWebServiceTests: XCTestCase {
var subject: OCRCoordinatesWebService!
var manager: FakeSessionManager!
// MARK: Setup and Teardown
override func setUp() {
super.setUp()
manager = FakeSessionManager()
subject = OCRCoordinatesWebService(manager: manager)
}
override func tearDown() {
subject = nil
manager = nil
super.tearDown()
}
// MARK: Tests
func testThat_whenStartRequestIsCalled_withAnEmptyLCCN_itImmediatelyReturnsAnInvalidParameterError() {
// when
var error: NSError?
subject.startRequest("", contextID: "") { result in
if case .failure(let err) = result {
error = err as NSError
}
}
// then
XCTAssertEqual(error?.code, NSError.Code.invalidParameter.rawValue)
}
func testThat_whenStartRequestIsCalled_withTheCorrectParameters_itStartsARequest_withTheCorrectURL() {
// given/when
let id = "lccn/sn83045487/1913-02-20/ed-1/seq-18/"
subject.startRequest(id, contextID: "fake-context") { _ in }
// then
let actual = try? manager.beginRequest_recorder.callLog[0].params.request.asURLRequest().url?.absoluteString
let expected = "http://chroniclingamerica.loc.gov/lccn/sn83045487/1913-02-20/ed-1/seq-18/coordinates"
XCTAssertEqual(actual, expected)
}
func testThat_whenStartRequestIsCalled_withADuplicateRequest_itImmediatelyReturnsADuplicateRequestError() {
// given
let id = "lccn/sn83045487/1913-02-20/ed-1/seq-18/"
let contextID = "fake-context"
subject.startRequest(id, contextID: contextID) { _ in }
// when
var error: NSError?
subject.startRequest(id, contextID: contextID) { result in
if case .failure(let err) = result {
error = err as NSError
}
}
// then
XCTAssertEqual(error?.code, NSError.Code.duplicateRequest.rawValue)
}
func testThat_whenARequestSucceeds_itCallsTheCompletionHandler_withTheCoordinates() {
// given
var returnedCoordinates: OCRCoordinates?
subject.startRequest("lccn/sn83045487/1913-02-20/ed-1/seq-18/", contextID: "fake-context") { result in
if case .success(let coords) = result {
returnedCoordinates = coords
}
}
let expectedCoordinates = OCRCoordinates(width: nil, height: nil, wordCoordinates: [:])
let data = try? JSONSerialization.data(withJSONObject: ["width": "", "height": "", "coords": [:]], options: [])
let result: Result<Data> = .success(data!)
let response = Alamofire.DataResponse(request: nil, response: nil, data: data, result: result)
// when
manager?.fake_beginRequest_response(response)
// then
XCTAssertEqual(returnedCoordinates, expectedCoordinates)
}
func testThat_whenARequestFails_itCallsTheCompletionHandler_withTheError() {
// given
var returnedError: NSError?
subject.startRequest("lccn/sn83045487/1913-02-20/ed-1/seq-18/", contextID: "fake-context") { result in
if case .failure(let err) = result {
returnedError = err as NSError
}
}
let expectedError = NSError(code: .invalidParameter, message: nil)
let result: Result<Data> = .failure(expectedError)
let response = Alamofire.DataResponse(request: nil, response: nil, data: nil, result: result)
// when
manager.fake_beginRequest_response(response)
// then
XCTAssertEqual(returnedError, expectedError)
}
func testThat_byTheTimeTheCompletionHandlerIsCalled_theRequestIsNotConsideredToBeInProgress() {
// given
var isInProgress = true
subject.startRequest("", contextID: "") { _ in
isInProgress = self.subject.isRequestInProgressWith(pageID: "", contextID: "")
}
let result: Result<Data> = .failure(NSError(code: .duplicateRequest, message: nil))
let response = DataResponse(request: nil, response: nil, data: nil, result: result)
// when
manager.fake_beginRequest_response(response)
// then
XCTAssertFalse(isInProgress)
}
}
| mit | 863816102d6ffaeffcd5150d4e17c514 | 29.232877 | 119 | 0.63729 | 4.387674 | false | true | false | false |
moysklad/ios-remap-sdk | Sources/MoyskladiOSRemapSDK/Network/HttpClient+Extensions.swift | 1 | 4735 | //
// HttpClient+Extensions.swift
// MoyskladNew
//
// Created by Anton Efimenko on 20.10.16.
// Copyright © 2016 Andrey Parshakov. All rights reserved.
//
import Foundation
import RxSwift
extension HttpClient {
static func register(email: String, phone: String?) -> Observable<JSONType?> {
var dictionary: Dictionary<String, Any> = ["email": email, "source": "msappstore"]
if let phoneParam = phone, !phoneParam.isEmpty {
dictionary["phone"] = phoneParam
}
let router = HttpRouter.create(apiRequest: .register,
method: .post,
contentType: .formUrlencoded,
httpBody: dictionary.toJSONType())
return resultCreate(router)
}
static func get(_ request: MSApiRequest,
auth: Auth,
urlPathComponents: [String] = [],
urlParameters: [UrlParameter] = []) -> Observable<JSONType?> {
let router = HttpRouter.create(apiRequest: request,
method: .get,
contentType: .json,
urlPathComponents: urlPathComponents,
httpBody: nil,
headers: auth.header,
urlParameters: urlParameters)
return resultCreate(router)
}
static func update(_ request: MSApiRequest,
auth: Auth,
urlPathComponents: [String] = [],
urlParameters: [UrlParameter] = [],
body: JSONType? = nil) -> Observable<JSONType?> {
var headers = auth.header
if body == nil {
headers["Content-Type"] = "application/json"
}
let router = HttpRouter.create(apiRequest: request,
method: .put,
contentType: .json,
urlPathComponents: urlPathComponents,
httpBody: body,
headers: headers,
urlParameters: urlParameters)
return resultCreate(router)
}
static func updateWithHeadersResult(_ request: MSApiRequest,
auth: Auth,
urlPathComponents: [String] = [],
urlParameters: [UrlParameter] = [],
body: JSONType?) -> Observable<Dictionary<String, String>?> {
var headers = auth.header
if body == nil {
headers["Content-Type"] = "application/json"
}
let router = HttpRouter.create(apiRequest: request,
method: .post,
contentType: .json,
urlPathComponents: urlPathComponents,
httpBody: body,
headers: headers,
urlParameters: urlParameters)
return resultCreateFromHeader(router)
}
static func create(_ request: MSApiRequest,
auth: Auth,
urlPathComponents: [String] = [],
urlParameters: [UrlParameter] = [],
body: JSONType,
contentType: HttpRequestContentType = .json) -> Observable<JSONType?> {
let router = HttpRouter.create(apiRequest: request,
method: .post,
contentType: contentType,
urlPathComponents: urlPathComponents,
httpBody: body,
headers: auth.header,
urlParameters: urlParameters)
return resultCreate(router)
}
static func delete(_ request: MSApiRequest,
auth: Auth,
urlPathComponents: [String] = [],
body: JSONType? = nil) -> Observable<JSONType?> {
var headers = auth.header
if body == nil {
headers["Content-Type"] = "application/json"
}
let router = HttpRouter.create(apiRequest: request,
method: .delete,
contentType: .json,
urlPathComponents: urlPathComponents,
httpBody: body,
headers: headers)
return resultCreate(router)
}
}
| mit | 4b74e88fdde8b432983bcc54de7fed3c | 40.526316 | 101 | 0.45902 | 5.844444 | false | false | false | false |
MenloHacks/ios-app | Menlo Hacks/Pods/Parchment/Parchment/Structs/PagingItems.swift | 1 | 2026 | import Foundation
/// A data structure used to hold an array of `PagingItem`'s, with
/// methods for getting the index path for a given `PagingItem` and
/// vice versa.
public struct PagingItems<T: PagingItem> where T: Hashable & Comparable {
/// A sorted array of the currently visible `PagingItem`'s.
public let items: [T]
let hasItemsBefore: Bool
let hasItemsAfter: Bool
let itemsCache: Set<T>
init(items: [T], hasItemsBefore: Bool = false, hasItemsAfter: Bool = false) {
self.items = items
self.hasItemsBefore = hasItemsBefore
self.hasItemsAfter = hasItemsAfter
self.itemsCache = Set(items)
}
/// The `IndexPath` for a given `PagingItem`. Returns nil if the
/// `PagingItem` is not in the `items` array.
///
/// - Parameter pagingItem: A `PagingItem` instance
/// - Returns: The `IndexPath` for the given `PagingItem`
public func indexPath(for pagingItem: T) -> IndexPath? {
guard let index = items.index(of: pagingItem) else { return nil }
return IndexPath(item: index, section: 0)
}
/// The `PagingItem` for a given `IndexPath`. This method will crash
/// if you pass in an `IndexPath` that is currently not visible in
/// the collection view.
///
/// - Parameter indexPath: An `IndexPath` that is currently visible
/// - Returns: The `PagingItem` for the given `IndexPath`
public func pagingItem(for indexPath: IndexPath) -> T {
return items[indexPath.item]
}
/// The direction from a given `PagingItem` to another `PagingItem`.
/// If the `PagingItem`'s are equal the direction will be .none.
///
/// - Parameter from: The current `PagingItem`
/// - Parameter to: The `PagingItem` being scrolled towards
/// - Returns: The `PagingDirection` for a given `PagingItem`
public func direction(from: T, to: T) -> PagingDirection {
if itemsCache.contains(from) == false {
return .none
} else if to > from {
return .forward
} else if to < from {
return .reverse
}
return .none
}
}
| mit | 3cd2d5095b9f82189c41ef1caa184b7c | 33.931034 | 79 | 0.671273 | 3.926357 | false | false | false | false |
StephenMIMI/U17Comics | U17Comics/U17Comics/classes/HomePage/main/Models/ComicReadedModel.swift | 1 | 1488 | //
// ComicReadedModel.swift
// U17Comics
//
// Created by qianfeng on 16/11/10.
// Copyright © 2016年 zhb. All rights reserved.
//
import UIKit
class ComicReadedModelArray: NSObject, NSCoding {
var readedArray: [ComicReadedModel]?
init(readedArray: [ComicReadedModel]? = nil ) {
self.readedArray = []
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(readedArray, forKey: "readedArray")
}
required init?(coder aDecoder: NSCoder) {
super.init()
readedArray = aDecoder.decodeObjectForKey("readedArray") as? [ComicReadedModel]
}
}
class ComicReadedModel: NSObject , NSCoding {
var comicId: String?
var chapterName: String?
var chapterId: String?
init(comicId: String? = nil, chapterName: String? = nil, chapterId: String? = nil) {
self.comicId = comicId
self.chapterName = chapterName
self.chapterId = chapterId
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(comicId, forKey: "comicId")
aCoder.encodeObject(chapterName, forKey: "chapterName")
aCoder.encodeObject(chapterId, forKey: "chapterId")
}
required init?(coder aDecoder: NSCoder) {
super.init()
comicId = aDecoder.decodeObjectForKey("comicId") as? String
chapterName = aDecoder.decodeObjectForKey("chapterName") as? String
chapterId = aDecoder.decodeObjectForKey("chapterId") as? String
}
}
| mit | 7ebbeab0bacc36b6a168aeb57ea3fc49 | 28.117647 | 88 | 0.657239 | 4.171348 | false | false | false | false |
coffee-cup/solis | SunriseSunset/MainViewController.swift | 1 | 7473 | //
// MainViewController.swift
// SunriseSunset
//
// Created by Jake Runzer on 2016-06-01.
// Copyright © 2016 Puddllee. All rights reserved.
//
import Foundation
import UIKit
protocol MenuProtocol {
func menuIsMoving(_ percent: Float)
func menuStartAnimatingIn()
func menuStartAnimatingOut()
func menuIsIn()
func menuIsOut()
}
class MainViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var sunContainerView: UIView!
@IBOutlet weak var menuContainerView: UIView!
@IBOutlet weak var menuLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var menuWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var menuButton: UIButton!
@IBOutlet weak var menuImageView: SpringImageView!
var menuViewController: MenuViewController!
var sunViewController: SunViewController!
// recognizers
var menuRecognizer: UIScreenEdgePanGestureRecognizer!
var panRecognizer: UIPanGestureRecognizer!
var menuWidth: CGFloat!
var anchorX: CGFloat = 0
var delegate: MenuProtocol?
var menuOut = false {
didSet {
if menuOut {
// Bus.sendMessage(.MenuOut, data: nil)
} else {
// Bus.sendMessage(.MenuIn, data: nil)
}
}
}
var holdingWhileOut = false
// Constants
let MenuAnimaitonDuration: TimeInterval = 0.25
let ClosenessToEdgeIn: CGFloat = 40
let ClosenessToEdgeOut: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
menuWidth = view.frame.width * menuWidthConstraint.multiplier
menuHardIn()
addGestureRecognizers()
Bus.subscribeEvent(.sendMenuIn, observer: self, selector: #selector(sendMenuIn))
menuImageView.duration = CGFloat(1)
menuImageView.curve = "easeInOut"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override var prefersStatusBarHidden : Bool {
return true
}
func addGestureRecognizers() {
panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(menuPan))
view.addGestureRecognizer(panRecognizer)
menuRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(sideSwipe))
menuRecognizer.edges = .left
menuRecognizer.delegate = self
view.addGestureRecognizer(menuRecognizer)
}
// Navigation
func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "MenuSegue" {
menuViewController = segue.destination as? MenuViewController
} else if segue.identifier == "SunSegue" {
sunViewController = segue.destination as? SunViewController
delegate = sunViewController
}
}
// Side Menu
// func animateMenu() {
// UIView.animateWithDuration(MenuAnimaitonDuration) {
// self.view.layoutIfNeeded()
// }
// }
// Adjusts the x position to be negative in terms of menuWidth
func adjustNegative(_ x: CGFloat) -> CGFloat {
return -menuWidth + x
}
func menuHardIn() {
menuLeadingConstraint.constant = adjustNegative(-1)
menuContainerView.alpha = 0
menuOut = false
delegate?.menuIsIn()
}
func menuSoftIn() {
menuLeadingConstraint.constant = adjustNegative(-1)
delegate?.menuStartAnimatingIn()
UIView.animate(withDuration: MenuAnimaitonDuration, animations: {
self.view.layoutIfNeeded()
}, completion: { finished in
self.menuOut = false
self.menuContainerView.alpha = 0
self.delegate?.menuIsIn()
})
sendMenuButtonOut()
}
func menuHardOut() {
menuLeadingConstraint.constant = adjustNegative(menuWidth)
menuContainerView.alpha = 1
menuOut = true
delegate?.menuIsOut()
}
func menuSoftOut() {
menuContainerView.alpha = 1
menuLeadingConstraint.constant = adjustNegative(menuWidth)
delegate?.menuStartAnimatingOut()
UIView.animate(withDuration: MenuAnimaitonDuration, animations: {
self.view.layoutIfNeeded()
}, completion: { finished in
self.menuOut = true
self.delegate?.menuIsOut()
})
}
// Moves the menu in or out depending on its position now
func menuInOut() {
let position = menuLeadingConstraint.constant
if menuWidth + position > menuWidth / 2 {
menuSoftOut()
} else {
menuSoftIn()
}
}
func menuToFinger(_ x: CGFloat) {
let adjustedX = x > menuWidth ? menuWidth : x
let menuTransform = adjustNegative(adjustedX!)
delegate?.menuIsMoving(Float(adjustedX! / menuWidth))
menuLeadingConstraint.constant = menuTransform
}
@objc func sideSwipe(_ recognizer: UIScreenEdgePanGestureRecognizer) {
let fingerX = recognizer.location(in: view).x
if recognizer.state == .began {
menuContainerView.alpha = 1
if !menuOut {
sendMenuButtonIn()
}
} else if recognizer.state == .changed {
if !menuOut {
menuToFinger(fingerX)
}
} else if recognizer.state == .ended {
menuInOut()
}
}
func between(_ val: Double, low: Double, high: Double) -> Bool {
return val >= low && val <= high
}
@objc func menuPan(_ recognizer: UIPanGestureRecognizer) {
let fingerX = recognizer.location(in: view).x
if recognizer.state == .began {
if menuOut && between(Double(fingerX), low: Double(menuWidth - ClosenessToEdgeIn), high: Double(menuWidth + menuWidth)) {
holdingWhileOut = true
anchorX = menuWidth - fingerX
}
} else if recognizer.state == .changed {
if holdingWhileOut {
menuToFinger(fingerX + anchorX)
}
} else if recognizer.state == .ended {
if holdingWhileOut {
menuInOut()
holdingWhileOut = false
}
}
}
@objc func sendMenuIn() {
if menuOut {
menuSoftIn()
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
@objc func sendMenuButtonOut() {
menuImageView.animation = "fadeIn"
menuImageView.animate()
}
@objc func sendMenuButtonIn() {
menuImageView.animation = "fadeOut"
menuImageView.animate()
}
@IBAction func menuButtonDidTouch(_ sender: AnyObject) {
menuSoftOut()
sendMenuButtonIn()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SunSegue" {
if let sunViewController = segue.destination as? SunViewController {
delegate = sunViewController
}
}
}
}
| mit | 8f27f7d185cb1086ebc03bdeba9074fc | 28.888 | 157 | 0.603319 | 5.086453 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne | DataAndTable/DataAndTable/Person.swift | 1 | 1693 | //
// Person.swift
// 数据存储和表格演练
//
// Created by bingoogol on 14/9/2.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
enum SexType : Int {
case SexMan
case SexWoman
case SexUnknow
}
class Person:NSObject,NSCoding {
var username:NSString?
var qq:NSString?
var phoneNo:NSString?
var sex:SexType?
var iconImage:UIImage?
var sexStr:NSString?
override init() {
}
func getSexStr() -> NSString {
if(SexType.SexMan == self.sex) {
return "男"
} else if(SexType.SexWoman == self.sex) {
return "女"
} else {
return ""
}
}
func setSexStr(var sexStr:NSString) {
if(sexStr == "男") {
sex = SexType.SexMan
} else if(sexStr == "女") {
sex = SexType.SexWoman
} else {
sex = SexType.SexUnknow
}
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(username!, forKey: "username")
aCoder.encodeObject(qq!, forKey: "qq")
aCoder.encodeObject(phoneNo!, forKey: "phoneNo")
aCoder.encodeInteger(SexType.SexMan.rawValue, forKey: "sex")
aCoder.encodeObject(iconImage!, forKey: "iconImage")
}
required init(coder aDecoder: NSCoder) {
username = aDecoder.decodeObjectForKey("username") as? NSString
qq = aDecoder.decodeObjectForKey("qq") as? NSString
phoneNo = aDecoder.decodeObjectForKey("phoneNo") as? NSString
sex = SexType(rawValue: aDecoder.decodeIntegerForKey("sex"))
iconImage = aDecoder.decodeObjectForKey("iconImage") as? UIImage
}
} | apache-2.0 | 35d604bd86ddb8e4ef9f3957a29d78cf | 25.444444 | 72 | 0.595195 | 4.031477 | false | false | false | false |
BGDigital/mcwa | mcwa/mcwa/ addQuestionController.swift | 1 | 16850 | //
// addQuestionController.swift
// mcwa
//
// Created by 陈强 on 15/10/13.
// Copyright © 2015年 XingfuQiu. All rights reserved.
//
import UIKit
class addQuestionController: UIViewController,UITextFieldDelegate,UMSocialUIDelegate,DBCameraViewControllerDelegate,UITextViewDelegate {
@IBOutlet weak var segmentedbtn: UISegmentedControl!
@IBOutlet weak var oneUploadBtn: UIButton!
@IBOutlet weak var twoUploadBtn: UIButton!
@IBOutlet weak var answerSegment: UISegmentedControl!
@IBOutlet weak var titleView: UITextView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageBtn: UIImageView!
var textView:UITextView!
var containerView:UIView!
var cancleButton:UIButton!
var sendButton:UIButton!
var lableView:UILabel!
@IBOutlet weak var oneView: UIView!
@IBOutlet weak var twoView: UIView!
@IBOutlet weak var threeView: UIView!
@IBOutlet weak var fourView: UIView!
@IBOutlet weak var answerOne: UILabel!
@IBOutlet weak var answerTwo: UILabel!
@IBOutlet weak var answerThree: UILabel!
@IBOutlet weak var answerFour: UILabel!
var answerFlag:Int = 1
var questionType:String! = "选择题"
var reallyAnswer:String! = "正确"
var icon:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.titleView.tag = 10
self.titleView.delegate = self
self.view.userInteractionEnabled = true
self.scrollView.userInteractionEnabled = true
self.answerSegment.hidden = true
self.twoUploadBtn.hidden = true
self.navigationItem.title = "出题"
// imageView.layer.borderWidth = 5.0
// imageView.layer.borderColor = UIColor(patternImage: UIImage(named:"DotedImage.png")!).CGColor
// let attributes = [NSForegroundColorAttributeName:UIColor(red: 0.329, green: 0.318, blue: 0.518, alpha: 1.00) ]
// segmentedBtn.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
// let highlightedAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
// segmentedBtn.setTitleTextAttributes(highlightedAttributes, forState: UIControlState.Selected)
self.navigationItem.title = "出题"
// one = UITextField(frame: CGRectMake(0, 100, 300, 100))
// one.backgroundColor = UIColor.whiteColor()
// one.font = UIFont.systemFontOfSize(40)
// one.delegate = self
// self.view.addSubview(one)
//
// segmentedControl = HMSegmentedControl(sectionTitles: kindsArray)
// segmentedControl.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 40)
// segmentedControl.backgroundColor = UIColor.blueColor()
// segmentedControl.tintColor = UIColor.redColor()
// segmentedControl.textColor = UIColor(red: 0.694, green: 0.694, blue: 0.694, alpha: 1.00)
// segmentedControl.selectedTextColor = UIColor(red: 0.255, green: 0.788, blue: 0.298, alpha: 1.00)
// segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationNone
// segmentedControl.addTarget(self, action: "segmentSelected:", forControlEvents: UIControlEvents.ValueChanged)
// self.view.addSubview(segmentedControl)
initSegmented()
initAddImage()
initReplyBar();
// initTextField()
initView();
}
func initView(){
self.textView.delegate = self
oneView.userInteractionEnabled = true
let oneTapGR = UITapGestureRecognizer(target: self, action: "oneQuestionAction:")
oneView.addGestureRecognizer(oneTapGR)
twoView.userInteractionEnabled = true
let twoTapGR = UITapGestureRecognizer(target: self, action: "twoQuestionAction:")
twoView.addGestureRecognizer(twoTapGR)
threeView.userInteractionEnabled = true
let threeTapGR = UITapGestureRecognizer(target: self, action: "threeQuestionAction:")
threeView.addGestureRecognizer(threeTapGR)
fourView.userInteractionEnabled = true
let fourTapGR = UITapGestureRecognizer(target: self, action: "fourQuestionAction:")
fourView.addGestureRecognizer(fourTapGR)
}
func oneQuestionAction(sender:UITapGestureRecognizer) {
self.containerView.alpha = 1
answerFlag = 1
self.textView.text = ""
self.textView.becomeFirstResponder()
}
func twoQuestionAction(sender:UITapGestureRecognizer) {
self.containerView.alpha = 1
answerFlag = 2
self.textView.text = ""
self.textView.becomeFirstResponder()
}
func threeQuestionAction(sender:UITapGestureRecognizer) {
self.containerView.alpha = 1
answerFlag = 3
self.textView.text = ""
self.textView.becomeFirstResponder()
}
func fourQuestionAction(sender:UITapGestureRecognizer) {
self.containerView.alpha = 1
answerFlag = 4
self.textView.text = ""
self.textView.becomeFirstResponder()
}
func initReplyBar() {
self.containerView = UIView(frame: CGRectMake(0, self.view.bounds.height, self.view.bounds.width, 110))
self.containerView.backgroundColor = UIColor(red: 0.949, green: 0.949, blue: 0.949, alpha: 1.00)
self.cancleButton = UIButton(frame: CGRectMake(5, 5, 50, 30))
self.cancleButton.setTitle("取消", forState: UIControlState.Normal)
self.cancleButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
self.cancleButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Highlighted)
self.cancleButton.titleLabel?.font = UIFont.systemFontOfSize(14)
self.cancleButton.addTarget(self, action: "cancleReply", forControlEvents: UIControlEvents.TouchUpInside)
self.sendButton = UIButton(frame: CGRectMake(self.containerView.frame.size.width-5-50, 5, 50, 30))
self.sendButton.setTitle("确定", forState: UIControlState.Normal)
self.sendButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
self.sendButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Highlighted)
self.sendButton.titleLabel?.font = UIFont.systemFontOfSize(14)
self.sendButton.addTarget(self, action: "sendReply", forControlEvents: UIControlEvents.TouchUpInside)
self.lableView = UILabel(frame: CGRectMake((self.containerView.frame.size.width)/2-40, 5, 80, 30))
self.lableView.text = "限制10字"
self.lableView.textAlignment = NSTextAlignment.Center
self.lableView.textColor = UIColor.grayColor()
self.textView = UITextView(frame: CGRectMake(15, 50, self.containerView.frame.size.width-30, 40))
self.textView.delegate = self
textView.layer.borderColor = UIColor.grayColor().CGColor;
textView.layer.borderWidth = 1;
textView.layer.cornerRadius = 6;
textView.layer.masksToBounds = true;
textView.userInteractionEnabled = true;
textView.font = UIFont.systemFontOfSize(18)
textView.scrollEnabled = true;
textView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
let tapDismiss = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
self.view.addGestureRecognizer(tapDismiss)
self.scrollView.addGestureRecognizer(tapDismiss)
self.containerView.addSubview(self.cancleButton)
self.containerView.addSubview(self.lableView)
self.containerView.addSubview(self.sendButton)
self.containerView.addSubview(self.textView)
self.view.addSubview(containerView)
self.containerView.alpha = 0
}
func textViewDidBeginEditing(textView: UITextView) {
if(textView.tag == 10){
if(textView.text == " 这里写题目"){
textView.text = ""
}
}
}
func textViewDidChange(textView: UITextView) {
textView.scrollRangeToVisible(textView.selectedRange)
}
func textViewDidEndEditing(textView: UITextView) {
if(textView.tag == 10){
if(textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == ""){
textView.text = " 这里写题目"
}
}
}
func keyboardDidShow(notification:NSNotification) {
self.view.bringSubviewToFront(containerView)
let userInfo: NSDictionary = notification.userInfo! as NSDictionary
let v : NSValue = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyHeight = v.CGRectValue().size.height
let duration = userInfo.objectForKey(UIKeyboardAnimationDurationUserInfoKey) as! NSNumber
let curve:NSNumber = userInfo.objectForKey(UIKeyboardAnimationCurveUserInfoKey) as! NSNumber
let temp:UIViewAnimationCurve = UIViewAnimationCurve(rawValue: curve.integerValue)!
UIView.animateWithDuration(duration.doubleValue, animations: {
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationCurve(temp)
self.containerView.frame = CGRectMake(0, self.view.frame.size.height-keyHeight-110, self.view.bounds.size.width, 110)
})
}
func keyboardDidHidden(notification:NSNotification) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.25)
self.containerView.frame = CGRectMake(0, self.view.frame.size.height, self.view.bounds.size.width, 110)
self.containerView.alpha = 0
UIView.commitAnimations()
}
func dismissKeyboard(){
self.textView.resignFirstResponder()
self.titleView.resignFirstResponder()
}
func cancleReply() {
self.textView.resignFirstResponder()
}
func sendReply() {
let answer:String! = self.textView.text
if(answer.characters.count > 10){
}else{
if(answerFlag == 1){
self.answerOne.text = answer
}else if(answerFlag == 2){
self.answerTwo.text = answer
}else if(answerFlag == 3){
self.answerThree.text = answer
}else if(answerFlag == 4){
self.answerFour.text = answer
}
dismissKeyboard()
}
}
// func initTextField(){
// print(self.imageBtn.frame.origin.y)
// one = UITextField(frame: CGRectMake(0, 800, 300, 300))
// one.borderStyle = UITextBorderStyle.None
// one.backgroundColor = UIColor.redColor()
// self.scrollView.addSubview(one)
// }
func initAddImage() {
imageBtn.userInteractionEnabled = true
let tapGR = UITapGestureRecognizer(target: self, action: "tapHandler:")
imageBtn.addGestureRecognizer(tapGR)
}
func tapHandler(sender:UITapGestureRecognizer) {
let cameraContainer:DBCameraContainerViewController = DBCameraContainerViewController(delegate: self)
cameraContainer.delegate = self
cameraContainer.setFullScreenMode()
let nav:UINavigationController = UINavigationController(rootViewController: cameraContainer)
nav.navigationBarHidden = true
self.presentViewController(nav, animated: true, completion: nil)
}
func camera(cameraViewController: AnyObject!, didFinishWithImage image: UIImage!, withMetadata metadata: [NSObject : AnyObject]!) {
imageBtn.image = image
// self.icon = image
cameraViewController.restoreFullScreenMode()
self.presentedViewController?.dismissViewControllerAnimated(true, completion: nil)
}
func dismissCamera(cameraViewController: AnyObject!) {
self.presentedViewController?.dismissViewControllerAnimated(true, completion: nil)
cameraViewController.restoreFullScreenMode()
}
func initSegmented() {
let attributes = [NSForegroundColorAttributeName:UIColor(red: 0.329, green: 0.318, blue: 0.518, alpha: 1.00) ]
segmentedbtn.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
let highlightedAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
segmentedbtn.setTitleTextAttributes(highlightedAttributes, forState: UIControlState.Selected)
answerSegment.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
answerSegment.setTitleTextAttributes(highlightedAttributes, forState: UIControlState.Selected)
}
@IBAction func answerSegmentAction(sender: UISegmentedControl) {
reallyAnswer = sender.titleForSegmentAtIndex(sender.selectedSegmentIndex)
}
@IBAction func segmentedAction(sender: UISegmentedControl) {
questionType = sender.titleForSegmentAtIndex(sender.selectedSegmentIndex)
if(sender.selectedSegmentIndex == 0){
self.oneView.hidden = false
self.twoView.hidden = false
self.threeView.hidden = false
self.fourView.hidden = false
self.oneUploadBtn.hidden = false
self.twoUploadBtn.hidden = true
self.answerSegment.hidden = true
}else if(sender.selectedSegmentIndex == 1){
self.oneView.hidden = true
self.twoView.hidden = true
self.threeView.hidden = true
self.fourView.hidden = true
self.oneUploadBtn.hidden = true
self.twoUploadBtn.hidden = false
self.answerSegment.hidden = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func shareFunction(sender: UIButton) {
let shareImg: UIImage! = UIImage(named: "share_default")
let shareText:String! = "jdskfjlskdjflkdsjflkdjf"
ShareUtil.shareInitWithTextAndPicture(self, text: shareText, image: shareImg!,shareUrl:"http://www.baidu.com", callDelegate: self)
}
func didFinishGetUMSocialDataInViewController(response: UMSocialResponseEntity!) {
if(response.responseCode == UMSResponseCodeSuccess) {
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
MobClick.beginLogPageView("addQuestion")
// //注册键盘通知事件
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
MobClick.endLogPageView("addQuestion")
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@IBAction func addQuestionAction(sender: UIButton) {
var type = "choice"
let answerTitle = self.titleView.text
var icon = ""
var one = self.answerOne.text
var two = self.answerTwo.text
var three = self.answerThree.text
var four = self.answerFour.text
if(answerTitle.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" || answerTitle == " 这里写题目"){
print("题目不能为空,必填项")
return
}
if(answerTitle.characters.count > 50){
print("题目字数不能超过50字")
return
}
if(self.questionType == "判断题"){
one = reallyAnswer
type = "judge"
}else{
if(one!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" || one == "正确答案"){
print("答案不能为空,必填项")
return
}
if(two!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" || two == "错误答案"){
print("答案不能为空,必填项")
return
}
if(three!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" || three == "错误答案"){
print("答案不能为空,必填项")
return
}
if(four!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" || four == "错误答案"){
print("答案不能为空,必填项")
return
}
}
}
} | mit | 4b6f5b25d11b11196c38e965143fa162 | 40.240695 | 145 | 0.661291 | 4.968311 | false | false | false | false |
m3rkus/Mr.Weather | Mr.Weather/WeatherModel.swift | 1 | 11308 | //
// WeatherModel.swift
// Mr.Weather
//
// Created by Роман Анистратенко on 13/09/2017.
// Copyright © 2017 m3rk edge. All rights reserved.
//
import Foundation
// MARK: Weather enums
enum WeatherCondition: String {
case clear = "Clear sky"
case clouds = "Clouds"
case drizzle = "Drizzle"
case rain = "Rain"
case snow = "Snow"
case atmosphere = "Fog"
case thunderstorm = "Thunderstorm"
case extreme = "Hurricane"
case additional = "Calm"
}
enum WindDirection: String {
case N
case NNE
case NE
case ENE
case E
case ESE
case SE
case SSE
case S
case SSW
case SW
case WSW
case W
case WNW
case NW
case NNW
}
// MARK: Private helpers
private func convertKelvin(temperature: Double) -> Int {
// Fahrenheit temperatue
if UserDefaultsController.useFahrenheitTemperature {
return Helper.roundToInt(temperature * 1.8 - 459.67)
}
// Celsius temperature
return Helper.roundToInt(temperature - 273.15)
}
private func convertWind(velocity: Double) -> (Int, String) {
// Miles per hour
if UserDefaultsController.useMilesPerHourWindSpeed {
return (Helper.roundToInt(velocity * 3600 / 1609), "m/h")
}
// Meters per second
return (Helper.roundToInt(velocity), "m/s")
}
// MARK: Main weather info
class MainWeatherInfo: NSObject, NSCoding {
// MARK: Properties & Init
private var date: Date
private var temperatureKelvin: Double
private var windSpeed: Double
private var windDirection: WindDirection!
private var condition: WeatherCondition!
private var windDegree: Double {
didSet {
switch self.windDegree {
case 11.25 ..< 33.75: self.windDirection = .NNE
case 33.75 ..< 56.25: self.windDirection = .NE
case 56.25 ..< 78.75: self.windDirection = .ENE
case 78.75 ..< 101.25: self.windDirection = .E
case 101.25 ..< 123.75: self.windDirection = .ESE
case 123.75 ..< 146.25: self.windDirection = .SE
case 146.25 ..< 168.75: self.windDirection = .SSE
case 168.75 ..< 191.25: self.windDirection = .S
case 191.25 ..< 213.75: self.windDirection = .SSW
case 213.75 ..< 236.25: self.windDirection = .SW
case 236.25 ..< 258.75: self.windDirection = .WSW
case 258.75 ..< 281.25: self.windDirection = .W
case 281.25 ..< 303.75: self.windDirection = .WNW
case 303.75 ..< 326.25: self.windDirection = .NW
case 326.25 ..< 348.75: self.windDirection = .NNW
default: self.windDirection = .N
}
}
}
private var state: String {
didSet {
switch self.state {
case "Thunderstorm": self.condition = .thunderstorm
case "Drizzle": self.condition = .drizzle
case "Rain": self.condition = .rain
case "Snow": self.condition = .snow
case "Atmosphere": self.condition = .atmosphere
case "Clear": self.condition = .clear
case "Clouds": self.condition = .clouds
case "Extreme": self.condition = .extreme
case "Additional": self.condition = .additional
default: fatalError("Unexpected behaviour mainWeatherInfo state")
}
}
}
init(date: Date, temperature: Double, state: String, windSpeed: Double, windDegree: Double) {
self.date = date
self.temperatureKelvin = temperature
self.windSpeed = windSpeed
self.windDegree = 0.0
self.state = ""
super.init()
defer {
self.windDegree = windDegree
self.state = state
}
}
// MARK: Getters
func getDayShortNameString() -> String {
return Helper.stringFrom(date: self.date, format: "E")
}
func getDayAndMonthString() -> String {
return Helper.stringFrom(date: self.date, format: "dd/MM")
}
func getTemperatureString() -> String {
return "\(convertKelvin(temperature: self.temperatureKelvin))º"
}
func getWindString() -> String {
let (windSpeed, windDimension) = convertWind(velocity: self.windSpeed)
let windInfo = "\(self.windDirection.rawValue) \(windSpeed) \(windDimension)"
return windInfo
}
func getWeatherConditionString() -> String {
return self.condition.rawValue
}
func getWeatherCondition() -> WeatherCondition {
return self.condition
}
// MARK: NSCoding
struct Keys {
static let date = "date"
static let temperatureKelvin = "temperatureKelvin"
static let windSpeed = "windSpeed"
static let windDegree = "windDegree"
static let state = "state"
}
required convenience init?(coder decoder: NSCoder) {
guard
let date = decoder.decodeObject(forKey: Keys.date) as? Date,
let state = decoder.decodeObject(forKey: Keys.state) as? String
else {
dLog("NSCoder error mainWeatherInfo")
return nil
}
let temperatureKelvin = decoder.decodeDouble(forKey: Keys.temperatureKelvin)
let windSpeed = decoder.decodeDouble(forKey: Keys.windSpeed)
let windDegree = decoder.decodeDouble(forKey: Keys.windDegree)
self.init(date: date, temperature: temperatureKelvin, state: state, windSpeed: windSpeed, windDegree: windDegree)
}
func encode(with coder: NSCoder) {
dLog("encode mainWeatherInfo")
coder.encode(self.date, forKey: Keys.date)
coder.encode(self.temperatureKelvin, forKey: Keys.temperatureKelvin)
coder.encode(self.windSpeed, forKey: Keys.windSpeed)
coder.encode(self.windDegree, forKey: Keys.windDegree)
coder.encode(self.state, forKey: Keys.state)
}
}
// MARK: Additional weather info
class AdditionalWeatherInfo: NSObject, NSCoding {
// MARK: Properties & Init
let specification: String
let humidity: Int
let pressure: Int
let clouds: Int
let visibility: Int
let sunrise: Date
let sunset: Date
init(specification: String, humidity: Int, pressure: Int, clouds: Int, visibility: Int, sunrise: Date, sunset: Date) {
self.specification = specification
self.humidity = humidity
self.pressure = pressure
self.clouds = clouds
self.visibility = visibility
self.sunrise = sunrise
self.sunset = sunset
super.init()
}
// MARK: Getters
func getHumidityString() -> String {
return "\(self.humidity) %"
}
func getPressureString() -> String {
return "\(self.pressure) hPa"
}
func getCloudsString() -> String {
return "\(self.clouds) %"
}
func getVisibilityString() -> String {
return "\(self.visibility) m"
}
func getSunriseString() -> String {
return Helper.stringFrom(date: self.sunrise, format: "HH:mm")
}
func getSunsetString() -> String {
return Helper.stringFrom(date: self.sunset, format: "HH:mm")
}
// MARK: NSCoding
struct Keys {
static let specification = "specification"
static let humidity = "humidity"
static let pressure = "pressure"
static let clouds = "clouds"
static let visibility = "visibility"
static let sunrise = "sunrise"
static let sunset = "sunset"
}
required convenience init?(coder decoder: NSCoder) {
guard
let specification = decoder.decodeObject(forKey: Keys.specification) as? String,
let sunrise = decoder.decodeObject(forKey: Keys.sunrise) as? Date,
let sunset = decoder.decodeObject(forKey: Keys.sunset) as? Date
else {
dLog("NSCoder error additionalWeatherInfo")
return nil
}
let humidity = decoder.decodeInteger(forKey: Keys.humidity)
let pressure = decoder.decodeInteger(forKey: Keys.pressure)
let clouds = decoder.decodeInteger(forKey: Keys.clouds)
let visibility = decoder.decodeInteger(forKey: Keys.visibility)
self.init(specification: specification, humidity: humidity, pressure: pressure, clouds: clouds, visibility: visibility, sunrise: sunrise, sunset: sunset)
}
func encode(with coder: NSCoder) {
dLog("encode additionalWeatherInfo")
coder.encode(self.specification, forKey: Keys.specification)
coder.encode(self.humidity, forKey: Keys.humidity)
coder.encode(self.pressure, forKey: Keys.pressure)
coder.encode(self.clouds, forKey: Keys.clouds)
coder.encode(self.visibility, forKey: Keys.visibility)
coder.encode(self.sunrise, forKey: Keys.sunrise)
coder.encode(self.sunset, forKey: Keys.sunset)
}
}
// MARK: Weather info
class WeatherInfo: NSObject, NSCoding {
// MARK: Properties & Init
let main: MainWeatherInfo
let additional: AdditionalWeatherInfo?
init(main: MainWeatherInfo, additional: AdditionalWeatherInfo?) {
self.main = main
self.additional = additional
super.init()
}
// MARK: NSCoding
struct Keys {
static let main = "main"
static let additional = "additional"
}
required convenience init?(coder decoder: NSCoder) {
guard let main = decoder.decodeObject(forKey: Keys.main) as? MainWeatherInfo else {
dLog("NSCoder error weatherInfo")
return nil
}
let additional = decoder.decodeObject(forKey: Keys.additional) as? AdditionalWeatherInfo
self.init(main: main, additional: additional)
}
func encode(with coder: NSCoder) {
dLog("encode weatherInfo")
coder.encode(self.main, forKey: Keys.main)
coder.encode(self.additional, forKey: Keys.additional)
}
}
// MARK: Weather model
class WeatherModel: NSObject, NSCoding {
// MARK: Properties & Init
var city: String!
var todayWeather: WeatherInfo!
var weekWeather: [WeatherInfo]!
override init() {}
// MARK: NSCoding
struct Keys {
static let city = "city"
static let todayWeather = "todayWeather"
static let weekWeather = "weekWeather"
}
required init?(coder decoder: NSCoder) {
guard
let city = decoder.decodeObject(forKey: Keys.city) as? String,
let todayWeather = decoder.decodeObject(forKey: Keys.todayWeather) as? WeatherInfo,
let weekWeather = decoder.decodeObject(forKey: Keys.weekWeather) as? [WeatherInfo]
else {
dLog("NSCoder error weatherModel")
return nil
}
self.city = city
self.todayWeather = todayWeather
self.weekWeather = weekWeather
}
func encode(with coder: NSCoder) {
dLog("encode weatherModel")
coder.encode(city, forKey: Keys.city)
coder.encode(todayWeather, forKey: Keys.todayWeather)
coder.encode(weekWeather, forKey: Keys.weekWeather)
}
}
| mit | 5339feeb53137970f48ce19b10fcfe0b | 29.760218 | 161 | 0.614138 | 4.390898 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Requests/Challenges/ChallengeResponseHandler.swift | 1 | 2290 | //
// ChallengeResponseHandler.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import ObjectMapper
class ChallengeResponseHandler: ResponseHandler {
fileprivate let completion: ChallengeClosure?
init(completion: ChallengeClosure?) {
self.completion = completion
}
override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) {
if let response = response,
let challengeMapper = Mapper<ChallengeMapper>().map(JSON: response["data"] as! [String : Any]) {
let metadata = MappingUtils.metadataFromResponse(response)
let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata)
let challenge = Challenge(mapper: challengeMapper, dataMapper: dataMapper, metadata: metadata)
executeOnMainQueue { self.completion?(challenge, ErrorTransformer.errorFromResponse(response, error: ErrorTransformer.errorFromResponse(response, error: error))) }
} else {
executeOnMainQueue { self.completion?(nil, ErrorTransformer.errorFromResponse(response, error: error)) }
}
}
}
| mit | 487d8c0185e97a4e5295bcb852e76bd3 | 47.723404 | 175 | 0.727948 | 4.841438 | false | false | false | false |
emilstahl/swift | test/SILGen/materializeForSet.swift | 10 | 20715 | // RUN: %target-swift-frontend -emit-sil -parse-stdlib %s | FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s | FileCheck %s -check-prefix=SILGEN
import Swift
func test_callback() {
let callback = Builtin.makeMaterializeForSetCallback
{(value, storage, inout selfV: Int, type) -> () in ()}
}
// CHECK: sil hidden @_TF17materializeForSet13test_callbackFT_T_ : $@convention(thin) () -> ()
// CHECK: [[T0:%.*]] = function_ref @_TFF17materializeForSet13test_callbackFT_T_U_FTBpRBBRSiMSi_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Int, @thick Int.Type) -> ()
// CHECK: sil shared @_TFF17materializeForSet13test_callbackFT_T_U_FTBpRBBRSiMSi_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Int, @thick Int.Type) -> () {
// CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Int, %3 : $@thick Int.Type):
// CHECK-NOT: alloc_box $Builtin.UnsafeValueBuffer
// CHECK: [[T0:%.*]] = metatype $@thin Int.Type
// CHECK: debug_value [[T0]] : $@thin Int.Type
class Base {
var stored: Int = 0
// The ordering here is unfortunate: we generate the property
// getters and setters after we've processed the decl.
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet4Basem8computedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Base, @thick Base.Type) -> ()>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base):
// CHECK: [[ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Int
// CHECK: [[T0:%.*]] = function_ref @_TFC17materializeForSet4Baseg8computedSi
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: store [[T1]] to [[ADDR]] : $*Int
// CHECK: [[T0:%.*]] = function_ref @_TFFC17materializeForSet4Basem8computedSiU_FTBpRBBRS0_MS0__T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> ()
// CHECK: [[T2:%.*]] = enum $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Base, @thick Base.Type) -> ()>, #Optional.Some!enumelt.1, [[T0]] : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type)
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[T2]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Base, @thick Base.Type) -> ()>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Base, @thick Base.Type) -> ()>)
// CHECK: }
// CHECK-LABEL: sil @_TFFC17materializeForSet4Basem8computedSiU_FTBpRBBRS0_MS0__T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Base, [[SELFTYPE:%.*]] : $@thick Base.Type):
// CHECK: [[T0:%.*]] = load [[SELF]]
// CHECK: strong_retain [[T0]]
// CHECK: [[T1:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Int
// CHECK: [[T2:%.*]] = load [[T1]] : $*Int
// CHECK: [[SETTER:%.*]] = function_ref @_TFC17materializeForSet4Bases8computedSi
// CHECK: apply [[SETTER]]([[T2]], [[T0]])
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet4Basem6storedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Base, @thick Base.Type) -> ()>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base):
// CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.stored
// CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// CHECK: inject_enum_addr [[TMP:%.*]]#1 : $*Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Base, @thick Base.Type) -> ()>, #Optional.None
// CHECK: [[T2:%.*]] = load [[TMP]]#1
// CHECK: [[T3:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T2]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Base, @thick Base.Type) -> ()>)
// CHECK: return [[T3]] : $(Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Base, @thick Base.Type) -> ()>)
// CHECK: }
var computed: Int {
get { return 0 }
set(value) {}
}
var storedFunction: () -> Int = { 0 }
final var finalStoredFunction: () -> Int = { 0 }
var computedFunction: () -> Int {
get { return {0} }
set {}
}
}
class Derived : Base {}
protocol Abstractable {
typealias Result
var storedFunction: () -> Result { get set }
var finalStoredFunction: () -> Result { get set }
var computedFunction: () -> Result { get set }
}
// Validate that we thunk materializeForSet correctly when there's
// an abstraction pattern present.
extension Derived : Abstractable {}
// SILGEN: sil hidden [transparent] [thunk] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FS1_m14storedFunction
// SILGEN: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived):
// SILGEN-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to $*@callee_owned (@out Int) -> ()
// SILGEN-NEXT: [[T0:%.*]] = load %2 : $*Derived
// SILGEN-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// SILGEN-NEXT: [[TEMP:%.*]] = alloc_stack $@callee_owned () -> Int
// SILGEN-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!getter.1
// SILGEN-NEXT: [[RESULT:%.*]] = apply [[FN]]([[SELF]])
// SILGEN-NEXT: store [[RESULT]] to [[TEMP]]
// SILGEN-NEXT: [[RESULT:%.*]] = load [[TEMP]]
// SILGEN-NEXT: strong_retain [[RESULT]]
// SILGEN-NEXT: function_ref
// SILGEN-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__dSi_XFo__iSi_ : $@convention(thin) (@out Int, @owned @callee_owned () -> Int) -> ()
// SILGEN-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]])
// SILGEN-NEXT: store [[T1]] to [[RESULT_ADDR]]
// SILGEN-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned (@out Int) -> () to $Builtin.RawPointer
// SILGEN-NEXT: function_ref
// SILGEN-NEXT: [[T0:%.*]] = function_ref @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFCS_4Basem14storedFunctionFT_SiU_XfTBpRBBRS2_XMTS2__T_
// SILGEN-NEXT: [[CALLBACK:%.*]] = enum $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Derived, @thick Derived.Type) -> ()>, #Optional.Some!enumelt.1, [[T0]]
// SILGEN-NEXT: [[T0:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Derived, @thick Derived.Type) -> ()>)
// SILGEN-NEXT: destroy_addr [[TEMP]]
// SILGEN-NEXT: dealloc_stack [[TEMP]]
// SILGEN-NEXT: return [[T0]]
// SILGEN: sil hidden [transparent] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFCS_4Basem14storedFunctionFT_SiU_XfTBpRBBRS2_XMTS2__T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Derived, @thick Derived.Type) -> ()
// SILGEN: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type):
// SILGEN-NEXT: [[T0:%.*]] = load %2 : $*Derived
// SILGEN-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// SILGEN-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to $*@callee_owned (@out Int) -> ()
// SILGEN-NEXT: [[VALUE:%.*]] = load [[RESULT_ADDR]] : $*@callee_owned (@out Int) -> ()
// SILGEN-NEXT: function_ref
// SILGEN-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__iSi_XFo__dSi_ : $@convention(thin) (@owned @callee_owned (@out Int) -> ()) -> Int
// SILGEN-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]])
// SILGEN-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!setter.1 : Base -> (() -> Int) -> ()
// SILGEN-NEXT: apply [[FN]]([[NEWVALUE]], [[SELF]])
// SILGEN-NEXT: tuple ()
// SILGEN-NEXT: return
// SILGEN: sil hidden [transparent] [thunk] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FS1_m19finalStoredFunction
// SILGEN: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived):
// SILGEN-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to $*@callee_owned (@out Int) -> ()
// SILGEN-NEXT: [[T0:%.*]] = load %2 : $*Derived
// SILGEN-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// SILGEN-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction
// SILGEN-NEXT: [[RESULT:%.*]] = load [[ADDR]]
// SILGEN-NEXT: strong_retain [[RESULT]]
// SILGEN-NEXT: function_ref
// SILGEN-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__dSi_XFo__iSi_ : $@convention(thin) (@out Int, @owned @callee_owned () -> Int) -> ()
// SILGEN-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]])
// SILGEN-NEXT: store [[T1]] to [[RESULT_ADDR]]
// SILGEN-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned (@out Int) -> () to $Builtin.RawPointer
// SILGEN-NEXT: function_ref
// SILGEN-NEXT: [[T0:%.*]] = function_ref @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFCS_4Basem19finalStoredFunctionFT_SiU_XfTBpRBBRS2_XMTS2__T_
// SILGEN-NEXT: [[CALLBACK:%.*]] = enum $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Derived, @thick Derived.Type) -> ()>, #Optional.Some!enumelt.1, [[T0]]
// SILGEN-NEXT: [[T0:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Derived, @thick Derived.Type) -> ()>)
// SILGEN-NEXT: return [[T0]]
// SILGEN: sil hidden [transparent] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFCS_4Basem19finalStoredFunctionFT_SiU_XfTBpRBBRS2_XMTS2__T_ :
// SILGEN: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type):
// SILGEN-NEXT: [[T0:%.*]] = load %2 : $*Derived
// SILGEN-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// SILGEN-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to $*@callee_owned (@out Int) -> ()
// SILGEN-NEXT: [[VALUE:%.*]] = load [[RESULT_ADDR]] : $*@callee_owned (@out Int) -> ()
// SILGEN-NEXT: function_ref
// SILGEN-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__iSi_XFo__dSi_ : $@convention(thin) (@owned @callee_owned (@out Int) -> ()) -> Int
// SILGEN-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]])
// SILGEN-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction
// SILGEN-NEXT: assign [[NEWVALUE]] to [[ADDR]]
// SILGEN-NEXT: tuple ()
// SILGEN-NEXT: return
protocol ClassAbstractable : class {
typealias Result
var storedFunction: () -> Result { get set }
var finalStoredFunction: () -> Result { get set }
var computedFunction: () -> Result { get set }
}
extension Derived : ClassAbstractable {}
protocol Signatures {
typealias Result
var computedFunction: () -> Result { get set }
}
protocol Implementations {}
extension Implementations {
var computedFunction: () -> Int {
get { return {0} }
set {}
}
}
class ImplementingClass : Implementations, Signatures {}
struct ImplementingStruct : Implementations, Signatures {
var ref: ImplementingClass?
}
class HasDidSet : Base {
override var stored: Int {
didSet {}
}
// Checking this after silgen, but before mandatory inlining, lets us
// test the intent much better.
// SILGEN-LABEL: sil hidden [transparent] @_TFC17materializeForSet9HasDidSetm6storedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout HasDidSet, @thick HasDidSet.Type) -> ()>) {
// SILGEN: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet):
// SILGEN: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Int
// SILGEN: [[T0:%.*]] = function_ref @_TFC17materializeForSet9HasDidSetg6storedSi
// SILGEN: [[T1:%.*]] = apply [[T0]]([[SELF]])
// SILGEN: store [[T1]] to [[T2]] : $*Int
// SILGEN: [[T0:%.*]] = function_ref @_TFFC17materializeForSet9HasDidSetm8computedSiU_FTBpRBBRS0_MS0__T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> ()
// SILGEN: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout HasDidSet, @thick HasDidSet.Type) -> ()>)
// SILGEN: return [[T4]] : $(Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout HasDidSet, @thick HasDidSet.Type) -> ()>)
// SILGEN: }
override var computed: Int {
get { return 0 }
set(value) {}
}
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet9HasDidSetm8computedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout HasDidSet, @thick HasDidSet.Type) -> ()>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet):
// CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Int
// CHECK: [[T0:%.*]] = function_ref @_TFC17materializeForSet9HasDidSetg8computedSi
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: store [[T1]] to [[T2]] : $*Int
// CHECK: [[T0:%.*]] = function_ref @_TFFC17materializeForSet9HasDidSetm8computedSiU_FTBpRBBRS0_MS0__T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> ()
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout HasDidSet, @thick HasDidSet.Type) -> ()>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout HasDidSet, @thick HasDidSet.Type) -> ()>)
// CHECK: }
}
class HasWeak {
weak var weakvar: HasWeak? = nil
}
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet7HasWeakm7weakvarXwGSqS0__ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasWeak) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout HasWeak, @thick HasWeak.Type) -> ()>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasWeak):
// CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Optional<HasWeak>
// CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $HasWeak, #HasWeak.weakvar
// CHECK: [[T1:%.*]] = load_weak [[T0]] : $*@sil_weak Optional<HasWeak>
// CHECK: store [[T1]] to [[T2]] : $*Optional<HasWeak>
// CHECK: [[T0:%.*]] = function_ref @_TFFC17materializeForSet7HasWeakm7weakvarXwGSqS0__U_FTBpRBBRS0_MS0__T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasWeak, @thick HasWeak.Type) -> ()
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout HasWeak, @thick HasWeak.Type) -> ()>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout HasWeak, @thick HasWeak.Type) -> ()>)
// CHECK: }
// rdar://22109071
// Test that we don't use materializeForSet from a protocol extension.
protocol Magic {}
extension Magic {
var hocus: Int {
get { return 0 }
set {}
}
}
struct Wizard : Magic {}
func improve(inout x: Int) {}
func improveWizard(inout wizard: Wizard) {
improve(&wizard.hocus)
}
// SILGEN-LABEL: sil hidden @_TF17materializeForSet13improveWizardFRVS_6WizardT_
// SILGEN: [[IMPROVE:%.*]] = function_ref @_TF17materializeForSet7improveFRSiT_ :
// SILGEN-NEXT: [[TEMP:%.*]] = alloc_stack $Int
// Call the getter and materialize the result in the temporary.
// SILGEN-NEXT: [[T0:%.*]] = load [[WIZARD:.*]] : $*Wizard
// SILGEN-NEXT: function_ref
// SILGEN-NEXT: [[GETTER:%.*]] = function_ref @_TFE17materializeForSetPS_5Magicg5hocusSi
// SILGEN-NEXT: [[WTEMP:%.*]] = alloc_stack $Wizard
// SILGEN-NEXT: store [[T0]] to [[WTEMP]]#1
// SILGEN-NEXT: [[T0:%.*]] = apply [[GETTER]]<Wizard>([[WTEMP]]#1)
// SILGEN-NEXT: store [[T0]] to [[TEMP]]#1
// Call improve.
// SILGEN-NEXT: apply [[IMPROVE]]([[TEMP]]#1)
// SILGEN-NEXT: [[T0:%.*]] = load [[TEMP]]#1
// SILGEN-NEXT: function_ref
// SILGEN-NEXT: [[SETTER:%.*]] = function_ref @_TFE17materializeForSetPS_5Magics5hocusSi
// SILGEN-NEXT: apply [[SETTER]]<Wizard>([[T0]], [[WIZARD]])
// SILGEN-NEXT: dealloc_stack [[WTEMP]]#0
// SILGEN-NEXT: dealloc_stack [[TEMP]]#0
protocol Totalled {
var total: Int { get set }
}
struct Bill : Totalled {
var total: Int
}
// SILGEN-LABEL: sil hidden [transparent] @_TFV17materializeForSet4Billm5totalSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Bill, @thick Bill.Type) -> ()>) {
// SILGEN: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill):
// SILGEN: debug_value %0 : $Builtin.RawPointer
// SILGEN: [[BOX:%.*]] = alloc_box $Bill
// SILGEN: copy_addr [[SELF]] to [initialization] [[BOX]]#1
// SILGEN: [[T0:%.*]] = struct_element_addr [[BOX]]#1 : $*Bill, #Bill.total
// SILGEN: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// SILGEN: [[INIT:%.*]] = function_ref @_TFSqC
// SILGEN: [[META:%.*]] = metatype $@thin Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Bill, @thick Bill.Type) -> ()>.Type
// SILGEN: [[T2:%.*]] = alloc_stack $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Bill, @thick Bill.Type) -> ()>
// SILGEN: [[OPT:%.*]] = apply [[INIT]]<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Bill, @thick Bill.Type) -> ()>([[T2]]#1, [[META]]) : $@convention(thin) <τ_0_0> (@out Optional<τ_0_0>, @thin Optional<τ_0_0>.Type) -> ()
// SILGEN: [[T3:%.*]] = load [[T2]]#1
// SILGEN: [[T4:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T3]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Bill, @thick Bill.Type) -> ()>)
// SILGEN: return [[T4]] : $(Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Bill, @thick Bill.Type) -> ()>)
// SILGEN: }
// SILGEN-LABEL: sil hidden [transparent] [thunk] @_TTWV17materializeForSet4BillS_8TotalledS_FS1_m5totalSi : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Bill, @thick Bill.Type) -> ()>) {
// SILGEN: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill):
// SILGEN: [[T0:%.*]] = function_ref @_TFV17materializeForSet4Billm5totalSi
// SILGEN: [[T1:%.*]] = apply [[T0]]([[BUFFER]], [[STORAGE]], [[SELF]])
// SILGEN: return [[T1]] :
// SILGEN: sil_witness_table hidden Bill: Totalled module materializeForSet {
// SILGEN: method #Totalled.total!getter.1: @_TTWV17materializeForSet4BillS_8TotalledS_FS1_g5totalSi
// SILGEN: method #Totalled.total!setter.1: @_TTWV17materializeForSet4BillS_8TotalledS_FS1_s5totalSi
// SILGEN: method #Totalled.total!materializeForSet.1: @_TTWV17materializeForSet4BillS_8TotalledS_FS1_m5totalSi
// SILGEN: }
protocol AddressOnlySubscript {
typealias Index
subscript(i: Index) -> Index { get set }
}
struct Foo<T>: AddressOnlySubscript {
subscript(i: T) -> T {
get { return i }
set { print("\(i) = \(newValue)") }
}
}
| apache-2.0 | c57d63d6eea796c3638f9bd6e3d56ce1 | 66.029126 | 351 | 0.665556 | 3.553878 | false | false | false | false |
ainopara/Stage1st-Reader | Stage1st/Manager/Navigation/RootNavigationController.swift | 1 | 1586 | //
// RootNavigationController.swift
// Stage1st
//
// Created by Zheng Li on 12/2/16.
// Copyright © 2016 Renaissance. All rights reserved.
//
import UIKit
class RootNavigationController: UINavigationController {
lazy var gagatTransitionHandle: Gagat.TransitionHandle = {
Gagat.configure(for: UIApplication.shared.delegate!.window!!, with: self)
}()
var colorPanRecognizer: UIPanGestureRecognizer { return gagatTransitionHandle.panGestureRecognizer }
override func viewDidLoad() {
super.viewDidLoad()
colorPanRecognizer.maximumNumberOfTouches = 5
interactivePopGestureRecognizer?.isEnabled = false
isNavigationBarHidden = true
}
}
// MARK: - GagatStyleable
extension RootNavigationController: GagatStyleable {
public func shouldStartTransition(with direction: TransitionCoordinator.Direction) -> Bool {
guard AppEnvironment.current.settings.gestureControledNightModeSwitch.value else {
return false
}
guard AppEnvironment.current.settings.manualControlInterfaceStyle.value else {
return false
}
if AppEnvironment.current.settings.nightMode.value == true {
return direction == .up
} else {
return direction == .down
}
}
public func toggleActiveStyle() {
if AppEnvironment.current.settings.nightMode.value == true {
AppEnvironment.current.settings.nightMode.value = false
} else {
AppEnvironment.current.settings.nightMode.value = true
}
}
}
| bsd-3-clause | 1d84225d8a2fbbef09d8daa58981f331 | 27.818182 | 104 | 0.683281 | 5.080128 | false | false | false | false |
rnystrom/GitHawk | Classes/Systems/GithubEmoji.swift | 1 | 1711 | //
// GithubEmoji.swift
// Freetime
//
// Created by Ryan Nystrom on 6/24/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
struct GitHubEmoji {
let emoji: String
let name: String
let aliases: [String]
let tags: [String]
init?(dict: [String: Any]) {
guard let emoji = dict["emoji"] as? String,
let aliases = dict["aliases"] as? [String],
let name = aliases.first,
let tags = dict["tags"] as? [String]
else { return nil }
self.emoji = emoji
self.name = name
self.aliases = aliases
self.tags = tags
}
}
// alias = ":smiley:" (surrounded w/ colons), search = words
typealias EmojiStore = (alias: [String: GitHubEmoji], search: [String: [GitHubEmoji]])
let GithubEmojis: EmojiStore = {
guard let url = Bundle.main.url(forResource: "emoji", withExtension: "json"),
let data = try? Data(contentsOf: url),
let json = try? JSONSerialization.jsonObject(with: data, options: .init(rawValue: 0)),
let dict = json as? [[String: Any]] else { return ([:], [:]) }
let emojis = dict.compactMap { GitHubEmoji(dict: $0) }
var aliasMap = [String: GitHubEmoji]()
var searchMap = [String: [GitHubEmoji]]()
for emoji in emojis {
for alias in emoji.aliases {
aliasMap[":" + alias + ":"] = emoji
// aliases have to be unique
searchMap[alias] = [emoji]
}
// collect all emoji tags
for tag in emoji.tags {
var arr = searchMap[tag] ?? []
arr.append(emoji)
searchMap[tag] = arr
}
}
return (aliasMap, searchMap)
}()
| mit | 777b43113c5e4561c2027a2620b023e2 | 26.142857 | 94 | 0.570175 | 3.90411 | false | false | false | false |
hyperoslo/Wall | Demo/InfinityScrolling/InfinityScrolling/AppDelegate.swift | 2 | 5788 | import UIKit
import Wall
import Fakery
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
lazy var navigationController: UINavigationController = { [unowned self] in
let controller = UINavigationController(rootViewController: self.wallController)
return controller
}()
lazy var wallController: WallController = { [unowned self] in
let controller = WallController()
controller.initializePosts(self.generatePosts(0, to: 10))
controller.title = "Infinity Scrolling".uppercaseString
controller.delegate = self
controller.actionDelegate = self
controller.informationDelegate = self
return controller
}()
lazy var commentController: WallController = { [unowned self] in
let controller = WallController()
controller.verticalOffset = 0
let post = self.generatePosts(0, to: 1, reusableIdentifier: PostDetailTableViewCell.reusableCellIdentifier).first!
let posts = [post] + self.generatePosts(1, to: 6, reusableIdentifier: CommentTableViewCell.reusableIdentifier)
controller.initializePosts(posts)
controller.loadingIndicator.alpha = 0
controller.title = "Post detail".uppercaseString
controller.registerCell(CommentTableViewCell.self, reusableIdentifier: CommentTableViewCell.reusableIdentifier)
controller.registerCell(PostDetailTableViewCell.self, reusableIdentifier: PostDetailTableViewCell.reusableCellIdentifier)
controller.delegate = self
controller.actionDelegate = self
controller.informationDelegate = self
controller.commentInformationDelegate = self
return controller
}()
let faker = Faker()
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
ImageList.Basis.reportButton = "reportButton"
return true
}
func generatePosts(from: Int, to: Int, reusableIdentifier: String = PostTableViewCell.reusableIdentifier) -> [PostConvertible] {
var posts = [PostConvertible]()
for i in from...to {
autoreleasepool({
var author = Author(name: "")
if let imageURL = NSURL(string: "http://lorempixel.com/75/75?type=avatar&id=\(i)") {
author = Author(name: faker.name.name(),
avatar: imageURL)
}
var media = [Media]()
var mediaCount = 0
var likes = 0
var commentCount = 0
var seen = 0
var liked = true
if i % 4 == 0 {
mediaCount = 4
commentCount = 3
likes = 3
seen = 4
liked = false
} else if i % 3 == 0 {
mediaCount = 2
commentCount = 1
likes = 1
seen = 2
liked = true
} else if i % 2 == 0 {
mediaCount = 1
commentCount = 4
likes = 4
seen = 6
liked = false
}
for x in 0..<mediaCount {
if let imageURL = NSURL(string: "http://lorempixel.com/250/250/?type=attachment&id=\(i)\(x)") {
media.append(Media(kind: .Image, source: imageURL))
}
}
let sencenceCount = Int(arc4random_uniform(8) + 1)
let post = Post(
id: i,
text: faker.lorem.sentences(amount: sencenceCount) + " " + faker.internet.url(),
publishDate: "3 hours ago",
author: author,
media: media
)
post.reusableIdentifier = reusableIdentifier
post.likeCount = likes
post.seenCount = seen
post.commentCount = commentCount
post.liked = liked
posts.append(post)
})
}
return posts
}
}
extension AppDelegate: WallControllerDelegate {
func shouldFetchMoreInformation() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { [unowned self] in
let posts = self.generatePosts(0, to: 10)
dispatch_async(dispatch_get_main_queue()) {
self.wallController.appendPosts(posts)
}
}
}
func shouldRefreshPosts(refreshControl: UIRefreshControl) {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1.5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
refreshControl.endRefreshing()
}
}
func didTapCell(id: Int, index: Int) {
print("Cell selected")
if navigationController.visibleViewController != commentController {
commentController.cachedHeights.removeAll()
navigationController.pushViewController(commentController, animated: true)
}
}
func willDisplayCell(cell: PostTableViewCell, id: Int, index: Int) { }
}
extension AppDelegate: PostActionDelegate {
func likeButtonDidPress(postID: Int) {
}
func commentsButtonDidPress(postID: Int) {
}
}
extension AppDelegate: CommentInformationDelegate {
func commentAuthorDidTap(commentID: Int) {
print("Comment's author")
}
func commentReportButtonDidPress(commentID: Int) {
print("Comment's report")
}
}
extension AppDelegate: PostInformationDelegate {
func likesInformationDidPress(postID: Int) {
print("Likes")
}
func commentsInformationDidPress(postID: Int) {
print("Comments")
commentController.cachedHeights.removeAll()
navigationController.pushViewController(commentController, animated: true)
}
func seenInformationDidPress(postID: Int) {
print("Seen")
}
func authorDidTap(postID: Int) {
print("Author")
}
func mediaDidTap(postID: Int, kind: Media.Kind, index: Int) {
print("Index \(index)")
}
func groupDidTap(postID: Int) {
}
func reportButtonDidPress(postID: Int) {
}
}
| mit | ba8ed2f4210c4f59a5905e86cb0b21ac | 27.234146 | 130 | 0.668798 | 4.593651 | false | false | false | false |
cplaverty/KeitaiWaniKani | WaniKaniKit/Database/DatabaseConnectionFactory.swift | 1 | 2727 | //
// DatabaseConnectionFactory.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
import FMDB
import os
public protocol DatabaseConnectionFactory {
func makeDatabaseQueue() -> FMDatabaseQueue?
func destroyDatabase() throws
}
open class DefaultDatabaseConnectionFactory: DatabaseConnectionFactory {
public let url: URL
public init(url: URL) {
self.url = url
}
public func makeDatabaseQueue() -> FMDatabaseQueue? {
os_log("Creating database queue using SQLite %@ and FMDB %@ at %@", type: .info, FMDatabase.sqliteLibVersion(), FMDatabase.fmdbUserVersion(), url.path)
return FMDatabaseQueue(url: url)
}
public func destroyDatabase() throws {
os_log("Removing database at %@", type: .info, url.path)
try FileManager.default.removeItem(at: url)
}
}
public class AppGroupDatabaseConnectionFactory: DefaultDatabaseConnectionFactory {
public init() {
let groupIdentifier = "group.uk.me.laverty.KeitaiWaniKani"
guard let appGroupContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier) else {
os_log("Can't find group shared directory for group identifier %@", type: .fault, groupIdentifier)
fatalError("Can't find group shared directory for group identifier \(groupIdentifier)")
}
super.init(url: appGroupContainerURL.appendingPathComponent("WaniKaniData-v2.db"))
let legacyPersistentStoreURL = appGroupContainerURL.appendingPathComponent("WaniKaniData.sqlite")
if FileManager.default.fileExists(atPath: legacyPersistentStoreURL.path) {
os_log("Trying to remove legacy store at %@", type: .debug, legacyPersistentStoreURL.path)
try? FileManager.default.removeItem(at: legacyPersistentStoreURL)
}
}
public override func makeDatabaseQueue() -> FMDatabaseQueue? {
let databaseQueue = super.makeDatabaseQueue()
excludeStoreFromBackup()
return databaseQueue
}
private func excludeStoreFromBackup() {
var url = super.url
do {
var resourceValues = try url.resourceValues(forKeys: [.isExcludedFromBackupKey])
if resourceValues.isExcludedFromBackup != true {
os_log("Excluding store at %@ from backup", type: .debug, url.path)
resourceValues.isExcludedFromBackup = true
try url.setResourceValues(resourceValues)
}
} catch {
os_log("Ignoring error when trying to exclude store at %@ from backup: %@", type: .error, url.path, error as NSError)
}
}
}
| mit | c359aa0eabb73f2cc75b33aff88707cd | 37.394366 | 159 | 0.67168 | 5.095327 | false | false | false | false |
ngoctuanqt/IOS | Twitter/Pods/LBTAComponents/LBTAComponents/Classes/CachedImageView.swift | 1 | 2889 | //
// UIImageView+Cache.swift
// streamapp
//
// Created by Brian Voong on 7/29/16.
// Copyright © 2016 luxeradio. All rights reserved.
//
import UIKit
/**
A convenient UIImageView to load and cache images.
*/
open class CachedImageView: UIImageView {
open static let imageCache = NSCache<NSString, DiscardableImageCacheItem>()
open var shouldUseEmptyImage = true
private var urlStringForChecking: String?
private var emptyImage: UIImage?
public convenience init(cornerRadius: CGFloat = 0, tapCallback: @escaping (() ->())) {
self.init(cornerRadius: cornerRadius, emptyImage: nil)
self.tapCallback = tapCallback
isUserInteractionEnabled = true
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
}
func handleTap() {
tapCallback?()
}
private var tapCallback: (() -> ())?
public init(cornerRadius: CGFloat = 0, emptyImage: UIImage? = nil) {
super.init(frame: .zero)
contentMode = .scaleAspectFill
clipsToBounds = true
layer.cornerRadius = cornerRadius
self.emptyImage = emptyImage
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Easily load an image from a URL string and cache it to reduce network overhead later.
- parameter urlString: The url location of your image, usually on a remote server somewhere.
- parameter completion: Optionally execute some task after the image download completes
*/
open func loadImage(urlString: String, completion: (() -> ())? = nil) {
image = nil
self.urlStringForChecking = urlString
let urlKey = urlString as NSString
if let cachedItem = CachedImageView.imageCache.object(forKey: urlKey) {
image = cachedItem.image
completion?()
return
}
guard let url = URL(string: urlString) else {
if shouldUseEmptyImage {
image = emptyImage
}
return
}
URLSession.shared.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in
if error != nil {
return
}
DispatchQueue.main.async {
if let image = UIImage(data: data!) {
let cacheItem = DiscardableImageCacheItem(image: image)
CachedImageView.imageCache.setObject(cacheItem, forKey: urlKey)
if urlString == self?.urlStringForChecking {
self?.image = image
completion?()
}
}
}
}).resume()
}
}
| mit | 4b3ea891794eb8fd0ca289bb529bdc35 | 30.053763 | 105 | 0.576524 | 5.270073 | false | false | false | false |
tavultesoft/keymanweb | ios/engine/KMEI/KeymanEngine/Classes/KeyboardKeymanPackage.swift | 1 | 1412 | //
// KeyboardKeymanPackage.swift
// KeymanEngine
//
// Created by Randy Boring on 3/14/19.
// Copyright © 2019 SIL International. All rights reserved.
//
import Foundation
public class KeyboardKeymanPackage : TypedKeymanPackage<InstallableKeyboard> {
internal var keyboards: [KMPKeyboard]!
override internal init(metadata: KMPMetadata, folder: URL) {
super.init(metadata: metadata, folder: folder)
self.keyboards = []
if let packagedKeyboards = metadata.keyboards {
for keyboard in packagedKeyboards {
keyboard.packageId = self.id
if(keyboard.isValid && FileManager.default.fileExists(atPath: self.sourceFolder.appendingPathComponent("\(keyboard.keyboardId).js").path)) {
keyboards.append(keyboard)
} else {
SentryManager.breadcrumbAndLog("\(keyboard.name) not valid / corresponding file not found")
}
}
}
self.setInstallableResourceSets(for: keyboards)
}
public override func defaultInfoHtml() -> String {
let formatString = NSLocalizedString("package-default-found-keyboards", bundle: engineBundle, comment: "See Localized.stringsdict")
var str = String.localizedStringWithFormat(formatString, keyboards.count) + "<br/>"
for keyboard in keyboards {
str += keyboard.keyboardId + "<br/>"
}
return str
}
override var resources: [AnyKMPResource] {
return keyboards
}
}
| apache-2.0 | 24f6e3b8dcbcda602f958c09a5b48771 | 29.673913 | 148 | 0.700213 | 4.46519 | false | false | false | false |
chanhx/Octogit | iGithub/Views/Cell/InfoNumberCell.swift | 2 | 2023 | //
// InfoNumberCell.swift
// iGithub
//
// Created by Chan Hocheung on 20/09/2017.
// Copyright © 2017 Hocheung. All rights reserved.
//
import Foundation
class InfoNumberCell: UITableViewCell {
let infoLabel = UILabel()
private let numberLabel = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
infoLabel.layer.isOpaque = true
infoLabel.backgroundColor = .white
let numberLabelHeight: CGFloat = 20
numberLabel.font = UIFont.systemFont(ofSize: 16)
numberLabel.textColor = UIColor(netHex: 0x464F58)
numberLabel.backgroundColor = UIColor(netHex: 0xE8E9EA)
numberLabel.layer.cornerRadius = numberLabelHeight / 2
numberLabel.layer.masksToBounds = true
contentView.addSubviews([infoLabel, numberLabel])
NSLayoutConstraint.activate([
infoLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
infoLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 11.5),
infoLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -11.5),
numberLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
numberLabel.centerYAnchor.constraint(equalTo: infoLabel.centerYAnchor),
numberLabel.heightAnchor.constraint(equalToConstant: numberLabelHeight)
])
}
var number: Int? {
didSet {
guard let number = number else { return }
numberLabel.text = " \(number) "
numberLabel.isHidden = false
}
}
override func prepareForReuse() {
numberLabel.isHidden = true
}
}
| gpl-3.0 | e428dbd774efa94f3dea756879b7aeab | 31.095238 | 98 | 0.641939 | 5.184615 | false | false | false | false |
ericvergnaud/antlr4 | runtime/Swift/Sources/Antlr4/dfa/DFAState.swift | 4 | 5658 | ///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
///
/// A DFA state represents a set of possible ATN configurations.
/// As Aho, Sethi, Ullman p. 117 says "The DFA uses its state
/// to keep track of all possible states the ATN can be in after
/// reading each input symbol. That is to say, after reading
/// input a1a2..an, the DFA is in a state that represents the
/// subset T of the states of the ATN that are reachable from the
/// ATN's start state along some path labeled a1a2..an."
/// In conventional NFA→DFA conversion, therefore, the subset T
/// would be a bitset representing the set of states the
/// ATN could be in. We need to track the alt predicted by each
/// state as well, however. More importantly, we need to maintain
/// a stack of states, tracking the closure operations as they
/// jump from rule to rule, emulating rule invocations (method calls).
/// I have to add a stack to simulate the proper lookahead sequences for
/// the underlying LL grammar from which the ATN was derived.
///
/// I use a set of ATNConfig objects not simple states. An ATNConfig
/// is both a state (ala normal conversion) and a RuleContext describing
/// the chain of rules (if any) followed to arrive at that state.
///
/// A DFA state may have multiple references to a particular state,
/// but with different ATN contexts (with same or different alts)
/// meaning that state was reached via a different set of rule invocations.
///
public final class DFAState: Hashable, CustomStringConvertible {
public internal(set) var stateNumber = ATNState.INVALID_STATE_NUMBER
public internal(set) var configs: ATNConfigSet
///
/// `edges[symbol]` points to target of symbol. Shift up by 1 so (-1)
/// _org.antlr.v4.runtime.Token#EOF_ maps to `edges[0]`.
///
public internal(set) var edges: [DFAState?]!
public internal(set) var isAcceptState = false
///
/// if accept state, what ttype do we match or alt do we predict?
/// This is set to _org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER_ when _#predicates_`!=null` or
/// _#requiresFullContext_.
///
public internal(set) var prediction = ATN.INVALID_ALT_NUMBER
public internal(set) var lexerActionExecutor: LexerActionExecutor?
///
/// Indicates that this state was created during SLL prediction that
/// discovered a conflict between the configurations in the state. Future
/// _org.antlr.v4.runtime.atn.ParserATNSimulator#execATN_ invocations immediately jumped doing
/// full context prediction if this field is true.
///
public internal(set) var requiresFullContext = false
///
/// During SLL parsing, this is a list of predicates associated with the
/// ATN configurations of the DFA state. When we have predicates,
/// _#requiresFullContext_ is `false` since full context prediction evaluates predicates
/// on-the-fly. If this is not null, then _#prediction_ is
/// _org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER_.
///
/// We only use these for non-_#requiresFullContext_ but conflicting states. That
/// means we know from the context (it's $ or we don't dip into outer
/// context) that it's an ambiguity not a conflict.
///
/// This list is computed by _org.antlr.v4.runtime.atn.ParserATNSimulator#predicateDFAState_.
///
public internal(set) var predicates: [PredPrediction]?
///
/// mutex for states changes.
///
internal private(set) var mutex = Mutex()
///
/// Map a predicate to a predicted alternative.
///
public final class PredPrediction: CustomStringConvertible {
public let pred: SemanticContext
// never null; at least SemanticContext.Empty.Instance
public let alt: Int
public init(_ pred: SemanticContext, _ alt: Int) {
self.alt = alt
self.pred = pred
}
public var description: String {
return "(\(pred),\(alt))"
}
}
public init(_ configs: ATNConfigSet) {
self.configs = configs
}
///
/// Get the set of all alts mentioned by all ATN configurations in this
/// DFA state.
///
public func getAltSet() -> Set<Int>? {
return configs.getAltSet()
}
public func hash(into hasher: inout Hasher) {
hasher.combine(configs)
}
public var description: String {
var buf = "\(stateNumber):\(configs)"
if isAcceptState {
buf += "=>"
if let predicates = predicates {
buf += String(describing: predicates)
}
else {
buf += String(prediction)
}
}
return buf
}
}
///
/// Two _org.antlr.v4.runtime.dfa.DFAState_ instances are equal if their ATN configuration sets
/// are the same. This method is used to see if a state already exists.
///
/// Because the number of alternatives and number of ATN configurations are
/// finite, there is a finite number of DFA states that can be processed.
/// This is necessary to show that the algorithm terminates.
///
/// Cannot test the DFA state numbers here because in
/// _org.antlr.v4.runtime.atn.ParserATNSimulator#addDFAState_ we need to know if any other state
/// exists that has this exact set of ATN configurations. The
/// _#stateNumber_ is irrelevant.
///
public func ==(lhs: DFAState, rhs: DFAState) -> Bool {
if lhs === rhs {
return true
}
return (lhs.configs == rhs.configs)
}
| bsd-3-clause | 8bf53f8353ba6d251dc8baf3df63db59 | 35.74026 | 102 | 0.665253 | 4.289613 | false | true | false | false |
srn214/Floral | Floral/Pods/JXPhotoBrowser/Source/Core/JXPhotoBrowserBaseCell.swift | 1 | 10305 | //
// JXPhotoBrowserBaseCell.swift
// JXPhotoBrowser
//
// Created by JiongXing on 2018/10/14.
//
import UIKit
open class JXPhotoBrowserBaseCell: UICollectionViewCell {
/// ImageView
open var imageView = UIImageView()
/// 图片缩放容器
open var imageContainer = UIScrollView()
/// 图片允许的最大放大倍率
open var imageMaximumZoomScale: CGFloat = 2.0
/// 单击时回调
open var clickCallback: ((UITapGestureRecognizer) -> Void)?
/// 长按时回调
open var longPressedCallback: ((UILongPressGestureRecognizer) -> Void)?
/// 图片拖动时回调
open var panChangedCallback: ((_ scale: CGFloat) -> Void)?
/// 图片拖动松手回调。isDown: 是否向下
open var panReleasedCallback: ((_ isDown: Bool) -> Void)?
/// 是否需要添加长按手势。子类可重写本属性,返回`false`即可避免添加长按手势
open var isNeededLongPressGesture: Bool {
return true
}
/// 记录pan手势开始时imageView的位置
private var beganFrame = CGRect.zero
/// 记录pan手势开始时,手势位置
private var beganTouch = CGPoint.zero
//
// MARK: - Life Cycle
//
/// 初始化
public override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageContainer)
imageContainer.maximumZoomScale = imageMaximumZoomScale
imageContainer.delegate = self
imageContainer.showsVerticalScrollIndicator = false
imageContainer.showsHorizontalScrollIndicator = false
if #available(iOS 11.0, *) {
imageContainer.contentInsetAdjustmentBehavior = .never
}
imageContainer.addSubview(imageView)
imageView.clipsToBounds = true
// 长按手势
if isNeededLongPressGesture {
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(onLongPress(_:)))
contentView.addGestureRecognizer(longPress)
}
// 双击手势
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(onDoubleClick(_:)))
doubleTap.numberOfTapsRequired = 2
contentView.addGestureRecognizer(doubleTap)
// 单击手势
let singleTap = UITapGestureRecognizer(target: self, action: #selector(onClick(_:)))
contentView.addGestureRecognizer(singleTap)
singleTap.require(toFail: doubleTap)
// 拖动手势
let pan = UIPanGestureRecognizer(target: self, action: #selector(onPan(_:)))
pan.delegate = self
// 必须加在图片容器上。不能加在contentView上,否则长图下拉不能触发
imageContainer.addGestureRecognizer(pan)
// 子类作进一步初始化
didInit()
}
/// 初始化完成时调用,空实现。子类可重写本方法以作进一步初始化
open func didInit() {
// 子类重写
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func layoutSubviews() {
super.layoutSubviews()
imageContainer.frame = contentView.bounds
imageContainer.setZoomScale(1.0, animated: false)
imageView.frame = fitFrame
imageContainer.setZoomScale(1.0, animated: false)
}
}
//
// MARK: - Private
//
extension JXPhotoBrowserBaseCell {
/// 计算图片复位坐标
private var resettingCenter: CGPoint {
let deltaWidth = bounds.width - imageContainer.contentSize.width
let offsetX = deltaWidth > 0 ? deltaWidth * 0.5 : 0
let deltaHeight = bounds.height - imageContainer.contentSize.height
let offsetY = deltaHeight > 0 ? deltaHeight * 0.5 : 0
return CGPoint(x: imageContainer.contentSize.width * 0.5 + offsetX,
y: imageContainer.contentSize.height * 0.5 + offsetY)
}
/// 计算图片适合的size
private var fitSize: CGSize {
guard let image = imageView.image else {
return CGSize.zero
}
var width: CGFloat
var height: CGFloat
if imageContainer.bounds.width < imageContainer.bounds.height {
// 竖屏
width = imageContainer.bounds.width
height = (image.size.height / image.size.width) * width
} else {
// 横屏
height = imageContainer.bounds.height
width = (image.size.width / image.size.height) * height
if width > imageContainer.bounds.width {
width = imageContainer.bounds.width
height = (image.size.height / image.size.width) * width
}
}
return CGSize(width: width, height: height)
}
/// 计算图片适合的frame
private var fitFrame: CGRect {
let size = fitSize
let y = imageContainer.bounds.height > size.height
? (imageContainer.bounds.height - size.height) * 0.5 : 0
let x = imageContainer.bounds.width > size.width
? (imageContainer.bounds.width - size.width) * 0.5 : 0
return CGRect(x: x, y: y, width: size.width, height: size.height)
}
/// 复位ImageView
private func resetImageView() {
// 如果图片当前显示的size小于原size,则重置为原size
let size = fitSize
let needResetSize = imageView.bounds.size.width < size.width
|| imageView.bounds.size.height < size.height
UIView.animate(withDuration: 0.25) {
self.imageView.center = self.resettingCenter
if needResetSize {
self.imageView.bounds.size = size
}
}
}
}
//
// MARK: - Events
//
extension JXPhotoBrowserBaseCell {
/// 响应拖动
@objc private func onPan(_ pan: UIPanGestureRecognizer) {
guard imageView.image != nil else {
return
}
switch pan.state {
case .began:
beganFrame = imageView.frame
beganTouch = pan.location(in: imageContainer)
case .changed:
let result = panResult(pan)
imageView.frame = result.0
panChangedCallback?(result.1)
case .ended, .cancelled:
imageView.frame = panResult(pan).0
let isDown = pan.velocity(in: self).y > 0
self.panReleasedCallback?(isDown)
if !isDown {
resetImageView()
}
default:
resetImageView()
}
}
/// 计算拖动时图片应调整的frame和scale值
private func panResult(_ pan: UIPanGestureRecognizer) -> (CGRect, CGFloat) {
// 拖动偏移量
let translation = pan.translation(in: imageContainer)
let currentTouch = pan.location(in: imageContainer)
// 由下拉的偏移值决定缩放比例,越往下偏移,缩得越小。scale值区间[0.3, 1.0]
let scale = min(1.0, max(0.3, 1 - translation.y / bounds.height))
let width = beganFrame.size.width * scale
let height = beganFrame.size.height * scale
// 计算x和y。保持手指在图片上的相对位置不变。
// 即如果手势开始时,手指在图片X轴三分之一处,那么在移动图片时,保持手指始终位于图片X轴的三分之一处
let xRate = (beganTouch.x - beganFrame.origin.x) / beganFrame.size.width
let currentTouchDeltaX = xRate * width
let x = currentTouch.x - currentTouchDeltaX
let yRate = (beganTouch.y - beganFrame.origin.y) / beganFrame.size.height
let currentTouchDeltaY = yRate * height
let y = currentTouch.y - currentTouchDeltaY
return (CGRect(x: x.isNaN ? 0 : x, y: y.isNaN ? 0 : y, width: width, height: height), scale)
}
/// 响应单击
@objc private func onClick(_ tap: UITapGestureRecognizer) {
clickCallback?(tap)
}
/// 响应双击
@objc private func onDoubleClick(_ tap: UITapGestureRecognizer) {
// 如果当前没有任何缩放,则放大到目标比例,否则重置到原比例
if imageContainer.zoomScale == 1.0 {
// 以点击的位置为中心,放大
let pointInView = tap.location(in: imageView)
let width = imageContainer.bounds.size.width / imageContainer.maximumZoomScale
let height = imageContainer.bounds.size.height / imageContainer.maximumZoomScale
let x = pointInView.x - (width / 2.0)
let y = pointInView.y - (height / 2.0)
imageContainer.zoom(to: CGRect(x: x, y: y, width: width, height: height), animated: true)
} else {
imageContainer.setZoomScale(1.0, animated: true)
}
}
/// 响应长按
@objc private func onLongPress(_ press: UILongPressGestureRecognizer) {
if press.state == .began {
longPressedCallback?(press)
}
}
}
//
// MARK: - UIScrollViewDelegate
//
extension JXPhotoBrowserBaseCell: UIScrollViewDelegate {
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
imageView.center = resettingCenter
}
}
//
// MARK: - UIGestureRecognizerDelegate
//
extension JXPhotoBrowserBaseCell: UIGestureRecognizerDelegate {
open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
// 只响应pan手势
guard let pan = gestureRecognizer as? UIPanGestureRecognizer else {
return true
}
let velocity = pan.velocity(in: self)
// 向上滑动时,不响应手势
if velocity.y < 0 {
return false
}
// 横向滑动时,不响应pan手势
if abs(Int(velocity.x)) > Int(velocity.y) {
return false
}
// 向下滑动,如果图片顶部超出可视区域,不响应手势
if imageContainer.contentOffset.y > 0 {
return false
}
// 响应允许范围内的下滑手势
return true
}
}
| mit | ce0a1a30d66563af6a7094dea04c7d43 | 30.887755 | 106 | 0.606187 | 4.372668 | false | false | false | false |
ArtisOracle/libSwiftCal | libSwiftCal/Duration.swift | 1 | 7740 | //
// Duration.swift
// libSwiftCal
//
// Created by Stefan Arambasich on 2/21/15.
//
// Copyright (c) 2015 Stefan Arambasich. 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.
/**
Represents a duration in time.
*/
public class Duration: CalendarObject, FloatLiteralConvertible, Printable {
public static let keyLetters: [Character] = ["W", "D", "H", "M", "S"]
public static let otherCharacters: [Character] = ["P", "T", "+", "-"]
public private(set) var weeks = 0
public private(set) var days = 0
public private(set) var hours: Hour = 0
public private(set) var minutes: Minute = 0
public private(set) var seconds: Second = 0
public var negative: Bool {
return weeks < 0 || days < 0 || hours < 0 || minutes < 0 || seconds < 0
}
public var timeInterval: NSTimeInterval {
var sumArr = [NSTimeInterval]()
sumArr.append(Conversions.Time.SecondsInAWeek * NSTimeInterval(self.weeks))
sumArr.append(Conversions.Time.SecondsInADay * NSTimeInterval(self.days))
sumArr.append(Conversions.Time.SecondsInAnHour * NSTimeInterval(self.hours))
sumArr.append(Conversions.Time.SecondsInAMinute * NSTimeInterval(self.minutes))
sumArr.append(NSTimeInterval(self.seconds))
return sumArr.reduce(0.0, combine: { $0 + $1 })
}
public required init() {
super.init()
}
public convenience init(string: String) {
var dictionary = [String : AnyObject]()
var period = string.uppercaseString
var negative = period.contains("-", options: .CaseInsensitiveSearch)
period = period.stringByReplacingOccurrencesOfString(String("+"), withString: "")
period = period.stringByReplacingOccurrencesOfString(String("-"), withString: "")
period = period.stringByReplacingOccurrencesOfString(String("P"), withString: "")
var periods = period.componentsSeparatedByString("T")
var date = periods.first!
var time: String?
if periods.count == 2 {
time = periods.last!
}
var curDateStartIdx = date.endIndex
var curDateEndIdx = date.endIndex
for var i = date.len - 1; i >= 0; i-- {
var char = date[advance(date.startIndex, i)]
if contains(Duration.keyLetters, char) {
let intStr = date.substringWithRange(Range(start: curDateStartIdx, end: curDateEndIdx))
let scanner = NSScanner(string: intStr)
var int = Int.max
if scanner.scanInteger(&int) {
if int != Int.max {
dictionary[String(char)] = negative ? -int : int
}
}
curDateStartIdx = advance(curDateStartIdx, -1)
curDateEndIdx = curDateStartIdx
} else {
curDateStartIdx = advance(curDateStartIdx, -1)
}
}
if let time = time {
var curTimeStartIdx = time.startIndex
var curTimeEndIdx = curTimeStartIdx
for i in 0 ..< time.len {
var char = time[advance(time.startIndex, i)]
if contains(Duration.keyLetters, char) {
let intStr = time.substringWithRange(Range(start: curTimeStartIdx, end: curTimeEndIdx))
let scanner = NSScanner(string: intStr)
var int: Int = -1
if scanner.scanInteger(&int) {
if int != -1 {
dictionary[String(char)] = negative ? -int : int
}
}
if i < time.len {
curTimeStartIdx = advance(time.startIndex, i + 1)
curTimeEndIdx = curTimeStartIdx
}
} else {
curTimeEndIdx = advance(curTimeEndIdx, 1)
}
}
}
self.init(dictionary: dictionary)
}
// MARK: - FloatLiteralConvertible
public required init(floatLiteral value: FloatLiteralType) {
super.init()
var negative = value < 0
var curValue = value
let weekVal = Int(curValue / NSTimeInterval(Conversions.Time.SecondsInAWeek))
self.weeks = weekVal
curValue -= Conversions.Time.SecondsInAWeek * NSTimeInterval(weekVal)
let dayVal = Int(curValue / NSTimeInterval(Conversions.Time.SecondsInADay))
self.days = dayVal
curValue -= Conversions.Time.SecondsInADay * NSTimeInterval(dayVal)
let hourVal = Int(curValue / NSTimeInterval(Conversions.Time.SecondsInAnHour))
self.hours = hourVal
curValue -= Conversions.Time.SecondsInAnHour * NSTimeInterval(hourVal)
let minVal = Int(curValue / NSTimeInterval(Conversions.Time.SecondsInAMinute))
self.minutes = minVal
curValue -= Conversions.Time.SecondsInAMinute * NSTimeInterval(minVal)
self.seconds = Int(curValue)
}
// MARK: - iCalendarSerializable
public override func serializeToiCal() -> String {
return self.description
}
// MARK: - NSCoding
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Printable
public override var description: String {
var durationString = (self.negative ? "-" : "") + "P"
let w = abs(self.weeks)
if w > 0 {
durationString += "\(w)W"
}
let d = abs(self.days)
if d > 0 {
durationString += "\(d)D"
}
var hasTime = false
let addTime = { () -> Void in
if !hasTime {
hasTime = true
durationString += "T"
}
}
let h = abs(self.hours)
if h > 0 {
addTime()
durationString += "\(h)H"
}
let m = abs(self.minutes)
if m > 0 {
addTime()
durationString += "\(m)M"
}
let s = abs(self.seconds)
if s > 0 {
addTime()
durationString += "\(s)S"
}
return durationString
}
// MARK: - Serializable
public required init(dictionary: [String : AnyObject]) {
super.init(dictionary: dictionary)
}
public override var serializationKeys: [String] {
return super.serializationKeys + ["W", "D", "H", "M", "S"]
}
}
| mit | d64e79a32434c81c1e98f81a112a52eb | 35.168224 | 107 | 0.573514 | 4.654239 | false | false | false | false |
naokits/my-programming-marathon | iPhoneSensorDemo/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift | 58 | 9404 | //
// Observable+Creation.swift
// Rx
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
extension Observable {
// MARK: create
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func create(subscribe: (AnyObserver<E>) -> Disposable) -> Observable<E> {
return AnonymousObservable(subscribe)
}
// MARK: empty
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func empty() -> Observable<E> {
return Empty<E>()
}
// MARK: never
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func never() -> Observable<E> {
return Never()
}
// MARK: just
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func just(element: E) -> Observable<E> {
return Just(element: element)
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- parameter: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func just(element: E, scheduler: ImmediateSchedulerType) -> Observable<E> {
return JustScheduled(element: element, scheduler: scheduler)
}
// MARK: fail
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func error(error: ErrorType) -> Observable<E> {
return Error(error: error)
}
// MARK: of
/**
This method creates a new Observable instance with a variable number of elements.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription.
- returns: The observable sequence whose elements are pulled from the given arguments.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func of(elements: E ..., scheduler: ImmediateSchedulerType? = nil) -> Observable<E> {
return Sequence(elements: elements, scheduler: scheduler)
}
// MARK: defer
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func deferred(observableFactory: () throws -> Observable<E>)
-> Observable<E> {
return Deferred(observableFactory: observableFactory)
}
/**
Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler
to run the loop send out observer messages.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter initialState: Initial state.
- parameter condition: Condition to terminate generation (upon returning `false`).
- parameter iterate: Iteration step function.
- parameter scheduler: Scheduler on which to run the generator loop.
- returns: The generated sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func generate(initialState initialState: E, condition: E throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: E throws -> E) -> Observable<E> {
return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler)
}
/**
Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages.
- seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html)
- parameter element: Element to repeat.
- parameter scheduler: Scheduler to run the producer loop on.
- returns: An observable sequence that repeats the given element infinitely.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func repeatElement(element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RepeatElement(element: element, scheduler: scheduler)
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html)
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func using<R: Disposable>(resourceFactory: () throws -> R, observableFactory: R throws -> Observable<E>) -> Observable<E> {
return Using(resourceFactory: resourceFactory, observableFactory: observableFactory)
}
}
extension Observable where Element : SignedIntegerType {
/**
Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages.
- seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html)
- parameter start: The value of the first integer in the sequence.
- parameter count: The number of sequential integers to generate.
- parameter scheduler: Scheduler to run the generator loop on.
- returns: An observable sequence that contains a range of sequential integral numbers.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func range(start start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RangeProducer<E>(start: start, count: count, scheduler: scheduler)
}
}
extension SequenceType {
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func toObservable(scheduler: ImmediateSchedulerType? = nil) -> Observable<Generator.Element> {
return Sequence(elements: Array(self), scheduler: scheduler)
}
}
extension Array {
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func toObservable(scheduler: ImmediateSchedulerType? = nil) -> Observable<Generator.Element> {
return Sequence(elements: self, scheduler: scheduler)
}
} | mit | f92e2a762ef3509ef0db04ab1713d392 | 41.940639 | 202 | 0.720089 | 4.641165 | false | false | false | false |
sxyx2008/GolangStudy | GolangStudy/XmlParseUtil.swift | 3 | 1772 | //
// XmlParseUtil.swift
// GolangStudy
//
// Created by scott on 14-10-26.
// Copyright (c) 2014年 scott. All rights reserved.
//
import Foundation
class XmlParseUtil:NSObject,NSXMLParserDelegate {
var course:Course?
var courseSet:[Course] = []
var elementname:String = String()
var name:String = String()
var desc:String = String()
var chapter:String = String()
init(name:String){
super.init()
let path = NSBundle.mainBundle().pathForResource(name, ofType: "xml")!
let xmlparser:NSXMLParser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: path)!)!
xmlparser.delegate = self
xmlparser.parse()
}
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {
elementname = elementName
if elementName == "Content"{
name = String()
desc = String()
chapter = String()
}
}
func parser(parser: NSXMLParser!, foundCharacters string: String!) {
let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if elementname == "Name"{
name += data
} else if elementname == "Abstract" {
desc += data
} else if elementname == "Chapter" {
chapter += data
}
}
func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {
if elementName == "Content"{
course = Course(name: name, desc: desc, chapter: chapter)
courseSet.append(course!)
}
}
}
| mit | 993bec7d8d42713e62192fc68af58258 | 30.052632 | 181 | 0.611864 | 4.770889 | false | false | false | false |
criticalmaps/criticalmaps-ios | CriticalMapsKit/Sources/SharedModels/AppearanceSettings.swift | 1 | 1121 | import ComposableArchitecture
import Foundation
import enum UIKit.UIUserInterfaceStyle
/// A structure that represents a users appearance settings.
public struct AppearanceSettings: Codable, Equatable {
@BindableState public var appIcon: AppIcon
@BindableState public var colorScheme: ColorScheme
public init(appIcon: AppIcon = .appIcon2, colorScheme: ColorScheme = .system) {
self.appIcon = appIcon
self.colorScheme = colorScheme
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.appIcon = (try? container.decode(AppIcon.self, forKey: .appIcon)) ?? .appIcon2
self.colorScheme = (try? container.decode(ColorScheme.self, forKey: .colorScheme)) ?? .system
}
}
public extension AppearanceSettings {
enum ColorScheme: String, CaseIterable, Codable {
case system
case dark
case light
public var userInterfaceStyle: UIUserInterfaceStyle {
switch self {
case .system:
return .unspecified
case .dark:
return .dark
case .light:
return .light
}
}
}
}
| mit | 7746440e162a2fe30719fb8feada2d4d | 27.74359 | 97 | 0.710972 | 4.670833 | false | false | false | false |
danielsaidi/Vandelay | Sources/Vandelay/ImportResult.swift | 1 | 1353 | //
// ImportResult.swift
// Vandelay
//
// Created by Daniel Saidi on 2016-06-22.
// Copyright © 2016 Daniel Saidi. All rights reserved.
//
import Foundation
/**
This struct represents the result of an import operation.
It specifies the import method, current state as well as the optional imported string or data and an optional error.
*/
public struct ImportResult {
public init(method: ImportMethod, state: ImportState) {
self.method = method
self.state = state
self.data = nil
self.error = nil
self.string = nil
}
public init(method: ImportMethod, string: String) {
self.method = method
self.state = .completed
self.data = nil
self.error = nil
self.string = string
}
public init(method: ImportMethod, data: Data) {
self.method = method
self.state = .completed
self.data = data
self.error = nil
self.string = nil
}
public init(method: ImportMethod, error: Error) {
self.method = method
self.state = .failed
self.data = nil
self.error = error
self.string = nil
}
public let method: ImportMethod
public let state: ImportState
public let data: Data?
public let error: Error?
public let string: String?
}
| mit | e33388714e2684ebc526276197943f6f | 23.581818 | 117 | 0.610207 | 4.238245 | false | false | false | false |
efremidze/NumPad | Sources/DefaultNumPad.swift | 1 | 1594 | //
// DefaultNumPad.swift
// NumPad
//
// Created by Lasha Efremidze on 1/7/18.
// Copyright © 2018 Lasha Efremidze. All rights reserved.
//
import UIKit
open class DefaultNumPad: NumPad {
override public init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
func initialize() {
dataSource = self
}
}
extension DefaultNumPad: NumPadDataSource {
public func numberOfRowsInNumPad(_ numPad: NumPad) -> Int {
return 4
}
public func numPad(_ numPad: NumPad, numberOfColumnsInRow row: Row) -> Int {
return 3
}
public func numPad(_ numPad: NumPad, itemAtPosition position: Position) -> Item {
var item = Item()
item.title = {
switch position {
case (3, 0):
return "C"
case (3, 1):
return "0"
case (3, 2):
return "00"
default:
var index = (0..<position.row).map { self.numPad(self, numberOfColumnsInRow: $0) }.reduce(0, +)
index += position.column
return "\(index + 1)"
}
}()
item.titleColor = {
switch position {
case (3, 0):
return .orange
default:
return UIColor(white: 0.3, alpha: 1)
}
}()
item.font = .systemFont(ofSize: 40)
return item
}
}
| mit | 46310a4a4a0cc18cfeafe99044d32b44 | 22.776119 | 111 | 0.502197 | 4.293801 | false | false | false | false |
jakehirzel/swift-tip-calculator | CheckPlease/ViewBlinker.swift | 1 | 1620 | //
// ViewBlinker.swift
// CheckPlease
//
// Created by Jake Hirzel on 7/6/16.
// Copyright © 2016 Jake Hirzel. All rights reserved.
//
import UIKit
import Messages
extension UIView {
func blink() {
UIView.animate(
withDuration: 1.0,
delay: 0.0,
options: [.autoreverse, .repeat],
animations: { [weak self] in self?.alpha = 0.0 },
completion: { [weak self] _ in self?.alpha = 1.0 })
}
func fadeIn() {
UIView.animate(
withDuration: 1.0,
delay: 0.0,
options: UIView.AnimationOptions.curveEaseIn,
animations: { self.alpha = 1.0 },
completion: nil)
}
func fadeOut() {
UIView.animate(
withDuration: 1.0,
delay: 0.0,
options: UIView.AnimationOptions.curveEaseOut,
animations: { self.alpha = 0.0 },
completion: nil)
}
func pulseOnce(_ delay: TimeInterval) {
UIView.animate(
withDuration: 0.4,
delay: delay,
options: .curveEaseIn,
animations: {
self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
},
completion: {
(finished: Bool) -> Void in
UIView.animate(
withDuration: 0.4,
delay: 0.1,
options: .curveEaseOut,
animations: {
self.transform = CGAffineTransform(scaleX: 1, y: 1)
},
completion: nil)
})
}
}
| mit | d20a6b7e17c0fc2d76c3e171fc31b0b2 | 25.540984 | 71 | 0.480544 | 4.472376 | false | false | false | false |
milseman/swift | test/IRGen/generic_casts.swift | 4 | 5915 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
import gizmo
// -- Protocol records for cast-to ObjC protocols
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ = private constant
// CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section "__DATA,__objc_protolist,coalesced,no_dead_strip"
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section "__DATA,__objc_protorefs,coalesced,no_dead_strip"
// CHECK: @_PROTOCOL_NSRuncing = private constant
// CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section "__DATA,__objc_protolist,coalesced,no_dead_strip"
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section "__DATA,__objc_protorefs,coalesced,no_dead_strip"
// CHECK: @_PROTOCOLS__TtC13generic_casts10ObjCClass2 = private constant { i64, [1 x i8*] } {
// CHECK: i64 1,
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto2_
// CHECK: }
// CHECK: @_DATA__TtC13generic_casts10ObjCClass2 = private constant {{.*}} @_PROTOCOLS__TtC13generic_casts10ObjCClass2
// CHECK: @_PROTOCOL_PROTOCOLS__TtP13generic_casts10ObjCProto2_ = private constant { i64, [1 x i8*] } {
// CHECK: i64 1,
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_
// CHECK: }
// CHECK: define hidden swiftcc i64 @_T013generic_casts8allToIntSixlF(%swift.opaque* noalias nocapture, %swift.type* %T)
func allToInt<T>(_ x: T) -> Int {
return x as! Int
// CHECK: [[INT_TEMP:%.*]] = alloca %TSi,
// CHECK: [[TYPE_ADDR:%.*]] = bitcast %swift.type* %T to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[TYPE_ADDR]], i64 -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[SIZE_WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 11
// CHECK: [[SIZE_WITNESS:%.*]] = load i8*, i8** [[SIZE_WITNESS_ADDR]]
// CHECK: [[SIZE:%.*]] = ptrtoint i8* [[SIZE_WITNESS]]
// CHECK: [[T_ALLOCA:%.*]] = alloca i8, {{.*}} [[SIZE]], align 16
// CHECK: [[T_TMP:%.*]] = bitcast i8* [[T_ALLOCA]] to %swift.opaque*
// CHECK: [[TEMP:%.*]] = call %swift.opaque* {{.*}}(%swift.opaque* noalias [[T_TMP]], %swift.opaque* noalias %0, %swift.type* %T)
// CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque*
// CHECK: call i1 @swift_rt_swift_dynamicCast(%swift.opaque* [[T0]], %swift.opaque* [[T_TMP]], %swift.type* %T, %swift.type* @_T0SiN, i64 7)
// CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0
// CHECK: [[INT_RESULT:%.*]] = load i64, i64* [[T0]],
// CHECK: ret i64 [[INT_RESULT]]
}
// CHECK: define hidden swiftcc void @_T013generic_casts8intToAllxSilF(%swift.opaque* noalias nocapture sret, i64, %swift.type* %T) {{.*}} {
func intToAll<T>(_ x: Int) -> T {
// CHECK: [[INT_TEMP:%.*]] = alloca %TSi,
// CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0
// CHECK: store i64 %1, i64* [[T0]],
// CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque*
// CHECK: call i1 @swift_rt_swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[T0]], %swift.type* @_T0SiN, %swift.type* %T, i64 7)
return x as! T
}
// CHECK: define hidden swiftcc i64 @_T013generic_casts8anyToIntSiypF(%Any* noalias nocapture dereferenceable({{.*}})) {{.*}} {
func anyToInt(_ x: Any) -> Int {
return x as! Int
}
@objc protocol ObjCProto1 {
static func forClass()
static func forInstance()
var prop: NSObject { get }
}
@objc protocol ObjCProto2 : ObjCProto1 {}
@objc class ObjCClass {}
// CHECK: define hidden swiftcc %objc_object* @_T013generic_casts9protoCastAA10ObjCProto1_So9NSRuncingpAA0E6CClassCF(%T13generic_casts9ObjCClassC*) {{.*}} {
func protoCast(_ x: ObjCClass) -> ObjCProto1 & NSRuncing {
// CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_"
// CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing"
// CHECK: call %objc_object* @swift_dynamicCastObjCProtocolUnconditional(%objc_object* {{%.*}}, i64 2, i8** {{%.*}})
return x as! ObjCProto1 & NSRuncing
}
@objc class ObjCClass2 : NSObject, ObjCProto2 {
class func forClass() {}
class func forInstance() {}
var prop: NSObject { return self }
}
// <rdar://problem/15313840>
// Class existential to opaque archetype cast
// CHECK: define hidden swiftcc void @_T013generic_casts33classExistentialToOpaqueArchetypexAA10ObjCProto1_plF(%swift.opaque* noalias nocapture sret, %objc_object*, %swift.type* %T)
func classExistentialToOpaqueArchetype<T>(_ x: ObjCProto1) -> T {
var x = x
// CHECK: [[X:%.*]] = alloca %T13generic_casts10ObjCProto1P
// CHECK: [[LOCAL:%.*]] = alloca %T13generic_casts10ObjCProto1P
// CHECK: [[LOCAL_OPAQUE:%.*]] = bitcast %T13generic_casts10ObjCProto1P* [[LOCAL]] to %swift.opaque*
// CHECK: [[PROTO_TYPE:%.*]] = call %swift.type* @_T013generic_casts10ObjCProto1_pMa()
// CHECK: call i1 @swift_rt_swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[LOCAL_OPAQUE]], %swift.type* [[PROTO_TYPE]], %swift.type* %T, i64 7)
return x as! T
}
protocol P {}
protocol Q {}
// CHECK: define hidden swiftcc void @_T013generic_casts19compositionToMemberAA1P_pAaC_AA1QpF{{.*}}(%T13generic_casts1PP* noalias nocapture sret, %T13generic_casts1P_AA1Qp* noalias nocapture dereferenceable({{.*}})) {{.*}} {
func compositionToMember(_ a: P & Q) -> P {
return a
}
| apache-2.0 | caa421846adb3d2b7f4d17b6c6264cb6 | 50.434783 | 228 | 0.664074 | 3.235777 | false | false | false | false |
eBardX/XestiMonitors | Tests/UIKit/Device/BatteryMonitorTests.swift | 1 | 3657 | //
// BatteryMonitorTests.swift
// XestiMonitorsTests
//
// Created by J. G. Pusey on 2017-12-27.
//
// © 2017 J. G. Pusey (see LICENSE.md)
//
import UIKit
import XCTest
@testable import XestiMonitors
internal class BatteryMonitorTests: XCTestCase {
let device = MockDevice()
let notificationCenter = MockNotificationCenter()
override func setUp() {
super.setUp()
DeviceInjector.inject = { self.device }
device.batteryLevel = 0
device.batteryState = .unknown
NotificationCenterInjector.inject = { self.notificationCenter }
}
func testLevel() {
let expectedLevel: Float = 75
let monitor = BatteryMonitor(options: .levelDidChange,
queue: .main) { _ in
XCTAssertEqual(OperationQueue.current, .main)
}
simulateLevelDidChange(to: expectedLevel)
XCTAssertEqual(monitor.level, expectedLevel)
}
func testMonitor_levelDidChange() {
let expectation = self.expectation(description: "Handler called")
let expectedLevel: Float = 50
var expectedEvent: BatteryMonitor.Event?
let monitor = BatteryMonitor(options: .levelDidChange,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateLevelDidChange(to: expectedLevel)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .levelDidChange(level) = event {
XCTAssertEqual(level, expectedLevel)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_stateDidChange() {
let expectation = self.expectation(description: "Handler called")
let expectedState: UIDeviceBatteryState = .charging
var expectedEvent: BatteryMonitor.Event?
let monitor = BatteryMonitor(options: .stateDidChange,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateStateDidChange(to: expectedState)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .stateDidChange(state) = event {
XCTAssertEqual(state, expectedState)
} else {
XCTFail("Unexpected event")
}
}
func testState() {
let expectedState: UIDeviceBatteryState = .full
let monitor = BatteryMonitor(options: .stateDidChange,
queue: .main) { _ in
XCTAssertEqual(OperationQueue.current, .main)
}
simulateStateDidChange(to: expectedState)
XCTAssertEqual(monitor.state, expectedState)
}
private func simulateLevelDidChange(to level: Float) {
device.batteryLevel = level
notificationCenter.post(name: .UIDeviceBatteryLevelDidChange,
object: device)
}
private func simulateStateDidChange(to state: UIDeviceBatteryState) {
device.batteryState = state
notificationCenter.post(name: .UIDeviceBatteryStateDidChange,
object: device)
}
}
| mit | f1259481808caec9721c2ec3959b92e2 | 30.517241 | 85 | 0.581783 | 5.615975 | false | true | false | false |
duycao2506/SASCoffeeIOS | Pods/DrawerController/DrawerController/AnimatedMenuButton.swift | 2 | 6168 | // Copyright (c) 2017 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 Foundation
import QuartzCore
import UIKit
open class AnimatedMenuButton : UIButton {
lazy var top: CAShapeLayer = CAShapeLayer()
lazy var middle: CAShapeLayer = CAShapeLayer()
lazy var bottom: CAShapeLayer = CAShapeLayer()
let strokeColor: UIColor
// MARK: - Constants
let animationDuration: CFTimeInterval = 8.0
let shortStroke: CGPath = {
let path = CGMutablePath()
path.move(to: CGPoint(x: 3.5, y: 6))
path.addLine(to: CGPoint(x: 22.5, y: 6))
return path
}()
var animatable = true
// MARK: - Initializers
required public init?(coder aDecoder: NSCoder) {
self.strokeColor = UIColor.gray
super.init(coder: aDecoder)
}
override convenience init(frame: CGRect) {
self.init(frame: frame, strokeColor: UIColor.gray)
}
init(frame: CGRect, strokeColor: UIColor) {
self.strokeColor = strokeColor
super.init(frame: frame)
if !self.animatable {
return
}
self.top.path = shortStroke;
self.middle.path = shortStroke;
self.bottom.path = shortStroke;
for layer in [ self.top, self.middle, self.bottom ] {
layer.fillColor = nil
layer.strokeColor = self.strokeColor.cgColor
layer.lineWidth = 1
layer.miterLimit = 2
layer.lineCap = kCALineCapSquare
layer.masksToBounds = true
if let path = layer.path, let strokingPath = CGPath(__byStroking: path, transform: nil, lineWidth: 1, lineCap: .square, lineJoin: .miter, miterLimit: 4) {
layer.bounds = strokingPath.boundingBoxOfPath
}
layer.actions = [
"opacity": NSNull(),
"transform": NSNull()
]
self.layer.addSublayer(layer)
}
self.top.anchorPoint = CGPoint(x: 1, y: 0.5)
self.top.position = CGPoint(x: 23, y: 7)
self.middle.position = CGPoint(x: 13, y: 13)
self.bottom.anchorPoint = CGPoint(x: 1, y: 0.5)
self.bottom.position = CGPoint(x: 23, y: 19)
}
open override func draw(_ rect: CGRect) {
if self.animatable {
return
}
self.strokeColor.setStroke()
let context = UIGraphicsGetCurrentContext()
context?.setShouldAntialias(false)
let top = UIBezierPath()
top.move(to: CGPoint(x:3,y:6.5))
top.addLine(to: CGPoint(x:23,y:6.5))
top.stroke()
let middle = UIBezierPath()
middle.move(to: CGPoint(x:3,y:12.5))
middle.addLine(to: CGPoint(x:23,y:12.5))
middle.stroke()
let bottom = UIBezierPath()
bottom.move(to: CGPoint(x:3,y:18.5))
bottom.addLine(to: CGPoint(x:23,y:18.5))
bottom.stroke()
}
// MARK: - Animations
open func animate(withFractionVisible fractionVisible: CGFloat, drawerSide: DrawerSide) {
if !self.animatable {
return
}
if drawerSide == DrawerSide.left {
self.top.anchorPoint = CGPoint(x: 1, y: 0.5)
self.top.position = CGPoint(x: 23, y: 7)
self.middle.position = CGPoint(x: 13, y: 13)
self.bottom.anchorPoint = CGPoint(x: 1, y: 0.5)
self.bottom.position = CGPoint(x: 23, y: 19)
} else if drawerSide == DrawerSide.right {
self.top.anchorPoint = CGPoint(x: 0, y: 0.5)
self.top.position = CGPoint(x: 3, y: 7)
self.middle.position = CGPoint(x: 13, y: 13)
self.bottom.anchorPoint = CGPoint(x: 0, y: 0.5)
self.bottom.position = CGPoint(x: 3, y: 19)
}
let middleTransform = CABasicAnimation(keyPath: "opacity")
middleTransform.duration = animationDuration
let topTransform = CABasicAnimation(keyPath: "transform")
topTransform.timingFunction = CAMediaTimingFunction(controlPoints: 0.5, -0.8, 0.5, 1.85)
topTransform.duration = animationDuration
topTransform.fillMode = kCAFillModeBackwards
let bottomTransform = topTransform.copy() as! CABasicAnimation
middleTransform.toValue = 1 - fractionVisible
let translation = CATransform3DMakeTranslation(-4 * fractionVisible, 0, 0)
let tanOfTransformAngle = 6.0/19.0
let transformAngle = atan(tanOfTransformAngle)
let sideInverter: CGFloat = drawerSide == DrawerSide.left ? -1 : 1
topTransform.toValue = NSValue(caTransform3D: CATransform3DRotate(translation, 1.0 * sideInverter * (CGFloat(transformAngle) * fractionVisible), 0, 0, 1))
bottomTransform.toValue = NSValue(caTransform3D: CATransform3DRotate(translation, (-1.0 * sideInverter * CGFloat(transformAngle) * fractionVisible), 0, 0, 1))
topTransform.beginTime = CACurrentMediaTime()
bottomTransform.beginTime = CACurrentMediaTime()
self.top.add(topTransform, forKey: topTransform.keyPath)
self.middle.add(middleTransform, forKey: middleTransform.keyPath)
self.bottom.add(bottomTransform, forKey: bottomTransform.keyPath)
self.top.setValue(topTransform.toValue, forKey: topTransform.keyPath!)
self.middle.setValue(middleTransform.toValue, forKey: middleTransform.keyPath!)
self.bottom.setValue(bottomTransform.toValue, forKey: bottomTransform.keyPath!)
}
}
| gpl-3.0 | 853abefe13c1e9acd3ee2c404ce1d65f | 34.045455 | 162 | 0.682879 | 4.007797 | false | false | false | false |
ibm-wearables-sdk-for-mobile/ios | IBMMobileEdge/IBMMobileEdge/AbstractModel.swift | 4 | 5738 | /*
* © Copyright 2015 IBM Corp.
*
* Licensed under the Mobile Edge iOS Framework License (the "License");
* you may not use this file except in compliance with the License. You may find
* a copy of the license in the license.txt file in this package.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public enum SensorType {
case Accelerometer, Temperature, Humidity, Magnetometer, Gyroscope, Barometer, Optical, AmbientLight, Calories, Gsr, Pedometer, HeartRate, SkinTemperature, UV
}
public class BaseSensorData {
public var timeStamp:NSDate
public var tag:String!
public init(){
timeStamp = NSDate()
}
public func asJSON() -> Dictionary<String,AnyObject>{
var data = Dictionary<String,AnyObject>()
data["timeStamp"] = timeStamp
if let tag = tag{
data["tag"] = tag
}
return data
}
}
public class AccelerometerData : BaseSensorData{
public var x:Double = 0.0
public var y:Double = 0.0
public var z:Double = 0.0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String,AnyObject> {
var data = super.asJSON()
data["accelerometer"] = ["x":x,"y":y,"z":z]
return data
}
}
public class TemperatureData : BaseSensorData{
public var temperature:Double = 0.0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String,AnyObject> {
var data = super.asJSON()
data["temperature"] = temperature
return data
}
}
public class HumidityData : BaseSensorData{
public var humidity:Double = 0.0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String,AnyObject> {
var data = super.asJSON()
data["humidity"] = humidity
return data
}
}
public class GyroscopeData : BaseSensorData{
public var x:Double = 0.0
public var y:Double = 0.0
public var z:Double = 0.0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String,AnyObject> {
var data = super.asJSON()
data["gyroscope"] = ["x":x,"y":y,"z":z]
return data
}
}
public class MagnetometerData : BaseSensorData{
public var x:Double = 0.0
public var y:Double = 0.0
public var z:Double = 0.0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String, AnyObject> {
var data = super.asJSON()
data["magnetometer"] = ["x":x,"y":y,"z":z]
return data
}
}
public class BarometerData : BaseSensorData{
public var temperature:Double = 0.0
public var airPressure:Double = 0.0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String, AnyObject> {
var data = super.asJSON()
data["barometer"] = ["temperature":temperature,"airPressure":airPressure]
return data
}
}
public class OpticalData : BaseSensorData{
}
public class AmbientLightData : BaseSensorData{
public var brightness:Int = 0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String, AnyObject> {
var data = super.asJSON()
data["brightness"] = [brightness]
return data
}
}
public class CaloriesData : BaseSensorData{
//data here
public var calories:UInt = 0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String, AnyObject> {
var data = super.asJSON()
data["calories"] = [calories]
return data
}
}
public class GsrData : BaseSensorData{
public var resistance:UInt = 0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String, AnyObject> {
var data = super.asJSON()
data["resistance"] = [resistance]
return data
}
}
public class PedometerData : BaseSensorData{
public var steps:UInt = 0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String, AnyObject> {
var data = super.asJSON()
data["steps"] = [steps]
return data
}
}
public class HeartRateData : BaseSensorData{
public var heartRate:UInt = 0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String, AnyObject> {
var data = super.asJSON()
data["heartRate"] = [heartRate]
return data
}
}
public class SkinTemperatureData : BaseSensorData{
public var temperature:Double = 0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String, AnyObject> {
var data = super.asJSON()
data["temperature"] = [temperature]
return data
}
}
public class UVData : BaseSensorData{
public var indexLevel:UInt = 0
override public init() {
super.init()
}
override public func asJSON() -> Dictionary<String, AnyObject> {
var data = super.asJSON()
data["indexLevel"] = [indexLevel]
return data
}
}
| epl-1.0 | 3ebd383896017815ac8b719939973a8e | 22.040161 | 162 | 0.604846 | 4.356112 | false | false | false | false |
lvnyk/BezierString | BezierString/Geometry.swift | 1 | 10211 | //
// Geometry.swift
//
// Created by Luka on 27. 08. 14.
// Copyright (c) 2014 lvnyk
//
// 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
// MARK: - calculations
// MARK: CGPoint
func +(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x+rhs.x, y: lhs.y+rhs.y)
}
func +=(lhs: inout CGPoint, rhs: CGPoint) {
lhs.x += rhs.x
lhs.y += rhs.y
}
func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x-rhs.x, y: lhs.y-rhs.y)
}
func -=(lhs: inout CGPoint, rhs: CGPoint) {
lhs.x -= rhs.x
lhs.y -= rhs.y
}
func *(lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return CGPoint(x: lhs.x*rhs, y: lhs.y*rhs)
}
func *=(lhs: inout CGPoint, rhs: CGFloat) {
lhs.x *= rhs
lhs.y *= rhs
}
func *(lhs: CGFloat, rhs: CGPoint) -> CGPoint {
return CGPoint(x: rhs.x*lhs, y: rhs.y*lhs)
}
func /(lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return CGPoint(x: lhs.x/rhs, y: lhs.y/rhs)
}
func /=(lhs: inout CGPoint, rhs: CGFloat) {
lhs.x /= rhs
lhs.y /= rhs
}
func +(lhs: CGPoint, rhs: CGVector) -> CGPoint {
return CGPoint(x: lhs.x+rhs.dx, y: lhs.y+rhs.dy)
}
func -(lhs: CGPoint, rhs: CGVector) -> CGPoint {
return CGPoint(x: lhs.x-rhs.dx, y: lhs.y-rhs.dy)
}
prefix func -(lhs: CGPoint) -> CGPoint {
return CGPoint(x: -lhs.x, y: -lhs.y)
}
// MARK: CGVector
func +(lhs: CGVector, rhs: CGVector) -> CGVector {
return CGVector(dx: lhs.dx+rhs.dx, dy: lhs.dy+rhs.dy)
}
func +=(lhs: inout CGVector, rhs: CGVector) {
lhs.dx += rhs.dx
lhs.dy += rhs.dy
}
func -(lhs: CGVector, rhs: CGVector) -> CGVector {
return CGVector(dx: lhs.dx-rhs.dx, dy: lhs.dy-rhs.dy)
}
func -=(lhs: inout CGVector, rhs: CGVector) {
lhs.dx -= rhs.dx
lhs.dy -= rhs.dy
}
func *(lhs: CGVector, rhs: CGFloat) -> CGVector {
return CGVector(dx: lhs.dx*rhs, dy: lhs.dy*rhs)
}
func *=(lhs: inout CGVector, rhs: CGFloat) {
lhs.dx *= rhs
lhs.dy *= rhs
}
func *(lhs: CGFloat, rhs: CGVector) -> CGVector {
return CGVector(dx: rhs.dx*lhs, dy: rhs.dy*lhs)
}
func /(lhs: CGVector, rhs: CGFloat) -> CGVector {
return CGVector(dx: lhs.dx/rhs, dy: lhs.dy/rhs)
}
func /=(lhs: inout CGVector, rhs: CGFloat) {
lhs.dx /= rhs
lhs.dy /= rhs
}
// MARK: CGSize
func +(lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width+rhs.width, height: lhs.height+rhs.height)
}
func +=(lhs: inout CGSize, rhs: CGSize) {
lhs.width += rhs.width
lhs.height += rhs.height
}
func -(lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width-rhs.width, height: lhs.height-rhs.height)
}
func -=(lhs: inout CGSize, rhs: CGSize) {
lhs.width -= rhs.width
lhs.height -= rhs.height
}
func *(lhs: CGFloat, rhs: CGSize) -> CGSize {
return CGSize(width: rhs.width*lhs, height: rhs.height*lhs)
}
func *(lhs: CGSize, rhs: CGFloat) -> CGSize {
return CGSize(width: lhs.width*rhs, height: lhs.height*rhs)
}
func *=(lhs: inout CGSize, rhs: CGFloat) {
lhs.width *= rhs
lhs.height *= rhs
}
func /(lhs: CGSize, rhs: CGFloat) -> CGSize {
return CGSize(width: lhs.width/rhs, height: lhs.height/rhs)
}
func /=(lhs: inout CGSize, rhs: CGFloat) {
lhs.width /= rhs
lhs.height /= rhs
}
// MARK: CGRect
func *(lhs: CGRect, rhs: CGFloat) -> CGRect {
return CGRect(origin: lhs.origin*rhs, size: lhs.size*rhs)
}
func *(lhs: CGFloat, rhs: CGRect) -> CGRect {
return CGRect(origin: lhs*rhs.origin, size: lhs*rhs.size)
}
func *=(lhs: inout CGRect, rhs: CGFloat) {
lhs.origin *= rhs
lhs.size *= rhs
}
func /(lhs: CGRect, rhs: CGFloat) -> CGRect {
return CGRect(origin: lhs.origin/rhs, size: lhs.size/rhs)
}
func /=(lhs: inout CGRect, rhs: CGFloat) {
lhs.origin /= rhs
lhs.size /= rhs
}
func +(lhs: CGRect, rhs: CGPoint) -> CGRect {
return lhs.offsetBy(dx: rhs.x, dy: rhs.y)
}
func -(lhs: CGRect, rhs: CGPoint) -> CGRect {
return lhs.offsetBy(dx: -rhs.x, dy: -rhs.y)
}
func +(lhs: CGRect, rhs: CGSize) -> CGRect {
return CGRect(origin: lhs.origin, size: lhs.size+rhs)
}
func -(lhs: CGRect, rhs: CGSize) -> CGRect {
return CGRect(origin: lhs.origin, size: lhs.size-rhs)
}
// MARK: - helpers
/// Determines whether the second vector is above > 0 or below < 0 the first one
func *(lhs: CGPoint, rhs: CGPoint ) -> CGFloat {
return lhs.x*rhs.y - lhs.y*rhs.x
}
/// smallest angle between 2 angles
func arcFi( _ fi1: CGFloat, fi2: CGFloat ) -> CGFloat {
let p = CGPoint(x: cos(fi1)-cos(fi2), y: sin(fi1)-sin(fi2))
let dSqr = p.x*p.x + p.y*p.y
let fi = acos(1-dSqr/2)
return fi
}
/// whether fi2 is larger than fi1 in reference to the ref angle
func compareAngles( _ ref: CGFloat, fi1: CGFloat, fi2: CGFloat ) -> CGFloat {
return -arcFi(ref, fi2: fi1)+arcFi(ref, fi2: fi2)
}
/// intersection
func lineIntersection( segmentStart p1:CGPoint, segmentEnd p2:CGPoint,
lineStart p3:CGPoint, lineEnd p4:CGPoint,
insideSegment: Bool = true, lineIsSegment: Bool = false, hardUpperLimit: Bool = false ) -> CGPoint? {
let parallel = CGFloat(p1.x-p2.x)*CGFloat(p3.y-p4.y) - CGFloat(p1.y-p2.y)*CGFloat(p3.x-p4.x) == 0
if parallel == false {
let x: CGFloat = CGFloat(CGFloat(CGFloat(p1.x*p2.y) - CGFloat(p1.y*p2.x))*CGFloat(p3.x-p4.x) - CGFloat(p1.x-p2.x)*CGFloat(CGFloat(p3.x*p4.y) - CGFloat(p3.y*p4.x))) / CGFloat(CGFloat(p1.x-p2.x)*CGFloat(p3.y-p4.y) - CGFloat(p1.y - p2.y)*CGFloat(p3.x-p4.x))
let y: CGFloat = CGFloat(CGFloat(CGFloat(p1.x*p2.y) - CGFloat(p1.y*p2.x))*CGFloat(p3.y-p4.y) - CGFloat(p1.y-p2.y)*CGFloat(CGFloat(p3.x*p4.y) - CGFloat(p3.y*p4.x))) / CGFloat(CGFloat(p1.x-p2.x)*CGFloat(p3.y-p4.y) - CGFloat(p1.y - p2.y)*CGFloat(p3.x-p4.x))
let intersection = CGPoint(
x: x,
y: y
)
if insideSegment {
let u = p2.x == p1.x ? 0 : (intersection.x - p1.x) / (p2.x - p1.x)
let v = p2.y == p1.y ? 0 : (intersection.y - p1.y) / (p2.y - p1.y)
if u<0 || v<0 || v>1 || u>1 || hardUpperLimit && (v>=1 || u>=1) {
return nil
}
if lineIsSegment {
let w = p4.x == p3.x ? 0 : (intersection.y - p3.x) / (p4.x - p3.x)
let x = p4.y == p3.y ? 0 : (intersection.y - p3.y) / (p4.y - p3.y)
if w<0 || x<0 || w>1 || x>1 || hardUpperLimit && (w>=1 || x>=1) {
return nil
}
}
}
return intersection
}
return nil
}
func segmentsIntersection(_ segment1: (CGPoint, CGPoint), _ segment2: (CGPoint, CGPoint)) -> CGPoint? {
return lineIntersection(segmentStart: segment1.0, segmentEnd: segment1.1, lineStart: segment2.0, lineEnd: segment2.1,
insideSegment: true, lineIsSegment: true, hardUpperLimit: true)
}
/// center of circle through points
func circleCenter(_ p0: CGPoint, p1: CGPoint, p2: CGPoint) -> CGPoint? {
let p01 = (p0+p1)/2 // midpoint
let p12 = (p1+p2)/2
let t01 = p1-p0 // parallel -> tangent
let t12 = p2-p1
return
lineIntersection(
segmentStart: p01,
segmentEnd: p01 + CGPoint(x: -t01.y, y: t01.x),
lineStart: p12,
lineEnd: p12 + CGPoint(x: -t12.y, y: t12.x),
insideSegment: false)
}
// MARK: - extensions
extension CGFloat {
static let Pi = CGFloat(M_PI)
static let Pi2 = CGFloat(M_PI)/2
static let Phi = CGFloat(1.618033988749894848204586834)
static func random(_ d:CGFloat = 1) -> CGFloat {
return CGFloat(arc4random())/CGFloat(UInt32.max) * d
}
}
extension CGRect {
var topLeft: CGPoint {
return CGPoint(x: self.minX, y: self.minY)
}
var topRight: CGPoint {
return CGPoint(x: self.maxX, y: self.minY)
}
var bottomLeft: CGPoint {
return CGPoint(x: self.minX, y: self.maxY)
}
var bottomRight: CGPoint {
return CGPoint(x: self.maxX, y: self.maxY)
}
var topMiddle: CGPoint {
return CGPoint(x: self.midX, y: self.minY)
}
var bottomMiddle: CGPoint {
return CGPoint(x: self.midX, y: self.maxY)
}
var middleLeft: CGPoint {
return CGPoint(x: self.minX, y: self.midY)
}
var middleRight: CGPoint {
return CGPoint(x: self.maxX, y: self.midY)
}
var center: CGPoint {
return CGPoint(x: self.midX, y: self.midY)
}
func transformed(_ t: CGAffineTransform) -> CGRect {
return self.applying(t)
}
public func insetWith(_ insets: UIEdgeInsets) -> CGRect {
return UIEdgeInsetsInsetRect(self, insets)
}
}
extension CGPoint {
/// distance to another point
func distanceTo(_ point: CGPoint) -> CGFloat {
return sqrt(pow(self.x-point.x, 2) + pow(self.y-point.y, 2))
}
func integral() -> CGPoint {
return CGPoint(x: round(self.x), y: round(self.y))
}
mutating func integrate() {
self.x = round(self.x)
self.y = round(self.y)
}
func transformed(_ t: CGAffineTransform) -> CGPoint {
return self.applying(t)
}
func normalized() -> CGPoint {
if self == .zero {
return CGPoint(x: 1, y: 0)
}
return self/self.distanceTo(.zero)
}
}
extension CGVector {
init(point: CGPoint) {
self.dx = point.x
self.dy = point.y
}
init(size: CGSize) {
self.dx = size.width
self.dy = size.height
}
var length: CGFloat {
return sqrt(self.dx*self.dx+self.dy*self.dy)
}
}
extension CGPoint {
init(vector: CGVector) {
self.x = vector.dx
self.y = vector.dy
}
}
extension CGSize {
func integral() -> CGSize {
var s = self
s.integrate()
return s
}
mutating func integrate() {
self.width = round(self.width)
self.height = round(self.height)
}
}
| mit | 9f88123118c974124e739888b2a663f8 | 23.254157 | 256 | 0.64646 | 2.758984 | false | false | false | false |
emilwojtaszek/collection-view-layout-examples | ExampleApp/ViewController1.swift | 1 | 1567 | //
// ViewController1.swift
// ExampleApp
//
// Created by Emil Wojtaszek on 12/03/2017.
// Copyright © 2017 AppUnite Sp. z o.o. All rights reserved.
//
import UIKit
class ViewController1: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
// since this controller is initialized from code we need to register all collection view elements
collectionView?.register(TextCell.self,
forCellWithReuseIdentifier: TextCell.reuseIdentifier)
// setup collection view layout (in this case subclass of UICollectionViewFlowLayout)
let layout = self.collectionViewLayout as! DecorationLayout
layout.itemSize = CGSize(width: self.view.frame.width, height: 44)
layout.minimumLineSpacing = 2.0
}
/// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// dequeue cell
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: TextCell.reuseIdentifier,
for: indexPath) as! TextCell
// update text
cell.titleLabel.text = "Cell: (\(indexPath.section),\(indexPath.row))"
return cell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 18
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
}
| mit | 249161aec9e1729ab329f3ba00257133 | 33.8 | 130 | 0.673691 | 5.4375 | false | false | false | false |
ps2/rileylink_ios | MinimedKit/PumpManager/EnliteSensorDisplayable.swift | 1 | 1395 | //
// EnliteSensorDisplayable.swift
// Loop
//
// Created by Timothy Mecklem on 12/28/16.
// Copyright © 2016 LoopKit Authors. All rights reserved.
//
import Foundation
import HealthKit
import LoopKit
struct EnliteSensorDisplayable: Equatable, GlucoseDisplayable {
public let isStateValid: Bool
public let trendType: LoopKit.GlucoseTrend?
public let trendRate: HKQuantity?
public let isLocal: Bool
// TODO Placeholder. This functionality will come with LOOP-1311
var glucoseRangeCategory: GlucoseRangeCategory? {
return nil
}
var glucoseCondition: GlucoseCondition? {
return nil
}
public init(_ event: MinimedKit.RelativeTimestampedGlucoseEvent) {
isStateValid = event.isStateValid
trendType = event.trendType
trendRate = event.trendRate
isLocal = event.isLocal
}
public init(_ status: MySentryPumpStatusMessageBody) {
isStateValid = status.isStateValid
trendType = status.trendType
trendRate = nil
isLocal = status.isLocal
}
}
extension MinimedKit.RelativeTimestampedGlucoseEvent {
var isStateValid: Bool {
return self is SensorValueGlucoseEvent
}
var trendType: LoopKit.GlucoseTrend? {
return nil
}
var trendRate: HKQuantity? {
return nil
}
var isLocal: Bool {
return true
}
}
| mit | 95a460f1ba1207756e04a00b1f8819cc | 22.233333 | 70 | 0.677905 | 4.496774 | false | false | false | false |
ivanbruel/snapist | SnapIST/Classes/Model/Extensions/Message+Networking.swift | 1 | 1906 | //
// Message+Networking.swift
// SnapIST
//
// Created by Ivan Bruel on 24/02/15.
// Copyright (c) 2015 SINFO 22. All rights reserved.
//
import Foundation
extension Message {
// MARK: Serialization
class func fromJSON(json: [String: AnyObject]?) -> Message? {
if let jsonUnwrapped = json {
if let id = jsonUnwrapped["id"] as? Int {
if let text = jsonUnwrapped["text"] as? String {
if let timestamp = timestampFromString(jsonUnwrapped["updatedAt"] as? String) {
if let username = jsonUnwrapped["username"] as? String {
return Message(id: id, text: text, timestamp: timestamp, username: username)
}
}
}
}
}
return nil
}
// Just a code alternative for fromJSON(_)
class func fromJSON2(json: [String: AnyObject]?) -> Message? {
if let jsonUnwrapped = json {
let id = jsonUnwrapped["id"] as? Int
let text = jsonUnwrapped["text"] as? String
let timestamp = timestampFromString(jsonUnwrapped["updatedAt"] as? String)
let username = jsonUnwrapped["username"] as? String
if id != nil && text != nil && timestamp != nil && username != nil {
return Message(id: id!, text: text!, timestamp: timestamp!, username: username!)
}
}
return nil
}
private class func timestampFromString(timestampString: String?) -> NSDate? {
if let timestampStringUnwrapped = timestampString {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'"
return dateFormatter.dateFromString(timestampStringUnwrapped)
}
return nil
}
} | apache-2.0 | 119b99834daa931b4d9eb0f6b5aa72ea | 33.672727 | 104 | 0.548793 | 4.899743 | false | false | false | false |
4taras4/totp-auth | TOTP/ViperModules/FolderSettings/Module/Presenter/FolderSettingsPresenter.swift | 1 | 4198 | //
// FolderSettingsFolderSettingsPresenter.swift
// TOTP
//
// Created by Tarik on 15/02/2021.
// Copyright © 2021 Taras Markevych. All rights reserved.
//
import UIKit
import RealmSwift
final class FolderSettingsPresenter: NSObject, FolderSettingsViewOutput {
// MARK: -
// MARK: Properties
weak var view: FolderSettingsViewInput!
var interactor: FolderSettingsInteractorInput!
var router: FolderSettingsRouterInput!
fileprivate var folders = [Folder]()
fileprivate var addFolerItem = Folder()
// MARK: -
// MARK: FolderSettingsViewOutput
func viewIsReady() {
addFolerItem.name = Constants.text.addNewItemText
interactor.getFoldersArray()
}
func editButtonPressed() {
view.changeIsEdit()
}
}
// MARK: -
// MARK: FolderSettingsInteractorOutput
extension FolderSettingsPresenter: FolderSettingsInteractorOutput {
func folderRemoved() {
interactor.getFoldersArray()
}
func folderRemovingFailure(error: Error) {
view.showError(error: error.localizedDescription)
}
func getFolders(array: [Folder]) {
folders = array
folders.append(addFolerItem)
view.reloadTable()
}
func folderAddedSuccess() {
interactor.getFoldersArray()
}
func folderAddedFailure(error: Error) {
view.showError(error: error.localizedDescription)
}
}
// MARK: -
// MARK: FolderSettingsModuleInput
extension FolderSettingsPresenter: FolderSettingsModuleInput {
}
extension FolderSettingsPresenter: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return folders.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FolderCell", for: indexPath)
cell.textLabel?.text = folders[indexPath.row].name
if indexPath.row == folders.count - 1 {
cell.textLabel?.textColor = .systemIndigo
} else {
cell.textLabel?.textColor = .label
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == folders.count - 1 {
showCreateFolderAlert()
} else {
router.openSettings(for: folders[indexPath.row])
}
}
fileprivate func showCreateFolderAlert() {
let alert = UIAlertController(title: Constants.text.folderNameTitle, message: Constants.text.folderNameDescription, preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = Constants.text.folderNamePlaceholder
}
alert.addAction(UIAlertAction(title: Constants.text.cancelAlertButton, style: .destructive, handler: { (_) in
}))
alert.addAction(UIAlertAction(title: Constants.text.createAlertButton, style: .default, handler: { [weak alert] (_) in
let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
print("Text field: \(String(describing: textField?.text))")
self.interactor.createFolder(with: textField!.text!)
}))
UIApplication.topViewController()?.present(alert, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return Constants.text.folderHeaderTitle
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
interactor.removeFolder(item: folders[indexPath.row])
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if indexPath.row == folders.count - 1 {
return .none
}
return .delete
}
}
| mit | 74b550336b5befa5f63912b97fe8f4bc | 31.789063 | 147 | 0.665237 | 5.002384 | false | false | false | false |
practicalswift/swift | test/RemoteAST/structural_types.swift | 31 | 1937 | // RUN: %target-swift-remoteast-test %s | %FileCheck %s
// REQUIRES: swift-remoteast-test
@_silgen_name("printMetadataType")
func printType(_: Any.Type)
@_silgen_name("stopRemoteAST")
func stopRemoteAST()
typealias Fn1 = () -> ()
printType(Fn1.self)
// CHECK: found type: () -> ()
typealias Fn2 = (Int, Float) -> ()
printType(Fn2.self)
// CHECK: found type: (Int, Float) -> ()
typealias Fn3 = (inout Int, Float) -> ()
printType(Fn3.self)
// CHECK: found type: (inout Int, Float) -> ()
typealias Fn4 = (inout Int, inout Float) -> ()
printType(Fn4.self)
// CHECK: found type: (inout Int, inout Float) -> ()
typealias Fn5 = (Int, inout Float) -> ()
printType(Fn5.self)
// CHECK: found type: (Int, inout Float) -> ()
typealias Fn6 = (Int, inout String, Float) -> ()
printType(Fn6.self)
// CHECK: found type: (Int, inout String, Float) -> ()
typealias Fn7 = (inout Int, String, inout Float, Double) -> ()
printType(Fn7.self)
// CHECK: found type: (inout Int, String, inout Float, Double) -> ()
typealias Fn8 = (String, Int, Double, Float) -> ()
printType(Fn8.self)
// CHECK: found type: (String, Int, Double, Float) -> ()
typealias Fn9 = ((Int, Float)) -> ()
printType(Fn9.self)
// CHECK: found type: ((Int, Float)) -> ()
typealias Fn10 = (Int...) -> ()
printType(Fn10.self)
// CHECK: found type: (Int...) -> ()
typealias Tuple1 = (Int, Float, Int)
printType(Tuple1.self)
// CHECK: found type: (Int, Float, Int)
printType(Int.Type.self)
// CHECK: found type: Int.Type
printType(Tuple1.Type.self)
// CHECK: found type: (Int, Float, Int).Type
typealias Tuple2 = (Int.Type, x: Float, Int)
printType(Tuple2.self)
// CHECK: found type: (Int.Type, x: Float, Int)
typealias Tuple3 = (x: Int, Float, y: Int.Type)
printType(Tuple3.self)
// CHECK: found type: (x: Int, Float, y: Int.Type)
func foo<T>(_: T) {
var f = T.self
printType(f)
}
foo() { (x: Int) -> Int in return x }
// CHECK: found type: (Int) -> Int
stopRemoteAST() | apache-2.0 | 7dcbc04b3e0e19a3804b9a27888cd680 | 24.168831 | 68 | 0.641198 | 2.831871 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Sources/StellarKit/Models/Accounts/AddressAccount/StellarAssetAccount.swift | 1 | 816 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
public struct StellarAssetAccount: Equatable {
public let address: StellarAssetAddress
public let accountAddress: String
public let name: String
public let description: String
public let sequence: Int
public let subentryCount: UInt
public let walletIndex: Int
public init(
accountAddress: String,
name: String,
description: String,
sequence: Int,
subentryCount: UInt
) {
walletIndex = 0
self.accountAddress = accountAddress
self.name = name
self.description = description
self.sequence = sequence
self.subentryCount = subentryCount
address = StellarAssetAddress(publicKey: accountAddress)
}
}
| lgpl-3.0 | 102e57c6237614f7fbc58b14e72b72b1 | 26.166667 | 64 | 0.67362 | 5.062112 | false | false | false | false |
ollie-williams/octopus | followedBy.swift | 1 | 1762 | class FollowedBy<T1 : Parser, T2 : Parser> : Parser {
let first : T1
let second: T2
init(first:T1, second:T2) {
self.first = first
self.second = second
}
typealias R1 = T1.Target
typealias R2 = T2.Target
typealias Target = (R1,R2)
func parse(stream: CharStream) -> Target? {
let old = stream.position
if let a = first.parse(stream) {
if let b = second.parse(stream) {
return (a,b)
}
}
stream.position = old
return nil
}
}
class FollowedByFirst<T1 : Parser, T2 : Parser> : Parser {
let helper: FollowedBy<T1,T2>
init (first:T1, second:T2) {
helper = FollowedBy(first:first, second:second)
}
typealias Target = T1.Target
func parse(stream: CharStream) -> Target? {
if let (a,_) = helper.parse(stream) {
return a
}
return nil
}
}
class FollowedBySecond<T1 : Parser, T2 : Parser> : Parser {
let helper: FollowedBy<T1,T2>
init (first:T1, second:T2) {
helper = FollowedBy(first:first, second:second)
}
typealias Target = T2.Target
func parse(stream: CharStream) -> Target? {
if let (_,b) = helper.parse(stream) {
return b
}
return nil
}
}
infix operator ~>~ {associativity left precedence 140}
func ~>~ <T1: Parser, T2: Parser>(first: T1, second: T2) -> FollowedBy<T1,T2> {
return FollowedBy(first: first, second: second)
}
infix operator ~> {associativity left precedence 140}
func ~> <T1: Parser, T2: Parser>(first: T1, second: T2) -> FollowedByFirst<T1,T2> {
return FollowedByFirst(first: first, second: second)
}
infix operator >~ {associativity left precedence 140}
func >~ <T1: Parser, T2: Parser>(first: T1, second: T2) -> FollowedBySecond<T1,T2> {
return FollowedBySecond(first: first, second: second)
}
| apache-2.0 | 23ab04c9bdcee256008b43467b3d5a12 | 22.493333 | 84 | 0.645289 | 3.129663 | false | false | false | false |
huonw/swift | test/ClangImporter/Darwin_test.swift | 44 | 628 | // RUN: %target-typecheck-verify-swift %clang-importer-sdk
// REQUIRES: objc_interop
import Darwin
import MachO
_ = nil as Fract? // expected-error{{use of undeclared type 'Fract'}}
_ = nil as Darwin.Fract? // okay
_ = 0 as OSErr
_ = noErr as OSStatus // noErr is from the overlay
_ = 0 as UniChar
_ = ProcessSerialNumber()
_ = 0 as Byte // expected-error {{use of undeclared type 'Byte'}} {{10-14=UInt8}}
Darwin.fakeAPIUsingByteInDarwin() as Int // expected-error {{cannot convert value of type 'UInt8' to type 'Int' in coercion}}
_ = FALSE // expected-error {{use of unresolved identifier 'FALSE'}}
_ = DYLD_BOOL.FALSE
| apache-2.0 | 6fd1880360fb814b120cfa13773cc76f | 28.904762 | 125 | 0.694268 | 3.322751 | false | false | false | false |
peteratseneca/dps923winter2015 | Week_07/Friends with photos/Classes/FriendEdit.swift | 1 | 4150 | //
// FriendEdit.swift
// Friends
//
// Created by Peter McIntyre on 2015-02-11.
// Copyright (c) 2015 School of ICT, Seneca College. All rights reserved.
//
import UIKit
class FriendEdit: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: - Properties
var delegate: EditItemDelegate?
var model: Model!
var friend: Friend?
var photo: UIImage?
// MARK: - User interface
@IBOutlet weak var friendName: UITextField!
@IBOutlet weak var course: UITextField!
@IBOutlet weak var phone: UITextField!
@IBOutlet weak var email: UITextField!
@IBOutlet weak var selectedPhoto: UIImageView!
// MARK: - User actions
@IBAction func takePhoto(sender: UIButton) {
// Create an instance of the image picker
let imagePicker = UIImagePickerController()
// Check whether the device has a camera - if not, we'll use the photo library
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
// Camera action
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
} else {
// Photo library action
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
}
// Set this object to be its delegate; we do this for code-created controllers/objects
imagePicker.delegate = self
// Don't support editing for now
imagePicker.allowsEditing = false
// Present the image picker
self.presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func cancel(sender: UIBarButtonItem) {
delegate?.editItemDelegate(self, didEditItem: nil)
}
@IBAction func save(sender: UIBarButtonItem) {
// If a passed-in Friend object exists,
// we're in 'edit item' mode
// Otherwise, we're in 'add item' mode,
// and we need to create a new Friend object
if friend == nil {
friend = model.addNew("Friend") as? Friend
}
// Configure the object's attributes
friend?.friendName = friendName.text
friend?.course = course.text
friend?.phone = phone.text
friend?.email = email.text
friend?.dateAdded = NSDate()
friend?.photo = UIImagePNGRepresentation(self.photo)
delegate?.editItemDelegate(self, didEditItem: friend)
}
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// If a Friend object was passed in,
// use its values to configure the user interface
if let f = friend {
friendName.text = f.friendName
course.text = f.course
phone.text = f.phone
email.text = f.email
selectedPhoto.image = UIImage(data: f.photo)
}
}
// MARK: - Delegate methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
// Get the image that was selected
let selectedImage: UIImage = (info as NSDictionary).objectForKey("UIImagePickerControllerOriginalImage") as UIImage
let imgRef: CGImageRef = selectedImage.CGImage
let w: UInt = CGImageGetWidth(imgRef)
let h: UInt = CGImageGetHeight(imgRef)
let orient: UIImageOrientation = selectedImage.imageOrientation
// If the image is too big, scale it smaller
var image: UIImage? = nil
// Save the image to a property of this class
// Which can then be used by the 'save' method
self.photo = selectedImage
selectedPhoto.image = selectedImage
// Dismiss the view controller
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
protocol EditItemDelegate {
func editItemDelegate(controller: AnyObject, didEditItem item: AnyObject?)
}
| mit | a51db54a667a00c29b45b8babae8ac70 | 29.970149 | 125 | 0.626747 | 5.361757 | false | false | false | false |
danoli3/ResearchKit | samples/ORKCatalog/ORKCatalog/Tasks/TaskListRow.swift | 1 | 51233 | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Copyright (c) 2015, Ricardo Sánchez-Sáez.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import ResearchKit
import AudioToolbox
/**
Wraps a SystemSoundID.
A class is used in order to provide appropriate cleanup when the sound is
no longer needed.
*/
class SystemSound {
var soundID: SystemSoundID = 0
init?(soundURL: NSURL) {
if AudioServicesCreateSystemSoundID(soundURL as CFURLRef, &soundID) != noErr {
return nil
}
}
deinit {
AudioServicesDisposeSystemSoundID(soundID)
}
}
/**
An enum that corresponds to a row displayed in a `TaskListViewController`.
Each of the tasks is composed of one or more steps giving examples of the
types of functionality supported by the ResearchKit framework.
*/
enum TaskListRow: Int, CustomStringConvertible {
case Form = 0
case Survey
case BooleanQuestion
case DateQuestion
case DateTimeQuestion
case EligibilityQuestion
case ImageChoiceQuestion
case NumericQuestion
case ScaleQuestion
case TextQuestion
case TextChoiceQuestion
case TimeIntervalQuestion
case TimeOfDayQuestion
case ValuePickerChoiceQuestion
case ImageCapture
case EligibilityTask
case Consent
case Passcode
case Audio
case Fitness
case HolePegTest
case PSAT
case ReactionTime
case ShortWalk
case SpatialSpanMemory
case TimedWalk
case ToneAudiometry
case TowerOfHanoi
case TwoFingerTappingInterval
class TaskListRowSection {
var title: String
var rows: [TaskListRow]
init(title: String, rows: [TaskListRow]) {
self.title = title
self.rows = rows
}
}
/// Returns an array of all the task list row enum cases.
static var sections: [ TaskListRowSection ] {
return [
TaskListRowSection(title: "Surveys", rows:
[
.Form,
.Survey,
]),
TaskListRowSection(title: "Survey Questions", rows:
[
.BooleanQuestion,
.DateQuestion,
.DateTimeQuestion,
.EligibilityQuestion,
.ImageChoiceQuestion,
.NumericQuestion,
.ScaleQuestion,
.TextQuestion,
.TextChoiceQuestion,
.TimeIntervalQuestion,
.TimeOfDayQuestion,
.ValuePickerChoiceQuestion,
.ImageCapture,
]),
TaskListRowSection(title: "Onboarding", rows:
[
.EligibilityTask,
.Consent,
.Passcode,
]),
TaskListRowSection(title: "Active Tasks", rows:
[
.Audio,
.Fitness,
.HolePegTest,
.PSAT,
.ReactionTime,
.ShortWalk,
.SpatialSpanMemory,
.TimedWalk,
.ToneAudiometry,
.TowerOfHanoi,
.TwoFingerTappingInterval,
]),
]}
// MARK: CustomStringConvertible
var description: String {
switch self {
case .Form:
return NSLocalizedString("Form Survey Example", comment: "")
case .Survey:
return NSLocalizedString("Simple Survey Example", comment: "")
case .BooleanQuestion:
return NSLocalizedString("Boolean Question", comment: "")
case .DateQuestion:
return NSLocalizedString("Date Question", comment: "")
case .DateTimeQuestion:
return NSLocalizedString("Date and Time Question", comment: "")
case .EligibilityQuestion:
return NSLocalizedString("Eligibility Question", comment: "")
case .ImageChoiceQuestion:
return NSLocalizedString("Image Choice Question", comment: "")
case .NumericQuestion:
return NSLocalizedString("Numeric Question", comment: "")
case .ScaleQuestion:
return NSLocalizedString("Scale Question", comment: "")
case .TextQuestion:
return NSLocalizedString("Text Question", comment: "")
case .TextChoiceQuestion:
return NSLocalizedString("Text Choice Question", comment: "")
case .TimeIntervalQuestion:
return NSLocalizedString("Time Interval Question", comment: "")
case .TimeOfDayQuestion:
return NSLocalizedString("Time of Day Question", comment: "")
case .ValuePickerChoiceQuestion:
return NSLocalizedString("Value Picker Choice Question", comment: "")
case .ImageCapture:
return NSLocalizedString("Image Capture Step", comment: "")
case .EligibilityTask:
return NSLocalizedString("Eligibility Task Example", comment: "")
case .Consent:
return NSLocalizedString("Consent-Obtaining Example", comment: "")
case .Passcode:
return NSLocalizedString("Passcode Creation", comment: "")
case .Audio:
return NSLocalizedString("Audio", comment: "")
case .Fitness:
return NSLocalizedString("Fitness Check", comment: "")
case .HolePegTest:
return NSLocalizedString("Hole Peg Test", comment: "")
case .PSAT:
return NSLocalizedString("PSAT", comment: "")
case .ReactionTime:
return NSLocalizedString("Reaction Time", comment: "")
case .ShortWalk:
return NSLocalizedString("Short Walk", comment: "")
case .SpatialSpanMemory:
return NSLocalizedString("Spatial Span Memory", comment: "")
case .TimedWalk:
return NSLocalizedString("Timed Walk", comment: "")
case .ToneAudiometry:
return NSLocalizedString("Tone Audiometry", comment: "")
case .TowerOfHanoi:
return NSLocalizedString("Tower of Hanoi", comment: "")
case .TwoFingerTappingInterval:
return NSLocalizedString("Two Finger Tapping Interval", comment: "")
}
}
// MARK: Types
/**
Every step and task in the ResearchKit framework has to have an identifier.
Within a task, the step identifiers should be unique.
Here we use an enum to ensure that the identifiers are kept unique. Since
the enum has a raw underlying type of a `String`, the compiler can determine
the uniqueness of the case values at compile time.
In a real application, the identifiers for your tasks and steps might
come from a database, or in a smaller application, might have some
human-readable meaning.
*/
private enum Identifier {
// Task with a form, where multiple items appear on one page.
case FormTask
case FormStep
case FormItem01
case FormItem02
// Survey task specific identifiers.
case SurveyTask
case IntroStep
case QuestionStep
case SummaryStep
// Task with a Boolean question.
case BooleanQuestionTask
case BooleanQuestionStep
// Task with an example of date entry.
case DateQuestionTask
case DateQuestionStep
// Task with an example of date and time entry.
case DateTimeQuestionTask
case DateTimeQuestionStep
// Task with an example of an eligibility question.
case EligibilityQuestionTask
case EligibilityQuestionStep
// Task with an image choice question.
case ImageChoiceQuestionTask
case ImageChoiceQuestionStep
// Task with examples of numeric questions.
case NumericQuestionTask
case NumericQuestionStep
case NumericNoUnitQuestionStep
// Task with examples of questions with sliding scales.
case ScaleQuestionTask
case DiscreteScaleQuestionStep
case ContinuousScaleQuestionStep
case DiscreteVerticalScaleQuestionStep
case ContinuousVerticalScaleQuestionStep
case TextScaleQuestionStep
case TextVerticalScaleQuestionStep
// Task with an example of free text entry.
case TextQuestionTask
case TextQuestionStep
// Task with an example of a multiple choice question.
case TextChoiceQuestionTask
case TextChoiceQuestionStep
// Task with an example of time of day entry.
case TimeOfDayQuestionTask
case TimeOfDayQuestionStep
// Task with an example of time interval entry.
case TimeIntervalQuestionTask
case TimeIntervalQuestionStep
// Task with a value picker.
case ValuePickerChoiceQuestionTask
case ValuePickerChoiceQuestionStep
// Image capture task specific identifiers.
case ImageCaptureTask
case ImageCaptureStep
// Eligibility task specific indentifiers.
case EligibilityTask
case EligibilityIntroStep
case EligibilityFormStep
case EligibilityFormItem01
case EligibilityFormItem02
case EligibilityFormItem03
case EligibilityIneligibleStep
case EligibilityEligibleStep
// Consent task specific identifiers.
case ConsentTask
case VisualConsentStep
case ConsentSharingStep
case ConsentReviewStep
case ConsentDocumentParticipantSignature
case ConsentDocumentInvestigatorSignature
// Passcode task specific identifiers.
case PasscodeTask
case PasscodeStep
// Active tasks.
case AudioTask
case FitnessTask
case HolePegTestTask
case PSATTask
case ReactionTime
case ShortWalkTask
case SpatialSpanMemoryTask
case TimedWalkTask
case ToneAudiometryTask
case TowerOfHanoi
case TwoFingerTappingIntervalTask
}
// MARK: Properties
/// Returns a new `ORKTask` that the `TaskListRow` enumeration represents.
var representedTask: ORKTask {
switch self {
case .Form:
return formTask
case .Survey:
return surveyTask
case .BooleanQuestion:
return booleanQuestionTask
case .DateQuestion:
return dateQuestionTask
case .DateTimeQuestion:
return dateTimeQuestionTask
case .EligibilityQuestion:
return eligibilityQuestionTask
case .ImageChoiceQuestion:
return imageChoiceQuestionTask
case .NumericQuestion:
return numericQuestionTask
case .ScaleQuestion:
return scaleQuestionTask
case .TextQuestion:
return textQuestionTask
case .TextChoiceQuestion:
return textChoiceQuestionTask
case .TimeIntervalQuestion:
return timeIntervalQuestionTask
case .TimeOfDayQuestion:
return timeOfDayQuestionTask
case .ValuePickerChoiceQuestion:
return valuePickerChoiceQuestionTask
case .ImageCapture:
return imageCaptureTask
case .EligibilityTask:
return eligibilityTask
case .Consent:
return consentTask
case .Passcode:
return passcodeTask
case .Audio:
return audioTask
case .Fitness:
return fitnessTask
case .HolePegTest:
return holePegTestTask
case .PSAT:
return PSATTask
case .ReactionTime:
return reactionTimeTask
case .ShortWalk:
return shortWalkTask
case .SpatialSpanMemory:
return spatialSpanMemoryTask
case .TimedWalk:
return timedWalkTask
case .ToneAudiometry:
return toneAudiometryTask
case .TowerOfHanoi:
return towerOfHanoiTask
case .TwoFingerTappingInterval:
return twoFingerTappingIntervalTask
}
}
// MARK: Task Creation Convenience
/**
This task demonstrates a form step, in which multiple items are presented
in a single scrollable form. This might be used for entering multi-value
data, like taking a blood pressure reading with separate systolic and
diastolic values.
*/
private var formTask: ORKTask {
let step = ORKFormStep(identifier: String(Identifier.FormStep), title: exampleQuestionText, text: exampleDetailText)
// A first field, for entering an integer.
let formItem01Text = NSLocalizedString("Field01", comment: "")
let formItem01 = ORKFormItem(identifier: String(Identifier.FormItem01), text: formItem01Text, answerFormat: ORKAnswerFormat.integerAnswerFormatWithUnit(nil))
formItem01.placeholder = NSLocalizedString("Your placeholder here", comment: "")
// A second field, for entering a time interval.
let formItem02Text = NSLocalizedString("Field02", comment: "")
let formItem02 = ORKFormItem(identifier: String(Identifier.FormItem02), text: formItem02Text, answerFormat: ORKTimeIntervalAnswerFormat())
formItem02.placeholder = NSLocalizedString("Your placeholder here", comment: "")
step.formItems = [
formItem01,
formItem02
]
return ORKOrderedTask(identifier: String(Identifier.FormTask), steps: [step])
}
/**
A task demonstrating how the ResearchKit framework can be used to present a simple
survey with an introduction, a question, and a conclusion.
*/
private var surveyTask: ORKTask {
// Create the intro step.
let instructionStep = ORKInstructionStep(identifier: String(Identifier.IntroStep))
instructionStep.title = NSLocalizedString("Sample Survey", comment: "")
instructionStep.text = exampleDescription
// Add a question step.
let questionStepAnswerFormat = ORKBooleanAnswerFormat()
let questionStepTitle = NSLocalizedString("Would you like to subscribe to our newsletter?", comment: "")
let questionStep = ORKQuestionStep(identifier: String(Identifier.QuestionStep), title: questionStepTitle, answer: questionStepAnswerFormat)
// Add a summary step.
let summaryStep = ORKInstructionStep(identifier: String(Identifier.SummaryStep))
summaryStep.title = NSLocalizedString("Thanks", comment: "")
summaryStep.text = NSLocalizedString("Thank you for participating in this sample survey.", comment: "")
return ORKOrderedTask(identifier: String(Identifier.SurveyTask), steps: [
instructionStep,
questionStep,
summaryStep
])
}
/// This task presents just a single "Yes" / "No" question.
private var booleanQuestionTask: ORKTask {
let answerFormat = ORKBooleanAnswerFormat()
// We attach an answer format to a question step to specify what controls the user sees.
let questionStep = ORKQuestionStep(identifier: String(Identifier.BooleanQuestionStep), title: exampleQuestionText, answer: answerFormat)
// The detail text is shown in a small font below the title.
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.BooleanQuestionTask), steps: [questionStep])
}
/// This task demonstrates a question which asks for a date.
private var dateQuestionTask: ORKTask {
/*
The date answer format can also support minimum and maximum limits,
a specific default value, and overriding the calendar to use.
*/
let answerFormat = ORKAnswerFormat.dateAnswerFormat()
let step = ORKQuestionStep(identifier: String(Identifier.DateQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.DateQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for a date and time of an event.
private var dateTimeQuestionTask: ORKTask {
/*
This uses the default calendar. Use a more detailed constructor to
set minimum / maximum limits.
*/
let answerFormat = ORKAnswerFormat.dateTimeAnswerFormat()
let step = ORKQuestionStep(identifier: String(Identifier.DateTimeQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.DateTimeQuestionTask), steps: [step])
}
/// This task demonstrates an eligibiltiy question.
private var eligibilityQuestionTask: ORKTask {
let answerFormat = ORKAnswerFormat.eligibilityAnswerFormat();
let step = ORKQuestionStep(identifier: String(Identifier.EligibilityQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.EligibilityQuestionTask), steps: [step])
}
/**
This task demonstrates a survey question involving picking from a series of
image choices. A more realistic applciation of this type of question might be to
use a range of icons for faces ranging from happy to sad.
*/
private var imageChoiceQuestionTask: ORKTask {
let roundShapeImage = UIImage(named: "round_shape")!
let roundShapeText = NSLocalizedString("Round Shape", comment: "")
let squareShapeImage = UIImage(named: "square_shape")!
let squareShapeText = NSLocalizedString("Square Shape", comment: "")
let imageChoces = [
ORKImageChoice(normalImage: roundShapeImage, selectedImage: nil, text: roundShapeText, value: roundShapeText),
ORKImageChoice(normalImage: squareShapeImage, selectedImage: nil, text: squareShapeText, value: squareShapeText)
]
let answerFormat = ORKAnswerFormat.choiceAnswerFormatWithImageChoices(imageChoces)
let questionStep = ORKQuestionStep(identifier: String(Identifier.ImageChoiceQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.ImageChoiceQuestionTask), steps: [questionStep])
}
/**
This task demonstrates use of numeric questions with and without units.
Note that the unit is just a string, prompting the user to enter the value
in the expected unit. The unit string propagates into the result object.
*/
private var numericQuestionTask: ORKTask {
// This answer format will display a unit in-line with the numeric entry field.
let localizedQuestionStep1AnswerFormatUnit = NSLocalizedString("Your unit", comment: "")
let questionStep1AnswerFormat = ORKAnswerFormat.decimalAnswerFormatWithUnit(localizedQuestionStep1AnswerFormatUnit)
let questionStep1 = ORKQuestionStep(identifier: String(Identifier.NumericQuestionStep), title: exampleQuestionText, answer: questionStep1AnswerFormat)
questionStep1.text = exampleDetailText
questionStep1.placeholder = NSLocalizedString("Your placeholder.", comment: "")
// This answer format is similar to the previous one, but this time without displaying a unit.
let questionStep2 = ORKQuestionStep(identifier: String(Identifier.NumericNoUnitQuestionStep), title: exampleQuestionText, answer: ORKAnswerFormat.decimalAnswerFormatWithUnit(nil))
questionStep2.text = exampleDetailText
questionStep2.placeholder = NSLocalizedString("Placeholder without unit.", comment: "")
return ORKOrderedTask(identifier: String(Identifier.NumericQuestionTask), steps: [
questionStep1,
questionStep2
])
}
/// This task presents two options for questions displaying a scale control.
private var scaleQuestionTask: ORKTask {
// The first step is a scale control with 10 discrete ticks.
let step1AnswerFormat = ORKAnswerFormat.scaleAnswerFormatWithMaximumValue(10, minimumValue: 1, defaultValue: NSIntegerMax, step: 1, vertical: false, maximumValueDescription: exampleHighValueText, minimumValueDescription: exampleLowValueText)
let questionStep1 = ORKQuestionStep(identifier: String(Identifier.DiscreteScaleQuestionStep), title: exampleQuestionText, answer: step1AnswerFormat)
questionStep1.text = exampleDetailText
// The second step is a scale control that allows continuous movement with a percent formatter.
let step2AnswerFormat = ORKAnswerFormat.continuousScaleAnswerFormatWithMaximumValue(1.0, minimumValue: 0.0, defaultValue: 99.0, maximumFractionDigits: 0, vertical: false, maximumValueDescription: nil, minimumValueDescription: nil)
step2AnswerFormat.numberStyle = .Percent
let questionStep2 = ORKQuestionStep(identifier: String(Identifier.ContinuousScaleQuestionStep), title: exampleQuestionText, answer: step2AnswerFormat)
questionStep2.text = exampleDetailText
// The third step is a vertical scale control with 10 discrete ticks.
let step3AnswerFormat = ORKAnswerFormat.scaleAnswerFormatWithMaximumValue(10, minimumValue: 1, defaultValue: NSIntegerMax, step: 1, vertical: true, maximumValueDescription: nil, minimumValueDescription: nil)
let questionStep3 = ORKQuestionStep(identifier: String(Identifier.DiscreteVerticalScaleQuestionStep), title: exampleQuestionText, answer: step3AnswerFormat)
questionStep3.text = exampleDetailText
// The fourth step is a vertical scale control that allows continuous movement.
let step4AnswerFormat = ORKAnswerFormat.continuousScaleAnswerFormatWithMaximumValue(5.0, minimumValue: 1.0, defaultValue: 99.0, maximumFractionDigits: 2, vertical: true, maximumValueDescription: exampleHighValueText, minimumValueDescription: exampleLowValueText)
let questionStep4 = ORKQuestionStep(identifier: String(Identifier.ContinuousVerticalScaleQuestionStep), title: exampleQuestionText, answer: step4AnswerFormat)
questionStep4.text = exampleDetailText
// The fifth step is a scale control that allows text choices.
let textChoices : [ORKTextChoice] = [ORKTextChoice(text: "Poor", value: 1), ORKTextChoice(text: "Fair", value: 2), ORKTextChoice(text: "Good", value: 3), ORKTextChoice(text: "Above Average", value: 10), ORKTextChoice(text: "Excellent", value: 5)]
let step5AnswerFormat = ORKAnswerFormat.textScaleAnswerFormatWithTextChoices(textChoices, defaultIndex: NSIntegerMax, vertical: false)
let questionStep5 = ORKQuestionStep(identifier: String(Identifier.TextScaleQuestionStep), title: exampleQuestionText, answer: step5AnswerFormat)
questionStep5.text = exampleDetailText
// The sixth step is a vertical scale control that allows text choices.
let step6AnswerFormat = ORKAnswerFormat.textScaleAnswerFormatWithTextChoices(textChoices, defaultIndex: NSIntegerMax, vertical: true)
let questionStep6 = ORKQuestionStep(identifier: String(Identifier.TextVerticalScaleQuestionStep), title: exampleQuestionText, answer: step6AnswerFormat)
questionStep6.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.ScaleQuestionTask), steps: [
questionStep1,
questionStep2,
questionStep3,
questionStep4,
questionStep5,
questionStep6
])
}
/**
This task demonstrates asking for text entry. Both single and multi-line
text entry are supported, with appropriate parameters to the text answer
format.
*/
private var textQuestionTask: ORKTask {
let answerFormat = ORKAnswerFormat.textAnswerFormat()
let step = ORKQuestionStep(identifier: String(Identifier.TextQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.TextQuestionTask), steps: [step])
}
/**
This task demonstrates a survey question for picking from a list of text
choices. In this case, the text choices are presented in a table view
(compare with the `valuePickerQuestionTask`).
*/
private var textChoiceQuestionTask: ORKTask {
let textChoiceOneText = NSLocalizedString("Choice 1", comment: "")
let textChoiceTwoText = NSLocalizedString("Choice 2", comment: "")
let textChoiceThreeText = NSLocalizedString("Choice 3", comment: "")
// The text to display can be separate from the value coded for each choice:
let textChoices = [
ORKTextChoice(text: textChoiceOneText, value: "choice_1"),
ORKTextChoice(text: textChoiceTwoText, value: "choice_2"),
ORKTextChoice(text: textChoiceThreeText, value: "choice_3")
]
let answerFormat = ORKAnswerFormat.choiceAnswerFormatWithStyle(.SingleChoice, textChoices: textChoices)
let questionStep = ORKQuestionStep(identifier: String(Identifier.TextChoiceQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.TextChoiceQuestionTask), steps: [questionStep])
}
/**
This task demonstrates requesting a time interval. For example, this might
be a suitable answer format for a question like "How long is your morning
commute?"
*/
private var timeIntervalQuestionTask: ORKTask {
/*
The time interval answer format is constrained to entering a time
less than 24 hours and in steps of minutes. For times that don't fit
these restrictions, use another mode of data entry.
*/
let answerFormat = ORKAnswerFormat.timeIntervalAnswerFormat()
let step = ORKQuestionStep(identifier: String(Identifier.TimeIntervalQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.TimeIntervalQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for a time of day.
private var timeOfDayQuestionTask: ORKTask {
/*
Because we don't specify a default, the picker will default to the
time the step is presented. For questions like "What time do you have
breakfast?", it would make sense to set the default on the answer
format.
*/
let answerFormat = ORKAnswerFormat.timeOfDayAnswerFormat()
let questionStep = ORKQuestionStep(identifier: String(Identifier.TimeOfDayQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.TimeOfDayQuestionTask), steps: [questionStep])
}
/**
This task demonstrates a survey question using a value picker wheel.
Compare with the `textChoiceQuestionTask` and `imageChoiceQuestionTask`
which can serve a similar purpose.
*/
private var valuePickerChoiceQuestionTask: ORKTask {
let textChoiceOneText = NSLocalizedString("Choice 1", comment: "")
let textChoiceTwoText = NSLocalizedString("Choice 2", comment: "")
let textChoiceThreeText = NSLocalizedString("Choice 3", comment: "")
// The text to display can be separate from the value coded for each choice:
let textChoices = [
ORKTextChoice(text: textChoiceOneText, value: "choice_1"),
ORKTextChoice(text: textChoiceTwoText, value: "choice_2"),
ORKTextChoice(text: textChoiceThreeText, value: "choice_3")
]
let answerFormat = ORKAnswerFormat.valuePickerAnswerFormatWithTextChoices(textChoices)
let questionStep = ORKQuestionStep(identifier: String(Identifier.ValuePickerChoiceQuestionStep), title: exampleQuestionText,
answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.ValuePickerChoiceQuestionTask), steps: [questionStep])
}
/// This task presents the image capture step in an ordered task.
private var imageCaptureTask: ORKTask {
// Create the intro step.
let instructionStep = ORKInstructionStep(identifier: String(Identifier.IntroStep))
instructionStep.title = NSLocalizedString("Sample Survey", comment: "")
instructionStep.text = exampleDescription
let handSolidImage = UIImage(named: "hand_solid")!
instructionStep.image = handSolidImage.imageWithRenderingMode(.AlwaysTemplate)
let imageCaptureStep = ORKImageCaptureStep(identifier: String(Identifier.ImageCaptureStep))
imageCaptureStep.optional = false
imageCaptureStep.accessibilityInstructions = NSLocalizedString("Your instructions for capturing the image", comment: "")
imageCaptureStep.accessibilityHint = NSLocalizedString("Captures the image visible in the preview", comment: "")
imageCaptureStep.templateImage = UIImage(named: "hand_outline_big")!
imageCaptureStep.templateImageInsets = UIEdgeInsets(top: 0.05, left: 0.05, bottom: 0.05, right: 0.05)
return ORKOrderedTask(identifier: String(Identifier.ImageCaptureTask), steps: [
instructionStep,
imageCaptureStep
])
}
/**
A task demonstrating how the ResearchKit framework can be used to determine
eligibility using the eligibilty answer format and a navigable ordered task.
*/
private var eligibilityTask: ORKTask {
// Intro step
let introStep = ORKInstructionStep(identifier: String(Identifier.EligibilityIntroStep))
introStep.title = NSLocalizedString("Eligibility Task Example", comment: "")
// Form step
let formStep = ORKFormStep(identifier: String(Identifier.EligibilityFormStep))
formStep.optional = false
// Form items
let formItem01 = ORKFormItem(identifier: String(Identifier.EligibilityFormItem01), text: exampleQuestionText, answerFormat: ORKAnswerFormat.eligibilityAnswerFormat())
formItem01.optional = false
let formItem02 = ORKFormItem(identifier: String(Identifier.EligibilityFormItem02), text: exampleQuestionText, answerFormat: ORKAnswerFormat.eligibilityAnswerFormat())
formItem02.optional = false
let formItem03 = ORKFormItem(identifier: String(Identifier.EligibilityFormItem03), text: exampleQuestionText, answerFormat: ORKAnswerFormat.eligibilityAnswerFormat())
formItem03.optional = false
formStep.formItems = [
formItem01,
formItem02,
formItem03
]
// Ineligible step
let ineligibleStep = ORKInstructionStep(identifier: String(Identifier.EligibilityIneligibleStep))
ineligibleStep.title = NSLocalizedString("You are ineligible to join the study", comment: "")
// Eligible step
let eligibleStep = ORKCompletionStep(identifier: String(Identifier.EligibilityEligibleStep))
eligibleStep.title = NSLocalizedString("You are eligible to join the study", comment: "")
// Create the task
let eligibilityTask = ORKNavigableOrderedTask(identifier: String(Identifier.EligibilityTask), steps: [
introStep,
formStep,
ineligibleStep,
eligibleStep
])
// Build navigation rules.
var resultSelector = ORKResultSelector(stepIdentifier: String(Identifier.EligibilityFormStep), resultIdentifier: String(Identifier.EligibilityFormItem01))
let predicateFormItem01 = ORKResultPredicate.predicateForBooleanQuestionResultWithResultSelector(resultSelector, expectedAnswer: true)
resultSelector = ORKResultSelector(stepIdentifier: String(Identifier.EligibilityFormStep), resultIdentifier: String(Identifier.EligibilityFormItem02))
let predicateFormItem02 = ORKResultPredicate.predicateForBooleanQuestionResultWithResultSelector(resultSelector, expectedAnswer: true)
resultSelector = ORKResultSelector(stepIdentifier: String(Identifier.EligibilityFormStep), resultIdentifier: String(Identifier.EligibilityFormItem03))
let predicateFormItem03 = ORKResultPredicate.predicateForBooleanQuestionResultWithResultSelector(resultSelector, expectedAnswer: false)
let predicateEligible = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateFormItem01, predicateFormItem02, predicateFormItem03])
let predicateRule = ORKPredicateStepNavigationRule(resultPredicates: [predicateEligible], destinationStepIdentifiers: [String(Identifier.EligibilityEligibleStep)])
eligibilityTask.setNavigationRule(predicateRule, forTriggerStepIdentifier:String(Identifier.EligibilityFormStep))
// Add end direct rules to skip unneeded steps
let directRule = ORKDirectStepNavigationRule(destinationStepIdentifier: ORKNullStepIdentifier)
eligibilityTask.setNavigationRule(directRule, forTriggerStepIdentifier:String(Identifier.EligibilityIneligibleStep))
return eligibilityTask
}
/// A task demonstrating how the ResearchKit framework can be used to obtain informed consent.
private var consentTask: ORKTask {
/*
Informed consent starts by presenting an animated sequence conveying
the main points of your consent document.
*/
let visualConsentStep = ORKVisualConsentStep(identifier: String(Identifier.VisualConsentStep), document: consentDocument)
let investigatorShortDescription = NSLocalizedString("Institution", comment: "")
let investigatorLongDescription = NSLocalizedString("Institution and its partners", comment: "")
let localizedLearnMoreHTMLContent = NSLocalizedString("Your sharing learn more content here.", comment: "")
/*
If you want to share the data you collect with other researchers for
use in other studies beyond this one, it is best practice to get
explicit permission from the participant. Use the consent sharing step
for this.
*/
let sharingConsentStep = ORKConsentSharingStep(identifier: String(Identifier.ConsentSharingStep), investigatorShortDescription: investigatorShortDescription, investigatorLongDescription: investigatorLongDescription, localizedLearnMoreHTMLContent: localizedLearnMoreHTMLContent)
/*
After the visual presentation, the consent review step displays
your consent document and can obtain a signature from the participant.
The first signature in the document is the participant's signature.
This effectively tells the consent review step which signatory is
reviewing the document.
*/
let signature = consentDocument.signatures!.first
let reviewConsentStep = ORKConsentReviewStep(identifier: String(Identifier.ConsentReviewStep), signature: signature, inDocument: consentDocument)
// In a real application, you would supply your own localized text.
reviewConsentStep.text = loremIpsumText
reviewConsentStep.reasonForConsent = loremIpsumText
return ORKOrderedTask(identifier: String(Identifier.ConsentTask), steps: [
visualConsentStep,
sharingConsentStep,
reviewConsentStep
])
}
/// This task demonstrates the Passcode creation process.
private var passcodeTask: ORKTask {
/*
If you want to protect the app using a passcode. It is reccomended to
ask user to create passcode as part of the consent process and use the
authentication and editing view controllers to interact with the passcode.
The passcode is stored in the keychain.
*/
let passcodeConsentStep = ORKPasscodeStep(identifier: String(Identifier.PasscodeStep))
return ORKOrderedTask(identifier: String(Identifier.PasscodeStep), steps: [passcodeConsentStep])
}
/// This task presents the Audio pre-defined active task.
private var audioTask: ORKTask {
return ORKOrderedTask.audioTaskWithIdentifier(String(Identifier.AudioTask), intendedUseDescription: exampleDescription, speechInstruction: exampleSpeechInstruction, shortSpeechInstruction: exampleSpeechInstruction, duration: 20, recordingSettings: nil, options: [])
}
/**
This task presents the Fitness pre-defined active task. For this example,
short walking and rest durations of 20 seconds each are used, whereas more
realistic durations might be several minutes each.
*/
private var fitnessTask: ORKTask {
return ORKOrderedTask.fitnessCheckTaskWithIdentifier(String(Identifier.FitnessTask), intendedUseDescription: exampleDescription, walkDuration: 20, restDuration: 20, options: [])
}
/// This task presents the Hole Peg Test pre-defined active task.
private var holePegTestTask: ORKTask {
return ORKNavigableOrderedTask.holePegTestTaskWithIdentifier(String(Identifier.HolePegTestTask), intendedUseDescription: exampleDescription, dominantHand: .Right, numberOfPegs: 9, threshold: 0.2, rotated: false, timeLimit: 300, options: [])
}
/// This task presents the PSAT pre-defined active task.
private var PSATTask: ORKTask {
return ORKOrderedTask.PSATTaskWithIdentifier(String(Identifier.PSATTask), intendedUseDescription: exampleDescription, presentationMode: ORKPSATPresentationMode.Auditory.union(.Visual), interStimulusInterval: 3.0, stimulusDuration: 1.0, seriesLength: 60, options: [])
}
/// This task presents the Reaction Time pre-defined active task.
private var reactionTimeTask: ORKTask {
/// An example of a custom sound.
let successSoundURL = NSBundle.mainBundle().URLForResource("tap", withExtension: "aif")!
let successSound = SystemSound(soundURL: successSoundURL)!
return ORKOrderedTask.reactionTimeTaskWithIdentifier(String(Identifier.ReactionTime), intendedUseDescription: exampleDescription, maximumStimulusInterval: 10, minimumStimulusInterval: 4, thresholdAcceleration: 0.5, numberOfAttempts: 3, timeout: 3, successSound: successSound.soundID, timeoutSound: 0, failureSound: UInt32(kSystemSoundID_Vibrate), options: [])
}
/// This task presents the Gait and Balance pre-defined active task.
private var shortWalkTask: ORKTask {
return ORKOrderedTask.shortWalkTaskWithIdentifier(String(Identifier.ShortWalkTask), intendedUseDescription: exampleDescription, numberOfStepsPerLeg: 20, restDuration: 20, options: [])
}
/// This task presents the Spatial Span Memory pre-defined active task.
private var spatialSpanMemoryTask: ORKTask {
return ORKOrderedTask.spatialSpanMemoryTaskWithIdentifier(String(Identifier.SpatialSpanMemoryTask), intendedUseDescription: exampleDescription, initialSpan: 3, minimumSpan: 2, maximumSpan: 15, playSpeed: 1.0, maxTests: 5, maxConsecutiveFailures: 3, customTargetImage: nil, customTargetPluralName: nil, requireReversal: false, options: [])
}
/// This task presents the Timed Walk pre-defined active task.
private var timedWalkTask: ORKTask {
return ORKOrderedTask.timedWalkTaskWithIdentifier(String(Identifier.TimedWalkTask), intendedUseDescription: exampleDescription, distanceInMeters: 100.0, timeLimit: 180.0, options: [])
}
/// This task presents the Tone Audiometry pre-defined active task.
private var toneAudiometryTask: ORKTask {
return ORKOrderedTask.toneAudiometryTaskWithIdentifier(String(Identifier.ToneAudiometryTask), intendedUseDescription: exampleDescription, speechInstruction: nil, shortSpeechInstruction: nil, toneDuration: 20, options: [])
}
private var towerOfHanoiTask: ORKTask {
return ORKOrderedTask.towerOfHanoiTaskWithIdentifier(String(Identifier.TowerOfHanoi), intendedUseDescription: exampleDescription, numberOfDisks: 5, options: [])
}
/// This task presents the Two Finger Tapping pre-defined active task.
private var twoFingerTappingIntervalTask: ORKTask {
return ORKOrderedTask.twoFingerTappingIntervalTaskWithIdentifier(String(Identifier.TwoFingerTappingIntervalTask), intendedUseDescription: exampleDescription, duration: 20, options: [])
}
// MARK: Consent Document Creation Convenience
/**
A consent document provides the content for the visual consent and consent
review steps. This helper sets up a consent document with some dummy
content. You should populate your consent document to suit your study.
*/
private var consentDocument: ORKConsentDocument {
let consentDocument = ORKConsentDocument()
/*
This is the title of the document, displayed both for review and in
the generated PDF.
*/
consentDocument.title = NSLocalizedString("Example Consent", comment: "")
// This is the title of the signature page in the generated document.
consentDocument.signaturePageTitle = NSLocalizedString("Consent", comment: "")
/*
This is the line shown on the signature page of the generated document,
just above the signatures.
*/
consentDocument.signaturePageContent = NSLocalizedString("I agree to participate in this research study.", comment: "")
/*
Add the participant signature, which will be filled in during the
consent review process. This signature initially does not have a
signature image or a participant name; these are collected during
the consent review step.
*/
let participantSignatureTitle = NSLocalizedString("Participant", comment: "")
let participantSignature = ORKConsentSignature(forPersonWithTitle: participantSignatureTitle, dateFormatString: nil, identifier: String(Identifier.ConsentDocumentParticipantSignature))
consentDocument.addSignature(participantSignature)
/*
Add the investigator signature. This is pre-populated with the
investigator's signature image and name, and the date of their
signature. If you need to specify the date as now, you could generate
a date string with code here.
This signature is only used for the generated PDF.
*/
let signatureImage = UIImage(named: "signature")!
let investigatorSignatureTitle = NSLocalizedString("Investigator", comment: "")
let investigatorSignatureGivenName = NSLocalizedString("Jonny", comment: "")
let investigatorSignatureFamilyName = NSLocalizedString("Appleseed", comment: "")
let investigatorSignatureDateString = "3/10/15"
let investigatorSignature = ORKConsentSignature(forPersonWithTitle: investigatorSignatureTitle, dateFormatString: nil, identifier: String(Identifier.ConsentDocumentInvestigatorSignature), givenName: investigatorSignatureGivenName, familyName: investigatorSignatureFamilyName, signatureImage: signatureImage, dateString: investigatorSignatureDateString)
consentDocument.addSignature(investigatorSignature)
/*
This is the HTML content for the "Learn More" page for each consent
section. In a real consent, this would be your content, and you would
have different content for each section.
If your content is just text, you can use the `content` property
instead of the `htmlContent` property of `ORKConsentSection`.
*/
let htmlContentString = "<ul><li>Lorem</li><li>ipsum</li><li>dolor</li></ul><p>\(loremIpsumLongText)</p><p>\(loremIpsumMediumText)</p>"
/*
These are all the consent section types that have pre-defined animations
and images. We use them in this specific order, so we see the available
animated transitions.
*/
let consentSectionTypes: [ORKConsentSectionType] = [
.Overview,
.DataGathering,
.Privacy,
.DataUse,
.TimeCommitment,
.StudySurvey,
.StudyTasks,
.Withdrawing
]
/*
For each consent section type in `consentSectionTypes`, create an
`ORKConsentSection` that represents it.
In a real app, you would set specific content for each section.
*/
var consentSections: [ORKConsentSection] = consentSectionTypes.map { contentSectionType in
let consentSection = ORKConsentSection(type: contentSectionType)
consentSection.summary = loremIpsumShortText
if contentSectionType == .Overview {
consentSection.htmlContent = htmlContentString
}
else {
consentSection.content = loremIpsumLongText
}
return consentSection
}
/*
This is an example of a section that is only in the review document
or only in the generated PDF, and is not displayed in `ORKVisualConsentStep`.
*/
let consentSection = ORKConsentSection(type: .OnlyInDocument)
consentSection.summary = NSLocalizedString(".OnlyInDocument Scene Summary", comment: "")
consentSection.title = NSLocalizedString(".OnlyInDocument Scene", comment: "")
consentSection.content = loremIpsumLongText
consentSections += [consentSection]
// Set the sections on the document after they've been created.
consentDocument.sections = consentSections
return consentDocument
}
// MARK: `ORKTask` Reused Text Convenience
private var exampleDescription: String {
return NSLocalizedString("Your description goes here.", comment: "")
}
private var exampleSpeechInstruction: String {
return NSLocalizedString("Your more specific voice instruction goes here. For example, say 'Aaaah'.", comment: "")
}
private var exampleQuestionText: String {
return NSLocalizedString("Your question goes here.", comment: "")
}
private var exampleHighValueText: String {
return NSLocalizedString("High Value", comment: "")
}
private var exampleLowValueText: String {
return NSLocalizedString("Low Value", comment: "")
}
private var exampleDetailText: String {
return NSLocalizedString("Additional text can go here.", comment: "")
}
private var loremIpsumText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
private var loremIpsumShortText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}
private var loremIpsumMediumText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam adhuc, meo fortasse vitio, quid ego quaeram non perspicis. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Quonam, inquit, modo?"
}
private var loremIpsumLongText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam adhuc, meo fortasse vitio, quid ego quaeram non perspicis. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Quonam, inquit, modo? An potest, inquit ille, quicquam esse suavius quam nihil dolere? Cave putes quicquam esse verius. Quonam, inquit, modo?"
}
}
| bsd-3-clause | da54763a1262ca0a68484e987922f0f8 | 43.27917 | 367 | 0.673752 | 5.540283 | false | false | false | false |
kysonyangs/ysbilibili | ysbilibili/Classes/Zone/Controller/YSZoneItemViewController.swift | 1 | 3481 | //
// YSZoneItemViewController.swift
// ysbilibili
//
// Created by MOLBASE on 2017/8/2.
// Copyright © 2017年 YangShen. All rights reserved.
//
import UIKit
class YSZoneItemViewController: UIViewController {
var zoneItemModel: YSZoneModel?
var inset = UIEdgeInsets.zero {
didSet {
contentTableView.contentInset = inset
contentTableView.scrollIndicatorInsets = contentTableView.contentInset
}
}
var itemViewModel = YSZoneItemViewModel()
fileprivate lazy var contentTableView: UITableView = { [unowned self] in
let tableView = UITableView(frame: CGRect.zero, style: .grouped)
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.backgroundColor = kHomeBackColor
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(contentTableView)
view.layer.cornerRadius = 10
view.clipsToBounds = true
contentTableView.frame = view.bounds
contentTableView.mj_header = YSGifHeader(refreshingBlock: { [weak self] in
self?.requestData()
})
requestData()
}
}
extension YSZoneItemViewController {
fileprivate func requestData() {
guard let tid = zoneItemModel?.tid else {
return
}
itemViewModel.requestData(rid: tid) { [weak self] in
self?.contentTableView.reloadData()
self?.contentTableView.mj_header.endRefreshing()
}
}
}
extension YSZoneItemViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return itemViewModel.statusArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemViewModel.statusArray[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = YSPlayerRelatesCell.relatesCellWithTableView(tableView: tableView)
let sectionArray = itemViewModel.statusArray[indexPath.section]
let itemModel = sectionArray[indexPath.row]
cell.playItemModel = itemModel
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = YSZoneItemHeader()
if section == 0 {
header.type = .recommend
}else {
header.type = .new
}
return header
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
}
extension YSZoneItemViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("跳转到播放界面")
// let sectionArray = itemViewModel.statusArray[indexPath.section]
// let itemModel = sectionArray[indexPath.row]
// let playerVC = YSNormalPlayerViewController()
// playerVC.itemModel = itemModel
// self.navigationController?.pushViewController(playerVC, animated: true)
}
}
| mit | 9cbc3a3d8ef370b1a4c56111573d87c8 | 31.373832 | 100 | 0.658199 | 5.154762 | false | false | false | false |
volodg/iAsync.social | Pods/iAsync.utils/iAsync.utils/String/NSString+FileAttributes.swift | 3 | 3002 | //
// NSString+FileAttributes.swift
// JUtils
//
// Created by Vladimir Gorbenko on 06.06.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
public extension NSString {
func addSkipBackupAttribute() {
var b: UInt8 = 1
let attributeName = "com.apple.MobileBackup".UTF8String
let result = withUnsafePointer(&b) { value -> Int32 in
let result = bridg_setxattr(self.fileSystemRepresentation, attributeName, value, Int(1), UInt32(0), CInt(0))
return result
}
if result != -1 {
return
}
let logger = { (log: String) in
jLogger.logError(log)
}
switch (errno)
{
case ENOENT:
//options is set to XATTR_REPLACE and the named attribute does not exist.
logger("addSkipBackupAttribute: No such file or directory")
case EEXIST, ENOATTR:
//options is set to XATTR_REPLACE and the named attribute does not exist.
let log = "addSkipBackupAttribute: \(attributeName) attribute does not exist"
logger(log)
case ENOTSUP:
logger("addSkipBackupAttribute: The file system does not support extended attributes or has them disabled.")
case EROFS:
logger("addSkipBackupAttribute: The file system is mounted read-only.")
case ERANGE:
logger("addSkipBackupAttribute: The data size of the attribute is out of range (some attributes have size restric-tions).")
case EPERM:
logger("addSkipBackupAttribute: Attributes cannot be associated with this type of object. For example, attributes are not allowed for resource forks.")
case EINVAL:
logger("addSkipBackupAttribute: name or options is invalid. name must be valid UTF-8 and options must make sense.")
case ENOTDIR:
logger("addSkipBackupAttribute: A component of path is not a directory.")
case ENAMETOOLONG:
logger("addSkipBackupAttribute: name exceeded XATTR_MAXNAMELEN UTF-8 bytes, or a component of path exceeded NAME_MAX characters, or the entire path exceeded PATH_MAX characters.")
case EACCES:
logger("addSkipBackupAttribute: Search permission is denied for a component of path or permission to set the attribute is denied.")
case ELOOP:
logger("addSkipBackupAttribute: Too many symbolic links were encountered resolving path.")
case EIO:
logger("addSkipBackupAttribute: An I/O error occurred while reading from or writing to the file system.")
case E2BIG:
logger("addSkipBackupAttribute: The data size of the extended attribute is too large.")
case ENOSPC:
logger("addSkipBackupAttribute: Not enough space left on the file system.")
default:
logger("addSkipBackupAttribute: unknown error type")
}
}
}
| mit | 9bdce90e7e4cc832cb5793e271b76148 | 43.147059 | 191 | 0.64557 | 5.166954 | false | false | false | false |
Leo19/swift_begin | test-swift/Class_Inheritance.playground/Contents.swift | 1 | 1520 | //: Playground - noun: a place where people can play
// 2015-12-03 Leo)Xcode7.1
import UIKit
/* 阻止被重写的方法,只需要在关键字前加上final(final var,final func) */
class Vehicle{
var currentSpeed = 0.0
var description: String{
return "traveling at \(currentSpeed) KM per hour"
}
func makeNoise(){
// maybe its subclass will do something
}
}
let basicVehicle = Vehicle()
basicVehicle.description
// 第一个子类(自行车)给一个属性
class Bicycle: Vehicle{
var hasGlassWindow = false
}
let bicycle = Bicycle()
bicycle.currentSpeed = 15.0
bicycle.hasGlassWindow = true
print("Bicycle: \(bicycle.description)")
// 第二个子类双人自行车
class Tandem: Bicycle{
var passengers = 2
}
let tandem = Tandem()
tandem.hasGlassWindow = false
tandem.passengers = 2
tandem.currentSpeed = 18.0
print("Tandem: \(tandem.description)")
// 重写属性和方法
class Car: Vehicle{
var gear = 1
override var description: String{
print(super.description)
return super.description + " in gear \(gear)"
}
override func makeNoise() {
print("Kahh Kahh")
}
}
let car = Car()
car.currentSpeed = 35.0
car.gear = 2
print("Car: " + car.description)
car.makeNoise()
// 给继承来的属性加属性观察器,一般不同时加set和观察器
class AutomaticCar: Car{
override var currentSpeed: Double{
didSet{
gear = Int(currentSpeed / 10.0) + 1
}
}
}
| gpl-2.0 | 23a3bea2efa8563c28af51feda2ca306 | 15.554217 | 57 | 0.652838 | 3.426434 | false | false | false | false |
Alexiuce/Tip-for-day | Tip for Day Demo/AVFoundationDemo/ViewController.swift | 1 | 3627 | //
// ViewController.swift
// AVFoundationDemo
//
// Created by alexiuce on 2017/6/20.
// Copyright © 2017年 com.Alexiuce. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
// 采集设备硬件
lazy var captureDevice : AVCaptureDevice = {
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)!
return device
}();
// 采集会话(用于管理设备输入和输出)
lazy var session : AVCaptureSession = {
let session = AVCaptureSession()
// 添加输入设备到采集会话
if session.canAddInput(self.inputDevice) {
session.addInput(self.inputDevice)
}
// 添加输出到采集会话
if session.canAddOutput(self.metaOutput) {
session.addOutput(self.metaOutput)
print(self.metaOutput.availableMetadataObjectTypes)
self.metaOutput.metadataObjectTypes = [AVMetadataObjectTypeFace]
}
// 添加视频输出到采集会话
if session.canAddOutput(self.videoOutput) {
session.addOutput(self.videoOutput)
}
return session
}();
// 输入设备
lazy var inputDevice : AVCaptureDeviceInput = {
let input = try! AVCaptureDeviceInput(device: self.captureDevice)
return input
}();
// 静态图片输出 (拍照时用)
lazy var imgOutput : AVCaptureStillImageOutput = {
let output = AVCaptureStillImageOutput()
return output
}();
// 视频输出 (视频流)
lazy var videoOutput : AVCaptureVideoDataOutput = {
let output = AVCaptureVideoDataOutput()
output.setSampleBufferDelegate(self, queue: self.sessionQueue)
return output
}();
// 元数据捕获输出(条码,二维码识别,人脸识别等)
lazy var metaOutput : AVCaptureMetadataOutput = {
let output = AVCaptureMetadataOutput()
output.setMetadataObjectsDelegate(self, queue: self.sessionQueue)
/** 对于AVCaptureMetadataOutput 的设置,需要在添加到session之后进行,否则报错 */
// output.metadataObjectTypes = [AVMetadataObjectTypeFace]
return output
}();
// 采集处理队列 : 视频捕捉时用来处理捕获数据
lazy var sessionQueue : DispatchQueue = {
let queue = DispatchQueue(label: "myVideoSessionQueue")
return queue
}()
override func viewDidLoad() {
super.viewDidLoad()
let previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer?.frame = view.bounds
view.layer.addSublayer(previewLayer!)
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.session .startRunning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
self.session.stopRunning()
}
}
extension ViewController : AVCaptureMetadataOutputObjectsDelegate{
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
print(metadataObjects,Thread.current)
}
}
extension ViewController : AVCaptureVideoDataOutputSampleBufferDelegate{
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
}
}
| mit | 516f6c8ee3465cc727575ee2b392def7 | 30.186916 | 151 | 0.662871 | 5.025602 | false | false | false | false |
gmission/gmission-ios | gmission/Carthage/Checkouts/Alamofire/Tests/DownloadTests.swift | 15 | 18174 | // DownloadTests.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Foundation
import XCTest
class DownloadInitializationTestCase: BaseTestCase {
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
func testDownloadClassMethodWithMethodURLAndDestination() {
// Given
let URLString = "https://httpbin.org/"
let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
// When
let request = Alamofire.download(.GET, URLString, destination: destination)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testDownloadClassMethodWithMethodURLHeadersAndDestination() {
// Given
let URLString = "https://httpbin.org/"
let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
// When
let request = Alamofire.download(.GET, URLString, headers: ["Authorization": "123456"], destination: destination)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET")
XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal")
let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class DownloadResponseTestCase: BaseTestCase {
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
let cachesURL: NSURL = {
let cachesDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
let cachesURL = NSURL(fileURLWithPath: cachesDirectory, isDirectory: true)
return cachesURL
}()
var randomCachesFileURL: NSURL {
return cachesURL.URLByAppendingPathComponent("\(NSUUID().UUIDString).json")
}
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "https://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(
directory: searchPathDirectory,
domain: searchPathDomain
)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination: destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
do {
let contents = try fileManager.contentsOfDirectoryAtURL(
directory,
includingPropertiesForKeys: nil,
options: .SkipsHiddenFiles
)
#if os(iOS) || os(tvOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(
file.lastPathComponent ?? "",
"\(suggestedFilename)",
"filename should be \(suggestedFilename)"
)
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
do {
try fileManager.removeItemAtURL(file)
} catch {
XCTFail("file manager should remove item at URL: \(file)")
}
} else {
XCTFail("file should not be nil")
}
} catch {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "https://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0]
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: NSData?
var responseError: ErrorType?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (
completedUnitCount: download.progress.completedUnitCount,
totalUnitCount: download.progress.totalUnitCount
)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(
progressValueFractionalCompletion,
1.0,
"progress value fractional completion should equal 1.0"
)
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
do {
try fileManager.removeItemAtURL(fileURL)
} catch {
XCTFail("file manager should remove item at URL: \(fileURL)")
}
}
func testDownloadRequestWithParameters() {
// Given
let fileURL = randomCachesFileURL
let URLString = "https://httpbin.org/get"
let parameters = ["foo": "bar"]
let destination: Request.DownloadFileDestination = { _, _ in fileURL }
let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, parameters: parameters, destination: destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
if let
data = NSData(contentsOfURL: fileURL),
JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
JSON = JSONObject as? [String: AnyObject],
args = JSON["args"] as? [String: String]
{
XCTAssertEqual(args["foo"], "bar", "foo parameter should equal bar")
} else {
XCTFail("args parameter in JSON should not be nil")
}
}
func testDownloadRequestWithHeaders() {
// Given
let fileURL = randomCachesFileURL
let URLString = "https://httpbin.org/get"
let headers = ["Authorization": "123456"]
let destination: Request.DownloadFileDestination = { _, _ in fileURL }
let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, headers: headers, destination: destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
if let
data = NSData(contentsOfURL: fileURL),
JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)),
JSON = JSONObject as? [String: AnyObject],
headers = JSON["headers"] as? [String: String]
{
XCTAssertEqual(headers["Authorization"], "123456", "Authorization parameter should equal 123456")
} else {
XCTFail("headers parameter in JSON should not be nil")
}
}
}
// MARK: -
class DownloadResumeDataTestCase: BaseTestCase {
let URLString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
let destination: Request.DownloadFileDestination = {
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
return Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
}()
func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, URLString, destination: destination)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
download.cancel()
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNil(data, "data should be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertNil(download.resumeData, "resume data should be nil")
}
func testThatCancelledDownloadResponseDataMatchesResumeData() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, URLString, destination: destination)
download.progress { _, _, _ in
download.cancel()
}
download.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertNotNil(download.resumeData, "resume data should not be nil")
if let
responseData = data as? NSData,
resumeData = download.resumeData
{
XCTAssertEqual(responseData, resumeData, "response data should equal resume data")
} else {
XCTFail("response data or resume data was unexpectedly nil")
}
}
func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var response: Response<AnyObject, NSError>?
// When
let download = Alamofire.download(.GET, URLString, destination: destination)
download.progress { _, _, _ in
download.cancel()
}
download.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isFailure, "result should be failure")
XCTAssertNotNil(response.result.error, "result error should not be nil")
} else {
XCTFail("response should not be nil")
}
XCTAssertNotNil(download.resumeData, "resume data should not be nil")
}
}
| mit | 38027197f4f7fc9b478be8083eebe245 | 38.590414 | 126 | 0.643187 | 5.886621 | false | false | false | false |
swifteroid/store | source/Migration/Migration.swift | 1 | 5009 | import CoreData
import Foundation
/*
- https://kean.github.io/blog/core-data-progressive-migrations
- https://www.objc.io/issues/4-core-data/core-data-migration/
- https://izeeshan.wordpress.com/2014/11/10/core-data-migration/
- http://9elements.com/io/index.php/customizing-core-data-migrations/
- http://themainthread.com/blog/2014/03/replacing-a-core-data-store.html
*/
open class Migration {
/// Migrates data store at the given url using specified schemas and returns final schema used by the store, schemas must
/// be ordered by their version.
///
/// - Parameter bundle: Bundles where to look for mapping models, if there no mapping models, make sure to pass an
/// empty array, otherwise all bundles will be searched, which will result in some overhead.
@discardableResult open func migrate(store: URL, schemas: [Schema], bundles: [Bundle]? = nil) throws -> Schema? {
// First things first, we must figure what schema is used with data store. We do this in reverse order, because
// if for whatever reason the earlier schema will be compatible, we will be migrating our data in loops, potentially
// damaging it along the way.
let metadata: [String: Any] = try Coordinator.metadataForPersistentStore(ofType: NSSQLiteStoreType, at: store)
let index: Int = schemas.reversed().firstIndex(where: { $0.compatible(with: metadata) }) ?? -1
if index == -1 {
throw Error.noCompatibleSchema
} else if index == 0 {
return schemas.last!
}
let fileManager: FileManager = FileManager.default
let dateFormatter: DateFormatter = DateFormatter(dateFormat: "yyyy-MM-dd-HH-mm-ss")
let backupUrl: URL = store.deletingLastPathComponent()
.appendingPathComponent("Backup", isDirectory: true)
.appendingPathComponent("\(store.deletingPathExtension().lastPathComponent) - \(dateFormatter.string(from: Date()))", isDirectory: false)
.appendingPathExtension(store.pathExtension)
guard fileManager.directoryExists(at: backupUrl.deletingLastPathComponent(), create: true) else {
throw Error.file("Cannot provide backup directory for migration.")
}
try! fileManager.copyItem(at: store, to: backupUrl)
for i in schemas.count - 1 - index ..< schemas.count - 1 {
let sourceSchema: Schema = schemas[i]
let destinationSchema: Schema = schemas[i + 1]
let migrationManager: NSMigrationManager = NSMigrationManager(sourceModel: sourceSchema, destinationModel: destinationSchema)
let mapping: NSMappingModel = self.mapping(from: sourceSchema, to: destinationSchema, in: bundles)
let temporaryUrl: URL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(UUID().uuidString)
let migrationUrl: URL = temporaryUrl.appendingPathComponent(store.lastPathComponent)
guard fileManager.directoryExists(at: temporaryUrl, create: true) else {
throw Error.file("Cannot provide temporary directory for migration.")
}
try! migrationManager.migrateStore(
from: store,
sourceType: NSSQLiteStoreType,
options: nil,
with: mapping,
toDestinationURL: migrationUrl,
destinationType: NSSQLiteStoreType,
destinationOptions: nil)
// Replace source store.
if #available(OSX 10.11, *) {
try! Coordinator(managedObjectModel: destinationSchema).replacePersistentStore(
at: store,
destinationOptions: nil,
withPersistentStoreFrom: migrationUrl,
sourceOptions: nil,
ofType: NSSQLiteStoreType)
} else {
try! fileManager.removeItem(at: store)
try! fileManager.moveItem(at: migrationUrl, to: store)
}
try! fileManager.removeItem(at: temporaryUrl)
}
return schemas.last!
}
/// Find existing mapping model for two schemas or create an inferred one if it doesn't exist.
open func mapping(from source: Schema, to destination: Schema, in bundles: [Bundle]? = nil) -> NSMappingModel {
let bundles: [Bundle] = bundles ?? Bundle.allBundles + Bundle.allFrameworks
let mapping: NSMappingModel? = NSMappingModel(from: bundles, forSourceModel: source, destinationModel: destination)
return mapping ?? (try! NSMappingModel.inferredMappingModel(forSourceModel: source, destinationModel: destination))
}
public init() {
}
}
extension Migration {
public enum Error: Swift.Error {
case noCompatibleSchema
case file(String)
}
}
extension DateFormatter {
fileprivate convenience init(dateFormat: String) {
self.init()
self.dateFormat = dateFormat
}
}
| mit | b0414b906df49d5f7f1bfee6f10d6b18 | 42.556522 | 149 | 0.658016 | 4.891602 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Sporth Based Effect.xcplaygroundpage/Contents.swift | 5 | 819 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Sporth Based Effect
//: ### You can also create nodes for AudioKit using [Sporth](https://github.com/PaulBatchelor/Sporth). This is an example of an effect written in Sporth.
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("drumloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
let input = AKStereoOperation.input
let sporth = "\(input) 15 200 7.0 8.0 10000 315 0 1500 0 1 0 zitarev"
let effect = AKOperationEffect(player, sporth: sporth)
AudioKit.output = effect
AudioKit.start()
player.play()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| apache-2.0 | f21b7918b166f81e023daff639f0d5e4 | 28.25 | 154 | 0.720391 | 3.64 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.