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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zhoujihang/SwiftNetworkAgent | SwiftNetworkAgent/SwiftNetworkAgent/Request/WeatherRequestResponse.swift | 1 | 822 | //
// WeatherRequestResponse.swift
// SwiftNetworkAgent
//
// Created by 周际航 on 2017/8/9.
// Copyright © 2017年 com.zjh. All rights reserved.
//
import Foundation
import ObjectMapper
class WeatherRequestResponse: Mappable {
var air: [String: Any] = [:]
var alarm: [String: Any] = [:]
var forecast: [String: Any] = [:]
var observe: [String: Any] = [:]
required init?(map: Map) {
guard map.JSON["air"] != nil else {return nil}
guard map.JSON["alarm"] != nil else {return nil}
guard map.JSON["forecast"] != nil else {return nil}
guard map.JSON["observe"] != nil else {return nil}
}
func mapping(map: Map) {
air <- map["air"]
alarm <- map["alarm"]
forecast <- map["forecast"]
observe <- map["observe"]
}
}
| mit | 89f9169dba4ef55747f21b5f967e8bce | 25.225806 | 59 | 0.576876 | 3.695455 | false | false | false | false |
6ag/WeiboSwift-mvvm | WeiboSwift/Classes/View/Main/BaseViewController.swift | 1 | 6143 | //
// BaseViewController.swift
// WeiboSwift
//
// Created by 周剑峰 on 2017/1/16.
// Copyright © 2017年 周剑峰. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
var tableView: UITableView?
var refreshControl: JFRefreshControl?
var isPullup = false // 标记上下拉 true上拉 false下拉
var visitorInfo: [String: String]? // 访客视图信息
override func viewDidLoad() {
super.viewDidLoad()
prepareUI()
// loadData()
// 开始刷新
refreshControl?.beginRefreshing()
// 监听登录成功的通知
NotificationCenter.default.addObserver(
self,
selector: #selector(loginSuccess(notification:)),
name: NSNotification.Name(USER_LOGIN_SUCCESS_NOTIFICATION),
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/// 登录成功
@objc fileprivate func loginSuccess(notification: Notification) {
// 清除所有顶部导航栏
navItem.leftBarButtonItem = nil
navItem.rightBarButtonItem = nil
// view == nil, 再次调用view的时候会去 loadView -> viewDidLoad
view = nil
// 避免重复注册通知
NotificationCenter.default.removeObserver(self)
}
/// 加载数据 - 让子类去重写
func loadData() {
refreshControl?.endRefreshing()
}
/// 注册
@objc fileprivate func register() {
// 发出请求登录的通知
NotificationCenter.default.post(name: NSNotification.Name(NEED_USER_LOGIN_NOTIFICATION), object: nil)
}
/// 登录
@objc fileprivate func login() {
// 发出请求登录的通知
NotificationCenter.default.post(name: NSNotification.Name(NEED_USER_LOGIN_NOTIFICATION), object: nil)
}
/// 重写title属性,给自定义导航条设置标题
override var title: String? {
didSet {
navItem.title = title
}
}
// MARK: - 懒加载
/// 自定义导航条
lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
/// 自定义导航条的条目
lazy var navItem = UINavigationItem()
}
// MARK: - 设置界面
extension BaseViewController {
/// 准备UI
fileprivate func prepareUI() {
view.backgroundColor = UIColor.white
// 如果隐藏了导航栏,会缩进20。需要取消自动缩进
automaticallyAdjustsScrollViewInsets = false
prepareNavigationBar()
NetworkManager.shared.isLogin ? prepareTableView() : prepareVisitorView()
}
/// 设置导航条
private func prepareNavigationBar() {
// 添加导航条
view.addSubview(navigationBar)
// 设置条目
navigationBar.items = [navItem]
// 背景颜色
navigationBar.barTintColor = UIColor.cz_color(withHex: 0xf6f6f6)
// 标题文字颜色
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.darkGray]
// 按钮文字颜色
navigationBar.tintColor = UIColor.orange
// 是否有半透明效果
navigationBar.isTranslucent = false
}
/// 设置登录后的表格视图 - 登录后的视图
func prepareTableView() {
tableView = UITableView(frame: view.bounds, style: .plain)
view.insertSubview(tableView!, belowSubview: navigationBar)
tableView?.dataSource = self
tableView?.delegate = self
let inset = UIEdgeInsets(top: navigationBar.bounds.height,
left: 0,
bottom: tabBarController?.tabBar.bounds.height ?? 49,
right: 0)
// 偏移内容区域
tableView?.contentInset = inset
// 偏移滚动条区域
tableView?.scrollIndicatorInsets = inset
// 设置刷新控件
refreshControl = JFRefreshControl()
// 添加刷新控件到表格视图
tableView?.addSubview(refreshControl!)
// 添加监听方法
refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
}
/// 设置未登录的访客视图 - 登录前的视图
private func prepareVisitorView() {
let visitorView = VisitorView(frame: view.bounds.insetBy(dx: 0, dy: 49))
visitorView.visitorInfo = visitorInfo
view.insertSubview(visitorView, belowSubview: navigationBar)
visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .done, target: self, action: #selector(register))
navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .done, target: self, action: #selector(login))
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension BaseViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// 取出某组的行数
let section = tableView.numberOfSections - 1
let count = tableView.numberOfRows(inSection: section) - 1
// 是否是最后一个cell并且还没有上拉刷新
if indexPath.row == count && !isPullup {
isPullup = true
loadData()
}
}
}
| mit | 1b20dae5af095a7cfcada77c2c2c072e | 29.888889 | 121 | 0.616187 | 4.937833 | false | false | false | false |
zisko/swift | stdlib/public/core/CollectionAlgorithms.swift | 1 | 19589 | //===--- CollectionAlgorithms.swift.gyb -----------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// last
//===----------------------------------------------------------------------===//
extension BidirectionalCollection {
/// The last element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let lastNumber = numbers.last {
/// print(lastNumber)
/// }
/// // Prints "50"
@_inlineable
public var last: Element? {
return isEmpty ? nil : self[index(before: endIndex)]
}
}
//===----------------------------------------------------------------------===//
// index(of:)/index(where:)
//===----------------------------------------------------------------------===//
extension Collection where Element : Equatable {
/// Returns the first index where the specified value appears in the
/// collection.
///
/// After using `index(of:)` to find the position of a particular element in
/// a collection, you can use it to access the element by subscripting. This
/// example shows how you can modify one of the names in an array of
/// students.
///
/// var students = ["Ben", "Ivy", "Jordell", "Maxime"]
/// if let i = students.index(of: "Maxime") {
/// students[i] = "Max"
/// }
/// print(students)
/// // Prints "["Ben", "Ivy", "Jordell", "Max"]"
///
/// - Parameter element: An element to search for in the collection.
/// - Returns: The first index where `element` is found. If `element` is not
/// found in the collection, returns `nil`.
@_inlineable
public func index(of element: Element) -> Index? {
if let result = _customIndexOfEquatableElement(element) {
return result
}
var i = self.startIndex
while i != self.endIndex {
if self[i] == element {
return i
}
self.formIndex(after: &i)
}
return nil
}
}
extension Collection {
/// Returns the first index in which an element of the collection satisfies
/// the given predicate.
///
/// You can use the predicate to find an element of a type that doesn't
/// conform to the `Equatable` protocol or to find an element that matches
/// particular criteria. Here's an example that finds a student name that
/// begins with the letter "A":
///
/// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// if let i = students.index(where: { $0.hasPrefix("A") }) {
/// print("\(students[i]) starts with 'A'!")
/// }
/// // Prints "Abena starts with 'A'!"
///
/// - Parameter predicate: A closure that takes an element as its argument
/// and returns a Boolean value that indicates whether the passed element
/// represents a match.
/// - Returns: The index of the first element for which `predicate` returns
/// `true`. If no elements in the collection satisfy the given predicate,
/// returns `nil`.
@_inlineable
public func index(
where predicate: (Element) throws -> Bool
) rethrows -> Index? {
var i = self.startIndex
while i != self.endIndex {
if try predicate(self[i]) {
return i
}
self.formIndex(after: &i)
}
return nil
}
}
//===----------------------------------------------------------------------===//
// partition(by:)
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Reorders the elements of the collection such that all the elements
/// that match the given predicate are after all the elements that don't
/// match.
///
/// After partitioning a collection, there is a pivot index `p` where
/// no element before `p` satisfies the `belongsInSecondPartition`
/// predicate and every element at or after `p` satisfies
/// `belongsInSecondPartition`.
///
/// In the following example, an array of numbers is partitioned by a
/// predicate that matches elements greater than 30.
///
/// var numbers = [30, 40, 20, 30, 30, 60, 10]
/// let p = numbers.partition(by: { $0 > 30 })
/// // p == 5
/// // numbers == [30, 10, 20, 30, 30, 60, 40]
///
/// The `numbers` array is now arranged in two partitions. The first
/// partition, `numbers[..<p]`, is made up of the elements that
/// are not greater than 30. The second partition, `numbers[p...]`,
/// is made up of the elements that *are* greater than 30.
///
/// let first = numbers[..<p]
/// // first == [30, 10, 20, 30, 30]
/// let second = numbers[p...]
/// // second == [60, 40]
///
/// - Parameter belongsInSecondPartition: A predicate used to partition
/// the collection. All elements satisfying this predicate are ordered
/// after all elements not satisfying it.
/// - Returns: The index of the first element in the reordered collection
/// that matches `belongsInSecondPartition`. If no elements in the
/// collection match `belongsInSecondPartition`, the returned index is
/// equal to the collection's `endIndex`.
///
/// - Complexity: O(*n*)
@_inlineable
public mutating func partition(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
var pivot = startIndex
while true {
if pivot == endIndex {
return pivot
}
if try belongsInSecondPartition(self[pivot]) {
break
}
formIndex(after: &pivot)
}
var i = index(after: pivot)
while i < endIndex {
if try !belongsInSecondPartition(self[i]) {
swapAt(i, pivot)
formIndex(after: &pivot)
}
formIndex(after: &i)
}
return pivot
}
}
extension MutableCollection where Self : BidirectionalCollection {
/// Reorders the elements of the collection such that all the elements
/// that match the given predicate are after all the elements that don't
/// match.
///
/// After partitioning a collection, there is a pivot index `p` where
/// no element before `p` satisfies the `belongsInSecondPartition`
/// predicate and every element at or after `p` satisfies
/// `belongsInSecondPartition`.
///
/// In the following example, an array of numbers is partitioned by a
/// predicate that matches elements greater than 30.
///
/// var numbers = [30, 40, 20, 30, 30, 60, 10]
/// let p = numbers.partition(by: { $0 > 30 })
/// // p == 5
/// // numbers == [30, 10, 20, 30, 30, 60, 40]
///
/// The `numbers` array is now arranged in two partitions. The first
/// partition, `numbers[..<p]`, is made up of the elements that
/// are not greater than 30. The second partition, `numbers[p...]`,
/// is made up of the elements that *are* greater than 30.
///
/// let first = numbers[..<p]
/// // first == [30, 10, 20, 30, 30]
/// let second = numbers[p...]
/// // second == [60, 40]
///
/// - Parameter belongsInSecondPartition: A predicate used to partition
/// the collection. All elements satisfying this predicate are ordered
/// after all elements not satisfying it.
/// - Returns: The index of the first element in the reordered collection
/// that matches `belongsInSecondPartition`. If no elements in the
/// collection match `belongsInSecondPartition`, the returned index is
/// equal to the collection's `endIndex`.
///
/// - Complexity: O(*n*)
@_inlineable
public mutating func partition(
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
let maybeOffset = try _withUnsafeMutableBufferPointerIfSupported {
(bufferPointer) -> Int in
let unsafeBufferPivot = try bufferPointer.partition(
by: belongsInSecondPartition)
return unsafeBufferPivot - bufferPointer.startIndex
}
if let offset = maybeOffset {
return index(startIndex, offsetBy: numericCast(offset))
}
var lo = startIndex
var hi = endIndex
// 'Loop' invariants (at start of Loop, all are true):
// * lo < hi
// * predicate(self[i]) == false, for i in startIndex ..< lo
// * predicate(self[i]) == true, for i in hi ..< endIndex
Loop: while true {
FindLo: repeat {
while lo < hi {
if try belongsInSecondPartition(self[lo]) { break FindLo }
formIndex(after: &lo)
}
break Loop
} while false
FindHi: repeat {
formIndex(before: &hi)
while lo < hi {
if try !belongsInSecondPartition(self[hi]) { break FindHi }
formIndex(before: &hi)
}
break Loop
} while false
swapAt(lo, hi)
formIndex(after: &lo)
}
return lo
}
}
//===----------------------------------------------------------------------===//
// sorted()/sort()
//===----------------------------------------------------------------------===//
extension Sequence where Element : Comparable {
/// Returns the elements of the sequence, sorted.
///
/// You can sort any sequence of elements that conform to the `Comparable`
/// protocol by calling this method. Elements are sorted in ascending order.
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements that compare equal.
///
/// Here's an example of sorting a list of students' names. Strings in Swift
/// conform to the `Comparable` protocol, so the names are sorted in
/// ascending order according to the less-than operator (`<`).
///
/// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// let sortedStudents = students.sorted()
/// print(sortedStudents)
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// To sort the elements of your sequence in descending order, pass the
/// greater-than operator (`>`) to the `sorted(by:)` method.
///
/// let descendingStudents = students.sorted(by: >)
/// print(descendingStudents)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// - Returns: A sorted array of the sequence's elements.
@_inlineable
public func sorted() -> [Element] {
var result = ContiguousArray(self)
result.sort()
return Array(result)
}
}
extension Sequence {
/// Returns the elements of the sequence, sorted using the given predicate as
/// the comparison between elements.
///
/// When you want to sort a sequence of elements that don't conform to the
/// `Comparable` protocol, pass a predicate to this method that returns
/// `true` when the first element passed should be ordered before the
/// second. The elements of the resulting array are ordered according to the
/// given predicate.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also `true`.
/// (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements for which `areInIncreasingOrder` does not
/// establish an order.
///
/// In the following example, the predicate provides an ordering for an array
/// of a custom `HTTPResponse` type. The predicate orders errors before
/// successes and sorts the error responses by their error code.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
/// let sortedResponses = responses.sorted {
/// switch ($0, $1) {
/// // Order errors by code
/// case let (.error(aCode), .error(bCode)):
/// return aCode < bCode
///
/// // All successes are equivalent, so none is before any other
/// case (.ok, .ok): return false
///
/// // Order errors before successes
/// case (.error, .ok): return true
/// case (.ok, .error): return false
/// }
/// }
/// print(sortedResponses)
/// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
///
/// You also use this method to sort elements that conform to the
/// `Comparable` protocol in descending order. To sort your sequence in
/// descending order, pass the greater-than operator (`>`) as the
/// `areInIncreasingOrder` parameter.
///
/// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// let descendingStudents = students.sorted(by: >)
/// print(descendingStudents)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// Calling the related `sorted()` method is equivalent to calling this
/// method and passing the less-than operator (`<`) as the predicate.
///
/// print(students.sorted())
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
/// print(students.sorted(by: <))
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: A sorted array of the sequence's elements.
@_inlineable
public func sorted(
by areInIncreasingOrder:
(Element, Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray(self)
try result.sort(by: areInIncreasingOrder)
return Array(result)
}
}
extension MutableCollection
where
Self : RandomAccessCollection, Element : Comparable {
/// Sorts the collection in place.
///
/// You can sort any mutable collection of elements that conform to the
/// `Comparable` protocol by calling this method. Elements are sorted in
/// ascending order.
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements that compare equal.
///
/// Here's an example of sorting a list of students' names. Strings in Swift
/// conform to the `Comparable` protocol, so the names are sorted in
/// ascending order according to the less-than operator (`<`).
///
/// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// students.sort()
/// print(students)
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// To sort the elements of your collection in descending order, pass the
/// greater-than operator (`>`) to the `sort(by:)` method.
///
/// students.sort(by: >)
/// print(students)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
@_inlineable
public mutating func sort() {
let didSortUnsafeBuffer: Void? =
_withUnsafeMutableBufferPointerIfSupported {
(bufferPointer) -> Void in
bufferPointer.sort()
return ()
}
if didSortUnsafeBuffer == nil {
_introSort(&self, subRange: startIndex..<endIndex)
}
}
}
extension MutableCollection where Self : RandomAccessCollection {
/// Sorts the collection in place, using the given predicate as the
/// comparison between elements.
///
/// When you want to sort a collection of elements that doesn't conform to
/// the `Comparable` protocol, pass a closure to this method that returns
/// `true` when the first element passed should be ordered before the
/// second.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also `true`.
/// (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements for which `areInIncreasingOrder` does not
/// establish an order.
///
/// In the following example, the closure provides an ordering for an array
/// of a custom enumeration that describes an HTTP response. The predicate
/// orders errors before successes and sorts the error responses by their
/// error code.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// var responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
/// responses.sort {
/// switch ($0, $1) {
/// // Order errors by code
/// case let (.error(aCode), .error(bCode)):
/// return aCode < bCode
///
/// // All successes are equivalent, so none is before any other
/// case (.ok, .ok): return false
///
/// // Order errors before successes
/// case (.error, .ok): return true
/// case (.ok, .error): return false
/// }
/// }
/// print(responses)
/// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
///
/// Alternatively, use this method to sort a collection of elements that do
/// conform to `Comparable` when you want the sort to be descending instead
/// of ascending. Pass the greater-than operator (`>`) operator as the
/// predicate.
///
/// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// students.sort(by: >)
/// print(students)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`. If `areInIncreasingOrder` throws an error during
/// the sort, the elements may be in a different order, but none will be
/// lost.
@_inlineable
public mutating func sort(
by areInIncreasingOrder:
(Element, Element) throws -> Bool
) rethrows {
let didSortUnsafeBuffer: Void? =
try _withUnsafeMutableBufferPointerIfSupported {
(bufferPointer) -> Void in
try bufferPointer.sort(by: areInIncreasingOrder)
return ()
}
if didSortUnsafeBuffer == nil {
try _introSort(
&self,
subRange: startIndex..<endIndex,
by: areInIncreasingOrder)
}
}
}
| apache-2.0 | 7503728e5829687e3a21dce923e35e16 | 36.816602 | 91 | 0.597784 | 4.253855 | false | false | false | false |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Login/LoginViewModel.swift | 1 | 1693 | //
// LoginViewModel.swift
// HiPDA
//
// Created by leizh007 on 16/9/4.
// Copyright © 2016年 HiPDA. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Curry
/// 登录的ViewModel
struct LoginViewModel {
/// 安全问题数组
static let questions = [
"安全问题",
"母亲的名字",
"爷爷的名字",
"父亲出生的城市",
"您其中一位老师的名字",
"您个人计算机的型号",
"您最喜欢的餐馆名称",
"驾驶执照的最后四位数字"
]
/// 登录按钮是否可点
let loginEnabled: Driver<Bool>
/// 是否登录成功
let loggedIn: Driver<LoginResult>
init(username: Driver<String>, password: Driver<String>, questionid: Driver<Int>, answer: Driver<String>, loginTaps: Driver<Void>) {
loginEnabled = Driver.combineLatest(username, password, questionid, answer) { (username, password, questionid, answer) in
username.characters.count > 0 &&
password.characters.count > 0 &&
(questionid == 0 || answer.characters.count > 0)
}
let accountInfos = Driver.combineLatest(username, password, questionid, answer) { ($0, $1, $2, $3) }
loggedIn = loginTaps.withLatestFrom(accountInfos)
.map { Account(name: $0, uid: 0, questionid: $2, answer: $3, password: $1) } // 这里传密码和密码md5加密后的都能登录成功...
.flatMapLatest { account in
return LoginManager.login(with: account)
.asDriver(onErrorJustReturn: .failure(.unKnown("未知错误")))
}
}
}
| mit | f13bbbca9809c04a704ca04b126b7fd1 | 28.6 | 136 | 0.591892 | 3.654321 | false | true | false | false |
TonyTong1993/test | DayDayNews/DayDayNews/Profile/View/YHProfileViewController.swift | 1 | 3860 | //
// YHProfileViewController.swift
// DayDayNews
//
// Created by 马卿 on 16/10/11.
// Copyright © 2016年 com.yihe. All rights reserved.
//
import UIKit
class YHProfileViewController: YHBaseViewController {
var dataSource : [YHSettingGroup]?
let ID = "cell"
override func viewDidLoad() {
super.viewDidLoad()
let collectionItem = YHSettingItem(icon: "MorePush", title: "收藏", itemType: .arrowAccessory)
collectionItem.option = { _ in
print("collectionItem")
}
let nightModeItem = YHSettingItem(icon: "handShake", title: "夜间模式", itemType: .switchAccessory)
let firstItems = [collectionItem,nightModeItem]
let helpItem = YHSettingItem(icon: "MoreHelp", title: "帮助与反馈", itemType: .arrowAccessory)
helpItem.detialText = "0"
helpItem.option = { _ in
print("helpItem")
}
let shareItem = YHSettingItem(icon: "MoreShare", title: "分享给好友", itemType: .arrowAccessory)
shareItem.option = { _ in
print("shareItem")
}
let clearItem = YHSettingItem(icon: "handShake", title: "清除缓存", itemType: .arrowAccessory)
clearItem.option = { _ in
print("clearItem")
}
clearItem.detialText = "100M"
let aboutItem = YHSettingItem(icon: "MoreAbout", title: "关于", itemType: .arrowAccessory)
aboutItem.option = { _ in
print("aboutItem")
}
let secondItems = [helpItem,shareItem,clearItem,aboutItem]
let groupZero = YHSettingGroup(items: firstItems)
let groupOne = YHSettingGroup(items: secondItems)
dataSource = [YHSettingGroup]()
dataSource?.append(groupZero)
dataSource?.append(groupOne)
}
override func setUpTableView() {
//设置 tableHeaderView
tableView = UITableView(frame: view.bounds, style: .Grouped )
tableView?.backgroundColor = randomColor
//实现数据源、代理方法
tableView?.delegate = self
tableView?.dataSource = self
view.addSubview(tableView!)
let rect = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: view.bounds.size.height/3);
let headerView = YHProfileHeadView(frame: rect);
headerView.backgroundColor = randomColor
tableView?.tableHeaderView = headerView;
}
}
extension YHProfileViewController{
@objc override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
guard let dataSource = dataSource else{
return 0
}
return dataSource.count
}
@objc override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let dataSource = dataSource else{
return 0
}
let group = dataSource[section]
return group.items.count
}
@objc override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = dataSource![indexPath.section].items[indexPath.row];
let cell = YHSettingCell(style: .Value1, reuseIdentifier: ID)
cell.item = item
return cell;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true);
let item = dataSource![indexPath.section].items[indexPath.row];
guard let option = item.option else{
return
}
switch item.itemType {
case .arrowAccessory:
option()
default:
break
}
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1
}
} | mit | af3a9d89e5ccb45ea8f3d90cdee017f2 | 34.383178 | 125 | 0.624835 | 4.610231 | false | false | false | false |
tristanchu/FlavorFinder | FlavorFinder/FlavorFinder/SearchUtils.swift | 1 | 7975 | //
// SearchUtils.swift
// FlavorFinder
//
// Util functions to use in search
//
// Created by Courtney Ligh on 2/2/16.
// Copyright © 2016 TeamFive. All rights reserved.
//
import UIKit
import Parse
// MARK: Properties: -----------------------------------------------
var currentSearch : [PFIngredient] = []
var currentResults : [(ingredient: PFIngredient, rank: Double)] = []
var currentIngredientToAdd : [PFIngredient] = []
// Search Term Parsing Functions: ------------------------------------
/* getPossibleIngredients
- returns list of possible ingredients with partial name matching to string
*/
func getPossibleIngredients(searchText: String) -> [PFIngredient] {
if let allIngredients = _allIngredients as? [PFIngredient] {
var filteredResults = allIngredients.filter({ (ingredient) -> Bool in
let tmp: PFObject = ingredient
let range = tmp[_s_name].rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
return range.location != NSNotFound
})
filteredResults = sortIngredientsByPartialStringMatch(searchText, possibleIngredients: filteredResults)
return filteredResults
} else {
return [PFIngredient]()
}
}
/* sortIngredientsByPartialStringMatch
- sorts list of possible matches with exact match, prefix, then suffix, then general matches
- sorts alphabetically within those categories
*/
func sortIngredientsByPartialStringMatch(searchText: String, possibleIngredients: [PFIngredient]) -> [PFIngredient] {
return possibleIngredients.sort({ a, b -> Bool in // return true to sort a before b, false for reverse
if a.name == searchText {
return true
} else if b.name == searchText {
return false
} else if a.name.hasPrefix(searchText) {
if b.name.hasPrefix(searchText) && a.name > b.name {
return false
} else {
return true
}
} else if b.name.hasPrefix(searchText) {
return false
} else if a.name.hasSuffix(searchText) {
if b.name.hasSuffix(searchText) && a.name > b.name {
return false
} else {
return true
}
} else if b.name.hasSuffix(searchText) {
return false
} else if a.name > b.name {
return false
} else {
return true
}
})
}
/* sortPrefixSuffixNeither
- sorts two of ingredients vs. a string with prefix, then suffix, then general matches
*/
func sortPrefixSuffixNeither(value1: String, value2: String) -> Bool {
// One string is alphabetically first.
// ... True means value1 precedes value2.
return value1 < value2;
}
// Parse DB Functions: -----------------------------------------------
/* getMatchingIngredients
Queries Parse db for match objects for given ingredient then
returns [(PFIngredient, Double)] of the matching ingredients
*/
func getMatchingIngredients(ingredient: PFIngredient) -> [(ingredient: PFIngredient, rank: Double)] {
var results: [(ingredient: PFIngredient, rank: Double)] = []
let matches: [PFObject] = getMatchObjectsForIngredient(ingredient)
// TODO: change to mapping:
for match in matches {
let otherIngredient =
(match[_s_secondIngredient] as! PFIngredient == ingredient)
? match[_s_firstIngredient] as! PFIngredient
: match[_s_secondIngredient] as! PFIngredient
let matchRank = match[_s_matchLevel] as? Int
let upvotes = match[_s_upvotes] as! Int
let downvotes = match[_s_downvotes] as! Int
// TODO: transition off of matchLevel, or find better conversion to votes (magic # now)
var ups = upvotes
if let _ = matchRank {
ups += matchRank! * 30
}
let downs = downvotes
let confidenceRank = confidence(ups, downs: downs)
results.append((ingredient: otherIngredient, rank: confidenceRank))
}
return results
}
/* getMatchObjectsForIngredient
Queries parse db for match objects for given ingredient.
returns [PFObject] - match objects
*/
func getMatchObjectsForIngredient(ingredient: PFIngredient) -> [PFObject] {
let query = PFQuery(className: _s_Match)
query.whereKey(_s_firstIngredient, equalTo: ingredient)
query.includeKey(_s_name)
query.limit = QUERY_LIMIT
var _matches: [PFObject]
do {
_matches = try query.findObjects()
} catch {
_matches = []
}
return _matches
}
// Search Functions: -----------------------------------------------
/* addToSearch
current_results = [PFIngredient] existing results
new_ingredient = PFIngredient to be added to currentSearch
filters current results -> keeps what also matches with new ingredient
returns new results
*/
func addToSearch(currentResults: [(ingredient: PFIngredient, rank: Double)], newIngredient: PFIngredient) -> [(ingredient: PFIngredient, rank: Double)] {
// Create new results list to populate
var newResults : [(ingredient: PFIngredient, rank: Double)] = []
// get new ingredient matches:
let newIngredientMatches = getMatchingIngredients(newIngredient);
// check if each old result in matches for new ingredient.
// if they are, then keep it and add ranks together.
for oldResult in currentResults {
// findMatchRank returns -1 if not found
let newIngredientMatchRank = findMatchRank(newIngredientMatches, b: oldResult)
if newIngredientMatchRank >= 0 {
let newRank = oldResult.rank + newIngredientMatchRank
newResults.append((ingredient: oldResult.ingredient, rank: newRank))
}
}
return newResults
}
/* getMultiSearch
creates results [(ingredient: PFIngredient, rank: Double)] based on the
currentSearch [PFIngredient]
*/
func getMultiSearch(currSearch: [PFIngredient]) -> [(ingredient: PFIngredient, rank: Double)] {
// Create new results list to populate:
var newResults : [(ingredient: PFIngredient, rank: Double)] = []
// if currSearch is empty (it shouldn't be) return empty
if currSearch.isEmpty { return newResults }
// get search results for first ingredient:
newResults = getMatchingIngredients(currSearch[0])
// go through rest of ingredients:
for i in 1..<currSearch.count {
newResults = addToSearch(newResults, newIngredient: currSearch[i])
}
// return ending results
return newResults
}
// SEARCH HELPER FUNCTIONS --------------------------------------
/* sortByRank -- sorts results by rank
*/
func sortByRank(results: [(ingredient: PFIngredient, rank: Double)]) -> [(ingredient: PFIngredient, rank: Double)] {
return results.sort {$0.1 == $1.1 ? $0.1 > $1.1 : $0.1 > $1.1 }
}
/* containsIngredient
- helper function to see if results contain an ingredient
(for multi-search)
*/
func containsIngredient(a: [(ingredient: PFIngredient, rank: Double)], b: PFIngredient) -> Bool {
// return true if ingredient found in the first part of the tuple
for (a1, _) in a { if a1 == b { return true}}
return false
}
/* containsMatch
- helper function to see if results match by ingredient (ignoring rank)
returns if a contains b (or b is found in a)
*/
func containsMatch(a: [(ingredient: PFIngredient, rank: Double)], b: (ingredient: PFIngredient, rank: Double)) -> Bool {
let (b1, _) = b
for (a1, _) in a { if a1 == b1 {return true}}
return false
}
/* findMatchRank
- helper function to see if can find current result (ingredient, rank) in
list of them.
looks for if a contains b (or b is found in a)
-- returns b2 rank if yes, -1 if not
*/
func findMatchRank(a: [(ingredient: PFIngredient, rank: Double)], b: (ingredient: PFIngredient, rank: Double)) -> Double {
let (b1, _) = b
for (a1, a2) in a { if a1 == b1 { return a2 }}
return -1
}
| mit | dbaa903b84cd2250d3504ee7dd9fbe73 | 34.44 | 153 | 0.643466 | 4.336052 | false | false | false | false |
AlesTsurko/DNMKit | DNM_iOS/DNM_iOS/Staff.swift | 1 | 9986 | //
// Staff.swift
// denm_view
//
// Created by James Bean on 8/17/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
import DNMModel
public class Staff: Graph, Guido {
// Size
public var g: CGFloat = 0
public var s: CGFloat = 1
public var gS: CGFloat { get { return g * s } }
public var lineWidth: CGFloat { get { return 0.0618 * gS } }
public var ledgerLineLength: CGFloat { get { return 2 * gS} }
public var ledgerLineWidth: CGFloat { get { return 1.875 * lineWidth } }
public var lines: [CAShapeLayer] = []
public var currentEvent: StaffEvent? { get { return events.last as? StaffEvent } }
public init(id: String, g: CGFloat) {
super.init(id: id)
self.g = g
}
public init(g: CGFloat, s: CGFloat = 1) {
super.init()
self.g = g
self.s = s
}
public init(left: CGFloat, top: CGFloat, g: CGFloat, s: CGFloat = 1) {
super.init()
self.left = left
self.top = top
self.g = g
self.s = s
pad_top = 2 * g
pad_bottom = 2 * g
}
public override init() { super.init() }
public override init(layer: AnyObject) { super.init(layer: layer) }
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
public func addClefWithType(
type: String,
withTransposition transposition: Int = 0,
atX x: CGFloat
)
{
if let clefType = ClefStaffType(rawValue: type) {
addClefWithType(clefType, withTransposition: transposition, atX: x)
}
}
public func addClefWithType(
type: ClefStaffType,
withTransposition transposition: Int = 0,
atX x: CGFloat
)
{
if clefs.count > 0 && lastLinesX != nil { stopLinesAtX(x - 0.618 * gS) }
let clef = ClefStaff.withType(type, transposition: transposition, x: x, top: 0, g: g, s: s)!
clefsLayer.addSublayer(clef)
clefs.append(clef)
startLinesAtX(x)
}
public override func startEventAtX(x: CGFloat,
withStemDirection stemDirection: StemDirection
) -> GraphEvent
{
let event = StaffEvent(x: x, stemDirection: stemDirection, staff: self, stem: nil)
event.graph = self
events.append(event)
startLinesAtX(x)
return event
}
public func middleCPositionAtX(x: CGFloat) -> CGFloat? {
if clefs.count == 0 { return nil }
if let mostRecentClef = clefs.sort({$0.x < $1.x}).filter({$0.x <= x}).last as? ClefStaff {
return mostRecentClef.middleCPosition
}
return nil
}
public func addPitchToCurrentEvent(pitch: Pitch) {
assert(currentEvent != nil, "no current event")
currentEvent?.addPitch(pitch, respellVerticality: false, andUpdateView: false)
}
public func addPitchToCurrentEvent(
pitch pitch: Pitch,
respellVerticality shouldRespellVerticality: Bool,
andUpdateView shouldUpdateView: Bool
)
{
assert(currentEvent != nil, "no current event")
currentEvent?.addPitch(pitch,
respellVerticality: shouldRespellVerticality,
andUpdateView: shouldUpdateView
)
}
public func addArticulationToCurrentEventWithType(type: ArticulationType) {
assert(currentEvent != nil, "no current event")
currentEvent?.addArticulationWithType(type)
}
public override func startLinesAtX(x: CGFloat) {
lastLinesX = x
lineActions.append(LineActionStart(x: x))
}
public override func stopLinesAtX(x: CGFloat) {
//assert(lastLinesX != nil, "must have started a line to stop a line")
lineActions.append(LineActionStop(x: x))
lastLinesX = nil
}
public func addLedgerLinesAtX(x: CGFloat, toLevel level: Int) -> [CAShapeLayer] {
var ledgerLines: [CAShapeLayer] = []
for l in 1...abs(level) {
let y: CGFloat = level > 0 ? -CGFloat(l) * g : /*height + CGFloat(l) * g*/ 4 * g + CGFloat(l) * g
let line = CAShapeLayer()
let line_path = UIBezierPath()
line_path.moveToPoint(CGPointMake(x - 0.5 * ledgerLineLength, y))
line_path.addLineToPoint(CGPointMake(x + 0.5 * ledgerLineLength, y))
line.path = line_path.CGPath
line.lineWidth = ledgerLineWidth
line.strokeColor = UIColor.grayscaleColorWithDepthOfField(.Middleground).CGColor
addLine(line)
ledgerLines.append(line)
}
return ledgerLines
}
public func addLine(line: CAShapeLayer) {
lines.append(line)
linesLayer.addSublayer(line)
}
// deprecate
public func addClef(clef: ClefStaff) {
clefsLayer.addSublayer(clef)
clefs.append(clef)
}
public override func build() {
commitLines()
commitClefs()
commitEvents()
setFrame()
adjustLayersYForMinY()
//addSkylines()
hasBeenBuilt = true
}
private func addSkylineAbove() {
let skyline = CAShapeLayer()
let path = UIBezierPath()
for (g, graphEvent) in events.enumerate() {
if g == 0 {
let y = convertY(graphEvent.minY, fromLayer: eventsLayer)
path.moveToPoint(CGPoint(x: graphEvent.x, y: y))
}
else {
let y = convertY(graphEvent.minY, fromLayer: eventsLayer)
path.addLineToPoint(CGPoint(x: graphEvent.x, y: y))
}
}
skyline.path = path.CGPath
skyline.strokeColor = UIColor.greenColor().CGColor
skyline.lineWidth = 0.5
skyline.opacity = 0.5
skyline.fillColor = UIColor.clearColor().CGColor
addSublayer(skyline)
}
private func addSkylineBelow() {
let skyline = CAShapeLayer()
let path = UIBezierPath()
for (g, graphEvent) in events.enumerate() {
if g == 0 {
let y = convertY(graphEvent.maxY, fromLayer: eventsLayer)
path.moveToPoint(CGPoint(x: graphEvent.x, y: y))
}
else {
let y = convertY(graphEvent.maxY, fromLayer: eventsLayer)
path.addLineToPoint(CGPoint(x: graphEvent.x, y: y))
}
}
skyline.path = path.CGPath
skyline.strokeColor = UIColor.greenColor().CGColor
skyline.lineWidth = 0.5
skyline.opacity = 0.5
skyline.fillColor = UIColor.clearColor().CGColor
addSublayer(skyline)
}
private func addSkylines() {
addSkylineAbove()
addSkylineBelow()
}
private func adjustLayersYForMinY() {
linesLayer.position.y -= getMinY()
eventsLayer.position.y -= getMinY()
clefsLayer.position.y -= getMinY()
}
public override func setFrame() {
let height: CGFloat = getMaxY() - getMinY()
// temp
let width: CGFloat = 1000
frame = CGRectMake(left, top, width, height)
}
private func addTestSlurs() {
// SLUR CONNECTION POINT FOR TESTING ONLY
for e in 0..<events.count {
let event = events[e] as! StaffEvent
if e != 0 {
let x0 = events[e - 1].x
let y0 = (events[e - 1] as! StaffEvent).slurConnectionY!
let x1 = event.x
let y1 = event.slurConnectionY!
let slur = Slur(point1: CGPointMake(x0, y0), point2: CGPointMake(x1, y1))
eventsLayer.addSublayer(slur)
slur.strokeColor = UIColor.orangeColor().CGColor
slur.opacity = 0.25
}
}
}
public override func commitLines() {
func commitLineFromLeft(left: CGFloat, toRight right: CGFloat) {
for i in 0..<5 {
let y: CGFloat = CGFloat(i) * gS
let line: CAShapeLayer = CAShapeLayer()
let line_path = UIBezierPath()
line_path.moveToPoint(CGPointMake(left, y))
line_path.addLineToPoint(CGPointMake(right, y))
line.path = line_path.CGPath
line.lineWidth = lineWidth
line.strokeColor = UIColor.grayColor().CGColor
addLine(line)
}
}
lineActions.sortInPlace({ $0.x < $1.x })
var allLineActions = lineActions
var lastX: CGFloat?
while allLineActions.count > 0 {
let lineAction = allLineActions.first!
let lineActionsWithCurrentXValue = allLineActions.filter({ $0.x == lineAction.x })
if lineActionsWithCurrentXValue.filter({ $0 is LineActionStart }).count > 0 {
if lastX == nil { lastX = lineAction.x }
}
else if let _lastX = lastX {
commitLineFromLeft(_lastX, toRight: lineAction.x)
lastX = nil
}
allLineActions = allLineActions.filter({ $0.x > lineAction.x })
}
addSublayer(linesLayer)
}
private func commitClefs() {
if clefs.count > 0 { clefsLayer.position.y -= (clefs.first as! ClefStaff).extenderHeight }
addSublayer(clefsLayer)
}
private func commitEvents() {
for event in events {
if let staffEvent = event as? StaffEvent {
staffEvent.setMiddleCPosition(middleCPositionAtX(staffEvent.x))
}
event.build()
eventsLayer.addSublayer(event)
}
addSublayer(eventsLayer)
}
public override func getGraphTop() -> CGFloat {
return eventsLayer.frame.minY
}
public override func getGraphBottom() -> CGFloat {
return graphTop + 4 * g // hack
}
}
public enum PlacementInStaff {
case Line, Space, Floating
}
| gpl-2.0 | 0f6354063de2cf0ead6f694270e6c0b7 | 31.737705 | 109 | 0.57366 | 4.169102 | false | false | false | false |
slavapestov/swift | stdlib/public/core/Shims.swift | 7 | 1397 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// Additions to 'SwiftShims' that can be written in Swift.
///
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
@warn_unused_result
internal func _makeSwiftNSFastEnumerationState()
-> _SwiftNSFastEnumerationState {
return _SwiftNSFastEnumerationState(
state: 0, itemsPtr: nil, mutationsPtr: nil,
extra: (0, 0, 0, 0, 0))
}
/// A dummy value to be used as the target for `mutationsPtr` in fast
/// enumeration implementations.
var _fastEnumerationStorageMutationsTarget: CUnsignedLong = 0
/// A dummy pointer to be used as `mutationsPtr` in fast enumeration
/// implementations.
public // SPI(Foundation)
var _fastEnumerationStorageMutationsPtr: UnsafeMutablePointer<CUnsignedLong> {
return UnsafeMutablePointer(
Builtin.addressof(&_fastEnumerationStorageMutationsTarget))
}
#endif
| apache-2.0 | 501562a15f85de5a5266bebe82ffcf83 | 34.820513 | 80 | 0.622047 | 5.193309 | false | false | false | false |
calkinssean/TIY-Assignments | Day 21/SpotifyAPI/Artist.swift | 1 | 1924 | //
// Artist.swift
// SpotifyAPI
//
// Created by Sean Calkins on 2/29/16.
// Copyright © 2016 Dape App Productions LLC. All rights reserved.
//
import Foundation
// NSCoding Constants
let kArtistIdString = "idString"
let kArtistName = "name"
let kArtistImageUrls = "imageUrls"
let kArtistAlbums = "alubms"
class Artist: NSObject, NSCoding {
var idString: String = ""
var name: String = ""
var imageUrls: [String] = [""]
var albums = [Album]()
override init() {
}
init(dict: JSONDictionary) {
if let idString = dict["id"] as? String {
self.idString = idString
} else {
print("couldn't parse id")
}
if let name = dict["name"] as? String {
self.name = name
} else {
print("couldn't parse name")
}
if let items = dict["images"] as? JSONArray {
for item in items {
if let imageUrl = item["url"] as? String {
self.imageUrls.append(imageUrl)
} else {
print("error with image url")
}
}
print(imageUrls.count)
}
}
required init?(coder aDecoder: NSCoder) {
self.idString = aDecoder.decodeObjectForKey(kArtistIdString) as! String
self.name = aDecoder.decodeObjectForKey(kArtistName) as! String
self.imageUrls = aDecoder.decodeObjectForKey(kArtistImageUrls) as! [String]
self.albums = aDecoder.decodeObjectForKey(kArtistAlbums) as! [Album]
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(idString, forKey: kArtistIdString)
aCoder.encodeObject(name, forKey: kArtistName)
aCoder.encodeObject(imageUrls, forKey: kArtistImageUrls)
aCoder.encodeObject(albums, forKey: kArtistAlbums)
}
} | cc0-1.0 | 3fdc0feb6e0d52c0024e3d5955240f79 | 27.294118 | 83 | 0.577223 | 4.370455 | false | false | false | false |
PomTTcat/SourceCodeGuideRead_JEFF | RxSwiftGuideRead/RxSwift-master/RxExample/RxExample/Examples/UIPickerViewExample/CustomPickerViewAdapterExampleViewController.swift | 5 | 2071 | //
// CustomPickerViewAdapterExampleViewController.swift
// RxExample
//
// Created by Sergey Shulga on 12/07/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
final class CustomPickerViewAdapterExampleViewController: ViewController {
@IBOutlet weak var pickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
Observable.just([[1, 2, 3], [5, 8, 13], [21, 34]])
.bind(to: pickerView.rx.items(adapter: PickerViewViewAdapter()))
.disposed(by: disposeBag)
pickerView.rx.modelSelected(Int.self)
.subscribe(onNext: { models in
print(models)
})
.disposed(by: disposeBag)
}
}
final class PickerViewViewAdapter
: NSObject
, UIPickerViewDataSource
, UIPickerViewDelegate
, RxPickerViewDataSourceType
, SectionedViewDataSourceType {
typealias Element = [[CustomStringConvertible]]
private var items: [[CustomStringConvertible]] = []
func model(at indexPath: IndexPath) throws -> Any {
return items[indexPath.section][indexPath.row]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return items.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return items[component].count
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label = UILabel()
label.text = items[component][row].description
label.textColor = UIColor.orange
label.font = UIFont.preferredFont(forTextStyle: .headline)
label.textAlignment = .center
return label
}
func pickerView(_ pickerView: UIPickerView, observedEvent: Event<Element>) {
Binder(self) { (adapter, items) in
adapter.items = items
pickerView.reloadAllComponents()
}.on(observedEvent)
}
}
| mit | ed1345f66364223ed2c2d307bc9f82cc | 29 | 132 | 0.654589 | 5 | false | false | false | false |
jovito-royeca/Cineko | Cineko/Review.swift | 1 | 1394 | //
// Review.swift
// Cineko
//
// Created by Jovit Royeca on 04/05/2016.
// Copyright © 2016 Jovito Royeca. All rights reserved.
//
import Foundation
import CoreData
class Review: NSManagedObject {
struct Keys {
static let Byline = "byline"
static let Headline = "headline"
static let Link = "url"
static let SuggestedLinkText = "suggested_link_text"
static let ReviewType = "type"
}
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
init(dictionary: [String : AnyObject], context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Review", inManagedObjectContext: context)!
super.init(entity: entity,insertIntoManagedObjectContext: context)
update(dictionary)
}
func update(dictionary: [String : AnyObject]) {
byline = dictionary[Keys.Byline] as? String
headline = dictionary[Keys.Headline] as? String
if let linkDict = dictionary["link"] as? [String: AnyObject] {
link = linkDict[Keys.Link] as? String
suggestedLinkText = linkDict[Keys.SuggestedLinkText] as? String
reviewType = linkDict[Keys.ReviewType] as? String
}
}
}
| apache-2.0 | 8d2956930aa07d2431926f4c0443fc85 | 30.659091 | 113 | 0.659009 | 4.690236 | false | false | false | false |
hisui/ReactiveSwift | ReactiveSwift/fake.swift | 1 | 4007 | // Copyright (c) 2014 segfault.jp. All rights reserved.
import Foundation
public class FakePID: PID {
public let name: String
public init(_ name: String) { self.name = name }
public override func equals(o: PID) -> Bool { return (o as? FakePID)?.name == name }
}
public class FakeExecutionContext: ExecutionContext, CustomStringConvertible {
private let executor: FakeExecutor
private let synch: Bool
private let actor: String
public let name: String
private init(_ executor: FakeExecutor, _ synch: Bool, _ actor: String, _ name: String) {
self.executor = executor
self.synch = synch
self.actor = actor
self.name = name
executor.count++
}
public var description: String { return "\(name)@\(actor)" }
public var pid: String { return actor }
public var currentTime: NSDate {
return NSDate(timeIntervalSince1970: executor.currentTime)
}
public func schedule(callerContext: ExecutionContext?, _ delay: Double, _ task: () -> ()) {
if synch
&& delay == 0
&& actor == (callerContext as? FakeExecutionContext)?.actor
{
call(task)()
}
else {
executor.schedule(delay, call(task))
}
}
public func requires(property: [ExecutionProperty]) -> ExecutionContext {
return executor.newContext(property, FakePID(actor), name)
}
public func close() { executor.count-- }
public func ensureCurrentlyInCompatibleContext() {
if let top = executor.stack.last?.actor {
assert(top == actor, "[error] Out of context violation occured; `\(actor)` != `\(top)`")
}
}
private func call(f: () -> ())() {
executor.stack.push(self)
f()
executor.stack.pop()
}
}
public class FakeExecutor {
private var currentTime: Double = 0
private var tasks = [Task]()
private var count = 0
private let stack = ArrayDeque<FakeExecutionContext>()
public init() {}
public var numberOfRunningContexts: Int { get { return count } }
public func newContext(name: String = __FUNCTION__) -> ExecutionContext {
return newContext([], nil, name)
}
public func newContext(property: [ExecutionProperty], _ pid: FakePID? = nil, _ name: String = __FUNCTION__) -> ExecutionContext {
var actor = pid?.name
var synch = false
for e in property {
switch e {
case .Actor(let pid as FakePID): actor = pid.name
case .AllowSync:
synch = true
default:
()
}
}
return FakeExecutionContext(self, synch, actor ?? "main", name)
}
public func consumeAll() -> Bool {
return consumeUntil(currentTime)
}
public func consumeUntil (time: Double, _ cond: () -> Bool = { true }) -> Bool {
assert(currentTime <= time)
var n = 0
while cond() {
var a = Array<Int>()
var t = Double.infinity
for (i, e) in tasks.enumerate() {
if (e.time <= min(time, t)) {
if (t > e.time) {
t = e.time
a.removeAll(keepCapacity: true)
}
a.append(i)
}
}
if a.isEmpty {
break
}
currentTime = t
for i in a {
n++
tasks[i].task()
}
for i in Array(a.reverse()) { tasks.removeAtIndex(i) }
}
currentTime = time
return n > 0
}
func schedule(delay: Double, _ f: () -> ()) {
tasks.append(Task(currentTime + delay, f))
}
}
private class Task {
let time: Double
let task: () -> ()
init(_ time: Double, _ task: () -> ()) {
self.time = time
self.task = task
}
}
| mit | 59133060c06361e7dba14208bffad1bb | 25.892617 | 133 | 0.528076 | 4.487122 | false | false | false | false |
xxxAIRINxxx/Cmg | Sources/HalftoneEffect.swift | 1 | 5494 | //
// HalftoneEffect.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/20.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
public struct CircularScreen: Filterable, FilterInputCollectionType,
InputCenterAvailable, InputWidthAvailable, InputSharpnessAvailable {
public let filter: CIFilter = CIFilter(name: "CICircularScreen")!
public let inputCenter: VectorInput
public let inputWidth: ScalarInput
public let inputSharpness: ScalarInput
public init(imageSize: CGSize) {
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
self.inputWidth = ScalarInput(filter: self.filter, key: kCIInputWidthKey)
self.inputSharpness = ScalarInput(filter: self.filter, key: kCIInputSharpnessKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputCenter,
self.inputWidth,
self.inputSharpness
]
}
}
@available(iOS 9.0, *)
public struct CMYKHalftone: Filterable, FilterInputCollectionType,
InputCenterAvailable, InputWidthAvailable, InputSharpnessAvailable,
InputAngleAvailable, InputGCRAvailable, InputUCRAvailable {
public let filter: CIFilter = CIFilter(name: "CICMYKHalftone")!
public let inputCenter: VectorInput
public let inputWidth: ScalarInput
public let inputSharpness: ScalarInput
public let inputAngle: ScalarInput
public let inputGCR: ScalarInput
public let inputUCR: ScalarInput
public init(imageSize: CGSize) {
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
self.inputWidth = ScalarInput(filter: self.filter, key: kCIInputWidthKey)
self.inputSharpness = ScalarInput(filter: self.filter, key: kCIInputSharpnessKey)
self.inputAngle = ScalarInput(filter: self.filter, key: kCIInputAngleKey)
self.inputGCR = ScalarInput(filter: self.filter, key: "inputGCR")
self.inputUCR = ScalarInput(filter: self.filter, key: "inputUCR")
}
public func inputs() -> [FilterInputable] {
return [
self.inputCenter,
self.inputWidth,
self.inputSharpness,
self.inputAngle,
self.inputGCR,
self.inputUCR
]
}
}
public struct DotScreen: Filterable, FilterInputCollectionType,
InputCenterAvailable, InputWidthAvailable, InputSharpnessAvailable,
InputAngleAvailable {
public let filter: CIFilter = CIFilter(name: "CIDotScreen")!
public let inputCenter: VectorInput
public let inputWidth: ScalarInput
public let inputSharpness: ScalarInput
public let inputAngle: ScalarInput
public init(imageSize: CGSize) {
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
self.inputWidth = ScalarInput(filter: self.filter, key: kCIInputWidthKey)
self.inputSharpness = ScalarInput(filter: self.filter, key: kCIInputSharpnessKey)
self.inputAngle = ScalarInput(filter: self.filter, key: kCIInputAngleKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputCenter,
self.inputWidth,
self.inputSharpness,
self.inputAngle,
]
}
}
public struct HatchedScreen: Filterable, FilterInputCollectionType,
InputCenterAvailable, InputWidthAvailable, InputSharpnessAvailable,
InputAngleAvailable {
public let filter: CIFilter = CIFilter(name: "CIHatchedScreen")!
public let inputCenter: VectorInput
public let inputWidth: ScalarInput
public let inputSharpness: ScalarInput
public let inputAngle: ScalarInput
public init(imageSize: CGSize) {
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
self.inputWidth = ScalarInput(filter: self.filter, key: kCIInputWidthKey)
self.inputSharpness = ScalarInput(filter: self.filter, key: kCIInputSharpnessKey)
self.inputAngle = ScalarInput(filter: self.filter, key: kCIInputAngleKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputCenter,
self.inputWidth,
self.inputSharpness,
self.inputAngle,
]
}
}
public struct LineScreen: Filterable, FilterInputCollectionType,
InputCenterAvailable, InputWidthAvailable, InputSharpnessAvailable,
InputAngleAvailable {
public let filter: CIFilter = CIFilter(name: "CILineScreen")!
public let inputCenter: VectorInput
public let inputWidth: ScalarInput
public let inputSharpness: ScalarInput
public let inputAngle: ScalarInput
public init(imageSize: CGSize) {
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
self.inputWidth = ScalarInput(filter: self.filter, key: kCIInputWidthKey)
self.inputSharpness = ScalarInput(filter: self.filter, key: kCIInputSharpnessKey)
self.inputAngle = ScalarInput(filter: self.filter, key: kCIInputAngleKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputCenter,
self.inputWidth,
self.inputSharpness,
self.inputAngle,
]
}
}
| mit | ccfbb6ee17b75a5efdd183472e876024 | 34.668831 | 120 | 0.695613 | 4.917637 | false | false | false | false |
DaSens/StartupDisk | Pods/ProgressKit/InDeterminate/Spinner.swift | 1 | 3203 | //
// Spinner.swift
// ProgressKit
//
// Created by Kauntey Suryawanshi on 28/07/15.
// Copyright (c) 2015 Kauntey Suryawanshi. All rights reserved.
//
import Foundation
import Cocoa
@IBDesignable
open class Spinner: IndeterminateAnimation {
var basicShape = CAShapeLayer()
var containerLayer = CAShapeLayer()
var starList = [CAShapeLayer]()
var animation: CAKeyframeAnimation = {
var animation = CAKeyframeAnimation(keyPath: "transform.rotation")
animation.repeatCount = Float.infinity
animation.calculationMode = kCAAnimationDiscrete
return animation
}()
@IBInspectable open var starSize:CGSize = CGSize(width: 6, height: 15) {
didSet {
notifyViewRedesigned()
}
}
@IBInspectable open var roundedCorners: Bool = true {
didSet {
notifyViewRedesigned()
}
}
@IBInspectable open var distance: CGFloat = CGFloat(20) {
didSet {
notifyViewRedesigned()
}
}
@IBInspectable open var starCount: Int = 10 {
didSet {
notifyViewRedesigned()
}
}
@IBInspectable open var duration: Double = 1 {
didSet {
animation.duration = duration
}
}
@IBInspectable open var clockwise: Bool = false {
didSet {
notifyViewRedesigned()
}
}
override func configureLayers() {
super.configureLayers()
containerLayer.frame = self.bounds
containerLayer.cornerRadius = frame.width / 2
self.layer?.addSublayer(containerLayer)
animation.duration = duration
}
override func notifyViewRedesigned() {
super.notifyViewRedesigned()
starList.removeAll(keepingCapacity: true)
containerLayer.sublayers = nil
animation.values = [Double]()
var i = 0.0
while i < 360 {
var iRadian = CGFloat(i * M_PI / 180.0)
if clockwise { iRadian = -iRadian }
animation.values?.append(iRadian)
let starShape = CAShapeLayer()
starShape.cornerRadius = roundedCorners ? starSize.width / 2 : 0
let centerLocation = CGPoint(x: frame.width / 2 - starSize.width / 2, y: frame.width / 2 - starSize.height / 2)
starShape.frame = CGRect(origin: centerLocation, size: starSize)
starShape.backgroundColor = foreground.cgColor
starShape.anchorPoint = CGPoint(x: 0.5, y: 0)
var rotation: CATransform3D = CATransform3DMakeTranslation(0, 0, 0.0);
rotation = CATransform3DRotate(rotation, -iRadian, 0.0, 0.0, 1.0);
rotation = CATransform3DTranslate(rotation, 0, distance, 0.0);
starShape.transform = rotation
starShape.opacity = Float(360 - i) / 360
containerLayer.addSublayer(starShape)
starList.append(starShape)
i = i + Double(360 / starCount)
}
}
override func startAnimation() {
containerLayer.add(animation, forKey: "rotation")
}
override func stopAnimation() {
containerLayer.removeAllAnimations()
}
}
| apache-2.0 | e1a1ed19eb4b5a6aaf768525196f92b7 | 27.096491 | 123 | 0.604433 | 4.802099 | false | false | false | false |
juliantejera/JTDataStructures | JTDataStructures/Sorting Algorithms/QuickSorter.swift | 1 | 1126 | //
// QuickSorter.swift
// JTDataStructures
//
// Created by Julian Tejera-Frias on 7/15/16.
// Copyright © 2016 Julian Tejera. All rights reserved.
//
import Foundation
public struct QuickSorter<T: Comparable> {
public init() {
}
public func sort(_ array: inout [T], low: Int, high: Int) {
if low < high {
let p = partition(&array, low: low, high: high)
sort(&array, low: low, high: p)
sort(&array, low: p + 1, high: high)
}
}
// Hoare's Partition
private func partition(_ array: inout [T], low: Int, high: Int) -> Int {
let pivot = array[Int(arc4random()) % array.count]
var i = low - 1
var j = high + 1
while (true) {
repeat {
i += 1
} while array[i] < pivot
repeat {
j -= 1
} while array[j] > pivot
if i < j {
array.swapAt(i, j)
} else {
return j
}
}
}
}
| mit | 64abb7493a74e28c43ae07e880eaf37d | 20.634615 | 76 | 0.433778 | 4.090909 | false | false | false | false |
eneko/JSONRequest | Sources/JSONRequest.swift | 1 | 10830 | //
// JSONRequest.swift
// JSONRequest
//
// Created by Eneko Alonso on 9/12/14.
// Copyright (c) 2014 Hathway. All rights reserved.
//
import Foundation
import SystemConfiguration
public typealias JSONObject = Dictionary<String, AnyObject?>
public enum JSONError: ErrorType {
case InvalidURL
case PayloadSerialization
case NoInternetConnection
case RequestFailed(error: NSError)
case NonHTTPResponse
case ResponseDeserialization
case UnknownError
}
public enum JSONResult {
case Success(data: AnyObject?, response: NSHTTPURLResponse)
case Failure(error: JSONError, response: NSHTTPURLResponse?, body: String?)
}
public extension JSONResult {
public var data: AnyObject? {
switch self {
case .Success(let data, _):
return data
case .Failure:
return nil
}
}
public var arrayValue: [AnyObject] {
return data as? [AnyObject] ?? []
}
public var dictionaryValue: [String: AnyObject] {
return data as? [String: AnyObject] ?? [:]
}
public var httpResponse: NSHTTPURLResponse? {
switch self {
case .Success(_, let response):
return response
case .Failure(_, let response, _):
return response
}
}
public var error: ErrorType? {
switch self {
case .Success:
return nil
case .Failure(let error, _, _):
return error
}
}
}
public class JSONRequest {
private(set) var request: NSMutableURLRequest?
public static var log: (String -> Void)?
public static var userAgent: String?
public static var requestTimeout = 5.0
public static var resourceTimeout = 10.0
public var httpRequest: NSMutableURLRequest? {
return request
}
public init() {
request = NSMutableURLRequest()
}
// MARK: Non-public business logic (testable but not public outside the module)
func submitAsyncRequest(method: JSONRequestHttpVerb, url: String,
queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
if isConnectedToNetwork() == false {
let error = JSONError.NoInternetConnection
complete(result: .Failure(error: error, response: nil, body: nil))
return
}
updateRequestUrl(method, url: url, queryParams: queryParams)
updateRequestHeaders(headers)
updateRequestPayload(payload)
let start = NSDate()
let task = networkSession().dataTaskWithRequest(request!) { (data, response, error) in
let elapsed = -start.timeIntervalSinceNow
self.traceResponse(elapsed, responseData: data, httpResponse: response as? NSHTTPURLResponse, error: error)
if let error = error {
let result = JSONResult.Failure(error: JSONError.RequestFailed(error: error),
response: response as? NSHTTPURLResponse,
body: self.bodyStringFromData(data))
complete(result: result)
return
}
let result = self.parseResponse(data, response: response)
complete(result: result)
}
traceTask(task)
task.resume()
}
func networkSession() -> NSURLSession {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.timeoutIntervalForRequest = JSONRequest.requestTimeout
config.timeoutIntervalForResource = JSONRequest.resourceTimeout
if let userAgent = JSONRequest.userAgent {
config.HTTPAdditionalHeaders = ["User-Agent": userAgent]
}
return NSURLSession(configuration: config)
}
func submitSyncRequest(method: JSONRequestHttpVerb, url: String, queryParams: JSONObject? = nil,
payload: AnyObject? = nil, headers: JSONObject? = nil) -> JSONResult {
let semaphore = dispatch_semaphore_create(0)
var requestResult: JSONResult = JSONResult.Failure(error: JSONError.UnknownError,
response: nil, body: nil)
submitAsyncRequest(method, url: url, queryParams: queryParams, payload: payload,
headers: headers) { result in
requestResult = result
dispatch_semaphore_signal(semaphore)
}
// Wait for the request to complete
while dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW) != 0 {
let intervalDate = NSDate(timeIntervalSinceNow: 0.01) // 10 milliseconds
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: intervalDate)
}
return requestResult
}
func updateRequestUrl(method: JSONRequestHttpVerb, url: String,
queryParams: JSONObject? = nil) {
request?.URL = createURL(url, queryParams: queryParams)
request?.HTTPMethod = method.rawValue
}
func updateRequestHeaders(headers: JSONObject?) {
request?.setValue("application/json", forHTTPHeaderField: "Content-Type")
request?.setValue("application/json", forHTTPHeaderField: "Accept")
if let headers = headers {
for (headerName, headerValue) in headers {
if let unwrapped = headerValue {
request?.setValue(String(unwrapped), forHTTPHeaderField: headerName)
}
}
}
}
func updateRequestPayload(payload: AnyObject?) {
guard let payload = payload else {
return
}
request?.HTTPBody = objectToJSON(payload)
}
func createURL(urlString: String, queryParams: JSONObject?) -> NSURL? {
let components = NSURLComponents(string: urlString)
if queryParams != nil {
if components?.queryItems == nil {
components?.queryItems = []
}
for (key, value) in queryParams! {
if let unwrapped = value {
let item = NSURLQueryItem(name: key, value: String(unwrapped))
components?.queryItems?.append(item)
} else {
let item = NSURLQueryItem(name: key, value: nil)
components?.queryItems?.append(item)
}
}
}
return components?.URL
}
func parseResponse(data: NSData?, response: NSURLResponse?) -> JSONResult {
guard let httpResponse = response as? NSHTTPURLResponse else {
return JSONResult.Failure(error: JSONError.NonHTTPResponse, response: nil, body: nil)
}
guard let data = data where data.length > 0 else {
return JSONResult.Success(data: nil, response: httpResponse)
}
guard let json = JSONToObject(data) else {
return JSONResult.Failure(error: JSONError.ResponseDeserialization,
response: httpResponse,
body: dataToUTFString(data))
}
return JSONResult.Success(data: json, response: httpResponse)
}
func bodyStringFromData(data: NSData?) -> String? {
guard let data = data else {
return nil
}
return String(data: data, encoding: NSUTF8StringEncoding)
}
public func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
guard let reachability = defaultRouteReachability else {
return false
}
var flags: SCNetworkReachabilityFlags = []
SCNetworkReachabilityGetFlags(reachability, &flags)
if flags.isEmpty {
return false
}
let isReachable = flags.contains(.Reachable)
let needsConnection = flags.contains(.ConnectionRequired)
return isReachable && !needsConnection
}
private func traceTask(task: NSURLSessionDataTask) {
guard let log = JSONRequest.log, let request = task.currentRequest else {
return
}
log(">>>>>>>>>> JSON Request >>>>>>>>>>")
if let method = task.currentRequest?.HTTPMethod {
log("HTTP Method: \(method)")
}
if let url = task.currentRequest?.URL?.absoluteString {
log("Url: \(url)")
}
if let headers = task.currentRequest?.allHTTPHeaderFields {
log("Headers: \(objectToJSONString(headers, pretty: true))")
}
if let payload = task.currentRequest?.HTTPBody,
let body = String(data: payload, encoding: NSUTF8StringEncoding) {
log("Payload: \(body)")
}
}
private func traceResponse(elapsed: NSTimeInterval, responseData: NSData?, httpResponse: NSHTTPURLResponse?,
error: NSError?) {
guard let log = JSONRequest.log else {
return
}
log("<<<<<<<<<< JSON Response <<<<<<<<<<")
log("Time Elapsed: \(elapsed)")
if let statusCode = httpResponse?.statusCode {
log("Status Code: \(statusCode)")
}
if let headers = httpResponse?.allHeaderFields {
log("Headers: \(objectToJSONString(headers, pretty: true))")
}
if let data = responseData, let body = JSONToObject(data) {
log("Body: \(objectToJSONString(body, pretty: true))")
}
if let errorString = error?.localizedDescription {
log("Error: \(errorString)")
}
}
private func JSONToObject(data: NSData) -> AnyObject? {
return try? NSJSONSerialization.JSONObjectWithData(data, options: [.AllowFragments])
}
private func objectToJSON(object: AnyObject, pretty: Bool = false) -> NSData? {
if NSJSONSerialization.isValidJSONObject(object) {
let options = pretty ? NSJSONWritingOptions.PrettyPrinted : []
return try? NSJSONSerialization.dataWithJSONObject(object, options: options)
}
return nil
}
private func objectToJSONString(object: AnyObject, pretty: Bool) -> String {
if let data = objectToJSON(object, pretty: pretty) {
return dataToUTFString(data)
}
return ""
}
private func dataToUTFString(data: NSData) -> String {
return String(data: data, encoding: NSUTF8StringEncoding) ?? ""
}
}
| mit | 9976f4bca583a974050683f37fce42a6 | 34.276873 | 119 | 0.598338 | 5.329724 | false | false | false | false |
hgl888/firefox-ios | StorageTests/TestSQLiteHistory.swift | 1 | 23439 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCTest
extension Site {
func asPlace() -> Place {
return Place(guid: self.guid!, url: self.url, title: self.title)
}
}
class TestSQLiteHistory: XCTestCase {
// Test that our visit partitioning for frecency is correct.
func testHistoryLocalAndRemoteVisits() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)!
let siteL = Site(url: "http://url1/", title: "title local only")
let siteR = Site(url: "http://url2/", title: "title remote only")
let siteB = Site(url: "http://url3/", title: "title local and remote")
siteL.guid = "locallocal12"
siteR.guid = "remoteremote"
siteB.guid = "bothbothboth"
let siteVisitL1 = SiteVisit(site: siteL, date: 1437088398461000, type: VisitType.Link)
let siteVisitL2 = SiteVisit(site: siteL, date: 1437088398462000, type: VisitType.Link)
let siteVisitR1 = SiteVisit(site: siteR, date: 1437088398461000, type: VisitType.Link)
let siteVisitR2 = SiteVisit(site: siteR, date: 1437088398462000, type: VisitType.Link)
let siteVisitR3 = SiteVisit(site: siteR, date: 1437088398463000, type: VisitType.Link)
let siteVisitBL1 = SiteVisit(site: siteB, date: 1437088398464000, type: VisitType.Link)
let siteVisitBR1 = SiteVisit(site: siteB, date: 1437088398465000, type: VisitType.Link)
let deferred =
history.clearHistory()
>>> { history.addLocalVisit(siteVisitL1) }
>>> { history.addLocalVisit(siteVisitL2) }
>>> { history.addLocalVisit(siteVisitBL1) }
>>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: 1437088398462) }
>>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: 1437088398463) }
>>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: 1437088398465) }
// Do this step twice, so we exercise the dupe-visit handling.
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) }
>>> { history.getSitesByFrecencyWithLimit(3)
>>== { (sites: Cursor) -> Success in
XCTAssertEqual(3, sites.count)
// Two local visits beat a single later remote visit and one later local visit.
// Two local visits beat three remote visits.
XCTAssertEqual(siteL.guid!, sites[0]!.guid!)
XCTAssertEqual(siteB.guid!, sites[1]!.guid!)
XCTAssertEqual(siteR.guid!, sites[2]!.guid!)
return succeed()
}
// This marks everything as modified so we can fetch it.
>>> history.onRemovedAccount
// Now check that we have no duplicate visits.
>>> { history.getModifiedHistoryToUpload()
>>== { (places) -> Success in
if let (_, visits) = find(places, f: {$0.0.guid == siteR.guid!}) {
XCTAssertEqual(3, visits.count)
} else {
XCTFail("Couldn't find site R.")
}
return succeed()
}
}
}
XCTAssertTrue(deferred.value.isSuccess)
}
func testUpgrades() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
// This calls createOrUpdate. i.e. it may fail, but should not crash and should always return a valid SQLiteHistory object.
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)!
XCTAssertNotNil(history)
// Insert some basic data that we'll have to upgrade
let expectation = self.expectationWithDescription("First.")
db.run([("INSERT INTO history (guid, url, title, server_modified, local_modified, is_deleted, should_upload) VALUES (guid, http://www.example.com, title, 5, 10, 0, 1)", nil),
("INSERT INTO visits (siteID, date, type, is_local) VALUES (1, 15, 1, 1)", nil),
("INSERT INTO favicons (url, width, height, type, date) VALUES (http://www.example.com/favicon.ico, 10, 10, 1, 20)", nil),
("INSERT INTO faviconSites (siteID, faviconID) VALUES (1, 1)", nil),
("INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES (guid, 1, http://www.example.com, 0, 1, title)", nil)
]).upon { result in
for i in 1...BrowserTable.DefaultVersion {
let history = SQLiteHistory(db: db, prefs: prefs, version: i)
XCTAssertNotNil(history)
}
// This checks to make sure updates actually work (or at least that they don't crash :))
var err: NSError? = nil
db.transaction(&err, callback: { (connection, err) -> Bool in
for i in 0...BrowserTable.DefaultVersion {
let table = BrowserTable(version: i)
switch db.updateTable(connection, table: table) {
case .Updated:
XCTAssertTrue(true, "Update to \(i) succeeded")
default:
XCTFail("Update to version \(i) failed")
return false
}
}
return true
})
if err != nil {
XCTFail("Error creating a transaction \(err)")
}
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
func testDomainUpgrade() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)!
let site = Site(url: "http://www.example.com/test1.1", title: "title one")
var err: NSError? = nil
// Insert something with an invalid domainId. We have to manually do this since domains are usually hidden.
db.withWritableConnection(&err, callback: { (connection, err) -> Int in
let insert = "INSERT INTO \(TableHistory) (guid, url, title, local_modified, is_deleted, should_upload, domain_id) " +
"?, ?, ?, ?, ?, ?, ?"
let args: Args = [Bytes.generateGUID(), site.url, site.title, NSDate.nowNumber(), 0, 0, -1]
err = connection.executeChange(insert, withArgs: args)
return 0
})
// Now insert it again. This should update the domain
history.addLocalVisit(SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: VisitType.Link))
// DomainID isn't normally exposed, so we manually query to get it
let results = db.withReadableConnection(&err, callback: { (connection, err) -> Cursor<Int> in
let sql = "SELECT domain_id FROM \(TableHistory) WHERE url = ?"
let args: Args = [site.url]
return connection.executeQuery(sql, factory: IntFactory, withArgs: args)
})
XCTAssertNotEqual(results[0]!, -1, "Domain id was updated")
}
func testDomains() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)!
let initialGuid = Bytes.generateGUID()
let site11 = Site(url: "http://www.example.com/test1.1", title: "title one")
let site12 = Site(url: "http://www.example.com/test1.2", title: "title two")
let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three")
let site3 = Site(url: "http://www.example2.com/test1", title: "title three")
let expectation = self.expectationWithDescription("First.")
history.clearHistory().bind({ success in
return all([history.addLocalVisit(SiteVisit(site: site11, date: NSDate.nowMicroseconds(), type: VisitType.Link)),
history.addLocalVisit(SiteVisit(site: site12, date: NSDate.nowMicroseconds(), type: VisitType.Link)),
history.addLocalVisit(SiteVisit(site: site3, date: NSDate.nowMicroseconds(), type: VisitType.Link))])
}).bind({ (results: [Maybe<()>]) in
return history.insertOrUpdatePlace(site13, modified: NSDate.nowMicroseconds())
}).bind({ guid in
XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct")
return history.getSitesByFrecencyWithLimit(10)
}).bind({ (sites: Maybe<Cursor<Site>>) -> Success in
XCTAssert(sites.successValue!.count == 2, "2 sites returned")
return history.removeSiteFromTopSites(site11)
}).bind({ success in
XCTAssertTrue(success.isSuccess, "Remove was successful")
return history.getSitesByFrecencyWithLimit(10)
}).upon({ (sites: Maybe<Cursor<Site>>) in
XCTAssert(sites.successValue!.count == 1, "1 site returned")
expectation.fulfill()
})
waitForExpectationsWithTimeout(10.0) { error in
return
}
}
// This is a very basic test. Adds an entry, retrieves it, updates it,
// and then clears the database.
func testHistoryTable() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)!
let bookmarks = SQLiteBookmarks(db: db)
let site1 = Site(url: "http://url1/", title: "title one")
let site1Changed = Site(url: "http://url1/", title: "title one alt")
let siteVisit1 = SiteVisit(site: site1, date: NSDate.nowMicroseconds(), type: VisitType.Link)
let siteVisit2 = SiteVisit(site: site1Changed, date: NSDate.nowMicroseconds() + 1000, type: VisitType.Bookmark)
let site2 = Site(url: "http://url2/", title: "title two")
let siteVisit3 = SiteVisit(site: site2, date: NSDate.nowMicroseconds() + 2000, type: VisitType.Link)
let expectation = self.expectationWithDescription("First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func checkSitesByFrecency(f: Cursor<Site> -> Success) -> () -> Success {
return {
history.getSitesByFrecencyWithLimit(10)
>>== f
}
}
func checkSitesByDate(f: Cursor<Site> -> Success) -> () -> Success {
return {
history.getSitesByLastVisit(10)
>>== f
}
}
func checkSitesWithFilter(filter: String, f: Cursor<Site> -> Success) -> () -> Success {
return {
history.getSitesByFrecencyWithLimit(10, whereURLContains: filter)
>>== f
}
}
func checkDeletedCount(expected: Int) -> () -> Success {
return {
history.getDeletedHistoryToUpload()
>>== { guids in
XCTAssertEqual(expected, guids.count)
return succeed()
}
}
}
history.clearHistory()
>>>
{ history.addLocalVisit(siteVisit1) }
>>> checkSitesByFrecency
{ (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1.title, sites[0]!.title)
XCTAssertEqual(site1.url, sites[0]!.url)
sites.close()
return succeed()
}
>>>
{ history.addLocalVisit(siteVisit2) }
>>> checkSitesByFrecency
{ (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site1Changed.url, sites[0]!.url)
sites.close()
return succeed()
}
>>>
{ history.addLocalVisit(siteVisit3) }
>>> checkSitesByFrecency
{ (sites: Cursor) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site2.title, sites[1]!.title)
return succeed()
}
>>> checkSitesByDate
{ (sites: Cursor<Site>) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of date last visited.
let first = sites[0]!
let second = sites[1]!
XCTAssertEqual(site2.title, first.title)
XCTAssertEqual(site1Changed.title, second.title)
XCTAssertTrue(siteVisit3.date == first.latestVisit!.date)
return succeed()
}
>>> checkSitesWithFilter("two")
{ (sites: Cursor<Site>) -> Success in
XCTAssertEqual(1, sites.count)
let first = sites[0]!
XCTAssertEqual(site2.title, first.title)
return succeed()
}
>>>
checkDeletedCount(0)
>>>
{ history.removeHistoryForURL("http://url2/") }
>>>
checkDeletedCount(1)
>>> checkSitesByFrecency
{ (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
return succeed()
}
>>>
{ history.clearHistory() }
>>>
checkDeletedCount(0)
>>> checkSitesByDate
{ (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> checkSitesByFrecency
{ (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> done
waitForExpectationsWithTimeout(10.0) { error in
return
}
}
func testFaviconTable() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)!
let bookmarks = SQLiteBookmarks(db: db)
let expectation = self.expectationWithDescription("First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func updateFavicon() -> Success {
let fav = Favicon(url: "http://url2/", date: NSDate(), type: .Icon)
fav.id = 1
let site = Site(url: "http://bookmarkedurl/", title: "My Bookmark")
return history.addFavicon(fav, forSite: site) >>> succeed
}
func checkFaviconForBookmarkIsNil() -> Success {
return bookmarks.bookmarksByURL("http://bookmarkedurl/".asURL!) >>== { results in
XCTAssertEqual(1, results.count)
XCTAssertNil(results[0]?.favicon)
return succeed()
}
}
func checkFaviconWasSetForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(1, results.count)
if let actualFaviconURL = results[0]??.url {
XCTAssertEqual("http://url2/", actualFaviconURL)
}
return succeed()
}
}
func removeBookmark() -> Success {
return bookmarks.removeByURL("http://bookmarkedurl/")
}
func checkFaviconWasRemovedForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(0, results.count)
return succeed()
}
}
history.clearAllFavicons()
>>> bookmarks.clearBookmarks
>>> { bookmarks.addToMobileBookmarks("http://bookmarkedurl/".asURL!, title: "Title", favicon: nil) }
>>> checkFaviconForBookmarkIsNil
>>> updateFavicon
>>> checkFaviconWasSetForBookmark
>>> removeBookmark
>>> checkFaviconWasRemovedForBookmark
>>> done
waitForExpectationsWithTimeout(10.0) { error in
return
}
}
func testTopSitesCache() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)!
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().value
history.clearHistory().value
// Make sure that we get back the top sites
populateHistoryForFrecencyCalcuations(history, siteCount: 100)
// Add extra visits to the 5th site to bubble it to the top of the top sites cache
let site = Site(url: "http://s\(5)ite\(5)/foo", title: "A \(5)")
site.guid = "abc\(5)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .Local, atTime: Timestamp(1438088398461 + (1000 * i)))
}
let expectation = self.expectationWithDescription("First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.updateTopSitesCacheIfInvalidated() >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
func invalidateIfNeededDoesntChangeResults() -> Success {
return history.updateTopSitesCacheIfInvalidated() >>> {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
}
func addVisitsToZerothSite() -> Success {
let site = Site(url: "http://s\(0)ite\(0)/foo", title: "A \(0)")
site.guid = "abc\(0)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .Local, atTime: Timestamp(1439088398461 + (1000 * i)))
}
return succeed()
}
func markInvalidation() -> Success {
history.setTopSitesNeedsInvalidation()
return succeed()
}
func checkSitesInvalidate() -> Success {
history.updateTopSitesCacheIfInvalidated().value
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(0)def")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> invalidateIfNeededDoesntChangeResults
>>> markInvalidation
>>> addVisitsToZerothSite
>>> checkSitesInvalidate
>>> done
waitForExpectationsWithTimeout(10.0) { error in
return
}
}
}
class TestSQLiteHistoryTransactionUpdate: XCTestCase {
func testUpdateInTransaction() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)!
history.clearHistory().value
let site = Site(url: "http://site/foo", title: "AA")
site.guid = "abcdefghiabc"
history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).value
let local = SiteVisit(site: site, date: Timestamp(1000 * 1437088398461), type: VisitType.Link)
XCTAssertTrue(history.addLocalVisit(local).value.isSuccess)
}
}
class TestSQLiteHistoryFrecencyPerf: XCTestCase {
func testFrecencyPerf() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)!
let count = 500
history.clearHistory().value
populateHistoryForFrecencyCalcuations(history, siteCount: count)
self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) {
for _ in 0...5 {
history.getSitesByFrecencyWithLimit(10, includeIcon: false).value
}
self.stopMeasuring()
}
}
}
class TestSQLiteHistoryTopSitesCachePref: XCTestCase {
func testCachePerf() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)!
let count = 500
history.clearHistory().value
populateHistoryForFrecencyCalcuations(history, siteCount: count)
history.setTopSitesNeedsInvalidation()
self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) {
history.updateTopSitesCacheIfInvalidated().value
self.stopMeasuring()
}
}
}
// MARK - Private Test Helper Methods
private enum VisitOrigin {
case Local
case Remote
}
private func populateHistoryForFrecencyCalcuations(history: SQLiteHistory, siteCount count: Int) {
for i in 0...count {
let site = Site(url: "http://s\(i)ite\(i)/foo", title: "A \(i)")
site.guid = "abc\(i)def"
history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).value
for j in 0...20 {
let visitTime = Timestamp(1000 * (1437088398461 + (1000 * i) + j))
addVisitForSite(site, intoHistory: history, from: .Local, atTime: visitTime)
addVisitForSite(site, intoHistory: history, from: .Remote, atTime: visitTime)
}
}
}
private func addVisitForSite(site: Site, intoHistory history: SQLiteHistory, from: VisitOrigin, atTime: Timestamp) {
let visit = SiteVisit(site: site, date: atTime, type: VisitType.Link)
switch from {
case .Local:
history.addLocalVisit(visit).value
case .Remote:
history.storeRemoteVisits([visit], forGUID: site.guid!).value
}
} | mpl-2.0 | 2722cb402deaa5999b96d75a42c24b1c | 39.413793 | 182 | 0.573019 | 4.806028 | false | false | false | false |
apple/swift | test/decl/var/static_var.swift | 7 | 17622 | // RUN: %target-typecheck-verify-swift -parse-as-library
// See also rdar://15626843.
static var gvu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{global 'var' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-2 {{add an initializer to silence this error}} {{18-18= = <#initializer#>}}
class var gvu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{global 'var' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-2 {{add an initializer to silence this error}} {{17-17= = <#initializer#>}}
override static var gvu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
// expected-error@-2 {{global 'var' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-3 {{add an initializer to silence this error}} {{27-27= = <#initializer#>}}
override class var gvu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
// expected-error@-2 {{global 'var' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-3 {{add an initializer to silence this error}} {{26-26= = <#initializer#>}}
static override var gvu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}}
// expected-error@-2 {{global 'var' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-3 {{add an initializer to silence this error}} {{27-27= = <#initializer#>}}
class override var gvu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}}
// expected-error@-2 {{global 'var' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-3 {{add an initializer to silence this error}} {{26-26= = <#initializer#>}}
static var gvu7: Int { // expected-error {{static properties may only be declared on a type}}{{1-8=}}
return 42
}
class var gvu8: Int { // expected-error {{class properties may only be declared on a type}}{{1-7=}}
return 42
}
static let glu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{global 'let' declaration requires an initializer expression}}
// expected-note@-2 {{add an initializer to silence this error}} {{18-18= = <#initializer#>}}
class let glu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{global 'let' declaration requires an initializer expression}}
// expected-note@-2 {{add an initializer to silence this error}} {{17-17= = <#initializer#>}}
override static let glu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
// expected-error@-2 {{global 'let' declaration requires an initializer expression}}
// expected-note@-3 {{add an initializer to silence this error}} {{27-27= = <#initializer#>}}
override class let glu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
// expected-error@-2 {{global 'let' declaration requires an initializer expression}}
// expected-note@-3 {{add an initializer to silence this error}} {{26-26= = <#initializer#>}}
static override let glu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}}
// expected-error@-2 {{global 'let' declaration requires an initializer expression}}
// expected-note@-3 {{add an initializer to silence this error}} {{27-27= = <#initializer#>}}
class override let glu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}}
// expected-error@-2 {{global 'let' declaration requires an initializer expression}}
// expected-note@-3 {{add an initializer to silence this error}} {{26-26= = <#initializer#>}}
static var gvi1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}}
class var gvi2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}}
override static var gvi3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
override class var gvi4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
static override var gvi5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}}
class override var gvi6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}}
static let gli1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}}
class let gli2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}}
override static let gli3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
override class let gli4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
static override let gli5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}}
class override let gli6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}}
func inGlobalFunc() {
static var v1: Int // expected-error {{static properties may only be declared on a type}}{{3-10=}}
class var v2: Int // expected-error {{class properties may only be declared on a type}}{{3-9=}}
static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{3-10=}}
class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{3-9=}}
v1 = 1; v2 = 1
_ = v1+v2+l1+l2
}
struct InMemberFunc {
func member() {
static var v1: Int // expected-error {{static properties may only be declared on a type}}{{5-12=}}
class var v2: Int // expected-error {{class properties may only be declared on a type}}{{5-11=}}
static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{5-12=}}
class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{5-11=}}
v1 = 1; v2 = 1
_ = v1+v2+l1+l2
}
}
struct S { // expected-note 3{{extended type declared here}}
static var v1: Int = 0
class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static var v3: Int { return 0 }
class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}}
static let l1: Int = 0
class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}}
}
extension S {
static var ev1: Int = 0
class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static var ev3: Int { return 0 }
class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static let el1: Int = 0
class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
}
enum E { // expected-note 3{{extended type declared here}}
static var v1: Int = 0
class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static var v3: Int { return 0 }
class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}}
static let l1: Int = 0
class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}}
}
extension E {
static var ev1: Int = 0
class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static var ev3: Int { return 0 }
class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
static let el1: Int = 0
class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
}
class C {
static var v1: Int = 0
class final var v3: Int = 0 // expected-error {{class stored properties not supported}}
class var v4: Int = 0 // expected-error {{class stored properties not supported}}
static var v5: Int { return 0 }
class var v6: Int { return 0 }
static final var v7: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}}
static let l1: Int = 0
class let l2: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
class final let l3: Int = 0 // expected-error {{class stored properties not supported}}
static final let l4 = 2 // expected-error {{static declarations are already final}} {{10-16=}}
}
extension C {
static var ev1: Int = 0
class final var ev2: Int = 0 // expected-error {{class stored properties not supported}}
class var ev3: Int = 0 // expected-error {{class stored properties not supported}}
static var ev4: Int { return 0 }
class var ev5: Int { return 0 }
static final var ev6: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}}
static let el1: Int = 0
class let el2: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
class final let el3: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
static final let el4: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}}
}
protocol P { // expected-note{{extended type declared here}}
// Both `static` and `class` property requirements are equivalent in protocols rdar://problem/17198298
static var v1: Int { get }
class var v2: Int { get } // expected-error {{class properties are only allowed within classes; use 'static' to declare a requirement fulfilled by either a static or class property}} {{3-8=static}}
static final var v3: Int { get } // expected-error {{only classes and class members may be marked with 'final'}}
static let l1: Int // expected-error {{protocols cannot require properties to be immutable; declare read-only properties by using 'var' with a '{ get }' specifier}}
class let l2: Int // expected-error {{class properties are only allowed within classes; use 'static' to declare a requirement fulfilled by either a static or class property}} {{3-8=static}} expected-error {{protocols cannot require properties to be immutable; declare read-only properties by using 'var' with a '{ get }' specifier}}
}
extension P {
class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}}
}
struct S1 {
// rdar://15626843
static var x: Int // expected-error {{'static var' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-1 {{add an initializer to silence this error}} {{17-17= = <#initializer#>}}
var y = 1
static var z = 5
}
extension S1 {
static var zz = 42
static var xy: Int { return 5 }
}
enum E1 {
static var y: Int {
get {}
}
}
class C1 {
class var x: Int // expected-error {{class stored properties not supported}} expected-error {{'class var' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-1 {{add an initializer to silence this error}} {{16-16= = <#initializer#>}}
class let x: Int // expected-error {{class stored properties not supported}} expected-error {{'class let' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-1 {{add an initializer to silence this error}} {{16-16= = <#initializer#>}}
static var x: Int // expected-error {{'static var' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-1 {{add an initializer to silence this error}} {{17-17= = <#initializer#>}}
static let x: Int // expected-error {{'static let' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-1 {{add an initializer to silence this error}} {{17-17= = <#initializer#>}}
// FIXME: We immediately invalidate the pattern binding after the first error
// is emitted, but we could definitely emit a second round of fixits for the
// other pattern here.
static var (x, y): (Int, Int), (z, w): (Int, Int) // expected-error {{'static var' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-1 {{add an initializer to silence this error}} {{31-31= = <#initializer#>}}
}
class C2 {
var x: Int = 19
class var x: Int = 17 // expected-error{{class stored properties not supported}}
func xx() -> Int { return self.x + C2.x }
}
class ClassHasVars {
static var computedStatic: Int { return 0 } // expected-note 3{{overridden declaration is here}}
final class var computedFinalClass: Int { return 0 } // expected-note 3{{overridden declaration is here}}
class var computedClass: Int { return 0 }
var computedInstance: Int { return 0 }
}
class ClassOverridesVars : ClassHasVars {
override static var computedStatic: Int { return 1 } // expected-error {{cannot override static property}}
override static var computedFinalClass: Int { return 1 } // expected-error {{static property overrides a 'final' class property}}
override class var computedClass: Int { return 1 }
override var computedInstance: Int { return 1 }
}
class ClassOverridesVars2 : ClassHasVars {
override final class var computedStatic: Int { return 1 } // expected-error {{cannot override static property}}
override final class var computedFinalClass: Int { return 1 } // expected-error {{class property overrides a 'final' class property}}
}
class ClassOverridesVars3 : ClassHasVars {
override class var computedStatic: Int { return 1 } // expected-error {{cannot override static property}}
override class var computedFinalClass: Int { return 1 } // expected-error {{class property overrides a 'final' class property}}
}
struct S2 {
var x: Int = 19
static var x: Int = 17
func xx() -> Int { return self.x + C2.x }
}
// Mutating vs non-mutating conflict with static stored property witness - rdar://problem/19887250
protocol Proto {
static var name: String {get set}
}
struct ProtoAdopter : Proto {
static var name: String = "name" // no error, even though static setters aren't mutating
}
// Make sure the logic remains correct if we synthesized accessors for our stored property
protocol ProtosEvilTwin {
static var name: String {get set}
}
extension ProtoAdopter : ProtosEvilTwin {}
// rdar://18990358
public struct Foo { // expected-note {{to match this opening '{'}}}
public static let S { _ = 0; aaaaaa // expected-error{{computed property must have an explicit type}} {{22-22=: <# Type #>}}
// expected-error@-1{{type annotation missing in pattern}}
// expected-error@-2{{'let' declarations cannot be computed properties}} {{17-20=var}}
// expected-error@-3{{cannot find 'aaaaaa' in scope}}
}
// expected-error@+1 {{expected '}' in struct}}
| apache-2.0 | 56b9141e387393e76a9e410d0540f830 | 58.533784 | 334 | 0.696232 | 3.945813 | false | false | false | false |
smartystreets/smartystreets-ios-sdk | UISamples/UISamples/SwiftSamples/SwiftController.swift | 1 | 2368 | import UIKit
class SwiftController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var examplePicker: UIPickerView!
var examples:[String] = ["US ZIP Code API","US Street API","International Street API","US Autocomplete API","US Autcomplete Pro API","US Extract API"]
override func viewDidLoad() {
super.viewDidLoad()
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "lines-map")?.draw(in: self.view.bounds)
let background = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: background!)
self.examplePicker.delegate = self
self.examplePicker.dataSource = self
examples = ["US ZIP Code API","US Street API","International Street API","US Autocomplete API","US Autcomplete Pro API","US Extract API"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return examples.count
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let name = NSAttributedString(string: examples[row], attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
return name
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch row {
case 0:
performSegue(withIdentifier: "ZIPCode", sender: self)
case 1:
performSegue(withIdentifier: "USStreet", sender: self)
case 2:
performSegue(withIdentifier: "International", sender: self)
case 3:
performSegue(withIdentifier: "Autocomplete", sender: self)
case 4:
performSegue(withIdentifier: "AutocompletePro", sender: self)
case 5:
performSegue(withIdentifier: "Extract", sender: self)
default:
return
}
}
@IBAction func Return(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | 145db7e012c35f91edfdd96ceaef0f49 | 36.587302 | 154 | 0.653294 | 5.418764 | false | false | false | false |
winslowdibona/TabDrawer | TabDrawer/Classes/Constant.swift | 2 | 4226 | // The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal
//
// 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
/**
Modifier used when a relationship is created between the target `UIView`
and the reference `UIView`.
Unlike `NSLayoutRelation` this enum also includes a `MultipliedBy` case
which acts as the `multiplier property of a `NSLayoutConstraint`
*/
public enum Modifier {
case EqualTo
case GreaterThanOrEqualTo
case LessThanOrEqualTo
case MultipliedBy
}
/**
Struct that aggregates `NSLayoutRelation`, constant and multiplier of a
layout constraint eventually created
*/
public struct Constant {
/// Value of the constant
let value: CGFloat
/// Modifier applied to the `value` of the `Constant`
var modifier: Modifier
/**
This initializer creates a `Constant` with the value supplied
and the modifier `.EqualTo`
- parameter value: Value of the `Constant`
- returns: the `Constant` struct created
*/
init(_ value: CGFloat) {
self.value = value
self.modifier = .EqualTo
}
/**
This initializer creates a `Constant` with the `value` and `modifier`
supplied.
- parameter value: Value of the `Constant`
- parameter modifier: Modifier applied to the `value`
- returns: the `Constant` struct created
*/
init(value: CGFloat, modifier: Modifier) {
self.value = value
self.modifier = modifier
}
/**
`NSLayoutRelation` equivalent to the `modifier` of the `Constant`
- returns: `NSLayoutRelation` equivalent
*/
internal func layoutRelation() -> NSLayoutRelation {
switch self.modifier {
case .EqualTo: return .Equal
case .LessThanOrEqualTo: return .LessThanOrEqual
case .GreaterThanOrEqualTo: return .GreaterThanOrEqual
case .MultipliedBy: return .Equal
}
}
/**
Determines the `CGFloat` value of the multiplier for the `modifier`
property
- returns: `CGFloat` multiplier
*/
internal func layoutMultiplier() -> CGFloat {
switch self.modifier {
case .EqualTo: return 1.0
case .LessThanOrEqualTo: return 1.0
case .GreaterThanOrEqualTo: return 1.0
case .MultipliedBy: return CGFloat(self.value)
}
}
/**
Value of the `Constant`
- returns: `CGFloat` value of the `Constant`
*/
internal func layoutValue() -> CGFloat {
switch self.modifier {
case .MultipliedBy: return 0.0
default: return CGFloat(self.value)
}
}
}
prefix operator >= {}
/**
Prefix operator that eases the creation of a `Constant` with a
`.GreaterThanOrEqualTo` modifier.
- parameter rhs: Value for the `Constant`
- returns: The resulting `Constant` struct
*/
public prefix func >= (rhs: CGFloat) -> Constant {
return Constant(value: rhs, modifier: .GreaterThanOrEqualTo)
}
prefix operator <= {}
/**
Prefix operator that eases the creation of a `Constant` with a
`.LessThanOrEqualTo` modifier.
- parameter rhs: Value for the `Constant`
- returns: The resulting `Constant` struct
*/
public prefix func <= (rhs: CGFloat) -> Constant {
return Constant(value: rhs, modifier: .LessThanOrEqualTo)
}
prefix operator * {}
/**
Prefix operator that eases the creation of a `Constant` with `value = 0.0`
and `multiplier` the value specifier at the right hand side of the operator.
- parameter rhs: Value for the `multiplier`
- returns: The resulting `Constant` struct
*/
public prefix func * (rhs: CGFloat) -> Constant {
return Constant(value: rhs, modifier: .MultipliedBy)
}
| mit | c2418d8b893bc023ed15e76334b83f40 | 29.623188 | 80 | 0.655703 | 4.649065 | false | false | false | false |
taher-mosbah/firefox-ios | Storage/SQL/BrowserTable.swift | 6 | 11467 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCGLogger
// To keep SwiftData happy.
typealias Args = [AnyObject?]
let TableBookmarks = "bookmarks"
let TableFavicons = "favicons"
let TableHistory = "history"
let TableVisits = "visits"
let TableFaviconSites = "favicon_sites"
let TableQueuedTabs = "queue"
let ViewWidestFaviconsForSites = "view_favicons_widest"
let ViewHistoryIDsWithWidestFavicons = "view_history_id_favicon"
let ViewIconForURL = "view_icon_for_url"
let IndexHistoryShouldUpload = "idx_history_should_upload"
let IndexVisitsSiteIDDate = "idx_visits_siteID_date"
private let AllTables: Args = [
TableFaviconSites,
TableHistory,
TableVisits,
TableBookmarks,
TableQueuedTabs,
]
private let AllViews: Args = [
ViewHistoryIDsWithWidestFavicons,
ViewWidestFaviconsForSites,
ViewIconForURL,
]
private let AllIndices: Args = [
IndexHistoryShouldUpload,
IndexVisitsSiteIDDate,
]
private let AllTablesIndicesAndViews: Args = AllViews + AllIndices + AllTables
private let log = XCGLogger.defaultInstance()
/**
* The monolithic class that manages the inter-related history etc. tables.
* We rely on SQLiteHistory having initialized the favicon table first.
*/
public class BrowserTable: Table {
var name: String { return "BROWSER" }
var version: Int { return 5 }
let sqliteVersion: Int32
let supportsPartialIndices: Bool
public init() {
let v = sqlite3_libversion_number()
self.sqliteVersion = v
self.supportsPartialIndices = v >= 3008000 // 3.8.0.
let ver = String.fromCString(sqlite3_libversion())!
log.info("SQLite version: \(ver) (\(v)).")
}
func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in BrowserTable. \(err?.localizedDescription)")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql, args: nil) {
return false
}
}
return true
}
func prepopulateRootFolders(db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.Folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func create(db: SQLiteDBConnection, version: Int) -> Bool {
// We ignore the version.
let history =
"CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
") "
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDDate) " +
"ON \(TableVisits) (siteID, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"\(TableFavicons).id AS iconID, " +
"\(TableFavicons).url AS iconURL, " +
"\(TableFavicons).date AS iconDate, " +
"\(TableFavicons).type AS iconType, " +
"MAX(\(TableFavicons).width) AS iconWidth " +
"FROM \(TableFaviconSites), \(TableFavicons) WHERE " +
"\(TableFaviconSites).faviconID = \(TableFavicons).id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT \(TableHistory).id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM \(TableHistory) " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS \(TableBookmarks) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES \(TableBookmarks)(id) NOT NULL, " +
"faviconID INTEGER REFERENCES \(TableFavicons)(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queue =
"CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
let queries = [
history, visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
queue,
]
assert(queries.count == AllTablesIndicesAndViews.count, "Did you forget to add your table, index, or view to the list?")
log.debug("Creating \(queries.count) tables, views, and indices.")
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating browser tables from zero. Assuming drop and recreate.")
return drop(db) && create(db, version: to)
}
log.debug("Updating browser tables from \(from) to \(to).")
if from < 4 {
return drop(db) && create(db, version: to)
}
if from < 5 {
let queue =
"CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
if !self.run(db, queries: [queue]) {
return false
}
}
return true
}
/**
* The Table mechanism expects to be able to check if a 'table' exists. In our (ab)use
* of Table, that means making sure that any of our tables and views exist.
* We do that by fetching all tables from sqlite_master with matching names, and verifying
* that we get back more than one.
* Note that we don't check for views -- trust to luck.
*/
func exists(db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllTables)
}
func drop(db: SQLiteDBConnection) -> Bool {
log.debug("Dropping all browser tables.")
let additional = [
"DROP TABLE IF EXISTS faviconSites", // We renamed it to match naming convention.
]
let queries = AllViews.map { "DROP VIEW IF EXISTS \($0!)" } +
AllIndices.map { "DROP INDEX IF EXISTS \($0!)" } +
AllTables.map { "DROP TABLE IF EXISTS \($0!)" } +
additional
return self.run(db, queries: queries)
}
} | mpl-2.0 | 17577d92b92a53c8ed5b1e130c4cbd6f | 39.380282 | 231 | 0.610273 | 4.568526 | false | false | false | false |
simplymadeapps/SMABannerView | SMABannerView/SMABannerView.swift | 1 | 8411 | //
// SMABannerView.swift
//
// Created by Bill Burgess on 5/4/16.
// Copyright © 2016 Simply Made Apps. All rights reserved.
//
import UIKit
enum SMABannerAlignment: Int {
case Center = 0
case Left = 1
case Right = 2
}
class SMABannerView: UIView {
private var bottomConstraint: NSLayoutConstraint?
var titleLabel: UILabel?
var messageLabel: UILabel?
var titleString: String?
var messageString: String?
var containerView: UIView?
var titleFont = UIFont.systemFontOfSize(24)
var titleColor = UIColor.blackColor()
var messageFont = UIFont.systemFontOfSize(18)
var messageColor = UIColor.blackColor()
var animationDuration = 0.3
var titlePaddingTop: CGFloat = 15.0
var paddingLeft: CGFloat = 40.0
var paddingRight: CGFloat = 40.0
var messagePaddingBottom: CGFloat = 10.0
var opacity: CGFloat = 0.8
var bannerHeight: CGFloat = 100.0
var alignment: SMABannerAlignment
var isShowing: Bool
var isAnimating: Bool
required init?(coder: NSCoder) {
isShowing = false
isAnimating = false
alignment = .Center
super.init(coder: coder)
}
init() {
isShowing = false
isAnimating = false
alignment = .Center
super.init(frame: CGRectZero)
}
convenience init(title: String?, message: String?, view: UIView) {
self.init()
self.containerView = view
self.titleString = title
self.messageString = message
}
func layoutBannerView() {
titleLabel = UILabel.init()
titleLabel?.numberOfLines = 1
titleLabel?.text = titleString
titleLabel?.font = self.titleFont
titleLabel?.textColor = titleColor
titleLabel?.adjustsFontSizeToFitWidth = true
messageLabel = UILabel.init()
messageLabel?.numberOfLines = 0
messageLabel?.text = messageString
messageLabel?.font = messageFont
messageLabel?.textColor = messageColor
messageLabel?.adjustsFontSizeToFitWidth = true
messageLabel?.lineBreakMode = .ByTruncatingTail
switch alignment {
case .Left:
titleLabel?.textAlignment = .Left
messageLabel?.textAlignment = .Left
case .Right:
titleLabel?.textAlignment = .Right
messageLabel?.textAlignment = .Right
case .Center:
titleLabel?.textAlignment = .Center
messageLabel?.textAlignment = .Center
}
self.addSubview(titleLabel!)
self.addSubview(messageLabel!)
self.containerView?.addSubview(self)
self.alpha = self.opacity
// constraints
// view
self.translatesAutoresizingMaskIntoConstraints = false
bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: self.containerView, attribute: .Bottom, multiplier: 1.0, constant: bannerHeight)
self.containerView!.addConstraint(bottomConstraint!)
let viewLeft = NSLayoutConstraint(item: self, attribute: .Left, relatedBy: .Equal, toItem: self.containerView, attribute: .Left, multiplier: 1.0, constant: 0)
self.containerView!.addConstraint(viewLeft)
let viewRight = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: self.containerView, attribute: .Right, multiplier: 1.0, constant: 0)
self.containerView!.addConstraint(viewRight)
let viewHeight = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: bannerHeight)
self.containerView!.addConstraint(viewHeight)
// title
titleLabel?.translatesAutoresizingMaskIntoConstraints = false
let titleTop = NSLayoutConstraint(item: titleLabel!, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: titlePaddingTop)
self.addConstraint(titleTop)
let titleLeft = NSLayoutConstraint(item: titleLabel!, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: paddingLeft)
self.addConstraint(titleLeft)
let titleRight = NSLayoutConstraint(item: titleLabel!, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1.0, constant: -paddingRight)
self.addConstraint(titleRight)
// message
messageLabel?.translatesAutoresizingMaskIntoConstraints = false
let messageTop = NSLayoutConstraint(item: messageLabel!, attribute: .Top, relatedBy: .Equal, toItem: titleLabel, attribute: .Bottom, multiplier: 1.0, constant: 0)
self.addConstraint(messageTop)
let messageLeft = NSLayoutConstraint(item: messageLabel!, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: paddingLeft)
self.addConstraint(messageLeft)
let messageRight = NSLayoutConstraint(item: messageLabel!, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1.0, constant: -paddingRight)
self.addConstraint(messageRight)
let messageBottom = NSLayoutConstraint(item: messageLabel!, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: -messagePaddingBottom)
self.addConstraint(messageBottom)
self.layoutIfNeeded()
}
func show() {
if self.isShowing || self.isAnimating {
print("Unable to present Banner View: Currently showing or animating")
return
}
if self.containerView != nil {
self.layoutBannerView()
self.isAnimating = true
self.containerView!.removeConstraint(bottomConstraint!)
bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: self.containerView, attribute: .Bottom, multiplier: 1.0, constant: 0)
self.containerView!.addConstraint(bottomConstraint!)
UIView.animateWithDuration(self.animationDuration, animations: {
self.layoutIfNeeded()
}, completion: { (complete) in
self.isShowing = true
self.isAnimating = false
})
}
}
func show(duration: Double) {
self.show()
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(duration * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.hide(nil)
})
}
func show(duration: Double, completion:(() -> Void)) {
self.show()
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(duration * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.hide(completion)
})
}
func hide(completion:((Void) -> ())?) {
if self.isAnimating || !self.isShowing {
print("Unable to dismiss Banner View: Currently animating or not showing")
if completion != nil {
completion!()
}
return
}
if self.containerView != nil {
self.isAnimating = true
self.containerView!.removeConstraint(bottomConstraint!)
bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: self.containerView, attribute: .Bottom, multiplier: 1.0, constant: bannerHeight)
self.containerView!.addConstraint(bottomConstraint!)
UIView.animateWithDuration(self.animationDuration, animations: {
// animations
self.layoutIfNeeded()
}, completion: { (complete) in
self.isAnimating = false
self.isShowing = false
self.removeFromSuperview()
if completion != nil {
completion!()
}
})
} else {
print("Unable to hide Banner View: No container view")
if completion != nil {
completion!()
}
}
}
func hide() {
self.hide(nil)
}
}
| mit | 8c7f4a2da9e05d3216924026a141a503 | 39.239234 | 190 | 0.627111 | 5.087719 | false | false | false | false |
WeezLabs/rwauth-ios | Tests/MockSessionError.swift | 1 | 2206 | //
// MockSessionError.swift
// RWAuth
//
// Created by Роман on 03.11.15.
// Copyright © 2015 weezlabs. All rights reserved.
//
import Foundation
enum MockSessionError: Int, ErrorType {
case UnrecognizedError = 0
case FakeRequestOrFakeAnswerNotSetted = 1
case EmptyBodyData = 2
case BodyDataNotConvertableToString = 3
case RequestDoesNotHaveURL = 4
case StubbedURLNotEqualRequestURL = 5
case StubbedRequestBodyNotEqualRequestBody = 6
case HTTPMethodsNotEqual = 7
static var domain: String = "com.weezlabs.httpmock.session"
var error: NSError {
switch self {
case .UnrecognizedError:
return NSError(domain: MockSessionError.domain, code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: "Unrecognized Error"])
case .FakeRequestOrFakeAnswerNotSetted:
return NSError(domain: MockSessionError.domain, code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: "Fake Request Or Fake Answer Not Setted"])
case .EmptyBodyData:
return NSError(domain: MockSessionError.domain, code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: "Empty Body Data"])
case .BodyDataNotConvertableToString:
return NSError(domain: MockSessionError.domain, code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: "Body Data Not Convertable To String"])
case .RequestDoesNotHaveURL:
return NSError(domain: MockSessionError.domain, code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: "Request Does Not have URL"])
case .StubbedURLNotEqualRequestURL:
return NSError(domain: MockSessionError.domain, code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: "Stubbed URL Not Equal Request URL"])
case .StubbedRequestBodyNotEqualRequestBody:
return NSError(domain: MockSessionError.domain, code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: "Stubbed Request Body Not Equal Request Body"])
case .HTTPMethodsNotEqual:
return NSError(domain: MockSessionError.domain, code: self.rawValue, userInfo: [NSLocalizedDescriptionKey: "HTTP Methods Not Equal"])
}
}
}
| mit | b64263892380ec84f54526ed094bfa72 | 49 | 166 | 0.722727 | 4.803493 | false | false | false | false |
fishermenlabs/Treasure | Treasure/Classes/Key.swift | 1 | 1671 | //
// Key.swift
// Treasure
//
// Created by Kevin Weber on 11/6/17.
// Copyright © 2018 Fishermen Labs. All rights reserved.
//
import Foundation
public struct Key {
public static let id = "id"
public static let type = "type"
public static let data = "data"
public static let links = "links"
public static let included = "included"
public static let meta = "meta"
public static let errors = "errors"
public static let jsonapi = "jsonapi"
public static let first = "first"
public static let last = "last"
public static let prev = "prev"
public static let next = "next"
public static let page = "page"
public static let self_ = "self"
public static let collection = "collection"
public static let href = "href"
public static let related = "related"
public static let relationship = "relationship"
public static let status = "status"
public static let code = "code"
public static let title = "title"
public static let detail = "detail"
public static let source = "source"
public static let version = "version"
public static let about = "about"
public static let pointer = "pointer"
public static let parameter = "parameter"
public static func attributes(_ key: String? = nil) -> String {
guard key?.isEmpty == false else {
return "attributes"
}
return "attributes.\(key!)"
}
public static func relationships(_ key: String? = nil) -> String {
guard key?.isEmpty == false else {
return "relationships"
}
return "relationships.\(key!)"
}
}
| mit | 6387e7aa39b97c12f232c5ddc046e258 | 28.821429 | 70 | 0.623952 | 4.337662 | false | false | false | false |
J3D1-WARR10R/WikiRaces | WikiRaces/Shared/Race View Controllers/ResultsViewController/ResultsViewController+Actions.swift | 2 | 2737 | //
// ResultsViewController+Actions.swift
// WikiRaces
//
// Created by Andrew Finke on 1/29/19.
// Copyright © 2019 Andrew Finke. All rights reserved.
//
import UIKit
import WKRUIKit
extension ResultsViewController {
// MARK: - Actions
@objc func doneButtonPressed() {
PlayerFirebaseAnalytics.log(event: .userAction(#function))
guard let alertController = quitAlertController else {
PlayerFirebaseAnalytics.log(event: .backupQuit,
attributes: ["RawGameState": state.rawValue])
listenerUpdate?(.quit)
return
}
present(alertController, animated: true, completion: nil)
}
@objc func shareResultsBarButtonItemPressed(_ sender: UIBarButtonItem) {
PlayerFirebaseAnalytics.log(event: .userAction(#function))
guard let image = resultImage else { return }
let hackTitle = "Hack"
let controller = UIActivityViewController(activityItems: [
image,
], applicationActivities: nil)
controller.completionWithItemsHandler = { [weak self] activityType, completed, _, _ in
if !(completed && activityType == UIActivity.ActivityType.saveToCameraRoll),
let hack = self?.presentedViewController,
hack.title == hackTitle {
self?.dismiss(animated: false, completion: nil)
}
}
controller.popoverPresentationController?.barButtonItem = sender
// seriously, iOS 13 broke activity sheet save to photos??
let hack = UIViewController()
hack.title = hackTitle
hack.view.alpha = 0.0
hack.modalPresentationStyle = .overCurrentContext
present(hack, animated: false, completion: {
hack.present(controller, animated: true, completion: nil)
})
PlayerFirebaseAnalytics.log(event: .openedShare)
}
func tapped(playerID: String) {
PlayerFirebaseAnalytics.log(event: .userAction(#function))
guard let resultsInfo = resultsInfo, let player = resultsInfo.player(for: playerID), state != .points else {
return
}
let controller = HistoryViewController(style: .grouped)
historyViewController = controller
controller.player = player
let navController = WKRUINavigationController(rootViewController: controller)
navController.modalPresentationStyle = UIDevice.current.userInterfaceIdiom == .phone ? .fullScreen : .formSheet
present(navController, animated: true, completion: nil)
PlayerFirebaseAnalytics.log(event: .openedHistory,
attributes: ["GameState": state.rawValue.description as Any])
}
}
| mit | 9062f39369500d310ca6cde5f352791c | 36.479452 | 119 | 0.65095 | 5.261538 | false | false | false | false |
GlimmerLabs/MathOverImages | iOS/Mist Renderer/mistRenderer.swift | 1 | 1816 | //
// mistRenderer.swift
// Mist Renderer
//
// Created by Alex Mitchell on 7/17/14.
// Copyright (c) 2014 Glimmer Labs. All rights reserved.
//
import UIKit
import CoreGraphics
class mistRenderer: UIView {
override func drawRect(rect: CGRect) {
let myContext = UIGraphicsGetCurrentContext()
CGContextSetRGBFillColor(myContext, 1, 0, 0, 1)
CGContextFillRect(myContext, CGRectMake(0, 0, 200, 100))
CGContextSetRGBFillColor(myContext, 0, 0, 1, (1/2))
CGContextFillRect(myContext, CGRectMake(0, 0, 100, 200))
}
func expType(exp: String, context: CGContextRef){}
func r2c(r: Double) -> Double {
return 127.5 + r * 127.5
}
func c2r(c: Double) -> Double {
return (c/127.5) - 1.0
}
/*
func cap(val: Double) -> Double {
return MAX(-1, MIN(1, val))
}*/
func wrap(val:Double) -> Double {
if (val < -1){
return wrap(val + 2)
}
else if (val > 1){
return wrap(val-2)
}
else {
return val
}
}
// MOI Functions
func MOIsign (range: Double) -> Double {
if (range < 0){
return -1
}
else if (range > 0){
return 1
}
else {
return range
}
}
func MOIshift (a: Double, b: Double) -> Double {
return self.wrap(a+b)
}
func MOIsquare(a: Double) -> Double {
return a * a
}
// Renderer
func renderFun(fun: String, context:CGContextRef, rLeft: Double, rTop: Double, rWidth: Double, rHeight: Double) {
var deltaX = 2.0/rWidth
var deltaY = 2.0/rHeight
var d = NSDate()
var x = -1
var y = -1 - deltaY
}
}
| lgpl-3.0 | a49ab2540ca2838cd859955a6742871f | 21.7 | 117 | 0.515419 | 3.767635 | false | false | false | false |
danielgindi/ChartsRealm | ChartsRealm/Classes/Data/RealmLineScatterCandleRadarDataSet.swift | 1 | 1942 | //
// RealmLineScatterCandleRadarDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import Charts
import Realm
import Realm.Dynamic
open class RealmLineScatterCandleRadarDataSet: RealmBarLineScatterCandleBubbleDataSet, ILineScatterCandleRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// Enables / disables the horizontal highlight-indicator. If disabled, the indicator is not drawn.
open var drawHorizontalHighlightIndicatorEnabled = true
/// Enables / disables the vertical highlight-indicator. If disabled, the indicator is not drawn.
open var drawVerticalHighlightIndicatorEnabled = true
/// - returns: `true` if horizontal highlight indicator lines are enabled (drawn)
open var isHorizontalHighlightIndicatorEnabled: Bool { return drawHorizontalHighlightIndicatorEnabled }
/// - returns: `true` if vertical highlight indicator lines are enabled (drawn)
open var isVerticalHighlightIndicatorEnabled: Bool { return drawVerticalHighlightIndicatorEnabled }
/// Enables / disables both vertical and horizontal highlight-indicators.
/// :param: enabled
open func setDrawHighlightIndicators(_ enabled: Bool)
{
drawHorizontalHighlightIndicatorEnabled = enabled
drawVerticalHighlightIndicatorEnabled = enabled
}
// MARK: NSCopying
open override func copy(with zone: NSZone? = nil) -> Any
{
let copy = super.copy(with: zone) as! RealmLineScatterCandleRadarDataSet
copy.drawHorizontalHighlightIndicatorEnabled = drawHorizontalHighlightIndicatorEnabled
copy.drawVerticalHighlightIndicatorEnabled = drawVerticalHighlightIndicatorEnabled
return copy
}
}
| apache-2.0 | 1605ec60c8019f389f5a0f4b3014f90a | 35.641509 | 122 | 0.746653 | 5.711765 | false | false | false | false |
sunlijian/sinaBlog_repository | sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Module/OAuth/Controller/IWOAthViewController.swift | 1 | 5361 | //
// IWOAthViewController.swift
// sinaBlog_sunlijian
//
// Created by sunlijian on 15/10/13.
// Copyright © 2015年 myCompany. All rights reserved.
//
import UIKit
import AFNetworking
//App Key:2039429805
//App Secret:27b45a9dc97a16956a49f95b991a5f1a
//请求
//https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
//同意授权后会重定向
//http://www.example.com/response&code=CODE
class IWOAthViewController: UIViewController, UIWebViewDelegate {
//拼接请求网址
let client_id = "2039429805"
let client_secret = "27b45a9dc97a16956a49f95b991a5f1a"
let redirect_uri = "http://www.qq.com"
weak var webView: UIWebView?
override func viewDidLoad() {
super.viewDidLoad()
//添加自动添充按钮
setupNav()
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
//创建 webView
let webView = UIWebView(frame: CGRectMake(0, 0, SCREEN_W, SCREEN_H))
//加载 request
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
//添加到当前 VIEW 上
view.addSubview(webView)
//设置代理
webView.delegate = self
self.webView = webView
}
private func setupNav(){
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoinput")
}
@objc private func autoinput(){
let script = "document.getElementById('userId').value='[email protected]';document.getElementById('passwd').value='2431009'"
self.webView!.stringByEvaluatingJavaScriptFromString(script)
}
//加载 webView 时的代理 方法
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//获取加载的网址
let urlString = request.URL!.absoluteString
//获取点击授权后调用的网址
if urlString.hasPrefix(redirect_uri) {
//获取 code
let codePre = "code="
let rang = (urlString as NSString).rangeOfString(codePre)
if rang.location != NSNotFound {
let code = (urlString as NSString).substringFromIndex(rang.location + rang.length)
print(code)//8b0e14d6b02dab43ef31e7bead160fec
loadAccessToken(code)
return false
}
}
return true
}
//获取授权过的 accessToken
private func loadAccessToken(code: String){
//请求地址
let urlString = "https://api.weibo.com/oauth2/access_token"
//请求参数
let paramters = [
"client_id": client_id,
"client_secret" : client_secret,
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect_uri
]
//请求管理者
let manager = AFHTTPSessionManager()
//添加请求类型
manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//开始请求
manager.POST(urlString, parameters: paramters, success:
{ (dataTask, result) -> Void in
//请请成功的闭包
print("请求成功:\(result)")
let account = IWUserAccount(dictionary: (result as? [String : AnyObject])!)
print(account)
//获取成功后 保存帐号信息 归档
// account.saveAccount()
self.loadUserInfo(account)
}) { (dataTask, error) -> Void in
//请求失败的闭包
print("请求失败:\(error)")
}
}
private func loadUserInfo(account: IWUserAccount) {
let manager = AFHTTPSessionManager()
//请求地址
let urlString = "https://api.weibo.com/2/users/show.json"
//拼装参数
let prams = [
"access_token":account.access_token!,
"uid": account.uid!
]
//发送 get请求
manager.GET(urlString, parameters: prams, success: { (dataTask, result) -> Void in
//通过 accessToken 获取个人信息成功
if let res = (result as? [String: AnyObject]) {
//获取头象
account.avatar_large = res["avatar_large"] as? String
//获取昵称
account.name = res["name"] as? String
//保存
account.saveAccount()
//跳转控制器到欢迎页
let window = UIApplication.sharedApplication().delegate!.window!
window?.rootViewController = IWWelcomViewController()
}
}) { (dataTask, error) -> Void in
//
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | b3fbe88d47fb34f86ee2fed7adb48b3e | 30.446541 | 144 | 0.5646 | 4.444444 | false | false | false | false |
kylecrawshaw/ImagrAdmin | ImagrAdmin/WorkflowSupport/WorkflowComponents/EraseVolumeComponent/EraseVolumeViewController.swift | 1 | 1031 | //
// ImageComponentViewController.swift
// ImagrManager
//
// Created by Kyle Crawshaw on 7/14/16.
// Copyright © 2016 Kyle Crawshaw. All rights reserved.
//
import Cocoa
class EraseVolumeViewController: NSViewController {
@IBOutlet weak var volumeNameField: NSTextField!
@IBOutlet weak var volumeFormatField: NSTextField!
var component: EraseVolumeComponent?
override func viewWillAppear() {
super.viewDidAppear()
component = ImagrConfigManager.sharedManager.getComponent(self.identifier!) as? EraseVolumeComponent
volumeNameField.stringValue = component!.volumeName
volumeFormatField.stringValue = component!.volumeFormat
}
override func viewDidDisappear() {
component!.volumeName = volumeNameField.stringValue
component!.volumeFormat = volumeFormatField.stringValue
component!.notifyUpdateTable()
}
@IBAction func okButtonClicked(sender: AnyObject) {
component!.closeComponentPanel()
}
}
| apache-2.0 | db882c6f944abc9c0e77ec894a20f70d | 26.837838 | 108 | 0.71068 | 5.02439 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDKTests/MXClientInformationServiceUnitTests.swift | 1 | 4724 | //
// Copyright 2022 The Matrix.org Foundation C.I.C
//
// 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 XCTest
@testable import MatrixSDK
class MXClientInformationServiceUnitTests: XCTestCase {
let mockDeviceId = "some_device_id"
let mockAppName = "Element"
let mockAppVersion = "1.9.7"
func testUpdateData() {
MXSDKOptions.sharedInstance().enableNewClientInformationFeature = true
let (session, bundle) = createSessionAndBundle()
let service = MXClientInformationService(withSession: session, bundle: bundle)
let type = "\(kMXAccountDataTypeClientInformation).\(mockDeviceId)"
// no client info before
let clientInfo = session.accountData.accountData(forEventType: type)
XCTAssertNil(clientInfo)
service.updateData()
// must be set after updateData
let updatedInfo = session.accountData.accountData(forEventType: type)
XCTAssertEqual(updatedInfo?["name"] as? String, "\(mockAppName) iOS")
XCTAssertEqual(updatedInfo?["version"] as? String, mockAppVersion)
session.close()
}
func testRedundantUpdateData() {
MXSDKOptions.sharedInstance().enableNewClientInformationFeature = true
let (session, bundle) = createSessionAndBundle()
let service = MXClientInformationService(withSession: session, bundle: bundle)
let type = "\(kMXAccountDataTypeClientInformation).\(mockDeviceId)"
let newClientInfo = [
"name": "\(mockAppName) iOS",
"version": mockAppVersion
]
// set account data internally
session.accountData.update(withType: type, data: newClientInfo)
// make a redundant update
service.updateData()
XCTAssertFalse(session.isSetAccountDataCalled)
session.close()
}
func testRemoveDataByDisablingFeature() {
// enable the feature
MXSDKOptions.sharedInstance().enableNewClientInformationFeature = true
let (session, bundle) = createSessionAndBundle()
let service = MXClientInformationService(withSession: session, bundle: bundle)
let type = "\(kMXAccountDataTypeClientInformation).\(mockDeviceId)"
service.updateData()
let clientInfo = session.accountData.accountData(forEventType: type)
XCTAssertNotNil(clientInfo)
// disable the feature
MXSDKOptions.sharedInstance().enableNewClientInformationFeature = false
service.updateData()
// must be empty after updateData
let updatedInfo = session.accountData.accountData(forEventType: type)
XCTAssert(updatedInfo?.isEmpty ?? true)
session.close()
}
// Returns (session, bundle) tuple
private func createSessionAndBundle() -> (MockSession, Bundle) {
let credentials = MXCredentials(homeServer: "", userId: "@userid:example.com", accessToken: "")
credentials.deviceId = mockDeviceId
guard let session = MockSession(matrixRestClient: MXRestClientStub(credentials: credentials)) else {
fatalError("Cannot create session")
}
let bundle = MockBundle(with: [
"CFBundleDisplayName": mockAppName,
"CFBundleShortVersionString": mockAppVersion
])
return (session, bundle)
}
}
private class MockSession: MXSession {
var isSetAccountDataCalled = false
override func setAccountData(_ data: [AnyHashable : Any]!,
forType type: String!,
success: (() -> Void)!,
failure: ((Swift.Error?) -> Void)!) -> MXHTTPOperation! {
isSetAccountDataCalled = true
return super.setAccountData(data,
forType: type,
success: success,
failure: failure)
}
}
private class MockBundle: Bundle {
private let dictionary: [String: String]
init(with dictionary: [String: String]) {
self.dictionary = dictionary
super.init()
}
override func object(forInfoDictionaryKey key: String) -> Any? {
dictionary[key]
}
}
| apache-2.0 | 1e668052d55d0d5cfe4c04c52a5a97b2 | 32.267606 | 108 | 0.652625 | 4.998942 | false | false | false | false |
peferron/algo | EPI/Binary Trees/Reconstruct a binary tree from traversal data/swift/main.swift | 1 | 1351 | public class Node<T: Hashable> {
public let value: T
public let left: Node?
public let right: Node?
public convenience init?(inorder: [T], preorder: [T]) {
var inorderIndexes = [T: Int]()
for (index, value) in inorder.enumerated() {
inorderIndexes[value] = index
}
self.init(
inorder: inorder[0..<inorder.count],
preorder: preorder[0..<preorder.count],
inorderIndexes: inorderIndexes
)
}
init?(inorder: ArraySlice<T>, preorder: ArraySlice<T>, inorderIndexes: [T: Int]) {
if inorder.isEmpty {
return nil
}
self.value = preorder.first!
let inorderRootIndex = inorderIndexes[self.value]!
let leftCount = inorderRootIndex - inorder.startIndex
let preorderRightStartIndex = preorder.startIndex + 1 + leftCount
self.left = Node(
inorder: inorder[inorder.startIndex..<inorderRootIndex],
preorder: preorder[preorder.startIndex + 1..<preorderRightStartIndex],
inorderIndexes: inorderIndexes
)
self.right = Node(
inorder: inorder[inorderRootIndex + 1..<inorder.endIndex],
preorder: preorder[preorderRightStartIndex..<preorder.endIndex],
inorderIndexes: inorderIndexes
)
}
}
| mit | 625aa087604040cf002a9d99495ea7d1 | 31.166667 | 86 | 0.603997 | 4.221875 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Playgrounds/Effects.playground/Pages/Flat Frequency Response Reverb.xcplaygroundpage/Contents.swift | 2 | 1080 | //: ## Flat Frequency Response Reverb
//:
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
var reverb = AKFlatFrequencyResponseReverb(player, loopDuration: 0.1)
reverb.reverbDuration = 1
AudioKit.output = reverb
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Flat Frequency Response Reverb")
addSubview(AKResourcesAudioFileLoaderView(
player: player,
filenames: processingPlaygroundFiles))
addSubview(AKPropertySlider(
property: "Duration",
value: reverb.reverbDuration, maximum: 5,
color: AKColor.greenColor()
) { sliderValue in
reverb.reverbDuration = sliderValue
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView() | mit | 1e972d2b8ef154288c08acf7f846a0ab | 25.365854 | 70 | 0.687037 | 5.346535 | false | false | false | false |
jianghongbing/APIReferenceDemo | UIKit/UIViewController/UIViewController/ContainerViewController.swift | 1 | 2859 | //
// ContainerViewController.swift
// UIViewController
//
// Created by pantosoft on 2017/6/28.
// Copyright © 2017年 jianghongbing. All rights reserved.
//
import UIKit
class ContainerViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .orange
}
@IBAction func addViewController(_ sender: Any) {
let viewContorller = UIViewController()
// viewContorller.preferredContentSize = CGSize(width: view.bounds.width, height: 100)
viewContorller.view.backgroundColor = UIColor(colorLiteralRed: Float(arc4random_uniform(255)) / 255.0, green: Float(arc4random_uniform(255)) / 255.0, blue: Float(arc4random_uniform(255)) / 255.0, alpha: 1.0)
viewContorller.willMove(toParentViewController: self)
addChildViewController(viewContorller)
view.addSubview(viewContorller.view)
viewContorller.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 100)
viewContorller.view.center = view.center
viewContorller.didMove(toParentViewController: self)
}
@IBAction func removeViewController(_ sender: Any) {
if let last = childViewControllers.last {
last.willMove(toParentViewController: nil)
last.view.removeFromSuperview()
last.removeFromParentViewController()
last.didMove(toParentViewController: nil)
}
}
@IBAction func replaceViewController(_ sender: Any) {
let viewControllers = childViewControllers
let toViewController = UIViewController()
toViewController.view.backgroundColor = UIColor(colorLiteralRed: Float(arc4random_uniform(255)) / 255.0, green: Float(arc4random_uniform(255)) / 255.0, blue: Float(arc4random_uniform(255)) / 255.0, alpha: 1.0)
toViewController.willMove(toParentViewController: self)
addChildViewController(toViewController)
view.addSubview(toViewController.view)
toViewController.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 100)
toViewController.view.center = view.center
toViewController.view.alpha = 0.0
toViewController.didMove(toParentViewController: self)
if let fromViewController = viewControllers.last {
// beginAppearanceTransition(true, animated: false)
transition(from: fromViewController, to: toViewController, duration: 0.5, options: .curveLinear, animations: {
toViewController.view.alpha = 1.0
fromViewController.view.alpha = 0.0
}, completion: {
if $0 {
print("animation compelte")
}
// self.endAppearanceTransition()
})
}
}
}
| mit | 62607f73d00043708662569c59f21d8e | 39.8 | 217 | 0.651961 | 4.744186 | false | false | false | false |
Cezar2005/SuperChat | SuperChat/LoginService.swift | 1 | 4618 | import Foundation
import Alamofire
import SwiftyJSON
import RealmSwift
//The service provides methods for authorization on server.
class LoginService {
/* Class properties.
'ServerPath' - it's a http path to server.
'curSession' - it's a string value of current an ID of session.
'headers' - it's headers for http request that contain an ID of session, accept type and content type.
*/
let ServerPath: String = ClientAPI().ServerPath
var curSession: String = ""
let headers: [String: String]
init () {
if Realm().objects(currSession2).count != 0 {
curSession = Realm().objects(currSession2)[0].session_id
}
self.headers = [
"X-Session-Id": "\(self.curSession)",
"Accept": "application/json",
"Content-type": "application/json"
]
}
/* Public functions.
'perform()' - the function that takes login and password, checks them and sends them into request.
'logout()' - the function that makes logout of the user.
*/
func perform(login: String, password: String, completion_request: (result: [String: String]) -> Void) -> [String: String] {
var loginIsAvalible = true
var response: [String: String] = [:]
if login.isEmpty || password.isEmpty {
loginIsAvalible = false
}
if loginIsAvalible {
make_request(login, password: password, completion_request: completion_request)
} else {
response = process_error()
completion_request(result: response)
}
return response
}
func logout(completion_request: (result: Bool) -> Void) -> Void {
make_request_logout(completion_request)
}
/* Private functions.
'make_request()' - the function that directly performs POST request to server for user login. It uses the Alamofire framework.
'process_error()' - the function that returns error when login or password are empty. It's UI error.
'make_request_logout()' - the function that directly performs POST request to server for user logout. It uses the Alamofire framework.
*/
private func make_request(login: String, password: String, completion_request: (result: [String: String]) -> Void) -> Void {
var result: [String: String] = [:]
Alamofire.request(.POST, "\(ServerPath)/v1/login", parameters: ["login":login, "password":password], encoding: .JSON).responseJSON
{ request, response, data, error in
if(error != nil) {
println("Error: \(error)")
println("Request: \(request)")
println("Response: \(response)")
} else {
var jsonData = JSON(data!)
if !jsonData.isEmpty {
if jsonData["error"]["code"].stringValue == "user_not_found" {
result["error"] = "user_not_found"
} else {
if !jsonData["session_id"].isEmpty {
result["session_id"] = jsonData["session_id"].stringValue
} else {
result["error"] = jsonData["error"]["code"].stringValue
println("Параметр session_id пуст")
}
}
} else {
result["error"] = "data_is_empty"
println("Параметр data в ответе на запрос пуст")
}
}
completion_request(result: result)
}
}
private func process_error() -> [String: String] {
return ["error": "wrong_credentials"]
}
private func make_request_logout(completion_request: (result: Bool) -> Void) -> Void {
var result = false
Alamofire.request(.POST, "\(ServerPath)/v1/logout", headers: headers).responseJSON
{ request, response, data, error in
if(error != nil) {
println("Error: \(error)")
println("Request: \(request)")
println("Response: \(response)")
} else {
completion_request(result: true)
}
}
}
} | lgpl-3.0 | e6eb40e2a69788367f4568573fa15a86 | 37.813559 | 142 | 0.515833 | 5.048512 | false | false | false | false |
Farteen/ios-charts | Charts/Classes/Utils/ChartSelectionDetail.swift | 1 | 2054 | //
// ChartSelectionDetail.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class ChartSelectionDetail: NSObject
{
private var _value = Double(0)
private var _dataSetIndex = Int(0)
private var _dataSet: ChartDataSet!
public override init()
{
super.init();
}
public init(value: Double, dataSetIndex: Int, dataSet: ChartDataSet)
{
super.init();
_value = value;
_dataSetIndex = dataSetIndex;
_dataSet = dataSet;
}
public var value: Double
{
return _value;
}
public var dataSetIndex: Int
{
return _dataSetIndex;
}
public var dataSet: ChartDataSet?
{
return _dataSet;
}
// MARK: NSObject
public override func isEqual(object: AnyObject?) -> Bool
{
if (object === nil)
{
return false;
}
if (!object!.isKindOfClass(self.dynamicType))
{
return false;
}
if (object!.value != _value)
{
return false;
}
if (object!.dataSetIndex != _dataSetIndex)
{
return false;
}
if (object!.dataSet !== _dataSet)
{
return false;
}
return true;
}
}
public func ==(lhs: ChartSelectionDetail, rhs: ChartSelectionDetail) -> Bool
{
if (lhs === rhs)
{
return true;
}
if (!lhs.isKindOfClass(rhs.dynamicType))
{
return false;
}
if (lhs.value != rhs.value)
{
return false;
}
if (lhs.dataSetIndex != rhs.dataSetIndex)
{
return false;
}
if (lhs.dataSet !== rhs.dataSet)
{
return false;
}
return true;
} | apache-2.0 | 1d7076953512ad04a6d156c2f3b93504 | 17.185841 | 76 | 0.513632 | 4.544248 | false | false | false | false |
JackieQu/QP_DouYu | QP_DouYu/QP_DouYu/Classes/Home/Controller/AmuseViewController.swift | 1 | 1344 | //
// AmuseViewController.swift
// QP_DouYu
//
// Created by JackieQu on 2017/2/26.
// Copyright © 2017年 JackieQu. All rights reserved.
//
import UIKit
private let kMenuViewH : CGFloat = 200;
class AmuseViewController: BaseAnchorViewController {
// MARK:- 懒加载属性
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var menuView : AmuseMenuView = {
let menuView = AmuseMenuView.amuseMenuView()
menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH)
return menuView
}()
}
// MARK:- 设置 UI
extension AmuseViewController {
override func setupUI() {
super.setupUI()
collectionView.addSubview(menuView)
collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0)
}
}
// MARK:- 请求数据
extension AmuseViewController {
override func loadData() {
// 1.给父类中的 VM 赋值
baseVM = amuseVM
// 2.请求数据
amuseVM.loadAmuseData {
self.collectionView.reloadData()
var tempGroups = self.amuseVM.anchorGroups
tempGroups.removeFirst()
self.menuView.groups = tempGroups
self.loadDataFinished()
}
}
}
| mit | c6a204fc1520588daf859bd46887ad39 | 23.942308 | 97 | 0.619121 | 4.750916 | false | false | false | false |
lennet/proNotes | app/proNotes/Document/DocumentViewController.swift | 1 | 14967 | //
// DocumentViewController.swift
// Student
//
// Created by Leo Thomas on 28/11/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
class DocumentViewController: UIViewController {
@IBOutlet weak var settingsContainerRightConstraint: NSLayoutConstraint!
@IBOutlet weak var pagesOverViewLeftConstraint: NSLayoutConstraint!
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var pageInfoButton: UIBarButtonItem!
@IBOutlet weak var undoButton: UIBarButtonItem!
@IBOutlet weak var sketchButton: UIBarButtonItem!
@IBOutlet weak var fullScreenButton: UIBarButtonItem!
@IBOutlet weak var actionBarButtonItem: UIBarButtonItem!
@IBOutlet var bottomConstraints: [NSLayoutConstraint]!
weak var pagesOverviewController: PagesOverviewTableViewController?
weak var importDataNavigationController: UINavigationController?
var isFullScreen = false
var isSketchMode = false {
didSet {
if isSketchMode {
sketchButton.image = UIImage(named: "sketchIconActive")
} else {
sketchButton.image = UIImage(named: "sketchIcon")
}
}
}
var isLoadingData = false
var document: Document? {
get {
return DocumentInstance.sharedInstance.document
}
}
override func viewDidLoad() {
super.viewDidLoad()
setUpTitle()
pageInfoButton.setHidden(true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
registerNotifications()
updateUndoButton()
if UIDevice.current.userInterfaceIdiom == .phone {
setUpForIphone()
}
isLoadingData = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
titleTextField.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if !isLoadingData {
titleTextField.delegate = nil
DocumentInstance.sharedInstance.removeAllDelegates()
DocumentInstance.sharedInstance.save({ (_) in
self.document?.close(completionHandler: nil)
})
removeNotifications()
undoManager?.removeAllActions()
}
}
func setUpForIphone() {
titleTextField.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
DocumentInstance.sharedInstance.flushUndoManager()
ImageCache.sharedInstance.clearCache()
}
override var canBecomeFirstResponder: Bool {
return true
}
func setUpTitle() {
titleTextField.text = document?.name
titleTextField.sizeToFit()
}
private func registerNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(DocumentViewController.updateUndoButton), name: NSNotification.Name.NSUndoManagerWillUndoChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(DocumentViewController.updateUndoButton), name: NSNotification.Name.NSUndoManagerCheckpoint, object: nil)
}
private func removeNotifications() {
NotificationCenter.default.removeObserver(self)
}
private func toggleFullScreen(_ animated: Bool = true) {
if isFullScreen {
settingsContainerRightConstraint.constant = 0
pagesOverViewLeftConstraint.constant = 0
isFullScreen = false
SettingsViewController.sharedInstance?.view.alpha = 1
pagesOverviewController?.view.alpha = 1
fullScreenButton.image = UIImage(named: "fullscreenOn")
} else {
settingsContainerRightConstraint.constant = -SettingsViewController.sharedInstance!.view.bounds.width
pagesOverViewLeftConstraint.constant = -pagesOverviewController!.view.bounds.width
isFullScreen = true
fullScreenButton.image = UIImage(named: "fullscreenOff")
}
UIView.animate(withDuration: animated ? standardAnimationDuration : 0, delay: 0, options: UIViewAnimationOptions(), animations: {
self.view.layoutIfNeeded()
PagesTableViewController.sharedInstance?.setUpScrollView()
PagesTableViewController.sharedInstance?.layoutDidChange()
}, completion: { (_) in
if self.isFullScreen {
SettingsViewController.sharedInstance?.view.alpha = 0
self.pagesOverviewController?.view.alpha = 0
}
})
}
// MARK: - Actions
@IBAction func handleSketchButtonPressed(_ sender: UIBarButtonItem) {
isSketchMode = !isSketchMode
if isSketchMode {
PagesTableViewController.sharedInstance?.currentPageView?.handleSketchButtonPressed()
} else {
PagesTableViewController.sharedInstance?.currentPageView?.deselectSelectedSubview()
}
}
@IBAction func handlePageInfoButtonPressed(_ sender: AnyObject) {
PagesTableViewController.sharedInstance?.currentPageView?.deselectSelectedSubview()
SettingsViewController.sharedInstance?.currentType = .pageInfo
if isFullScreen {
toggleFullScreen()
}
}
@IBAction func handleFullscreenToggleButtonPressed(_ sender: UIBarButtonItem) {
toggleFullScreen()
}
@IBAction func handleUndoButtonPressed(_ sender: AnyObject) {
undoManager?.undo()
}
func updateUndoButton() {
undoButton.isEnabled = undoManager?.canUndo ?? false
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController = segue.destination as? PagesOverviewTableViewController {
viewController.pagesOverViewDelegate = self
pagesOverviewController = viewController
} else if let viewController = segue.destination as? PagesTableViewController {
PagesTableViewController.sharedInstance = viewController
} else if let viewController = segue.destination as? SettingsViewController {
viewController.delegate = self
} else if let navigationController = segue.destination as? UINavigationController {
if UIDevice.current.userInterfaceIdiom == .phone {
isLoadingData = true
}
if let viewController = navigationController.visibleViewController as? ImportExportBaseViewController {
viewController.delegate = self
}
if importDataNavigationController != nil {
dismiss()
}
importDataNavigationController = navigationController
}
}
@IBAction func unwind(_ sender: AnyObject) {
_ = navigationController?.popViewController(animated: true)
}
}
// MARK: - UITextfieldDelegate
extension DocumentViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.borderStyle = .roundedRect
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
guard let newName = textField.text else { return }
guard let fileUrl = document?.fileURL else { return }
document?.close(completionHandler: { [weak self](_) in
_ = RenameDocumentManager(oldURL: fileUrl, newName: newName, viewController: self, completion: { (success, url) in
let newURL = url ?? fileUrl
let newDocument = Document(fileURL: newURL)
newDocument.open(completionHandler: { (_) in
DocumentInstance.sharedInstance.document = newDocument
PagesTableViewController.sharedInstance?.tableView.reloadData()
self?.setUpTitle()
})
}).rename()
})
textField.borderStyle = .none
}
}
// MARK: - SettingsViewControllerDelegate
extension DocumentViewController: SettingsViewControllerDelegate {
func didChangeSettingsType(to newType: SettingsType) {
pageInfoButton.setHidden(newType == .pageInfo)
isSketchMode = newType == .sketch
}
}
// MARK: - ImportDataViewControllerDelegate
extension DocumentViewController: ImportExportDataViewControllerDelgate {
func addEmptyPage() {
document?.addEmptyPage()
dismiss()
}
func addTextField() {
dismiss()
if let textLayer = DocumentInstance.sharedInstance.currentPage?.addTextLayer("") {
if let currentPageView = PagesTableViewController.sharedInstance?.currentPageView {
currentPageView.addTextView(textLayer)
currentPageView.page = DocumentInstance.sharedInstance.currentPage
currentPageView.setLayerSelected(currentPageView.subviews.count - 1)
if let pageIndex = currentPageView.page?.index {
DocumentInstance.sharedInstance.didUpdatePage(pageIndex)
showPage(pageIndex)
}
}
}
}
func addPDF(_ url: URL) {
document?.addPDF(url)
dismiss()
}
func addImage(_ image: UIImage) {
if let imageLayer = DocumentInstance.sharedInstance.currentPage?.addImageLayer(image) {
if let currentPageView = PagesTableViewController.sharedInstance?.currentPageView {
currentPageView.addImageView(imageLayer)
currentPageView.page = DocumentInstance.sharedInstance.currentPage
currentPageView.setLayerSelected(currentPageView.subviews.count - 1)
if let pageIndex = currentPageView.page?.index {
DocumentInstance.sharedInstance.didUpdatePage(pageIndex)
showPage(pageIndex)
}
}
}
dismiss()
}
func addSketchLayer() {
PagesTableViewController.sharedInstance?.currentPageView?.addSketchLayer()
dismiss()
}
func exportAsPDF(_ data: Data) {
dismiss()
DocumentExporter.presentActivityViewController(self, barbuttonItem: actionBarButtonItem, items: [data])
}
func exportAsImages(_ images: [UIImage]) {
dismiss(false)
DocumentExporter.presentActivityViewController(self, barbuttonItem: actionBarButtonItem, items: images)
}
func exportAsProNote(_ url: URL) {
dismiss()
DocumentExporter.presentActivityViewController(self, barbuttonItem: actionBarButtonItem, items: [url])
}
func dismiss(_ animated: Bool = true) {
importDataNavigationController?.dismiss(animated: animated, completion: nil)
importDataNavigationController?.delegate = nil
importDataNavigationController = nil
}
}
// MARK: - PagesOverViewDelegate
extension DocumentViewController: PagesOverviewTableViewCellDelegate {
func showPage(_ index: Int) {
PagesTableViewController.sharedInstance?.showPage(index)
}
}
// MARK: - UIKeyCommands
extension DocumentViewController {
override var keyCommands: [UIKeyCommand]? {
var commands = [UIKeyCommand]()
if let settingsViewController = SettingsViewController.sharedInstance,
settingsViewController.currentType == .image{
commands.append(UIKeyCommand(input: UIKeyInputRightArrow, modifierFlags: .control, action: #selector(DocumentViewController.handleRotateImageKeyPressed(_:)), discoverabilityTitle: "Rotate Image Right"))
commands.append(UIKeyCommand(input: UIKeyInputLeftArrow, modifierFlags: .control, action: #selector(DocumentViewController.handleRotateImageKeyPressed(_:)), discoverabilityTitle: "Rotate Image Left"))
}
if PagesTableViewController.sharedInstance?.currentPageView?.selectedSubView is MovableView {
commands.append(UIKeyCommand(input: UIKeyInputRightArrow, modifierFlags: .command, action: #selector(DocumentViewController.handleMoveMovableViewKeyPressed(_:)), discoverabilityTitle: "Move Right"))
commands.append(UIKeyCommand(input: UIKeyInputLeftArrow, modifierFlags: .command, action: #selector(DocumentViewController.handleMoveMovableViewKeyPressed(_:)), discoverabilityTitle: "Move Left"))
commands.append(UIKeyCommand(input: UIKeyInputUpArrow, modifierFlags: .command, action: #selector(DocumentViewController.handleMoveMovableViewKeyPressed(_:)), discoverabilityTitle: "Move Up"))
commands.append(UIKeyCommand(input: UIKeyInputDownArrow, modifierFlags: .command, action: #selector(DocumentViewController.handleMoveMovableViewKeyPressed(_:)), discoverabilityTitle: "Move Down"))
} else {
commands.append(UIKeyCommand(input: UIKeyInputDownArrow, modifierFlags: [], action: #selector(DocumentViewController.handleDownKeyPressed(_:)), discoverabilityTitle: "Scroll Down"))
commands.append(UIKeyCommand(input: UIKeyInputUpArrow, modifierFlags: [], action: #selector(DocumentViewController.handleUpKeyPressed(_:)), discoverabilityTitle: "Scroll Up"))
}
return commands
}
func handleRotateImageKeyPressed(_ sender: UIKeyCommand) {
if let imageSettingsViewController = SettingsViewController.sharedInstance?.currentChildViewController as? ImageSettingsViewController {
imageSettingsViewController.rotateImage(sender.input == UIKeyInputRightArrow ? .right : .left)
}
}
func handleDownKeyPressed(_ sender: UIKeyCommand) {
PagesTableViewController.sharedInstance?.scroll(true)
}
func handleUpKeyPressed(_ sender: UIKeyCommand) {
PagesTableViewController.sharedInstance?.scroll(false)
}
func handleMoveMovableViewKeyPressed(_ sender: UIKeyCommand) {
guard let movableView = PagesTableViewController.sharedInstance?.currentPageView?.selectedSubView as? MovableView else {
return
}
let offSet = 10
var translation: CGPoint = .zero
switch sender.input {
case UIKeyInputRightArrow:
translation = CGPoint(x: offSet, y: 0)
break
case UIKeyInputLeftArrow:
translation = CGPoint(x: -offSet, y: 0)
break
case UIKeyInputDownArrow:
translation = CGPoint(x: 0, y: offSet)
break
case UIKeyInputUpArrow:
translation = CGPoint(x: 0, y: -offSet)
break
default:
break
}
movableView.selectedTouchControl = .center
movableView.handlePanTranslation(translation)
movableView.handlePanEnded()
}
}
| mit | de70244a6ad5a1f38915dabe2dba009a | 37.772021 | 214 | 0.668515 | 5.725325 | false | false | false | false |
ya7lelkom/swift-k | tests/apps/046-tibi.swift | 2 | 2078 | // this is from Tibi's message
// on 8th feb 2007777777
type file {}
//define the wavelet procedure
(file wavelets) waveletTransf (file waveletScript, int subjNo,
string trialType, file dataFiles) {
app {
cwtsmall @filename(waveletScript) subjNo trialType;
}
}
(file outputs[]) batchTrials ( string trialTypes[] ){
file waveletScript<single_file_mapper;
file="scripts/runTrialSubjectWavelet.R">;
//file dataFiles[]<simple_mapper; prefix="101_", suffix="-epochs.Rdata">;
foreach s,i in trialTypes {
//file output<simple_mapper;prefix=s,suffix="101.tgz">;
file dataFiles<simple_mapper; prefix="101_", suffix=s>;
outputs[i] = waveletTransf(waveletScript,101,s,dataFiles);
}
}
//string trialTypes[] = ["FB", "FC", "FI", "SB", "SC", "SI" ];
string trialTypes[] = [ "FB" ];
file allOutputs[];
file namedOutputs[]<fixed_array_mapper;
files="101-FBchannel10_cwt-results.Rdata, 101-FBchannel11_cwt-results.Rdata, 101-FBchannel12_cwt-results.Rdata, 101-FBchannel13_cwt-results.Rdata, 101-FBchannel14_cwt-results.Rdata, 101-FBchannel15_cwt-results.Rdata, 101-FBchannel16_cwt-results.Rdata, 101-FBchannel17_cwt-results.Rdata, 101-FBchannel18_cwt-results.Rdata, 101-FBchannel19_cwt-results.Rdata, 101-FBchannel1_cwt-results.Rdata, 101-FBchannel20_cwt-results.Rdata, 101-FBchannel21_cwt-results.Rdata, 101-FBchannel22_cwt-results.Rdata, 101-FBchannel23_cwt-results.Rdata, 101-FBchannel24_cwt-results.Rdata, 101-FBchannel25_cwt-results.Rdata, 101-FBchannel26_cwt-results.Rdata, 101-FBchannel27_cwt-results.Rdata, 101-FBchannel28_cwt-results.Rdata, 101-FBchannel2_cwt-results.Rdata, 101-FBchannel3_cwt-results.Rdata, 101-FBchannel4_cwt-results.Rdata, 101-FBchannel5_cwt-results.Rdata, 101-FBchannel6_cwt-results.Rdata, 101-FBchannel7_cwt-results.Rdata, 101-FBchannel8_cwt-results.Rdata, 101-FBchannel9_cwt-results.Rdata">;
//the MAIN program
//file waveletScript<single_file_mapper;
string file="scripts/runTrialSubjectWavelet.R";
//namedOutputs = waveletTransf(waveletScript, 101, "FB");
namedOutputs = batchTrials(trialTypes);
| apache-2.0 | 60e69fca097ab006ac1d6e1b52d20c55 | 52.282051 | 979 | 0.754572 | 2.882108 | false | false | false | false |
gardner-lab/syllable-detector-swift | SyllableDetector/Time.swift | 2 | 2419 | //
// Time.swift
// SyllableDetector
//
// Created by Nathan Perkins on 3/30/16.
// Copyright © 2016 Gardner Lab. All rights reserved.
//
import Foundation
import Darwin
class Time
{
private var timeStart: UInt64 = 0
private var timeStop: UInt64 = 0
private static var timeBase: Double?
private static var globalTimers = [String: Time]()
private static var globalStats = [String: [Double]]()
private static func getTimeBase() -> Double {
if let base = self.timeBase {
return base
}
var info = mach_timebase_info(numer: 0, denom: 0)
mach_timebase_info(&info)
// calculate base
let base = Double(info.numer) / Double(info.denom)
self.timeBase = base
return base
}
func start() {
timeStart = mach_absolute_time()
}
func stop() {
timeStop = mach_absolute_time()
}
var nanoseconds: Double {
return Double(timeStop - timeStart) * Time.getTimeBase()
}
static func startWithName(_ key: String) {
if let t = Time.globalTimers[key] {
t.start()
}
else {
let t = Time()
Time.globalTimers[key] = t
t.start()
}
}
static func stopWithName(_ key: String) -> Double {
if let t = Time.globalTimers[key] {
t.stop()
return t.nanoseconds
}
return -1.0
}
static func stopAndSaveWithName(_ key: String) {
if let t = Time.globalTimers[key] {
t.stop()
if nil == Time.globalStats[key] {
Time.globalStats[key] = [Double]()
}
Time.globalStats[key]!.append(t.nanoseconds)
}
}
static func saveWithName(_ key: String, andValue value: Double) {
if nil == Time.globalStats[key] {
Time.globalStats[key] = [Double]()
}
Time.globalStats[key]!.append(value)
}
static func stopAndPrintWithName(_ key: String) {
if let t = Time.globalTimers[key] {
t.stop()
print("\(key): \(t.nanoseconds)ns")
}
}
static func printAll() {
for (k, a) in Time.globalStats {
print("\(k):")
a.forEach { print("\($0)") }
}
}
}
| mit | 78121dfcc55ac126739be1a7ea94622c | 22.940594 | 69 | 0.51158 | 4.197917 | false | false | false | false |
Hansoncoder/SpriteDemo | SpriteKitDemo/SpriteKitDemo/HSGameScene.swift | 1 | 2032 | //
// HSGameScene.swift
// SpriteKitDemo
//
// Created by Hanson on 16/5/9.
// Copyright © 2016年 Hanson. All rights reserved.
//
import SpriteKit
class HSGameScene: SKScene {
var contentCreated: Bool?
override func didMoveToView(view: SKView) {
if let create = contentCreated where create { return }
backgroundColor = SKColor.blueColor()
scaleMode = .AspectFill
addChild(newHelloNode())
}
func newHelloNode() -> SKLabelNode {
let helloNode = SKLabelNode()
helloNode.name = "HelloNode"
helloNode.text = "Hello Scene"
helloNode.fontSize = 10
helloNode.position = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame))
return helloNode
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let helloNode = childNodeWithName("HelloNode") {
helloNode.name = nil
let moveUp = SKAction.moveByX(0, y: 100, duration: 0.5)
let zoom = SKAction.scaleTo(2.0, duration: 0.25)
let pause = SKAction.waitForDuration(0.5)
let fadeAway = SKAction.fadeInWithDuration(0.5)
let remove = SKAction.removeFromParent()
let moveSequence = SKAction.sequence([moveUp,zoom,pause,fadeAway,remove])
helloNode.runAction(moveSequence) { [unowned self] in
let spaceshipScene = SpaceshipScene(size: self.size)
// 转场动画
// let fade = SKTransition.fadeWithDuration(0.5) // 淡化
// let cross = SKTransition.crossFadeWithDuration(0.5) // 淡化
// let doors = SKTransition.doorwayWithDuration(0.5) // 开门
let flip = SKTransition.flipHorizontalWithDuration(0.5) // 翻转
self.view?.presentScene(spaceshipScene, transition: flip)
}
}
}
}
| apache-2.0 | 831910abdf2551646ac80f97b0ed152b | 31.868852 | 85 | 0.577057 | 4.641204 | false | false | false | false |
sinsoku/FizzBuzz | Example/Tests/Tests.swift | 1 | 1175 | // https://github.com/Quick/Quick
import Quick
import Nimble
import FizzBuzz
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | c971893b48646dffc8312dbd33e36817 | 22.38 | 63 | 0.362703 | 5.488263 | false | false | false | false |
NghiaTranUIT/Unofficial-Uber-macOS | UberGo/UberGo/UberButton.swift | 1 | 1073 | //
// UberButton.swift
// UberGo
//
// Created by Nghia Tran on 6/5/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import Cocoa
class UberButton: NSButton {
override func awakeFromNib() {
super.awakeFromNib()
// Common
self.initCommon()
}
func setTitleColor(_ color: NSColor, kern: Float? = nil) {
guard let font = font else {
return
}
// Paragraph
let style = NSMutableParagraphStyle()
style.alignment = self.alignment
// Attribute
var attributes = [NSForegroundColorAttributeName: color,
NSFontAttributeName: font,
NSParagraphStyleAttributeName: style] as [String: Any]
// Kern
if let kern = kern {
attributes[NSKernAttributeName] = kern
}
// Override
let attributedTitle = NSAttributedString(string: self.title, attributes: attributes)
self.attributedTitle = attributedTitle
}
fileprivate func initCommon() {
}
}
| mit | 10d4cf2f7daab83c5345f511ec2b4485 | 21.808511 | 92 | 0.583955 | 5.178744 | false | false | false | false |
hilen/TimedSilver | Sources/UIKit/UIControl+TSSound.swift | 2 | 2207 | //
// UIControl+TSSound.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 8/10/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
extension UIControl {
fileprivate struct AssociatedKeys {
static var ts_soundKey = "ts_soundKey"
}
/**
Add sound to UIControl
- parameter name: music name
- parameter controlEvent: controlEvent
*/
public func ts_addSoundName(_ name: String, forControlEvent controlEvent: UIControl.Event) {
let oldSoundKey: String = "\(controlEvent)"
let oldSound: AVAudioPlayer = self.ts_sounds[oldSoundKey]!
let selector = NSSelectorFromString("play")
self.removeTarget(oldSound, action: selector, for: controlEvent)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: "AVAudioSessionCategoryAmbient"))
// Find the sound file.
guard let soundFileURL = Bundle.main.url(forResource: name, withExtension: "") else {
assert(false, "File not exist")
return
}
let tapSound: AVAudioPlayer = try! AVAudioPlayer(contentsOf: soundFileURL)
let controlEventKey: String = "\(controlEvent)"
var sounds: [AnyHashable: Any] = self.ts_sounds
sounds[controlEventKey] = tapSound
tapSound.prepareToPlay()
self.addTarget(tapSound, action: selector, for: controlEvent)
}
catch _ {}
}
/// AssociatedObject for UIControl
var ts_sounds: Dictionary<String, AVAudioPlayer> {
get {
if let sounds = objc_getAssociatedObject(self, &AssociatedKeys.ts_soundKey) {
return sounds as! Dictionary<String, AVAudioPlayer>
}
var sounds = Dictionary() as Dictionary<String, AVAudioPlayer>
sounds = self.ts_sounds
return sounds
}
set { objc_setAssociatedObject(self, &AssociatedKeys.ts_soundKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)}
}
}
| mit | baf05240ece6e66e03878eadddd8d8b7 | 34.015873 | 142 | 0.626927 | 4.848352 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | ch08-Animation/Decoration/Decoration/DecorationViewController.swift | 1 | 1018 | //
// DecorationViewController.swift
// Decoration
//
// Created by wj on 15/10/9.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
class DecorationViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var layer = CALayer()
layer.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
layer.cornerRadius = 10
layer.backgroundColor = UIColor.red.cgColor
layer.borderColor = UIColor.blue.cgColor
layer.borderWidth = 5
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: 3, height: 3)
view.layer.addSublayer(layer)
layer = CALayer()
layer.frame = CGRect(x: 150, y: 150, width: 100, height: 100)
layer.cornerRadius = 10
layer.backgroundColor = UIColor.green.cgColor
layer.borderWidth = 5
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: 3, height: 3)
view.layer.addSublayer(layer)
}
}
| mit | 6e2fabf8a0d5b3b29298169d1077be02 | 28.852941 | 69 | 0.628571 | 4.142857 | false | false | false | false |
igroomgrim/swift101 | swift101/Day100_object_template_pattern.swift | 1 | 691 | //
// Day100_object_template_pattern.swift
// swift101
//
// Created by Anak Mirasing on 9/28/2558 BE.
// Copyright © 2558 iGROOMGRiM. All rights reserved.
//
import Foundation
class Book {
var name:String
var author:String
var year:Int
var pages:Int
var stock:Int
init(name:String, author:String, year:Int, pages:Int, stock:Int) {
self.name = name
self.author = author
self.year = year
self.pages = pages
self.stock = stock
}
var hasInStore:Bool {
get {
if (stock <= 0) {
return false
} else {
return true
}
}
}
} | mit | ed40b8012a44b576bce905255dab3303 | 18.742857 | 70 | 0.531884 | 3.791209 | false | false | false | false |
anhnc55/fantastic-swift-library | Example/Example/AppDelegate.swift | 1 | 3257 | //
// AppDelegate.swift
// Example
//
// Created by AnhNC on 6/2/16.
// Copyright © 2016 AnhNC. All rights reserved.
//
import UIKit
import Material
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let navigationController: AppNavigationController = AppNavigationController(rootViewController: RecipesViewController())
let menuController: AppMenuController = AppMenuController(rootViewController: navigationController)
menuController.edgesForExtendedLayout = .None
let bottomNavigationController: BottomNavigationController = BottomNavigationController()
bottomNavigationController.viewControllers = [menuController, VideoViewController(), PhotoViewController()]
bottomNavigationController.selectedIndex = 0
bottomNavigationController.tabBar.tintColor = MaterialColor.white
bottomNavigationController.tabBar.backgroundColor = MaterialColor.grey.darken4
let sideNavigationController: SideNavigationController = SideNavigationController(rootViewController: bottomNavigationController, leftViewController: AppLeftViewController())
sideNavigationController.statusBarStyle = .LightContent
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window!.rootViewController = sideNavigationController
window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 88def310659657ec06e5f0f1587b5d36 | 55.137931 | 285 | 0.757985 | 6.225621 | false | false | false | false |
swift365/CFBannerView | Example/CFBannerView/ViewController.swift | 1 | 1590 | //
// ViewController.swift
// CFBannerView
//
// Created by chengfei.heng on 01/07/2017.
// Copyright (c) 2017 chengfei.heng. All rights reserved.
//
import UIKit
import CFBannerView
import SDWebImage
class ViewController: UIViewController {
var banner:UIView!
let banners = ["http://pic.58pic.com/58pic/13/72/07/55Z58PICKka_1024.jpg",
"http://pic.qiantucdn.com/58pic/18/13/67/72w58PICshJ_1024.jpg",
"http://h.hiphotos.baidu.com/zhidao/pic/item/024f78f0f736afc396060dbbb119ebc4b64512e1.jpg"]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "轮播banner"
let banner = UIView(frame: CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: 170))
self.view.addSubview(banner)
var frame = banner.frame
frame.origin.y = 0
let bannerView = CFBannerView(frame:frame)
bannerView.dataSource = self
bannerView.delegate = self
bannerView.reloadData()
banner.addSubview(bannerView)
}
}
extension ViewController:CFBannerViewDataSource,CFBannerViewDelegate{
func numberOfItems() -> Int {
return banners.count
}
func viewForItem(bannerView: CFBannerView, index: Int) -> UIView {
let imageView = UIImageView(frame: bannerView.bounds)
imageView.sd_setImage(with: URL(string: banners[index]), placeholderImage: UIImage(named: "default"))
return imageView
}
func didSelectItem(index: Int) {
print(index)
}
}
| mit | 338467628d8a7f0e18e7380fba7d90fd | 27.321429 | 110 | 0.638714 | 3.896806 | false | false | false | false |
Appudo/Appudo.github.io | static/dashs/showcase/c/s/14/10.swift | 1 | 5323 | import libappudo
import libappudo_run
import libappudo_env
import libappudo_backend
import Foundation
struct BlogData : FastCodable {
let i : String?
let l : String?
let h : String?
let c : String?
let t : Int?
}
func main() -> Void {
if(Page.requestMethod == .POST) {
switch(Post.t.value) {
case "c": // list categories
doListCategories()
case "a": // add item
doAddItem()
case "d": // remove item
doRemoveItem()
case "m": // update item
doUpdateItem()
default:
break
}
}
printSub()
}
func checkLogin() -> Bool {
if let id = User.logon, let user = <!id.value, <!user.hasGroup(Role.admin) != false {
_ = User.swap(User.owner)
return true
}
return false
}
func pushUpdate() -> Void {
if var wsDev = <!Dir.dev1.open("websocket_push_server", [.O_APPUDO]) {
let ticket = Post.h.value
if let _ = <!wsDev.write("{\"t\":\"blog\",\"h\":\"\(ticket)\"}") {
}
} else {
}
if var wsDev = <!Dir.dev2.open("page_blog", [.O_APPUDO]) {
let ticket = Post.h.value
if let _ = <!wsDev.write("{\"t\":\"blog\",\"h\":\"\(ticket)\"}") {
}
} else {
}
}
func printCategories() -> Void {
let qry = SQLQry("SELECT id, label FROM categories")
if <!qry.exec() {
var first = true
print("{")
for i in 0..<qry.numRows {
let id = qry.get(i, 0).int ?? 0
let label = qry.get(i, 1).string ?? ""
if(!first) {
print(",")
} else {
first = false
}
print("\"\(label)\":\"\(id)\"")
}
print("}")
}
}
func doListCategories() -> Void {
RESULT_DATA();
RESULT_VALUE("", printer:printCategories)
RESULT(String(1))
OP_RESULT()
}
func doAddItem() -> Void {
let json = Post.d.value
var res = 0
if(checkLogin()) {
if let data = BlogData.from(json:json) {
if let label = data.l {
let type = data.t ?? 0
let qry = type == 0 ? SQLQry("INSERT INTO categories(label)VALUES($1) RETURNING id") :
SQLQry("INSERT INTO posts(date, text, head, users_id, categories_id)VALUES($1,$2,$3,$4,$5) RETURNING id")
if(type == 1) {
let user = User.logon!.rawValue
let time = Date().to1970
let txt = data.l ?? ""
let head = data.h ?? ""
let cat = data.c ?? ""
qry.values = [time, txt, head, user, cat]
} else {
qry.values = [label]
}
if <!qry.exec() != false {
R_DATA(String(qry.get(0, 0).int ?? 0))
res = 1
pushUpdate()
}
}
}
}
RESULT(String(res))
OP_RESULT()
}
func doRemoveItem() -> Void {
let json = Post.d.value
var res = 0
if(checkLogin()) {
if let data = BlogData.from(json:json) {
if let id = data.i {
let type = data.t ?? 0
let qry = type == 0 ? SQLQry("DELETE FROM categories WHERE id=$1") :
SQLQry("DELETE FROM posts WHERE id=$1")
qry.values = [id]
if <!qry.exec() != false {
res = 1
pushUpdate()
}
}
}
}
RESULT(String(res))
OP_RESULT()
}
func doUpdateItem() -> Void {
let json = Post.d.value
var res = 0
if(checkLogin()) {
if let data = BlogData.from(json:json) {
if let id = data.i {
let type = data.t ?? 0
let qry = type == 0 ? SQLQry("UPDATE categories SET label=$2 WHERE id=$1") :
SQLQry("UPDATE posts SET head=$2, text=$3, categories_id=$4 WHERE id=$1")
if(type == 0) {
let label = data.l ?? ""
qry.values = [id, label]
} else {
let txt = data.l ?? ""
let head = data.h ?? ""
let cat = data.c ?? ""
qry.values = [id, head, txt, cat]
}
if <!qry.exec() != false {
res = 1
pushUpdate()
}
}
}
}
RESULT(String(res))
OP_RESULT()
}
func OP_RESULT(_ out : Bool = true) -> Void {
if(out) {
printSub()
}
}
func RESULT(_ result : String) -> Void {
print(result)
}
func R_DATA(_ result : String) -> Void {
RESULT_BEFORE()
RESULT_AFTER()
RESULT_DATA()
RESULT_VALUE(result)
}
func RESULT_DATA(_ out : Bool = true) -> Void {
printSub()
}
func RESULT_VALUE(_ result : String, printer : (() -> Void)? = nil) -> Void {
if(printer != nil) {
printer!()
} else {
print(result)
}
}
func RESULT_BEFORE(_ out : Bool = true) -> Void {
printSub()
}
func RESULT_AFTER(_ out : Bool = true) -> Void {
printSub()
} | apache-2.0 | 2d4bbd8e8bcc98108a8dbf938fd9b283 | 25.753769 | 143 | 0.436408 | 3.871273 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01015-swift-inflightdiagnostic.swift | 1 | 967 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
var d {
func a() -> {
class A {
}
func a(f<h == d: T>()
let foo as String) {
protocol C {
func a<I : a {
var a(")(self)
}
protocol B : Sequence> Any, range.C> V {
struct c(a: T> U) {
}
class B {
var b: [c<T>?) {
}
}
case .C<B : b(b() {
case C("[Byte]()
struct B<T where B {
typealias b = Swift.init(array: a {
return b: P {
case b {
}
}
typealias F = c] {
}
class B : d = {
class A? {
print() -> {
func f<T> Int = [self[T : d {
}
class A {
struct Q<T> <T) {
}({
enum S(bytes: Hashable> (T: T] {
}
typealias b {
i> Any) {
class func b<1 {
i<T) -> [Any, let b {
return "
| apache-2.0 | d7740168257191a1231587ea66a81c2b | 18.34 | 79 | 0.620476 | 2.693593 | false | false | false | false |
gsapoz/Social-Streamliner | SStreamliner/SStreamliner/SimpleAuth/ResultType.swift | 1 | 9601 | // Copyright (c) 2015 Rob Rix. All rights reserved.
#if swift(>=3.0)
public typealias ResultErrorType = Error
#else
public typealias ResultErrorType = ErrorType
#endif
/// A type that can represent either failure with an error or success with a result value.
public protocol ResultType {
associatedtype Value
associatedtype Error: ResultErrorType
/// Constructs a successful result wrapping a `value`.
init(value: Value)
/// Constructs a failed result wrapping an `error`.
init(error: Error)
/// Case analysis for ResultType.
///
/// Returns the value produced by appliying `ifFailure` to the error if self represents a failure, or `ifSuccess` to the result value if self represents a success.
#if swift(>=3)
func analysis<U>(ifSuccess: @noescape (Value) -> U, ifFailure: @noescape (Error) -> U) -> U
#else
func analysis<U>(@noescape ifSuccess ifSuccess: Value -> U, @noescape ifFailure: Error -> U) -> U
#endif
/// Returns the value if self represents a success, `nil` otherwise.
///
/// A default implementation is provided by a protocol extension. Conforming types may specialize it.
var value: Value? { get }
/// Returns the error if self represents a failure, `nil` otherwise.
///
/// A default implementation is provided by a protocol extension. Conforming types may specialize it.
var error: Error? { get }
}
public extension ResultType {
/// Returns the value if self represents a success, `nil` otherwise.
public var value: Value? {
return analysis(ifSuccess: { $0 }, ifFailure: { _ in nil })
}
/// Returns the error if self represents a failure, `nil` otherwise.
public var error: Error? {
return analysis(ifSuccess: { _ in nil }, ifFailure: { $0 })
}
/// Returns a new Result by mapping `Success`es’ values using `transform`, or re-wrapping `Failure`s’ errors.
#if swift(>=3)
@warn_unused_result
public func map<U>(_ transform: @noescape (Value) -> U) -> Result<U, Error> {
return flatMap { .Success(transform($0)) }
}
#else
@warn_unused_result
public func map<U>(@noescape transform: Value -> U) -> Result<U, Error> {
return flatMap { .Success(transform($0)) }
}
#endif
/// Returns the result of applying `transform` to `Success`es’ values, or re-wrapping `Failure`’s errors.
#if swift(>=3)
@warn_unused_result
public func flatMap<U>(_ transform: @noescape (Value) -> Result<U, Error>) -> Result<U, Error> {
return analysis(
ifSuccess: transform,
ifFailure: Result<U, Error>.Failure)
}
#else
@warn_unused_result
public func flatMap<U>(@noescape transform: Value -> Result<U, Error>) -> Result<U, Error> {
return analysis(
ifSuccess: transform,
ifFailure: Result<U, Error>.Failure)
}
#endif
/// Returns a new Result by mapping `Failure`'s values using `transform`, or re-wrapping `Success`es’ values.
#if swift(>=3)
@warn_unused_result
public func mapError<Error2>(_ transform: @noescape (Error) -> Error2) -> Result<Value, Error2> {
return flatMapError { .Failure(transform($0)) }
}
#else
@warn_unused_result
public func mapError<Error2>(@noescape transform: Error -> Error2) -> Result<Value, Error2> {
return flatMapError { .Failure(transform($0)) }
}
#endif
/// Returns the result of applying `transform` to `Failure`’s errors, or re-wrapping `Success`es’ values.
#if swift(>=3)
@warn_unused_result
public func flatMapError<Error2>(_ transform: @noescape (Error) -> Result<Value, Error2>) -> Result<Value, Error2> {
return analysis(
ifSuccess: Result<Value, Error2>.Success,
ifFailure: transform)
}
#else
@warn_unused_result
public func flatMapError<Error2>(@noescape transform: Error -> Result<Value, Error2>) -> Result<Value, Error2> {
return analysis(
ifSuccess: Result<Value, Error2>.Success,
ifFailure: transform)
}
#endif
}
public extension ResultType {
// MARK: Higher-order functions
/// Returns `self.value` if this result is a .Success, or the given value otherwise. Equivalent with `??`
#if swift(>=3)
public func recover(_ value: @autoclosure () -> Value) -> Value {
return self.value ?? value()
}
#else
public func recover(@autoclosure value: () -> Value) -> Value {
return self.value ?? value()
}
#endif
/// Returns this result if it is a .Success, or the given result otherwise. Equivalent with `??`
#if swift(>=3)
public func recoverWith(_ result: @autoclosure () -> Self) -> Self {
return analysis(
ifSuccess: { _ in self },
ifFailure: { _ in result() })
}
#else
public func recoverWith(@autoclosure result: () -> Self) -> Self {
return analysis(
ifSuccess: { _ in self },
ifFailure: { _ in result() })
}
#endif
}
/// Protocol used to constrain `tryMap` to `Result`s with compatible `Error`s.
public protocol ErrorTypeConvertible: ResultErrorType {
#if swift(>=3)
static func errorFromErrorType(_ error: ResultErrorType) -> Self
#else
static func errorFromErrorType(error: ResultErrorType) -> Self
#endif
}
public extension ResultType where Error: ErrorTypeConvertible {
/// Returns the result of applying `transform` to `Success`es’ values, or wrapping thrown errors.
#if swift(>=3)
@warn_unused_result
public func tryMap<U>(_ transform: @noescape (Value) throws -> U) -> Result<U, Error> {
return flatMap { value in
do {
return .Success(try transform(value))
}
catch {
let convertedError = Error.errorFromErrorType(error)
// Revisit this in a future version of Swift. https://twitter.com/jckarter/status/672931114944696321
return .Failure(convertedError)
}
}
}
#else
@warn_unused_result
public func tryMap<U>(@noescape transform: Value throws -> U) -> Result<U, Error> {
return flatMap { value in
do {
return .Success(try transform(value))
}
catch {
let convertedError = Error.errorFromErrorType(error)
// Revisit this in a future version of Swift. https://twitter.com/jckarter/status/672931114944696321
return .Failure(convertedError)
}
}
}
#endif
}
// MARK: - Operators
infix operator &&& {
/// Same associativity as &&.
associativity left
/// Same precedence as &&.
precedence 120
}
/// Returns a Result with a tuple of `left` and `right` values if both are `Success`es, or re-wrapping the error of the earlier `Failure`.
#if swift(>=3)
public func &&& <L: ResultType, R: ResultType where L.Error == R.Error> (left: L, right: @autoclosure () -> R) -> Result<(L.Value, R.Value), L.Error> {
return left.flatMap { left in right().map { right in (left, right) } }
}
#else
public func &&& <L: ResultType, R: ResultType where L.Error == R.Error> (left: L, @autoclosure right: () -> R) -> Result<(L.Value, R.Value), L.Error> {
return left.flatMap { left in right().map { right in (left, right) } }
}
#endif
infix operator >>- {
// Left-associativity so that chaining works like you’d expect, and for consistency with Haskell, Runes, swiftz, etc.
associativity left
// Higher precedence than function application, but lower than function composition.
precedence 100
}
/// Returns the result of applying `transform` to `Success`es’ values, or re-wrapping `Failure`’s errors.
///
/// This is a synonym for `flatMap`.
#if swift(>=3)
public func >>- <T: ResultType, U> (result: T, transform: @noescape (T.Value) -> Result<U, T.Error>) -> Result<U, T.Error> {
return result.flatMap(transform)
}
#else
public func >>- <T: ResultType, U> (result: T, @noescape transform: T.Value -> Result<U, T.Error>) -> Result<U, T.Error> {
return result.flatMap(transform)
}
#endif
/// Returns `true` if `left` and `right` are both `Success`es and their values are equal, or if `left` and `right` are both `Failure`s and their errors are equal.
public func == <T: ResultType where T.Value: Equatable, T.Error: Equatable> (left: T, right: T) -> Bool {
if let left = left.value, let right = right.value {
return left == right
} else if let left = left.error, let right = right.error {
return left == right
}
return false
}
/// Returns `true` if `left` and `right` represent different cases, or if they represent the same case but different values.
public func != <T: ResultType where T.Value: Equatable, T.Error: Equatable> (left: T, right: T) -> Bool {
return !(left == right)
}
/// Returns the value of `left` if it is a `Success`, or `right` otherwise. Short-circuits.
#if swift(>=3)
public func ?? <T: ResultType> (left: T, right: @autoclosure () -> T.Value) -> T.Value {
return left.recover(right())
}
#else
public func ?? <T: ResultType> (left: T, @autoclosure right: () -> T.Value) -> T.Value {
return left.recover(right())
}
#endif
/// Returns `left` if it is a `Success`es, or `right` otherwise. Short-circuits.
#if swift(>=3)
public func ?? <T: ResultType> (left: T, right: @autoclosure () -> T) -> T {
return left.recoverWith(right())
}
#else
public func ?? <T: ResultType> (left: T, @autoclosure right: () -> T) -> T {
return left.recoverWith(right())
}
#endif
| apache-2.0 | dd73fcea5005158db76c10aa80f1b275 | 35.284091 | 167 | 0.635453 | 3.911392 | false | false | false | false |
frootloops/swift | test/attr/attr_noescape.swift | 1 | 18625 | // RUN: %target-typecheck-verify-swift
@noescape var fn : () -> Int = { 4 } // expected-error {{attribute can only be applied to types, not declarations}}
func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{@escaping conflicts with @noescape}}
// expected-warning@-1{{@noescape is the default and is deprecated}} {{29-39=}}
func doesEscape(_ fn : @escaping () -> Int) {}
func takesGenericClosure<T>(_ a : Int, _ fn : @noescape () -> T) {} // expected-warning{{@noescape is the default and is deprecated}} {{47-57=}}
func takesNoEscapeClosure(_ fn : () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-2{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-3{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-4{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
takesNoEscapeClosure { 4 } // ok
_ = fn() // ok
var x = fn // expected-error {{non-escaping parameter 'fn' may only be called}}
// This is ok, because the closure itself is noescape.
takesNoEscapeClosure { fn() }
// This is not ok, because it escapes the 'fn' closure.
doesEscape { fn() } // expected-error {{closure use of non-escaping parameter 'fn' may allow it to escape}}
// This is not ok, because it escapes the 'fn' closure.
func nested_function() {
_ = fn() // expected-error {{declaration closing over non-escaping parameter 'fn' may allow it to escape}}
}
takesNoEscapeClosure(fn) // ok
doesEscape(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
takesGenericClosure(4, fn) // ok
takesGenericClosure(4) { fn() } // ok.
}
class SomeClass {
final var x = 42
func test() {
// This should require "self."
doesEscape { x } // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
// Since 'takesNoEscapeClosure' doesn't escape its closure, it doesn't
// require "self." qualification of member references.
takesNoEscapeClosure { x }
}
@discardableResult
func foo() -> Int {
foo()
func plain() { foo() }
let plain2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
func multi() -> Int { foo(); return 0 }
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{31-31=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
takesNoEscapeClosure { foo() } // okay
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
takesNoEscapeClosure { foo(); return 0 } // okay
func outer() {
func inner() { foo() }
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 }
let _: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{28-28=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() }
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 }
}
let outer2: () -> Void = {
func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}}
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
}
doesEscape {
func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}}
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
return 0
}
takesNoEscapeClosure {
func inner() { foo() }
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 }
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // okay
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // okay
return 0
}
struct Outer {
@discardableResult
func bar() -> Int {
bar()
func plain() { bar() }
let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
func multi() -> Int { bar(); return 0 }
let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
takesNoEscapeClosure { bar() } // okay
doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
takesNoEscapeClosure { bar(); return 0 } // okay
return 0
}
}
func structOuter() {
struct Inner {
@discardableResult
func bar() -> Int {
bar() // no-warning
func plain() { bar() }
let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{26-26=self.}}
func multi() -> Int { bar(); return 0 }
let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{32-32=self.}}
doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
takesNoEscapeClosure { bar() } // okay
doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
takesNoEscapeClosure { bar(); return 0 } // okay
return 0
}
}
}
return 0
}
}
// Implicit conversions (in this case to @convention(block)) are ok.
@_silgen_name("whatever")
func takeNoEscapeAsObjCBlock(_: @noescape @convention(block) () -> Void) // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}}
func takeNoEscapeTest2(_ fn : @noescape () -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{31-41=}}
takeNoEscapeAsObjCBlock(fn)
}
// Autoclosure implies noescape, but produce nice diagnostics so people know
// why noescape problems happen.
func testAutoclosure(_ a : @autoclosure () -> Int) { // expected-note{{parameter 'a' is implicitly non-escaping}}
doesEscape { a() } // expected-error {{closure use of non-escaping parameter 'a' may allow it to escape}}
}
// <rdar://problem/19470858> QoI: @autoclosure implies @noescape, so you shouldn't be allowed to specify both
func redundant(_ fn : @noescape // expected-error @+1 {{@noescape is implied by @autoclosure and should not be redundantly specified}}
@autoclosure () -> Int) {
// expected-warning@-2{{@noescape is the default and is deprecated}} {{23-33=}}
}
protocol P1 {
associatedtype Element
}
protocol P2 : P1 {
associatedtype Element
}
func overloadedEach<O: P1, T>(_ source: O, _ transform: @escaping (O.Element) -> (), _: T) {}
func overloadedEach<P: P2, T>(_ source: P, _ transform: @escaping (P.Element) -> (), _: T) {}
struct S : P2 {
typealias Element = Int
func each(_ transform: @noescape (Int) -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{26-36=}}
overloadedEach(self, // expected-error {{cannot invoke 'overloadedEach' with an argument list of type '(S, (Int) -> (), Int)'}}
transform, 1)
// expected-note @-2 {{overloads for 'overloadedEach' exist with these partially matching parameter lists: (O, @escaping (O.Element) -> (), T), (P, @escaping (P.Element) -> (), T)}}
}
}
// rdar://19763676 - False positive in @noescape analysis triggered by parameter label
func r19763676Callee(_ f: @noescape (_ param: Int) -> Int) {} // expected-warning{{@noescape is the default and is deprecated}} {{27-37=}}
func r19763676Caller(_ g: @noescape (Int) -> Int) { // expected-warning{{@noescape is the default and is deprecated}} {{27-37=}}
r19763676Callee({ _ in g(1) })
}
// <rdar://problem/19763732> False positive in @noescape analysis triggered by default arguments
func calleeWithDefaultParameters(_ f: @noescape () -> (), x : Int = 1) {} // expected-warning{{@noescape is the default and is deprecated}} {{39-49=}}
func callerOfDefaultParams(_ g: @noescape () -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}}
calleeWithDefaultParameters(g)
}
// <rdar://problem/19773562> Closures executed immediately { like this }() are not automatically @noescape
class NoEscapeImmediatelyApplied {
func f() {
// Shouldn't require "self.", the closure is obviously @noescape.
_ = { return ivar }()
}
final var ivar = 42
}
// Reduced example from XCTest overlay, involves a TupleShuffleExpr
public func XCTAssertTrue(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void {
}
public func XCTAssert(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void {
XCTAssertTrue(expression, message, file: file, line: line);
}
/// SR-770 - Currying and `noescape`/`rethrows` don't work together anymore
func curriedFlatMap<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-warning{{@noescape is the default and is deprecated}} {{41-50=}}
return { f in
x.flatMap(f)
}
}
func curriedFlatMap2<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-warning{{@noescape is the default and is deprecated}} {{42-51=}}
return { (f : @noescape (A) -> [B]) in // expected-warning{{@noescape is the default and is deprecated}} {{17-27=}}
x.flatMap(f)
}
}
func bad(_ a : @escaping (Int)-> Int) -> Int { return 42 }
func escapeNoEscapeResult(_ x: [Int]) -> (@noescape (Int) -> Int) -> Int { // expected-warning{{@noescape is the default and is deprecated}} {{43-52=}}
return { f in // expected-note{{parameter 'f' is implicitly non-escaping}}
bad(f) // expected-error {{passing non-escaping parameter 'f' to function expecting an @escaping closure}}
}
}
// SR-824 - @noescape for Type Aliased Closures
//
// Old syntax -- @noescape is the default, and is redundant
typealias CompletionHandlerNE = @noescape (_ success: Bool) -> () // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}}
// Explicit @escaping is not allowed here
typealias CompletionHandlerE = @escaping (_ success: Bool) -> () // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-42=}}
// No @escaping -- it's implicit from context
typealias CompletionHandler = (_ success: Bool) -> ()
var escape : CompletionHandlerNE
var escapeOther : CompletionHandler
func doThing1(_ completion: (_ success: Bool) -> ()) {
// expected-note@-1{{parameter 'completion' is implicitly non-escaping}}
// expected-error @+2 {{non-escaping value 'escape' may only be called}}
// expected-error @+1 {{non-escaping parameter 'completion' may only be called}}
escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}}
}
func doThing2(_ completion: CompletionHandlerNE) {
// expected-note@-1{{parameter 'completion' is implicitly non-escaping}}
// expected-error @+2 {{non-escaping value 'escape' may only be called}}
// expected-error @+1 {{non-escaping parameter 'completion' may only be called}}
escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}}
}
func doThing3(_ completion: CompletionHandler) {
// expected-note@-1{{parameter 'completion' is implicitly non-escaping}}
// expected-error @+2 {{non-escaping value 'escape' may only be called}}
// expected-error @+1 {{non-escaping parameter 'completion' may only be called}}
escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}}
}
func doThing4(_ completion: @escaping CompletionHandler) {
escapeOther = completion
}
// <rdar://problem/19997680> @noescape doesn't work on parameters of function type
func apply<T, U>(_ f: @noescape (T) -> U, g: @noescape (@noescape (T) -> U) -> U) -> U {
// expected-warning@-1{{@noescape is the default and is deprecated}} {{23-33=}}
// expected-warning@-2{{@noescape is the default and is deprecated}} {{46-56=}}
// expected-warning@-3{{@noescape is the default and is deprecated}} {{57-66=}}
return g(f)
// expected-warning@-1{{passing a non-escaping function parameter 'f' to a call to a non-escaping function parameter}}
}
// <rdar://problem/19997577> @noescape cannot be applied to locals, leading to duplication of code
enum r19997577Type {
case Unit
case Function(() -> r19997577Type, () -> r19997577Type)
case Sum(() -> r19997577Type, () -> r19997577Type)
func reduce<Result>(_ initial: Result, _ combine: @noescape (Result, r19997577Type) -> Result) -> Result { // expected-warning{{@noescape is the default and is deprecated}} {{53-63=}}
let binary: @noescape (r19997577Type, r19997577Type) -> Result = { combine(combine(combine(initial, self), $0), $1) } // expected-warning{{@noescape is the default and is deprecated}} {{17-27=}}
switch self {
case .Unit:
return combine(initial, self)
case let .Function(t1, t2):
return binary(t1(), t2())
case let .Sum(t1, t2):
return binary(t1(), t2())
}
}
}
// type attribute and decl attribute
func noescapeD(@noescape f: @escaping () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}}
func noescapeT(f: @noescape () -> Bool) {} // expected-warning{{@noescape is the default and is deprecated}} {{19-29=}}
func noescapeG<T>(@noescape f: () -> T) {} // expected-error{{attribute can only be applied to types, not declarations}}
func autoclosureD(@autoclosure f: () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}}
func autoclosureT(f: @autoclosure () -> Bool) {} // ok
func autoclosureG<T>(@autoclosure f: () -> T) {} // expected-error{{attribute can only be applied to types, not declarations}}
func noescapeD_noescapeT(@noescape f: @noescape () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}}
// expected-warning@-1{{@noescape is the default and is deprecated}} {{39-49=}}
func autoclosureD_noescapeT(@autoclosure f: @noescape () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}}
// expected-warning@-1{{@noescape is the default and is deprecated}} {{45-55=}}
| apache-2.0 | df9a6b514ae363c17befc7b5a1265ca5 | 53.300292 | 198 | 0.659705 | 4.027027 | false | false | false | false |
mmsaddam/TheMovie | TheMovie/MovieView.swift | 1 | 1841 | //
// MovieView.swift
// TheMovie
//
// Created by Md. Muzahidul Islam on 7/16/16.
// Copyright © 2016 iMuzahid. All rights reserved.
//
import UIKit
class MovieView: UIView {
private var coverImage: UIImageView!
private var indicator: UIActivityIndicatorView!
private var myContext = 0
var id: Int?
init(frame: CGRect, albumCover: String) {
super.init(frame: frame)
commonInit()
NSNotificationCenter.defaultCenter().postNotificationName("BLDownloadImageNotification", object: self, userInfo: ["imageView":coverImage, "coverUrl" : albumCover])
}
func commonInit() {
backgroundColor = UIColor.blackColor()
coverImage = UIImageView(frame: CGRectMake(5, 5, frame.size.width - 10, frame.size.height - 10))
addSubview(coverImage)
coverImage.addObserver(self, forKeyPath: "image", options: .New, context: &myContext)
coverImage.userInteractionEnabled = true
indicator = UIActivityIndicatorView()
indicator.center = self.center
indicator.activityIndicatorViewStyle = .WhiteLarge
indicator.startAnimating()
addSubview(indicator)
}
// stop indicator when finish download
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "image" {
indicator.stopAnimating()
}
}
// remove observer when deallocate the view
deinit {
coverImage.removeObserver(self, forKeyPath: "image")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit | 130c80750c8141f437220623ce8aca1d | 26.058824 | 167 | 0.694565 | 4.611529 | false | false | false | false |
Higgcz/Buildasaur | BuildaKit/XcodeProjectParser.swift | 1 | 6850 | //
// XcodeProjectParser.swift
// Buildasaur
//
// Created by Honza Dvorsky on 24/01/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import BuildaUtils
public class XcodeProjectParser {
static private var sourceControlFileParsers: [SourceControlFileParser] = [
CheckoutFileParser(),
BlueprintFileParser()
]
private class func firstItemMatchingTestRecursive(url: NSURL, test: (itemUrl: NSURL) -> Bool) throws -> NSURL? {
let fm = NSFileManager.defaultManager()
if let path = url.path {
var isDir: ObjCBool = false
let exists = fm.fileExistsAtPath(path, isDirectory: &isDir)
if !exists {
return nil
}
if !isDir {
//not dir, test
return test(itemUrl: url) ? url : nil
}
let contents = try fm.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
for i in contents {
if let foundUrl = try self.firstItemMatchingTestRecursive(i, test: test) {
return foundUrl
}
}
}
return nil
}
private class func firstItemMatchingTest(url: NSURL, test: (itemUrl: NSURL) -> Bool) throws -> NSURL? {
return try self.allItemsMatchingTest(url, test: test).first
}
private class func allItemsMatchingTest(url: NSURL, test: (itemUrl: NSURL) -> Bool) throws -> [NSURL] {
let fm = NSFileManager.defaultManager()
let contents = try fm.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
let filtered = contents.filter(test)
return filtered
}
private class func findCheckoutOrBlueprintUrl(projectOrWorkspaceUrl: NSURL) throws -> NSURL {
if let found = try self.firstItemMatchingTestRecursive(projectOrWorkspaceUrl, test: { (itemUrl: NSURL) -> Bool in
let pathExtension = itemUrl.pathExtension
return pathExtension == "xccheckout" || pathExtension == "xcscmblueprint"
}) {
return found
}
throw Error.withInfo("No xccheckout or xcscmblueprint file found")
}
private class func parseCheckoutOrBlueprintFile(url: NSURL) throws -> WorkspaceMetadata {
let pathExtension = url.pathExtension!
let maybeParser = self.sourceControlFileParsers.filter {
Set($0.supportedFileExtensions()).contains(pathExtension)
}.first
guard let parser = maybeParser else {
throw Error.withInfo("Could not find a parser for path extension \(pathExtension)")
}
let parsedWorkspace = try parser.parseFileAtUrl(url)
return parsedWorkspace
}
public class func parseRepoMetadataFromProjectOrWorkspaceURL(url: NSURL) throws -> WorkspaceMetadata {
do {
let checkoutUrl = try self.findCheckoutOrBlueprintUrl(url)
let parsed = try self.parseCheckoutOrBlueprintFile(checkoutUrl)
return parsed
} catch {
throw Error.withInfo("Cannot find the Checkout/Blueprint file, please make sure to open this project in Xcode at least once (it will generate the required Checkout/Blueprint file) and create at least one Bot from Xcode. Then please try again. Create an issue on GitHub is this issue persists. (Error \((error as NSError).localizedDescription))")
}
}
public class func sharedSchemesFromProjectOrWorkspaceUrl(url: NSURL) -> [XcodeScheme] {
var projectUrls: [NSURL]
if self.isWorkspaceUrl(url) {
//first parse project urls from workspace contents
projectUrls = self.projectUrlsFromWorkspace(url) ?? [NSURL]()
//also add the workspace's url, it might own some schemes as well
projectUrls.append(url)
} else {
//this already is a project url, take just that
projectUrls = [url]
}
//we have the project urls, now let's parse schemes from each of them
let schemes = projectUrls.map {
return self.sharedSchemeUrlsFromProjectUrl($0)
}.reduce([XcodeScheme](), combine: { (arr, newSchemes) -> [XcodeScheme] in
return arr + newSchemes
})
return schemes
}
private class func sharedSchemeUrlsFromProjectUrl(url: NSURL) -> [XcodeScheme] {
//the structure is
//in a project file, if there are any shared schemes, they will be in
//xcshareddata/xcschemes/*
do {
if let sharedDataFolder = try self.firstItemMatchingTest(url,
test: { (itemUrl: NSURL) -> Bool in
return itemUrl.lastPathComponent == "xcshareddata"
}) {
if let schemesFolder = try self.firstItemMatchingTest(sharedDataFolder,
test: { (itemUrl: NSURL) -> Bool in
return itemUrl.lastPathComponent == "xcschemes"
}) {
//we have the right folder, yay! just filter all files ending with xcscheme
let schemeUrls = try self.allItemsMatchingTest(schemesFolder, test: { (itemUrl: NSURL) -> Bool in
let ext = itemUrl.pathExtension ?? ""
return ext == "xcscheme"
})
let schemes = schemeUrls.map { XcodeScheme(path: $0, ownerProjectOrWorkspace: url) }
return schemes
}
}
} catch {
Log.error(error)
}
return []
}
private class func isProjectUrl(url: NSURL) -> Bool {
return url.absoluteString.hasSuffix(".xcodeproj")
}
private class func isWorkspaceUrl(url: NSURL) -> Bool {
return url.absoluteString.hasSuffix(".xcworkspace")
}
private class func projectUrlsFromWorkspace(url: NSURL) -> [NSURL]? {
assert(self.isWorkspaceUrl(url), "Url \(url) is not a workspace url")
do {
let urls = try XcodeProjectXMLParser.parseProjectsInsideOfWorkspace(url)
return urls
} catch {
Log.error("Couldn't load workspace at path \(url) with error \(error)")
return nil
}
}
private class func parseSharedSchemesFromProjectURL(url: NSURL) -> (schemeUrls: [NSURL]?, error: NSError?) {
return (schemeUrls: [NSURL](), error: nil)
}
}
| mit | cdd062af411400da26b8b7387d5ab92e | 36.637363 | 357 | 0.587007 | 5.181543 | false | true | false | false |
BlackSourceLabs/BlackNectar-iOS | BlackNectar/BlackNectar/AppDelegate.swift | 1 | 4156 | //
// AppDelegate.swift
// BlackNectar
//
// Created by Cordero Hernandez on 11/19/16.
// Copyright © 2017 BlackSource. All rights reserved.
//
import Archeota
import AromaSwiftClient
import Crashlytics
import Fabric
import Kingfisher
import NVActivityIndicatorView
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
static internal let buildNumber: String = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as? String ?? ""
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Fabric.with([Crashlytics.self, Answers.self])
self.logUser()
LOG.level = .debug
LOG.enable()
AromaClient.TOKEN_ID = "34576d0b-6060-4666-9ac1-f5a09be219c3"
AromaClient.beginMessage(withTitle: "App Launched")
.addBody("Build #\(AppDelegate.buildNumber)")
.withPriority(.low)
.send()
NSSetUncaughtExceptionHandler() { error in
AromaClient.beginMessage(withTitle: "App Crashed")
.addBody("On Device: \(UIDevice.current.name)")
.addLine(2)
.addBody("\(error)")
.withPriority(.high)
.send()
LOG.error("Uncaught Exception: \(error)")
}
ImageCache.default.maxDiskCacheSize = UInt(150.mb)
ImageCache.default.maxCachePeriodInSecond = (3.0).days
NVActivityIndicatorView.DEFAULT_TYPE = .ballClipRotatePulse
return true
}
func logUser() {
Crashlytics.sharedInstance().setUserIdentifier(UIDevice.current.name)
}
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.
AromaClient.sendLowPriorityMessage(withTitle: "App Entered Background")
ImageCache.default.clearMemoryCache()
ImageCache.default.cleanExpiredDiskCache()
}
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:.
AromaClient.sendMediumPriorityMessage(withTitle: "App Terminated")
}
func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
AromaClient.beginMessage(withTitle: "Memory Warning")
.withPriority(.medium)
.addBody("Build #\(AppDelegate.buildNumber)")
.send()
ImageCache.default.clearMemoryCache()
}
}
| apache-2.0 | e29619e8a1527fa7d049eeaa7bcf0558 | 37.472222 | 285 | 0.671961 | 5.554813 | false | false | false | false |
SuperW116/SwiftyTaiwan | SwiftyTaiwan/SpecialLetter.swift | 1 | 5527 | //
// SpecialLetter.swift
// SwiftyTaiwan
//
// Created by 劉士維 on 2016/11/22.
// Copyright © 2016年 LPB. All rights reserved.
//
import UIKit
func getLogString(with text:String) -> NSAttributedString {
let attributedStr = NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName:UIColor.white])
return attributedStr
}
func getProcessedString(with text:String) -> NSAttributedString {
var attributedStr = NSAttributedString()
let textArray = getProcessedStringArray(with:text)
attributedStr = processString(with: textArray)
return attributedStr
}
func processString(with textArray:[String]) -> NSAttributedString {
var attributedStr = NSAttributedString()
textArray.forEach { (text) in
if text == "let" || text == "func" || text == "var" || text == "if" || text == "return" || text == "nil" {
attributedStr = attributedStr + Word.getSpecial(of: text)
} else if text.contains("\"") {
attributedStr = attributedStr + Word.getQuotedString(of: text)
} else if text == "print" {
attributedStr = attributedStr + Word.getPrint()
} else if text == "Run" {
attributedStr = attributedStr + Word.getRun()
}
else {
attributedStr = attributedStr + Word.getBlack(of: text)
}
}
return attributedStr
}
func getInstructionString(with text:String) -> NSAttributedString {
var attributedStr = NSAttributedString()
let textArray = getProcessedStringArray(with:text)
attributedStr = processInstructionString(with: textArray)
return attributedStr
}
func processInstructionString(with textArray:[String]) -> NSAttributedString {
var attributedStr = NSAttributedString()
textArray.forEach { (text) in
if text == "let" || text == "func" || text == "var" || text == "if" || text == "return" || text == "nil" {
attributedStr = attributedStr + Word.getSpecial(of: text)
} else if text.contains("\"") {
attributedStr = attributedStr + Word.getQuotedString(of: text)
} else if text == "print" {
attributedStr = attributedStr + Word.getPrint()
} else if text == "Run" {
attributedStr = attributedStr + Word.getRun()
}
else {
attributedStr = attributedStr + Word.getDarkBlueString(with: text)
}
}
return attributedStr
}
func getProcessedStringArray(with text:String) -> [String] {
var textToBeProcessed = text
textToBeProcessed = textToBeProcessed.replacingOccurrences(of: " ", with: "/")
let textArray = textToBeProcessed.components(separatedBy: "/")
return textArray
}
class Word {
class func getLet() -> NSAttributedString {
let myAttribute = [NSForegroundColorAttributeName:Color.alizarinRed, NSFontAttributeName: UIFont(name: "DamascusBold", size: 15.0)]
let attributedString = NSAttributedString(string: "let ", attributes: myAttribute)
return attributedString
}
//let, func, etc.
class func getSpecial(of text:String) -> NSAttributedString {
let myAttribute = [NSForegroundColorAttributeName:Color.alizarinRed, NSFontAttributeName: UIFont(name: "DamascusBold", size: 15.0)]
let attributedString = NSAttributedString(string: text + " ", attributes: myAttribute)
return attributedString
}
class func getQuotedString(of text:String) -> NSAttributedString {
let myAttribute = [NSForegroundColorAttributeName: UIColor.orange, NSFontAttributeName: UIFont(name: "DamascusBold", size: 15.0)]
let attributedString = NSAttributedString(string: text + " ", attributes: myAttribute)
return attributedString
}
class func getPrint() -> NSAttributedString {
let myAttribute = [NSForegroundColorAttributeName:Color.alizarinRed, NSFontAttributeName: UIFont(name: "DamascusBold", size: 15.0)]
let attributedString = NSAttributedString(string: "print", attributes: myAttribute)
return attributedString
}
class func getBlack(of text:String) -> NSAttributedString {
let myAttribute = [NSForegroundColorAttributeName: UIColor(hexString:"#1abc9c")]
let attributedString = NSAttributedString(string: text + " ", attributes: myAttribute)
return attributedString
}
class func getWhite(of text:String) -> NSAttributedString {
let myAttribute = [NSForegroundColorAttributeName: UIColor.white]
let attributedString = NSAttributedString(string: text + " ", attributes: myAttribute)
return attributedString
}
class func getRun() -> NSAttributedString {
let myAttribute = [NSForegroundColorAttributeName: UIColor(hexString:"#3498db"), NSFontAttributeName: UIFont(name: "DamascusBold", size: 15.0)]
let attributedString = NSAttributedString(string: " Run ", attributes: myAttribute)
return attributedString
}
class func getDarkBlueString(with text:String) -> NSAttributedString {
let attributedStr = NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName:UIColor(hexString:"#2c3e50")])
return attributedStr
}
}
func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString
{
let result = NSMutableAttributedString()
result.append(left)
result.append(right)
return result
}
| mit | dc187988e5822ea29c795d7701d4e219 | 36.283784 | 152 | 0.668902 | 4.944444 | false | false | false | false |
aijaz/icw1502 | playgrounds/Week07.playground/Pages/Protocols.xcplaygroundpage/Contents.swift | 1 | 623 | //: Playground - noun: a place where people can play
import Foundation
var a = 3
print(a)
var v = Vertex(x: 3, y: 4)
var v2 = v.moveByX(3)
var rect1 = Rectangle(topLeftCorner: Vertex(x: 3, y: 4), width: 10, height: 20)
var rect2 = rect1.moveByX(50)
v.location
rect1.location
func shiftLeft(movableThing: Movable) -> Movable {
return movableThing.moveByX(-1)
}
v
shiftLeft(rect2)
v.whatAmI()
var v3 = shiftLeft(v) as! Vertex
v3.whatAmI()
func newShiftLeft<T: Movable>(movableThing: T) -> T {
return movableThing.moveByX(-1)
}
var v4 = newShiftLeft(v)
v4.whatAmI()
v.whereAmI()
rect1.whereAmI()
| mit | c7f838d628b86514c9c5f5d9edfceb35 | 12.543478 | 79 | 0.682183 | 2.617647 | false | false | false | false |
tkremenek/swift | stdlib/public/core/SIMDVector.swift | 3 | 44652 | //===--- SIMDVector.swift -------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
infix operator .==: ComparisonPrecedence
infix operator .!=: ComparisonPrecedence
infix operator .<: ComparisonPrecedence
infix operator .<=: ComparisonPrecedence
infix operator .>: ComparisonPrecedence
infix operator .>=: ComparisonPrecedence
infix operator .&: LogicalConjunctionPrecedence
infix operator .^: LogicalDisjunctionPrecedence
infix operator .|: LogicalDisjunctionPrecedence
infix operator .&=: AssignmentPrecedence
infix operator .^=: AssignmentPrecedence
infix operator .|=: AssignmentPrecedence
prefix operator .!
/// A type that can function as storage for a SIMD vector type.
///
/// The `SIMDStorage` protocol defines a storage layout and provides
/// elementwise accesses. Computational operations are defined on the `SIMD`
/// protocol, which refines this protocol, and on the concrete types that
/// conform to `SIMD`.
public protocol SIMDStorage {
/// The type of scalars in the vector space.
associatedtype Scalar: Codable, Hashable
/// The number of scalars, or elements, in the vector.
var scalarCount: Int { get }
/// Creates a vector with zero in all lanes.
init()
/// Accesses the element at the specified index.
///
/// - Parameter index: The index of the element to access. `index` must be in
/// the range `0..<scalarCount`.
subscript(index: Int) -> Scalar { get set }
}
extension SIMDStorage {
/// The number of scalars, or elements, in a vector of this type.
@_alwaysEmitIntoClient
public static var scalarCount: Int {
// Wouldn't it make more sense to define the instance var in terms of the
// static var? Yes, probably, but by doing it this way we make the static
// var backdeployable.
return Self().scalarCount
}
}
/// A type that can be used as an element in a SIMD vector.
public protocol SIMDScalar {
associatedtype SIMDMaskScalar: SIMDScalar & FixedWidthInteger & SignedInteger
associatedtype SIMD2Storage: SIMDStorage where SIMD2Storage.Scalar == Self
associatedtype SIMD4Storage: SIMDStorage where SIMD4Storage.Scalar == Self
associatedtype SIMD8Storage: SIMDStorage where SIMD8Storage.Scalar == Self
associatedtype SIMD16Storage: SIMDStorage where SIMD16Storage.Scalar == Self
associatedtype SIMD32Storage: SIMDStorage where SIMD32Storage.Scalar == Self
associatedtype SIMD64Storage: SIMDStorage where SIMD64Storage.Scalar == Self
}
/// A SIMD vector of a fixed number of elements.
public protocol SIMD: SIMDStorage,
Codable,
Hashable,
CustomStringConvertible,
ExpressibleByArrayLiteral {
/// The mask type resulting from pointwise comparisons of this vector type.
associatedtype MaskStorage: SIMD
where MaskStorage.Scalar: FixedWidthInteger & SignedInteger
}
extension SIMD {
/// The valid indices for subscripting the vector.
@_transparent
public var indices: Range<Int> {
return 0 ..< scalarCount
}
/// A vector with the specified value in all lanes.
@_transparent
public init(repeating value: Scalar) {
self.init()
for i in indices { self[i] = value }
}
/// Returns a Boolean value indicating whether two vectors are equal.
@_transparent
public static func ==(a: Self, b: Self) -> Bool {
var result = true
for i in a.indices { result = result && a[i] == b[i] }
return result
}
/// Hashes the elements of the vector using the given hasher.
@inlinable
public func hash(into hasher: inout Hasher) {
for i in indices { hasher.combine(self[i]) }
}
/// Encodes the scalars of this vector into the given encoder in an unkeyed
/// container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for i in indices {
try container.encode(self[i])
}
}
/// Creates a new vector by decoding scalars from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
guard container.count == scalarCount else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Expected vector with exactly \(scalarCount) elements."
)
)
}
for i in indices {
self[i] = try container.decode(Scalar.self)
}
}
/// A textual description of the vector.
public var description: String {
get {
return "\(Self.self)(" + indices.map({"\(self[$0])"}).joined(separator: ", ") + ")"
}
}
/// A vector mask with the result of a pointwise equality comparison.
///
/// Equivalent to:
/// ```
/// var result = SIMDMask<MaskStorage>()
/// for i in result.indices {
/// result[i] = a[i] == b[i]
/// }
/// ```
@_transparent
public static func .==(a: Self, b: Self) -> SIMDMask<MaskStorage> {
var result = SIMDMask<MaskStorage>()
for i in result.indices { result[i] = a[i] == b[i] }
return result
}
/// A vector mask with the result of a pointwise inequality comparison.
///
/// Equivalent to:
/// ```
/// var result = SIMDMask<MaskStorage>()
/// for i in result.indices {
/// result[i] = a[i] != b[i]
/// }
/// ```
@_transparent
public static func .!=(a: Self, b: Self) -> SIMDMask<MaskStorage> {
var result = SIMDMask<MaskStorage>()
for i in result.indices { result[i] = a[i] != b[i] }
return result
}
/// Replaces elements of this vector with elements of `other` in the lanes
/// where `mask` is `true`.
///
/// Equivalent to:
/// ```
/// for i in indices {
/// if mask[i] { self[i] = other[i] }
/// }
/// ```
@_transparent
public mutating func replace(with other: Self, where mask: SIMDMask<MaskStorage>) {
for i in indices { self[i] = mask[i] ? other[i] : self[i] }
}
/// Creates a vector from the specified elements.
///
/// - Parameter scalars: The elements to use in the vector. `scalars` must
/// have the same number of elements as the vector type.
@inlinable
public init(arrayLiteral scalars: Scalar...) {
self.init(scalars)
}
/// Creates a vector from the given sequence.
///
/// - Precondition: `scalars` must have the same number of elements as the
/// vector type.
///
/// - Parameter scalars: The elements to use in the vector.
@inlinable
public init<S: Sequence>(_ scalars: S) where S.Element == Scalar {
self.init()
var index = 0
for scalar in scalars {
if index == scalarCount {
_preconditionFailure("Too many elements in sequence.")
}
self[index] = scalar
index += 1
}
if index < scalarCount {
_preconditionFailure("Not enough elements in sequence.")
}
}
/// Extracts the scalars at specified indices to form a SIMD2.
///
/// The elements of the index vector are wrapped modulo the count of elements
/// in this vector. Because of this, the index is always in-range and no trap
/// can occur.
@_alwaysEmitIntoClient
public subscript<Index>(index: SIMD2<Index>) -> SIMD2<Scalar>
where Index: FixedWidthInteger {
var result = SIMD2<Scalar>()
for i in result.indices {
result[i] = self[Int(index[i]) % scalarCount]
}
return result
}
/// Extracts the scalars at specified indices to form a SIMD3.
///
/// The elements of the index vector are wrapped modulo the count of elements
/// in this vector. Because of this, the index is always in-range and no trap
/// can occur.
@_alwaysEmitIntoClient
public subscript<Index>(index: SIMD3<Index>) -> SIMD3<Scalar>
where Index: FixedWidthInteger {
var result = SIMD3<Scalar>()
for i in result.indices {
result[i] = self[Int(index[i]) % scalarCount]
}
return result
}
/// Extracts the scalars at specified indices to form a SIMD4.
///
/// The elements of the index vector are wrapped modulo the count of elements
/// in this vector. Because of this, the index is always in-range and no trap
/// can occur.
@_alwaysEmitIntoClient
public subscript<Index>(index: SIMD4<Index>) -> SIMD4<Scalar>
where Index: FixedWidthInteger {
var result = SIMD4<Scalar>()
for i in result.indices {
result[i] = self[Int(index[i]) % scalarCount]
}
return result
}
/// Extracts the scalars at specified indices to form a SIMD8.
///
/// The elements of the index vector are wrapped modulo the count of elements
/// in this vector. Because of this, the index is always in-range and no trap
/// can occur.
@_alwaysEmitIntoClient
public subscript<Index>(index: SIMD8<Index>) -> SIMD8<Scalar>
where Index: FixedWidthInteger {
var result = SIMD8<Scalar>()
for i in result.indices {
result[i] = self[Int(index[i]) % scalarCount]
}
return result
}
/// Extracts the scalars at specified indices to form a SIMD16.
///
/// The elements of the index vector are wrapped modulo the count of elements
/// in this vector. Because of this, the index is always in-range and no trap
/// can occur.
@_alwaysEmitIntoClient
public subscript<Index>(index: SIMD16<Index>) -> SIMD16<Scalar>
where Index: FixedWidthInteger {
var result = SIMD16<Scalar>()
for i in result.indices {
result[i] = self[Int(index[i]) % scalarCount]
}
return result
}
/// Extracts the scalars at specified indices to form a SIMD32.
///
/// The elements of the index vector are wrapped modulo the count of elements
/// in this vector. Because of this, the index is always in-range and no trap
/// can occur.
@_alwaysEmitIntoClient
public subscript<Index>(index: SIMD32<Index>) -> SIMD32<Scalar>
where Index: FixedWidthInteger {
var result = SIMD32<Scalar>()
for i in result.indices {
result[i] = self[Int(index[i]) % scalarCount]
}
return result
}
/// Extracts the scalars at specified indices to form a SIMD64.
///
/// The elements of the index vector are wrapped modulo the count of elements
/// in this vector. Because of this, the index is always in-range and no trap
/// can occur.
@_alwaysEmitIntoClient
public subscript<Index>(index: SIMD64<Index>) -> SIMD64<Scalar>
where Index: FixedWidthInteger {
var result = SIMD64<Scalar>()
for i in result.indices {
result[i] = self[Int(index[i]) % scalarCount]
}
return result
}
}
// Implementations of comparison operations. These should eventually all
// be replaced with @_semantics to lower directly to vector IR nodes.
extension SIMD where Scalar: Comparable {
/// Returns a vector mask with the result of a pointwise less than
/// comparison.
@_transparent
public static func .<(a: Self, b: Self) -> SIMDMask<MaskStorage> {
var result = SIMDMask<MaskStorage>()
for i in result.indices { result[i] = a[i] < b[i] }
return result
}
/// Returns a vector mask with the result of a pointwise less than or equal
/// comparison.
@_transparent
public static func .<=(a: Self, b: Self) -> SIMDMask<MaskStorage> {
var result = SIMDMask<MaskStorage>()
for i in result.indices { result[i] = a[i] <= b[i] }
return result
}
/// The least element in the vector.
@_alwaysEmitIntoClient
public func min() -> Scalar {
return indices.reduce(into: self[0]) { $0 = Swift.min($0, self[$1]) }
}
/// The greatest element in the vector.
@_alwaysEmitIntoClient
public func max() -> Scalar {
return indices.reduce(into: self[0]) { $0 = Swift.max($0, self[$1]) }
}
}
// These operations should never need @_semantics; they should be trivial
// wrappers around the core operations defined above.
extension SIMD {
/// Returns a vector mask with the result of a pointwise equality comparison.
@_transparent
public static func .==(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {
return Self(repeating: a) .== b
}
/// Returns a vector mask with the result of a pointwise inequality comparison.
@_transparent
public static func .!=(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {
return Self(repeating: a) .!= b
}
/// Returns a vector mask with the result of a pointwise equality comparison.
@_transparent
public static func .==(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {
return a .== Self(repeating: b)
}
/// Returns a vector mask with the result of a pointwise inequality comparison.
@_transparent
public static func .!=(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {
return a .!= Self(repeating: b)
}
/// Replaces elements of this vector with `other` in the lanes where `mask`
/// is `true`.
///
/// Equivalent to:
/// ```
/// for i in indices {
/// if mask[i] { self[i] = other }
/// }
/// ```
@_transparent
public mutating func replace(with other: Scalar, where mask: SIMDMask<MaskStorage>) {
replace(with: Self(repeating: other), where: mask)
}
/// Returns a copy of this vector, with elements replaced by elements of
/// `other` in the lanes where `mask` is `true`.
///
/// Equivalent to:
/// ```
/// var result = Self()
/// for i in indices {
/// result[i] = mask[i] ? other[i] : self[i]
/// }
/// ```
@_transparent
public func replacing(with other: Self, where mask: SIMDMask<MaskStorage>) -> Self {
var result = self
result.replace(with: other, where: mask)
return result
}
/// Returns a copy of this vector, with elements `other` in the lanes where
/// `mask` is `true`.
///
/// Equivalent to:
/// ```
/// var result = Self()
/// for i in indices {
/// result[i] = mask[i] ? other : self[i]
/// }
/// ```
@_transparent
public func replacing(with other: Scalar, where mask: SIMDMask<MaskStorage>) -> Self {
return replacing(with: Self(repeating: other), where: mask)
}
}
extension SIMD where Scalar: Comparable {
/// Returns a vector mask with the result of a pointwise greater than or
/// equal comparison.
@_transparent
public static func .>=(a: Self, b: Self) -> SIMDMask<MaskStorage> {
return b .<= a
}
/// Returns a vector mask with the result of a pointwise greater than
/// comparison.
@_transparent
public static func .>(a: Self, b: Self) -> SIMDMask<MaskStorage> {
return b .< a
}
/// Returns a vector mask with the result of a pointwise less than comparison.
@_transparent
public static func .<(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {
return Self(repeating: a) .< b
}
/// Returns a vector mask with the result of a pointwise less than or equal
/// comparison.
@_transparent
public static func .<=(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {
return Self(repeating: a) .<= b
}
/// Returns a vector mask with the result of a pointwise greater than or
/// equal comparison.
@_transparent
public static func .>=(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {
return Self(repeating: a) .>= b
}
/// Returns a vector mask with the result of a pointwise greater than
/// comparison.
@_transparent
public static func .>(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {
return Self(repeating: a) .> b
}
/// Returns a vector mask with the result of a pointwise less than comparison.
@_transparent
public static func .<(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {
return a .< Self(repeating: b)
}
/// Returns a vector mask with the result of a pointwise less than or equal
/// comparison.
@_transparent
public static func .<=(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {
return a .<= Self(repeating: b)
}
/// Returns a vector mask with the result of a pointwise greater than or
/// equal comparison.
@_transparent
public static func .>=(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {
return a .>= Self(repeating: b)
}
/// Returns a vector mask with the result of a pointwise greater than
/// comparison.
@_transparent
public static func .>(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {
return a .> Self(repeating: b)
}
@_alwaysEmitIntoClient
public mutating func clamp(lowerBound: Self, upperBound: Self) {
self = self.clamped(lowerBound: lowerBound, upperBound: upperBound)
}
@_alwaysEmitIntoClient
public func clamped(lowerBound: Self, upperBound: Self) -> Self {
return pointwiseMin(upperBound, pointwiseMax(lowerBound, self))
}
}
extension SIMD where Scalar: FixedWidthInteger {
/// A vector with zero in all lanes.
@_transparent
public static var zero: Self {
return Self()
}
/// A vector with one in all lanes.
@_alwaysEmitIntoClient
public static var one: Self {
return Self(repeating: 1)
}
/// Returns a vector with random values from within the specified range in
/// all lanes, using the given generator as a source for randomness.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: Range<Scalar>,
using generator: inout T
) -> Self {
var result = Self()
for i in result.indices {
result[i] = Scalar.random(in: range, using: &generator)
}
return result
}
/// Returns a vector with random values from within the specified range in
/// all lanes.
@inlinable
public static func random(in range: Range<Scalar>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
/// Returns a vector with random values from within the specified range in
/// all lanes, using the given generator as a source for randomness.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: ClosedRange<Scalar>,
using generator: inout T
) -> Self {
var result = Self()
for i in result.indices {
result[i] = Scalar.random(in: range, using: &generator)
}
return result
}
/// Returns a vector with random values from within the specified range in
/// all lanes.
@inlinable
public static func random(in range: ClosedRange<Scalar>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
}
extension SIMD where Scalar: FloatingPoint {
/// A vector with zero in all lanes.
@_transparent
public static var zero: Self {
return Self()
}
/// A vector with one in all lanes.
@_alwaysEmitIntoClient
public static var one: Self {
return Self(repeating: 1)
}
@_alwaysEmitIntoClient
public mutating func clamp(lowerBound: Self, upperBound: Self) {
self = self.clamped(lowerBound: lowerBound, upperBound: upperBound)
}
@_alwaysEmitIntoClient
public func clamped(lowerBound: Self, upperBound: Self) -> Self {
return pointwiseMin(upperBound, pointwiseMax(lowerBound, self))
}
}
extension SIMD
where Scalar: BinaryFloatingPoint, Scalar.RawSignificand: FixedWidthInteger {
/// Returns a vector with random values from within the specified range in
/// all lanes, using the given generator as a source for randomness.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: Range<Scalar>,
using generator: inout T
) -> Self {
var result = Self()
for i in result.indices {
result[i] = Scalar.random(in: range, using: &generator)
}
return result
}
/// Returns a vector with random values from within the specified range in
/// all lanes.
@inlinable
public static func random(in range: Range<Scalar>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
/// Returns a vector with random values from within the specified range in
/// all lanes, using the given generator as a source for randomness.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: ClosedRange<Scalar>,
using generator: inout T
) -> Self {
var result = Self()
for i in result.indices {
result[i] = Scalar.random(in: range, using: &generator)
}
return result
}
/// Returns a vector with random values from within the specified range in
/// all lanes.
@inlinable
public static func random(in range: ClosedRange<Scalar>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
}
@frozen
public struct SIMDMask<Storage>: SIMD
where Storage: SIMD,
Storage.Scalar: FixedWidthInteger & SignedInteger {
public var _storage: Storage
public typealias MaskStorage = Storage
public typealias Scalar = Bool
@_transparent
public var scalarCount: Int {
return _storage.scalarCount
}
@_transparent
public init() {
_storage = Storage()
}
@_transparent
public init(_ _storage: Storage) {
self._storage = _storage
}
public subscript(index: Int) -> Bool {
@_transparent
get {
_precondition(indices.contains(index))
return _storage[index] < 0
}
@_transparent
set {
_precondition(indices.contains(index))
_storage[index] = newValue ? -1 : 0
}
}
}
extension SIMDMask {
/// Returns a vector mask with `true` or `false` randomly assigned in each
/// lane, using the given generator as a source for randomness.
@inlinable
public static func random<T: RandomNumberGenerator>(using generator: inout T) -> SIMDMask {
var result = SIMDMask()
for i in result.indices { result[i] = Bool.random(using: &generator) }
return result
}
/// Returns a vector mask with `true` or `false` randomly assigned in each
/// lane.
@inlinable
public static func random() -> SIMDMask {
var g = SystemRandomNumberGenerator()
return SIMDMask.random(using: &g)
}
}
// Implementations of integer operations. These should eventually all
// be replaced with @_semantics to lower directly to vector IR nodes.
extension SIMD where Scalar: FixedWidthInteger {
@_transparent
public var leadingZeroBitCount: Self {
var result = Self()
for i in indices { result[i] = Scalar(self[i].leadingZeroBitCount) }
return result
}
@_transparent
public var trailingZeroBitCount: Self {
var result = Self()
for i in indices { result[i] = Scalar(self[i].trailingZeroBitCount) }
return result
}
@_transparent
public var nonzeroBitCount: Self {
var result = Self()
for i in indices { result[i] = Scalar(self[i].nonzeroBitCount) }
return result
}
@_transparent
public static prefix func ~(a: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = ~a[i] }
return result
}
@_transparent
public static func &(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] & b[i] }
return result
}
@_transparent
public static func ^(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] ^ b[i] }
return result
}
@_transparent
public static func |(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] | b[i] }
return result
}
@_transparent
public static func &<<(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] &<< b[i] }
return result
}
@_transparent
public static func &>>(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] &>> b[i] }
return result
}
@_transparent
public static func &+(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] &+ b[i] }
return result
}
@_transparent
public static func &-(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] &- b[i] }
return result
}
@_transparent
public static func &*(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] &* b[i] }
return result
}
@_transparent
public static func /(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] / b[i] }
return result
}
@_transparent
public static func %(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] % b[i] }
return result
}
/// Returns the sum of the scalars in the vector, computed with wrapping
/// addition.
///
/// Equivalent to `indices.reduce(into: 0) { $0 &+= self[$1] }`.
@_alwaysEmitIntoClient
public func wrappedSum() -> Scalar {
return indices.reduce(into: 0) { $0 &+= self[$1] }
}
}
// Implementations of floating-point operations. These should eventually all
// be replaced with @_semantics to lower directly to vector IR nodes.
extension SIMD where Scalar: FloatingPoint {
@_transparent
public static func +(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] + b[i] }
return result
}
@_transparent
public static func -(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] - b[i] }
return result
}
@_transparent
public static func *(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] * b[i] }
return result
}
@_transparent
public static func /(a: Self, b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = a[i] / b[i] }
return result
}
@_transparent
public func addingProduct(_ a: Self, _ b: Self) -> Self {
var result = Self()
for i in result.indices { result[i] = self[i].addingProduct(a[i], b[i]) }
return result
}
@_transparent
public func squareRoot( ) -> Self {
var result = Self()
for i in result.indices { result[i] = self[i].squareRoot() }
return result
}
/// A vector formed by rounding each lane of the source vector to an integral
/// value according to the specified rounding `rule`.
@_transparent
public func rounded(_ rule: FloatingPointRoundingRule) -> Self {
var result = Self()
for i in result.indices { result[i] = self[i].rounded(rule) }
return result
}
/// The least scalar in the vector.
@_alwaysEmitIntoClient
public func min() -> Scalar {
return indices.reduce(into: self[0]) { $0 = Scalar.minimum($0, self[$1]) }
}
/// The greatest scalar in the vector.
@_alwaysEmitIntoClient
public func max() -> Scalar {
return indices.reduce(into: self[0]) { $0 = Scalar.maximum($0, self[$1]) }
}
/// The sum of the scalars in the vector.
@_alwaysEmitIntoClient
public func sum() -> Scalar {
// Implementation note: this eventually be defined to lower to either
// llvm.experimental.vector.reduce.fadd or an explicit tree-sum. Open-
// coding the tree sum is problematic, we probably need to define a
// Swift Builtin to support it.
return indices.reduce(into: 0) { $0 += self[$1] }
}
}
extension SIMDMask {
/// A vector mask that is the pointwise logical negation of the input.
///
/// Equivalent to:
/// ```
/// var result = SIMDMask<${Vector}>()
/// for i in result.indices {
/// result[i] = !a[i]
/// }
/// ```
@_transparent
public static prefix func .!(a: SIMDMask) -> SIMDMask {
return SIMDMask(~a._storage)
}
/// A vector mask that is the pointwise logical conjunction of the inputs.
///
/// Equivalent to:
/// ```
/// var result = SIMDMask<${Vector}>()
/// for i in result.indices {
/// result[i] = a[i] && b[i]
/// }
/// ```
///
/// Note that unlike the scalar `&&` operator, the SIMD `.&` operator
/// always fully evaluates both arguments.
@_transparent
public static func .&(a: SIMDMask, b: SIMDMask) -> SIMDMask {
return SIMDMask(a._storage & b._storage)
}
/// A vector mask that is the pointwise exclusive or of the inputs.
///
/// Equivalent to:
/// ```
/// var result = SIMDMask<${Vector}>()
/// for i in result.indices {
/// result[i] = a[i] != b[i]
/// }
/// ```
@_transparent
public static func .^(a: SIMDMask, b: SIMDMask) -> SIMDMask {
return SIMDMask(a._storage ^ b._storage)
}
/// A vector mask that is the pointwise logical disjunction of the inputs.
///
/// Equivalent to:
/// ```
/// var result = SIMDMask<${Vector}>()
/// for i in result.indices {
/// result[i] = a[i] || b[i]
/// }
/// ```
///
/// Note that unlike the scalar `||` operator, the SIMD `.|` operator
/// always fully evaluates both arguments.
@_transparent
public static func .|(a: SIMDMask, b: SIMDMask) -> SIMDMask {
return SIMDMask(a._storage | b._storage)
}
}
// These operations should never need @_semantics; they should be trivial
// wrappers around the core operations defined above.
extension SIMD where Scalar: FixedWidthInteger {
@_transparent
public static func &(a: Scalar, b: Self) -> Self {
return Self(repeating: a) & b
}
@_transparent
public static func ^(a: Scalar, b: Self) -> Self {
return Self(repeating: a) ^ b
}
@_transparent
public static func |(a: Scalar, b: Self) -> Self {
return Self(repeating: a) | b
}
@_transparent
public static func &<<(a: Scalar, b: Self) -> Self {
return Self(repeating: a) &<< b
}
@_transparent
public static func &>>(a: Scalar, b: Self) -> Self {
return Self(repeating: a) &>> b
}
@_transparent
public static func &+(a: Scalar, b: Self) -> Self {
return Self(repeating: a) &+ b
}
@_transparent
public static func &-(a: Scalar, b: Self) -> Self {
return Self(repeating: a) &- b
}
@_transparent
public static func &*(a: Scalar, b: Self) -> Self {
return Self(repeating: a) &* b
}
@_transparent
public static func /(a: Scalar, b: Self) -> Self {
return Self(repeating: a) / b
}
@_transparent
public static func %(a: Scalar, b: Self) -> Self {
return Self(repeating: a) % b
}
@_transparent
public static func &(a: Self, b: Scalar) -> Self {
return a & Self(repeating: b)
}
@_transparent
public static func ^(a: Self, b: Scalar) -> Self {
return a ^ Self(repeating: b)
}
@_transparent
public static func |(a: Self, b: Scalar) -> Self {
return a | Self(repeating: b)
}
@_transparent
public static func &<<(a: Self, b: Scalar) -> Self {
return a &<< Self(repeating: b)
}
@_transparent
public static func &>>(a: Self, b: Scalar) -> Self {
return a &>> Self(repeating: b)
}
@_transparent
public static func &+(a: Self, b: Scalar) -> Self {
return a &+ Self(repeating: b)
}
@_transparent
public static func &-(a: Self, b: Scalar) -> Self {
return a &- Self(repeating: b)
}
@_transparent
public static func &*(a: Self, b: Scalar) -> Self {
return a &* Self(repeating: b)
}
@_transparent
public static func /(a: Self, b: Scalar) -> Self {
return a / Self(repeating: b)
}
@_transparent
public static func %(a: Self, b: Scalar) -> Self {
return a % Self(repeating: b)
}
@_transparent
public static func &=(a: inout Self, b: Self) {
a = a & b
}
@_transparent
public static func ^=(a: inout Self, b: Self) {
a = a ^ b
}
@_transparent
public static func |=(a: inout Self, b: Self) {
a = a | b
}
@_transparent
public static func &<<=(a: inout Self, b: Self) {
a = a &<< b
}
@_transparent
public static func &>>=(a: inout Self, b: Self) {
a = a &>> b
}
@_transparent
public static func &+=(a: inout Self, b: Self) {
a = a &+ b
}
@_transparent
public static func &-=(a: inout Self, b: Self) {
a = a &- b
}
@_transparent
public static func &*=(a: inout Self, b: Self) {
a = a &* b
}
@_transparent
public static func /=(a: inout Self, b: Self) {
a = a / b
}
@_transparent
public static func %=(a: inout Self, b: Self) {
a = a % b
}
@_transparent
public static func &=(a: inout Self, b: Scalar) {
a = a & b
}
@_transparent
public static func ^=(a: inout Self, b: Scalar) {
a = a ^ b
}
@_transparent
public static func |=(a: inout Self, b: Scalar) {
a = a | b
}
@_transparent
public static func &<<=(a: inout Self, b: Scalar) {
a = a &<< b
}
@_transparent
public static func &>>=(a: inout Self, b: Scalar) {
a = a &>> b
}
@_transparent
public static func &+=(a: inout Self, b: Scalar) {
a = a &+ b
}
@_transparent
public static func &-=(a: inout Self, b: Scalar) {
a = a &- b
}
@_transparent
public static func &*=(a: inout Self, b: Scalar) {
a = a &* b
}
@_transparent
public static func /=(a: inout Self, b: Scalar) {
a = a / b
}
@_transparent
public static func %=(a: inout Self, b: Scalar) {
a = a % b
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead")
public static func +(a: Self, b: Self) -> Self {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead")
public static func -(a: Self, b: Self) -> Self {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead")
public static func *(a: Self, b: Self) -> Self {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead")
public static func +(a: Self, b: Scalar) -> Self {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead")
public static func -(a: Self, b: Scalar) -> Self {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead")
public static func *(a: Self, b: Scalar) -> Self {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead")
public static func +(a: Scalar, b: Self) -> Self {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead")
public static func -(a: Scalar, b: Self) -> Self {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead")
public static func *(a: Scalar, b: Self) -> Self {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+=' instead")
public static func +=(a: inout Self, b: Self) {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-=' instead")
public static func -=(a: inout Self, b: Self) {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*=' instead")
public static func *=(a: inout Self, b: Self) {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+=' instead")
public static func +=(a: inout Self, b: Scalar) {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-=' instead")
public static func -=(a: inout Self, b: Scalar) {
fatalError()
}
@available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*=' instead")
public static func *=(a: inout Self, b: Scalar) {
fatalError()
}
}
extension SIMD where Scalar: FloatingPoint {
@_transparent
public static prefix func -(a: Self) -> Self {
return 0 - a
}
@_transparent
public static func +(a: Scalar, b: Self) -> Self {
return Self(repeating: a) + b
}
@_transparent
public static func -(a: Scalar, b: Self) -> Self {
return Self(repeating: a) - b
}
@_transparent
public static func *(a: Scalar, b: Self) -> Self {
return Self(repeating: a) * b
}
@_transparent
public static func /(a: Scalar, b: Self) -> Self {
return Self(repeating: a) / b
}
@_transparent
public static func +(a: Self, b: Scalar) -> Self {
return a + Self(repeating: b)
}
@_transparent
public static func -(a: Self, b: Scalar) -> Self {
return a - Self(repeating: b)
}
@_transparent
public static func *(a: Self, b: Scalar) -> Self {
return a * Self(repeating: b)
}
@_transparent
public static func /(a: Self, b: Scalar) -> Self {
return a / Self(repeating: b)
}
@_transparent
public static func +=(a: inout Self, b: Self) {
a = a + b
}
@_transparent
public static func -=(a: inout Self, b: Self) {
a = a - b
}
@_transparent
public static func *=(a: inout Self, b: Self) {
a = a * b
}
@_transparent
public static func /=(a: inout Self, b: Self) {
a = a / b
}
@_transparent
public static func +=(a: inout Self, b: Scalar) {
a = a + b
}
@_transparent
public static func -=(a: inout Self, b: Scalar) {
a = a - b
}
@_transparent
public static func *=(a: inout Self, b: Scalar) {
a = a * b
}
@_transparent
public static func /=(a: inout Self, b: Scalar) {
a = a / b
}
@_transparent
public func addingProduct(_ a: Scalar, _ b: Self) -> Self {
return self.addingProduct(Self(repeating: a), b)
}
@_transparent
public func addingProduct(_ a: Self, _ b: Scalar) -> Self {
return self.addingProduct(a, Self(repeating: b))
}
@_transparent
public mutating func addProduct(_ a: Self, _ b: Self) {
self = self.addingProduct(a, b)
}
@_transparent
public mutating func addProduct(_ a: Scalar, _ b: Self) {
self = self.addingProduct(a, b)
}
@_transparent
public mutating func addProduct(_ a: Self, _ b: Scalar) {
self = self.addingProduct(a, b)
}
@_transparent
public mutating func formSquareRoot( ) {
self = self.squareRoot()
}
@_transparent
public mutating func round(_ rule: FloatingPointRoundingRule) {
self = self.rounded(rule)
}
}
extension SIMDMask {
/// A vector mask that is the pointwise logical conjunction of the inputs.
///
/// Equivalent to `a ? b : SIMDMask(repeating: false)`.
@_transparent
public static func .&(a: Bool, b: SIMDMask) -> SIMDMask {
return SIMDMask(repeating: a) .& b
}
/// A vector mask that is the pointwise exclusive or of the inputs.
///
/// Equivalent to `a ? .!b : b`.
@_transparent
public static func .^(a: Bool, b: SIMDMask) -> SIMDMask {
return SIMDMask(repeating: a) .^ b
}
/// A vector mask that is the pointwise logical disjunction of the inputs.
///
/// Equivalent to `a ? SIMDMask(repeating: true) : b`.
@_transparent
public static func .|(a: Bool, b: SIMDMask) -> SIMDMask {
return SIMDMask(repeating: a) .| b
}
/// A vector mask that is the pointwise logical conjunction of the inputs.
///
/// Equivalent to `b ? a : SIMDMask(repeating: false)`.
@_transparent
public static func .&(a: SIMDMask, b: Bool) -> SIMDMask {
return a .& SIMDMask(repeating: b)
}
/// A vector mask that is the pointwise exclusive or of the inputs.
///
/// Equivalent to `b ? .!a : a`.
@_transparent
public static func .^(a: SIMDMask, b: Bool) -> SIMDMask {
return a .^ SIMDMask(repeating: b)
}
/// A vector mask that is the pointwise logical disjunction of the inputs.
///
/// Equivalent to `b ? SIMDMask(repeating: true) : a`
@_transparent
public static func .|(a: SIMDMask, b: Bool) -> SIMDMask {
return a .| SIMDMask(repeating: b)
}
/// Replaces `a` with the pointwise logical conjuction of `a` and `b`.
///
/// Equivalent to:
/// ```
/// for i in a.indices {
/// a[i] = a[i] && b[i]
/// }
/// ```
@_transparent
public static func .&=(a: inout SIMDMask, b: SIMDMask) {
a = a .& b
}
/// Replaces `a` with the pointwise exclusive or of `a` and `b`.
///
/// Equivalent to:
/// ```
/// for i in a.indices {
/// a[i] = a[i] != b[i]
/// }
/// ```
@_transparent
public static func .^=(a: inout SIMDMask, b: SIMDMask) {
a = a .^ b
}
/// Replaces `a` with the pointwise logical disjunction of `a` and `b`.
///
/// Equivalent to:
/// ```
/// for i in a.indices {
/// a[i] = a[i] || b[i]
/// }
/// ```
@_transparent
public static func .|=(a: inout SIMDMask, b: SIMDMask) {
a = a .| b
}
/// Replaces `a` with the pointwise logical conjuction of `a` and `b`.
///
/// Equivalent to:
/// ```
/// if !b { a = SIMDMask(repeating: false) }
/// ```
@_transparent
public static func .&=(a: inout SIMDMask, b: Bool) {
a = a .& b
}
/// Replaces `a` with the pointwise exclusive or of `a` and `b`.
///
/// Equivalent to:
/// ```
/// if b { a = .!a }
/// ```
@_transparent
public static func .^=(a: inout SIMDMask, b: Bool) {
a = a .^ b
}
/// Replaces `a` with the pointwise logical disjunction of `a` and `b`.
///
/// Equivalent to:
/// ```
/// if b { a = SIMDMask(repeating: true) }
/// ```
@_transparent
public static func .|=(a: inout SIMDMask, b: Bool) {
a = a .| b
}
}
/// True if any lane of mask is true.
@_alwaysEmitIntoClient
public func any<Storage>(_ mask: SIMDMask<Storage>) -> Bool {
return mask._storage.min() < 0
}
/// True if every lane of mask is true.
@_alwaysEmitIntoClient
public func all<Storage>(_ mask: SIMDMask<Storage>) -> Bool {
return mask._storage.max() < 0
}
/// The lanewise minimum of two vectors.
///
/// Each element of the result is the minimum of the corresponding elements
/// of the inputs.
@_alwaysEmitIntoClient
public func pointwiseMin<T>(_ a: T, _ b: T) -> T
where T: SIMD, T.Scalar: Comparable {
var result = T()
for i in result.indices {
result[i] = min(a[i], b[i])
}
return result
}
/// The lanewise maximum of two vectors.
///
/// Each element of the result is the minimum of the corresponding elements
/// of the inputs.
@_alwaysEmitIntoClient
public func pointwiseMax<T>(_ a: T, _ b: T) -> T
where T: SIMD, T.Scalar: Comparable {
var result = T()
for i in result.indices {
result[i] = max(a[i], b[i])
}
return result
}
/// The lanewise minimum of two vectors.
///
/// Each element of the result is the minimum of the corresponding elements
/// of the inputs.
@_alwaysEmitIntoClient
public func pointwiseMin<T>(_ a: T, _ b: T) -> T
where T: SIMD, T.Scalar: FloatingPoint {
var result = T()
for i in result.indices {
result[i] = T.Scalar.minimum(a[i], b[i])
}
return result
}
/// The lanewise maximum of two vectors.
///
/// Each element of the result is the maximum of the corresponding elements
/// of the inputs.
@_alwaysEmitIntoClient
public func pointwiseMax<T>(_ a: T, _ b: T) -> T
where T: SIMD, T.Scalar: FloatingPoint {
var result = T()
for i in result.indices {
result[i] = T.Scalar.maximum(a[i], b[i])
}
return result
}
// Break the ambiguity between AdditiveArithmetic and SIMD for += and -=
extension SIMD where Self: AdditiveArithmetic, Self.Scalar: FloatingPoint {
@_alwaysEmitIntoClient
public static func +=(a: inout Self, b: Self) {
a = a + b
}
@_alwaysEmitIntoClient
public static func -=(a: inout Self, b: Self) {
a = a - b
}
}
| apache-2.0 | 1bcd5979562b424f77cece6fe00f5766 | 27.422661 | 136 | 0.632536 | 3.968714 | false | false | false | false |
xwu/swift | test/Distributed/distributed_actor_nonisolated.swift | 1 | 1901 | // RUN: %target-typecheck-verify-swift -enable-experimental-distributed -disable-availability-checking
// REQUIRES: concurrency
// REQUIRES: distributed
import _Distributed
@available(SwiftStdlib 5.5, *)
distributed actor DA {
let local: Int = 42
// expected-note@-1{{distributed actor state is only available within the actor instance}}
// expected-note@-2{{distributed actor state is only available within the actor instance}}
nonisolated let nope: Int = 13
// expected-error@-1{{'nonisolated' can not be applied to distributed actor stored properties}}
nonisolated var computedNonisolated: Int {
// nonisolated computed properties are outside of the actor and as such cannot access local
_ = self.local // expected-error{{distributed actor-isolated property 'local' can only be referenced inside the distributed actor}}
_ = self.id // ok, special handled and always available
_ = self.actorTransport // ok, special handled and always available
}
distributed func dist() {}
nonisolated func access() async throws {
_ = self.id // ok
_ = self.actorTransport // ok
// self is a distributed actor self is NOT isolated
_ = self.local // expected-error{{distributed actor-isolated property 'local' can only be referenced inside the distributed actor}}
_ = try await self.dist() // ok, was made implicitly throwing and async
_ = self.computedNonisolated // it's okay, only the body of computedNonisolated is wrong
}
nonisolated distributed func nonisolatedDistributed() async {
// expected-error@-1{{function 'nonisolatedDistributed()' cannot be both 'nonisolated' and 'distributed'}}{{3-15=}}
fatalError()
}
distributed nonisolated func distributedNonisolated() async {
// expected-error@-1{{function 'distributedNonisolated()' cannot be both 'nonisolated' and 'distributed'}}{{15-27=}}
fatalError()
}
}
| apache-2.0 | c081db10e9c4a1d4533f7d9d9e425654 | 39.446809 | 135 | 0.723304 | 4.625304 | false | false | false | false |
chuganzy/HCImage-BPG | Tests/Tests.swift | 2 | 1785 | //
// Tests.swift
// HCImage+BPG
//
// Created by Takeru Chuganji on 3/13/16.
// Copyright © 2016 Takeru Chuganji. All rights reserved.
//
import XCTest
@testable import HCImageBPG
#if os(iOS)
typealias ImageType = UIImage
#elseif os(OSX)
typealias ImageType = NSImage
#endif
final class Tests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testDecodeImages() {
(0...19).forEach { index in
let name = String(format: "image-%05d", index)
XCTAssertNotNil(decodeBPG(forResource: name))
}
}
func testDecodeInvalidImages() {
XCTAssertNil(decodeBPG(forResource: "broken-00000"))
XCTAssertNil(decodeBPG(forResource: "jpeg-00000", withExtension: "jpg"))
XCTAssertNil(ImageType(bpgData: Data(bytes: [])))
}
func testDecodeAnimatedImages() {
let image = decodeBPG(forResource: "animation-00000")
let expectedCount = 40
#if os(iOS)
XCTAssertEqual(image?.images?.count, expectedCount)
#elseif os(OSX)
let count = (image?.representations.first as? NSBitmapImageRep)?
.value(forProperty: .frameCount) as? Int
XCTAssertEqual(count, expectedCount)
#endif
}
func testDecodePerformance() {
measure {
XCTAssertNotNil(decodeBPG(forResource: "image-00000"))
}
}
private func decodeBPG(forResource res: String, withExtension ext: String = "bpg") -> ImageType? {
return Bundle(for: type(of: self))
.url(forResource: res, withExtension: ext)
.flatMap { try? Data(contentsOf: $0) }
.flatMap(ImageType.init(bpgData:))
}
}
| mit | 20e7cb722b1c7be5a2371e198314d16c | 26.446154 | 102 | 0.610426 | 4.158508 | false | true | false | false |
makingsensetraining/mobile-pocs | IOS/SwiftSeedProject/SwiftSeedProject/Interfaces/Components/NewsCollection/Cells/ArticleViewModel.swift | 1 | 644 | //
// ArticleViewModel.swift
// SwiftSeedProject
//
// Created by Lucas Pelizza on 4/18/17.
// Copyright © 2017 Making Sense. All rights reserved.
//
import Foundation
import Bond
final class ArticleViewModel {
var imageUrl: URL
var date: NSDate
var description: String
var title: String
var author: String
var sourceURL: URL
init(article: Article) {
self.imageUrl = article.urlToImage!
self.date = article.publishedAt!
self.description = article.detail!
self.title = article.title!
self.author = article.author!
self.sourceURL = article.url!
}
}
| mit | 857ce8dfeee5d032539e5ca0ade85c81 | 21.172414 | 55 | 0.648523 | 4.01875 | false | false | false | false |
jacobwhite/firefox-ios | Client/Frontend/Browser/ContextMenuHelper.swift | 1 | 3967 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import WebKit
protocol ContextMenuHelperDelegate: class {
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer)
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer)
}
class ContextMenuHelper: NSObject {
struct Elements {
let link: URL?
let image: URL?
}
fileprivate weak var tab: Tab?
weak var delegate: ContextMenuHelperDelegate?
fileprivate var nativeHighlightLongPressRecognizer: UILongPressGestureRecognizer?
fileprivate var elements: Elements?
required init(tab: Tab) {
super.init()
self.tab = tab
nativeHighlightLongPressRecognizer = gestureRecognizerWithDescriptionFragment("action=_highlightLongPressRecognized:") as? UILongPressGestureRecognizer
if let nativeLongPressRecognizer = gestureRecognizerWithDescriptionFragment("action=_longPressRecognized:") as? UILongPressGestureRecognizer {
nativeLongPressRecognizer.removeTarget(nil, action: nil)
nativeLongPressRecognizer.addTarget(self, action: #selector(longPressGestureDetected))
}
}
func gestureRecognizerWithDescriptionFragment(_ descriptionFragment: String) -> UIGestureRecognizer? {
return tab?.webView?.scrollView.subviews.compactMap({ $0.gestureRecognizers }).joined().first(where: { $0.description.contains(descriptionFragment) })
}
@objc func longPressGestureDetected(_ sender: UIGestureRecognizer) {
if sender.state == .cancelled {
delegate?.contextMenuHelper(self, didCancelGestureRecognizer: sender)
return
}
guard sender.state == .began, let elements = self.elements else {
return
}
delegate?.contextMenuHelper(self, didLongPressElements: elements, gestureRecognizer: sender)
// To prevent the tapped link from proceeding with navigation, "cancel" the native WKWebView
// `_highlightLongPressRecognizer`. This preserves the original behavior as seen here:
// https://github.com/WebKit/webkit/blob/d591647baf54b4b300ca5501c21a68455429e182/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm#L1600-L1614
if let nativeHighlightLongPressRecognizer = self.nativeHighlightLongPressRecognizer,
nativeHighlightLongPressRecognizer.isEnabled {
nativeHighlightLongPressRecognizer.isEnabled = false
nativeHighlightLongPressRecognizer.isEnabled = true
}
self.elements = nil
}
}
extension ContextMenuHelper: TabContentScript {
class func name() -> String {
return "ContextMenuHelper"
}
func scriptMessageHandlerName() -> String? {
return "contextMenuMessageHandler"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard let data = message.body as? [String: AnyObject] else {
return
}
var linkURL: URL?
if let urlString = data["link"] as? String,
let escapedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .URLAllowed) {
linkURL = URL(string: escapedURLString)
}
var imageURL: URL?
if let urlString = data["image"] as? String,
let escapedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .URLAllowed) {
imageURL = URL(string: escapedURLString)
}
if linkURL != nil || imageURL != nil {
elements = Elements(link: linkURL, image: imageURL)
} else {
elements = nil
}
}
}
| mpl-2.0 | c76740e6d40b5147a521730bcb9e562e | 39.070707 | 165 | 0.704058 | 5.464187 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Basics.playground/Pages/Splitting Nodes.xcplaygroundpage/Contents.swift | 1 | 1180 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Splitting Nodes
//: All nodes in AudioKit can have multiple destinations, the only
//: caveat is that all of the destinations do have to eventually be mixed
//: back together and none of the parallel signal paths can have any time stretching.
import AudioKitPlaygrounds
import AudioKit
//: Prepare the source audio player
let file = try AKAudioFile(readFileName: "drumloop.wav")
let player = try AKAudioPlayer(file: file)
player.looping = true
//: The following nodes are both acting on the original player node
var ringMod = AKRingModulator(player)
var delay = AKDelay(player)
delay.time = 0.01
delay.feedback = 0.8
delay.dryWetMix = 1
//: Any number of inputs can be equally summed into one output, including the
//: original player, allowing us to create dry/wet mixes even for effects that
//: don't have that property by default
let mixer = AKMixer(player, delay)
AudioKit.output = mixer
AudioKit.start()
player.play()
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | 420ae3f5b71dc4d7b1c37c25567978d5 | 30.891892 | 85 | 0.744915 | 3.959732 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/Facebook/Posts/HATFacebookPrivacy.swift | 1 | 5609 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
/// A struct representing the privacy settings of the post
public struct HATFacebookPrivacy: HatApiType, Comparable, HATObject {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `friends` in JSON is `friends`
* `value` in JSON is `value`
* `deny` in JSON is `deny`
* `description` in JSON is `description`
* `allow` in JSON is `allow`
*/
private enum CodingKeys: String, CodingKey {
case friends
case value
case deny
case description
case allow
}
// MARK: - Comparable protocol
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: HATFacebookPrivacy, rhs: HATFacebookPrivacy) -> Bool {
return (lhs.friends == rhs.friends && lhs.value == rhs.value && lhs.deny == rhs.deny && lhs.description == rhs.description && lhs.allow == rhs.allow)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func < (lhs: HATFacebookPrivacy, rhs: HATFacebookPrivacy) -> Bool {
return lhs.description < rhs.description
}
// MARK: - Variables
/// Is it friends only?
public var friends: String = ""
/// The value. Possible values are SELF(private, only me) and ALL_FRIENDS(when it's set to public)
public var value: String = ""
/// deny access?
public var deny: String = ""
/// The desctiption of the setting, Only me or All Friends
public var description: String = ""
/// Allow?
public var allow: String = ""
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
friends = ""
value = ""
deny = ""
description = ""
allow = ""
}
/**
It initialises everything from the received JSON file from the HAT
- dictionary: The JSON file received
*/
public init(from dictionary: Dictionary<String, JSON>) {
self.init()
if let tempFriends: String = dictionary[CodingKeys.friends.rawValue]?.stringValue {
friends = tempFriends
}
if let tempValue: String = dictionary[CodingKeys.value.rawValue]?.stringValue {
value = tempValue
}
if let tempDeny: String = dictionary[CodingKeys.deny.rawValue]?.string {
deny = tempDeny
}
if let tempDescription: String = dictionary[CodingKeys.description.rawValue]?.stringValue {
description = tempDescription
}
if let tempAllow: String = dictionary[CodingKeys.allow.rawValue]?.stringValue {
allow = tempAllow
}
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received
*/
public mutating func inititialize(dict: Dictionary<String, JSON>) {
if let tempFriends: String = dict[CodingKeys.friends.rawValue]?.stringValue {
friends = tempFriends
}
if let tempValue: String = dict[CodingKeys.value.rawValue]?.stringValue {
value = tempValue
}
if let tempDeny: String = dict[CodingKeys.deny.rawValue]?.string {
deny = tempDeny
}
if let tempDescription: String = dict[CodingKeys.description.rawValue]?.stringValue {
description = tempDescription
}
if let tempAllow: String = dict[CodingKeys.allow.rawValue]?.stringValue {
allow = tempAllow
}
}
/**
It initialises everything from the received JSON file from the cache
- fromCache: The Dictionary file received from the cache
*/
public mutating func initialize(fromCache: Dictionary<String, Any>) {
let dictionary: JSON = JSON(fromCache)
self.inititialize(dict: dictionary.dictionaryValue)
}
// MARK: - JSON Mapper
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
return [
CodingKeys.friends.rawValue: self.friends,
CodingKeys.deny.rawValue: self.deny,
CodingKeys.value.rawValue: self.value,
CodingKeys.description.rawValue: self.description,
CodingKeys.allow.rawValue: self.allow
]
}
}
| mpl-2.0 | 75e63ee83e3d224a1a0ad2ea45f0377c | 28.994652 | 157 | 0.60189 | 4.741336 | false | false | false | false |
castial/Quick-Start-iOS | Quick-Start-iOS/Controllers/Home/View/HomeView.swift | 1 | 2260 | //
// HomeView.swift
// Quick-Start-iOS
//
// Created by work on 2016/10/14.
// Copyright © 2016年 hyyy. All rights reserved.
//
import UIKit
import SnapKit
// MARK: - Class
class HomeView: UIView {
// lazy var menuCollectionView: UICollectionView = {
// let collectionLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout ()
//// collectionLayout.scrollDirection = .horizontal // 设置视图滚动方向
//
// let collectionView: UICollectionView = UICollectionView (frame: CGRect (x: 0, y: 30, width: Constants.Rect.ScreenWidth, height: 700), collectionViewLayout: collectionLayout)
//// collectionView.showsHorizontalScrollIndicator = false
// collectionView.backgroundColor = UIColor.lightGray
// collectionView.isPagingEnabled = true
// return collectionView
// }()
lazy var shareTable: UITableView = {
let tableView: UITableView = UITableView (frame: CGRect (x: 0,
y: 0,
width: Constants.Rect.ScreenWidth,
height:Constants.Rect.ScreenHeight - Constants.Rect.tabBarHeight),
style: .plain)
tableView.backgroundColor = UIColor.white
// tableView.isScrollEnabled = false
return tableView
}()
/// 存储各个collectionView的偏移量
var contentOffsetDictionary: NSMutableDictionary = NSMutableDictionary ()
override init(frame: CGRect) {
super.init(frame: frame)
initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - LifeCycle
extension HomeView {
fileprivate func initUI() {
// self.menuCollectionView.delegate = self
// self.menuCollectionView.dataSource = self
// self.menuCollectionView.register(HYShareCollectionCell.self, forCellWithReuseIdentifier: HYShareCollectionCell.ID())
// self.addSubview(self.menuCollectionView)
}
}
| mit | 9d264bc3c01ea1018b17ac46df607265 | 36.711864 | 187 | 0.585169 | 5.534826 | false | false | false | false |
hughbe/swift | test/IRGen/builtins.swift | 2 | 32417 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-stdlib -primary-file %s -emit-ir -o - -disable-objc-attr-requires-foundation-module | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
// REQUIRES: executable_test
// REQUIRES: CPU=x86_64
import Swift
// CHECK-DAG: [[REFCOUNT:%swift.refcounted.*]] = type
// CHECK-DAG: [[X:%T8builtins1XC]] = type
// CHECK-DAG: [[Y:%T8builtins1YC]] = type
typealias Int = Builtin.Int32
typealias Bool = Builtin.Int1
infix operator * {
associativity left
precedence 200
}
infix operator / {
associativity left
precedence 200
}
infix operator % {
associativity left
precedence 200
}
infix operator + {
associativity left
precedence 190
}
infix operator - {
associativity left
precedence 190
}
infix operator << {
associativity none
precedence 180
}
infix operator >> {
associativity none
precedence 180
}
infix operator ... {
associativity none
precedence 175
}
infix operator < {
associativity none
precedence 170
}
infix operator <= {
associativity none
precedence 170
}
infix operator > {
associativity none
precedence 170
}
infix operator >= {
associativity none
precedence 170
}
infix operator == {
associativity none
precedence 160
}
infix operator != {
associativity none
precedence 160
}
func * (lhs: Int, rhs: Int) -> Int {
return Builtin.mul_Int32(lhs, rhs)
// CHECK: mul i32
}
func / (lhs: Int, rhs: Int) -> Int {
return Builtin.sdiv_Int32(lhs, rhs)
// CHECK: sdiv i32
}
func % (lhs: Int, rhs: Int) -> Int {
return Builtin.srem_Int32(lhs, rhs)
// CHECK: srem i32
}
func + (lhs: Int, rhs: Int) -> Int {
return Builtin.add_Int32(lhs, rhs)
// CHECK: add i32
}
func - (lhs: Int, rhs: Int) -> Int {
return Builtin.sub_Int32(lhs, rhs)
// CHECK: sub i32
}
// In C, 180 is <<, >>
func < (lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_slt_Int32(lhs, rhs)
// CHECK: icmp slt i32
}
func > (lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sgt_Int32(lhs, rhs)
// CHECK: icmp sgt i32
}
func <=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sle_Int32(lhs, rhs)
// CHECK: icmp sle i32
}
func >=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sge_Int32(lhs, rhs)
// CHECK: icmp sge i32
}
func ==(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_eq_Int32(lhs, rhs)
// CHECK: icmp eq i32
}
func !=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_ne_Int32(lhs, rhs)
// CHECK: icmp ne i32
}
func gepRaw_test(_ ptr: Builtin.RawPointer, offset: Builtin.Int64)
-> Builtin.RawPointer {
return Builtin.gepRaw_Int64(ptr, offset)
// CHECK: getelementptr inbounds i8, i8*
}
// CHECK: define hidden {{.*}}i64 @_T08builtins9load_test{{[_0-9a-zA-Z]*}}F
func load_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64*
// CHECK-NEXT: load i64, i64* [[CASTPTR]]
// CHECK: ret
return Builtin.load(ptr)
}
// CHECK: define hidden {{.*}}i64 @_T08builtins13load_raw_test{{[_0-9a-zA-Z]*}}F
func load_raw_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64*
// CHECK-NEXT: load i64, i64* [[CASTPTR]]
// CHECK: ret
return Builtin.loadRaw(ptr)
}
// CHECK: define hidden {{.*}}void @_T08builtins11assign_test{{[_0-9a-zA-Z]*}}F
func assign_test(_ value: Builtin.Int64, ptr: Builtin.RawPointer) {
Builtin.assign(value, ptr)
// CHECK: ret
}
// CHECK: define hidden {{.*}}%swift.refcounted* @_T08builtins16load_object_test{{[_0-9a-zA-Z]*}}F
func load_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]**
// CHECK: call void @swift_rt_swift_retain([[REFCOUNT]]* [[T0]])
// CHECK: ret [[REFCOUNT]]* [[T0]]
return Builtin.load(ptr)
}
// CHECK: define hidden {{.*}}%swift.refcounted* @_T08builtins20load_raw_object_test{{[_0-9a-zA-Z]*}}F
func load_raw_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]**
// CHECK: call void @swift_rt_swift_retain([[REFCOUNT]]* [[T0]])
// CHECK: ret [[REFCOUNT]]* [[T0]]
return Builtin.loadRaw(ptr)
}
// CHECK: define hidden {{.*}}void @_T08builtins18assign_object_test{{[_0-9a-zA-Z]*}}F
func assign_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) {
Builtin.assign(value, ptr)
}
// CHECK: define hidden {{.*}}void @_T08builtins16init_object_test{{[_0-9a-zA-Z]*}}F
func init_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) {
// CHECK: [[DEST:%.*]] = bitcast i8* {{%.*}} to %swift.refcounted**
// CHECK-NEXT: store [[REFCOUNT]]* {{%.*}}, [[REFCOUNT]]** [[DEST]]
Builtin.initialize(value, ptr)
}
func cast_test(_ ptr: inout Builtin.RawPointer, i8: inout Builtin.Int8,
i64: inout Builtin.Int64, f: inout Builtin.FPIEEE32,
d: inout Builtin.FPIEEE64
) {
// CHECK: cast_test
i8 = Builtin.trunc_Int64_Int8(i64) // CHECK: trunc
i64 = Builtin.zext_Int8_Int64(i8) // CHECK: zext
i64 = Builtin.sext_Int8_Int64(i8) // CHECK: sext
i64 = Builtin.ptrtoint_Int64(ptr) // CHECK: ptrtoint
ptr = Builtin.inttoptr_Int64(i64) // CHECK: inttoptr
i64 = Builtin.fptoui_FPIEEE64_Int64(d) // CHECK: fptoui
i64 = Builtin.fptosi_FPIEEE64_Int64(d) // CHECK: fptosi
d = Builtin.uitofp_Int64_FPIEEE64(i64) // CHECK: uitofp
d = Builtin.sitofp_Int64_FPIEEE64(i64) // CHECK: sitofp
d = Builtin.fpext_FPIEEE32_FPIEEE64(f) // CHECK: fpext
f = Builtin.fptrunc_FPIEEE64_FPIEEE32(d) // CHECK: fptrunc
i64 = Builtin.bitcast_FPIEEE64_Int64(d) // CHECK: bitcast
d = Builtin.bitcast_Int64_FPIEEE64(i64) // CHECK: bitcast
}
func intrinsic_test(_ i32: inout Builtin.Int32, i16: inout Builtin.Int16) {
i32 = Builtin.int_bswap_Int32(i32) // CHECK: llvm.bswap.i32(
i16 = Builtin.int_bswap_Int16(i16) // CHECK: llvm.bswap.i16(
var x = Builtin.int_sadd_with_overflow_Int16(i16, i16) // CHECK: call { i16, i1 } @llvm.sadd.with.overflow.i16(
Builtin.int_trap() // CHECK: llvm.trap()
}
// CHECK: define hidden {{.*}}void @_T08builtins19sizeof_alignof_testyyF()
func sizeof_alignof_test() {
// CHECK: store i64 4, i64*
var xs = Builtin.sizeof(Int.self)
// CHECK: store i64 4, i64*
var xa = Builtin.alignof(Int.self)
// CHECK: store i64 1, i64*
var ys = Builtin.sizeof(Bool.self)
// CHECK: store i64 1, i64*
var ya = Builtin.alignof(Bool.self)
}
// CHECK: define hidden {{.*}}void @_T08builtins27generic_sizeof_alignof_testyxlF(
func generic_sizeof_alignof_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 11
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[SIZE:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: store i64 [[SIZE]], i64* [[S:%.*]]
var s = Builtin.sizeof(T.self)
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 12
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[T2:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: [[T3:%.*]] = and i64 [[T2]], 65535
// CHECK-NEXT: [[ALIGN:%.*]] = add i64 [[T3]], 1
// CHECK-NEXT: store i64 [[ALIGN]], i64* [[A:%.*]]
var a = Builtin.alignof(T.self)
}
// CHECK: define hidden {{.*}}void @_T08builtins21generic_strideof_testyxlF(
func generic_strideof_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 13
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[STRIDE:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: store i64 [[STRIDE]], i64* [[S:%.*]]
var s = Builtin.strideof(T.self)
}
class X {}
class Y {}
func move(_ ptr: Builtin.RawPointer) {
var temp : Y = Builtin.take(ptr)
// CHECK: define hidden {{.*}}void @_T08builtins4move{{[_0-9a-zA-Z]*}}F
// CHECK: [[SRC:%.*]] = bitcast i8* {{%.*}} to [[Y]]**
// CHECK-NEXT: [[VAL:%.*]] = load [[Y]]*, [[Y]]** [[SRC]]
// CHECK-NEXT: store [[Y]]* [[VAL]], [[Y]]** {{%.*}}
}
func allocDealloc(_ size: Builtin.Word, align: Builtin.Word) {
var ptr = Builtin.allocRaw(size, align)
Builtin.deallocRaw(ptr, size, align)
}
func fence_test() {
// CHECK: fence acquire
Builtin.fence_acquire()
// CHECK: fence singlethread acq_rel
Builtin.fence_acqrel_singlethread()
}
func cmpxchg_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32, b: Builtin.Int32) {
// rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers
// CHECK: [[Z_RES:%.*]] = cmpxchg i32* {{.*}}, i32 {{.*}}, i32 {{.*}} acquire acquire
// CHECK: [[Z_VAL:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 0
// CHECK: [[Z_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 1
// CHECK: store i32 [[Z_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[Z_SUCCESS]], i1* {{.*}}, align 1
var (z, zSuccess) = Builtin.cmpxchg_acquire_acquire_Int32(ptr, a, b)
// CHECK: [[Y_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} monotonic monotonic
// CHECK: [[Y_VAL:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 0
// CHECK: [[Y_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 1
// CHECK: store i32 [[Y_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[Y_SUCCESS]], i1* {{.*}}, align 1
var (y, ySuccess) = Builtin.cmpxchg_monotonic_monotonic_volatile_Int32(ptr, a, b)
// CHECK: [[X_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} singlethread acquire monotonic
// CHECK: [[X_VAL:%.*]] = extractvalue { i32, i1 } [[X_RES]], 0
// CHECK: [[X_SUCCESS:%.*]] = extractvalue { i32, i1 } [[X_RES]], 1
// CHECK: store i32 [[X_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[X_SUCCESS]], i1* {{.*}}, align 1
var (x, xSuccess) = Builtin.cmpxchg_acquire_monotonic_volatile_singlethread_Int32(ptr, a, b)
// CHECK: [[W_RES:%.*]] = cmpxchg volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst
// CHECK: [[W_VAL:%.*]] = extractvalue { i64, i1 } [[W_RES]], 0
// CHECK: [[W_SUCCESS:%.*]] = extractvalue { i64, i1 } [[W_RES]], 1
// CHECK: [[W_VAL_PTR:%.*]] = inttoptr i64 [[W_VAL]] to i8*
// CHECK: store i8* [[W_VAL_PTR]], i8** {{.*}}, align 8
// CHECK: store i1 [[W_SUCCESS]], i1* {{.*}}, align 1
var (w, wSuccess) = Builtin.cmpxchg_seqcst_seqcst_volatile_singlethread_RawPointer(ptr, ptr, ptr)
// CHECK: [[V_RES:%.*]] = cmpxchg weak volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst
// CHECK: [[V_VAL:%.*]] = extractvalue { i64, i1 } [[V_RES]], 0
// CHECK: [[V_SUCCESS:%.*]] = extractvalue { i64, i1 } [[V_RES]], 1
// CHECK: [[V_VAL_PTR:%.*]] = inttoptr i64 [[V_VAL]] to i8*
// CHECK: store i8* [[V_VAL_PTR]], i8** {{.*}}, align 8
// CHECK: store i1 [[V_SUCCESS]], i1* {{.*}}, align 1
var (v, vSuccess) = Builtin.cmpxchg_seqcst_seqcst_weak_volatile_singlethread_RawPointer(ptr, ptr, ptr)
}
func atomicrmw_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32,
ptr2: Builtin.RawPointer) {
// CHECK: atomicrmw add i32* {{.*}}, i32 {{.*}} acquire
var z = Builtin.atomicrmw_add_acquire_Int32(ptr, a)
// CHECK: atomicrmw volatile max i32* {{.*}}, i32 {{.*}} monotonic
var y = Builtin.atomicrmw_max_monotonic_volatile_Int32(ptr, a)
// CHECK: atomicrmw volatile xchg i32* {{.*}}, i32 {{.*}} singlethread acquire
var x = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_Int32(ptr, a)
// rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers
// CHECK: atomicrmw volatile xchg i64* {{.*}}, i64 {{.*}} singlethread acquire
var w = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_RawPointer(ptr, ptr2)
}
func addressof_test(_ a: inout Int, b: inout Bool) {
// CHECK: bitcast i32* {{.*}} to i8*
var ap : Builtin.RawPointer = Builtin.addressof(&a)
// CHECK: bitcast i1* {{.*}} to i8*
var bp : Builtin.RawPointer = Builtin.addressof(&b)
}
func fneg_test(_ half: Builtin.FPIEEE16,
single: Builtin.FPIEEE32,
double: Builtin.FPIEEE64)
-> (Builtin.FPIEEE16, Builtin.FPIEEE32, Builtin.FPIEEE64)
{
// CHECK: fsub half 0xH8000, {{%.*}}
// CHECK: fsub float -0.000000e+00, {{%.*}}
// CHECK: fsub double -0.000000e+00, {{%.*}}
return (Builtin.fneg_FPIEEE16(half),
Builtin.fneg_FPIEEE32(single),
Builtin.fneg_FPIEEE64(double))
}
// The call to the builtins should get removed before we reach IRGen.
func testStaticReport(_ b: Bool, ptr: Builtin.RawPointer) -> () {
Builtin.staticReport(b, b, ptr);
return Builtin.staticReport(b, b, ptr);
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins12testCondFail{{[_0-9a-zA-Z]*}}F(i1, i1)
func testCondFail(_ b: Bool, c: Bool) {
// CHECK: br i1 %0, label %[[FAIL:.*]], label %[[CONT:.*]]
Builtin.condfail(b)
// CHECK: <label>:[[CONT]]
// CHECK: br i1 %1, label %[[FAIL2:.*]], label %[[CONT:.*]]
Builtin.condfail(c)
// CHECK: <label>:[[CONT]]
// CHECK: ret void
// CHECK: <label>:[[FAIL]]
// CHECK: call void @llvm.trap()
// CHECK: unreachable
// CHECK: <label>:[[FAIL2]]
// CHECK: call void @llvm.trap()
// CHECK: unreachable
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins8testOnce{{[_0-9a-zA-Z]*}}F(i8*, i8*) {{.*}} {
// CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]*
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: br i1 [[IS_DONE]], label %[[DONE:.*]], label %[[NOT_DONE:.*]]
// CHECK-objc: [[NOT_DONE]]:
// CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1, i8* undef)
// CHECK-objc: br label %[[DONE]]
// CHECK-objc: [[DONE]]:
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]])
func testOnce(_ p: Builtin.RawPointer, f: @escaping @convention(thin) () -> ()) {
Builtin.once(p, f)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins19testOnceWithContext{{[_0-9a-zA-Z]*}}F(i8*, i8*, i8*) {{.*}} {
// CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]*
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: br i1 [[IS_DONE]], label %[[DONE:.*]], label %[[NOT_DONE:.*]]
// CHECK-objc: [[NOT_DONE]]:
// CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1, i8* %2)
// CHECK-objc: br label %[[DONE]]
// CHECK-objc: [[DONE]]:
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]])
func testOnceWithContext(_ p: Builtin.RawPointer, f: @escaping @convention(thin) (Builtin.RawPointer) -> (), k: Builtin.RawPointer) {
Builtin.onceWithContext(p, f, k)
}
class C {}
struct S {}
@objc class O {}
@objc protocol OP1 {}
@objc protocol OP2 {}
protocol P {}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins10canBeClass{{[_0-9a-zA-Z]*}}F
func canBeClass<T>(_ f: @escaping (Builtin.Int8) -> (), _: T) {
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(O.self))
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(OP1.self))
typealias ObjCCompo = OP1 & OP2
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(ObjCCompo.self))
// CHECK: call {{.*}}void {{%.*}}(i8 0
f(Builtin.canBeClass(S.self))
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(C.self))
// CHECK: call {{.*}}void {{%.*}}(i8 0
f(Builtin.canBeClass(P.self))
typealias MixedCompo = OP1 & P
// CHECK: call {{.*}}void {{%.*}}(i8 0
f(Builtin.canBeClass(MixedCompo.self))
// CHECK: call {{.*}}void {{%.*}}(i8 2
f(Builtin.canBeClass(T.self))
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15destroyPODArray{{[_0-9a-zA-Z]*}}F(i8*, i64)
// CHECK-NOT: loop:
// CHECK: ret void
func destroyPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) {
Builtin.destroyArray(Int.self, array, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins18destroyNonPODArray{{[_0-9a-zA-Z]*}}F(i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: call {{.*}} @swift_rt_swift_release
// CHECK: br label %iter
func destroyNonPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) {
Builtin.destroyArray(C.self, array, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15destroyGenArrayyBp_Bw5countxtlF(i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
// CHECK-NOT: loop:
// CHECK: call void %destroyArray
func destroyGenArray<T>(_ array: Builtin.RawPointer, count: Builtin.Word, _: T) {
Builtin.destroyArray(T.self, array, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins12copyPODArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
func copyPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(Int.self, dest, src, count)
Builtin.takeArrayFrontToBack(Int.self, dest, src, count)
Builtin.takeArrayBackToFront(Int.self, dest, src, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins11copyBTArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: call {{.*}} @swift_rt_swift_retain
// CHECK: br label %iter
// CHECK: mul nuw i64 8, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 8, i1 false)
// CHECK: mul nuw i64 8, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 8, i1 false)
func copyBTArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(C.self, dest, src, count)
Builtin.takeArrayFrontToBack(C.self, dest, src, count)
Builtin.takeArrayBackToFront(C.self, dest, src, count)
}
struct W { weak var c: C? }
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15copyNonPODArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: swift_weakCopyInit
// CHECK: iter{{.*}}:
// CHECK: loop{{.*}}:
// CHECK: swift_weakTakeInit
// CHECK: iter{{.*}}:
// CHECK: loop{{.*}}:
// CHECK: swift_weakTakeInit
func copyNonPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(W.self, dest, src, count)
Builtin.takeArrayFrontToBack(W.self, dest, src, count)
Builtin.takeArrayBackToFront(W.self, dest, src, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins12copyGenArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithCopy
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithTakeFrontToBack
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithTakeBackToFront
func copyGenArray<T>(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word, _: T) {
Builtin.copyArray(T.self, dest, src, count)
Builtin.takeArrayFrontToBack(T.self, dest, src, count)
Builtin.takeArrayBackToFront(T.self, dest, src, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins24conditionallyUnreachableyyF
// CHECK-NEXT: entry
// CHECK-NEXT: unreachable
func conditionallyUnreachable() {
Builtin.conditionallyUnreachable()
}
struct Abc {
var value : Builtin.Word
}
// CHECK-LABEL define hidden {{.*}}@_T08builtins22assumeNonNegative_testBwAA3AbcVzF
func assumeNonNegative_test(_ x: inout Abc) -> Builtin.Word {
// CHECK: load {{.*}}, !range ![[R:[0-9]+]]
return Builtin.assumeNonNegative_Word(x.value)
}
@inline(never)
func return_word(_ x: Builtin.Word) -> Builtin.Word {
return x
}
// CHECK-LABEL define hidden {{.*}}@_T08builtins23assumeNonNegative_test2BwAA3AbcVzF
func assumeNonNegative_test2(_ x: Builtin.Word) -> Builtin.Word {
// CHECK: call {{.*}}, !range ![[R]]
return Builtin.assumeNonNegative_Word(return_word(x))
}
struct Empty {}
struct Pair { var i: Int, b: Bool }
// CHECK-LABEL: define hidden {{.*}}i64 @_T08builtins15zeroInitializerAA5EmptyV_AA4PairVtyF() {{.*}} {
// CHECK: [[ALLOCA:%.*]] = alloca { i64 }
// CHECK: bitcast
// CHECK: lifetime.start
// CHECK: [[EMPTYPAIR:%.*]] = bitcast { i64 }* [[ALLOCA]]
// CHECK: [[PAIR:%.*]] = getelementptr inbounds {{.*}} [[EMPTYPAIR]], i32 0, i32 0
// CHECK: [[FLDI:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 0
// CHECK: store i32 0, i32* [[FLDI]]
// CHECK: [[FLDB:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 1
// CHECK: store i1 false, i1* [[FLDB]]
// CHECK: [[RET:%.*]] = getelementptr inbounds {{.*}} [[ALLOCA]], i32 0, i32 0
// CHECK: [[RES:%.*]] = load i64, i64* [[RET]]
// CHECK: ret i64 [[RES]]
func zeroInitializer() -> (Empty, Pair) {
return (Builtin.zeroInitializer(), Builtin.zeroInitializer())
}
// CHECK-LABEL: define hidden {{.*}}i64 @_T08builtins20zeroInitializerTupleAA5EmptyV_AA4PairVtyF() {{.*}} {
// CHECK: [[ALLOCA:%.*]] = alloca { i64 }
// CHECK: bitcast
// CHECK: lifetime.start
// CHECK: [[EMPTYPAIR:%.*]] = bitcast { i64 }* [[ALLOCA]]
// CHECK: [[PAIR:%.*]] = getelementptr inbounds {{.*}} [[EMPTYPAIR]], i32 0, i32 0
// CHECK: [[FLDI:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 0
// CHECK: store i32 0, i32* [[FLDI]]
// CHECK: [[FLDB:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 1
// CHECK: store i1 false, i1* [[FLDB]]
// CHECK: [[RET:%.*]] = getelementptr inbounds {{.*}} [[ALLOCA]], i32 0, i32 0
// CHECK: [[RES:%.*]] = load i64, i64* [[RET]]
// CHECK: ret i64 [[RES]]
func zeroInitializerTuple() -> (Empty, Pair) {
return Builtin.zeroInitializer()
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins20zeroInitializerEmptyyyF() {{.*}} {
// CHECK: ret void
func zeroInitializerEmpty() {
return Builtin.zeroInitializer()
}
// ----------------------------------------------------------------------------
// isUnique variants
// ----------------------------------------------------------------------------
// CHECK: define hidden {{.*}}void @_T08builtins26acceptsBuiltinNativeObjectyBoSgzF([[BUILTIN_NATIVE_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
func acceptsBuiltinNativeObject(_ ref: inout Builtin.NativeObject?) {}
// native
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BoSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool {
return Builtin.isUnique(&ref)
}
// native nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BozF(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.NativeObject) -> Bool {
return Builtin.isUnique(&ref)
}
// native pinned
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BoSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUniqueOrPinned(_ ref: inout Builtin.NativeObject?) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// native pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BozF(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native(%swift.refcounted* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.NativeObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// CHECK: define hidden {{.*}}void @_T08builtins27acceptsBuiltinUnknownObjectyBOSgzF([[BUILTIN_UNKNOWN_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
func acceptsBuiltinUnknownObject(_ ref: inout Builtin.UnknownObject?) {}
// ObjC
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BOSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_UNKNOWN_OBJECT_TY]]* %0 to %objc_object**
// CHECK-NEXT: load %objc_object*, %objc_object** %1
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC(%objc_object* %2)
// CHECK-NEXT: ret i1 %3
func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool {
return Builtin.isUnique(&ref)
}
// ObjC nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BOzF(%objc_object** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %objc_object*, %objc_object** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull(%objc_object* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool {
return Builtin.isUnique(&ref)
}
// ObjC pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BOzF(%objc_object** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %objc_object*, %objc_object** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedOrPinnedNonObjC_nonNull(%objc_object* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.UnknownObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// BridgeObject nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull_bridgeObject(%swift.bridge* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUnique(&ref)
}
// Bridge pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedOrPinnedNonObjC_nonNull_bridgeObject(%swift.bridge* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// BridgeObject nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins15isUnique_nativeBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUnique_native(&ref)
}
// Bridge pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins23isUniqueOrPinned_nativeBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUniqueOrPinned_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUniqueOrPinned_native(&ref)
}
// ImplicitlyUnwrappedOptional argument to isUnique.
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins11isUniqueIUOBi1_BoSgzF(%{{.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted*
// CHECK: ret i1
func isUniqueIUO(_ ref: inout Builtin.NativeObject?) -> Bool {
var iuo : Builtin.NativeObject! = ref
return Builtin.isUnique(&iuo)
}
// CHECK-LABEL: define {{.*}} @{{.*}}generic_ispod_test
func generic_ispod_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 12
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[FLAGS:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: [[ISNOTPOD:%.*]] = and i64 [[FLAGS]], 65536
// CHECK-NEXT: [[ISPOD:%.*]] = icmp eq i64 [[ISNOTPOD]], 0
// CHECK-NEXT: store i1 [[ISPOD]], i1* [[S:%.*]]
var s = Builtin.ispod(T.self)
}
// CHECK-LABEL: define {{.*}} @{{.*}}ispod_test
func ispod_test() {
// CHECK: store i1 true, i1*
// CHECK: store i1 false, i1*
var t = Builtin.ispod(Int.self)
var f = Builtin.ispod(Builtin.NativeObject)
}
// CHECK-LABEL: define {{.*}} @{{.*}}is_same_metatype
func is_same_metatype_test(_ t1: Any.Type, _ t2: Any.Type) {
// CHECK: [[MT1_AS_PTR:%.*]] = bitcast %swift.type* %0 to i8*
// CHECK: [[MT2_AS_PTR:%.*]] = bitcast %swift.type* %1 to i8*
// CHECK: icmp eq i8* [[MT1_AS_PTR]], [[MT2_AS_PTR]]
var t = Builtin.is_same_metatype(t1, t2)
}
// CHECK-LABEL: define {{.*}} @{{.*}}generic_unsafeGuaranteed_test
// CHECK: call void @{{.*}}swift_{{.*}}etain({{.*}}* %0)
// CHECK: call void @{{.*}}swift_{{.*}}elease({{.*}}* %0)
// CHECK: ret {{.*}}* %0
func generic_unsafeGuaranteed_test<T: AnyObject>(_ t : T) -> T {
let (g, _) = Builtin.unsafeGuaranteed(t)
return g
}
// CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteed_test
// CHECK: [[LOCAL:%.*]] = alloca %swift.refcounted*
// CHECK: call void @swift_rt_swift_retain(%swift.refcounted* %0)
// CHECK: store %swift.refcounted* %0, %swift.refcounted** [[LOCAL]]
// CHECK: call void @swift_rt_swift_release(%swift.refcounted* %0)
// CHECK: ret %swift.refcounted* %0
func unsafeGuaranteed_test(_ x: Builtin.NativeObject) -> Builtin.NativeObject {
var (g,t) = Builtin.unsafeGuaranteed(x)
Builtin.unsafeGuaranteedEnd(t)
return g
}
// CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteedEnd_test
// CHECK-NEXT: {{.*}}:
// CHECK-NEXT: ret void
func unsafeGuaranteedEnd_test(_ x: Builtin.Int8) {
Builtin.unsafeGuaranteedEnd(x)
}
// CHECK-LABEL: define {{.*}} @{{.*}}atomicload
func atomicload(_ p: Builtin.RawPointer) {
// CHECK: [[A:%.*]] = load atomic i8*, i8** {{%.*}} unordered, align 8
let a: Builtin.RawPointer = Builtin.atomicload_unordered_RawPointer(p)
// CHECK: [[B:%.*]] = load atomic i32, i32* {{%.*}} singlethread monotonic, align 4
let b: Builtin.Int32 = Builtin.atomicload_monotonic_singlethread_Int32(p)
// CHECK: [[C:%.*]] = load atomic volatile i64, i64* {{%.*}} singlethread acquire, align 8
let c: Builtin.Int64 =
Builtin.atomicload_acquire_volatile_singlethread_Int64(p)
// CHECK: [[D0:%.*]] = load atomic volatile i32, i32* {{%.*}} seq_cst, align 4
// CHECK: [[D:%.*]] = bitcast i32 [[D0]] to float
let d: Builtin.FPIEEE32 = Builtin.atomicload_seqcst_volatile_FPIEEE32(p)
// CHECK: store atomic i8* [[A]], i8** {{%.*}} unordered, align 8
Builtin.atomicstore_unordered_RawPointer(p, a)
// CHECK: store atomic i32 [[B]], i32* {{%.*}} singlethread monotonic, align 4
Builtin.atomicstore_monotonic_singlethread_Int32(p, b)
// CHECK: store atomic volatile i64 [[C]], i64* {{%.*}} singlethread release, align 8
Builtin.atomicstore_release_volatile_singlethread_Int64(p, c)
// CHECK: [[D1:%.*]] = bitcast float [[D]] to i32
// CHECK: store atomic volatile i32 [[D1]], i32* {{.*}} seq_cst, align 4
Builtin.atomicstore_seqcst_volatile_FPIEEE32(p, d)
}
// CHECK: ![[R]] = !{i64 0, i64 9223372036854775807}
| apache-2.0 | 82c9d6389c20e3b27cdd66837b89753c | 39.070457 | 237 | 0.626492 | 3.277093 | false | true | false | false |
USAssignmentWarehouse/EnglishNow | EnglishNow/Model/Profile/Rating.swift | 1 | 2121 | //
// Rating.swift
// EnglishNow
//
// Created by GeniusDoan on 6/29/17.
// Copyright © 2017 IceTeaViet. All rights reserved.
//
import Foundation
class Rating: NSObject, NSCoding {
var listening: Double!
var pronounciation: Double!
var fluency: Double!
var vocabulary: Double!
override init() {
super.init()
listening = 0
pronounciation = 0
fluency = 0
vocabulary = 0
}
func encode(with aCoder: NSCoder) {
aCoder.encode(listening, forKey: "listening")
aCoder.encode(pronounciation, forKey: "pronounciation")
aCoder.encode(fluency, forKey: "fluency")
aCoder.encode(vocabulary, forKey: "vocabulary")
}
required init?(coder aDecoder: NSCoder) {
listening = aDecoder.decodeObject(forKey: "listening") as! Double
pronounciation = aDecoder.decodeObject(forKey: "pronounciation") as! Double
fluency = aDecoder.decodeObject(forKey: "fluency") as! Double
vocabulary = aDecoder.decodeObject(forKey: "vocabulary") as! Double
}
init(dictionary: NSDictionary) {
super.init()
if let listening = dictionary["listening"] as? Double {
self.listening = listening
} else {
listening = 0
}
if let pronounciation = dictionary["pronounciation"] as? Double {
self.pronounciation = pronounciation
} else {
pronounciation = 0
}
if let fluency = dictionary["fluency"] as? Double {
self.fluency = fluency
} else {
fluency = 0
}
if let vocabulary = dictionary["vocabulary"] as? Double {
self.vocabulary = vocabulary
} else {
vocabulary = 0
}
}
func dictionary() -> [String: AnyObject] {
return ["listening": listening as AnyObject,
"pronounciation": pronounciation as AnyObject,
"fluency": fluency as AnyObject,
"vocabulary": vocabulary as AnyObject]
}
}
| apache-2.0 | 78c28f6f0d9706284541bdaf663440f1 | 27.648649 | 83 | 0.575472 | 4.568966 | false | false | false | false |
sergii-frost/FrostComponents | FrostComponents/Classes/FrostButton/FRButton.swift | 1 | 1954 | //
// FRButton.swift
// FrostComponents
//
// Created by Sergii Frost on 2017-08-03.
//
import UIKit
@IBDesignable
open class FRButton: UIButton {
@IBInspectable public var borderWidth: CGFloat = 0.0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
@IBInspectable public var disabledColor: UIColor? {
didSet {
setBackgroundImage(UIImage.image(fromColor: disabledColor), for: .disabled)
}
}
@IBInspectable public var normalColor: UIColor? {
didSet {
setBackgroundImage(UIImage.image(fromColor: normalColor), for: .normal)
}
}
@IBInspectable public var highlightedColor: UIColor? {
didSet {
setBackgroundImage(UIImage.image(fromColor: highlightedColor), for: .highlighted)
}
}
@IBInspectable public var selectedColor: UIColor? {
didSet {
setBackgroundImage(UIImage.image(fromColor: selectedColor), for: .selected)
}
}
public var style: FRButtonStyle? {
didSet {
stylize(from: style)
}
}
fileprivate func stylize(from style: FRButtonStyle?) {
guard let safeStyle = style else {
return
}
borderWidth = safeStyle.borderWidth
borderColor = safeStyle.borderColor
cornerRadius = safeStyle.cornerRadius
normalColor = safeStyle.normalColor
disabledColor = safeStyle.disabledColor
selectedColor = safeStyle.selectedColor
highlightedColor = safeStyle.highlightedColor
let states: [UIControlState] = [.normal, .highlighted, .selected, .disabled]
states.forEach({state in
setTitleColor(safeStyle.titleColor, for: state)
})
}
}
| mit | 361ffca1927df6edb983fc543c42a013 | 25.767123 | 93 | 0.60696 | 5.142105 | false | false | false | false |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/WithLatestFrom.swift | 7 | 5836 | //
// WithLatestFrom.swift
// RxSwift
//
// Created by Yury Korolev on 10/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- note: Elements emitted by self before the second source has emitted any values will be omitted.
- parameter second: Second observable source.
- parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<Source: ObservableConvertibleType, ResultType>(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Observable<ResultType> {
WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: resultSelector)
}
/**
Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- note: Elements emitted by self before the second source has emitted any values will be omitted.
- parameter second: Second observable source.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<Source: ObservableConvertibleType>(_ second: Source) -> Observable<Source.Element> {
WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: { $1 })
}
}
final private class WithLatestFromSink<FirstType, SecondType, Observer: ObserverType>
: Sink<Observer>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias ResultType = Observer.Element
typealias Parent = WithLatestFrom<FirstType, SecondType, ResultType>
typealias Element = FirstType
private let parent: Parent
fileprivate var lock = RecursiveLock()
fileprivate var latest: SecondType?
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let sndSubscription = SingleAssignmentDisposable()
let sndO = WithLatestFromSecond(parent: self, disposable: sndSubscription)
sndSubscription.setDisposable(self.parent.second.subscribe(sndO))
let fstSubscription = self.parent.first.subscribe(self)
return Disposables.create(fstSubscription, sndSubscription)
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func synchronized_on(_ event: Event<Element>) {
switch event {
case let .next(value):
guard let latest = self.latest else { return }
do {
let res = try self.parent.resultSelector(value, latest)
self.forwardOn(.next(res))
} catch let e {
self.forwardOn(.error(e))
self.dispose()
}
case .completed:
self.forwardOn(.completed)
self.dispose()
case let .error(error):
self.forwardOn(.error(error))
self.dispose()
}
}
}
final private class WithLatestFromSecond<FirstType, SecondType, Observer: ObserverType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias ResultType = Observer.Element
typealias Parent = WithLatestFromSink<FirstType, SecondType, Observer>
typealias Element = SecondType
private let parent: Parent
private let disposable: Disposable
var lock: RecursiveLock {
self.parent.lock
}
init(parent: Parent, disposable: Disposable) {
self.parent = parent
self.disposable = disposable
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func synchronized_on(_ event: Event<Element>) {
switch event {
case let .next(value):
self.parent.latest = value
case .completed:
self.disposable.dispose()
case let .error(error):
self.parent.forwardOn(.error(error))
self.parent.dispose()
}
}
}
final private class WithLatestFrom<FirstType, SecondType, ResultType>: Producer<ResultType> {
typealias ResultSelector = (FirstType, SecondType) throws -> ResultType
fileprivate let first: Observable<FirstType>
fileprivate let second: Observable<SecondType>
fileprivate let resultSelector: ResultSelector
init(first: Observable<FirstType>, second: Observable<SecondType>, resultSelector: @escaping ResultSelector) {
self.first = first
self.second = second
self.resultSelector = resultSelector
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType {
let sink = WithLatestFromSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit | f4a4a6f95b5a020f1d06bd750c669200 | 37.642384 | 201 | 0.681919 | 5.140969 | false | true | false | false |
noahemmet/WorldKit | WorldKit/Sources/CanvasView.swift | 1 | 2399 | ////
//// CanvasView.swift
//// WorldKit
////
//// Created by Noah Emmet on 2/19/16.
//// Copyright © 2016 Sticks. All rights reserved.
////
//
//import Foundation
//
//public class CanvasView: View {
// internal let stackView: NSStackView
// internal let worldView: WorldView
// internal let settingsView: SettingsView
//
// public init(worldView: WorldView) {
// self.worldView = worldView
// self.settingsView = SettingsView(frame: Rect(x: 0, y: 0, width: worldView.frame.size.width, height: 100))
//
// stackView = NSStackView(views: [worldView, self.settingsView])
// stackView.translatesAutoresizingMaskIntoConstraints = false
//// stackView.alignment = .Leading
//// stackView.distribution = .Fill
// stackView.orientation = .Vertical
// super.init(frame: Rect(x: 0, y: 0, width: 480, height: 580))
//
// self.settingsView.delegate = self
//
// self.translatesAutoresizingMaskIntoConstraints = false
// addSubview(stackView)
//
//// self.settingsView.widthAnchor.constraintEqualToAnchor(settingsView.scrollView.widthAnchor, multiplier: 1)
//// self.settingsView.heightAnchor.constraintEqualToAnchor(settingsView.scrollView.heightAnchor, multiplier: 1)
// self.settingsView.widthAnchor.constraintEqualToAnchor(worldView.widthAnchor).active = true
// self.settingsView.heightAnchor.constraintEqualToConstant(100).active = true
//
//// stackView.topAnchor.constraintEqualToAnchor(worldView.bottomAnchor).active = true
//// stackView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor).active = true
//
// self.heightAnchor.constraintEqualToAnchor(stackView.heightAnchor, multiplier: 1.0)
// self.widthAnchor.constraintEqualToAnchor(stackView.widthAnchor, multiplier: 1.0)
//// stackView.widthAnchor.constraintEqualToAnchor(self.widthAnchor, multiplier: 1.0).active = true
//// stackView.heightAnchor.constraintEqualToAnchor(self.heightAnchor, multiplier: 1.0).active = true;
//// stackView.heightAnchor.constraintEqualToAnchor(stackView.intri, multiplier: 1.0).active = true;
// }
//
//
// required public init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
//
//}
//
//extension CanvasView: SettingsViewDelegate {
// func settingsView(settingsView: SettingsView, didSelectSetting setting: String) {
// worldView.paused = !worldView.paused
// Swift.print(worldView.paused ? "pause" : "resume")
// }
//} | apache-2.0 | 4f3c62b130ac38383b80fa5b8b6df522 | 39.661017 | 113 | 0.742702 | 3.892857 | false | false | false | false |
AlbertWu0212/MyDailyTodo | MyDailyTodo/MyDailyTodo/Checklist.swift | 1 | 1173 | //
// Checklist.swift
// MyDailyTodo
//
// Created by WuZhengBin on 16/7/4.
// Copyright © 2016年 WuZhengBin. All rights reserved.
//
import UIKit
import Foundation
class Checklist: NSObject, NSCoding {
var name = ""
var iconName: String
var items = [ChecklistItem]()
// MARK: NSCoding protocol
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObjectForKey("Name") as! String
items = aDecoder.decodeObjectForKey("Items") as! [ChecklistItem]
iconName = aDecoder.decodeObjectForKey("IconName") as! String
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "Name")
aCoder.encodeObject(items, forKey: "Items")
aCoder.encodeObject(iconName, forKey: "IconName")
}
// MARK: initial
convenience init(name: String) {
self.init(name: name, iconName: "No Icon")
}
init(name: String, iconName: String) {
self.name = name
self.iconName = iconName
super.init()
}
// MARK: API Methods
func countUncheckedItems() -> Int {
var count = 0
for item in items where !item.checked {
count += 1
}
return count
}
}
| mit | 314a55f3764016113bd214c322309b7f | 21.075472 | 68 | 0.654701 | 3.952703 | false | false | false | false |
mysangle/algorithm-study | valid-anagram/ValidAnagram.swift | 1 | 706 | /**
* isAnagram uses sorting
* isAnagram2 uses hash table
*
* isAnagram2 is faster then isAnagram
*/
func isAnagram(_ s: String, _ t: String) -> Bool {
return s.characters.sorted() == t.characters.sorted()
}
func isAnagram2(_ s: String, _ t: String) -> Bool {
var ss = [Character: Int]()
for c in s.characters {
if ss[c] != nil {
ss[c] = ss[c]! + 1
} else {
ss[c] = 1
}
}
for c in t.characters {
if ss[c] != nil {
ss[c] = ss[c]! - 1
if ss[c] == 0 {
ss.removeValue(forKey: c)
}
} else {
return false
}
}
return ss.count == 0
}
| mit | ecd2b7c7c1aa25c7ca3804663f4880a2 | 20.393939 | 57 | 0.454674 | 3.443902 | false | false | false | false |
4faramita/TweeBox | TweeBox/TwitterAttributedContent.swift | 1 | 8359 | //
// TwitterAttributedContent.swift
// TweeBox
//
// Created by 4faramita on 2017/8/19.
// Copyright © 2017年 4faramita. All rights reserved.
//
import Foundation
import UIKit
import YYText
import SafariServices
class TwitterAttributedContent {
public var tweet: Tweet?
public var user: TwitterUser?
private var plainString: String {
return (tweet?.text) ?? (user?.description) ?? ""
}
private var attributed: NSMutableAttributedString!
private var tweetEntity: Entity? {
return (tweet?.entities) ?? (user?.entities)
}
init(_ tweet: Tweet) {
self.tweet = tweet
}
init(_ user: TwitterUser) {
self.user = user
}
public var attributedString: NSAttributedString {
return getAttributedContent()
}
private func changeColorAttribute(to entity: TweetEntity, with color: UIColor?) -> NSRange? {
let start = plainString.index(plainString.startIndex, offsetBy: entity.indices[0], limitedBy: plainString.endIndex)
let end = plainString.index(plainString.startIndex, offsetBy: entity.indices[1], limitedBy: plainString.endIndex)
if let start = start, let end = end {
let stringToBeRender = String(plainString[start..<end])
let range = (attributed.string as NSString).range(of: stringToBeRender)
// attributed.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
if let url = entity as? TweetURL {
attributed.yy_setTextHighlight(
range,
color: color ?? Constants.themeColor,
backgroundColor: nil,
userInfo: nil,
tapAction: { (containerView, attributedString, range, rect) in
if let realURL = url.url {
let safariViewController = SFSafariViewController(url: realURL, entersReaderIfAvailable: true)
containerView.yy_viewController?.present(safariViewController, animated: true)
}
},
longPressAction: nil
)
} else if entity is Hashtag {
attributed.yy_setTextHighlight(
range,
color: color ?? Constants.themeColor,
backgroundColor: nil,
userInfo: nil,
tapAction: { (containerView, attributedString, range, rect) in
if var sourceViewController = containerView.yy_viewController as? TweetClickableContentProtocol {
let keyword = (attributedString.string as NSString).substring(with: range)
sourceViewController.keyword = keyword
sourceViewController.setAndPerformSegueForHashtag()
// sourceViewController.performSegue(withIdentifier: "Show Tweets with Hashtag", sender: self)
}
},
longPressAction: nil
)
} else if entity is Mention {
attributed.yy_setTextHighlight(
range,
color: color ?? Constants.themeColor,
backgroundColor: nil,
userInfo: nil,
tapAction: { [weak self] (containerView, attributedString, range, rect) in
if var sourceViewController = containerView.yy_viewController as? TweetClickableContentProtocol {
let keyword = (attributedString.string as NSString).substring(with: range)
sourceViewController.keyword = keyword
SingleUser(
params: UserParams(userID: nil, screenName: keyword),
resourceURL: ResourceURL.user_show
).fetchData { (singleUser) in
if let user = singleUser {
sourceViewController.fetchedUser = user
sourceViewController.performSegue(withIdentifier: "profileImageTapped", sender: self)
} else {
sourceViewController.alertForNoSuchUser(viewController: sourceViewController as! UIViewController)
}
}
}
},
longPressAction: nil
)
} else {
attributed.yy_setTextHighlight(
range,
color: color ?? Constants.themeColor,
backgroundColor: nil,
userInfo: nil,
tapAction: { (containerView, attributedString, range, rect) in
print(">>> Unknown entity >> \(attributedString)") },
longPressAction: nil
)
}
return range
} else {
return nil
}
}
// fileprivate func fetchUser(keyword: String, _ handler: @escaping (TwitterUser?) -> Void) {
//
// SingleUser(
// userParams: UserParams(userID: nil, screenName: keyword),
// resourceURL: ResourceURL.user_show
// ).fetchData { (singleUser) in
// handler(singleUser)
// }
// }
private func getAttributedContent() -> NSAttributedString {
attributed = NSMutableAttributedString.init(string: plainString.stringByDecodingHTMLEntities)
let fullRange = NSRange.init(location: 0, length: attributed.length)
// Set unified paragraph style
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .natural
attributed.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: fullRange)
if user != nil {
let descriptionFont = UIFont.preferredFont(forTextStyle: .caption2)
attributed.addAttribute(NSAttributedStringKey.font, value: descriptionFont, range: fullRange)
attributed.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.white, range: fullRange)
} else {
let fontColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.75)
attributed.addAttribute(NSAttributedStringKey.foregroundColor, value: fontColor, range: fullRange)
}
if let hashtags = tweetEntity?.hashtags {
for hashtag in hashtags {
let _ = changeColorAttribute(to: hashtag, with: Constants.lightenThemeColor)
}
}
if let mentions = tweetEntity?.userMentions {
for mention in mentions {
let _ = changeColorAttribute(to: mention, with: Constants.themeColor)
}
}
if let urls = tweetEntity?.urls {
for url in urls {
if let range = changeColorAttribute(to: url, with: Constants.themeColor),
let urlString = url.displayURL?.absoluteString {
attributed.mutableString.replaceCharacters(in: range, with: urlString)
}
}
}
if let symbols = tweetEntity?.symbols {
for symbol in symbols {
let _ = changeColorAttribute(to: symbol, with: Constants.themeColor)
}
}
if let media = tweetEntity?.media, media.count > 0 {
let firstMedia = media[0]
if let range = changeColorAttribute(to: firstMedia, with: nil) {
attributed.mutableString.replaceCharacters(in: range, with: "")
}
}
return attributed
}
}
| mit | de1388ee183ded58bb941e49fd49c40b | 38.601896 | 134 | 0.528124 | 6.103725 | false | false | false | false |
barrymcandrews/aurora-ios | Aurora/DragAndDropCollectionView.swift | 1 | 12397 | //
// KDDragAndDropCollectionView.swift
// KDDragAndDropCollectionViews
//
// Created by Michael Michailidis on 10/04/2015.
// Copyright (c) 2015 Karmadust. All rights reserved.
//
import UIKit
@objc protocol DragAndDropCollectionViewDataSource : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, indexPathForDataItem dataItem: AnyObject) -> IndexPath?
func collectionView(_ collectionView: UICollectionView, dataItemForIndexPath indexPath: IndexPath) -> AnyObject
func collectionView(_ collectionView: UICollectionView, moveDataItemFromIndexPath from: IndexPath, toIndexPath to : IndexPath) -> Void
func collectionView(_ collectionView: UICollectionView, insertDataItem dataItem : AnyObject, atIndexPath indexPath: IndexPath) -> Void
func collectionView(_ collectionView: UICollectionView, replaceDataItemWithCopyatIndexPath indexPath: IndexPath) -> Void
func collectionView(_ collectionView: UICollectionView, deleteDataItemAtIndexPath indexPath: IndexPath)
}
class DragAndDropCollectionView: UICollectionView, Draggable, Droppable {
var draggingCellIndexPath : IndexPath?
var iDataSource : UICollectionViewDataSource?
var iDelegate : UICollectionViewDelegate?
var animating: Bool = false
var paging : Bool = false
var isHorizontal : Bool { return (self.collectionViewLayout as? UICollectionViewFlowLayout)?.scrollDirection == .horizontal}
fileprivate var currentInRect : CGRect?
var sourceContainer = false
var selfDesc: String { return sourceContainer ? "Source" : "Pattern" }
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
}
// MARK: - Draggable
func canDragAtPoint(_ point : CGPoint) -> Bool {
if self.dataSource is DragAndDropCollectionViewDataSource {
return self.indexPathForItem(at: point) != nil
}
return false
}
func representationImageAtPoint(_ point : CGPoint) -> UIView? {
guard let indexPath = self.indexPathForItem(at: point) else {
return nil
}
guard let cell = self.cellForItem(at: indexPath) else {
return nil
}
UIGraphicsBeginImageContextWithOptions(cell.bounds.size, cell.isOpaque, 0)
cell.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageView = UIImageView(image: image)
imageView.frame = cell.frame
return imageView
}
func dataItemAtPoint(_ point : CGPoint) -> AnyObject? {
guard let indexPath = self.indexPathForItem(at: point) else { return nil }
guard let dragDropDS = self.dataSource as? DragAndDropCollectionViewDataSource else { return nil }
return dragDropDS.collectionView(self, dataItemForIndexPath: indexPath)
}
func startDraggingAtPoint(_ point : CGPoint) -> Void {
self.draggingCellIndexPath = self.indexPathForItem(at: point)
self.reloadData()
}
func stopDragging() -> Void {
if let idx = self.draggingCellIndexPath {
if let cell = self.cellForItem(at: idx) {
cell.isHidden = false
}
}
self.draggingCellIndexPath = nil
self.reloadData()
}
func dragDataItem(_ item : AnyObject) -> Void {
print("DragDataItem")
guard let dragDropDataSource = self.dataSource as? DragAndDropCollectionViewDataSource else {
return
}
guard let existngIndexPath = dragDropDataSource.collectionView(self, indexPathForDataItem: item) else {
return
}
if (!sourceContainer) {
dragDropDataSource.collectionView(self, deleteDataItemAtIndexPath: existngIndexPath)
self.animating = true
self.performBatchUpdates({ () -> Void in
self.deleteItems(at: [existngIndexPath])
}, completion: { complete -> Void in
self.animating = false
self.reloadData()
})
}
}
// MARK: - Droppable
func canDropAtRect(_ rect : CGRect) -> Bool {
return (self.indexPathForCellOverlappingRect(rect) != nil)
}
func indexPathForCellOverlappingRect( _ rect : CGRect) -> IndexPath? {
var overlappingArea : CGFloat = 0.0
var cellCandidate : UICollectionViewCell?
let visibleCells = self.visibleCells
if visibleCells.count == 0 {
return IndexPath(row: 0, section: 0)
}
if isHorizontal && rect.origin.x > self.contentSize.width || !isHorizontal && rect.origin.y > self.contentSize.height {
return IndexPath(row: visibleCells.count - 1, section: 0)
}
for visible in visibleCells {
let intersection = visible.frame.intersection(rect)
if (intersection.width * intersection.height) > overlappingArea {
overlappingArea = intersection.width * intersection.height
cellCandidate = visible
}
}
if let cellRetrieved = cellCandidate {
return self.indexPath(for: cellRetrieved)
}
return nil
}
func checkForEdgesAndScroll(_ rect : CGRect) -> Void {
if paging == true {
return
}
let currentRect : CGRect = CGRect(x: self.contentOffset.x, y: self.contentOffset.y, width: self.bounds.size.width, height: self.bounds.size.height)
var rectForNextScroll : CGRect = currentRect
if isHorizontal {
let leftBoundary = CGRect(x: -30.0, y: 0.0, width: 30.0, height: self.frame.size.height)
let rightBoundary = CGRect(x: self.frame.size.width, y: 0.0, width: 30.0, height: self.frame.size.height)
if rect.intersects(leftBoundary) == true {
rectForNextScroll.origin.x -= self.bounds.size.width * 0.5
if rectForNextScroll.origin.x < 0 {
rectForNextScroll.origin.x = 0
}
}
else if rect.intersects(rightBoundary) == true {
rectForNextScroll.origin.x += self.bounds.size.width * 0.5
if rectForNextScroll.origin.x > self.contentSize.width - self.bounds.size.width {
rectForNextScroll.origin.x = self.contentSize.width - self.bounds.size.width
}
}
} else { // is vertical
let topBoundary = CGRect(x: 0.0, y: -30.0, width: self.frame.size.width, height: 30.0)
let bottomBoundary = CGRect(x: 0.0, y: self.frame.size.height, width: self.frame.size.width, height: 30.0)
if rect.intersects(topBoundary) == true {
}
else if rect.intersects(bottomBoundary) == true {
}
}
// check to see if a change in rectForNextScroll has been made
if currentRect.equalTo(rectForNextScroll) == false {
self.paging = true
self.scrollRectToVisible(rectForNextScroll, animated: true)
let delayTime = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.paging = false
}
}
}
func willMoveItem(_ item : AnyObject, inRect rect : CGRect) -> Void {
print(selfDesc + ".willMoveItem")
let dragDropDataSource = self.dataSource as! DragAndDropCollectionViewDataSource // its guaranteed to have a data source
if let _ = dragDropDataSource.collectionView(self, indexPathForDataItem: item) { // if data item exists
return
}
if (!sourceContainer) {
if let indexPath = self.indexPathForCellOverlappingRect(rect) {
dragDropDataSource.collectionView(self, insertDataItem: item, atIndexPath: indexPath)
self.draggingCellIndexPath = indexPath
self.animating = true
self.performBatchUpdates({ () -> Void in
self.insertItems(at: [indexPath])
}, completion: { complete -> Void in
self.animating = false
// if in the meantime we have let go
if self.draggingCellIndexPath == nil {
self.reloadData()
}
})
}
}
currentInRect = rect
}
func didMoveItem(_ item : AnyObject, inRect rect : CGRect) -> Void {
let dragDropDS = self.dataSource as! DragAndDropCollectionViewDataSource // guaranteed to have a ds
if let existingIndexPath = dragDropDS.collectionView(self, indexPathForDataItem: item),
let indexPath = self.indexPathForCellOverlappingRect(rect) {
if indexPath.item != existingIndexPath.item {
dragDropDS.collectionView(self, moveDataItemFromIndexPath: existingIndexPath, toIndexPath: indexPath)
self.animating = true
self.performBatchUpdates({ () -> Void in
self.moveItem(at: existingIndexPath, to: indexPath)
}, completion: { (finished) -> Void in
self.animating = false
self.reloadData()
})
self.draggingCellIndexPath = indexPath
}
}
// Check Paging
var normalizedRect = rect
normalizedRect.origin.x -= self.contentOffset.x
normalizedRect.origin.y -= self.contentOffset.y
currentInRect = normalizedRect
self.checkForEdgesAndScroll(normalizedRect)
}
func didMoveOutItem(_ item : AnyObject) -> Void {
print(selfDesc + ".didMoveOutItem")
guard let dragDropDataSource = self.dataSource as? DragAndDropCollectionViewDataSource,
let existngIndexPath = dragDropDataSource.collectionView(self, indexPathForDataItem: item) else {
return
}
if (!sourceContainer) {
dragDropDataSource.collectionView(self, deleteDataItemAtIndexPath: existngIndexPath)
self.animating = true
self.performBatchUpdates({ () -> Void in
self.deleteItems(at: [existngIndexPath])
}, completion: { (finished) -> Void in
self.animating = false;
self.reloadData()
})
if let idx = self.draggingCellIndexPath {
if let cell = self.cellForItem(at: idx) {
cell.isHidden = false
}
}
self.draggingCellIndexPath = nil
currentInRect = nil
}
}
func dropDataItem(_ item : AnyObject, atRect : CGRect) -> Void {
print(selfDesc + ".dropDataItem")
// show hidden cell
if let index = draggingCellIndexPath, let cell = self.cellForItem(at: index), cell.isHidden == true {
cell.alpha = 1.0
cell.isHidden = false
let dragDropDataSource = dataSource as! DragAndDropCollectionViewDataSource
dragDropDataSource.collectionView(self, replaceDataItemWithCopyatIndexPath: index)
}
currentInRect = nil
self.draggingCellIndexPath = nil
self.reloadData()
}
}
| bsd-2-clause | bcbfe14867ecfb5efcce1e8d638e7f0f | 35.677515 | 155 | 0.58127 | 5.456426 | false | false | false | false |
nathawes/swift | test/Interop/Cxx/templates/decl-with-definition-irgen.swift | 2 | 2375 | // RUN: %target-swift-emit-ir %s -I %S/Inputs -enable-cxx-interop | %FileCheck %s
// REQUIRES: rdar67257133
import DeclWithDefinition
public func getWrappedMagicInt() -> CInt {
let myInt = IntWrapper(value: 7)
var magicInt = PartiallyDefinedMagicallyWrappedInt(t: myInt)
return magicInt.getValuePlusArg(13)
}
// CHECK: define {{(protected |dllexport )?}}swiftcc i32 @"$s4main18getWrappedMagicInts5Int32VyF"()
// CHECK: %magicInt = alloca %TSo037__CxxTemplateInst12MagicWrapperI10IntE1EV, align 4
// CHECK: %magicInt.t = getelementptr inbounds %TSo037__CxxTemplateInst12MagicWrapperI10IntE1EV, %TSo037__CxxTemplateInst12MagicWrapperI10IntE1EV* %magicInt, i32 0, i32 0
// CHECK: [[MAGIC_WRAPPER:%.*]] = bitcast %TSo037__CxxTemplateInst12MagicWrapperI10IntE1EV* %magicInt to %struct.MagicWrapper*
// CHECK: call i32 @{{_ZNK12MagicWrapperI10IntWrapperE15getValuePlusArgEi|"\?getValuePlusArg@\?\$MagicWrapper@UIntWrapper@@@@QEBAHH@Z"}}(%struct.MagicWrapper* [[MAGIC_WRAPPER]], i32 13)
// CHECK: define weak_odr{{( dso_local)?}} i32 @{{_ZNK12MagicWrapperI10IntWrapperE15getValuePlusArgEi|"\?getValuePlusArg@\?\$MagicWrapper@UIntWrapper@@@@QEBAHH@Z"}}(%struct.MagicWrapper* %this, i32 %arg)
// CHECK: %this.addr = alloca %struct.MagicWrapper*, align {{4|8}}
// CHECK: store %struct.MagicWrapper* %this, %struct.MagicWrapper** %this.addr, align {{4|8}}
// CHECK: %this1 = load %struct.MagicWrapper*, %struct.MagicWrapper** %this.addr, align {{4|8}}
// CHECK: %t = getelementptr inbounds %struct.MagicWrapper, %struct.MagicWrapper* %this1, i32 0, i32 0
// CHECK: %call = call i32 @{{_ZNK10IntWrapper8getValueEv|"\?getValue@IntWrapper@@QEBAHXZ"}}(%struct.IntWrapper* %t)
// CHECK: [[ARG:%.*]] = load i32, i32* %arg.addr, align 4
// CHECK: %add = add nsw i32 %call, [[ARG]]
// CHECK: ret i32 %add
// CHECK: define linkonce_odr{{( dso_local)?}} i32 @{{_ZNK10IntWrapper8getValueEv|"\?getValue@IntWrapper@@QEBAHXZ"}}(%struct.IntWrapper* %this)
// CHECK: %this.addr = alloca %struct.IntWrapper*, align {{4|8}}
// CHECK: store %struct.IntWrapper* %this, %struct.IntWrapper** %this.addr, align {{4|8}}
// CHECK: %this1 = load %struct.IntWrapper*, %struct.IntWrapper** %this.addr, align {{4|8}}
// CHECK: %value = getelementptr inbounds %struct.IntWrapper, %struct.IntWrapper* %this1, i32 0, i32 0
// CHECK: [[VALUE:%.*]] = load i32, i32* %value, align 4
// CHECK: ret i32 [[VALUE]]
| apache-2.0 | 0b4ff8ba09b75ebb851dce1f7a843aba | 70.969697 | 203 | 0.719579 | 3.253425 | false | false | false | false |
novi/mysql-swift | Sources/MySQL/Transaction.swift | 1 | 1178 | //
// Connection-Transaction.swift
// MySQL
//
// Created by ito on 12/24/15.
// Copyright © 2015 Yusuke Ito. All rights reserved.
//
extension Connection {
func beginTransaction() throws {
_ = try query("START TRANSACTION;")
}
func commit() throws {
_ = try query("COMMIT;")
}
func rollback() throws {
_ = try query("ROLLBACK;")
}
}
extension ConnectionPool {
public func transaction<T>( _ block: (_ conn: Connection) throws -> T ) throws -> T {
let conn = try getConnection()
defer {
if option.reconnect {
conn.setReconnect(true)
}
releaseConnection(conn)
}
// disable reconnect option of MySQL while transaction
conn.setReconnect(false)
try conn.beginTransaction()
do {
let result = try block(conn)
try conn.commit()
return result
} catch {
do {
try conn.rollback()
} catch {
print("error while `ROLLBACK`.", error)
}
throw error
}
}
}
| mit | e13bcadbbacca9b0ec51d66eb36ee6d4 | 21.207547 | 90 | 0.500425 | 4.784553 | false | false | false | false |
pattypatpat2632/EveryoneGetsToDJ | EveryoneGetsToDJ/EveryoneGetsToDJ/TrackContentView.swift | 1 | 1694 | //
// TrackContentView.swift
// EveryoneGetsToDJ
//
// Created by Patrick O'Leary on 7/12/17.
// Copyright © 2017 Patrick O'Leary. All rights reserved.
//
import UIKit
class TrackContentView: UIView {
@IBOutlet var contentView: DJContentView!
@IBOutlet weak var trackTitleLabel: DJLabel!
@IBOutlet weak var artistLabel: DJLabel!
@IBOutlet weak var userLabel: DJLabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit() {
Bundle.main.loadNibNamed("TrackContentView", owner: self, options: nil)
self.addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1).isActive = true
contentView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1).isActive = true
contentView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
contentView.backgroundColor = UIColor.clear
self.backgroundColor = UIColor.clear
activityIndicator.hidesWhenStopped = true
}
func setLabels(to track: Track) {
trackTitleLabel.text = track.name
artistLabel.text = track.artistName
}
func set(image: UIImage) {
imageView.image = image
}
}
| mit | 623ef65b690a28152330a480be6866b7 | 29.781818 | 102 | 0.679858 | 4.823362 | false | false | false | false |
PerfectServers/Perfect-Authentication-Server | Sources/PerfectAuthServer/handlers/user/oAuth2UpgradeToUser.swift | 1 | 2654 | //
// oAuth2UpgradeToUser.swift
// PerfectAuthServer
//
// Created by Jonathan Guthrie on 2017-08-15.
//
import PerfectHTTP
import PerfectLogger
import PerfectLocalAuthentication
import OAuth2
extension Handlers {
// Upgrade a supplied access token to a VALIDATED user
// Note that this is conducted via API only. The Convert2User method is for Web
static func oAuth2UpgradeToUser(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let provider = request.urlVariables["provider"] ?? ""
let accessToken = request.urlVariables["token"] ?? ""
var userProfile = [String:Any]()
// initially supporting Facebook, Linkedin, Google.
switch provider {
case "facebook":
userProfile = Facebook(clientID: "",clientSecret: "").getUserData(accessToken)
case "linkedin":
userProfile = Linkedin(clientID: "",clientSecret: "").getUserData(accessToken)
case "google":
userProfile = Google(clientID: "",clientSecret: "").getUserData(accessToken)
case "local":
let tok = AccessToken()
try? tok.get(accessToken)
userProfile["userid"] = tok.userid
let thisUser = Account()
try? thisUser.get(tok.userid)
userProfile["first_name"] = thisUser.detail["firstname"] as? String ?? ""
userProfile["last_name"] = thisUser.detail["lastname"] as? String ?? ""
userProfile["picture"] = thisUser.detail["picture"] as? String ?? ""
default:
response.completed(status: .badRequest)
return
}
let userid = userProfile["userid"] as? String ?? ""
if userid.isEmpty {
response.completed(status: .badRequest)
return
}
let user = Account()
do {
try user.find(["source": provider, "remoteid": userid])
//print("FOUND \(provider) user \(userid), id is \(user.id)")
if user.id.isEmpty {
// no user, make one.
user.makeID()
user.usertype = .standard
user.source = provider
user.remoteid = userid // storing remote id so we can upgrade to user
user.detail["firstname"] = userProfile["first_name"] as? String ?? ""
user.detail["lastname"] = userProfile["last_name"] as? String ?? ""
try user.create()
request.session?.userid = user.id // storing new user id in session
} else {
// user exists, upgrade session to user.
request.session?.userid = user.id
}
} catch {
// no user
print("something wrong finding user: \(error)")
response.completed(status: .badRequest)
return
}
let _ = try? response.setBody(json: ["userid": user.id, "firstname": user.detail["firstname"], "lastname": user.detail["lastname"]])
response.completed()
}
}
}
| apache-2.0 | dab670e8b3f33fcc1bb348ebefaf209a | 28.820225 | 135 | 0.661643 | 3.66069 | false | false | false | false |
jopamer/swift | test/stdlib/ErrorBridged.swift | 1 | 21814 | // RUN: %target-run-simple-swift-swift3
// REQUIRES: executable_test
// REQUIRES: objc_interop
import StdlibUnittest
import Foundation
import CoreLocation
import Darwin
var ErrorBridgingTests = TestSuite("ErrorBridging")
var NoisyErrorLifeCount = 0
var NoisyErrorDeathCount = 0
var CanaryHandle = 0
protocol OtherProtocol {
var otherProperty: String { get }
}
protocol OtherClassProtocol : class {
var otherClassProperty: String { get }
}
class NoisyError : Error, OtherProtocol, OtherClassProtocol {
init() { NoisyErrorLifeCount += 1 }
deinit { NoisyErrorDeathCount += 1 }
let _domain = "NoisyError"
let _code = 123
let otherProperty = "otherProperty"
let otherClassProperty = "otherClassProperty"
}
@objc enum EnumError : Int, Error {
case BadError = 9000
case ReallyBadError = 9001
}
ErrorBridgingTests.test("NSError") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
autoreleasepool {
let ns = NSError(domain: "SomeDomain", code: 321, userInfo: nil)
objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let e: Error = ns
expectEqual(e._domain, "SomeDomain")
expectEqual(e._code, 321)
let ns2 = e as NSError
expectTrue(ns === ns2)
expectEqual(ns2._domain, "SomeDomain")
expectEqual(ns2._code, 321)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
ErrorBridgingTests.test("NSCopying") {
autoreleasepool {
let orig = EnumError.ReallyBadError as NSError
let copy = orig.copy() as! NSError
expectEqual(orig, copy)
}
}
func archiveAndUnarchiveObject<T: NSCoding>(
_ object: T
) -> T?
where T: NSObject {
let unarchiver = NSKeyedUnarchiver(forReadingWith:
NSKeyedArchiver.archivedData(withRootObject: object)
)
unarchiver.requiresSecureCoding = true
return unarchiver.decodeObject(of: T.self, forKey: "root")
}
ErrorBridgingTests.test("NSCoding") {
autoreleasepool {
let orig = EnumError.ReallyBadError as NSError
let unarchived = archiveAndUnarchiveObject(orig)!
expectEqual(orig, unarchived)
expectTrue(type(of: unarchived) == NSError.self)
}
}
ErrorBridgingTests.test("NSError-to-enum bridging") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
let testURL = URL(string: "https://swift.org")!
autoreleasepool {
let underlyingError = CocoaError(.fileLockingError)
as Error as NSError
let ns = NSError(domain: NSCocoaErrorDomain,
code: NSFileNoSuchFileError,
userInfo: [
AnyHashable(NSFilePathErrorKey): "/dev/null",
AnyHashable(NSStringEncodingErrorKey): /*ASCII=*/1,
AnyHashable(NSUnderlyingErrorKey): underlyingError,
AnyHashable(NSURLErrorKey): testURL
])
objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let e: Error = ns
let cocoaCode: Int?
switch e {
case let x as CocoaError:
cocoaCode = x._code
expectTrue(x.isFileError)
expectEqual(x.code, CocoaError.fileNoSuchFileError)
default:
cocoaCode = nil
}
expectEqual(NSFileNoSuchFileError, cocoaCode)
let cocoaCode2: Int? = (ns as? CocoaError)?._code
expectEqual(NSFileNoSuchFileError, cocoaCode2)
let isNoSuchFileError: Bool
switch e {
case CocoaError.fileNoSuchFileError:
isNoSuchFileError = true
default:
isNoSuchFileError = false
}
expectTrue(isNoSuchFileError)
// Check the contents of the error.
let cocoaError = e as! CocoaError
expectOptionalEqual("/dev/null", cocoaError.filePath)
expectOptionalEqual(String.Encoding.ascii, cocoaError.stringEncoding)
expectOptionalEqual(underlyingError, cocoaError.underlying.map { $0 as NSError })
expectOptionalEqual(testURL, cocoaError.url)
// URLError domain
let nsURL = NSError(domain: NSURLErrorDomain,
code: NSURLErrorBadURL,
userInfo: [AnyHashable(NSURLErrorFailingURLErrorKey): testURL])
let eURL: Error = nsURL
let isBadURLError: Bool
switch eURL {
case URLError.badURL:
isBadURLError = true
default:
isBadURLError = false
}
expectTrue(isBadURLError)
let urlError = eURL as! URLError
expectOptionalEqual(testURL, urlError.failingURL)
expectNil(urlError.failureURLPeerTrust)
// CoreLocation error domain
let nsCL = NSError(domain: kCLErrorDomain,
code: CLError.headingFailure.rawValue,
userInfo: [AnyHashable(NSURLErrorKey): testURL])
let eCL: Error = nsCL
let isHeadingFailure: Bool
switch eCL {
case CLError.headingFailure:
isHeadingFailure = true
default:
isHeadingFailure = false
}
let isCLError: Bool
switch eCL {
case let error as CLError:
isCLError = true
expectOptionalEqual(testURL, (error as NSError).userInfo[NSURLErrorKey as NSObject] as? URL)
expectOptionalEqual(testURL, error.userInfo[NSURLErrorKey] as? URL)
default:
isCLError = false
}
expectTrue(isCLError)
// NSPOSIXError domain
let nsPOSIX = NSError(domain: NSPOSIXErrorDomain,
code: Int(EDEADLK),
userInfo: [:])
let ePOSIX: Error = nsPOSIX
let isDeadlock: Bool
switch ePOSIX {
case POSIXError.EDEADLK:
isDeadlock = true
default:
isDeadlock = false
}
expectTrue(isDeadlock)
// NSMachError domain
let nsMach = NSError(domain: NSMachErrorDomain,
code: Int(KERN_MEMORY_FAILURE),
userInfo: [:])
let eMach: Error = nsMach
let isMemoryFailure: Bool
switch eMach {
case MachError.memoryFailure:
isMemoryFailure = true
default:
isMemoryFailure = false
}
expectTrue(isMemoryFailure)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
func opaqueUpcastToAny<T>(_ x: T) -> Any {
return x
}
struct StructError: Error {
var _domain: String { return "StructError" }
var _code: Int { return 4812 }
}
ErrorBridgingTests.test("Error-to-NSError bridging") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
autoreleasepool {
let e: Error = NoisyError()
let ns = e as NSError
let ns2 = e as NSError
expectTrue(ns === ns2)
expectEqual(ns._domain, "NoisyError")
expectEqual(ns._code, 123)
let e3: Error = ns
expectEqual(e3._domain, "NoisyError")
expectEqual(e3._code, 123)
let ns3 = e3 as NSError
expectTrue(ns === ns3)
let nativeNS = NSError(domain: NSCocoaErrorDomain,
code: NSFileNoSuchFileError,
userInfo: nil)
objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let nativeE: Error = nativeNS
let nativeNS2 = nativeE as NSError
expectTrue(nativeNS === nativeNS2)
expectEqual(nativeNS2._domain, NSCocoaErrorDomain)
expectEqual(nativeNS2._code, NSFileNoSuchFileError)
let any: Any = NoisyError()
let ns4 = any as! NSError
expectEqual(ns4._domain, "NoisyError")
expectEqual(ns4._code, 123)
let ao: AnyObject = NoisyError()
let ns5 = ao as! NSError
expectEqual(ns5._domain, "NoisyError")
expectEqual(ns5._code, 123)
let any2: Any = StructError()
let ns6 = any2 as! NSError
expectEqual(ns6._domain, "StructError")
expectEqual(ns6._code, 4812)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
ErrorBridgingTests.test("NSError-to-error bridging in bridged container") {
autoreleasepool {
let error = NSError(domain: "domain", code: 42, userInfo: nil)
let nsdictionary = ["error": error] as NSDictionary
let dictionary = nsdictionary as? Dictionary<String, Error>
expectNotNil(dictionary)
expectEqual(error, dictionary?["error"] as NSError?)
}
}
ErrorBridgingTests.test("enum-to-NSError round trip") {
autoreleasepool {
// Emulate throwing an error from Objective-C.
func throwNSError(_ error: EnumError) throws {
throw NSError(domain: "main.EnumError", code: error.rawValue,
userInfo: [:])
}
var caughtError: Bool
caughtError = false
do {
try throwNSError(.BadError)
expectUnreachable()
} catch let error as EnumError {
expectEqual(.BadError, error)
caughtError = true
} catch _ {
expectUnreachable()
}
expectTrue(caughtError)
caughtError = false
do {
try throwNSError(.ReallyBadError)
expectUnreachable()
} catch EnumError.BadError {
expectUnreachable()
} catch EnumError.ReallyBadError {
caughtError = true
} catch _ {
expectUnreachable()
}
expectTrue(caughtError)
}
}
class SomeNSErrorSubclass: NSError {}
ErrorBridgingTests.test("Thrown NSError identity is preserved") {
do {
let e = NSError(domain: "ClericalError", code: 219,
userInfo: [AnyHashable("yeah"): "yeah"])
do {
throw e
} catch let e2 as NSError {
expectTrue(e === e2)
expectTrue(e2.userInfo["yeah"] as? String == "yeah")
} catch {
expectUnreachable()
}
}
do {
let f = SomeNSErrorSubclass(domain: "ClericalError", code: 219,
userInfo: [AnyHashable("yeah"): "yeah"])
do {
throw f
} catch let f2 as NSError {
expectTrue(f === f2)
expectTrue(f2.userInfo["yeah"] as? String == "yeah")
} catch {
expectUnreachable()
}
}
}
// Check errors customized via protocol.
struct MyCustomizedError : Error {
let code: Int
}
extension MyCustomizedError : LocalizedError {
var errorDescription: String? {
return NSLocalizedString("something went horribly wrong", comment: "")
}
var failureReason: String? {
return NSLocalizedString("because someone wrote 'throw'", comment: "")
}
var recoverySuggestion: String? {
return NSLocalizedString("delete the 'throw'", comment: "")
}
var helpAnchor: String? {
return NSLocalizedString("there is no help when writing tests", comment: "")
}
}
extension MyCustomizedError : CustomNSError {
static var errorDomain: String {
return "custom"
}
/// The error code within the given domain.
var errorCode: Int {
return code
}
/// The user-info dictionary.
var errorUserInfo: [String : Any] {
return [NSURLErrorKey : URL(string: "https://swift.org")!]
}
}
extension MyCustomizedError : RecoverableError {
var recoveryOptions: [String] {
return ["Delete 'throw'", "Disable the test" ]
}
func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool {
return recoveryOptionIndex == 0
}
}
/// An error type that provides localization and recovery, but doesn't
/// customize NSError directly.
enum MySwiftCustomizedError : Error {
case failed
static var errorDescriptionCount = 0
}
extension MySwiftCustomizedError : LocalizedError {
var errorDescription: String? {
MySwiftCustomizedError.errorDescriptionCount =
MySwiftCustomizedError.errorDescriptionCount + 1
return NSLocalizedString("something went horribly wrong", comment: "")
}
var failureReason: String? {
return NSLocalizedString("because someone wrote 'throw'", comment: "")
}
var recoverySuggestion: String? {
return NSLocalizedString("delete the 'throw'", comment: "")
}
var helpAnchor: String? {
return NSLocalizedString("there is no help when writing tests", comment: "")
}
}
extension MySwiftCustomizedError : RecoverableError {
var recoveryOptions: [String] {
return ["Delete 'throw'", "Disable the test" ]
}
func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool {
return recoveryOptionIndex == 0
}
}
/// Fake definition of the informal protocol
/// "NSErrorRecoveryAttempting" that we use to poke at the object
/// produced for a RecoverableError.
@objc protocol FakeNSErrorRecoveryAttempting {
@objc(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:)
func attemptRecovery(fromError nsError: Error,
optionIndex recoveryOptionIndex: Int,
delegate: AnyObject?,
didRecoverSelector: Selector,
contextInfo: UnsafeMutableRawPointer?)
@objc(attemptRecoveryFromError:optionIndex:)
func attemptRecovery(fromError nsError: Error,
optionIndex recoveryOptionIndex: Int) -> Bool
}
class RecoveryDelegate {
let expectedSuccess: Bool
let expectedContextInfo: UnsafeMutableRawPointer?
var called = false
init(expectedSuccess: Bool,
expectedContextInfo: UnsafeMutableRawPointer?) {
self.expectedSuccess = expectedSuccess
self.expectedContextInfo = expectedContextInfo
}
@objc func recover(success: Bool, contextInfo: UnsafeMutableRawPointer?) {
expectEqual(expectedSuccess, success)
expectEqual(expectedContextInfo, contextInfo)
called = true
}
}
/// Helper for testing a customized error.
func testCustomizedError(error: Error, nsError: NSError) {
// LocalizedError
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectNil(nsError.userInfo[NSLocalizedDescriptionKey as NSObject])
expectNil(nsError.userInfo[NSLocalizedFailureReasonErrorKey as NSObject])
expectNil(nsError.userInfo[NSLocalizedRecoverySuggestionErrorKey as NSObject])
expectNil(nsError.userInfo[NSHelpAnchorErrorKey as NSObject])
} else {
expectOptionalEqual("something went horribly wrong",
nsError.userInfo[NSLocalizedDescriptionKey as NSObject] as? String)
expectOptionalEqual("because someone wrote 'throw'",
nsError.userInfo[NSLocalizedFailureReasonErrorKey as NSObject] as? String)
expectOptionalEqual("delete the 'throw'",
nsError.userInfo[NSLocalizedRecoverySuggestionErrorKey as NSObject] as? String)
expectOptionalEqual("there is no help when writing tests",
nsError.userInfo[NSHelpAnchorErrorKey as NSObject] as? String)
}
expectEqual("something went horribly wrong", error.localizedDescription)
expectEqual("something went horribly wrong", nsError.localizedDescription)
expectEqual("because someone wrote 'throw'", nsError.localizedFailureReason)
expectEqual("delete the 'throw'", nsError.localizedRecoverySuggestion)
expectEqual("there is no help when writing tests", nsError.helpAnchor)
// RecoverableError
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectNil(nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey as NSObject])
} else {
expectOptionalEqual(["Delete 'throw'", "Disable the test" ],
nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey as NSObject] as? [String])
}
expectOptionalEqual(["Delete 'throw'", "Disable the test" ],
nsError.localizedRecoveryOptions)
// Directly recover.
let ctx = UnsafeMutableRawPointer(bitPattern:0x1234567)
let attempter: AnyObject
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectNil(nsError.userInfo[NSRecoveryAttempterErrorKey as NSObject])
attempter = nsError.recoveryAttempter! as AnyObject
} else {
attempter = nsError.userInfo[NSRecoveryAttempterErrorKey as NSObject]! as AnyObject
}
expectOptionalEqual(attempter.attemptRecovery(fromError: nsError,
optionIndex: 0),
true)
expectOptionalEqual(attempter.attemptRecovery(fromError: nsError,
optionIndex: 1),
false)
// Recover through delegate.
let rd1 = RecoveryDelegate(expectedSuccess: true, expectedContextInfo: ctx)
expectEqual(false, rd1.called)
attempter.attemptRecovery(
fromError: nsError,
optionIndex: 0,
delegate: rd1,
didRecoverSelector: #selector(RecoveryDelegate.recover(success:contextInfo:)),
contextInfo: ctx)
expectEqual(true, rd1.called)
let rd2 = RecoveryDelegate(expectedSuccess: false, expectedContextInfo: nil)
expectEqual(false, rd2.called)
attempter.attemptRecovery(
fromError: nsError,
optionIndex: 1,
delegate: rd2,
didRecoverSelector: #selector(RecoveryDelegate.recover(success:contextInfo:)),
contextInfo: nil)
expectEqual(true, rd2.called)
}
ErrorBridgingTests.test("Customizing NSError via protocols") {
let error = MyCustomizedError(code: 12345)
let nsError = error as NSError
// CustomNSError
expectEqual("custom", nsError.domain)
expectEqual(12345, nsError.code)
expectOptionalEqual(URL(string: "https://swift.org")!,
nsError.userInfo[NSURLErrorKey as NSObject] as? URL)
testCustomizedError(error: error, nsError: nsError)
}
ErrorBridgingTests.test("Customizing localization/recovery via protocols") {
let error = MySwiftCustomizedError.failed
let nsError = error as NSError
testCustomizedError(error: error, nsError: nsError)
}
ErrorBridgingTests.test("Customizing localization/recovery laziness") {
let countBefore = MySwiftCustomizedError.errorDescriptionCount
let error = MySwiftCustomizedError.failed
let nsError = error as NSError
// RecoverableError
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectNil(nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey as NSObject])
} else {
expectOptionalEqual(["Delete 'throw'", "Disable the test" ],
nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey as NSObject] as? [String])
}
expectOptionalEqual(["Delete 'throw'", "Disable the test" ],
nsError.localizedRecoveryOptions)
// None of the operations above should affect the count
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectEqual(countBefore, MySwiftCustomizedError.errorDescriptionCount)
}
// This one does affect the count.
expectEqual("something went horribly wrong", error.localizedDescription)
// Check that we did get a call to errorDescription.
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectEqual(countBefore+1, MySwiftCustomizedError.errorDescriptionCount)
}
}
enum DefaultCustomizedError1 : CustomNSError {
case bad
case worse
}
enum DefaultCustomizedError2 : Int, CustomNSError {
case bad = 7
case worse = 13
}
enum DefaultCustomizedError3 : UInt, CustomNSError {
case bad = 9
case worse = 115
static var errorDomain: String {
return "customized3"
}
}
enum DefaultCustomizedParent {
enum ChildError: CustomNSError {
case foo
}
}
ErrorBridgingTests.test("Default-customized via CustomNSError") {
expectEqual(1, (DefaultCustomizedError1.worse as NSError).code)
expectEqual(13, (DefaultCustomizedError2.worse as NSError).code)
expectEqual(115, (DefaultCustomizedError3.worse as NSError).code)
expectEqual("main.DefaultCustomizedError1", (DefaultCustomizedError1.worse as NSError).domain)
expectEqual("customized3", (DefaultCustomizedError3.worse as NSError).domain)
expectEqual("main.DefaultCustomizedParent.ChildError", (DefaultCustomizedParent.ChildError.foo as NSError).domain)
}
class MyNSError : NSError { }
ErrorBridgingTests.test("NSError subclass identity") {
let myNSError: Error = MyNSError(domain: "MyNSError", code: 0, userInfo: [:])
let nsError = myNSError as NSError
expectTrue(type(of: nsError) == MyNSError.self)
}
ErrorBridgingTests.test("Wrapped NSError identity") {
let nsError = NSError(domain: NSCocoaErrorDomain,
code: NSFileNoSuchFileError,
userInfo: [
AnyHashable(NSFilePathErrorKey) : "/dev/null",
AnyHashable(NSStringEncodingErrorKey): /*ASCII=*/1,
])
let error: Error = nsError
let nsError2: NSError = error as NSError
expectTrue(nsError === nsError2)
// Extracting the NSError via the runtime.
let cocoaErrorAny: Any = error as! CocoaError
let nsError3: NSError = cocoaErrorAny as! NSError
expectTrue(nsError === nsError3)
if let cocoaErrorAny2: Any = error as? CocoaError {
let nsError4: NSError = cocoaErrorAny2 as! NSError
expectTrue(nsError === nsError4)
} else {
expectUnreachable()
}
// Extracting the NSError via direct call.
let cocoaError = error as! CocoaError
let nsError5: NSError = cocoaError as NSError
expectTrue(nsError === nsError5)
if let cocoaError2 = error as? CocoaError {
let nsError6: NSError = cocoaError as NSError
expectTrue(nsError === nsError6)
} else {
expectUnreachable()
}
}
extension Error {
func asNSError() -> NSError {
return self as NSError
}
}
func unconditionalCast<T>(_ x: Any, to: T.Type) -> T {
return x as! T
}
func conditionalCast<T>(_ x: Any, to: T.Type) -> T? {
return x as? T
}
// SR-1562
ErrorBridgingTests.test("Error archetype identity") {
let myError = NSError(domain: "myErrorDomain", code: 0,
userInfo: [ AnyHashable("one") : 1 ])
expectTrue(myError === myError.asNSError())
expectTrue(unconditionalCast(myError, to: Error.self) as NSError
=== myError)
expectTrue(conditionalCast(myError, to: Error.self)! as NSError
=== myError)
let nsError = NSError(domain: NSCocoaErrorDomain,
code: NSFileNoSuchFileError,
userInfo: [
AnyHashable(NSFilePathErrorKey) : "/dev/null",
AnyHashable(NSStringEncodingErrorKey): /*ASCII=*/1,
])
let cocoaError = nsError as Error as! CocoaError
expectTrue(cocoaError.asNSError() === nsError)
expectTrue(unconditionalCast(cocoaError, to: Error.self) as NSError
=== nsError)
expectTrue(conditionalCast(cocoaError, to: Error.self)! as NSError
=== nsError)
}
runAllTests()
| apache-2.0 | b2d5107e4560f6227cf10fabba00a7c4 | 29.509091 | 116 | 0.690703 | 4.494952 | false | true | false | false |
chrisjmendez/swift-exercises | Transitions/Razzle/Pods/RazzleDazzle/Source/ScrollViewPageConstraintAnimation.swift | 25 | 1373 | //
// ScrollViewPageConstraintAnimation.swift
// RazzleDazzle
//
// Created by Laura Skelton on 6/16/15.
// Copyright (c) 2015 IFTTT. All rights reserved.
//
import UIKit
public enum HorizontalPositionAttribute {
case Left
case Right
case CenterX
}
/**
Animates the `constant` of an `NSLayoutConstraint` to keep the view on a certain page given the `pageWidth` of the scroll view.
*/
public class ScrollViewPageConstraintAnimation : Animation<CGFloat>, Animatable {
private let superview : UIView
private let constraint : NSLayoutConstraint
private let attribute : HorizontalPositionAttribute
public var pageWidth : CGFloat
public init(superview: UIView, constraint: NSLayoutConstraint, pageWidth: CGFloat, attribute: HorizontalPositionAttribute) {
self.superview = superview
self.constraint = constraint
self.attribute = attribute
self.pageWidth = pageWidth
}
public func animate(time: CGFloat) {
if !hasKeyframes() {return}
let page = self[time]
var offset : CGFloat
switch attribute {
case .CenterX:
offset = 0.5
case .Left:
offset = 0
case .Right:
offset = 1
}
constraint.constant = (offset + page) * pageWidth
superview.layoutIfNeeded()
}
}
| mit | 36e1efe84797a5d2e77f04cf1eb3bd84 | 26.46 | 128 | 0.650401 | 4.767361 | false | false | false | false |
taiwancek/KNLayout | Source/Extension/ExUIDevice.swift | 1 | 2288 | //
// ExUIDevice.swift
// KNLayout
//
// Created by cek on 2017/6/29.
// Copyright © 2017年 . All rights reserved.
//
import UIKit
import Foundation
public extension UIDevice
{
var kn:knNamespace
{
get { return knNamespace(self) }
}
struct knNamespace
{
var _self:UIDevice
init(_ _self:UIDevice)
{
self._self = _self
}
public var isPhone: Bool
{
return UIDevice().userInterfaceIdiom == .phone
}
public var isPad: Bool
{
return UIDevice().userInterfaceIdiom == .pad
}
public var isLandscape: Bool
{
let bounds = UIScreen.main.bounds
return ( bounds.width > bounds.height)
}
public var isPortrait: Bool
{
let bounds = UIScreen.main.bounds
return ( bounds.height > bounds.width)
}
public var statusBarHeight:CGFloat
{
#if NS_EXTENSION_UNAVAILABLE
return UIApplication.shared.statusBarFrame.size.height
#else
return 0
#endif
}
public var sizeScale: CGFloat
{
var desingWidthPoint:CGFloat = 414 //The default is the width of the iPhone 6 Plus
if let path = Bundle.main.path(forResource: "Info", ofType: "plist")
{
if let dictRoot = NSDictionary(contentsOfFile: path)
{
if let value = dictRoot["Design Width Point"] as? CGFloat
{
desingWidthPoint = value
}
}
}
return (UIScreen.main.nativeBounds.width / UIScreen.main.nativeScale) / desingWidthPoint
}
public var appFrameSize: CGSize
{
return UIScreen.main.bounds.size
}
public var viewScale:CGFloat
{
if UIDevice.current.userInterfaceIdiom == .pad
{
let frameWidth = UIScreen.main.bounds.size.width
let deviceWidth = UIScreen.main.bounds.width
return frameWidth / deviceWidth
}
return 1
}
}
}
| mit | 4f40374ca4309b35822860a173881941 | 22.316327 | 100 | 0.508972 | 5.134831 | false | false | false | false |
apple/swift-nio-extras | Sources/NIOExtrasPerformanceTester/HTTP1PCAPPerformanceTests.swift | 1 | 2077 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOExtras
import Foundation
class HTTP1ThreadedPCapPerformanceTest: HTTP1ThreadedPerformanceTest {
private class SinkHolder {
var fileSink: NIOWritePCAPHandler.SynchronizedFileSink!
func setUp() throws {
let outputFile = NSTemporaryDirectory() + "/" + UUID().uuidString
self.fileSink = try NIOWritePCAPHandler.SynchronizedFileSink.fileSinkWritingToFile(path: outputFile) { error in
print("ERROR: \(error)")
exit(1)
}
}
func tearDown() {
try! self.fileSink.syncClose()
}
}
init() {
let sinkHolder = SinkHolder()
func addPCap(channel: Channel) -> EventLoopFuture<Void> {
let pcapHandler = NIOWritePCAPHandler(mode: .client,
fileSink: sinkHolder.fileSink.write)
return channel.pipeline.addHandler(pcapHandler, position: .first)
}
self.sinkHolder = sinkHolder
super.init(numberOfRepeats: 50,
numberOfClients: System.coreCount,
requestsPerClient: 500,
extraInitialiser: { channel in return addPCap(channel: channel) })
}
private let sinkHolder: SinkHolder
override func run() throws -> Int {
// Opening and closing the file included here as flushing data to disk is not known to complete until closed.
try sinkHolder.setUp()
defer {
sinkHolder.tearDown()
}
return try super.run()
}
}
| apache-2.0 | 0b111390c5d117d66eabf562cd6487b5 | 33.04918 | 123 | 0.574868 | 4.992788 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Product/SLV_501_ProcuctDetailController.swift | 1 | 33976 | //
// SLV_501_ProcuctDetailController.swift
// selluv-ios
//
// Created by 조백근 on 2016. 11. 8..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
/*
상품 상세페이지 컨트롤러
*/
import Foundation
import UIKit
let movingLongInterval = 0.05
let longInterval = 0.2
class SLV_501_ProcuctDetailController: SLVBaseStatusHiddenController {
var imageName: String?
var imageHeight: CGFloat = 0
var imagePath: NSIndexPath?
@IBOutlet weak var contentsView: UIView!
@IBOutlet weak var productNavigation: UINavigationBar!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var purchaseButton: UIButton!
@IBOutlet weak var negoButton: UIButton!
@IBOutlet weak var blurView: UIView!
@IBOutlet weak var imageContent: UIImageView?
var parentCellImage: UIImage?
var firstCenter: CGPoint?
var firstTouch: CGPoint = .zero
var offsetY: CGFloat = 0
var notCallBackTimer: Timer?
var beginTime: NSDate?
var isDrag:Bool = false
var listProductInfo: SLVDetailProduct? {
didSet {
self.loadSellerProducts(same: false)
self.loadRecommandProducts(same: false)
self.loadSimilarProducts(same: false)
self.loadThatguls()
}
}
var sellerItems: [SLVDetailProduct]?
var similarItems: [SLVDetailProduct]?
var recommandItems: [SLVDetailProduct]?
var thatguls: [SLVComment]?
var thatgulField: UITextField?
fileprivate lazy var myToolbar = AccessoryToolbar()
override func viewDidLoad() {
self.navigationBar?.isHidden = true
super.viewDidLoad()
self.extendedLayoutIncludesOpaqueBars = true
self.automaticallyAdjustsScrollViewInsets = false
self.setupTopButtons()
self.setupTableView()
self.setupKeypadLayout()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setupKeypadLayout() {
let keyboardViewV = KeypadLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.bottomLayoutGuide, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0)
self.view.addConstraint(keyboardViewV)
}
func setupTableView() {
tableView.register(UINib(nibName: "SLVProductInfo1Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo1Cell")
tableView.register(UINib(nibName: "SLVProductInfo2Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo2Cell")
tableView.register(UINib(nibName: "SLVProductInfo3Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo3Cell")
tableView.register(UINib(nibName: "SLVProductInfo4Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo4Cell")
tableView.register(UINib(nibName: "SLVProductInfo5Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo5Cell")
tableView.register(UINib(nibName: "SLVProductInfo6Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo6Cell")
tableView.register(UINib(nibName: "SLVProductInfo7Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo7Cell")
tableView.register(UINib(nibName: "SLVProductInfo8Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo8Cell")
tableView.register(UINib(nibName: "SLVProductInfo9Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo9Cell")
tableView.register(UINib(nibName: "SLVProductInfo10Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo10Cell")
tableView.register(UINib(nibName: "SLVProductInfo11Cell", bundle: nil), forCellReuseIdentifier: "SLVProductInfo11Cell")
tableView.delegate = self
tableView.dataSource = self
tableView.parentCollectionPath = self.imagePath
}
func setupTopButtons() {
self.productNavigation?.barHeight = 64
_ = self.productNavigation?.sizeThatFits(.zero)
let back = UIButton()
back.setImage(UIImage(named:"ic-back-arrow.png"), for: .normal)
back.frame = CGRect(x: 0, y: 20, width: 12+32, height: 20)
back.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26)
back.addTarget(self, action: #selector(SLV_501_ProcuctDetailController.touchBack(sender:)), for: .touchUpInside)
let like = UIButton()
like.setImage(UIImage(named:"detail-header-heart-nor.png"), for: .normal)
like.frame = CGRect(x: 0, y: 20, width: 34, height: 34)
like.addTarget(self, action: #selector(SLV_501_ProcuctDetailController.touchLike(sender:)), for: .touchUpInside)
let eye = UIButton()
eye.setImage(UIImage(named:"detail-eye.png"), for: .normal)
eye.frame = CGRect(x: 0, y: 20, width: 34, height: 34)
eye.addTarget(self, action: #selector(SLV_501_ProcuctDetailController.touchEye(sender:)), for: .touchUpInside)
let ittem = UIButton(type: .custom)
ittem.setImage(UIImage(named:"detail-ittem-nor.png"), for: .normal)
ittem.setTitle("잇템", for: .normal)
ittem.setTitleColor(text_color_bl51, for: .normal)
ittem.frame = CGRect(x: 0, y: 24, width: 64, height: 36)
ittem.imageEdgeInsets = UIEdgeInsets(top: 0, left:5, bottom: 0, right: 38)
ittem.backgroundColor = text_color_g181
ittem.cornerRadius = 5
ittem.addTarget(self, action: #selector(SLV_501_ProcuctDetailController.touchIttem(sender:)), for: .touchUpInside)
let barBack = UIBarButtonItem(customView:back)
let barLike = UIBarButtonItem(customView:like)
let barEye = UIBarButtonItem(customView:eye)
let barIttem = UIBarButtonItem(customView:ittem)
let naviItem = UINavigationItem()
naviItem.setLeftBarButtonItems([barBack, barLike, barEye], animated: false)
naviItem.setRightBarButtonItems([barIttem], animated: false)
productNavigation.items = [naviItem]
}
//Data loading~!
func loadRecommandProducts(same: Bool) {
let c1Id = self.listProductInfo?.category1?.categoryId ?? ""
let c2Id = self.listProductInfo?.category2?.categoryId ?? ""
let brandId = self.listProductInfo?.brand?.brandId ?? ""
ProductsModel.shared.recommandProductsStylePhotos(cate1Id: c1Id, cate2Id: c2Id, brandId: brandId, isSame: same) { (success, list) in
if success == true {
if list != nil {
if same == false {
self.recommandItems = list!
} else {
self.recommandItems!.append(contentsOf: list!)
}
}
}
}
}
func loadSimilarProducts(same: Bool) {
let brand = BrandP()
brand?.brandId = self.listProductInfo?.brand?.brandId ?? ""
brand?.english = self.listProductInfo?.brand?.english ?? ""
brand?.korean = self.listProductInfo?.brand?.korean ?? ""
ProductsModel.shared.similarProducts(brand: brand!, isSame: same) { (success, list) in
if success == true {
if list != nil {
if same == false {
self.similarItems = list!
} else {
self.similarItems!.append(contentsOf: list!)
}
}
}
}
}
func loadThatguls() {
let productId = self.listProductInfo?.id
if let productId = productId {
ProductsModel.shared.comments(productId: productId) { (success, list) in
if success == true {
if let list = list {
self.refactoringThatguls(list: list)
// self.thatguls = list
// self.tableView.reloadData()
}
}
}
}
}
func refactoringThatguls(list: [SLVComment]) {
let nick = self.listProductInfo?.userInfo?.nickname ?? ""
let avatar = self.listProductInfo?.userInfo?.avatar ?? ""
var extendThatguls: [SLVComment] = []
for (_, v) in list.enumerated() {
let item = v as! SLVComment
extendThatguls.append(item)
if item.reply?.replyId != nil {
let comment = SLVComment()
/*
var productId: String?
var writerId: String?
var text: String?
var createdAt: Date?
var replyId: String?
var text: String?
var createdAt: Date?
*/
let interval = item.reply?.createdAt?.timeIntervalSinceReferenceDate ?? 0
let text = item.reply?.text ?? ""
comment?.userInfo = SLVCommentUserInfo()
comment?.userInfo?.nickname = nick.copy() as! String
comment?.userInfo?.avatar = avatar.copy() as! String
comment?.isReply = true
comment?.text = text.copy() as! String
comment?.createdAt = Date(timeIntervalSinceReferenceDate: interval)
extendThatguls.append(comment!)
}
}
self.thatguls = extendThatguls
// var sets: [IndexPath] = []
// for i in 0...((self.thatguls?.count)! - 1) {
// let row = i + 17
// let path = IndexPath(row: row, section: 0)
// sets.append(path)
// }
// self.tableView.reloadRows(at: sets, with: .automatic)
self.tableView.reloadData()
}
func countForCells() -> Int {
var cellCount = 19 //20//셀 카운트는 20 + 코멘트 갯수 (구매하기 제외 20 -> 19)
if let list = self.thatguls {
cellCount = cellCount + list.count
}
return cellCount
}
func loadSellerProducts(same: Bool) {
let userId = self.listProductInfo?.userId ?? ""
let kind = "items"
ProductsModel.shared.productsForSeller(userId: userId, kind: kind, isSame: same) { (success, list) in
if success == true {
if list != nil {
if same == false {
self.sellerItems = list!
} else {
self.sellerItems!.append(contentsOf: list!)
}
}
}
}
}
//테이블 뷰 셀의 유형별 제목 처리
func labelInfoForCell2(row: Int) -> (String, String, Bool) {
var main = ""
var sub = ""
var isHidden = true
switch row {
case 2 :
main = "SELLER"
sub = "판매자"
break
case 5 :
main = "STYLE"
sub = "판매자 착용 사진"
break
case 7 :
main = "ITEM CONDITION"
sub = "상품 하자"
break
case 10 :
main = "ACCESSORIES"
sub = "부속품"
break
case 13 :
main = "RECOMMEND STYLE"
sub = "추천 착용 사진"
isHidden = false
break
case 15 :
main = "SIMILAR ITEMS"
sub = "비슷한 상품"
isHidden = false
break
case 17 :
let count = 10
main = "COMMENT"
sub = "댓글 \(count)" //TODO: 댓글 카운트 추가
break
default: break
}
return (main, sub, isHidden)
}
func photoTypeForCell5(row: Int) -> (ProductPhotoType, [String], [SLVDetailProduct]) {
var type: ProductPhotoType = .none
var photos: [String] = []
var items: [SLVDetailProduct] = []
//판매자 상품사진, 스타일사진, 상품 하자사진, 부속품 사진, 추천상품사진, 유사상품사진
switch row {
case 4 :
type = .sellerItem
if self.sellerItems != nil {
_ = self.sellerItems!.map() {
let item = $0 as! SLVDetailProduct
if let pictures = item.photos {
if pictures.count > 0 {
photos.append(pictures.first!)
}
}
}
items.append(contentsOf: self.sellerItems!)
}
break
case 6 :
type = .style
if let pictures = self.listProductInfo!.styles {
photos.append(contentsOf: pictures)
}
break
case 8 :
type = .damage
if let pictures = self.listProductInfo!.damages {
photos.append(contentsOf: pictures)
}
break
case 11 :
type = .accessory
if let pictures = self.listProductInfo!.accessories {
photos.append(contentsOf: pictures)
}
break
case 14 :
type = .recommand
if self.recommandItems != nil {
_ = self.recommandItems!.map() {
let item = $0 as! SLVDetailProduct
if let pictures = item.styles {
if pictures.count > 0 {
photos.append(pictures.first!)
}
}
}
items.append(contentsOf: self.recommandItems!)
}
break
case 16 :
type = .similar
if self.similarItems != nil {
_ = self.similarItems!.map() {
let item = $0 as! SLVDetailProduct
if let pictures = item.photos {
if pictures.count > 0 {
photos.append(pictures.first!)
}
}
}
items.append(contentsOf: self.similarItems!)
}
break
default: break
}
return (type, photos, items)
}
//MAKR: EVENT
func touchBack(sender: UIBarButtonItem) {
self.navigationController?.popViewController(animated: true)
}
func touchLike(sender: UIBarButtonItem) {
}
func touchEye(sender: UIBarButtonItem) {
}
func touchIttem(sender: UIBarButtonItem) {
}
@IBAction func touchAddButton(_ sender: Any) {
}
@IBAction func touchPurchaseButton(_ sender: Any) {
}
@IBAction func touchNegoButton(_ sender: Any) {
}
}
extension SLV_501_ProcuctDetailController: UITableViewDelegate, UITableViewDataSource {
// @nonobjc func tableView(tableView: UITableView, didSelectRowAt indexPath: NSIndexPath) {
// self.tableView.deselectRow(at: indexPath as IndexPath, animated: false)
// }
// @nonobjc func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
// }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
/*
//(이미지) + (상품정보) + (판매자 타이틀 2) + (판매자 정보) + (판매상품) + (스타일 타이틀 5) +
(스타일들) + (상품하자 타이틀 7) + (상품하자들) + (하자유형) + (부속품 타이틀 10) + (부속품들) + (부속품 유형) +
(추천 타이틀 13) + (추천사진들) + (유사상품 타이틀 15 ) + (유사상품들) + (코멘트 타이틀 17) + (댓글입력) + //제외함 (구매하기)
-> 20 + 댓글 수
*/
return self.countForCells() //20 + 댓글수 -> 구매하기 제외
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellRow = indexPath.row
let cellCount = self.countForCells()
if cellRow == 0 {//상품 이미지들
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo1Cell") as! SLVProductInfo1Cell!
cell?.item = self.listProductInfo
cell?.firstImage = self.parentCellImage
cell?.setupViewer(block: { (path) in
let board = UIStoryboard(name:"Sell", bundle: nil)
let controller = board.instantiateViewController(withIdentifier: "SLV_318_SellPhotoEdit") as! SLV_318_SellPhotoEdit
controller.photoMode = .viewer(urlString: dnProduct, items: self.listProductInfo!.photos!)
self.present(controller, animated: true, completion: {
controller.moveCurrentIndex(index: path.row)
})
})
return cell!
}
else if cellRow == 1 {//상품정보
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo2Cell") as! SLVProductInfo2Cell!
cell?.setupData(product: self.listProductInfo!)
return cell!
}
else if [2, 5, 7, 10, 13, 15, 17].contains(cellRow) {//판매자, 스타일, 상품하자, 부속품, 추천, 유사상품, 코멘트 타이틀
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo3Cell") as! SLVProductInfo3Cell!
let titles = self.labelInfoForCell2(row: cellRow)
cell?.mainTitleLabel.text = titles.0
cell?.subTitleLabel.text = titles.1
cell?.moreButton.isHidden = titles.2
cell?.cellIndex = cellRow
return cell!
}
else if cellRow == 3 {//판매자 정보
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo4Cell") as! SLVProductInfo4Cell!
cell?.setupData(product: self.listProductInfo!)
return cell!
}
else if [4, 6, 8, 11, 14, 16].contains(cellRow) {//판매자 상품사진, 스타일사진, 상품 하자사진, 부속품 사진, 추천상품사진, 유사상품사진
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo5Cell") as! SLVProductInfo5Cell!
let data = self.photoTypeForCell5(row: cellRow)
cell?.setupData(item: self.listProductInfo!, type: data.0, photos: data.1, items: data.2)
cell?.setupViewer(block: { (path, type, item) in
switch type {
case .none : break
case .style, .damage, .accessory :
// var list: [String] = []
// var urlString = dnProduct
// if type == .style {
// if let photos = self.listProductInfo?.styles {
// list = photos
// urlString = dnStyle
// }
// } else if type == .damage {
// if let photos = self.listProductInfo?.damages {
// list = photos
// urlString = dnDamage
// }
// } else if type == .accessory {
// if let photos = self.listProductInfo?.accessories {
// list = photos
// urlString = dnAccessory
// }
// }
// if list.count == 0 {
// return
// }
// let board = UIStoryboard(name:"Sell", bundle: nil)
// let controller = board.instantiateViewController(withIdentifier: "SLV_318_SellPhotoEdit") as! SLV_318_SellPhotoEdit
// controller.photoMode = .viewer(urlString: urlString, items: list)
// self.present(controller, animated: true, completion: {
// controller.moveCurrentIndex(index: path.row)
// })
break
case .sellerItem, .recommand, .similar :
if let item = item {
let board = UIStoryboard(name:"Main", bundle: nil)
let controller = board.instantiateViewController(withIdentifier: "SLVProductPhotoViewer") as! SLVProductPhotoViewer
controller.modalPresentationStyle = .overCurrentContext
controller.setupData(type: data.0, photos: data.1, items: data.2)
controller.setupViewer(block: { (viewPath, image, viewType, viewItem) in
let productController = board.instantiateViewController(withIdentifier: "SLV_501_ProcuctDetailController") as! SLV_501_ProcuctDetailController
productController.listProductInfo = item
productController.imageContent?.image = image
//productController.imagePath = indexPath as NSIndexPath?
self.navigationController?.pushViewController(productController, animated: true)
})
self.present(controller, animated: true, completion: {
controller.moveIndex(index: path.row)
})
}
break
}
})
return cell!
}
else if cellRow == 9 {//판매상품 하자 유형
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo6Cell") as! SLVProductInfo6Cell!
cell?.item = self.listProductInfo
cell?.setupDamegeTags()
return cell!
}
else if cellRow == 12 {//판매상품 부속품 유형
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo7Cell") as! SLVProductInfo7Cell!
cell?.item = self.listProductInfo
cell?.setupAccessoriesButtons()
return cell!
}
else if cellCount == cellRow + 1 {//댓글 입력
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo10Cell") as! SLVProductInfo10Cell!
self.thatgulField = cell?.inputTextField
self.thatgulField?.delegate = self
return cell!
}
// else if cellCount == cellRow + 1 {//구매하기 제외
// let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo11Cell") as! SLVProductInfo11Cell!
// return cell!
// }
else {//코멘트
let thatIndex = indexPath.row - 18//17 에서 (입력창), 인덱스 시작이 0인거 고려해서
if thatIndex >= 0 {
if let list = self.thatguls {
if list.count >= thatIndex + 1 {
let gulItem = list[thatIndex] as! SLVComment
if gulItem.isReply == true {
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo9Cell") as! SLVProductInfo9Cell!
cell?.setupCommentData(item: gulItem)
return cell!
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo8Cell") as! SLVProductInfo8Cell!
cell?.setupCommentData(item: gulItem)
return cell!
}
}
}
}
}
let cell = tableView.dequeueReusableCell(withIdentifier: "SLVProductInfo8Cell") as! SLVProductInfo8Cell!
return cell!
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let width = UIScreen.main.bounds.width
let cellCount = self.countForCells()
let cellRow = indexPath.row
if cellRow == 0 {//상품 이미지들
return width - CGFloat(20)
}
else if cellRow == 1 {//상품정보
return 640
}
else if [2, 5, 7, 10, 13, 15, 17].contains(cellRow) {//판매자, 스타일, 상품하자, 부속품, 추천, 유사상품, 코멘트 타이틀
return 80
}
else if cellRow == 3 {//판매자 정보
return 54
}
else if [4, 6, 8, 11, 14, 16].contains(cellRow) {//판매자 상품사진, 스타일사진, 상품 하자사진, 부속품 사진, 추천상품사진, 유사상품사진
return 120
}
else if cellRow == 9 {//판매상품 하자 유형
// return 160
return self.damagesHeight()
}
else if cellRow == 12 {//판매상품 부속품 유형
// return 200
return self.accessoriesHeight()
}
else if cellCount == cellRow {
return 60
}
else if cellCount == cellRow + 1 {
return 60
}
else {//코멘트
return 60
}
}
func damagesHeight() -> CGFloat {
let baseHeight: CGFloat = 160
var cellHeight: CGFloat = baseHeight
if let item = self.listProductInfo {
if let damages = item.damage {
var addDamages: [String] = []
var codes: [String] = []
for (_, v) in (CodeModel.shared.itemDemage?.enumerated())! {
let item = v as Code
codes.append(item.value)
}
for (_, v) in damages.enumerated() {
let name = v
let selected = codes.contains(name)
if selected == false {
addDamages.append(name)
}
}
if addDamages.count > 0 {
let count = addDamages.count
let addRow = (count + 2)/3
let addHeight = addRow * (81 + 12)
cellHeight = cellHeight + CGFloat(addHeight)
}
}
}
return cellHeight
}
func accessoriesHeight() -> CGFloat {
let baseHeight: CGFloat = 200
var cellHeight: CGFloat = baseHeight
if let item = self.listProductInfo {
if let accessories = item.accessory {
var addAccessories: [String] = []
var codes: [String] = []
for (_, v) in (CodeModel.shared.itemAccessory?.enumerated())! {
let item = v as Code
codes.append(item.value)
}
for (_, v) in accessories.enumerated() {
let name = v
let selected = codes.contains(name)
if selected == false {
addAccessories.append(name)
}
}
if addAccessories.count > 0 {
let count = addAccessories.count
let addRow = (count + 2)/3
let addHeight = addRow * (81 + 12)
cellHeight = cellHeight + CGFloat(addHeight)
}
}
}
return cellHeight
}
func scrollViewWillBeginDecelerating(_ scrollView : UIScrollView){
log.debug("offset.y : \(scrollView.contentOffset.y)")
let offset = fabs(scrollView.contentOffset.y)
if scrollView.contentOffset.y < 0 && offset > navigationHeight {
// self.offsetY = offset
// self.isDrag = true
self.navigationController?.popViewController(animated: true)
}
}
// func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
// log.debug("offset.y : \(scrollView.contentOffset.y)")
// log.debug("velocity : (\(velocity.x), \(velocity.y))")
//
// scrollView.isExclusiveTouch = true
//
// let offset = fabs(scrollView.contentOffset.y)
// if scrollView.contentOffset.y < 0 && offset > 20/*navigationHeight*/ {
//// self.offsetY = offset
//// self.isDrag = true
//// self.rotateImageView()
// self.navigationController?.popViewController(animated: true)
// }
// }
}
extension SLV_501_ProcuctDetailController {
func rotateImageView() {
// let path = NSIndexPath(row: 0, section: 0)
// let cell = tableView.cellForRow(at: path as IndexPath) as! SLVProductTableCell
// cell.imageViewContent?.isHidden = true
//
// self.blurView.isHidden = false
//
// let image = UIImage(named: imageName!)
// self.imageContent?.image = image
// var frame: CGRect = (self.imageContent?.frame)!
// frame.origin.y = 15 + self.offsetY
// frame.size.height = imageHeight
// self.imageContent?.frame = frame
// bottomConstraint.constant = blurView.frame.size.height - imageHeight - 15
// self.imageContent?.updateConstraints()
}
func backImageView() {
// let path = NSIndexPath(row: 0, section: 0)
// let cell = tableView.cellForRow(at: path as IndexPath) as! SLVProductTableCell
// cell.imageViewContent?.isHidden = false
// self.blurView.isHidden = true
}
func timeout() {
self.notCallBackTimer?.invalidate()
self.notCallBackTimer = nil
self.beginTime = nil
self.isDrag = false
let point: CGPoint = self.imageContent!.center
self.moveEnd()
self.backImageView()
self.firstTouch = .zero
}
func moveEnd() {
UIView.animate(withDuration: 0.1) { () -> Void in
self.imageContent!.center = self.firstCenter!
self.imageContent!.updateConstraints()
}
}
func moving(point: CGPoint) {
UIView.animate(withDuration: 0.1) { () -> Void in
self.imageContent!.center = point
}
}
//MARK:
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if !self.isDrag {
return
}
if let touch = touches.first! as? UITouch {
self.firstTouch = touch.location(in: self.tableView)
let now = NSDate()
self.firstCenter = self.imageContent!.center
self.beginTime = now
}
}
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
if self.notCallBackTimer != nil {
self.notCallBackTimer?.invalidate()
self.notCallBackTimer = nil
}
if let touch = touches.first! as? UITouch {
let point = touch.location(in: self.blurView)
log.debug("point.y: \(point.y)")
if self.beginTime != nil {
let now = NSDate()
let interval = now.timeIntervalSince(self.beginTime! as Date)
if self.isDrag == true {
self.moving(point: point)
self.notCallBackTimer = Timer.scheduledTimer(timeInterval: longInterval, target: self, selector: #selector(SLV_501_ProcuctDetailController.timeout), userInfo: nil, repeats: false)
}
}
}
}
}
extension SLV_501_ProcuctDetailController: SLVTableTransitionProtocol {
func transitionTableView() -> UITableView! {
return tableView
}
}
extension SLV_501_ProcuctDetailController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.bottomView.isHidden = true
let fields = [self.thatgulField]
_ = fields.map() {
if textField == $0 {
if textField.inputAccessoryView == nil {
textField.inputAccessoryView = self.myToolbar
}
self.myToolbar.currentView = textField
return
}
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let text = textField.text?.trimmed
self.endEditingInput(text: text!)
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.thatgulField?.inputAccessoryView = nil
self.bottomView.isHidden = false
let text = textField.text?.trimmed
self.endEditingInput(text: text!)
}
func endEditingInput(text: String) {
if text != "" {
let seller = self.listProductInfo?.userId
let user = BBAuthToken.shared.name()
if seller == user {
//TODO: 판매자가 사용자가 동일하면 댓글 등록을 못하게 처리한다.
let thatId = "" //어떤 댓글에 답변할 댓글인지를 알아야 한다.(문의사항)
ProductsModel.shared.newReply(thatgulId: thatId, text: text, completion: { (success) in
if success == true {
self.thatgulField?.text = ""
self.loadThatguls()
}
})
} else {
let productId = self.listProductInfo?.id?.copy() as! String
ProductsModel.shared.newComment(productId: productId, text: text, completion: { (success) in
if success == true {
self.thatgulField?.text = ""
self.loadThatguls()
}
})
}
}
}
}
| mit | 4b6e1a21f06db14df4bb1169b8e96d1d | 38.361575 | 237 | 0.54258 | 4.553424 | false | false | false | false |
OpenKitten/MongoKitten | Sources/MongoCore/Protocol/MessageHeader.swift | 2 | 1139 | import BSON
public struct MongoMessageHeader {
public enum OpCode: Int32 {
case reply = 1
case update = 2001
case insert = 2002
// Reserved = 2003
case query = 2004
case getMore = 2005
case delete = 2006
case killCursors = 2007
case message = 2013
}
public static let byteSize: Int32 = 16
public let messageLength: Int32
public var bodyLength: Int32 {
return messageLength - MongoMessageHeader.byteSize
}
public var requestId: Int32
public var responseTo: Int32
public var opCode: OpCode
internal init(messageLength: Int32, requestId: Int32, responseTo: Int32, opCode: OpCode) {
self.messageLength = messageLength
self.requestId = requestId
self.responseTo = responseTo
self.opCode = opCode
}
public init(bodyLength: Int32, requestId: Int32, responseTo: Int32, opCode: OpCode) {
self.messageLength = MongoMessageHeader.byteSize + bodyLength
self.requestId = requestId
self.responseTo = responseTo
self.opCode = opCode
}
}
| mit | 532f6aa46cebe7f7f4b1985ff8ee2a99 | 28.205128 | 94 | 0.636523 | 4.726141 | false | false | false | false |
ManueGE/Actions | actions/actions/Action.swift | 1 | 2186 | //
// Action.swift
// actions
//
// Created by Manu on 1/6/16.
// Copyright © 2016 manuege. All rights reserved.
//
import UIKit
import ObjectiveC
/**
Protocol used to convert Swift closures into ObjC selectors
*/
@objc public protocol Action {
// The key used to store the `Action`. Must be unique.
var key: String { get }
// The selector provided by the action
var selector: Selector { get }
}
// Action that takes zero parameters
class VoidAction: Action {
@objc let key = ProcessInfo.processInfo.globallyUniqueString
@objc let selector: Selector = #selector(perform)
var action: (() -> Void)!
init(action: @escaping () -> Void) {
self.action = action
}
@objc func perform() {
action()
}
}
// Action which takes one single parameter
class ParametizedAction<T: Any>: Action {
@objc let key = ProcessInfo.processInfo.globallyUniqueString
@objc let selector: Selector = #selector(perform)
let action: ((T) -> Void)!
init(action: @escaping (T) -> Void) {
self.action = action
}
@objc func perform(parameter: AnyObject) {
action(parameter as! T)
}
}
// MARK: Actionable
/*!
Actionable is a protocol used to store `Action` instances. Its only purpose is avoid them to be deallocated.
*/
protocol Actionable: class {
var actions: [String: Action]! { get }
}
private var actionsKey: UInt8 = 0
extension Actionable {
fileprivate(set) var actions: [String: Action]! {
get {
var actions = objc_getAssociatedObject(self, &actionsKey) as? [String: Action]
if actions == nil {
actions = [:]
self.actions = actions
}
return actions
}
set(newValue) {
objc_setAssociatedObject(self, &actionsKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
}
func retainAction(_ action: Action, _ object: NSObject) {
object.actions[action.key] = action
}
func releaseAction(_ action: Action, _ object: NSObject) {
object.actions[action.key] = nil
}
extension NSObject: Actionable {}
| mit | 88a425cf3a7226519e0e123be2e984b8 | 22.494624 | 109 | 0.612815 | 4.185824 | false | false | false | false |
prey/prey-ios-client | Prey/Swifter/DemoServer.swift | 1 | 6427 | //
// DemoServer.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
// swiftlint:disable function_body_length
public func demoServer(_ publicDir: String) -> HttpServer {
print(publicDir)
let server = HttpServer()
server["/public/:path"] = shareFilesFromDirectory(publicDir)
server["/files/:path"] = directoryBrowser("/")
server["/"] = scopes {
html {
body {
ul(server.routes) { service in
li {
a { href = service; inner = service }
}
}
}
}
}
server["/magic"] = { .ok(.html("You asked for " + $0.path)) }
server["/test/:param1/:param2"] = { request in
scopes {
html {
body {
h3 { inner = "Address: \(request.address ?? "unknown")" }
h3 { inner = "Url: \(request.path)" }
h3 { inner = "Method: \(request.method)" }
h3 { inner = "Query:" }
table(request.queryParams) { param in
tr {
td { inner = param.0 }
td { inner = param.1 }
}
}
h3 { inner = "Headers:" }
table(request.headers) { header in
tr {
td { inner = header.0 }
td { inner = header.1 }
}
}
h3 { inner = "Route params:" }
table(request.params) { param in
tr {
td { inner = param.0 }
td { inner = param.1 }
}
}
}
}
}(request)
}
server.GET["/upload"] = scopes {
html {
body {
form {
method = "POST"
action = "/upload"
enctype = "multipart/form-data"
input { name = "my_file1"; type = "file" }
input { name = "my_file2"; type = "file" }
input { name = "my_file3"; type = "file" }
button {
type = "submit"
inner = "Upload"
}
}
}
}
}
server.POST["/upload"] = { request in
var response = ""
for multipart in request.parseMultiPartFormData() {
guard let name = multipart.name, let fileName = multipart.fileName else { continue }
response += "Name: \(name) File name: \(fileName) Size: \(multipart.body.count)<br>"
}
return HttpResponse.ok(.html(response))
}
server.GET["/login"] = scopes {
html {
head {
script { src = "http://cdn.staticfile.org/jquery/2.1.4/jquery.min.js" }
stylesheet { href = "http://cdn.staticfile.org/twitter-bootstrap/3.3.0/css/bootstrap.min.css" }
}
body {
h3 { inner = "Sign In" }
form {
method = "POST"
action = "/login"
fieldset {
input { placeholder = "E-mail"; name = "email"; type = "email"; autofocus = "" }
input { placeholder = "Password"; name = "password"; type = "password"; autofocus = "" }
a {
href = "/login"
button {
type = "submit"
inner = "Login"
}
}
}
}
javascript {
src = "http://cdn.staticfile.org/twitter-bootstrap/3.3.0/js/bootstrap.min.js"
}
}
}
}
server.POST["/login"] = { request in
let formFields = request.parseUrlencodedForm()
return HttpResponse.ok(.html(formFields.map({ "\($0.0) = \($0.1)" }).joined(separator: "<br>")))
}
server["/demo"] = scopes {
html {
body {
center {
h2 { inner = "Hello Swift" }
img { src = "https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png" }
}
}
}
}
server["/raw"] = { _ in
return HttpResponse.raw(200, "OK", ["XXX-Custom-Header": "value"], { try $0.write([UInt8]("test".utf8)) })
}
server["/redirect/permanently"] = { _ in
return .movedPermanently("http://www.google.com")
}
server["/redirect/temporarily"] = { _ in
return .movedTemporarily("http://www.google.com")
}
server["/long"] = { _ in
var longResponse = ""
for index in 0..<1000 { longResponse += "(\(index)),->" }
return .ok(.html(longResponse))
}
server["/wildcard/*/test/*/:param"] = { request in
return .ok(.html(request.path))
}
server["/stream"] = { _ in
return HttpResponse.raw(200, "OK", nil, { writer in
for index in 0...100 {
try writer.write([UInt8]("[chunk \(index)]".utf8))
}
})
}
server["/websocket-echo"] = websocket(text: { (session, text) in
session.writeText(text)
}, binary: { (session, binary) in
session.writeBinary(binary)
}, pong: { (_, _) in
// Got a pong frame
}, connected: { _ in
// New client connected
}, disconnected: { _ in
// Client disconnected
})
server.notFoundHandler = { _ in
return .movedPermanently("https://github.com/404")
}
server.middleware.append { request in
print("Middleware: \(request.address ?? "unknown address") -> \(request.method) -> \(request.path)")
return nil
}
return server
}
| gpl-3.0 | 0964acdae252b5e4c57c9396c0bf4df1 | 30.194175 | 114 | 0.403361 | 4.820705 | false | false | false | false |
shadanan/mado | Antlr4Runtime/Sources/Antlr4/tree/pattern/ParseTreePatternMatcher.swift | 1 | 21396 | /* 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 tree pattern matching mechanism for ANTLR {@link org.antlr.v4.runtime.tree.ParseTree}s.
*
* <p>Patterns are strings of source input text with special tags representing
* token or rule references such as:</p>
*
* <p>{@code <ID> = <expr>;}</p>
*
* <p>Given a pattern start rule such as {@code statement}, this object constructs
* a {@link org.antlr.v4.runtime.tree.ParseTree} with placeholders for the {@code ID} and {@code expr}
* subtree. Then the {@link #match} routines can compare an actual
* {@link org.antlr.v4.runtime.tree.ParseTree} from a parse with this pattern. Tag {@code <ID>} matches
* any {@code ID} token and tag {@code <expr>} references the result of the
* {@code expr} rule (generally an instance of {@code ExprContext}.</p>
*
* <p>Pattern {@code x = 0;} is a similar pattern that matches the same pattern
* except that it requires the identifier to be {@code x} and the expression to
* be {@code 0}.</p>
*
* <p>The {@link #matches} routines return {@code true} or {@code false} based
* upon a match for the tree rooted at the parameter sent in. The
* {@link #match} routines return a {@link org.antlr.v4.runtime.tree.pattern.ParseTreeMatch} object that
* contains the parse tree, the parse tree pattern, and a map from tag name to
* matched nodes (more below). A subtree that fails to match, returns with
* {@link org.antlr.v4.runtime.tree.pattern.ParseTreeMatch#mismatchedNode} set to the first tree node that did not
* match.</p>
*
* <p>For efficiency, you can compile a tree pattern in string form to a
* {@link org.antlr.v4.runtime.tree.pattern.ParseTreePattern} object.</p>
*
* <p>See {@code TestParseTreeMatcher} for lots of examples.
* {@link org.antlr.v4.runtime.tree.pattern.ParseTreePattern} has two static helper methods:
* {@link org.antlr.v4.runtime.tree.pattern.ParseTreePattern#findAll} and {@link org.antlr.v4.runtime.tree.pattern.ParseTreePattern#match} that
* are easy to use but not super efficient because they create new
* {@link org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher} objects each time and have to compile the
* pattern in string form before using it.</p>
*
* <p>The lexer and parser that you pass into the {@link org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher}
* constructor are used to parse the pattern in string form. The lexer converts
* the {@code <ID> = <expr>;} into a sequence of four tokens (assuming lexer
* throws out whitespace or puts it on a hidden channel). Be aware that the
* input stream is reset for the lexer (but not the parser; a
* {@link org.antlr.v4.runtime.ParserInterpreter} is created to parse the input.). Any user-defined
* fields you have put into the lexer might get changed when this mechanism asks
* it to scan the pattern string.</p>
*
* <p>Normally a parser does not accept token {@code <expr>} as a valid
* {@code expr} but, from the parser passed in, we create a special version of
* the underlying grammar representation (an {@link org.antlr.v4.runtime.atn.ATN}) that allows imaginary
* tokens representing rules ({@code <expr>}) to match entire rules. We call
* these <em>bypass alternatives</em>.</p>
*
* <p>Delimiters are {@code <} and {@code >}, with {@code \} as the escape string
* by default, but you can set them to whatever you want using
* {@link #setDelimiters}. You must escape both start and stop strings
* {@code \<} and {@code \>}.</p>
*/
public class ParseTreePatternMatcher {
// public class CannotInvokeStartRule : RuntimeException {
// public convenience init(_ e : Throwable) {
// super.init(e);
// }
// }
//
// // Fixes https://github.com/antlr/antlr4/issues/413
// // "Tree pattern compilation doesn't check for a complete parse"
// public class StartRuleDoesNotConsumeFullPattern : RuntimeException {
// }
/**
* This is the backing field for {@link #getLexer()}.
*/
private final var lexer: Lexer
/**
* This is the backing field for {@link #getParser()}.
*/
private final var parser: Parser
internal var start: String = "<"
internal var stop: String = ">"
internal var escape: String = "\\"
// e.g., \< and \> must escape BOTH!
/**
* Constructs a {@link org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher} or from a {@link org.antlr.v4.runtime.Lexer} and
* {@link org.antlr.v4.runtime.Parser} object. The lexer input stream is altered for tokenizing
* the tree patterns. The parser is used as a convenient mechanism to get
* the grammar name, plus token, rule names.
*/
public init(_ lexer: Lexer, _ parser: Parser) {
self.lexer = lexer
self.parser = parser
}
/**
* Set the delimiters used for marking rule and token tags within concrete
* syntax used by the tree pattern parser.
*
* @param start The start delimiter.
* @param stop The stop delimiter.
* @param escapeLeft The escape sequence to use for escaping a start or stop delimiter.
*
* @exception IllegalArgumentException if {@code start} is {@code null} or empty.
* @exception IllegalArgumentException if {@code stop} is {@code null} or empty.
*/
public func setDelimiters(_ start: String, _ stop: String, _ escapeLeft: String) throws {
//start == nil ||
if start.isEmpty {
throw ANTLRError.illegalArgument(msg: "start cannot be null or empty")
// RuntimeException("start cannot be null or empty")
//throwException() /* throw IllegalArgumentException("start cannot be null or empty"); */
}
//stop == nil ||
if stop.isEmpty {
throw ANTLRError.illegalArgument(msg: "stop cannot be null or empty")
//RuntimeException("stop cannot be null or empty")
//throwException() /* throw IllegalArgumentException("stop cannot be null or empty"); */
}
self.start = start
self.stop = stop
self.escape = escapeLeft
}
/** Does {@code pattern} matched as rule {@code patternRuleIndex} match {@code tree}? */
public func matches(_ tree: ParseTree, _ pattern: String, _ patternRuleIndex: Int) throws -> Bool {
let p: ParseTreePattern = try compile(pattern, patternRuleIndex)
return try matches(tree, p)
}
/** Does {@code pattern} matched as rule patternRuleIndex match tree? Pass in a
* compiled pattern instead of a string representation of a tree pattern.
*/
public func matches(_ tree: ParseTree, _ pattern: ParseTreePattern) throws -> Bool {
let labels: MultiMap<String, ParseTree> = MultiMap<String, ParseTree>()
let mismatchedNode: ParseTree? = try matchImpl(tree, pattern.getPatternTree(), labels)
return mismatchedNode == nil
}
/**
* Compare {@code pattern} matched as rule {@code patternRuleIndex} against
* {@code tree} and return a {@link org.antlr.v4.runtime.tree.pattern.ParseTreeMatch} object that contains the
* matched elements, or the node at which the match failed.
*/
public func match(_ tree: ParseTree, _ pattern: String, _ patternRuleIndex: Int) throws -> ParseTreeMatch {
let p: ParseTreePattern = try compile(pattern, patternRuleIndex)
return try match(tree, p)
}
/**
* Compare {@code pattern} matched against {@code tree} and return a
* {@link org.antlr.v4.runtime.tree.pattern.ParseTreeMatch} object that contains the matched elements, or the
* node at which the match failed. Pass in a compiled pattern instead of a
* string representation of a tree pattern.
*/
public func match(_ tree: ParseTree, _ pattern: ParseTreePattern) throws -> ParseTreeMatch {
let labels: MultiMap<String, ParseTree> = MultiMap<String, ParseTree>()
let mismatchedNode: ParseTree? = try matchImpl(tree, pattern.getPatternTree(), labels)
return ParseTreeMatch(tree, pattern, labels, mismatchedNode)
}
/**
* For repeated use of a tree pattern, compile it to a
* {@link org.antlr.v4.runtime.tree.pattern.ParseTreePattern} using this method.
*/
public func compile(_ pattern: String, _ patternRuleIndex: Int) throws -> ParseTreePattern {
let tokenList: Array<Token> = try tokenize(pattern)
let tokenSrc: ListTokenSource = ListTokenSource(tokenList)
let tokens: CommonTokenStream = CommonTokenStream(tokenSrc)
let parserInterp: ParserInterpreter = try ParserInterpreter(parser.getGrammarFileName(),
parser.getVocabulary(),
parser.getRuleNames(),
parser.getATNWithBypassAlts(),
tokens)
var tree: ParseTree //= nil;
//TODO: exception handler
//try {
parserInterp.setErrorHandler(BailErrorStrategy())
tree = try parserInterp.parse(patternRuleIndex)
// print("pattern tree = "+tree.toStringTree(parserInterp));
// }
// catch (ParseCancellationException e) {
// throwException() /* throw e.getCause() as RecognitionException; */
// }
// catch (RecognitionException re) {
// throwException() /* throw re; */
// }
// catch (Exception e) {
// throwException() /* throw CannotInvokeStartRule(e); */
// }
// Make sure tree pattern compilation checks for a complete parse
if try tokens.LA(1) != CommonToken.EOF {
throw ANTLRError.illegalState(msg: "Tree pattern compilation doesn't check for a complete parse")
// RuntimeException("Tree pattern compilation doesn't check for a complete parse")
//throw ANTLRException.StartRuleDoesNotConsumeFullPattern
//throwException() /* throw StartRuleDoesNotConsumeFullPattern(); */
}
return ParseTreePattern(self, pattern, patternRuleIndex, tree)
}
/**
* Used to convert the tree pattern string into a series of tokens. The
* input stream is reset.
*/
public func getLexer() -> Lexer {
return lexer
}
/**
* Used to collect to the grammar file name, token names, rule names for
* used to parse the pattern into a parse tree.
*/
public func getParser() -> Parser {
return parser
}
// ---- SUPPORT CODE ----
/**
* Recursively walk {@code tree} against {@code patternTree}, filling
* {@code match.}{@link org.antlr.v4.runtime.tree.pattern.ParseTreeMatch#labels labels}.
*
* @return the first node encountered in {@code tree} which does not match
* a corresponding node in {@code patternTree}, or {@code null} if the match
* was successful. The specific node returned depends on the matching
* algorithm used by the implementation, and may be overridden.
*/
internal func matchImpl(_ tree: ParseTree,
_ patternTree: ParseTree,
_ labels: MultiMap<String, ParseTree>) throws -> ParseTree? {
// x and <ID>, x and y, or x and x; or could be mismatched types
if tree is TerminalNode && patternTree is TerminalNode {
let t1: TerminalNode = tree as! TerminalNode
let t2: TerminalNode = patternTree as! TerminalNode
var mismatchedNode: ParseTree? = nil
// both are tokens and they have same type
if t1.getSymbol()!.getType() == t2.getSymbol()!.getType() {
if t2.getSymbol() is TokenTagToken {
// x and <ID>
let tokenTagToken: TokenTagToken = t2.getSymbol() as! TokenTagToken
// track label->list-of-nodes for both token name and label (if any)
labels.map(tokenTagToken.getTokenName(), tree)
if tokenTagToken.getLabel() != nil {
labels.map(tokenTagToken.getLabel()!, tree)
}
} else {
if t1.getText() == t2.getText() {
// x and x
} else {
// x and y
if mismatchedNode == nil {
mismatchedNode = t1
}
}
}
} else {
if mismatchedNode == nil {
mismatchedNode = t1
}
}
return mismatchedNode
}
if tree is ParserRuleContext && patternTree is ParserRuleContext {
let r1: ParserRuleContext = tree as! ParserRuleContext
let r2: ParserRuleContext = patternTree as! ParserRuleContext
var mismatchedNode: ParseTree? = nil
// (expr ...) and <expr>
if let ruleTagToken = getRuleTagToken(r2) {
//var m : ParseTreeMatch? = nil;
if r1.getRuleContext().getRuleIndex() == r2.getRuleContext().getRuleIndex() {
// track label->list-of-nodes for both rule name and label (if any)
labels.map(ruleTagToken.getRuleName(), tree)
if ruleTagToken.getLabel() != nil {
labels.map(ruleTagToken.getLabel()!, tree)
}
} else {
if mismatchedNode == nil {
mismatchedNode = r1
}
}
return mismatchedNode
}
// (expr ...) and (expr ...)
if r1.getChildCount() != r2.getChildCount() {
if mismatchedNode == nil {
mismatchedNode = r1
}
return mismatchedNode
}
let n: Int = r1.getChildCount()
for i in 0..<n {
let childMatch: ParseTree? =
try matchImpl(r1.getChild(i) as! ParseTree, patternTree.getChild(i) as! ParseTree, labels)
if childMatch != nil {
return childMatch
}
}
return mismatchedNode
}
// if nodes aren't both tokens or both rule nodes, can't match
return tree
}
/** Is {@code t} {@code (expr <expr>)} subtree? */
internal func getRuleTagToken(_ t: ParseTree) -> RuleTagToken? {
if t is RuleNode {
let r: RuleNode = t as! RuleNode
if r.getChildCount() == 1 && r.getChild(0) is TerminalNode {
let c: TerminalNode = r.getChild(0) as! TerminalNode
if c.getSymbol() is RuleTagToken {
// print("rule tag subtree "+t.toStringTree(parser));
return c.getSymbol() as? RuleTagToken
}
}
}
return nil
}
public func tokenize(_ pattern: String) throws -> Array<Token> {
// split pattern into chunks: sea (raw input) and islands (<ID>, <expr>)
let chunks: Array<Chunk> = try split(pattern)
// create token stream from text and tags
var tokens: Array<Token> = Array<Token>()
for chunk: Chunk in chunks {
if chunk is TagChunk {
let tagChunk: TagChunk = chunk as! TagChunk
// add special rule token or conjure up new token from name
let firstStr = String(tagChunk.getTag()[0])
if firstStr.lowercased() != firstStr {
//if ( Character.isUpperCase(tagChunk.getTag().charAt(0)) ) {
let ttype: Int = parser.getTokenType(tagChunk.getTag())
if ttype == CommonToken.INVALID_TYPE {
throw ANTLRError.illegalArgument(msg: "Unknown token " + tagChunk.getTag() + " in pattern: " + pattern)
}
let t: TokenTagToken = TokenTagToken(tagChunk.getTag(), ttype, tagChunk.getLabel())
tokens.append(t)
} else {
if firstStr.uppercased() != firstStr {
// if ( Character.isLowerCase(tagChunk.getTag().charAt(0)) ) {
let ruleIndex: Int = parser.getRuleIndex(tagChunk.getTag())
if ruleIndex == -1 {
throw ANTLRError.illegalArgument(msg: "Unknown rule " + tagChunk.getTag() + " in pattern: " + pattern)
}
let ruleImaginaryTokenType: Int = parser.getATNWithBypassAlts().ruleToTokenType[ruleIndex]
tokens.append(RuleTagToken(tagChunk.getTag(), ruleImaginaryTokenType, tagChunk.getLabel()))
} else {
throw ANTLRError.illegalArgument(msg: "invalid tag: " + tagChunk.getTag() + " in pattern: " + pattern)
}
}
} else {
let textChunk: TextChunk = chunk as! TextChunk
let inputStream: ANTLRInputStream = ANTLRInputStream(textChunk.getText())
try lexer.setInputStream(inputStream)
var t: Token = try lexer.nextToken()
while t.getType() != CommonToken.EOF {
tokens.append(t)
t = try lexer.nextToken()
}
}
}
// print("tokens="+tokens);
return tokens
}
/** Split {@code <ID> = <e:expr> ;} into 4 chunks for tokenizing by {@link #tokenize}. */
public func split(_ pattern: String) throws -> Array<Chunk> {
var p: Int = 0
let n: Int = pattern.length
var chunks: Array<Chunk> = Array<Chunk>()
//var buf : StringBuilder = StringBuilder();
// find all start and stop indexes first, then collect
var starts: Array<Int> = Array<Int>()
var stops: Array<Int> = Array<Int>()
while p < n {
if p == pattern.indexOf(escape + start, startIndex: p) {
p += escape.length + start.length
} else {
if p == pattern.indexOf(escape + stop, startIndex: p) {
p += escape.length + stop.length
} else {
if p == pattern.indexOf(start, startIndex: p) {
starts.append(p)
p += start.length
} else {
if p == pattern.indexOf(stop, startIndex: p) {
stops.append(p)
p += stop.length
} else {
p += 1
}
}
}
}
}
if starts.count > stops.count {
throw ANTLRError.illegalArgument(msg: "unterminated tag in pattern: " + pattern)
}
if starts.count < stops.count {
throw ANTLRError.illegalArgument(msg: "missing start tag in pattern: " + pattern)
}
let ntags: Int = starts.count
for i in 0..<ntags {
if starts[i] != stops[i] {
throw ANTLRError.illegalArgument(msg: "tag delimiters out of order in pattern: " + pattern)
}
}
// collect into chunks now
if ntags == 0 {
let text: String = pattern[0 ..< n]
chunks.append(TextChunk(text))
}
if ntags > 0 && starts[0] > 0 {
// copy text up to first tag into chunks
let text: String = pattern[0 ..< starts[0]] //; substring(0, starts.get(0));
chunks.append(TextChunk(text))
}
for i in 0..<ntags {
// copy inside of <tag>
let tag: String = pattern[starts[i] + start.length ..< stops[i]] // pattern.substring(starts.get(i) + start.length(), stops.get(i));
var ruleOrToken: String = tag
var label: String = ""
let colon: Int = tag.indexOf(":")
if colon >= 0 {
label = tag[0 ..< colon] //(0,colon);
ruleOrToken = tag[colon + 1 ..< tag.length] //(colon+1, tag.length());
}
chunks.append(try TagChunk(label, ruleOrToken))
if i + 1 < ntags {
// copy from end of <tag> to start of next
let text: String = pattern[stops[i] + stop.length ..< starts[i] + 1] //.substring(stops.get(i) + stop.length(), starts.get(i + 1));
chunks.append(TextChunk(text))
}
}
if ntags > 0 {
let afterLastTag: Int = stops[ntags - 1] + stop.length
if afterLastTag < n {
// copy text from end of last tag to end
let text: String = pattern[afterLastTag ..< n] //.substring(afterLastTag, n);
chunks.append(TextChunk(text))
}
}
// strip out the escape sequences from text chunks but not tags
let length = chunks.count
for i in 0..<length {
let c: Chunk = chunks[i]
if c is TextChunk {
let tc: TextChunk = c as! TextChunk
let unescaped: String = tc.getText().replaceAll(escape, replacement: "")
if unescaped.length < tc.getText().length {
chunks[i] = TextChunk(unescaped)
}
}
}
return chunks
}
}
| mit | e2f8d390ebd63686174f49d53d8765fa | 42.311741 | 147 | 0.582071 | 4.412456 | false | false | false | false |
coolgeng/swiftris | swiftris/swiftris/Block.swift | 1 | 1485 | //
// Block.swift
// swiftris
//
// Created by Yong on 5/7/15.
// Copyright (c) 2015 Yong. All rights reserved.
//
import SpriteKit
let NumberOfColors: UInt32 = 6
enum BlockColor: Int, Printable {
case Blue = 0, Orange, Purple, Red, Teal, Yellow
var spriteName: String {
switch self {
case .Blue:
return "blue"
case .Orange:
return "orange"
case .Purple:
return "purple"
case .Red:
return "red"
case .Teal:
return "teal"
case .Yellow:
return "yellow"
}
}
var description: String {
return self.spriteName
}
static func random() -> BlockColor {
return BlockColor(rawValue: Int(arc4random_uniform(NumberOfColors)))!
}
}
class Block: Hashable, Printable {
let color: BlockColor
var column: Int
var row: Int
var sprite: SKSpriteNode?
var spriteName: String{
return color.spriteName
}
var hashValue: Int {
return self.column ^ self.row
}
var description: String {
return "\(color): [\(column), \(row)]"
}
init(column: Int, row: Int, color: BlockColor) {
self.column = column
self.row = row
self.color = color
}
}
func == (lhs: Block, rhs: Block) -> Bool {
return lhs.column == rhs.column && lhs.row == rhs.row && lhs.color.rawValue == rhs.color.rawValue
}
| mit | d2dfa1e2954e269549cee735b44dbef1 | 19.625 | 101 | 0.547475 | 4.002695 | false | false | false | false |
jmalesh/CareShare | CareShare/CareShare/ShoppingListViewController.swift | 1 | 5745 | //
// ShoppingListViewController.swift
// CareShare
//
// Created by Jessica Malesh on 7/7/16.
// Copyright © 2016 Jess Malesh. All rights reserved.
//
import UIKit
import CoreData
class ShoppingListViewController: UITableViewController
{
@IBOutlet var shoppingTableView: UITableView!
var list = [NSManagedObject]()
override func viewDidLoad()
{
super.viewDidLoad()
title = "Shopping List"
shoppingTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Shopping")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
list = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
@IBAction func addItem(sender: AnyObject)
{
let alert = UIAlertController(title: "New Item", message: "Add a new item", preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save", style: .Default, handler: { (action: UIAlertAction) -> Void in
let textField = alert.textFields!.first
self.saveItem(textField!.text!)
self.shoppingTableView.reloadData()
})
let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction) -> Void in
}
alert.addTextFieldWithConfigurationHandler
{
(textField: UITextField) -> Void in
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
presentViewController(alert, animated: true, completion: nil)
}
func saveItem(item: String!)
{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("Shopping", inManagedObjectContext: managedContext)
let shop = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
shop.setValue(item, forKey: "item")
do {
try managedContext.save()
list.append(shop)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return list.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
let shop = list[indexPath.row]
cell!.textLabel!.text = shop.valueForKey("item") as! String
return cell!
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
list.removeAtIndex(indexPath.row)
shoppingTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
}
| mit | 9f1a45e85ed28974444b7a6b464999f9 | 31.822857 | 157 | 0.648329 | 5.692765 | false | false | false | false |
Bouke/LedgerTools | Sources/ledger-import-csv/NSRegularExpression+Swift.swift | 1 | 1002 | import Foundation
struct MatchResult {
var string: String
var result: NSTextCheckingResult
var match: String {
let start = String.UTF16Index(result.range.location)
let end = String.UTF16Index(result.range.location + result.range.length)
return String(string.utf16[start..<end])!
}
var groups: [String] {
return (1..<result.numberOfRanges).map { rangeIndex in
let range = result.rangeAt(rangeIndex)
let start = String.UTF16Index(range.location)
let end = String.UTF16Index(range.location + range.length)
return String(string.utf16[start..<end])!
}
}
}
extension NSRegularExpression {
func matches(`in` string: String, options: NSRegularExpression.MatchingOptions = []) -> [MatchResult] {
let range = NSRange(location: 0, length: string.utf16.count)
return self.matches(in: string, options: options, range: range).map { MatchResult(string: string, result: $0) }
}
}
| mit | 3bef11ababd73f8a3fa591648ecdaf4f | 37.538462 | 119 | 0.656687 | 4.157676 | false | false | false | false |
SpiciedCrab/MGRxKitchen | Example/MGRxKitchen/TableViewTestViewModel.swift | 1 | 2253 | //
// TableViewTestViewModel.swift
// RxMogo
//
// Created by Harly on 2017/8/7.
// Copyright © 2017年 Harly. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
import MGRxActivityIndicator
import MGRxKitchen
import MGBricks
import Result
internal class MGItem {
var name: String = ""
init(str: String) {
name = str
}
}
internal class TableViewTestViewModel: HaveRequestRx, PageableJSONRequest, PageExtensible {
var pageOutputer: PublishSubject<MGPage> = PublishSubject<MGPage>()
typealias PageJSONType = SuperDemo
var jsonOutputer: PublishSubject<SuperDemo> = PublishSubject<SuperDemo>()
var loadingActivity: ActivityIndicator = ActivityIndicator()
var errorProvider: PublishSubject<RxMGError> = PublishSubject<RxMGError>()
var firstPage: PublishSubject<Void> = PublishSubject()
var nextPage: PublishSubject<Void> = PublishSubject()
//Output
var finalPageReached: PublishSubject<Void> = PublishSubject()
let disposeBag: DisposeBag = DisposeBag()
let service: MockService = MockService()
var serviceDriver: Observable<[Demo]>!
init() {
}
func initial() {
// pagedRequest(request: <#T##(MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>>#>)
// let requestObser: Observable<Result<([Demo], MGPage), MGAPIError>> = interuptPage(origin: self.service.providePageJSONMock(on: 1)) { json -> [Demo] in
// return json.demos
// }
//
// serviceDriver = pagedRequest(request: { _ in requestObser })
serviceDriver = pagedRequest(request: { page -> Observable<Result<([String : Any], MGPage), MGAPIError>> in
return self.service.providePageJSONMock(on: page.currentPage)
}) { json -> [Demo] in
return json.demos
}
}
func sectionableData() -> Observable<[MGSection<MGItem>]> {
let item1 = MGItem(str: "1")
let item2 = MGItem(str: "2")
let item3 = MGItem(str: "4")
let item4 = MGItem(str: "5")
let section1 = MGSection(header: "header1", items: [item1, item2])
let section2 = MGSection(header: "header2", items: [item3, item4])
return Observable.of([section1, section2])
}
}
| mit | 4a9f280c1f2c21398da83ec2b4335414 | 26.108434 | 160 | 0.660444 | 3.968254 | false | false | false | false |
debugsquad/nubecero | nubecero/View/Home/VHomeCellUpload.swift | 1 | 1789 | import UIKit
class VHomeCellUpload:VHomeCell
{
private weak var layoutAddLeft:NSLayoutConstraint!
private let kAddWidth:CGFloat = 150
override init(frame:CGRect)
{
super.init(frame:frame)
let add:VHomeCellUploadAdd = VHomeCellUploadAdd()
add.addTarget(
self,
action:#selector(actionAdd(sender:)),
for:UIControlEvents.touchUpInside)
addSubview(add)
let views:[String:UIView] = [
"add":add]
let metrics:[String:CGFloat] = [
"addWidth":kAddWidth]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:[add(addWidth)]",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-20-[add]-0-|",
options:[],
metrics:metrics,
views:views))
layoutAddLeft = NSLayoutConstraint(
item:add,
attribute:NSLayoutAttribute.left,
relatedBy:NSLayoutRelation.equal,
toItem:self,
attribute:NSLayoutAttribute.left,
multiplier:1,
constant:0)
addConstraint(layoutAddLeft)
}
required init?(coder:NSCoder)
{
fatalError()
}
override func layoutSubviews()
{
let width:CGFloat = bounds.size.width
let remain:CGFloat = width - kAddWidth
let margin:CGFloat = remain / 2.0
layoutAddLeft.constant = margin
super.layoutSubviews()
}
//MARK: actions
func actionAdd(sender button:UIButton)
{
controller?.uploadPictures()
}
}
| mit | 6214c4283a969e49d5145f14cafe0f38 | 24.557143 | 57 | 0.555618 | 5.15562 | false | false | false | false |
filestack/filestack-ios | Sources/Filestack/UI/Internal/PhotoEditor/EditionController/Handlers/CropGesturesHandler.swift | 1 | 8118 | //
// CropGesturesHandler.swift
// EditImage
//
// Created by Mihály Papp on 12/07/2018.
// Copyright © 2018 Mihály Papp. All rights reserved.
//
import UIKit
protocol EditCropDelegate: EditDataSource {
func updateCropInset(_ inset: UIEdgeInsets)
}
class CropGesturesHandler {
typealias RelativeInsets = (top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat)
enum Corner {
case topLeft, topRight, bottomLeft, bottomRight, center, top, bottom, left, right
static var all: [Corner] = [.topLeft, .topRight, .bottomLeft, .bottomRight, .center, .top, .bottom, .left, .right]
}
weak var delegate: EditCropDelegate?
private var beginInset: RelativeInsets?
private var movingCorner: Corner?
private var relativeCropInsets = CropGesturesHandler.initialInsets
init(delegate: EditCropDelegate) {
self.delegate = delegate
}
var croppedRect: CGRect {
return delegate?.imageFrame.inset(by: cropInsets) ?? .zero
}
var actualEdgeInsets: UIEdgeInsets {
guard let delegate = delegate else { return .zero }
return UIEdgeInsets(top: relativeCropInsets.top * delegate.imageActualSize.height,
left: relativeCropInsets.left * delegate.imageActualSize.width,
bottom: relativeCropInsets.bottom * delegate.imageActualSize.height,
right: relativeCropInsets.right * delegate.imageActualSize.width)
}
func reset() {
relativeCropInsets = CropGesturesHandler.initialInsets
}
private static var initialInsets: RelativeInsets = RelativeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
extension CropGesturesHandler {
func handlePanGesture(recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: recognizer.view)
let origin = recognizer.location(in: recognizer.view).movedBy(x: -translation.x, y: -translation.y)
handle(translation: translation, from: origin, forState: recognizer.state)
}
func rotateCounterClockwise() {
let rotatedInsets = RelativeInsets(top: relativeCropInsets.right,
left: relativeCropInsets.top,
bottom: relativeCropInsets.left,
right: relativeCropInsets.bottom)
relativeCropInsets = rotatedInsets
}
}
private extension CropGesturesHandler {
var cropInsets: UIEdgeInsets {
get {
return edgeInsets(from: relativeCropInsets)
}
set {
relativeCropInsets = relativeInsets(from: newValue)
delegate?.updateCropInset(newValue)
}
}
func edgeInsets(from relativeInsets: RelativeInsets?) -> UIEdgeInsets {
guard let delegate = delegate, let relativeInsets = relativeInsets else { return .zero }
return UIEdgeInsets(top: relativeInsets.top * delegate.imageSize.height,
left: relativeInsets.left * delegate.imageSize.width,
bottom: relativeInsets.bottom * delegate.imageSize.height,
right: relativeInsets.right * delegate.imageSize.width)
}
func relativeInsets(from edgeInsets: UIEdgeInsets?) -> RelativeInsets {
guard let delegate = delegate, let edgeInsets = edgeInsets else {
return RelativeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
return RelativeInsets(top: edgeInsets.top / delegate.imageSize.height,
left: edgeInsets.left / delegate.imageSize.width,
bottom: edgeInsets.bottom / delegate.imageSize.height,
right: edgeInsets.right / delegate.imageSize.width)
}
}
private extension CropGesturesHandler {
func handle(translation: CGPoint, from origin: CGPoint, forState state: UIGestureRecognizer.State) {
guard let delegate = delegate else { return }
switch state {
case .began:
beginInset = relativeCropInsets
let adjustedPoint = origin.movedBy(x: -delegate.imageOrigin.x, y: -delegate.imageOrigin.y)
movingCorner = nearestCorner(for: adjustedPoint)
move(by: translation)
case .changed:
move(by: translation)
case .ended:
move(by: translation)
beginInset = nil
case .cancelled,
.failed:
resetTranslation(to: edgeInsets(from: beginInset))
case .possible:
fallthrough
@unknown default:
return
}
}
func location(of corner: Corner) -> CGPoint {
guard let delegate = delegate else { return .zero }
var top: CGFloat { return cropInsets.top }
var bottom: CGFloat { return delegate.imageSize.height - cropInsets.bottom }
var left: CGFloat { return cropInsets.left }
var right: CGFloat { return delegate.imageSize.width - cropInsets.right }
switch corner {
case .topLeft:
return CGPoint(x: left, y: top)
case .topRight:
return CGPoint(x: right, y: top)
case .bottomLeft:
return CGPoint(x: left, y: bottom)
case .bottomRight:
return CGPoint(x: right, y: bottom)
case .top:
return CGPoint(x: (left + right) / 2, y: top)
case .bottom:
return CGPoint(x: (left + right) / 2, y: bottom)
case .left:
return CGPoint(x: left, y: (top + bottom) / 2)
case .right:
return CGPoint(x: right, y: (top + bottom) / 2)
case .center:
return CGPoint(x: (left + right) / 2, y: (top + bottom) / 2)
}
}
func nearestCorner(for point: CGPoint) -> Corner? {
typealias CornerDistance = (corner: Corner, distance: CGFloat)
var distances = Corner.all.map { CornerDistance(corner: $0, distance: location(of: $0).distance(to: point)) }
distances = distances.filter { (_, distance) -> Bool in distance < 100 }
distances.sort(by: { $0.distance < $1.distance })
return distances.first?.corner
}
func resetTranslation(to insets: UIEdgeInsets?) {
guard let insets = insets else { return }
cropInsets = insets
}
func move(by translation: CGPoint) {
guard let delegate = delegate, let beginInset = beginInset, let movingCorner = movingCorner else { return }
let startInset = edgeInsets(from: beginInset)
var top = startInset.top
var left = startInset.left
var right = startInset.right
var bottom = startInset.bottom
let minHeight = delegate.imageSize.height - top - bottom
let minWidth = delegate.imageSize.width - left - right
switch movingCorner {
case .topLeft:
top += min(translation.y, minHeight)
left += min(translation.x, minWidth)
case .topRight:
top += min(translation.y, minHeight)
right += min(-translation.x, minWidth)
case .bottomLeft:
bottom += min(-translation.y, minHeight)
left += min(translation.x, minWidth)
case .bottomRight:
bottom += min(-translation.y, minHeight)
right += min(-translation.x, minWidth)
case .top:
top += min(translation.y, minHeight)
case .bottom:
bottom += min(-translation.y, minHeight)
case .left:
left += min(translation.x, minWidth)
case .right:
right += min(-translation.x, minWidth)
case .center:
let moveVertical = clamp(translation.y, min: -top, max: bottom)
let moveHorizontal = clamp(translation.x, min: -left, max: right)
top += moveVertical
left += moveHorizontal
right += -moveHorizontal
bottom += -moveVertical
}
cropInsets = UIEdgeInsets(top: max(0, top), left: max(0, left), bottom: max(0, bottom), right: max(0, right))
}
}
| mit | e8934dfc41a3a71b7fd274fe77ce94bb | 36.569444 | 122 | 0.60838 | 4.587337 | false | false | false | false |
paidy/paidy-ios | PaidyCheckoutSDK/PaidyCheckoutSDK/Buyer.swift | 1 | 2442 | //
// Buyer.swift
// Paidycheckoutsdk
//
// Copyright (c) 2015 Paidy. All rights reserved.
//
import UIKit
import ObjectMapper
public class Buyer: Mappable {
var name: String!
var name2: String!
var dob: String!
public var email: Email!
public var phone: Phone!
public var address: Address!
public init(name: String, name2: String, dob: String){
self.name = name
self.name2 = name2
self.dob = dob
}
required public init?(_ map: Map) {
mapping(map)
}
// Mappable
public func mapping(map: Map) {
name <- map["name"]
name2 <- map["name2"]
dob <- map["dob"]
email <- map["email"]
phone <- map["phone"]
address <- map["address"]
}
public class Email: Mappable {
var address: String = ""
public init(address: String){
self.address = address
}
required public init?(_ map: Map) {
mapping(map)
}
// Mappable
public func mapping(map: Map) {
address <- map["address"]
}
}
public class Phone: Mappable {
var number: String = ""
public init(number: String){
self.number = number
}
required public init?(_ map: Map) {
mapping(map)
}
// Mappable
public func mapping(map: Map) {
number <- map["number"]
}
}
public class Address: Mappable {
var address1: String = ""
var address2: String = ""
var address3: String = ""
var address4: String = ""
var postal_code: String = ""
public init(address1: String, address2: String, address3: String, address4: String, postal_code: String){
self.address1 = address1
self.address2 = address2
self.address3 = address3
self.address4 = address4
self.postal_code = postal_code
}
required public init?(_ map: Map) {
mapping(map)
}
// Mappable
public func mapping(map: Map) {
address1 <- map["address1"]
address2 <- map["address2"]
address3 <- map["address3"]
address4 <- map["address4"]
postal_code <- map["postal_code"]
}
}
}
| mit | ac6adebcffef78c2b89306b7d4491dac | 23.178218 | 113 | 0.497543 | 4.384201 | false | false | false | false |
StephenZhuang/Gongyinglian | Gongyinglian/Gongyinglian/ListViewController.swift | 1 | 5250 | //
// ListViewController.swift
// Gongyinglian
//
// Created by Stephen Zhuang on 14-7-3.
// Copyright (c) 2014年 udows. All rights reserved.
//
import UIKit
class ListViewController: UITableViewController {
var dataArray: NSMutableArray?
init(style: UITableViewStyle) {
super.init(style: style)
// Custom initialization
}
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController.setNavigationBarHidden(false, animated: true)
self.addTitleView(title: "库存", subtitle: "库存查询")
self.dataArray = NSMutableArray()
self.refreshControl.addTarget(self, action: Selector("refreshControlValueChanged"), forControlEvents: .ValueChanged)
self.refreshControl!.beginRefreshing()
loadData()
}
func refreshControlValueChanged() {
if self.refreshControl.refreshing {
loadData()
}
}
func loadData() {
var params: NSMutableDictionary = NSMutableDictionary()
var dic: NSMutableDictionary = NSMutableDictionary()
dic.setObject("com.shqj.webservice.entity.UserKey", forKey: "class")
dic.setObject(ToolUtils.shareInstance().user!.key, forKey: "key")
let jsonString: NSString = dic.JSONString()
params.setObject(jsonString, forKey: "userkey")
var webservice: WebServiceRead = WebServiceRead()
webservice = WebServiceRead(self , selecter:Selector("webServiceFinished:"))
webservice.postWithMethodName("doQueryKc", params: params)
}
func webServiceFinished(data: NSString) {
var dic: NSDictionary = data.objectFromJSONString() as NSDictionary
var kcList: QueryKcList = QueryKcList()
kcList.build(dic)
self.dataArray!.removeAllObjects()
self.dataArray!.addObjectsFromArray(kcList.data)
self.tableView!.reloadData()
if self.refreshControl.refreshing {
self.refreshControl.endRefreshing()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.dataArray!.count
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell : GoodsCell! = tableView!.dequeueReusableCellWithIdentifier("cell") as GoodsCell
// Configure the cell...
var querykc:QueryKc = self.dataArray!.objectAtIndex(indexPath!.row) as QueryKc
cell.nameLabel.text = querykc.spname?
cell.codeLabel.text = querykc.spcode?
cell.countLabel.text = querykc.spcount?.stringValue
return cell
}
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
tableView!.deselectRowAtIndexPath(indexPath , animated:true)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath?) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView?, moveRowAtIndexPath fromIndexPath: NSIndexPath?, toIndexPath: NSIndexPath?) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView?, canMoveRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0929762e1ebd9fae1f16c5c8d15c5970 | 34.619048 | 159 | 0.671314 | 5.236 | false | false | false | false |
DominikBucher12/BEExtension | BEExtension/Identifiers+Info.swift | 1 | 4845 | //
// ContentIdentifiers.swift
// emptyProject
//
// Created by Dominik Bucher on 21/05/2017.
// Copyright © 2017 Dominik Bucher. All rights reserved.
//
import Foundation
import XcodeKit
/*
Maybe I should write down the algorithm in here:
The idea is pretty straightforward and simple, as everything in this world...well except you take one piece of task and you find out it is as comprehensive as the whole universe itself with revealing more things to study or observe... jokes aside, let's get to business.
1.) We must make sure, we are editing the right document -> It Cannot be Objective-C (Who wants to code Objective C anyway)
-> We use ContentUTI here (kUTTypeSwiftSource) AKA public.swift-source AKA spend whole night finding information about this AKA my head will blow
2.) We take our selected text
-> This is a bit complicated now, because of taking-text-from-buffer algorithm, so I will divide it into few tasks:
a) Get indexes of lines in a current file
a - optional) For the weak type of solution -> Get index of last selected line to recognize where to put the variable/switch
b) According to indexes, we extract our lines as [String]
c) Now we are done with taking the selected text
3.) After we got our beautiful iterating trought lines, we must extract the cases names and remove every garbage we don't need -> rawValue declarations, associatedTypes, handle multiple cases on one line...I WOULD LIKE TO THANK KEN THOMPSON AND DENNIS RITCHIE that we have one problem solved, Enum with raw type cannot have cases with arguments 🤔 (Yes, please refer to them as gods)
Anyway -> This freaking point includes impossible-to-do REGEX which I sure will be figuring out for at least 20 hours, so I will start timer and post the result(woahh great, only 3 hours thanks to that beautiful tool referenced in String+Extensions.swift file 😎
4.) Next thing we do is putting those cases into our switch/variable String containing the structure...
-> I would really love Swift to have a feature which is contained in other languages, including C# 🎸, which is priceless: Multilined Strings aka I love you
//C# :
String thisIsSuperBeautiful = @"
Hello there,
I am multilined text, as you can see,
this is my really cool feature, so I would be really happy to be your favourite programming language";
//Swifty Swift
let iDGAF: String = "Sup' bro\n" + "sorry, no multilines\n" + "but you can use your imagination\n" +
"or divide lines like this\n" +
"but you can forget semicolon\n" +
"or let it be as is"
//Objective-C bonus:
//oh how I hate this thing:
NSString *my_string = @"Good evening mister, \
even I can do multilines!";
//should work this way too:
NSString *whatsGoingOnWithThisSyntax = @"Good evening mister,"
"even I can do multilines!";
edit: Swift 4 🤵🏻
5.) After we fire this up we need to insert this text properly... I guess I will map functions under these points
*/
//TODO: Make more of singleton, didn't think of creating only one instance
struct Identifiers {
///Content UTIs identificators
///
/// -> You can do your homework and read [this](https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html)
///
/// Enum:
/// - swiftSource
public enum ContentUTIs: String {
case swiftSource = "public.swift-source"
}
//TODO: Make this more generic -> could be some class XcodeKitError which implements NSError straight to completionHandler
public enum PossibleErrors: LocalizedError {
case wrongUTI
case emptySelection
case wrongSelection
case `default`
var errorDescription: String {
switch self {
case .wrongUTI:
return NSLocalizedString("Wrong UTI, please ensure you are trying to edit Swift source code", comment: "wrong UTI")
case .emptySelection:
return NSLocalizedString("Empty selection, please select enum cases to work with", comment: "Empty selection")
case .wrongSelection:
return NSLocalizedString("Whoops, something went bad, please ensure you are selecting right part of text", comment: "Wrong selection")
case .default:
return NSLocalizedString("Whoops, something went wrong", comment: "Default error")
}
}
}
/// enum for identifiying command names (Available to change in info.plist of this extension)
/// No need for declaring rawValues as it carries the same name, cool feature Swift 👍
/// - makeVariable: 🙀
/// - makeJustSwitch: 🙀
public enum Commands: String {
case makeVariable
case makeJustSwitch
}
}
| mit | eba887dd6be8df965e28bbc033217c54 | 41.280702 | 383 | 0.705809 | 4.393801 | false | false | false | false |
lorentey/swift | test/IDE/infer_import_as_member.swift | 6 | 6436 | // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/custom-modules/CollisionImportAsMember.h -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=InferImportAsMember -always-argument-labels -enable-infer-import-as-member -skip-unavailable > %t.printed.A.txt
// RUN: %target-swift-frontend -typecheck -import-objc-header %S/Inputs/custom-modules/CollisionImportAsMember.h -I %t -I %S/Inputs/custom-modules %s -enable-infer-import-as-member -verify -enable-invalid-ephemeralness-as-error
// RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt
// REQUIRES: objc_interop
import InferImportAsMember
let mine = IAMStruct1()
let _ = mine.getCollisionNonProperty(1)
// TODO: more cases, eventually exhaustive, as we start inferring the result we
// want
// PRINT-LABEL: struct IAMStruct1 {
// PRINT-NEXT: var x: Double
// PRINT-NEXT: var y: Double
// PRINT-NEXT: var z: Double
// PRINT-NEXT: init()
// PRINT-NEXT: init(x x: Double, y y: Double, z z: Double)
// PRINT-NEXT: }
// PRINT-LABEL: extension IAMStruct1 {
// PRINT-NEXT: static var globalVar: Double
//
// PRINT-LABEL: /// Init
// PRINT-NEXT: init(copyIn in: IAMStruct1)
// PRINT-NEXT: init(simpleValue value: Double)
// PRINT-NEXT: init(redundant redundant: Double)
// PRINT-NEXT: init(specialLabel specialLabel: ())
//
// PRINT-LABEL: /// Methods
// PRINT-NEXT: func invert() -> IAMStruct1
// PRINT-NEXT: mutating func invertInPlace()
// PRINT-NEXT: func rotate(radians radians: Double) -> IAMStruct1
// PRINT-NEXT: func selfComesLast(x x: Double)
// PRINT-NEXT: func selfComesThird(a a: Double, b b: Float, x x: Double)
//
// PRINT-LABEL: /// Properties
// PRINT-NEXT: var radius: Double { get nonmutating set }
// PRINT-NEXT: var altitude: Double
// PRINT-NEXT: var magnitude: Double { get }
// PRINT-NEXT: var length: Double
//
// PRINT-LABEL: /// Various instance functions that can't quite be imported as properties.
// PRINT-NEXT: func getNonPropertyNumParams() -> Float
// PRINT-NEXT: func setNonPropertyNumParams(a a: Float, b b: Float)
// PRINT-NEXT: func getNonPropertyType() -> Float
// PRINT-NEXT: func setNonPropertyType(x x: Double)
// PRINT-NEXT: func getNonPropertyNoSelf() -> Float
// PRINT-NEXT: static func setNonPropertyNoSelf(x x: Double, y y: Double)
// PRINT-NEXT: func setNonPropertyNoGet(x x: Double)
// PRINT-NEXT: func setNonPropertyExternalCollision(x x: Double)
//
// PRINT-LABEL: /// Various static functions that can't quite be imported as properties.
// PRINT-NEXT: static func staticGetNonPropertyNumParams() -> Float
// PRINT-NEXT: static func staticSetNonPropertyNumParams(a a: Float, b b: Float)
// PRINT-NEXT: static func staticGetNonPropertyNumParamsGetter(d d: Double)
// PRINT-NEXT: static func staticGetNonPropertyType() -> Float
// PRINT-NEXT: static func staticSetNonPropertyType(x x: Double)
// PRINT-NEXT: static func staticGetNonPropertyNoSelf() -> Float
// PRINT-NEXT: static func staticSetNonPropertyNoSelf(x x: Double, y y: Double)
// PRINT-NEXT: static func staticSetNonPropertyNoGet(x x: Double)
//
// PRINT-LABEL: /// Static method
// PRINT-NEXT: static func staticMethod() -> Double
// PRINT-NEXT: static func tlaThreeLetterAcronym() -> Double
//
// PRINT-LABEL: /// Static computed properties
// PRINT-NEXT: static var staticProperty: Double
// PRINT-NEXT: static var staticOnlyProperty: Double { get }
//
// PRINT-LABEL: /// Omit needless words
// PRINT-NEXT: static func onwNeedlessTypeArgLabel(_ Double: Double) -> Double
//
// PRINT-LABEL: /// Fuzzy
// PRINT-NEXT: init(fuzzy fuzzy: ())
// PRINT-NEXT: init(fuzzyWithFuzzyName fuzzyWithFuzzyName: ())
// PRINT-NEXT: init(fuzzyName fuzzyName: ())
//
// PRINT-NEXT: func getCollisionNonProperty(_ _: Int32) -> Float
//
// PRINT-NEXT: }
//
// PRINT-NEXT: func __IAMStruct1IgnoreMe(_ s: IAMStruct1) -> Double
//
// PRINT-LABEL: /// Mutable
// PRINT-NEXT: struct IAMMutableStruct1 {
// PRINT-NEXT: init()
// PRINT-NEXT: }
// PRINT-NEXT: extension IAMMutableStruct1 {
// PRINT-NEXT: init(with withIAMStruct1: IAMStruct1)
// PRINT-NEXT: init(url url: UnsafePointer<Int8>!)
// PRINT-NEXT: func doSomething()
// PRINT-NEXT: }
//
// PRINT-LABEL: struct TDStruct {
// PRINT-NEXT: var x: Double
// PRINT-NEXT: init()
// PRINT-NEXT: init(x x: Double)
// PRINT-NEXT: }
// PRINT-NEXT: extension TDStruct {
// PRINT-NEXT: init(float Float: Float)
// PRINT-NEXT: }
//
// PRINT-LABEL: /// Class
// PRINT-NEXT: class IAMClass {
// PRINT-NEXT: }
// PRINT-NEXT: typealias IAMOtherName = IAMClass
// PRINT-NEXT: extension IAMClass {
// PRINT-NEXT: class var typeID: UInt32 { get }
// PRINT-NEXT: init!(i i: Double)
// PRINT-NEXT: class func invert(_ iamOtherName: IAMOtherName!)
// PRINT-NEXT: }
//
// PRINT-LABEL: struct IAMPointerStruct {
// PRINT-NEXT: var ptr1: UnsafeMutablePointer<Double>!
// PRINT-NEXT: var ptr2: UnsafeMutablePointer<Double>!
// PRINT-NEXT: init()
// PRINT-NEXT: init(ptr1 ptr1: UnsafeMutablePointer<Double>!, ptr2 ptr2: UnsafeMutablePointer<Double>!)
// PRINT-NEXT: }
// PRINT-NEXT: extension IAMPointerStruct {
// PRINT-NEXT: init(otherPtr ptr: UnsafeMutablePointer<Double>!)
// PRINT-NEXT: }
func testNonEphemeralInitParams(x: Double) {
var x = x
_ = IAMPointerStruct(ptr1: &x, ptr2: &x)
// expected-error@-1 {{cannot use inout expression here; argument 'ptr1' must be a pointer that outlives the call to 'init(ptr1:ptr2:)'}}
// expected-note@-2 {{implicit argument conversion from 'Double' to 'UnsafeMutablePointer<Double>?' produces a pointer valid only for the duration of the call to 'init(ptr1:ptr2:)'}}
// expected-note@-3 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
// expected-error@-4 {{cannot use inout expression here; argument 'ptr2' must be a pointer that outlives the call to 'init(ptr1:ptr2:)'}}
// expected-note@-5 {{implicit argument conversion from 'Double' to 'UnsafeMutablePointer<Double>?' produces a pointer valid only for the duration of the call to 'init(ptr1:ptr2:)'}}
// expected-note@-6 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = IAMPointerStruct(otherPtr: &x) // Okay.
}
| apache-2.0 | f0ddfa5d9b4751b3ecf2c63df952c8b3 | 45.978102 | 329 | 0.699347 | 3.477039 | false | false | false | false |
AliSoftware/SwiftGen | Tests/SwiftGenKitTests/PlistTests.swift | 1 | 2520 | //
// SwiftGenKit UnitTests
// Copyright © 2020 SwiftGen
// MIT Licence
//
import PathKit
@testable import SwiftGenKit
import TestUtils
import XCTest
final class PlistTests: XCTestCase {
func testEmpty() throws {
let parser = try Plist.Parser()
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "empty", sub: .plist)
}
func testArray() throws {
let parser = try Plist.Parser()
try parser.searchAndParse(path: Fixtures.resource(for: "shopping-list.plist", sub: .plistGood))
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "shopping-list", sub: .plist)
}
func testDictionary() throws {
let parser = try Plist.Parser()
try parser.searchAndParse(path: Fixtures.resource(for: "configuration.plist", sub: .plistGood))
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "configuration", sub: .plist)
}
func testInfo() throws {
let parser = try Plist.Parser()
try parser.searchAndParse(path: Fixtures.resource(for: "Info.plist", sub: .plistGood))
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "info", sub: .plist)
}
func testDirectoryInput() {
do {
let parser = try Plist.Parser()
try parser.searchAndParse(path: Fixtures.resourceDirectory(sub: .plistGood))
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "all", sub: .plist)
} catch let error {
XCTFail("Unexpected error occured while parsing: \(error)")
}
}
func testFileWithBadSyntax() {
do {
_ = try Plist.Parser().searchAndParse(path: Fixtures.resource(for: "syntax.plist", sub: .plistBad))
XCTFail("Code did parse file successfully while it was expected to fail for bad syntax")
} catch Plist.ParserError.invalidFile {
// That's the expected exception we want to happen
} catch let error {
XCTFail("Unexpected error occured while parsing: \(error)")
}
}
// MARK: - Custom options
func testUnknownOption() throws {
do {
_ = try AssetsCatalog.Parser(options: ["SomeOptionThatDoesntExist": "foo"])
XCTFail("Parser successfully created with an invalid option")
} catch ParserOptionList.Error.unknownOption(let key, _) {
// That's the expected exception we want to happen
XCTAssertEqual(key, "SomeOptionThatDoesntExist", "Failed for unexpected option \(key)")
} catch let error {
XCTFail("Unexpected error occured: \(error)")
}
}
}
| mit | eb84b00a0f07e9a42c02fe643b5b878f | 30.4875 | 105 | 0.686383 | 4.27674 | false | true | false | false |
everlof/RestKit-n-Django-Sample | Project_iOS/Cite/AppDelegate.swift | 1 | 6274 | //
// AppDelegate.swift
// Cite
//
// Created by David Everlöf on 05/08/16.
//
//
import UIKit
func appDelegate() -> AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}
private var SERVER_PROTOCOL: String = "http"
private var SERVER_IP: String = "127.0.0.1"
private var SERVER_PORT: String = "8000"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var loginManager: LoginManager! = nil
var setupControllersOnceToken: dispatch_once_t = 0
let mainTabBar = TabBarController()
var managedObjectStore: RKManagedObjectStore!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UINavigationBar.appearance().tintColor = UIColor.citeColor4()
UINavigationBar.appearance().barTintColor = UIColor.citeColor5()
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "ic_leftarrow")
UITabBar.appearance().tintColor = UIColor.citeColor4()
UITabBar.appearance().barTintColor = UIColor.citeColor5()
UIBarButtonItem.appearance()
.setTitleTextAttributes([NSFontAttributeName : UIFont.citeFontOfSize(18)],
forState: UIControlState.Normal)
setupRestkit()
// We need to initialize restkit before we create `LoginManager`
// Since we use the HTTPClient of RestKit
loginManager = LoginManager()
setupMainTabController()
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func setupMainTabController() {
dispatch_once(&setupControllersOnceToken) {
var vcs = [UIViewController]()
let quoteVC = QuoteViewController()
let quoteNavVC = NavigationController()
quoteNavVC.setViewControllers([ quoteVC ], animated: false)
quoteNavVC.tabBarItem.title = "Quotes"
quoteNavVC.tabBarItem.image = UIImage(named: "ic_quotes")
vcs.append(quoteNavVC)
let profileVC = ProfileViewController()
let profileNavVC = NavigationController()
profileNavVC.setViewControllers([ profileVC ], animated: false)
profileNavVC.tabBarItem.title = "Profile"
profileNavVC.tabBarItem.image = UIImage(named: "ic_user")
vcs.append(profileNavVC)
self.mainTabBar.setViewControllers(vcs, animated: false)
if self.window == nil {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
}
if self.loginManager.loggedInUser == nil {
self.window?.rootViewController = LoginViewController()
} else {
self.window?.rootViewController = self.mainTabBar
}
}
}
func setupRestkit() {
let baseURL = NSURL(string: "\(SERVER_PROTOCOL)://\(SERVER_IP):\(SERVER_PORT)")
let objectManager = RKObjectManager(baseURL: baseURL)
AFNetworkActivityIndicatorManager.sharedManager().enabled = true
let modelURL = NSBundle.mainBundle().URLForResource("Cite", withExtension: "momd")!
let managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)!
let managedObjectStore = RKManagedObjectStore(managedObjectModel: managedObjectModel)
objectManager.managedObjectStore = managedObjectStore
self.managedObjectStore = managedObjectStore
//RKlcl_configure_by_name("RestKit/CoreData", RKlcl_vDebug.rawValue)
//RKlcl_configure_by_name("RestKit/Network", RKlcl_vDebug.rawValue);
//RKlcl_configure_by_name("RestKit/ObjectMapping", RKlcl_vDebug.rawValue);
RKlcl_configure_by_name("RestKit/CoreData", RKlcl_vError.rawValue)
RKlcl_configure_by_name("RestKit/Network", RKlcl_vError.rawValue);
RKlcl_configure_by_name("RestKit/ObjectMapping", RKlcl_vError.rawValue);
RKObjectManager.sharedManager().requestSerializationMIMEType = RKMIMETypeJSON
User.rkSetupRouter()
Quote.rkSetupRouter()
HashTag.rkSetupRouter()
// We print it, to force the lazy load of the static properties
print(User.mapping)
print(HashTag.mapping)
print(Quote.mapping)
managedObjectStore.createPersistentStoreCoordinator()
let storePath = RKApplicationDataDirectory().stringByAppendingString("/Cite.sqlite")
let _ = try! managedObjectStore.addSQLitePersistentStoreAtPath(storePath, fromSeedDatabaseAtPath: nil, withConfiguration: nil, options: nil)
managedObjectStore.createManagedObjectContexts()
managedObjectStore.managedObjectCache = RKInMemoryManagedObjectCache(managedObjectContext: managedObjectStore.persistentStoreManagedObjectContext)
}
}
| mit | aa3e6ee233f3721bb80179a6df6b62e3 | 39.211538 | 281 | 0.731388 | 4.974623 | false | false | false | false |
Miridescen/M_365key | 365KEY_swift/365KEY_swift/MainController/Class/Produce/controller/SKProductVC.swift | 1 | 10692 | //
// SKProductVC.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/11/2.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
private let produceCellID = "produceCellID"
class SKProductVC: UIViewController {
var refControl: UIRefreshControl?
var searchView: SKProduceSearchView?
var navBar: UINavigationBar?
var navItem: UINavigationItem?
var tableView: UITableView?
var activityView: UIActivityIndicatorView?
// 用于判断是否是上啦加载
var isPullUp = false
var productViewModel = SKProductViewModel()
lazy var noInfoLabel = UILabel(frame: CGRect(x: 0, y: 50, width: SKScreenWidth, height: 50))
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: SKNoUserLoginNotifiction), object: nil, queue: OperationQueue.main) { notifiction in
self.present(SKNavigationController(rootViewController: SKLoginController()), animated: true, completion: nil)
}
NotificationCenter.default.addObserver(self, selector: #selector(userLoginSuccess), name: NSNotification.Name(rawValue: SKUserLoginSuccessNotifiction), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userLoginSuccess), name: NSNotification.Name(rawValue: SKUserLogoutNotifiction), object: nil)
addSubView()
loadData()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func userLoginSuccess() {
loadData()
}
func loadData() {
print("产品加载数据")
productViewModel.loadProductData(isPullUp: isPullUp){ isSuccess in
if isSuccess{
self.tableView?.reloadData()
self.noInfoLabel.removeFromSuperview()
self.tableView?.tableFooterView?.isHidden = false
} else {
if self.productViewModel.prodectDataArray.count == 0{
self.addNoInfoView(with: "暂无内容")
}
}
if #available(iOS 10.0, *) {
self.tableView?.refreshControl?.endRefreshing()
} else {
self.refControl?.endRefreshing()
}
self.activityView?.stopAnimating()
}
isPullUp = false
}
}
extension SKProductVC: UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
var parames = [String: AnyObject]()
parames["name"] = textField.text as AnyObject
parames["id"] = SKUserShared.getUserShared()?.uid as AnyObject
NSURLConnection.connection.searchProdecdRequest(params: parames) { (bool, anyData) in
if bool {
let searchProductVC = SKSearchVC()
searchProductVC.data = anyData!
self.navigationController?.pushViewController(searchProductVC, animated: true)
} else {
SKProgressHUD.setErrorString(with: "没有您要的产品")
}
}
return true
}
}
extension SKProductVC{
@objc private func searchButtonDidclick(){
// MARK: 添加searchBar
searchView = SKProduceSearchView(withAnimation: true)
searchView?.searchTF?.delegate = self
navBar?.addSubview(searchView!)
}
@objc private func addButtonDidClick(){
let userShared = SKUserShared.getUserSharedNeedPresentLoginView()
if userShared == nil {
return
}
if userShared?.userInfo?.tel == nil || (userShared?.userInfo?.tel?.isEmpty)! || userShared?.userInfo?.tel == "" {
let nav = SKNavigationController(rootViewController: SKPerfectInfoVC())
present(nav, animated: true, completion: nil)
} else {
navigationController?.pushViewController(SKAddProductVC(), animated: true)
}
}
// MARK: 添加subView
func addSubView() {
navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 64))
navBar?.isTranslucent = false
navBar?.barTintColor = UIColor().mainColor
navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
view.addSubview(navBar!)
navItem = UINavigationItem()
navItem?.title = "365KEY"
navItem?.leftBarButtonItem = UIBarButtonItem(SK_barButtonItem: UIImage(named:"icon_search"), selectorImage: UIImage(named:"icon_search"), tragtic: self, action: #selector(searchButtonDidclick))
navItem?.rightBarButtonItem = UIBarButtonItem(SK_barButtonItem: UIImage(named:"icon_add"), selectorImage: UIImage(named:"icon_add"), tragtic: self, action: #selector(addButtonDidClick))
navBar?.items = [navItem!]
tableView = UITableView(frame: view.bounds)
tableView?.delegate = self
tableView?.dataSource = self
tableView?.separatorStyle = .none
tableView?.register(UINib(nibName: "SKProdectCell", bundle: nil), forCellReuseIdentifier: produceCellID)
tableView?.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
tableView?.scrollIndicatorInsets = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0)
tableView?.rowHeight = UITableViewAutomaticDimension
tableView?.estimatedRowHeight = 300
view.insertSubview(tableView!, at: 0)
refControl = UIRefreshControl()
refControl?.tintColor = UIColor.gray
refControl?.attributedTitle = NSAttributedString(string: "下拉刷新")
refControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
if #available(iOS 10.0, *) {
tableView?.refreshControl = refControl
} else {
tableView?.addSubview(refControl!)
}
let footView = UIButton()
footView.frame = CGRect(x: 0, y: 0, width: SKScreenWidth, height: 60)
footView.setTitle("点击加载更多", for: .normal)
footView.setTitleColor(UIColor.black, for: .normal)
footView.addTarget(self, action: #selector(touchFooterView), for: .touchUpInside)
tableView?.tableFooterView = footView
tableView?.tableFooterView?.isHidden = true
activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityView?.center = CGPoint(x: (view?.centerX)!, y: (view?.centerY)!)
activityView?.startAnimating()
activityView?.hidesWhenStopped = true
activityView?.color = UIColor.gray
view.addSubview(activityView!)
view.bringSubview(toFront: activityView!)
}
@objc func touchFooterView(){
isPullUp = true
loadData()
}
// MARK: 没有内容时显示
func addNoInfoView(with string: String) {
noInfoLabel.text = string
noInfoLabel.textAlignment = .center
noInfoLabel.textColor = UIColor(red: 225/255.0, green: 225/255.0, blue: 225/255.0, alpha: 1)
noInfoLabel.font = UIFont.systemFont(ofSize: 20)
tableView?.addSubview(self.noInfoLabel)
}
}
extension SKProductVC: UITableViewDelegate, UITableViewDataSource{
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return productViewModel.prodectDataArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let dic = productViewModel.prodectDataArray[section] as [String : [SKProductListModel]]
let keyValue = dic[dic.startIndex]
let value = keyValue.1
return value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: produceCellID, for: indexPath) as! SKProdectCell
let dic = productViewModel.prodectDataArray[indexPath.section]
let keyValue = dic[dic.startIndex]
let value = keyValue.1
cell.productListModel = value[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.frame = CGRect(x: 0, y: -10, width: SKScreenWidth, height: 40)
view.backgroundColor = UIColor.white
let todayDate = Date().description
let strIndex = todayDate.index(todayDate.startIndex, offsetBy: 10)
let todayDateStr = todayDate.substring(to: strIndex)
let dic = productViewModel.prodectDataArray[section] as [String : [SKProductListModel]]
let keyValue = dic[dic.startIndex]
let value = keyValue.0
let titleText = value == todayDateStr ? "Today":value
let titleLabel = UILabel()
titleLabel.frame = CGRect(x: 16, y: 20, width: SKScreenWidth-10, height: 20)
titleLabel.textAlignment = .left
titleLabel.textColor = UIColor(red: 254/255.0, green: 216/255.0, blue: 203/255.0, alpha: 1.0)
titleLabel.font = UIFont.systemFont(ofSize: 19)
titleLabel.text = titleText
view.addSubview(titleLabel)
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.section == productViewModel.prodectDataArray.count-1 && !isPullUp && indexPath.row == 0{
isPullUp = true
loadData()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 135
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let dic = productViewModel.prodectDataArray[indexPath.section]
let keyValue = dic[dic.startIndex]
let value = keyValue.1
let productListModel = value[indexPath.row]
let detailVC = SKProductDetailController()
detailVC.productListModel = productListModel
navigationController?.pushViewController(detailVC, animated: true)
}
}
| apache-2.0 | 9ae7d66e9e68f03709a17d81410c0c73 | 34.888136 | 201 | 0.627657 | 5.046235 | false | false | false | false |
craftsmanship-toledo/katangapp-ios | Katanga/ViewControllers/FavoriteBusStopsViewController.swift | 1 | 2972 | /**
* Copyright 2016-today Software Craftmanship Toledo
*
* 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.
*/
/*!
@author Víctor Galán
*/
import UIKit
import RxSwift
import RxCocoa
class FavoriteBusStopsViewController: UIViewController, DataListTableView, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.rowHeight = 80
tableView.layoutMargins = .zero
tableView.separatorColor = .black
tableView.separatorInset = .zero
tableView.tableFooterView = UIView()
tableView.dataSource = self
tableView.delegate = self
}
}
let viewModel = FavoriteBusStopsViewModel()
var busStops = [BusStop]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(FavoriteBusStopCell.self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
busStops = viewModel.getFavorites()
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return busStops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: FavoriteBusStopCell.reuseIdentifier, for: indexPath)
as! FavoriteBusStopCell
fillCell(row: indexPath.row, element: busStops[indexPath.row], cell: cell)
return cell
}
func fillCell(row: Int, element: BusStop, cell: FavoriteBusStopCell) {
cell.busStopId = element.id
cell.busStopAddress = element.address
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle,
forRowAt indexPath: IndexPath) {
let busStop = busStops[indexPath.row]
viewModel.removeFavorite(busStop: busStop)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .automatic)
busStops.remove(at: indexPath.row)
tableView.endUpdates()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let busStop = busStops[indexPath.row]
performSegue(withIdentifier: "times", sender: busStop)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let busStop = sender as? BusStop else { return }
let viewModel = NearBusStopIdViewModel(busStopId: busStop.id)
let vc = segue.destination as? NearBusStopsViewController
vc?.viewModel = viewModel
}
}
| apache-2.0 | 55f8677e4d1f68aba7daf6ac3e438dc8 | 27.018868 | 119 | 0.758923 | 4.10221 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.