repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
sbooth/SFBAudioEngine | Output/SFBOutputSource.swift | 1 | 3938 | //
// Copyright (c) 2020 - 2021 Stephen F. Booth <me@sbooth.org>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
import Foundation
extension OutputSource {
/// Reads bytes from the input
/// - parameter buffer: A buffer to receive data
/// - parameter length: The maximum number of bytes to read
/// - returns: The number of bytes actually read
/// - throws: An `NSError` object if an error occurs
public func read(_ buffer: UnsafeMutableRawPointer, length: Int) throws -> Int {
var bytesRead = 0
try __readBytes(buffer, length: length, bytesRead: &bytesRead)
return bytesRead
}
/// Writes bytes to the output
/// - parameter buffer: A buffer of data to write
/// - parameter length: The maximum number of bytes to write
/// - returns:The number of bytes actually written
/// - throws: An `NSError` object if an error occurs
public func write(_ buffer: UnsafeRawPointer, length: Int) throws -> Int {
var bytesWritten = 0
try __writeBytes(buffer, length: length, bytesWritten: &bytesWritten)
return bytesWritten
}
/// Returns the current offset in the output, in bytes
/// - throws: An `NSError` object if an error occurs
public func offset() throws -> Int {
var offset = 0
try __getOffset(&offset)
return offset
}
/// Returns the length of the output, in bytes
/// - throws: An `NSError` object if an error occurs
public func length() throws -> Int {
var length = 0
try __getLength(&length)
return length
}
/// Writes bytes to the output
/// - parameter data: The data to write
/// - throws: An `NSError` object if an error occurs
public func write(_ data: Data) throws {
let bytesWritten = try data.withUnsafeBytes { (bufptr) -> Int in
guard let baseAddress = bufptr.baseAddress else {
return 0
}
return try write(baseAddress, length: data.count)
}
if bytesWritten != data.count {
throw NSError(domain: NSPOSIXErrorDomain, code: Int(EIO), userInfo: nil)
}
}
/// Writes a binary integer to the output
/// - parameter i: The value to write
/// - throws: An `NSError` object if an error occurs
public func write<T: BinaryInteger>(_ i: T) throws {
let size = MemoryLayout<T>.size
var tmp = i
let bytesWritten = try write(&tmp, length: size)
if bytesWritten != size {
throw NSError(domain: NSPOSIXErrorDomain, code: Int(EIO), userInfo: nil)
}
}
/// Writes a 16-bit integer to the output in big-endian format
/// - parameter ui16: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeBigEndian(_ ui16: UInt16) throws {
try write(CFSwapInt16HostToBig(ui16))
}
/// Writes a 32-bit integer to the output in big-endian format
/// - parameter ui32: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeBigEndian(_ ui32: UInt32) throws {
try write(CFSwapInt32HostToBig(ui32))
}
/// Writes a 64-bit integer to the output in little-endian format
/// - parameter ui64: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeBigEndian(_ ui64: UInt64) throws {
try write(CFSwapInt64HostToBig(ui64))
}
/// Writes a 16-bit integer to the output in big-endian format
/// - parameter ui16: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeLittleEndian(_ ui16: UInt16) throws {
try write(CFSwapInt16HostToLittle(ui16))
}
/// Writes a 32-bit integer to the output in little-endian format
/// - parameter ui32: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeLittleEndian(_ ui32: UInt32) throws {
try write(CFSwapInt32HostToLittle(ui32))
}
/// Writes a 64-bit integer to the output in little-endian format
/// - parameter ui64: The value to write
/// - throws: An `NSError` object if an error occurs
public func writeLittleEndian(_ ui64: UInt64) throws {
try write(CFSwapInt64HostToLittle(ui64))
}
}
| mit |
jpavley/Copy-Edit | Copy Edit/ViewController.swift | 1 | 630 | //
// ViewController.swift
// Copy Edit
//
// Created by John Pavley on 11/26/16.
// Copyright © 2016 John Pavley. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet var logger: NSTextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
logger.isEditable = false
logger.textStorage?.mutableString.setString(logPasteboard())
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit |
LYM-mg/MGDS_Swift | MGDS_Swift/MGDS_Swift/Class/Music/Controller/SearchMusicViewController.swift | 1 | 17891 | //
// SearchViewController.swift
// ProductionReport
//
// Created by i-Techsys.com on 17/2/13.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
private let KSearchResultCellID = "KSearchResultCellID"
private let KSearchHistoryCellID = "KSearchHistoryCellID"
private let KHeaderReusableViewID = "KHeaderReusableViewID"
private let KHotSearchCellID = "KHotSearchCellID"
private let KHistoryHeaderViewID = "KHistoryHeaderViewID"
private let KSearchResultHeaderViewID = "KSearchResultHeaderViewID"
class SearchMusicViewController: UIViewController {
fileprivate var hotSearchView: HotSearchView?
// MARK: - 懒加载属性
fileprivate lazy var tableView: UITableView = { [unowned self] in
// let tb = UITableView(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: self.view.mg_height))
let tb = UITableView()
tb.backgroundColor = UIColor.white
tb.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tb.dataSource = self
tb.delegate = self
tb.isHidden = true
tb.rowHeight = 60
tb.tableFooterView = UIView()
// tb.estimatedRowHeight = 60 // 设置估算高度
// tb.rowHeight = UITableView.automaticDimension // 告诉tableView我们cell的高度是自动的
tb.keyboardDismissMode = UIScrollView.KeyboardDismissMode.onDrag
tb.register(UINib(nibName: "SearchResultHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: KSearchResultHeaderViewID)
return tb
}()
@objc fileprivate lazy var collectionView: UICollectionView = { [unowned self] in
let fl = UICollectionViewFlowLayout()
fl.minimumLineSpacing = 4
fl.minimumInteritemSpacing = 0
fl.headerReferenceSize = CGSize(width: MGScreenW, height: 35)
fl.itemSize = CGSize(width: MGScreenW, height: 44)
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: fl)
cv.frame = CGRect(x: 0, y: 0, width: MGScreenW, height: self.view.mg_height)
cv.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
cv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cv.dataSource = self
cv.delegate = self
cv.alwaysBounceVertical = true
cv.keyboardDismissMode = UIScrollView.KeyboardDismissMode.interactive
cv.register(SearchHistoryCell.classForCoder(), forCellWithReuseIdentifier: KSearchHistoryCellID)
cv.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: KHotSearchCellID)
cv.register(UINib(nibName: "HistoryHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: KHistoryHeaderViewID)
return cv
}()
fileprivate lazy var SearchMusicVM = SearchMusicViewModel()
let searchBar = UISearchBar()
fileprivate lazy var historyData = [[String: Any]]()
fileprivate lazy var hotSearchArr: [String] = {[unowned self] in
let hotArr = [String]()
return hotArr
}()
fileprivate lazy var songSearchArr = [SearchModel]()
// MARK: - 系统方法
override func viewDidLoad() {
super.viewDidLoad()
setUpMainView()
loadHotSearchData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadHistorySearchData()
}
deinit {
debugPrint("SearchViewController--deinit")
}
}
// MARK: - setUpUI
extension SearchMusicViewController {
fileprivate func setUpMainView() {
view.backgroundColor = UIColor.white
buildSearchBar()
view.addSubview(collectionView)
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(MGNavHeight)
make.bottom.left.right.equalToSuperview()
}
}
fileprivate func buildSearchBar() {
searchBar.frame = CGRect(x: -10, y: 0, width: MGScreenW * 0.9, height: 30)
searchBar.placeholder = "请输入关键字查询歌曲"
searchBar.barTintColor = UIColor.white
searchBar.keyboardType = UIKeyboardType.default
searchBar.delegate = self
navigationItem.titleView = searchBar
for view in searchBar.subviews {
for subView in view.subviews {
if NSStringFromClass(subView.classForCoder) == "UINavigationButton" {
let btn = subView as? UIButton
btn?.setTitle("取消" , for: .normal)
}
if NSStringFromClass(subView.classForCoder) == "UISearchBarTextField" {
let textField = subView as? UITextField
textField?.tintColor = UIColor.gray
}
}
}
}
}
// MARK: - 加载数据
extension SearchMusicViewController {
// 加载历史数据
fileprivate func loadHistorySearchData() {
DispatchQueue.global().async {
if self.historyData.count > 0 {
self.historyData.removeAll()
}
guard var historySearch = SaveTools.mg_getLocalData(key: MGSearchMusicHistorySearchArray) as? [[String : Any]] else { return }
if historySearch.count > 15 {
historySearch.removeLast()
}
self.historyData = historySearch
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
// loadHotSearchData
fileprivate func loadHotSearchData() {
hotSearchArr.removeAll()
let parameters = ["from":"ios","version":"5.5.6","channel":"appstore","operator":"1","format":"json","method":"baidu.ting.search.hot","page_num":"15"]
NetWorkTools.requestData(type: .get, urlString: "http://tingapi.ting.baidu.com/v1/restserver/ting",parameters: parameters, succeed: { (response, err) in
guard let result = response as? [String: Any] else { return }
let dictArr = result["result"] as! [[String: Any]]
for dict in dictArr {
self.hotSearchArr.append(dict["word"] as! String)
}
self.collectionView.reloadData()
}) { (err) in
}
}
}
// MARK: - TableView数据源 和 代理
extension SearchMusicViewController: UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
if songSearchArr.count == 0 { return 0 }
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if songSearchArr.count == 0 { return 0 }
if section == 0 {
return songSearchArr.first!.songArray.count
}else if section == 1 {
return songSearchArr.first!.albumArray.count
}else if section == 2 {
return songSearchArr.first!.artistArray.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: KSearchResultCellID)
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: KSearchResultCellID)
}
if indexPath.section == 0 {
let model = songSearchArr.first!.songArray[indexPath.row]
cell!.imageView?.image = #imageLiteral(resourceName: "default-user")
cell!.textLabel?.text = model.songname
cell!.detailTextLabel?.text = model.artistname
}else if indexPath.section == 1 {
let model = songSearchArr.first!.albumArray[indexPath.row]
cell!.textLabel?.text = model.albumname
cell!.detailTextLabel?.text = model.artistname
cell!.imageView?.setImageWithURLString(model.artistpic, placeholder: #imageLiteral(resourceName: "default-user"))
}else if indexPath.section == 2 {
let model = songSearchArr.first!.artistArray[indexPath.row]
cell!.textLabel?.text = model.artistname
cell!.imageView?.setImageWithURLString(model.artistpic, placeholder: #imageLiteral(resourceName: "default-user"))
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var text = ""
if indexPath.section == 0 {
let model = songSearchArr.first!.songArray[indexPath.row]
text = model.songname
}else if indexPath.section == 1 {
let model = songSearchArr.first!.albumArray[indexPath.row]
text = model.albumname
}else if indexPath.section == 2 {
let model = songSearchArr.first!.artistArray[indexPath.row]
text = model.artistname
}
pushTosearchResultView(withText: text)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let head = tableView.dequeueReusableHeaderFooterView(withIdentifier: KSearchResultHeaderViewID) as! SearchResultHeaderView
if (section == 0) {
head.titleLabel.text = "歌曲"
} else if(section == 1){
head.titleLabel.text = "专辑"
} else{
head.titleLabel.text = "歌手"
}
return head;
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35
}
}
// MARK: - collectionView数据源 和 代理
extension SearchMusicViewController: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 1
}
return historyData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KHotSearchCellID, for: indexPath)
if hotSearchArr.count > 0 {
if hotSearchView == nil {
let hotSearchView = HotSearchView(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: 200), searchTitleText: "热门搜索", searchButtonTitleTexts: hotSearchArr, searchButton: {[unowned self] (btn) in
self.searchBar.text = btn?.currentTitle
self.loadProductsWithKeyword(self.searchBar.text!)
self.tableView.isHidden = false
self.searchBar.resignFirstResponder()
})
cell.addSubview(hotSearchView!)
self.hotSearchView = hotSearchView!
print(hotSearchView!.searchHeight)
// cell.frame = hotSearchView!.frame
// cell.layoutIfNeeded()
// IndexSet(index: 0)
let indexSet = IndexSet(integer: 0)
collectionView.reloadSections(indexSet)
}
}
return cell
}else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KSearchHistoryCellID, for: indexPath) as! SearchHistoryCell
let dict = historyData[indexPath.item]
cell.historyLabel.text = dict["searchFilter"] as! String?
return cell
}
}
// 清除历史搜索记录
@objc fileprivate func clearHistorySearch() {
SaveTools.mg_removeLocalData(key: MGSearchMusicHistorySearchArray)
loadHistorySearchData()
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var dict = historyData[indexPath.item]
searchBar.text = dict["searchFilter"] as? String
self.loadProductsWithKeyword(self.searchBar.text!)
dict = self.historyData.remove(at: indexPath.item)
historyData.insert(dict, at: 0)
SaveTools.mg_SaveToLocal(value: historyData, key: MGSearchMusicHistorySearchArray)
loadHistorySearchData()
tableView.isHidden = false
searchBar.resignFirstResponder()
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//如果是headerView
if kind == UICollectionView.elementKindSectionHeader {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: KHistoryHeaderViewID, for: indexPath) as! HistoryHeaderView
headerView.titleLabel.text = (indexPath.section == 0) ? "热门搜索" : "历史搜索"
headerView.iconImageView.image = (indexPath.section == 0) ? #imageLiteral(resourceName: "home_header_hot"): #imageLiteral(resourceName: "search_history")
headerView.moreBtn.isHidden = (indexPath.section == 0)
headerView.moreBtnClcikOperation = {
self.clearHistorySearch()
}
return headerView
}
return HistoryHeaderView()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 0 {
return CGSize(width: MGScreenW, height: (self.hotSearchView == nil) ? 200 : (self.hotSearchView?.searchHeight)!)
}
return CGSize(width: MGScreenW, height: 44)
}
//设定页脚的尺寸为0
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: MGScreenW, height: 0)
}
}
// MARK: - UISearchBarDelegate
extension SearchMusicViewController: UISearchBarDelegate,UIScrollViewDelegate {
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.text = ""
tableView.isHidden = true
searchBar.showsCancelButton = false
songSearchArr.removeAll()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
tableView.isHidden = false
// 写入到本地
writeHistorySearchToUserDefault(searchFilter: searchBar.text!)
//去除搜索字符串左右和中间的空格
searchBar.text = searchBar.text!.trimmingCharacters(in: CharacterSet.whitespaces)
// 加载数据
loadProductsWithKeyword(searchBar.text!)
tableView.reloadData()
searchBar.resignFirstResponder()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.count == 0 {
// 将tableView隐藏
tableView.isHidden = true
collectionView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
searchBar.resignFirstResponder()
}
}
// MARK: - 搜索网络加载数据
extension SearchMusicViewController {
// MARK: - 本地数据缓存
fileprivate func writeHistorySearchToUserDefault(searchFilter: String) {
var historySearchs = SaveTools.mg_getLocalData(key: MGSearchMusicHistorySearchArray) as? [[String: Any]]
if historySearchs != nil {
for dict in historySearchs! {
if dict["searchFilter"] as? String == searchFilter { print("已经缓存") ; return }
}
}else {
historySearchs = [[String: Any]]()
}
var dict = [String: Any]()
dict["searchFilter"] = searchFilter
historySearchs?.insert(dict, at: 0)
SaveTools.mg_SaveToLocal(value: historySearchs!, key: MGSearchMusicHistorySearchArray)
loadHistorySearchData()
}
// MARK: - 搜索网络加载数据
fileprivate func loadProductsWithKeyword(_ keyword: String) {
songSearchArr.removeAll()
// 1.显示指示器
self.showHudInViewWithMode(view: self.view, hint: "正在查询数据", mode: .indeterminate, imageName: nil)
let parameters = ["from":"ios","version":"5.5.6","channel":"appstore","operator":"1","format":"json","method":"baidu.ting.search.catalogSug","query":keyword]
NetWorkTools.requestData(type: .get, urlString: "http://tingapi.ting.baidu.com/v1/restserver/ting",parameters: parameters, succeed: {[weak self] (response, err) in
self?.hideHud()
guard let result = response as? [String: Any] else { return }
let model = SearchModel(dict: result)
if model.songArray.isEmpty && model.albumArray.isEmpty && model.artistArray.isEmpty {
self?.showHint(hint: "没有查询到结果")
self?.tableView.reloadData()
return
}
self?.songSearchArr.append(model)
self?.tableView.reloadData()
}) { (err) in
self.hideHud()
self.showHint(hint: "请求数据失败", imageName: "sad_face_icon")
}
}
}
// 跳转到下一个控制器搜索🔍
extension SearchMusicViewController {
func pushTosearchResultView(withText text: String) {
let result = MGSearchMusicResultVC()
result.searchText = text
navigationController?.pushViewController(result, animated: false)
}
}
| mit |
wibosco/ASOS-Consumer | ASOSConsumer/Networking/Product/Parsers/Product/ProductParser.swift | 1 | 1083 | //
// ProductParser.swift
// ASOSConsumer
//
// Created by William Boles on 07/03/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
class ProductParser: NSObject {
//MARK: - Product
func parseProduct(productResponse: Dictionary<String, AnyObject>) -> Product {
let product = Product()
product.productID = productResponse["ProductId"] as? Int
product.displayPrice = productResponse["CurrentPrice"] as? String
product.price = productResponse["BasePrice"] as? NSDecimal
product.brand = productResponse["Brand"] as? String
product.displayDescription = productResponse["Description"] as? String
product.title = productResponse["Title"] as? String
let mediaResponse = productResponse["ProductImageUrls"] as! Array<String>
for mediaRemoteURL: String in mediaResponse {
let media = Media()
media.remoteURL = mediaRemoteURL
product.medias.append(media)
}
return product
}
}
| mit |
kaunteya/Linex | Line/SourceEditorExtension.swift | 1 | 713 | //
// SourceEditorExtension.swift
// Line
//
// Created by Kaunteya Suryawanshi on 29/08/17.
// Copyright © 2017 Kaunteya Suryawanshi. All rights reserved.
//
import Foundation
import XcodeKit
class SourceEditorExtension: NSObject, XCSourceEditorExtension {
/*
func extensionDidFinishLaunching() {
// If your extension needs to do any work at launch, implement this optional method.
}
*/
/*
var commandDefinitions: [[XCSourceEditorCommandDefinitionKey: Any]] {
// If your extension needs to return a collection of command definitions that differs from those in its Info.plist, implement this optional property getter.
return []
}
*/
}
| mit |
MadAppGang/SmartLog | iOS/Pods/CoreStore/Sources/CSCoreStore+Querying.swift | 2 | 9600 | //
// CSCoreStore+Querying.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - CSCoreStore
public extension CSCoreStore {
/**
Using the `defaultStack`, fetches the `NSManagedObject` instance in the transaction's context from a reference created from a transaction or from a different managed object context.
- parameter object: a reference to the object created/fetched outside the transaction
- returns: the `NSManagedObject` instance if the object exists in the transaction, or `nil` if not found.
*/
@objc
public static func fetchExistingObject(_ object: NSManagedObject) -> Any? {
return self.defaultStack.fetchExistingObject(object)
}
/**
Using the `defaultStack`, fetches the `NSManagedObject` instance in the transaction's context from an `NSManagedObjectID`.
- parameter objectID: the `NSManagedObjectID` for the object
- returns: the `NSManagedObject` instance if the object exists in the transaction, or `nil` if not found.
*/
@objc
public static func fetchExistingObjectWithID(_ objectID: NSManagedObjectID) -> Any? {
return self.defaultStack.fetchExistingObjectWithID(objectID)
}
/**
Using the `defaultStack`, fetches the `NSManagedObject` instances in the transaction's context from references created from a transaction or from a different managed object context.
- parameter objects: an array of `NSManagedObject`s created/fetched outside the transaction
- returns: the `NSManagedObject` array for objects that exists in the transaction
*/
@objc
public static func fetchExistingObjects(_ objects: [NSManagedObject]) -> [Any] {
return self.defaultStack.fetchExistingObjects(objects)
}
/**
Using the `defaultStack`, fetches the `NSManagedObject` instances in the transaction's context from a list of `NSManagedObjectID`.
- parameter objectIDs: the `NSManagedObjectID` array for the objects
- returns: the `NSManagedObject` array for objects that exists in the transaction
*/
@objc
public static func fetchExistingObjectsWithIDs(_ objectIDs: [NSManagedObjectID]) -> [Any] {
return self.defaultStack.fetchExistingObjectsWithIDs(objectIDs)
}
/**
Using the `defaultStack`, fetches the first `NSManagedObject` instance that satisfies the specified `CSFetchClause`s. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `CSFetchClause` instances for the fetch request. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- returns: the first `NSManagedObject` instance that satisfies the specified `CSFetchClause`s
*/
@objc
public static func fetchOneFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> Any? {
return self.defaultStack.fetchOneFrom(from, fetchClauses: fetchClauses)
}
/**
Using the `defaultStack`, fetches all `NSManagedObject` instances that satisfy the specified `CSFetchClause`s. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- parameter from: a `CSFrom` clause indicating the entity type
- parameter fetchClauses: a series of `CSFetchClause` instances for the fetch request. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- returns: all `NSManagedObject` instances that satisfy the specified `CSFetchClause`s
*/
@objc
public static func fetchAllFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> [Any]? {
return self.defaultStack.fetchAllFrom(from, fetchClauses: fetchClauses)
}
/**
Using the `defaultStack`, fetches the number of `NSManagedObject`s that satisfy the specified `CSFetchClause`s. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- parameter from: a `CSFrom` clause indicating the entity type
- parameter fetchClauses: a series of `CSFetchClause` instances for the fetch request. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- returns: the number `NSManagedObject`s that satisfy the specified `CSFetchClause`s
*/
@objc
public static func fetchCountFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> NSNumber? {
return self.defaultStack.fetchCountFrom(from, fetchClauses: fetchClauses)
}
/**
Using the `defaultStack`, fetches the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `CSFetchClause`s. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- parameter from: a `CSFrom` clause indicating the entity type
- parameter fetchClauses: a series of `CSFetchClause` instances for the fetch request. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- returns: the `NSManagedObjectID` for the first `NSManagedObject` that satisfies the specified `CSFetchClause`s
*/
@objc
public static func fetchObjectIDFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> NSManagedObjectID? {
return self.defaultStack.fetchObjectIDFrom(from, fetchClauses: fetchClauses)
}
/**
Using the `defaultStack`, fetches the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `CSFetchClause`s. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- parameter from: a `CSFrom` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `CSWhere`, `CSOrderBy`, and `CSTweak` clauses.
- returns: the `NSManagedObjectID` for all `NSManagedObject`s that satisfy the specified `CSFetchClause`s
*/
@objc
public static func fetchObjectIDsFrom(_ from: CSFrom, fetchClauses: [CSFetchClause]) -> [NSManagedObjectID]? {
return self.defaultStack.fetchObjectIDsFrom(from, fetchClauses: fetchClauses)
}
/**
Using the `defaultStack`, queries aggregate values as specified by the `CSQueryClause`s. Requires at least a `CSSelect` clause, and optional `CSWhere`, `CSOrderBy`, `CSGroupBy`, and `CSTweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `CSFrom` clause indicating the entity type
- parameter selectClause: a `CSSelect` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `CSQueryClause` instances for the query request. Accepts `CSWhere`, `CSOrderBy`, `CSGroupBy`, and `CSTweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `CSSelect` parameter.
*/
@objc
public static func queryValueFrom(_ from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> Any? {
return self.defaultStack.queryValueFrom(from, selectClause: selectClause, queryClauses: queryClauses)
}
/**
Using the `defaultStack`, queries a dictionary of attribute values as specified by the `CSQueryClause`s. Requires at least a `CSSelect` clause, and optional `CSWhere`, `CSOrderBy`, `CSGroupBy`, and `CSTweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `CSFrom` clause indicating the entity type
- parameter selectClause: a `CSSelect` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `CSQueryClause` instances for the query request. Accepts `CSWhere`, `CSOrderBy`, `CSGroupBy`, and `CSTweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `CSSelect` parameter.
*/
@objc
public static func queryAttributesFrom(_ from: CSFrom, selectClause: CSSelect, queryClauses: [CSQueryClause]) -> [[String: Any]]? {
return self.defaultStack.queryAttributesFrom(from, selectClause: selectClause, queryClauses: queryClauses)
}
}
| mit |
LesCoureurs/Courir | Courir/Courir/GameEndTableCell.swift | 1 | 683 | //
// GameEndTableCell
// Courir
//
// Created by Hieu Giang on 31/3/16.
// Copyright © 2016 NUS CS3217. All rights reserved.
//
import UIKit
class GameEndTableCell: UITableViewCell {
@IBOutlet weak var indexNum: UILabel!
@IBOutlet weak var playerNameLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
backgroundColor = UIColor.clearColor()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
banxi1988/BXiOSUtils | Pod/Classes/QRCodeUtils.swift | 4 | 1075 | //
// QRCodeUtils.swift
// Youjia
//
// Created by Haizhen Lee on 15/11/23.
// Copyright © 2015年 xiyili. All rights reserved.
//
import UIKit
public struct QRCodeUtils {
public static func generateQRCodeImage(_ text:String,imageSize:CGSize=CGSize(width: 200, height: 200)) -> UIImage?{
if let ciImage = generateQRCode(text){
NSLog("QRCode imageSize \(imageSize)")
let scaleX = imageSize.width / ciImage.extent.width
let scaleY = imageSize.height / ciImage.extent.height
let transformedImage = ciImage.applying(CGAffineTransform(scaleX: scaleX, y: scaleY))
return UIImage(ciImage:transformedImage)
}else{
NSLog("generateQRCode Failed \(text)")
}
return nil
}
public static func generateQRCode(_ text:String) -> CIImage?{
let data = text.data(using: String.Encoding.isoLatin1, allowLossyConversion: true)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue("Q", forKey: "inputCorrectionLevel")
return filter?.outputImage
}
}
| mit |
NelsonLeDuc/JSACollection | JSACollection/Classes/Public/Swift/Mapper.swift | 1 | 2335 | //
// Mapper.swift
// JSACollection
//
// Created by Nelson LeDuc on 12/23/15.
// Copyright © 2015 Nelson LeDuc. All rights reserved.
//
import Foundation
public class ObjectMapper<T: NSObject>: ClassSerializer {
public typealias ObjectType = T
public var allowNonStandard = false {
didSet { _objectMapper.allowNonStandardTypes = allowNonStandard }
}
public var setterBlock: ((KeyValueAccessible, T) -> T?)? {
didSet {
let wrapper: JSACObjectMapperObjectSetterBlock?
if let setter = setterBlock {
wrapper = { (dict, object) in
guard let model = object as? T, let dict = dict else { return nil }
return setter(dict, model)
}
} else {
wrapper = nil
}
_objectMapper.setterBlock = wrapper
}
}
public var dateFormatter: NSDateFormatter? {
didSet { _objectMapper.dateFormatter = dateFormatter }
}
public var customKeyDictionary: [String : String]? {
didSet { _objectMapper.setCustomKeyDictionary(customKeyDictionary) }
}
public init(_ type: T.Type) {
}
public func addSetter(name: String, setterBlock: (AnyObject, T) -> Void) -> Self {
//Work around for compiler crash
let wrapper: JSACObjectMapperPropertySetterBlock = { (value, object) in
if let value = value, let object = object as? T {
setterBlock(value, object)
}
}
_objectMapper.addSetterForPropertyWithName(name, withBlock: wrapper)
return self
}
public func addSubMapper<S: NSObject>(name: String, mapper: ObjectMapper<S>) -> Self {
_objectMapper.addSubObjectMapper(mapper._objectMapper, forPropertyName: name)
return self
}
// MARK: ClassSerializer
public func listOfKeys() -> [String] {
return _objectMapper.listOfKeys() as? [String] ?? []
}
public func object(dictionary: KeyValueAccessible, serializer: JSACCollectionSerializer) -> ObjectType? {
let object = _objectMapper.objectForDictionary(dictionary, forCollectionSerializer: serializer) as? ObjectType
return object
}
internal let _objectMapper = JSACObjectMapper(forClass: T.self)
}
| mit |
Yalantis/PixPic | PixPic/Classes/Services/ErrorHandler.swift | 1 | 2292 | //
// ErrorHandler.swift
// PixPic
//
// Created by anna on 1/21/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import Foundation
class ErrorHandler {
static func handle(error: NSError) {
var message: String
let errorCode = error.code
if error.domain == FBSDKErrorDomain {
switch errorCode {
case FBSDKErrorCode.NetworkErrorCode.rawValue:
message = "The request failed due to a network error"
case FBSDKErrorCode.UnknownErrorCode.rawValue:
message = "The error code for unknown errors"
default:
message = error.localizedDescription
break
}
} else if error.domain == NSURLErrorDomain {
switch (error.domain, error.code) {
case (NSURLErrorDomain, NSURLErrorCancelled):
return
case (NSURLErrorDomain, NSURLErrorCannotFindHost),
(NSURLErrorDomain, NSURLErrorDNSLookupFailed),
(NSURLErrorDomain, NSURLErrorCannotConnectToHost),
(NSURLErrorDomain, NSURLErrorNetworkConnectionLost),
(NSURLErrorDomain, NSURLErrorNotConnectedToInternet):
message = "The Internet connection appears to be offline"
default:
message = error.localizedDescription
}
} else if error.domain == PFParseErrorDomain {
switch errorCode {
case PFErrorCode.ErrorConnectionFailed.rawValue:
message = "Connection is failed"
case PFErrorCode.ErrorFacebookIdMissing.rawValue:
message = "Facebook id is missed in request"
case PFErrorCode.ErrorObjectNotFound.rawValue:
message = "Object Not Found"
case PFErrorCode.ErrorFacebookInvalidSession.rawValue:
message = "Facebook session is invalid"
default:
message = error.localizedDescription
break
}
} else if error.domain == NSBundle.mainBundle().bundleIdentifier {
message = error.localizedDescription
}
message = error.localizedDescription
AlertManager.sharedInstance.showSimpleAlert(message)
}
}
| mit |
JornWu/ZhiBo_Swift | ZhiBo_Swift/Class/BaseVC/LiveRoom/LiveRoomViewController.swift | 1 | 9884 | //
// LiveRoomViewController.swift
// ZhiBo_Swift
//
// Created by JornWu on 2017/4/26.
// Copyright © 2017年 Jorn.Wu(jorn_wza@sina.com). All rights reserved.
//
import UIKit
import ReactiveCocoa
import ReactiveSwift
import Result
protocol LiveRoomViewControllerDelegate {
///
/// 这是LiveRoomViewController必须实现的三个方法
///
///
/// 给直播控制器传入数据
///
func setRoomDatas(withDataAr dataAr: [AnyObject])
///
/// 设置当前的直播间
///
func setCurrentRoomIndex(index: Int)
///
/// 打开要进入的直播间
///
func openCurrentRoom()
}
private let instance = LiveRoomViewController()
final class LiveRoomViewController:
UIViewController,
LiveRoomViewControllerDelegate,
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout,
UIScrollViewDelegate {
///---------------------------------------------------
/// Singleton
///
///
/// 单例的实现
/// static let shareLiveRoomViewController = LiveRoomViewController()
///
/// static var shareLiveRoomViewController: LiveRoomViewController {
/// struct Singleton {
/// static var instance = LiveRoomViewController()
/// }
/// return Singleton.instance
/// }
///
final class var shareLiveRoomViewController: LiveRoomViewController {
return instance
}
///
/// 私有化构造方法,避免外部调用
///
private init() {
super.init(nibName: nil, bundle: nil)
}
///
/// 私有化构造方法,避免外部调用
///
private override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
///
/// 私有化构造方法,避免外部调用
///
internal required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
///---------------------------------------------------
/// property
///
///
/// 直播间数据
///
private lazy var roomDataAr: [LiveRoomModel] = {
return [LiveRoomModel]()
}()
///
/// 直播间列表
///
private var roomCollectionView: UICollectionView!
///
/// 直播间(播放视图)
///
private lazy var liveRoomView: LiveRoomView = {
return LiveRoomView.shareLiveRoomView
}()
///
/// 当前房间(用于定位初始化进入的直播间)
///
public var currentRoomIndex: Int = 0
///
/// 当前直播间数据模型(信号)
///
public lazy var currentRoomModeSignalPipe: (output: Signal<LiveRoomModel, NoError>, input: Observer<LiveRoomModel, NoError>) = {
return Signal<LiveRoomModel, NoError>.pipe()
}()
///
/// ViewModel
///
private lazy var liveRoomViewControllerViewModel: LiveRoomViewControllerViewModel = {
return LiveRoomViewControllerViewModel()
}()
///---------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
}
///
/// 退出直播列表
///
override func viewWillDisappear(_ animated: Bool) {
liveRoomView.stop()
currentRoomIndex = 0
}
///
/// 进入点击的直播间
///
override func viewDidAppear(_ animated: Bool) {
openCurrentRoom()
}
///---------------------------------------------------
/// LiveRoomViewControllerDelegate
///
public func setRoomDatas(withDataAr dataAr: [AnyObject]) {
self.roomDataAr.removeAll()
for item in dataAr {
self.roomDataAr.append(LiveRoomModel.modelWith(item))
}
if roomCollectionView != nil {
roomCollectionView.reloadData()
}
else {
self.setupCollectionView()
}
}
public func setCurrentRoomIndex(index: Int) {
currentRoomIndex = index
}
internal func openCurrentRoom() {
if self.roomCollectionView != nil {
self.roomCollectionView.contentOffset = CGPoint(x: 0, y: Int(self.view.frame.height) * currentRoomIndex)
///
/// 这种方法返回的cell回空,不好使
///
/// let roomCell = roomCollectionView.cellForItem(at: IndexPath(row: currentRoomIndex,
/// section: 0))
/// if let cell = roomCell {
/// cell.contentView.addSubview(self.liveRoomView)
/// self.liveRoomView.snp.makeConstraints { (make) in
/// make.edges.height.equalToSuperview()
/// }
/// }
///
let cells = roomCollectionView.visibleCells
if cells.count > 0 {
cells[0].contentView.addSubview(self.liveRoomView)
self.liveRoomView.snp.makeConstraints { (make) in
make.edges.height.equalToSuperview()
}
print("------cells[0].contentView:", cells[0].contentView)
}
/// 这个方法要放在self.liveRoomView之后,因为self.liveRoomView会调用懒加载
/// 在LiveRoomView.shareLiveRoomView内部中会监听currentRoomModeSignalPipe的信号
/// 否则会漏掉第一次发送的数据
/// ## 如果roomDataAr[currentRoomIndex]是值类型,其实可以使用reactive的KOV来实现,或者监听方法来实现 ##
self.currentRoomModeSignalPipe.input.send(value: self.roomDataAr[currentRoomIndex])
}
}
///---------------------------------------------------------------
/// 构建热门主视图
///
private func setupCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.view.frame.size
layout.scrollDirection = .vertical
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
roomCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
roomCollectionView.dataSource = self
roomCollectionView.delegate = self
roomCollectionView.bounces = false
roomCollectionView.isPagingEnabled = true
roomCollectionView.backgroundColor = UIColor.orange
self.view.addSubview(roomCollectionView)
roomCollectionView.snp.makeConstraints { (make) in
make.edges.height.equalToSuperview()
}
roomCollectionView.register(LiveRoomCollectionViewCell.self, forCellWithReuseIdentifier: "LiveRoomCell")
NotificationCenter.default
.reactive
.notifications(forName: NSNotification.Name.UIDeviceOrientationDidChange)
.observeValues { (noti) in
self.roomCollectionView.reloadData()
}
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return roomDataAr.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let dataItem = roomDataAr[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LiveRoomCell",
for: indexPath) as! LiveRoomCollectionViewCell
cell.setupCell(withImageURLString: dataItem.bigpic ?? dataItem.photo ?? "",
flvLinkString: dataItem.flv ?? "")
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.view.frame.size
}
func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
let index = Int((collectionView.contentOffset.y + 5) / collectionView.frame.height)
if currentRoomIndex != index {
currentRoomIndex = index
///
/// 从前一个cell中移出
///
self.liveRoomView.removeFromSuperview()
///
/// 如果roomDataAr[currentRoomIndex]是值类型,可以直接调用setter,产生信号
///
self.currentRoomModeSignalPipe.input.send(value: self.roomDataAr[currentRoomIndex])
let cell = roomCollectionView.cellForItem(at: IndexPath(row: currentRoomIndex, section: 0))
cell?.contentView.addSubview(self.liveRoomView)
if cell != nil {
self.liveRoomView.snp.makeConstraints { (make) in
make.edges.height.equalToSuperview()
}
}
}
}
///---------------------------------------------------
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
qutheory/vapor | Tests/VaporTests/PipelineTests.swift | 2 | 5056 | @testable import Vapor
import XCTest
final class PipelineTests: XCTestCase {
func testEchoHandlers() throws {
let app = Application(.testing)
defer { app.shutdown() }
app.on(.POST, "echo", body: .stream) { request -> Response in
Response(body: .init(stream: { writer in
request.body.drain { body in
switch body {
case .buffer(let buffer):
return writer.write(.buffer(buffer))
case .error(let error):
return writer.write(.error(error))
case .end:
return writer.write(.end)
}
}
}))
}
let channel = EmbeddedChannel()
try channel.pipeline.addVaporHTTP1Handlers(
application: app,
responder: app.responder,
configuration: app.http.server.configuration
).wait()
try channel.writeInbound(ByteBuffer(string: "POST /echo HTTP/1.1\r\ntransfer-encoding: chunked\r\n\r\n1\r\na\r\n"))
let chunk = try channel.readOutbound(as: ByteBuffer.self)?.string
XCTAssertContains(chunk, "HTTP/1.1 200 OK")
XCTAssertContains(chunk, "connection: keep-alive")
XCTAssertContains(chunk, "transfer-encoding: chunked")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "1\r\n")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "a")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "\r\n")
try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)?.string)
try channel.writeInbound(ByteBuffer(string: "1\r\nb\r\n"))
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "1\r\n")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "b")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "\r\n")
try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)?.string)
try channel.writeInbound(ByteBuffer(string: "1\r\nc\r\n"))
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "1\r\n")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "c")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "\r\n")
try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)?.string)
try channel.writeInbound(ByteBuffer(string: "0\r\n\r\n"))
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "0\r\n\r\n")
try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)?.string)
}
func testEOFFraming() throws {
let app = Application(.testing)
defer { app.shutdown() }
app.on(.POST, "echo", body: .stream) { request -> Response in
Response(body: .init(stream: { writer in
request.body.drain { body in
switch body {
case .buffer(let buffer):
return writer.write(.buffer(buffer))
case .error(let error):
return writer.write(.error(error))
case .end:
return writer.write(.end)
}
}
}))
}
let channel = EmbeddedChannel()
try channel.pipeline.addVaporHTTP1Handlers(
application: app,
responder: app.responder,
configuration: app.http.server.configuration
).wait()
try channel.writeInbound(ByteBuffer(string: "POST /echo HTTP/1.1\r\n\r\n"))
try XCTAssertContains(channel.readOutbound(as: ByteBuffer.self)?.string, "HTTP/1.1 200 OK")
}
func testBadStreamLength() throws {
let app = Application(.testing)
defer { app.shutdown() }
app.on(.POST, "echo", body: .stream) { request -> Response in
Response(body: .init(stream: { writer in
writer.write(.buffer(.init(string: "a")), promise: nil)
writer.write(.end, promise: nil)
}, count: 2))
}
let channel = EmbeddedChannel()
try channel.connect(to: .init(unixDomainSocketPath: "/foo")).wait()
try channel.pipeline.addVaporHTTP1Handlers(
application: app,
responder: app.responder,
configuration: app.http.server.configuration
).wait()
XCTAssertEqual(channel.isActive, true)
try channel.writeInbound(ByteBuffer(string: "POST /echo HTTP/1.1\r\n\r\n"))
XCTAssertEqual(channel.isActive, false)
try XCTAssertContains(channel.readOutbound(as: ByteBuffer.self)?.string, "HTTP/1.1 200 OK")
try XCTAssertEqual(channel.readOutbound(as: ByteBuffer.self)?.string, "a")
try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self)?.string)
}
override class func setUp() {
XCTAssert(isLoggingConfigured)
}
}
| mit |
squaremeals/squaremeals-ios-app | SquareMeals/Model/Protocols/AlertableError.swift | 1 | 670 | //
// AlertableError.swift
// SquareMeals
//
// Created by Zachary Shakked on 10/18/17.
// Copyright © 2017 Shakd, LLC. All rights reserved.
//
import UIKit
public protocol AlertableError {
var title: String { get }
var message: String { get }
func createAlertController() -> UIAlertController
}
public extension AlertableError {
public func createAlertController() -> UIAlertController {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okay = UIAlertAction(title: "Okay", style: .default, handler: nil)
alert.addAction(okay)
return alert
}
}
| mit |
alternativeapps/MemoryCap | MemoryCap/ViewController.swift | 1 | 502 | //
// ViewController.swift
// MemoryCap
//
// Created by Bao Trinh on 2/15/17.
// Copyright © 2017 Bao Trinh. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 |
qiang437587687/Brother | Brother/Brother/MoreOptional.swift | 1 | 1653 | //
// MoreOptional.swift
// Brother
//
// Created by zhang on 15/11/30.
// Copyright © 2015年 zhang. All rights reserved.
//
import Foundation
class MoreOptional {
func test() {
var string : String? = "string"
//下面的这两个是等效的~
var anotherString : String?? = string
var literalOptional : String?? = "string"
var aNil : String? = nil
//下面这两个是不等效的~
var anotherNil : String?? = aNil
var literalNil : String?? = nil
//下面这个是 在lldb 控制台中 打印的信息 fr v -R anotherNil 其中 anotherNil = Some literalNil = None
/*
fr v -R anotherNil
(Swift.Optional<Swift.Optional<Swift.String>>) anotherNil = Some {
Some = None {
Some = {
_core = {
_baseAddress = {
_rawValue = 0x0000000000000000
}
_countAndFlags = {
value = 0
}
_owner = None {
Some = {
instance_type = 0x0000000000000000
}
}
}
}
}
}
fr v -R literalNil
(Swift.Optional<Swift.Optional<Swift.String>>) literalNil = None {
Some = Some {
Some = {
_core = {
_baseAddress = {
_rawValue = 0x0000000000000000
}
_countAndFlags = {
value = 0
}
_owner = None {
Some = {
instance_type = 0x0000000000000000
}
}
}
}
}
}
*/
}
} | mit |
clowwindy/firefox-ios | Token/TokenServerClientTests.swift | 5 | 5651 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import XCTest
import FxA
import Client
let TEST_TOKEN_SERVER_ENDPOINT = STAGE_TOKEN_SERVER_ENDPOINT
let TEST_USERNAME = "testuser" // Really, testuser@mockmyid.com.
class TokenServerClientTests: XCTestCase {
func testAudienceForEndpoint() {
// Sub-domains and path components.
XCTAssertEqual("http://sub.test.com", TokenServerClient.getAudienceForEndpoint("http://sub.test.com"));
XCTAssertEqual("http://test.com", TokenServerClient.getAudienceForEndpoint("http://test.com/"));
XCTAssertEqual("http://test.com", TokenServerClient.getAudienceForEndpoint("http://test.com/path/component"));
XCTAssertEqual("http://test.com", TokenServerClient.getAudienceForEndpoint("http://test.com/path/component/"));
// No port and default port.
XCTAssertEqual("http://test.com", TokenServerClient.getAudienceForEndpoint("http://test.com"));
XCTAssertEqual("http://test.com:80", TokenServerClient.getAudienceForEndpoint("http://test.com:80"));
XCTAssertEqual("https://test.com", TokenServerClient.getAudienceForEndpoint("https://test.com"));
XCTAssertEqual("https://test.com:443", TokenServerClient.getAudienceForEndpoint("https://test.com:443"));
// Ports that are the default ports for a different scheme.
XCTAssertEqual("https://test.com:80", TokenServerClient.getAudienceForEndpoint("https://test.com:80"));
XCTAssertEqual("http://test.com:443", TokenServerClient.getAudienceForEndpoint("http://test.com:443"));
// Arbitrary ports.
XCTAssertEqual("http://test.com:8080", TokenServerClient.getAudienceForEndpoint("http://test.com:8080"));
XCTAssertEqual("https://test.com:4430", TokenServerClient.getAudienceForEndpoint("https://test.com:4430"));
}
func testSuccess() {
let url = TEST_TOKEN_SERVER_ENDPOINT
let expectation = expectationWithDescription("\(url)")
let keyPair = RSAKeyPair.generateKeyPairWithModulusSize(512)
let assertion = MockMyIDTokenFactory.defaultFactory().createAssertionWithKeyPair(keyPair, username: TEST_USERNAME, audience: TokenServerClient.getAudienceForEndpoint(url))
let client = TokenServerClient(endpoint: url)
client.tokenRequest(assertion: assertion).onSuccess { (token) in
expectation.fulfill()
XCTAssertNotNil(token.id)
XCTAssertNotNil(token.key)
XCTAssertNotNil(token.api_endpoint)
XCTAssertTrue(token.uid >= 0)
XCTAssertTrue(token.api_endpoint.hasSuffix(String(token.uid)))
}
.go { (error) in
expectation.fulfill()
println(error)
XCTFail("should have succeeded");
}
waitForExpectationsWithTimeout(10) { (error) in
XCTAssertNil(error, "\(error)")
}
}
func testFailure() {
let url = TEST_TOKEN_SERVER_ENDPOINT
let expectation = expectationWithDescription("\(url)")
let client = TokenServerClient(endpoint: url)
client.tokenRequest(assertion: "").onSuccess { (token) in
expectation.fulfill()
XCTFail("should have failed");
}
.go { (error) in
expectation.fulfill()
let t = error.userInfo!["code"]! as Int
XCTAssertEqual(t, 401)
}
waitForExpectationsWithTimeout(10) { (error) in
XCTAssertNil(error, "\(error)")
}
}
// let TEST_CLIENT_STATE = "1";
// let TEST_USERNAME_FOR_CLIENT_STATE = "test3";
//
// // Testing client state so delicate that I'm not going to test this. The test below does two requests; we would need a third, and a guarantee of the server state, to test this completely.
// // The rule is: if you turn up with a never-before-seen client state; you win. If you turn up with a seen-before client state, you lose.
// func testClientStateMatters() {
// let url = STAGE_TOKEN_SERVER_ENDPOINT
// let expectation1 = expectationWithDescription("\(url)")
// let expectation2 = expectationWithDescription("\(url)")
//
// let keyPair = RSAKeyPair.generateKeyPairWithModulusSize(512)
// let assertion = MockMyIDTokenFactory.defaultFactory().createAssertionWithKeyPair(keyPair, username: TEST_USERNAME_FOR_CLIENT_STATE, audience: TokenServerClient.getAudienceForEndpoint(url))
//
// var token1 : TokenServerToken!
// var token2 : TokenServerToken!
//
// let client = TokenServerClient(endpoint: url)
// client.tokenRequest(assertion: assertion).onSuccess { (token) in
// expectation1.fulfill()
// token1 = token
// }
// .go { (error) in
// expectation1.fulfill()
// println(error.userInfo!["code"]);
// XCTFail("should have succeeded");
// }
//
// client.tokenRequest(assertion: assertion).onSuccess { (token) in
// expectation2.fulfill()
// token2 = token
// }
// .go { (error) in
// expectation2.fulfill()
// println(error.userInfo!["code"]);
// XCTFail("should have succeeded");
// }
//
// waitForExpectationsWithTimeout(10) { (error) in
// XCTAssertNil(error, "\(error)")
// }
//
// XCTAssertNotEqual(token1.uid, token2.uid)
// }
}
| mpl-2.0 |
OneBestWay/EasyCode | Foundation.playground/Pages/NSTimier.xcplaygroundpage/Contents.swift | 1 | 1787 | //: Playground - noun: a place where people can play
/*:
在未来的某一时刻,执行一次或周期性的执行多次指定的方法
# Links
[nstimier-in-swift](https://www.weheartswift.com/nstimer-in-swift/)
# Note
* timier在哪个线程被触发,必须在哪个线程调用invalidate,将定时器从runloop中移出来
* timier会对他的target进行retain
* runloop会对添加到它里面的timer进行强引用
* timer在一个周期内智慧触发一次
* timier并不是实时的,会存在延迟,延迟的程度与当前执行的线程有关
* timier是一种source,source要起作用,必须添加到runloop中
* 如果某个runloop中没有了source,那么runloop会立即退出
# Timer没有运行的可能原因
* 没有添加到runloop中
* 所在的runloop没有运行
* 所在的runloopmode没有运行
#相关
延迟执行的三种方法: NSObject 的performSelector:withObject:afterDelay
NStimier: 在未来的某一断时间执行某个方法
GCD: dispatchafter
CADisplayLink:也可用作定时器,启调用间隔与屏幕刷新频率一致,每秒60次,如果在两次间隔之间执行了比较耗时的任务,将会造成界面卡顿
NSTimier和NSObject 都是基于runloop的,NSTimer的创建和销毁必须在同一线程,performselector的创建喝撤销必须在同一线程
performSelector:withObject:afterDelay的本质是在当前线程的runloop里去创建一个timer
dispatchAfter系统会处理线程级的问题,不用关心runloop的问题
dispatchAfter一旦执行,就不能被撤销
而performSelector可以使用cancelPreviousPerformRequestsWithTarget方法撤销
NSTimer也可以调用invalidate进行撤销
#用GCD实现一个timer
[ss](GCDTimier.png)
*/
| mit |
mergesort/Anchorman | Sources/Anchorman/Anchorable.swift | 1 | 14081 | import UIKit
/// A protocol for anything that provides a set `NSLayoutAnchor`s found in `UIView` and `UILayoutGuide`.
public protocol Anchorable {
var topAnchor: NSLayoutYAxisAnchor { get }
var bottomAnchor: NSLayoutYAxisAnchor { get }
var leadingAnchor: NSLayoutXAxisAnchor { get }
var trailingAnchor: NSLayoutXAxisAnchor { get }
var leftAnchor: NSLayoutXAxisAnchor { get }
var rightAnchor: NSLayoutXAxisAnchor { get }
var centerXAnchor: NSLayoutXAxisAnchor { get }
var centerYAnchor: NSLayoutYAxisAnchor { get }
var widthAnchor: NSLayoutDimension { get }
var heightAnchor: NSLayoutDimension { get }
}
extension UIView: Anchorable {}
extension UILayoutGuide: Anchorable {}
public extension Anchorable {
/// A function that allows you to add a `SizeAnchor` to an `Anchorable`.
///
/// - Parameters:
/// - sizeAnchor: The `SizeAnchor` we want to add to an `Anchorable`.
/// - relation: The relation to apply to the underlying `NSLayoutConstraint`.
/// - isActive: Whether or not the underlying `NSLayoutConstraint` will be active.
/// - Returns: An `NSLayoutConstraint` between the current `Anchorable` and another `Anchorable`.
@discardableResult
func set(size sizeAnchor: SizeAnchor, relation: NSLayoutConstraint.Relation = .equal, isActive: Bool = true) -> NSLayoutConstraint {
let currentDimension = sizeAnchor.layoutDimensionForAnchorable(anchorable: self)
let constraint: NSLayoutConstraint
if relation == .greaterThanOrEqual {
constraint = currentDimension.constraint(greaterThanOrEqualToConstant: sizeAnchor.constant)
} else if relation == .lessThanOrEqual {
constraint = currentDimension.constraint(lessThanOrEqualToConstant: sizeAnchor.constant)
} else {
constraint = currentDimension.constraint(equalToConstant: sizeAnchor.constant)
}
constraint.priority = sizeAnchor.priority
constraint.isActive = isActive
return constraint
}
/// A function that allows you to add a `[SizeAnchor]` to an `Anchorable`.
///
/// - Parameters:
/// - sizeAnchors: The `[SizeAnchor]` we want to add to an `Anchorable`.
/// - relation: The relation to apply to the underlying `NSLayoutConstraint`.
/// - isActive: Whether or not the underlying `NSLayoutConstraint` will be active.
/// - Returns: An `[NSLayoutConstraint]` between the current `Anchorable` and another `Anchorable`.
@discardableResult
func set(size sizeAnchors: [SizeAnchor] = [ SizeAnchor.width, SizeAnchor.height ], relation: NSLayoutConstraint.Relation = .equal, isActive: Bool = true) -> [NSLayoutConstraint] {
return sizeAnchors.map { return self.set(size: $0, relation: relation, isActive: isActive) }
}
}
extension Anchorable {
/// A function that allows you to pin one `Anchorable` to another `Anchorable`.
///
/// - Parameters:
/// - anchorable: The `Anchorable` to pin the current `Anchorable` to.
/// - edges: The `EdgeAnchor`s we wish to create `NSLayoutConstraint`s for.
/// - relation: The relation to apply to the underlying `NSLayoutConstraint`.
/// - isActive: Whether or not the underlying `NSLayoutConstraint` will be active.
/// - Returns: An `[NSLayoutConstraint]` between the current `Anchorable` and another `Anchorable`.
@discardableResult
func pin(toAnchorable anchorable: Anchorable, edges: [EdgeAnchor] = EdgeAnchor.allSides, relation: NSLayoutConstraint.Relation = .equal, isActive: Bool = true) -> [NSLayoutConstraint] {
func addConstraint(edge: EdgeAnchor) -> NSLayoutConstraint? {
guard edges.contains(edge) else {
return nil
}
let constant: CGFloat
let priority: UILayoutPriority
if let index = edges.firstIndex(of: edge) {
let currentEdge = edges[index]
constant = currentEdge.constant
priority = currentEdge.priority
} else {
constant = 0.0
priority = .required
}
let currentAnchor = edge.layoutAnchorForAnchorable(anchorable: self)
let viewAnchor = edge.layoutAnchorForAnchorable(anchorable: anchorable)
let constraint: NSLayoutConstraint
if relation == .greaterThanOrEqual {
constraint = currentAnchor.constraint(greaterThanOrEqualTo: viewAnchor, constant: constant)
} else if relation == .lessThanOrEqual {
constraint = currentAnchor.constraint(lessThanOrEqualTo: viewAnchor, constant: constant)
} else {
constraint = currentAnchor.constraint(equalTo: viewAnchor, constant: constant)
}
constraint.priority = priority
return constraint
}
let leadingConstraint = addConstraint(edge: .leading)
let trailingConstraint = addConstraint(edge: .trailing)
let topConstraint = addConstraint(edge: .top)
let bottomConstraint = addConstraint(edge: .bottom)
let centerXConstraint = addConstraint(edge: .centerX)
let centerYConstraint = addConstraint(edge: .centerY)
let widthConstraint = addConstraint(edge: .width)
let heightConstraint = addConstraint(edge: .height)
let viewConstraints = [ leadingConstraint, trailingConstraint, topConstraint, bottomConstraint, centerXConstraint, centerYConstraint, widthConstraint, heightConstraint ].compactMap { $0 }
viewConstraints.forEach { $0.isActive = isActive }
return viewConstraints
}
/// A function that allows you to pin one `Anchorable` to another `Anchorable`.
///
/// - Parameters:
/// - Parameters:
/// - edge: The `EdgeAnchor` of the current `Anchorable` we wish to create an `NSLayoutConstraint` for.
/// - toEdge: The `EdgeAnchor` of the `Anchorable` we wish to create an `NSLayoutConstraint` for.
/// - anchorable: The `Anchorable` to pin the current `Anchorable` to.
/// - relation: The relation to apply to the underlying `NSLayoutConstraint`.
/// - constant: The constant for the underlying `NSLayoutConstraint`.
/// - priority: The priority for the underlying `NSLayoutConstraint`. Default argument is `.required`.
/// - isActive: Whether or not the underlying `NSLayoutConstraint` will be active.
/// - Returns: An `NSLayoutConstraint` between the current `Anchorable` and another `Anchorable`.
@discardableResult
func pin(edge: EdgeAnchor, toEdge: EdgeAnchor, ofAnchorable anchorable: Anchorable, relation: NSLayoutConstraint.Relation = .equal, constant: CGFloat = 0.0, priority: UILayoutPriority = .required, isActive: Bool = true) -> NSLayoutConstraint {
let fromAnchor = edge.layoutAnchorForAnchorable(anchorable: self)
let toAnchor = toEdge.layoutAnchorForAnchorable(anchorable: anchorable)
let constraint: NSLayoutConstraint
if relation == .greaterThanOrEqual {
constraint = fromAnchor.constraint(greaterThanOrEqualTo: toAnchor, constant: constant)
} else if relation == .lessThanOrEqual {
constraint = fromAnchor.constraint(lessThanOrEqualTo: toAnchor, constant: constant)
} else {
constraint = fromAnchor.constraint(equalTo: toAnchor, constant: constant)
}
constraint.priority = priority
constraint.isActive = isActive
return constraint
}
/// A function that allows you to pin one `Anchorable` to another `Anchorable`.
///
/// - Parameters:
/// - sizeAnchor: The `SizeAnchor` of the current `Anchorable` we wish to create an `NSLayoutConstraint` for.
/// - toSizeAnchor: The `SizeAnchor` of the `Anchorable` we wish to create an `NSLayoutConstraint` for.
/// - anchorable: The `Anchorable` to pin the current `Anchorable` to.
/// - multiplier: The multiplier for the underlying `NSLayoutConstraint`.
/// - constant: The constant for the underlying `NSLayoutConstraint`.
/// - relation: The relation to apply to the underlying `NSLayoutConstraint`.
/// - isActive: Whether or not the underlying `NSLayoutConstraint` will be active.
/// - Returns: An `NSLayoutConstraint` between the current `Anchorable` and another `Anchorable`.
@discardableResult
func set(relativeSize sizeAnchor: SizeAnchor, toSizeAnchor: SizeAnchor, ofAnchorable anchorable: Anchorable, multiplier: CGFloat, constant: CGFloat, relation: NSLayoutConstraint.Relation = .equal, isActive: Bool = true) -> NSLayoutConstraint {
let fromDimension = sizeAnchor.layoutDimensionForAnchorable(anchorable: self)
let toDimension = toSizeAnchor.layoutDimensionForAnchorable(anchorable: anchorable)
let constraint: NSLayoutConstraint
if relation == .greaterThanOrEqual {
constraint = fromDimension.constraint(greaterThanOrEqualTo: toDimension, multiplier: multiplier, constant: constant)
} else if relation == .lessThanOrEqual {
constraint = fromDimension.constraint(lessThanOrEqualTo: toDimension, multiplier: multiplier, constant: constant)
} else {
constraint = fromDimension.constraint(equalTo: toDimension, multiplier: multiplier, constant: constant)
}
constraint.priority = sizeAnchor.priority
constraint.isActive = isActive
return constraint
}
}
private extension EdgeAnchor {
func layoutAnchorForAnchorable(anchorable: Anchorable) -> TypedAnchor {
switch self {
case EdgeAnchor.leading:
return .x(anchorable.leadingAnchor)
case EdgeAnchor.trailing:
return .x(anchorable.trailingAnchor)
case EdgeAnchor.top:
return .y(anchorable.topAnchor)
case EdgeAnchor.bottom:
return .y(anchorable.bottomAnchor)
case EdgeAnchor.centerX:
return .x(anchorable.centerXAnchor)
case EdgeAnchor.centerY:
return .y(anchorable.centerYAnchor)
case EdgeAnchor.width:
return .dimension(anchorable.widthAnchor)
case EdgeAnchor.height:
return .dimension(anchorable.heightAnchor)
default:
fatalError("There is an unhandled edge case with edges. Get it? Edge case… 😂")
}
}
}
private extension SizeAnchor {
func layoutDimensionForAnchorable(anchorable: Anchorable) -> NSLayoutDimension {
switch self {
case SizeAnchor.width:
return anchorable.widthAnchor
case SizeAnchor.height:
return anchorable.heightAnchor
default:
fatalError("There is an unhandled size. Have you considered inventing another dimension? 📐")
}
}
}
/// A typed anchor allows for creating only valid constraints along the same axis or dimension.
/// We want to prevent you from being able to pin a `.top` anchor to a `.leading`, since that is
/// an invalid combination.
///
/// - x: Anchors that are typed as `NSLayoutXAxisAnchor`.
/// - y: Anchors that are typed as `NSLayoutYAxisAnchor`.
/// - dimension: Anchors that are typed as `NSLayoutDimension`.
private enum TypedAnchor {
case x(NSLayoutXAxisAnchor)
case y(NSLayoutYAxisAnchor)
case dimension(NSLayoutDimension)
func constraint(equalTo anchor: TypedAnchor, constant: CGFloat) -> NSLayoutConstraint {
switch (self, anchor) {
case let (.x(fromConstraint), .x(toConstraint)):
return fromConstraint.constraint(equalTo: toConstraint, constant: constant)
case let(.y(fromConstraint), .y(toConstraint)):
return fromConstraint.constraint(equalTo: toConstraint, constant: constant)
case let(.dimension(fromConstraint), .dimension(toConstraint)):
return fromConstraint.constraint(equalTo: toConstraint, constant: constant)
default:
fatalError("I feel so constrainted, not cool! 🤐")
}
}
func constraint(greaterThanOrEqualTo anchor: TypedAnchor, constant: CGFloat) -> NSLayoutConstraint {
switch (self, anchor) {
case let (.x(fromConstraint), .x(toConstraint)):
return fromConstraint.constraint(greaterThanOrEqualTo: toConstraint, constant: constant)
case let(.y(fromConstraint), .y(toConstraint)):
return fromConstraint.constraint(greaterThanOrEqualTo: toConstraint, constant: constant)
case let(.dimension(fromConstraint), .dimension(toConstraint)):
return fromConstraint.constraint(greaterThanOrEqualTo: toConstraint, constant: constant)
default:
fatalError("I feel so constrainted, not cool! 🤐")
}
}
func constraint(lessThanOrEqualTo anchor: TypedAnchor, constant: CGFloat) -> NSLayoutConstraint {
switch (self, anchor) {
case let (.x(fromConstraint), .x(toConstraint)):
return fromConstraint.constraint(lessThanOrEqualTo: toConstraint, constant: constant)
case let(.y(fromConstraint), .y(toConstraint)):
return fromConstraint.constraint(lessThanOrEqualTo: toConstraint, constant: constant)
case let(.dimension(fromConstraint), .dimension(toConstraint)):
return fromConstraint.constraint(lessThanOrEqualTo: toConstraint, constant: constant)
default:
fatalError("I feel so constrainted, not cool! 🤐")
}
}
}
| mit |
taaviteska/CoreDataManager | Pod/Classes/Serializers.swift | 1 | 1348 | //
// Serializers.swift
// Pods
//
// Created by Taavi Teska on 12/09/15.
//
//
import CoreData
import SwiftyJSON
public typealias CDMValidator = (_ data:JSON) -> JSON?
open class CDMSerializer<T:NSManagedObject> {
open var identifiers = [String]()
open var forceInsert = false
open var insertMissing = true
open var updateExisting = true
open var deleteMissing = true
open var mapping: [String: CDMAttribute]
public init() {
self.mapping = [String: CDMAttribute]()
}
open func getValidators() -> [CDMValidator] {
return [CDMValidator]()
}
open func getGroupers() -> [NSPredicate] {
return [NSPredicate]()
}
open func addAttributes(_ attributes: JSON, toObject object: NSManagedObject) {
for (key, attribute) in self.mapping {
var newValue: Any?
if attribute.needsContext {
if let context = object.managedObjectContext {
newValue = attribute.valueFrom(attributes, inContext: context)
} else {
fatalError("Object has to have a managed object context")
}
} else {
newValue = attribute.valueFrom(attributes)
}
object.setValue(newValue, forKey: key)
}
}
}
| mit |
ismailbozkurt77/ZendeskClient | ZendeskExercise/Modules/TicketList/Mapper/TicketMapper.swift | 1 | 1045 | //
// TicketMapper.swift
// ZendeskExercise
//
// Created by Ismail on 07/01/2017.
// Copyright © 2017 Zendesk. All rights reserved.
//
import UIKit
class TicketMapper {
private lazy var numberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()
func ticketViewModel(model: Ticket) -> TicketViewModel {
let viewModel = TicketViewModel()
viewModel.status = model.status
viewModel.ticketDescription = model.ticketDescription
viewModel.subject = model.subject
if let ticketId = model.ticketId {
let ticketNumber = NSNumber(value: ticketId)
viewModel.ticketId = numberFormatter.string(from: ticketNumber)
}
return viewModel
}
func ticketViewModelArray(models: [Ticket]) -> [TicketViewModel] {
let viewModels = models.flatMap {
self.ticketViewModel(model: $0)
}
return viewModels
}
}
| mit |
milseman/swift | test/IRGen/vtable_symbol_linkage.swift | 8 | 449 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %S/Inputs/vtable_symbol_linkage_base.swift -emit-module -emit-module-path=%t/BaseModule.swiftmodule -emit-library -module-name BaseModule -o %t/BaseModule.%target-dylib-extension
// RUN: %target-build-swift -I %t %s %t/BaseModule.%target-dylib-extension -o %t/a.out
// Check if the program can be linked without undefined symbol errors.
import BaseModule
public class Derived : Base {
}
| apache-2.0 |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/iOS/Extensions/UICollectionViewLayoutAttributes+Color.swift | 1 | 469 |
import Foundation
extension UICollectionViewLayoutAttributes {
private struct AssociatedKeys {
static var colorKey = "UICollectionViewLayoutAttributes.colorKey"
}
var color: UIColor? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.colorKey) as? UIColor
} set {
objc_setAssociatedObject(self, &AssociatedKeys.colorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
| gpl-3.0 |
thinkclay/FlourishUI | Example/FlourishUI/AppDelegate.swift | 1 | 2180 | //
// AppDelegate.swift
// FlourishUI
//
// Created by Clay McIlrath on 01/22/2016.
// Copyright (c) 2016 Clay McIlrath. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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 |
pinterest/plank | Sources/Core/ObjectiveCDebugExtension.swift | 1 | 4584 | //
// ObjectiveCDebugExtension.swift
// plank
//
// Created by Rahul Malik on 2/28/17.
//
//
import Foundation
extension ObjCModelRenderer {
func renderDebugDescription() -> ObjCIR.Method {
let props = properties.filter { (_, schema) -> Bool in
!schema.schema.isBoolean()
}.map { (param, prop) -> String in
ObjCIR.ifStmt("props.\(dirtyPropertyOption(propertyName: param, className: self.className))") {
let ivarName = "_\(Languages.objectiveC.snakeCaseToPropertyName(param))"
return ["[descriptionFields addObject:[NSString stringWithFormat:\("\(ivarName) = %@".objcLiteral()), \(renderDebugStatement(param, prop.schema))]];"]
}
}.joined(separator: "\n")
let boolProps = properties.filter { (_, schema) -> Bool in
schema.schema.isBoolean()
}.map { (param, _) -> String in
ObjCIR.ifStmt("props.\(dirtyPropertyOption(propertyName: param, className: self.className))") {
let ivarName = "_\(booleanPropertiesIVarName).\(booleanPropertyOption(propertyName: param, className: self.className))"
return ["[descriptionFields addObject:[NSString stringWithFormat:\("\(ivarName) = %@".objcLiteral()), @(\(ivarName))]];"]
}
}
let printFormat = "\(className) = {\\n%@\\n}".objcLiteral()
return ObjCIR.method("- (NSString *)debugDescription", debug: true) { [
"NSArray<NSString *> *parentDebugDescription = [[super debugDescription] componentsSeparatedByString:\("\\n".objcLiteral())];",
"NSMutableArray *descriptionFields = [NSMutableArray arrayWithCapacity:\(self.properties.count)];",
"[descriptionFields addObject:parentDebugDescription];",
!self.properties.isEmpty ? "struct \(self.dirtyPropertyOptionName) props = _\(self.dirtyPropertiesIVarName);" : "",
props,
] + boolProps + ["return [NSString stringWithFormat:\(printFormat), debugDescriptionForFields(descriptionFields)];"] }
}
}
extension ObjCADTRenderer {
func renderDebugDescription() -> ObjCIR.Method {
let props = properties.map { (param, prop) -> String in
ObjCIR.ifStmt("self.internalType == \(self.renderInternalEnumTypeCase(name: ObjCADTRenderer.objectName(prop.schema)))") {
let ivarName = "_\(Languages.objectiveC.snakeCaseToPropertyName(param))"
return ["[descriptionFields addObject:[NSString stringWithFormat:\("\(ivarName) = %@".objcLiteral()), \(renderDebugStatement(param, prop.schema))]];"]
}
}.joined(separator: "\n")
let printFormat = "\(className) = {\\n%@\\n}".objcLiteral()
return ObjCIR.method("- (NSString *)debugDescription") { [
"NSArray<NSString *> *parentDebugDescription = [[super debugDescription] componentsSeparatedByString:\("\\n".objcLiteral())];",
"NSMutableArray *descriptionFields = [NSMutableArray arrayWithCapacity:\(self.properties.count)];",
"[descriptionFields addObject:parentDebugDescription];",
props,
"return [NSString stringWithFormat:\(printFormat), debugDescriptionForFields(descriptionFields)];",
] }
}
}
extension ObjCFileRenderer {
fileprivate func renderDebugStatement(_ param: String, _ schema: Schema) -> String {
let propIVarName = "_\(Languages.objectiveC.snakeCaseToPropertyName(param))"
switch schema {
case .enumT(.string):
return enumToStringMethodName(propertyName: param, className: className) + "(\(propIVarName))"
case .boolean:
return "@(_.\(booleanPropertyOption(propertyName: param, className: className)))"
case .float, .integer:
return "@(\(propIVarName))"
case .enumT(.integer):
return "@(\(propIVarName))"
case .string(format: _):
return propIVarName
case .array(itemType: _):
return propIVarName
case .set(itemType: _):
return propIVarName
case .map(valueType: _):
return propIVarName
case .object:
return propIVarName
case .oneOf(types: _):
return propIVarName
case let .reference(with: ref):
switch ref.force() {
case let .some(.object(schemaRoot)):
return renderDebugStatement(param, .object(schemaRoot))
default:
fatalError("Bad reference found in schema for class: \(className)")
}
}
}
}
| apache-2.0 |
vanyaland/Popular-Movies | iOS/PopularMovies/PopularMovies/MoviesCollectionViewDataSource.swift | 1 | 3803 | /**
* Copyright (c) 2016 Ivan Magda
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import AlamofireImage
// MARK: MoviesCollectionViewDataSource: NSObject
final class MoviesCollectionViewDataSource: NSObject {
var movies: [Movie]?
var didSelect: ((Movie) -> ())? = { _ in }
fileprivate var currentOrientation: UIDeviceOrientation!
override init() {
super.init()
let device = UIDevice.current
device.beginGeneratingDeviceOrientationNotifications()
let nc = NotificationCenter.default
nc.addObserver(forName: NSNotification.Name("UIDeviceOrientationDidChangeNotification"),
object: device, queue: nil, using: handleOrientationChange)
}
convenience init(_ movies: [Movie]) {
self.init()
self.movies = movies
}
deinit {
UIDevice.current.endGeneratingDeviceOrientationNotifications()
NotificationCenter.default.removeObserver(self)
}
private func handleOrientationChange(_ notification: Notification) {
if let device = notification.object as? UIDevice {
currentOrientation = device.orientation
}
}
}
// MARK: MoviesCollectionViewDataSource: UICollectionViewDataSource
extension MoviesCollectionViewDataSource: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return movies?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: MovieCollectionViewCell.reuseIdentifier,
for: indexPath) as! MovieCollectionViewCell
configure(cell: cell, atIndexPath: indexPath)
return cell
}
private func configure(cell: MovieCollectionViewCell, atIndexPath indexPath: IndexPath) {
let viewModel = MovieCellViewModel(movie: movies![indexPath.row])
cell.configure(with: viewModel)
}
}
// MARK: - MoviesCollectionViewDataSource: UICollectionViewDelegateFlowLayout -
extension MoviesCollectionViewDataSource: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return MovieCellViewModel.sizeForItem(with: currentOrientation,
andRootViewSize: collectionView.bounds.size)
}
}
// MARK: - MoviesCollectionViewDataSource: UICollectionViewDelegate -
extension MoviesCollectionViewDataSource: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
didSelect?(movies![indexPath.row])
}
}
| mit |
ngageoint/mage-ios | Mage/GridSystems.swift | 1 | 1305 | //
// GridSystems.swift
// MAGE
//
// Created by Brian Osborn on 9/15/22.
// Copyright © 2022 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import gars_ios
import mgrs_ios
/**
* Grid Systems support for GARS and MGRS grid tile overlays and coordinates
*/
@objc public class GridSystems : NSObject {
@objc public static func garsTileOverlay() -> GARSTileOverlay {
let tileOverlay = GARSTileOverlay()
// Customize GARS grid as needed here
return tileOverlay
}
@objc public static func mgrsTileOverlay() -> MGRSTileOverlay {
let tileOverlay = MGRSTileOverlay()
// Customize MGRS grid as needed here
return tileOverlay
}
@objc public static func gars(_ coordinate: CLLocationCoordinate2D) -> String {
return GARS.coordinate(coordinate)
}
@objc public static func mgrs(_ coordinate: CLLocationCoordinate2D) -> String {
return MGRS.coordinate(coordinate)
}
@objc public static func garsParse(_ coordinate: String) -> CLLocationCoordinate2D {
return GARS.parseToCoordinate(coordinate)
}
@objc public static func mgrsParse(_ coordinate: String) -> CLLocationCoordinate2D {
return MGRS.parseToCoordinate(coordinate)
}
}
| apache-2.0 |
cbrentharris/swift | validation-test/compiler_crashers/27915-swift-typechecker-checkomitneedlesswords.swift | 1 | 335 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class S<T{func a<h{func b<T where h.g=a{}}
enum a{{{}}struct b{{}struct S{enum a{{}class A{class a
let a
func a
| apache-2.0 |
roecrew/AudioKit | AudioKit/Common/Tests/AKWhiteNoiseTests.swift | 2 | 346 | //
// AKWhiteNoiseTests.swift
// AudioKitTestSuite
//
// Created by Nicholas Arner on 8/9/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import XCTest
import AudioKit
class AKWhiteNoiseTests: AKTestCase {
func testDefault() {
output = AKWhiteNoise()
AKTestMD5("d6b3484278d57bc40ce66df5decb88be")
}
} | mit |
nathawes/swift | test/SILOptimizer/inline_thunk.swift | 22 | 879 | // RUN: %target-swift-frontend -primary-file %s -parse-as-library -emit-ir -O | %FileCheck %s
// Two thunks are generated:
// 1. from function signature opts
// 2. the witness thunk
// Both should not inline the testit function and should set the noinline-attribute for llvm.
// CHECK-LABEL: define hidden swiftcc i32 @"{{.*}}testit{{.*}}F"(i32 %0)
// CHECK: call swiftcc i32 @{{.*}}testit{{.*}}Tf{{.*}} #[[ATTR:[0-9]+]]
// CHECK: ret
// CHECK-LABEL: define internal swiftcc i32 @"{{.*}}testit{{.*}}FTW"(i32
// CHECK: call swiftcc i32 @{{.*}}testit{{.*}}Tf{{.*}} #[[ATTR]]
// CHECK: ret
// CHECK: attributes #[[ATTR]] = { noinline }
protocol Proto {
func testit(x: Int32) -> Int32
}
struct TestStruct : Proto {
func testit(x: Int32) -> Int32 {
var y = x * 2
y += 1
y *= x
y += 1
y *= x
y += 1
y *= x
y += 1
y *= x
y += 1
y *= x
y += 1
return y
}
}
| apache-2.0 |
ivanarellano/swift-eightpuzzle | EightPuzzle/Coordinate.swift | 1 | 39 | typealias Coordinate = (x: Int, y: Int) | mit |
iosprogrammingwithswift/iosprogrammingwithswift | 08_SwiftTableViewControllerAndOtherFunnyStuff_Start_Final/SwiftTableViewControllerAndOtherFunnyStuff/DetailImageViewController.swift | 1 | 1160 | //
// DetailImageViewController.swift
// SwiftTableViewControllerAndOtherFunnyStuff
//
// Created by Andreas Wittmann on 10/01/15.
// Copyright (c) 2015 Telekom. All rights reserved.
//
import UIKit
class DetailImageViewController: UIViewController {
var image:UIImage?
@IBOutlet var detailImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
detailImageView.image = image
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
@IBAction func backToLastVC(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit |
killerpsyco/Parameter-Calculator-of-Transistor | TFT Performance/CalculatorViewController.swift | 1 | 6741 | //
// CalculatorViewController.swift
// TFT Performance
//
// Created by dyx on 15/7/21.
// Copyright (c) 2015年 dyx. All rights reserved.
//
import UIKit
class CalculatorViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var sumInMemory: Double = 0.0
var sumSoFar: Double = 0.0
var factorSoFar: Double = 0.0
var pendingAdditiveOperator = ""
var pendingMultiplicativeOperator = ""
var waitingForOperand = true
var displayValue: Double {
set {
let intValue = Int(newValue)
if (Double(intValue) == newValue) {
display.text = "\(intValue)"
} else {
display.text = "\(newValue)"
}
}
get {
return (display.text! as NSString).doubleValue
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func calculate(rightOperand: Double, pendingOperator: String) -> Bool {
var result = false
switch pendingOperator {
case "+":
sumSoFar += rightOperand
result = true
case "-":
sumSoFar -= rightOperand
result = true
case "*":
factorSoFar *= rightOperand
result = true
case "/":
if rightOperand != 0.0 {
factorSoFar /= rightOperand
result = true
}
default:
break
}
return result
}
func abortOperation() {
clearAll()
display.text = "####"
}
@IBAction func digitClicked(sender: UIButton) {
let digitValue = sender.currentTitle?.toInt()
if display.text!.toInt() == 0 && digitValue == 0 {
return
}
if waitingForOperand {
display.text = ""
waitingForOperand = false
}
display.text = display.text! + sender.currentTitle!
}
@IBAction func changeSignClicked() {
displayValue *= -1
}
@IBAction func backspaceClicked() {
if waitingForOperand {
return
}
var strValue = display.text!
display.text = dropLast(strValue)
if display.text!.isEmpty {
displayValue = 0.0
waitingForOperand = true
}
}
@IBAction func clear() {
if waitingForOperand {
return
}
displayValue = 0
waitingForOperand = true
}
@IBAction func clearAll() {
sumSoFar = 0.0
factorSoFar = 0.0
pendingAdditiveOperator = ""
pendingMultiplicativeOperator = ""
displayValue = 0.0
waitingForOperand = true
}
@IBAction func clearMemory() {
sumInMemory = 0.0
}
@IBAction func readMemory() {
displayValue = sumInMemory
waitingForOperand = true
}
@IBAction func setMemory() {
equalClicked()
sumInMemory = displayValue
}
@IBAction func addToMemory() {
equalClicked()
sumInMemory += displayValue
}
@IBAction func multiplicativeOperatorClicked(sender: UIButton) {
var clickedOperator = sender.currentTitle!
var operand = displayValue
if !pendingMultiplicativeOperator.isEmpty {
if !calculate(operand, pendingOperator: pendingMultiplicativeOperator) {
abortOperation()
return
}
displayValue = factorSoFar
} else {
factorSoFar = operand
}
pendingMultiplicativeOperator = clickedOperator
waitingForOperand = true
}
@IBAction func additiveOperatorClicked(sender: UIButton) {
let clickedOperator = sender.currentTitle!
var operand = displayValue
if !pendingMultiplicativeOperator.isEmpty {
if !calculate(operand, pendingOperator: pendingMultiplicativeOperator) {
abortOperation()
return
}
displayValue = factorSoFar
factorSoFar = 0.0
pendingMultiplicativeOperator = ""
}
if !pendingAdditiveOperator.isEmpty {
if !calculate(operand, pendingOperator: pendingAdditiveOperator) {
abortOperation()
return
}
displayValue = sumSoFar
} else {
sumSoFar = operand
}
pendingAdditiveOperator = clickedOperator
waitingForOperand = true
}
@IBAction func unaryOperatorClicked(sender: UIButton) {
let clickedOperator = sender.currentTitle!
var result: Double = 0
if clickedOperator == "Sqrt" {
if displayValue < 0 {
abortOperation()
return
}
result = sqrt(displayValue)
} else if clickedOperator == "x^2" {
result = pow(displayValue, 2)
} else if clickedOperator == "1/x" {
if displayValue == 0 {
abortOperation()
return
}
result = 1.0 / displayValue
}
displayValue = result
waitingForOperand = true
}
@IBAction func equalClicked() {
var operand = displayValue
if !pendingMultiplicativeOperator.isEmpty {
if !calculate(operand, pendingOperator: pendingMultiplicativeOperator) {
abortOperation()
return
}
operand = factorSoFar
factorSoFar = 0.0
pendingMultiplicativeOperator = ""
}
if !pendingAdditiveOperator.isEmpty {
if !calculate(operand, pendingOperator: pendingAdditiveOperator) {
abortOperation()
return
}
pendingAdditiveOperator = ""
} else {
sumSoFar = operand
}
displayValue = sumSoFar
sumSoFar = 0.0
waitingForOperand = 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.
}
*/
}
| epl-1.0 |
Mattmlm/codepathInstagramFeed | InstagramFeed/PhotosTableViewCell.swift | 1 | 730 | //
// PhotosTableViewCell.swift
// InstagramFeed
//
// Created by admin on 9/16/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
import AFNetworking
class PhotosTableViewCell: UITableViewCell {
@IBOutlet weak var instagramImageView: UIImageView?
// var imageURL : String?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setInstagramImage(imageURL: String) {
self.instagramImageView? .setImageWithURL(NSURL(string: imageURL)!)
}
}
| mit |
seyfeddin/Telefon | Telefon/Classes/TelefonConnectionType.swift | 1 | 1568 | //
// TelefonConnectionType.swift
// Pods
//
// Created by Seyfeddin Bassarac on 23/08/2017.
//
//
import Foundation
import ReachabilitySwift
import CoreTelephony
final public class TelefonConnectionType {
private let reachability = Reachability()!
public var w3cConnectionTypeString: String {
let networkStatus = reachability.currentReachabilityStatus
switch networkStatus {
case .notReachable:
return "none"
case .reachableViaWWAN:
let telephonyInfo = CTTelephonyNetworkInfo()
if telephonyInfo.currentRadioAccessTechnology != nil {
switch telephonyInfo.currentRadioAccessTechnology! {
case CTRadioAccessTechnologyGPRS, CTRadioAccessTechnologyEdge:
return "2g"
case CTRadioAccessTechnologyWCDMA,
CTRadioAccessTechnologyHSDPA,
CTRadioAccessTechnologyHSUPA,
CTRadioAccessTechnologyCDMA1x,
CTRadioAccessTechnologyCDMAEVDORev0,
CTRadioAccessTechnologyCDMAEVDORevA,
CTRadioAccessTechnologyCDMAEVDORevB,
CTRadioAccessTechnologyeHRPD:
return "3g"
case CTRadioAccessTechnologyLTE:
return "4g"
default:
return "unknown"
}
} else {
return "unknown"
}
case .reachableViaWiFi:
return "wifi"
}
}
}
| mit |
kylef/Stencil | Tests/StencilTests/XCTestManifests.swift | 1 | 7642 | import XCTest
extension ContextTests {
static let __allTests = [
("testContextRestoration", testContextRestoration),
("testContextSubscripting", testContextSubscripting),
]
}
extension EnvironmentBaseAndChildTemplateTests {
static let __allTests = [
("testRuntimeErrorInBaseTemplate", testRuntimeErrorInBaseTemplate),
("testRuntimeErrorInChildTemplate", testRuntimeErrorInChildTemplate),
("testSyntaxErrorInBaseTemplate", testSyntaxErrorInBaseTemplate),
("testSyntaxErrorInChildTemplate", testSyntaxErrorInChildTemplate),
]
}
extension EnvironmentIncludeTemplateTests {
static let __allTests = [
("testRuntimeError", testRuntimeError),
("testSyntaxError", testSyntaxError),
]
}
extension EnvironmentTests {
static let __allTests = [
("testLoading", testLoading),
("testRendering", testRendering),
("testRenderingError", testRenderingError),
("testSyntaxError", testSyntaxError),
("testUnknownFilter", testUnknownFilter),
]
}
extension ExpressionsTests {
static let __allTests = [
("testAndExpression", testAndExpression),
("testEqualityExpression", testEqualityExpression),
("testExpressionParsing", testExpressionParsing),
("testFalseExpressions", testFalseExpressions),
("testFalseInExpression", testFalseInExpression),
("testInequalityExpression", testInequalityExpression),
("testLessThanEqualExpression", testLessThanEqualExpression),
("testLessThanExpression", testLessThanExpression),
("testMoreThanEqualExpression", testMoreThanEqualExpression),
("testMoreThanExpression", testMoreThanExpression),
("testMultipleExpressions", testMultipleExpressions),
("testNotExpression", testNotExpression),
("testOrExpression", testOrExpression),
("testTrueExpressions", testTrueExpressions),
("testTrueInExpression", testTrueInExpression),
]
}
extension FilterTagTests {
static let __allTests = [
("testFilterTag", testFilterTag),
]
}
extension FilterTests {
static let __allTests = [
("testDefaultFilter", testDefaultFilter),
("testDynamicFilters", testDynamicFilters),
("testFilterSuggestion", testFilterSuggestion),
("testIndentContent", testIndentContent),
("testIndentFirstLine", testIndentFirstLine),
("testIndentNotEmptyLines", testIndentNotEmptyLines),
("testIndentWithArbitraryCharacter", testIndentWithArbitraryCharacter),
("testJoinFilter", testJoinFilter),
("testRegistration", testRegistration),
("testRegistrationOverrideDefault", testRegistrationOverrideDefault),
("testRegistrationWithArguments", testRegistrationWithArguments),
("testSplitFilter", testSplitFilter),
("testStringFilters", testStringFilters),
("testStringFiltersWithArrays", testStringFiltersWithArrays),
]
}
extension ForNodeTests {
static let __allTests = [
("testArrayOfTuples", testArrayOfTuples),
("testForNode", testForNode),
("testHandleInvalidInput", testHandleInvalidInput),
("testIterateDictionary", testIterateDictionary),
("testIterateRange", testIterateRange),
("testIterateUsingMirroring", testIterateUsingMirroring),
("testLoopMetadata", testLoopMetadata),
("testWhereExpression", testWhereExpression),
]
}
extension IfNodeTests {
static let __allTests = [
("testEvaluatesNilAsFalse", testEvaluatesNilAsFalse),
("testParseIf", testParseIf),
("testParseIfnot", testParseIfnot),
("testParseIfWithElif", testParseIfWithElif),
("testParseIfWithElifWithoutElse", testParseIfWithElifWithoutElse),
("testParseIfWithElse", testParseIfWithElse),
("testParseMultipleElif", testParseMultipleElif),
("testParsingErrors", testParsingErrors),
("testRendering", testRendering),
("testSupportsRangeVariables", testSupportsRangeVariables),
("testSupportVariableFilters", testSupportVariableFilters),
]
}
extension IncludeTests {
static let __allTests = [
("testParsing", testParsing),
("testRendering", testRendering),
]
}
extension InheritanceTests {
static let __allTests = [
("testInheritance", testInheritance),
]
}
extension LexerTests {
static let __allTests = [
("testComment", testComment),
("testContentMixture", testContentMixture),
("testEmptyVariable", testEmptyVariable),
("testEscapeSequence", testEscapeSequence),
("testNewlines", testNewlines),
("testPerformance", testPerformance),
("testText", testText),
("testTokenizeIncorrectSyntaxWithoutCrashing", testTokenizeIncorrectSyntaxWithoutCrashing),
("testTokenWithoutSpaces", testTokenWithoutSpaces),
("testUnclosedBlock", testUnclosedBlock),
("testUnclosedTag", testUnclosedTag),
("testVariable", testVariable),
("testVariablesWithoutBeingGreedy", testVariablesWithoutBeingGreedy),
]
}
extension NodeTests {
static let __allTests = [
("testRendering", testRendering),
("testTextNode", testTextNode),
("testVariableNode", testVariableNode),
]
}
extension NowNodeTests {
static let __allTests = [
("testParsing", testParsing),
("testRendering", testRendering),
]
}
extension StencilTests {
static let __allTests = [
("testStencil", testStencil),
]
}
extension TemplateLoaderTests {
static let __allTests = [
("testDictionaryLoader", testDictionaryLoader),
("testFileSystemLoader", testFileSystemLoader),
]
}
extension TemplateTests {
static let __allTests = [
("testTemplate", testTemplate),
]
}
extension TokenParserTests {
static let __allTests = [
("testTokenParser", testTokenParser),
]
}
extension TokenTests {
static let __allTests = [
("testToken", testToken),
]
}
extension VariableTests {
static let __allTests = [
("testArray", testArray),
("testDictionary", testDictionary),
("testKVO", testKVO),
("testLiterals", testLiterals),
("testMultipleSubscripting", testMultipleSubscripting),
("testOptional", testOptional),
("testRangeVariable", testRangeVariable),
("testReflection", testReflection),
("testSubscripting", testSubscripting),
("testTuple", testTuple),
("testVariable", testVariable),
]
}
#if !os(macOS)
public func __allTests() -> [XCTestCaseEntry] {
return [
testCase(ContextTests.__allTests),
testCase(EnvironmentBaseAndChildTemplateTests.__allTests),
testCase(EnvironmentIncludeTemplateTests.__allTests),
testCase(EnvironmentTests.__allTests),
testCase(ExpressionsTests.__allTests),
testCase(FilterTagTests.__allTests),
testCase(FilterTests.__allTests),
testCase(ForNodeTests.__allTests),
testCase(IfNodeTests.__allTests),
testCase(IncludeTests.__allTests),
testCase(InheritanceTests.__allTests),
testCase(LexerTests.__allTests),
testCase(NodeTests.__allTests),
testCase(NowNodeTests.__allTests),
testCase(StencilTests.__allTests),
testCase(TemplateLoaderTests.__allTests),
testCase(TemplateTests.__allTests),
testCase(TokenParserTests.__allTests),
testCase(TokenTests.__allTests),
testCase(VariableTests.__allTests),
]
}
#endif
| bsd-2-clause |
kostiakoval/Seru | Example/SeruDemoTests/PersistanceConfiguratorTest.swift | 9 | 1507 | //
// PersistanceConfiguratorTest.swift
// Seru
//
// Created by Konstantin Koval on 26/12/14.
// Copyright (c) 2014 Konstantin Koval. All rights reserved.
//
import Foundation
import XCTest
import CoreData
import Seru
class PersistanceConfiguratorTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testConfigurator() {
let config = PersistanceConfigurator(name: "MyTestName")
XCTAssertEqual(config.type, StoreType.SQLite)
XCTAssertEqual(config.location, StoreLocationType.PrivateFolder)
}
func testDefaultModelProvider() {
let config = PersistanceConfigurator(name: "MyTestName")
XCTAssertNotNil(config.modelProvider())
}
func testModelProvider() {
let modelProvider : ModelProviderType = {
let bundle = NSBundle(forClass: PersistenceStack.self)
return NSManagedObjectModel.mergedModelFromBundles([bundle])!
}
let config = PersistanceConfigurator(name: "MyTestName", modelLocation:.Custom(modelProvider))
let model = config.modelProvider()
XCTAssertNotNil(model)
let entities = model.entities as! [NSEntityDescription]
XCTAssertEqual(entities.count, 1)
XCTAssertEqual(entities.first!.name!, "Entity")
}
}
| mit |
johnfairh/TMLPersistentContainer | Tests/TMLPersistentContainerTests/TestModelVersionOrder.swift | 1 | 6291 | //
// TestModelVersionOrder.swift
// TMLPersistentContainer
//
// Distributed under the ISC license, see LICENSE.
//
import XCTest
import CoreData
@testable import TMLPersistentContainer
/// Tests for the version ordering widget
///
class TestModelVersionOrder: TestCase {
let dummyDescription = NSPersistentStoreDescription()
// Helper -- check an order implements a total order...
private func checkOrder(_ order: ModelVersionOrder, spec: [String]) {
spec.forEach { XCTAssertTrue(order.valid(version: $0)) }
for i in 0..<spec.count {
let earlier = spec[0..<i]
let this = spec[i]
let later = spec[i+1..<spec.count]
earlier.forEach {
XCTAssertTrue(order.precedes($0, this))
XCTAssertFalse(order.precedes(this, $0))
}
later.forEach {
XCTAssertTrue(order.precedes(this, $0))
XCTAssertFalse(order.precedes($0, this))
}
}
}
func testCanUseListOrder() {
let versions = ["Ver3", "Ver1", "Ver2"]
let order = ModelVersionOrder.list(versions)
guard let preparedOrder = order.prepare(for: dummyDescription) else {
XCTFail()
return
}
XCTAssertFalse(order.valid(version:"Not a version"))
checkOrder(preparedOrder, spec: versions)
}
func testCanDetectBadListOrder() {
let badOrder1 = ModelVersionOrder.list([])
XCTAssertNil(badOrder1.prepare(for: dummyDescription))
let badOrder2 = ModelVersionOrder.list(["VER1", "VER2", "VER1"])
XCTAssertNil(badOrder2.prepare(for: dummyDescription))
}
func testCanUseStringOrder() {
let versions = ["Ver1", "Ver2", "Ver10", "Ver400", "Ver3000"]
let order = ModelVersionOrder.compare
guard let preparedOrder = order.prepare(for: dummyDescription) else {
XCTFail()
return
}
checkOrder(preparedOrder, spec: versions)
}
// Helper for regex-type orders
private func prepareAndCheckNumericMatchOrder(_ order: ModelVersionOrder) {
let versions = ["Bar1", "Foo20", "Baz1000"]
guard let preparedOrder = order.prepare(for: dummyDescription) else {
XCTFail()
return
}
checkOrder(preparedOrder, spec: versions)
}
func testCanUsePatternOrderWithCaptureGroup() {
let order = ModelVersionOrder.patternMatchCompare("(\\d+)")
prepareAndCheckNumericMatchOrder(order)
}
func testCanUsePatternOrderWithoutCaptureGroup() {
let order = ModelVersionOrder.patternMatchCompare("\\d+")
prepareAndCheckNumericMatchOrder(order)
}
func testCanUseRegexOrder() {
let order = ModelVersionOrder.regexMatchCompare(try! NSRegularExpression(pattern: "\\d+"))
prepareAndCheckNumericMatchOrder(order)
}
func testCanUsePerStoreOrder() {
func descriptionToOrder(description: NSPersistentStoreDescription) -> ModelVersionOrder {
XCTAssertEqual(description, dummyDescription)
return ModelVersionOrder.patternMatchCompare("\\d+")
}
let order = ModelVersionOrder.perStore(descriptionToOrder)
prepareAndCheckNumericMatchOrder(order)
}
func testCanDetectBadRegex() {
let order = ModelVersionOrder.patternMatchCompare("(")
let preparedOrder = order.prepare(for: dummyDescription)
XCTAssertNil(preparedOrder)
}
// Pair-list orders.
func testCanUsePairList() {
let order = ModelVersionOrder.pairList([("A", "B"), ("B", "C"), ("C", "D")])
guard let preparedOrder = order.prepare(for: dummyDescription) else {
XCTFail("Prepare failed")
return
}
["A", "B", "C", "D"].forEach {
XCTAssertTrue(preparedOrder.valid(version: $0))
}
["Z", ""].forEach {
XCTAssertFalse(preparedOrder.valid(version: $0))
}
[("A", "B"), ("B", "C"), ("C", "D")].forEach { from, to in
XCTAssertTrue(preparedOrder.precedes(from, to))
}
[("A", "C"), ("B", "A"), ("Q", "C"), ("C", "Q"), ("Q", "Z")].forEach { from, to in
XCTAssertFalse(preparedOrder.precedes(from, to))
}
}
func testCanDetectPairListCycle() {
let order = ModelVersionOrder.pairList([("A", "B"), ("B", "C"), ("C", "A")])
let preparedOrder = order.prepare(for: dummyDescription)
XCTAssertNil(preparedOrder)
}
func testCanDetectBadPairListSelfCycle() {
let order = ModelVersionOrder.pairList([("A", "A")])
let preparedOrder = order.prepare(for: dummyDescription)
XCTAssertNil(preparedOrder)
}
func testCanSafelyHandleApiMisuse() {
let patternOrder = ModelVersionOrder.patternMatchCompare("Ab\\d+")
XCTAssertFalse(patternOrder.valid(version: "AnyVersion"))
XCTAssertFalse(patternOrder.valid(version: "Ab123"))
XCTAssertFalse(patternOrder.precedes("Ab1", "Ab2"))
XCTAssertFalse(patternOrder.precedes("Ab2", "Ab1"))
let perStoreOrder = ModelVersionOrder.perStore( { _ in .compare } )
XCTAssertFalse(perStoreOrder.valid(version: "AnyVersion"))
XCTAssertFalse(perStoreOrder.valid(version: "Ab123"))
XCTAssertFalse(perStoreOrder.precedes("Ab1", "Ab2"))
XCTAssertFalse(perStoreOrder.precedes("Ab2", "Ab1"))
let listOrder = ModelVersionOrder.list(["V1"])
XCTAssertFalse(listOrder.precedes("V2", "V3"))
XCTAssertFalse(listOrder.precedes("V1", "V2"))
XCTAssertFalse(listOrder.precedes("V2", "V1"))
}
// this just tests the to-string routines do not crash....
func testCanLogModelVersionOrders() {
let o1 = ModelVersionOrder.compare
let o2 = ModelVersionOrder.patternMatchCompare(".*")
let o3 = ModelVersionOrder.regexMatchCompare(try! NSRegularExpression(pattern: ".*"))
let o4 = ModelVersionOrder.list(["A", "B", "C"])
let o5 = ModelVersionOrder.pairList([("A", "B"), ("C", "D")])
let o6 = ModelVersionOrder.perStore({ _ in return ModelVersionOrder.compare})
print("\(o1) \(o2) \(o3) \(o4) \(o5) \(o6)")
}
}
| isc |
kysonyangs/ysbilibili | ysbilibili/Expand/Extensions/General/UIColor+ysAdd.swift | 1 | 2699 | //
// UIColor+ysAdd.swift
//
// Created by YangShen on 2017/7/19.
// Copyright © 2017年 YangShen. All rights reserved.
//
import UIKit
extension UIColor {
class func ysColor(red:CGFloat,green:CGFloat,blue:CGFloat,alpha:CGFloat) -> UIColor {
return UIColor(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: alpha)
}
/** 16进制转UIColor */
class func ysHexColor(hex: String) -> UIColor {
return proceesHex(hex: hex, alpha: 1)
}
/** 16进制转UIColor */
class func ysHexColorWithAlpha(hex: String, alpha: CGFloat) -> UIColor {
return proceesHex(hex: hex, alpha: alpha)
}
/// 随机色
class func ysRandomColor() -> UIColor {
let r = CGFloat(arc4random_uniform(256))
let g = CGFloat(arc4random_uniform(256))
let b = CGFloat(arc4random_uniform(256))
return ysColor(red: r, green: g, blue: b, alpha: 1)
}
}
// MARK: - 主要逻辑
fileprivate func proceesHex(hex: String, alpha: CGFloat) -> UIColor{
/** 如果传入的字符串为空 */
if hex.isEmpty {
return UIColor.clear
}
/** 传进来的值。 去掉了可能包含的空格、特殊字符, 并且全部转换为大写 */
let set = CharacterSet.whitespacesAndNewlines
var hHex = hex.trimmingCharacters(in: set).uppercased()
/** 如果处理过后的字符串少于6位 */
if hHex.characters.count < 6 {
return UIColor.clear
}
/** 开头是用0x开始的 */
if hHex.hasPrefix("0X") {
hHex = (hHex as NSString).substring(from: 2)
}
/** 开头是以#开头的 */
if hHex.hasPrefix("#") {
hHex = (hHex as NSString).substring(from: 1)
}
/** 开头是以##开始的 */
if hHex.hasPrefix("##") {
hHex = (hHex as NSString).substring(from: 2)
}
/** 截取出来的有效长度是6位, 所以不是6位的直接返回 */
if hHex.characters.count != 6 {
return UIColor.clear
}
/** R G B */
var range = NSMakeRange(0, 2)
/** R */
let rHex = (hHex as NSString).substring(with: range)
/** G */
range.location = 2
let gHex = (hHex as NSString).substring(with: range)
/** B */
range.location = 4
let bHex = (hHex as NSString).substring(with: range)
/** 类型转换 */
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rHex).scanHexInt32(&r)
Scanner(string: gHex).scanHexInt32(&g)
Scanner(string: bHex).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
}
| mit |
chengxianghe/XHPhotoBrowser | XHPhotoBrowser/AppDelegate.swift | 1 | 438 | //
// AppDelegate.swift
// XHPhotoBrowser
//
// Created by chengxianghe on 16/8/9.
// Copyright © 2016年 cn. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
}
| mit |
rishindrareddy/VM-Backup | FirstStep/FirstStep/HomeViewController.swift | 1 | 856 | //
// HomeViewController.swift
// FirstStep
//
// Created by Rishi on 5/7/17.
// Copyright © 2017 rishindra. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 |
kazmasaurus/SwiftTransforms | SmokeTest/SmokeTest.swift | 1 | 1426 | //
// SmokeTest.swift
// SmokeTest
//
// Created by Zak Remer on 7/19/15.
// Copyright (c) 2015 Zak. All rights reserved.
//
import UIKit
import XCTest
class SmokeTest: XCTestCase {
// This is a smoke test to see if any of this functionality has been included by Apple.
// Every line here represents functionality provided by this library.
// Any line _not_ throwing a build error has been added by Apple and can be removed.
typealias Transform = CGAffineTransform
static let xi = 10
static let yi = 11
typealias S = SmokeTest
let x = CGFloat(S.xi)
let y = CGFloat(S.yi)
let xd = Double(S.xi)
let yd = Double(S.yi)
let xi: Int = S.xi
let yi: Int = S.yi
func testCompilation() {
Transform() == Transform()
Transform.identityTransform
Transform(scalex: x, y: y)
Transform(scalex: xd, y: yd)
Transform(scalex: xi, y: yi)
Transform(translatex: x, y: y)
Transform(translatex: xd, y: yd)
Transform(translatex: xi, y: yi)
Transform(rotate: x)
Transform(rotate: xd)
Transform(rotate: xi)
Transform().translate(x, ty: y)
Transform().translate(xd, ty: yd)
Transform().translate(xi, ty: yi)
Transform().scale(x, sy: y)
Transform().scale(xd, sy: yd)
Transform().scale(xi, sy: yi)
Transform().rotate(x)
Transform().rotate(xd)
Transform().rotate(xi)
Transform().invert()
Transform().inverse
Transform().concat(Transform())
Transform() * Transform()
}
}
| mit |
michaello/Aloha | AlohaGIF/Promise/Promise.swift | 1 | 7256 | //
// Promise.swift
// Promise
//
// Created by Soroush Khanlou on 7/21/16.
//
//
import Foundation
public protocol ExecutionContext {
func execute(_ work: @escaping () -> Void)
}
extension DispatchQueue: ExecutionContext {
public func execute(_ work: @escaping () -> Void) {
self.async(execute: work)
}
}
public final class InvalidatableQueue: ExecutionContext {
private var valid = true
private let queue: DispatchQueue
public init(queue: DispatchQueue = .main) {
self.queue = queue
}
public func invalidate() {
valid = false
}
public func execute(_ work: @escaping () -> Void) {
guard valid else { return }
self.queue.async(execute: work)
}
}
struct Callback<Value> {
let onFulfilled: (Value) -> ()
let onRejected: (Error) -> ()
let queue: ExecutionContext
func callFulfill(_ value: Value) {
queue.execute({
self.onFulfilled(value)
})
}
func callReject(_ error: Error) {
queue.execute({
self.onRejected(error)
})
}
}
enum State<Value>: CustomStringConvertible {
/// The promise has not completed yet.
/// Will transition to either the `fulfilled` or `rejected` state.
case pending
/// The promise now has a value.
/// Will not transition to any other state.
case fulfilled(value: Value)
/// The promise failed with the included error.
/// Will not transition to any other state.
case rejected(error: Error)
var isPending: Bool {
if case .pending = self {
return true
} else {
return false
}
}
var isFulfilled: Bool {
if case .fulfilled = self {
return true
} else {
return false
}
}
var isRejected: Bool {
if case .rejected = self {
return true
} else {
return false
}
}
var value: Value? {
if case let .fulfilled(value) = self {
return value
}
return nil
}
var error: Error? {
if case let .rejected(error) = self {
return error
}
return nil
}
var description: String {
switch self {
case .fulfilled(let value):
return "Fulfilled (\(value))"
case .rejected(let error):
return "Rejected (\(error))"
case .pending:
return "Pending"
}
}
}
public final class Promise<Value> {
private var state: State<Value>
private let lockQueue = DispatchQueue(label: "promise_lock_queue", qos: .userInitiated)
private var callbacks: [Callback<Value>] = []
public init() {
state = .pending
}
public init(value: Value) {
state = .fulfilled(value: value)
}
public init(error: Error) {
state = .rejected(error: error)
}
public convenience init(queue: DispatchQueue = DispatchQueue.global(qos: .userInitiated), work: @escaping (_ fulfill: @escaping (Value) -> (), _ reject: @escaping (Error) -> () ) throws -> ()) {
self.init()
queue.async(execute: {
do {
try work(self.fulfill, self.reject)
} catch let error {
self.reject(error)
}
})
}
/// - note: This one is "flatMap"
@discardableResult
public func then<NewValue>(on queue: ExecutionContext = DispatchQueue.main, _ onFulfilled: @escaping (Value) throws -> Promise<NewValue>) -> Promise<NewValue> {
return Promise<NewValue>(work: { fulfill, reject in
self.addCallbacks(
on: queue,
onFulfilled: { value in
do {
try onFulfilled(value).then(fulfill, reject)
} catch let error {
reject(error)
}
},
onRejected: reject
)
})
}
/// - note: This one is "map"
@discardableResult
public func then<NewValue>(on queue: ExecutionContext = DispatchQueue.main, _ onFulfilled: @escaping (Value) throws -> NewValue) -> Promise<NewValue> {
return then(on: queue, { (value) -> Promise<NewValue> in
do {
return Promise<NewValue>(value: try onFulfilled(value))
} catch let error {
return Promise<NewValue>(error: error)
}
})
}
@discardableResult
public func then(on queue: ExecutionContext = DispatchQueue.main, _ onFulfilled: @escaping (Value) -> (), _ onRejected: @escaping (Error) -> () = { _ in }) -> Promise<Value> {
_ = Promise<Value>(work: { fulfill, reject in
self.addCallbacks(
on: queue,
onFulfilled: { value in
fulfill(value)
onFulfilled(value)
},
onRejected: { error in
reject(error)
onRejected(error)
}
)
})
return self
}
@discardableResult
public func `catch`(on queue: ExecutionContext = DispatchQueue.main, _ onRejected: @escaping (Error) -> ()) -> Promise<Value> {
return then(on: queue, { _ in }, onRejected)
}
public func reject(_ error: Error) {
updateState(.rejected(error: error))
}
public func fulfill(_ value: Value) {
updateState(.fulfilled(value: value))
}
public var isPending: Bool {
return !isFulfilled && !isRejected
}
public var isFulfilled: Bool {
return value != nil
}
public var isRejected: Bool {
return error != nil
}
public var value: Value? {
return lockQueue.sync(execute: {
return self.state.value
})
}
public var error: Error? {
return lockQueue.sync(execute: {
return self.state.error
})
}
private func updateState(_ state: State<Value>) {
guard self.isPending else { return }
lockQueue.sync(execute: {
self.state = state
})
fireCallbacksIfCompleted()
}
private func addCallbacks(on queue: ExecutionContext = DispatchQueue.main, onFulfilled: @escaping (Value) -> (), onRejected: @escaping (Error) -> ()) {
let callback = Callback(onFulfilled: onFulfilled, onRejected: onRejected, queue: queue)
lockQueue.async(execute: {
self.callbacks.append(callback)
})
fireCallbacksIfCompleted()
}
private func fireCallbacksIfCompleted() {
lockQueue.async(execute: {
guard !self.state.isPending else { return }
self.callbacks.forEach { callback in
switch self.state {
case let .fulfilled(value):
callback.callFulfill(value)
case let .rejected(error):
callback.callReject(error)
default:
break
}
}
self.callbacks.removeAll()
})
}
}
| mit |
yellowChao/beverly | DTMaster/DTMaster/ViewController.swift | 1 | 540 | //
// ViewController.swift
// DTMaster
//
// Created by yellow on 16/5/9.
// Copyright © 2016年 yellow. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
#if BETA
print("BETA")
#endif
#if STAGING
print("STAGING")
#endif
#if PRODUCT
print("PRODUCT")
#endif
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
sathishkraj/SwiftLazyLoading | SwiftLazyLoading/ParseOperation.swift | 1 | 4318 | //
// ParseOperation.swift
// SwiftLazyLoading
//
// Copyright (c) 2015 Sathish Kumar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
let kIDStr: NSString = "id"
let kNameStr: NSString = "im:name";
let kImageStr: NSString = "im:image";
let kArtistStr: NSString = "im:artist";
let kEntryStr: NSString = "entry";
class ParseOperation: NSOperation , NSXMLParserDelegate {
var errorHandler: ((error: NSError?) -> ())? = nil
var appRecordList: NSArray? = nil
var dataToParse: NSData? = nil
var workingArray: NSMutableArray? = nil
var workingEntry: AppRecord? = nil
var workingPropertyString: NSMutableString? = nil
var elementsToParse: NSArray? = nil
var storingCharacterData: Bool = false
init(data: NSData?) {
super.init()
self.dataToParse = data
self.elementsToParse = NSArray(objects: kIDStr, kNameStr, kImageStr, kArtistStr)
}
override func main() {
self.workingArray = NSMutableArray()
self.workingPropertyString = NSMutableString()
let parser = NSXMLParser(data: self.dataToParse!)
parser.delegate = self
parser.parse()
if !self.cancelled {
self.appRecordList = NSArray(array: self.workingArray!)
}
self.workingArray = nil;
self.workingPropertyString = nil;
self.dataToParse = nil;
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
if elementName == kEntryStr {
self.workingEntry = AppRecord()
}
self.storingCharacterData = self.elementsToParse!.containsObject(elementName)
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if self.workingEntry != nil {
if self.storingCharacterData
{
let trimmedString: NSString = self.workingPropertyString!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
self.workingPropertyString!.setString("")
if elementName == kIDStr {
self.workingEntry!.appURLString = trimmedString
} else if elementName == kNameStr {
self.workingEntry!.appName = trimmedString
} else if elementName == kImageStr {
self.workingEntry!.imageURLString = trimmedString
} else if elementName == kArtistStr {
self.workingEntry!.artist = trimmedString
}
}
else if elementName == kEntryStr
{
self.workingArray!.addObject(self.workingEntry!)
self.workingEntry = nil;
}
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
if self.storingCharacterData {
self.workingPropertyString!.appendString(string)
}
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
if (self.errorHandler != nil) {
self.errorHandler!(error: parseError)
}
}
}
| mit |
jaredsinclair/sodes-audio-example | Sodes/SodesAudio/ResourceLoaderDelegate.swift | 1 | 24946 | //
// ResourceLoaderDelegate.swift
// SodesAudio
//
// Created by Jared Sinclair on 7/14/16.
//
//
import Foundation
import AVFoundation
import CommonCryptoSwift
import SodesFoundation
import SwiftableFileHandle
protocol ResourceLoaderDelegateDelegate: class {
func resourceLoaderDelegate(_ delegate: ResourceLoaderDelegate, didEncounter error: Error?)
func resourceLoaderDelegate(_ delegate: ResourceLoaderDelegate, didUpdateLoadedByteRanges ranges: [ByteRange])
}
///-----------------------------------------------------------------------------
/// ResourceLoaderDelegate
///-----------------------------------------------------------------------------
/// Custom AVAssetResourceLoaderDelegate which stores downloaded audio data to
/// re-usable scratch files on disk. This class thus allows an audio file to be
/// streamed across multiple app sessions with the least possible amount of
/// redownloaded data.
///
/// ResourceLoaderDelegate does not currently keep data for more than one
/// resource at a time. If the user frequently changes audio sources this class
/// will be of limited benefit. In the future, it might be wise to provide a
/// dynamic maximum number of cached sources, perhaps keeping data for the most
/// recent 3 to 5 sources.
internal class ResourceLoaderDelegate: NSObject, AVAssetResourceLoaderDelegate {
/// Enough said.
internal enum ErrorStatus {
case none
case error(Error?)
}
// MARK: Internal Properties
/// The ResourceLoaderDelegate's, err..., delegate.
internal weak var delegate: ResourceLoaderDelegateDelegate?
/// The current error status
internal fileprivate(set) var errorStatus: ErrorStatus = .none
// MARK: Private Properties (Immutable)
/// Used to store the URL for the most-recently used audio source.
fileprivate let defaults: UserDefaults
/// The directory where all scratch file subdirectories are stored.
fileprivate let resourcesDirectory: URL
/// A loading scheme used to ensure that the AVAssetResourceLoader routes
/// its requests to this class.
fileprivate let customLoadingScheme: String
/// A serial queue on which AVAssetResourceLoader will call delegate methods.
fileprivate let loaderQueue: DispatchQueue
/// A date formatter used when parsing Last-Modified header values.
fileprivate let formatter = RFC822Formatter()
/// A throttle used to limit how often we save scratch file metadata (byte
/// ranges, cache validation header info) to disk.
fileprivate let byteRangeThrottle = Throttle(
minimumInterval: 1.0,
qualityOfService: .background
)
// MARK: Private Properties (Mutable)
/// The current resource loader. We can't assume that the same one will
/// always be used, so keeping a reference to it here helps us avoid
/// cross-talk between audio sessions.
fileprivate var currentAVAssetResourceLoader: AVAssetResourceLoader?
/// The info for the scratch file for the current session.
fileprivate var scratchFileInfo: ScratchFileInfo? {
didSet {
if let oldValue = oldValue {
if oldValue.resourceUrl != scratchFileInfo?.resourceUrl {
unprepare(oldValue)
}
}
}
}
/// The request wrapper object containg references to all the info needed
/// to process the current AVAssetResourceLoadingRequest.
fileprivate var currentRequest: Request? {
didSet {
// Under conditions that I don't know how to reproduce, AVFoundation
// sometimes fails to cancel previous requests that cover ~90% of
// of the previous. It seems to happen when repeatedly seeking, but
// it could have been programmer error. Either way, in my testing, I
// found that cancelling (by finishing early w/out data) the
// previous request, I can keep the activity limited to a single
// request and vastly improve loading times, especially on poor
// networks.
oldValue?.cancel()
}
}
// MARK: Init/Deinit
/// Designated initializer.
internal init(customLoadingScheme: String, resourcesDirectory: URL, defaults: UserDefaults) {
SodesLog(resourcesDirectory)
self.defaults = defaults
self.resourcesDirectory = resourcesDirectory
self.customLoadingScheme = customLoadingScheme
self.loaderQueue = DispatchQueue(label: "com.SodesAudio.ResourceLoaderDelegate.loaderQueue")
super.init()
// Remove zombie scratch file directories in case of a premature exit
// during a previous session.
if let mostRecentResourceUrl = defaults.mostRecentResourceUrl {
let directoryToKeep = scratchFileDirectory(for: mostRecentResourceUrl).lastPathComponent
if let contents = try? FileManager.default.contentsOfDirectory(atPath: resourcesDirectory.path) {
for directoryName in contents.filter({$0 != directoryToKeep && !$0.hasPrefix(".")}) {
SodesLog("Removing zombie scratch directory at: \(directoryName)")
let url = resourcesDirectory.appendingPathComponent(directoryName, isDirectory: true)
_ = FileManager.default.removeDirectory(url)
}
}
}
}
// MARK: Internal Methods
/// Prepares an AVURLAsset, configuring the resource loader's delegate, etc.
/// This method returns nil if the receiver cannot prepare an asset that it
/// can handle.
internal func prepareAsset(for url: URL) -> AVURLAsset? {
errorStatus = .none
guard url.hasPathExtension("mp3") else {
SodesLog("Bad url: \(url)\nResourceLoaderDelegate only supports urls with an .mp3 path extension.")
return nil
}
guard let redirectUrl = url.convertToRedirectURL(prefix: customLoadingScheme) else {
SodesLog("Bad url: \(url)\nCould not convert the url to a redirect url.")
return nil
}
currentAVAssetResourceLoader = nil
// If there's no scratch file info, that means that playback has not yet
// begun during this app session. A previous session could still have
// its scratchfile data on disk. If the most recent resource url is the
// same as `url`, then leave it as-is so we can re-use the data.
// Otherwise, remove that data from disk.
if scratchFileInfo == nil {
if let previous = defaults.mostRecentResourceUrl, previous != url {
removeFiles(for: previous)
}
}
loaderQueue.sync {
currentRequest = nil
scratchFileInfo = prepareScratchFileInfo(for: url)
}
guard scratchFileInfo != nil else {
assertionFailure("Could not create scratch file info for: \(url)")
defaults.mostRecentResourceUrl = nil
return nil
}
delegate?.resourceLoaderDelegate(self, didUpdateLoadedByteRanges: scratchFileInfo!.loadedByteRanges)
defaults.mostRecentResourceUrl = url
let asset = AVURLAsset(url: redirectUrl)
asset.resourceLoader.setDelegate(self, queue: loaderQueue)
currentAVAssetResourceLoader = asset.resourceLoader
return asset
}
// MARK: Private Methods
/// Convenience method for handling a content info request.
fileprivate func handleContentInfoRequest(for loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
SodesLog("Will attempt to handle content info request.")
guard let infoRequest = loadingRequest.contentInformationRequest else {return false}
guard let redirectURL = loadingRequest.request.url else {return false}
guard let originalURL = redirectURL.convertFromRedirectURL(prefix: customLoadingScheme) else {return false}
guard let scratchFileInfo = self.scratchFileInfo else {return false}
SodesLog("Will handle content info request.")
// Even though we re-use the downloaded bytes from a previous session,
// we should always make a roundtrip for the content info requests so
// that we can use HTTP cache validation header values to see if we need
// to redownload the data. Podcast MP3s can be replaced without changing
// the URL for the episode (adding new commercials to old episodes, etc.)
let request: URLRequest = {
var request = URLRequest(url: originalURL)
if let dataRequest = loadingRequest.dataRequest {
// Nota Bene: Even though the content info request is often
// accompanied by a data request, **do not** invoke the data
// requests `respondWithData()` method as this will put the
// asset loading request into an undefined state. This isn't
// documented anywhere, but beware.
request.setByteRangeHeader(for: dataRequest.byteRange)
}
return request
}()
let task = URLSession.shared.downloadTask(with: request) { (tempUrl, response, error) in
// I'm using strong references to `self` because I don't know if
// AVFoundation could recover if `self` became nil before cancelling
// all active requests. Retaining `self` here is easier than the
// alternatives. Besides, this class has been designed to accompany
// a singleton PlaybackController.
self.loaderQueue.async {
// Bail early if the content info request was cancelled.
guard !loadingRequest.isCancelled else
{
SodesLog("Bailing early because the loading request was cancelled.")
return
}
guard let request = self.currentRequest as? ContentInfoRequest,
loadingRequest === request.loadingRequest else
{
SodesLog("Bailing early because the loading request has changed.")
return
}
guard let delayedScratchFileInfo = self.scratchFileInfo,
delayedScratchFileInfo === scratchFileInfo else
{
SodesLog("Bailing early because the scratch file info has changed.")
return
}
if let response = response, error == nil {
// Check the Etag and Last-Modified header values to see if
// the file has changed since the last cache info was
// fetched (if this is the first time we're seeing this
// file, the existing info will be blank, which is fine). If
// the cached info is no longer valid, wipe the loaded byte
// ranges from the metadata and update the metadata with the
// new Etag/Last-Modified header values.
//
// If the content provider never provides cache validation
// values, this means we will always re-download the data.
//
// Note that we're not removing the bytes from the actual
// scratch file on disk. This may turn out to be a bad idea,
// but for now lets assume that our byte range metadata is
// always up-to-date, and that by resetting the loaded byte
// ranges here we will prevent future subrequests from
// reading byte ranges that have since been invalidated.
// This works because DataRequestLoader will not create any
// scratch file subrequests if the loaded byte ranges are
// empty.
let cacheInfo = response.cacheInfo(using: self.formatter)
if !delayedScratchFileInfo.cacheInfo.isStillValid(comparedTo: cacheInfo) {
delayedScratchFileInfo.cacheInfo = cacheInfo
self.saveUpdatedScratchFileMetaData(immediately: true)
SodesLog("Reset the scratch file meta data since the cache validation values have changed.")
}
SodesLog("Item completed: content request: \(response)")
infoRequest.update(with: response)
loadingRequest.finishLoading()
}
else {
// Do not update the scratch file meta data here since the
// request could have failed for any number of reasons.
// Let's only reset meta data if we receive a successful
// response.
SodesLog("Failed with error: \(error)")
self.finish(loadingRequest, with: error)
}
if self.currentRequest === request {
// Nil-out `currentRequest` since we're done with it, but
// only if the value of self.currentRequest didn't change
// (since we just called `loadingRequest.finishLoading()`.
self.currentRequest = nil
}
}
}
self.currentRequest = ContentInfoRequest(
resourceUrl: originalURL,
loadingRequest: loadingRequest,
infoRequest: infoRequest,
task: task
)
task.resume()
return true
}
/// Convenience method for handling a data request. Uses a DataRequestLoader
/// to load data from either the scratch file or the network, optimizing for
/// the former to prevent unnecessary network usage.
fileprivate func handleDataRequest(for loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
SodesLog("Will attempt to handle data request.")
guard let avDataRequest = loadingRequest.dataRequest else {return false}
guard let redirectURL = loadingRequest.request.url else {return false}
guard let originalURL = redirectURL.convertFromRedirectURL(prefix: customLoadingScheme) else {return false}
guard let scratchFileInfo = scratchFileInfo else {return false}
SodesLog("Can handle this data request.")
let lowerBound = avDataRequest.requestedOffset // e.g. 0, for Range(0..<4)
let length = avDataRequest.requestedLength // e.g. 3, for Range(0..<4)
let upperBound = lowerBound + length // e.g. 4, for Range(0..<4)
let dataRequest: DataRequest = {
let loader = DataRequestLoader(
resourceUrl: originalURL,
requestedRange: (lowerBound..<upperBound),
delegate: self,
callbackQueue: loaderQueue,
scratchFileHandle: scratchFileInfo.fileHandle,
scratchFileRanges: scratchFileInfo.loadedByteRanges
)
return DataRequest(
resourceUrl: originalURL,
loadingRequest: loadingRequest,
dataRequest: avDataRequest,
loader: loader
)
}()
self.currentRequest = dataRequest
dataRequest.loader.start()
return true
}
}
///-----------------------------------------------------------------------------
/// ResourceLoaderDelegate: AVAssetResourceLoaderDelegate
///-----------------------------------------------------------------------------
extension ResourceLoaderDelegate {
/// Initiates a new loading request. This could be either a content info or
/// a data request. This method returns `false` if the request cannot be
/// handled.
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
guard currentAVAssetResourceLoader === resourceLoader else {return false}
if let _ = loadingRequest.contentInformationRequest {
return handleContentInfoRequest(for: loadingRequest)
} else if let _ = loadingRequest.dataRequest {
return handleDataRequest(for: loadingRequest)
} else {
return false
}
}
/// Not used. Throws a fatal error when hit. ResourceLoaderDelegate has not
/// been designed to be used with assets that require authentication.
func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForRenewalOfRequestedResource renewalRequest: AVAssetResourceRenewalRequest) -> Bool {
fatalError()
}
/// Cancels the current request.
@objc(resourceLoader:didCancelLoadingRequest:) func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) {
guard let request = currentRequest as? DataRequest else {return}
guard loadingRequest === request.loadingRequest else {return}
currentRequest = nil
}
}
///-----------------------------------------------------------------------------
/// ResourceLoaderDelegate: Scratch File Info Handling
///-----------------------------------------------------------------------------
fileprivate extension ResourceLoaderDelegate {
/// Returns a unique id for `url`.
func identifier(for url: URL) -> String {
return Hash.MD5(url.absoluteString)!
}
/// Returns the desired URL for the scratch file subdirectory for `resourceUrl`.
func scratchFileDirectory(for resourceUrl: URL) -> URL {
let directoryName = identifier(for: resourceUrl)
return resourcesDirectory.appendingPathComponent(directoryName, isDirectory: true)
}
/// Prepares a subdirectory for the scratch file and its metadata, as well
/// as a file handle for reading/writing. This method returns nil if there
/// was an unrecoverable error during setup.
func prepareScratchFileInfo(for resourceUrl: URL) -> ScratchFileInfo? {
let directory = scratchFileDirectory(for: resourceUrl)
let scratchFileUrl = directory.appendingPathComponent("scratch", isDirectory: false)
let metaDataUrl = directory.appendingPathComponent("metadata.xml", isDirectory: false)
guard FileManager.default.createDirectoryAt(directory) else {return nil}
if !FileManager.default.fileExists(atPath: scratchFileUrl.path) {
FileManager.default.createFile(atPath: scratchFileUrl.path, contents: nil)
}
guard let fileHandle = SODSwiftableFileHandle(url: scratchFileUrl) else {return nil}
let (ranges, cacheInfo): ([ByteRange], ScratchFileInfo.CacheInfo)
if let (r,c) = FileManager.default.readRanges(at: metaDataUrl) {
(ranges, cacheInfo) = (r, c)
} else {
(ranges, cacheInfo) = ([], .none)
}
SodesLog("Prepared info using directory:\n\(directory)\ncacheInfo: \(cacheInfo)")
return ScratchFileInfo(
resourceUrl: resourceUrl,
directory: directory,
scratchFileUrl: scratchFileUrl,
metaDataUrl: metaDataUrl,
fileHandle: fileHandle,
cacheInfo: cacheInfo,
loadedByteRanges: ranges
)
}
/// Closes the file handle and removes the scratch file subdirectory.
func unprepare(_ info: ScratchFileInfo) {
info.fileHandle.closeFile()
_ = FileManager.default.removeDirectory(info.directory)
}
/// Removes the scratch file subdirectory for `resourceUrl`, if any.
func removeFiles(for resourceUrl: URL) {
let directory = scratchFileDirectory(for: resourceUrl)
_ = FileManager.default.removeDirectory(directory)
}
/// Updates the loaded byte ranges for the current scratch file info. This
/// is done by combining all contiguous/overlapping ranges. This also saves
/// the result to disk using `throttle`.
func updateLoadedByteRanges(additionalRange: ByteRange) {
guard let info = scratchFileInfo else {return}
info.loadedByteRanges.append(additionalRange)
info.loadedByteRanges = combine(info.loadedByteRanges)
saveUpdatedScratchFileMetaData()
}
/// Convenience method for saving the current scratch file metadata.
///
/// - parameter immediately: Forces the throttle to process the save now.
/// Passing `false` will use the default throttling mechanism.
func saveUpdatedScratchFileMetaData(immediately: Bool = false) {
guard let currentUrl = currentRequest?.resourceUrl else {return}
guard let info = scratchFileInfo else {return}
byteRangeThrottle.enqueue(immediately: immediately) { [weak self] in
guard let this = self else {return}
guard currentUrl == this.currentRequest?.resourceUrl else {return}
guard let delayedInfo = this.scratchFileInfo else {return}
let combinedRanges = combine(info.loadedByteRanges)
_ = FileManager.default.save(
byteRanges: combinedRanges,
cacheInfo: info.cacheInfo,
to: delayedInfo.metaDataUrl
)
this.delegate?.resourceLoaderDelegate(this, didUpdateLoadedByteRanges: combinedRanges)
}
}
func finish(_ loadingRequest: AVAssetResourceLoadingRequest, with error: Error?) {
self.errorStatus = .error(error)
loadingRequest.finishLoading(with: error as? NSError)
DispatchQueue.main.async {
if case .error(_) = self.errorStatus {
self.delegate?.resourceLoaderDelegate(self, didEncounter: error)
}
}
}
}
///-----------------------------------------------------------------------------
/// ResourceLoaderDelegate: DataRequestLoaderDelegate
///-----------------------------------------------------------------------------
extension ResourceLoaderDelegate: DataRequestLoaderDelegate {
/// Updates the loaded byte ranges for the scratch file info, and appends
/// the data to the current data request. This method will only be called
/// after `data` has already been successfully written to the scratch file.
func dataRequestLoader(_ loader: DataRequestLoader, didReceive data: Data, forSubrange subrange: ByteRange) {
guard let request = currentRequest as? DataRequest else {return}
guard loader === request.loader else {return}
updateLoadedByteRanges(additionalRange: subrange)
request.dataRequest.respond(with: data)
}
/// Called with the DataRequestLoader has finished all subrequests.
func dataRequestLoaderDidFinish(_ loader: DataRequestLoader) {
guard let request = currentRequest as? DataRequest else {return}
guard loader === request.loader else {return}
request.loadingRequest.finishLoading()
}
/// Called when the DataRequestLoader encountered an error. It will not
/// proceed with pending subrequests if it encounters an error while
/// handling a given subrequest.
func dataRequestLoader(_ loader: DataRequestLoader, didFailWithError error: Error?) {
guard let request = currentRequest as? DataRequest else {return}
guard loader === request.loader else {return}
finish(request.loadingRequest, with: error)
}
}
///-----------------------------------------------------------------------------
/// UserDefaults: Convenience Methods
///-----------------------------------------------------------------------------
fileprivate let mostRecentResourceUrlKey = "com.sodesaudio.ResourceLoaderDelegate.mostRecentResourceUrl"
fileprivate extension UserDefaults {
/// Stores the URL for the most-recently used audio source.
var mostRecentResourceUrl: URL? {
get {
if let string = self.string(forKey: mostRecentResourceUrlKey) {
return URL(string: string)
} else {
return nil
}
}
set { set(newValue?.absoluteString, forKey: mostRecentResourceUrlKey) }
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/04160-swift-sourcemanager-getmessage.swift | 11 | 343 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum b {
protocol a {
class a {
{
enum b { func a
return "[1]]
func b: B<T {
class b
let f = compose(x: P {
init<h: b : b> {
{
struct d<1 {
return "[1)
class
case c,
class
c
| mit |
oneCup/MyWeiBo | MyWeiBoo/MyWeiBoo/AppDelegate.swift | 1 | 4768 | //
// AppDelegate.swift
// MyWeiBoo
//
// Created by 李永方 on 15/10/8.
// Copyright © 2015年 李永方. All rights reserved.
//
import UIKit
let YFRootViewControollerSwithNotifacation = "YFRootViewControollerSwithNotifacation"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
SQLiteManager.sharedManager
print(NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist"))
//注册一个通知中心
NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: YFRootViewControollerSwithNotifacation, object: nil)
// print(YFUserAcount.sharedAcount)
//设置外观对象,一旦设置全局共享,越早设置越好
setApperance()
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = defultViewController()
window?.makeKeyAndVisible()
return true
}
//程序结束才会被只执行,不写不会影响程序的执行,因为通知也是一个单例
deinit {
//注销一个通知 - 知识一个习惯
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/// 切换控制器(通过通知实现)
func switchViewController(n:NSNotification) {
print("切换控制器\(n)")
//判断是否为true
let mainVC = n.object as! Bool
print(mainVC)
window?.rootViewController = mainVC ? YFMainController() : YFWelcomViewController()
}
/// 返回默认的控制器
private func defultViewController() -> UIViewController {
//1.判断用户,没有登录则进入主界面
if !YFUserAcount.userLogin {
return YFMainController()
}
//2.判断是否有更新版本,有,则进入新特性界面,没有则进入欢迎界面
return isUpDateVersion() ? YFNewFutureController() : YFWelcomViewController()
}
/// 判断版本号
func isUpDateVersion()->Bool {
//1.获取软件的版本号
let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
//2.获取沙盒文件中的版本号
//2.1设置软件版本的key
let sandBoxVersionkey = "sandBoxVersionkey"
//2.2 从沙盒中获取版本
let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandBoxVersionkey)
//2.3将版本存放在沙盒中
NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandBoxVersionkey)
//3.返回比较结果
return currentVersion > sandBoxVersion
}
//设置外观对象
func setApperance() {
//获取外观单例对象并设置代理
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
}
//MAEK:清除数据库缓存,在用户推出后台会清理缓存
func applicationDidEnterBackground(application: UIApplication) {
YFStatusDAL.clearDateCache()
}
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 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 |
hollance/swift-algorithm-club | LRU Cache/LRUCache.playground/Contents.swift | 3 | 328 | let cache = LRUCache<String>(2)
cache.set("a", val: 1)
cache.set("b", val: 2)
cache.get("a") // returns 1
cache.set("c", val: 3) // evicts key "b"
cache.get("b") // returns nil (not found)
cache.set("d", val: 4) // evicts key "a"
cache.get("a") // returns nil (not found)
cache.get("c") // returns 3
cache.get("d") // returns 4
| mit |
yq616775291/DiliDili-Fun | Pods/Kingfisher/Sources/ThreadHelper.swift | 2 | 1833 | //
// ThreadHelper.swift
// Kingfisher
//
// Created by Wei Wang on 15/10/9.
//
// Copyright (c) 2016 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
func dispatch_async_safely_to_main_queue(block: ()->()) {
dispatch_async_safely_to_queue(dispatch_get_main_queue(), block)
}
// This methd will dispatch the `block` to a specified `queue`.
// If the `queue` is the main queue, and current thread is main thread, the block
// will be invoked immediately instead of being dispatched.
func dispatch_async_safely_to_queue(queue: dispatch_queue_t, _ block: ()->()) {
if queue === dispatch_get_main_queue() && NSThread.isMainThread() {
block()
} else {
dispatch_async(queue) {
block()
}
}
}
| mit |
EstefaniaGilVaquero/ciceIOS | App_VolksWagenFinal-/App_VolksWagenFinal-/VWConcesionarioTableViewController.swift | 1 | 3393 | //
// VWConcesionarioTableViewController.swift
// App_VolksWagenFinal_CICE
//
// Created by Formador on 3/10/16.
// Copyright © 2016 icologic. All rights reserved.
//
import UIKit
import Kingfisher
class VWConcesionarioTableViewController: UITableViewController {
//MARK: - VARIABLES LOCALES GLOBALES
var refreshTVC = UIRefreshControl()
var arrayConcesionarios = [VWConcesionariosModel]()
override func viewDidLoad() {
super.viewDidLoad()
refreshTVC.backgroundColor = UIColor(red: 255/255, green: 128/255, blue: 0/255, alpha: 1.0)
refreshTVC.attributedTitle = NSAttributedString(string: CONSTANTES.TEXTO_RECARGA_TABLA)
refreshTVC.addTarget(self, action: Selector(refreshFunction(tableView, endRefreshTVC: refreshTVC)), forControlEvents: .EditingDidEnd)
tableView.addSubview(refreshTVC)
//Aqui alimentamos nuestro array
arrayConcesionarios = VWAPIManager.sharedInstance.getConcesionarioParse()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return arrayConcesionarios.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! VWConcesionarioCustomCell
let concesionarioData = arrayConcesionarios[indexPath.row]
cell.myNombreConcesionario.text = concesionarioData.Nombre
cell.myDireccionConcesionario.text = concesionarioData.Ubicacion
cell.myWebConcesionario.text = concesionarioData.Provincia_Nombre
cell.hacerLlamada.setTitle("\(concesionarioData.telefono!)", forState: .Normal)
cell.hacerLlamada.tag = indexPath.row
cell.hacerLlamada.addTarget(self, action: #selector(VWConcesionarioTableViewController.muestraTelefono(_:)), forControlEvents: .TouchUpInside)
cell.myImagenConcesionario.kf_setImageWithURL(NSURL(string: getImagePath(concesionarioData.Imagen!)))
return cell
}
@IBAction func muestraTelefono(sender : UIButton){
let concesionarioData = arrayConcesionarios[sender.tag].telefono
let url = NSURL(string: "tel://\(concesionarioData!)")
UIApplication.sharedApplication().openURL(url!)
print("estoy haciendo una llamada")
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let detalleConcesionarioVC = self.storyboard?.instantiateViewControllerWithIdentifier("detalleConcesionarios") as! VWDetalleConcesionarioViewController
detalleConcesionarioVC.arrayConcesionariosData = arrayConcesionarios[indexPath.row]
navigationController?.pushViewController(detalleConcesionarioVC, animated: true)
}
}
| apache-2.0 |
ChristianKienle/highway | Tests/FSKitTests/LocalFileSystemTests.swift | 1 | 4773 | import XCTest
import FileSystem
final class LocalFileSystemTests: XCTestCase {
private var fs = AnchoredFileSystem(underlyingFileSystem: InMemoryFileSystem(), achnoredAt: .root)
// MARK: - FileSystemTest
override func setUp() {
super.setUp()
// Since the local file system writes directly on disk we have to make reroot
// it. Thanks Swift Package Manager for the idea! Great artitst steal - u know? :)
let fm = FileManager()
let tempDir = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
// lets make it unique
let uniqueDir = tempDir.appendingPathComponent(UUID().uuidString, isDirectory: true)
XCTAssertNoThrow(try fm.createDirectory(at: uniqueDir, withIntermediateDirectories: true, attributes: nil))
print("Created uniqure directory for LocalFileSystemTests at:")
print(uniqueDir.path)
// Create the local FS + Reroot it
let localFS = LocalFileSystem()
let anchoredFS = AnchoredFileSystem(underlyingFileSystem: localFS, achnoredAt: Absolute(uniqueDir))
fs = anchoredFS
}
override func tearDown() {
// cleanup the mess - no we don't. The files we create are so small - let's not risk deleting / by accident...
super.tearDown()
}
// MARK: Tests
func testEmpty() {
let url = Absolute("/Users/test")
let file = fs.file(at: url)
_assertThrowsFileSystemError(try file.data()) { error in
XCTAssertTrue(error.isDoesNotExistError)
}
}
func testSingleFileExistence() {
let url = Absolute("/simple_file")
let input = "hello world"
XCTAssertNoThrow(try fs.writeString(input, to: url))
XCTAssertEqual(try fs.file(at: url).string(), input)
}
func testFileInSubdirectoryCanBeFound() {
XCTAssertNoThrow(try fs.createDirectory(at: Absolute("/folderA")))
XCTAssertNoThrow(try fs.writeString("Hello World", to: Absolute("/folderA/simple_file")))
XCTAssertEqual(try fs.file(at: Absolute("/folderA/simple_file")).string(), "Hello World")
}
func testComplextExistenceScenarios() {
XCTAssertNoThrow(try fs.createDirectory(at: Absolute("/d1/d1-1")))
XCTAssertNoThrow(try fs.writeString("file d1-1-1", to: Absolute("/d1/d1-1/f1-1-1")))
XCTAssertEqual(try fs.file(at: Absolute("/d1/d1-1/f1-1-1")).string(), "file d1-1-1")
XCTAssertNoThrow(try fs.writeString("file d1-1-2", to: Absolute("/d1/d1-1/f1-1-2")))
XCTAssertEqual(try fs.file(at: Absolute("/d1/d1-1/f1-1-2")).string(), "file d1-1-2")
XCTAssertEqual(try fs.file(at: Absolute("/d1/d1-1/f1-1-1")).string(), "file d1-1-1")
}
func testWriteData() {
let fileURL = Absolute("/test.txt")
XCTAssertThrowsError(try fs.writeString("x", to: Absolute("/users/cmk/test.txt")))
XCTAssertNoThrow(try fs.writeString("hello", to: fileURL))
XCTAssertEqual(try fs.file(at: fileURL).string(), "hello")
}
func testCreateDirectory() {
let usersDir = Absolute("/users")
let userFile = usersDir.appending("chris.txt")
XCTAssertNoThrow(try fs.createDirectory(at: usersDir))
XCTAssertNoThrow(try fs.writeString("ich", to: userFile))
let users = fs.directory(at: usersDir)
XCTAssertEqual(try users.file(named: "chris.txt").string(), "ich")
XCTAssertNoThrow(try fs.createDirectory(at: Absolute("/l1/l2")))
XCTAssertNoThrow(try fs.writeString("jsonbla", to: Absolute("/l1/l2/file.json")))
XCTAssertEqual(try fs.file(at: Absolute("/l1/l2/file.json")).string(), "jsonbla")
}
func testCreateDirectory_with_trailing_slash() {
XCTAssertNoThrow(try fs.createDirectory(at: Absolute("/users/")), "")
XCTAssertNoThrow(try fs.writeString("ich", to: Absolute("/users/test/")))
XCTAssertEqual(try fs.directory(at: Absolute("/users")).file(named: "test").string(), "ich")
}
func testDelete() {
XCTAssertNoThrow(try fs.createDirectory(at: Absolute("/l1/l2")), "")
XCTAssertNoThrow(try fs.writeString("content", to: Absolute("/l1/l2/bla.txt")), "")
XCTAssertEqual(try fs.file(at: Absolute("/l1/l2/bla.txt")).string(), "content", "")
XCTAssertNoThrow(try fs.deleteItem(at: Absolute("/l1/l2/bla.txt")))
_assertThrowsFileSystemError(try fs.file(at: Absolute("/l1/l2/bla.txt")).string()) { error in
XCTAssertTrue(error.isDoesNotExistError)
print(error)
let failure = !error.isDoesNotExistError
if failure {
print("doh")
}
}
}
}
| mit |
jsslai/Action | Carthage/Checkouts/RxSwift/Rx.playground/Pages/Mathematical_and_Aggregate_Operators.xcplaygroundpage/Contents.swift | 3 | 2598 | /*:
> # IMPORTANT: To use **Rx.playground**:
1. Open **Rx.xcworkspace**.
1. Build the **RxSwift-OSX** scheme (**Product** → **Build**).
1. Open **Rx** playground in the **Project navigator**.
1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**).
----
[Previous](@previous) - [Table of Contents](Table_of_Contents)
*/
import RxSwift
/*:
# Mathematical and Aggregate Operators
Operators that operate on the entire sequence of items emitted by an `Observable`.
## `toArray`
Converts an `Observable` sequence into an array, emits that array as a new single-element `Observable` sequence, and then terminates. [More info](http://reactivex.io/documentation/operators/to.html)

*/
example("toArray") {
let disposeBag = DisposeBag()
Observable.range(start: 1, count: 10)
.toArray()
.subscribe { print($0) }
.addDisposableTo(disposeBag)
}
/*:
----
## `reduce`
Begins with an initial seed value, and then applies an accumulator closure to all elements emitted by an `Observable` sequence, and returns the aggregate result as a single-element `Observable` sequence. [More info](http://reactivex.io/documentation/operators/reduce.html)

*/
example("reduce") {
let disposeBag = DisposeBag()
Observable.of(10, 100, 1000)
.reduce(1, accumulator: +)
.subscribe(onNext: { print($0) })
.addDisposableTo(disposeBag)
}
/*:
----
## `concat`
Joins elements from inner `Observable` sequences of an `Observable` sequence in a sequential manner, waiting for each sequence to terminate successfully before emitting elements from the next sequence. [More info](http://reactivex.io/documentation/operators/concat.html)

*/
example("concat") {
let disposeBag = DisposeBag()
let subject1 = BehaviorSubject(value: "🍎")
let subject2 = BehaviorSubject(value: "🐶")
let variable = Variable(subject1)
variable.asObservable()
.concat()
.subscribe { print($0) }
.addDisposableTo(disposeBag)
subject1.onNext("🍐")
subject1.onNext("🍊")
variable.value = subject2
subject2.onNext("I would be ignored")
subject2.onNext("🐱")
subject1.onCompleted()
subject2.onNext("🐭")
}
//: [Next](@next) - [Table of Contents](Table_of_Contents)
| mit |
apple/swift | validation-test/compiler_crashers_fixed/25489-swift-valuedecl-getinterfacetype.swift | 65 | 441 | // 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
// RUN: not %target-swift-frontend %s -typecheck
func a}class a
enum Sh{
class d:a}struct n
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/00562-swift-typechecker-typecheckexpression.swift | 1 | 431 | // 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
class A {
private let a = [Void{
| apache-2.0 |
akshayg13/Game | Games/ImageModel.swift | 1 | 1949 | //
// ImageModel.swift
// Games
//
// Created by Appinventiv on 21/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import Foundation
import SwiftyJSON
struct ImageModel {
let id : String!
var isFav = false
var comments = 0
var downloads = 0
var favorites = 0
var likes = 0
var views = 0
var pageURL : String = ""
var userImageURL : String = ""
var webformatURL : String = ""
var previewURL : String = ""
init(withJSON json: JSON) {
self.id = json["id"].stringValue
self.comments = json["comments"].intValue
self.downloads = json["downloads"].intValue
self.favorites = json["favorites"].intValue
self.likes = json["likes"].intValue
self.views = json["views"].intValue
self.pageURL = json["pageURL"].stringValue
self.userImageURL = json["userImageURL"].stringValue
self.webformatURL = json["webformatURL"].stringValue
self.previewURL = json["previewURL"].stringValue
}
}
//{
// "imageHeight" : 3122,
// "user" : "jarmoluk",
// "previewWidth" : 150,
// "imageWidth" : 4714,
// "likes" : 29,
// "previewHeight" : 99,
// "webformatHeight" : 423,
// "tags" : "gokart, action, umpteen",
// "type" : "photo",
// "downloads" : 2211,
// "webformatURL" : "https:\/\/pixabay.com\/get\/e835b90f2cfd033ed95c4518b7484096eb7fe1d404b0154992f6c77da5e9b5_640.jpg",
// "views" : 5857,
// "id" : 1080492,
// "favorites" : 28,
// "webformatWidth" : 640,
// "pageURL" : "https:\/\/pixabay.com\/en\/gokart-action-umpteen-motor-speed-1080492\/",
// "previewURL" : "https:\/\/cdn.pixabay.com\/photo\/2015\/12\/07\/10\/24\/gokart-1080492_150.jpg",
// "comments" : 4,
// "user_id" : 143740,
// "userImageURL" : "https:\/\/cdn.pixabay.com\/user\/2015\/04\/13\/12-35-01-432_250x250.jpg"
//}
| mit |
cnoon/swift-compiler-crashes | fixed/25189-swift-expr-walk.swift | 7 | 228 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B{struct b{let a=}}protocol a{{{{{}}}}typealias d:d
| mit |
laszlokorte/reform-swift | ReformCore/ReformCore/DrawingMode.swift | 1 | 216 | //
// DrawingMode.swift
// ReformCore
//
// Created by Laszlo Korte on 13.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
public enum DrawingMode {
case draw
case mask
case guide
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/19713-getselftypeforcontainer.swift | 11 | 220 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol P {
protocol A : a {
func a
func <
}
}
S<
| mit |
avaidyam/Parrot | MochaUI/CGSSpace.swift | 1 | 2458 | import AppKit
import Mocha
/// Small Spaces API wrapper.
public final class CGSSpace {
private let identifier: CGSSpaceID
public var windows: Set<NSWindow> = [] {
didSet {
let remove = oldValue.subtracting(self.windows)
let add = self.windows.subtracting(oldValue)
CGSRemoveWindowsFromSpaces(_CGSDefaultConnection(),
remove.map { $0.windowNumber } as NSArray,
[self.identifier])
CGSAddWindowsToSpaces(_CGSDefaultConnection(),
add.map { $0.windowNumber } as NSArray,
[self.identifier])
}
}
/// Initialized `CGSSpace`s *MUST* be de-initialized upon app exit!
public init(level: Int = 0) {
let flag = 0x1 // this value MUST be 1, otherwise, Finder decides to draw desktop icons
self.identifier = CGSSpaceCreate(_CGSDefaultConnection(), flag, nil)
CGSSpaceSetAbsoluteLevel(_CGSDefaultConnection(), self.identifier, level/*400=facetime?*/)
CGSShowSpaces(_CGSDefaultConnection(), [self.identifier])
}
deinit {
CGSHideSpaces(_CGSDefaultConnection(), [self.identifier])
CGSSpaceDestroy(_CGSDefaultConnection(), self.identifier)
}
}
// CGSSpace stuff:
fileprivate typealias CGSConnectionID = UInt
fileprivate typealias CGSSpaceID = UInt64
@_silgen_name("_CGSDefaultConnection")
fileprivate func _CGSDefaultConnection() -> CGSConnectionID
@_silgen_name("CGSSpaceCreate")
fileprivate func CGSSpaceCreate(_ cid: CGSConnectionID, _ unknown: Int, _ options: NSDictionary?) -> CGSSpaceID
@_silgen_name("CGSSpaceDestroy")
fileprivate func CGSSpaceDestroy(_ cid: CGSConnectionID, _ space: CGSSpaceID)
@_silgen_name("CGSSpaceSetAbsoluteLevel")
fileprivate func CGSSpaceSetAbsoluteLevel(_ cid: CGSConnectionID, _ space: CGSSpaceID, _ level: Int)
@_silgen_name("CGSAddWindowsToSpaces")
fileprivate func CGSAddWindowsToSpaces(_ cid: CGSConnectionID, _ windows: NSArray, _ spaces: NSArray)
@_silgen_name("CGSRemoveWindowsFromSpaces")
fileprivate func CGSRemoveWindowsFromSpaces(_ cid: CGSConnectionID, _ windows: NSArray, _ spaces: NSArray)
@_silgen_name("CGSHideSpaces")
fileprivate func CGSHideSpaces(_ cid: CGSConnectionID, _ spaces: NSArray)
@_silgen_name("CGSShowSpaces")
fileprivate func CGSShowSpaces(_ cid: CGSConnectionID, _ spaces: NSArray)
| mpl-2.0 |
valentinknabel/StateMachine | Sources/Transition.swift | 1 | 2270 | //
// Transition.swift
// StateMachine
//
// Created by Valentin Knabel on 19.02.15.
// Copyright (c) 2015 Valentin Knabel. All rights reserved.
//
/**
The Transition class represents a transition from a given state to a targeted state.
There are three types of transitions:
1. Absolute Transitions have a source and a target state set.
2. Relative Transitions have only one state set.
3. Nil Transitions have none states set and will be ignored.
*/
public struct Transition<T: Hashable>: Hashable, CustomStringConvertible {
/// Nil transitions will be ignored.
public static var nilTransition: Transition<T> {
return Transition<T>(from: nil, to: nil)
}
/// The source state.
public var from: T?
/// The targeted state.
public var to: T?
/**
Constructs an absolute, relative or nil transition.
- parameter from: The source state.
- parameter to: The target state.
*/
public init(from: T?, to: T?) {
self.from = from
self.to = to
}
/**
All more general transitions include itself except the nil transition.
- returns: All general transitions.
- Generals of an absolute transition is itself and relative transitions.
- Generals of a relative transition is only itself.
- Nil transitions have no generals.
*/
public var generalTransitions: Set<Transition> {
var generals = Set<Transition>([self, Transition(from: from, to: nil), Transition(from: nil, to: to)])
generals.remove(.nilTransition)
return generals
}
public var description: String {
let f = from != nil ? String(describing: from!) : "any"
let t = to != nil ? String(describing: to!) : "any"
return "\(f) -> \(t)"
}
#if swift(>=4.2)
// Synthesized by compiler
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(from)
hasher.combine(to)
}
#else
/// :nodoc:
public var hashValue: Int {
return (from?.hashValue ?? 0) + (to?.hashValue ?? 0)
}
#endif
}
/// :nodoc:
public func == <T>(lhs: Transition<T>, rhs: Transition<T>) -> Bool {
return lhs.from == rhs.from && lhs.to == rhs.to
}
| mit |
1457792186/JWSwift | 熊猫TV2/XMTV/Classes/Entertainment/Controller/LovelyPetsVC.swift | 2 | 514 | //
// LovelyPetsVC.swift
// XMTV
//
// Created by Mac on 2017/1/11.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
class LovelyPetsVC: BaseEntertainmentVC {
fileprivate lazy var lovelyVM: LovelyPetsVM = LovelyPetsVM()
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadData() {
baseVM = self.lovelyVM
lovelyVM.requestData {
self.collectionView.reloadData()
self.loadDataFinished()
}
}
}
| apache-2.0 |
steelwheels/Coconut | CoconutData/Source/Value/CNValuePath.swift | 1 | 8580 | /**
* @file CNValuePath.swift
* @brief Define CNValuePath class
* @par Copyright
* Copyright (C) 2022 Steel Wheels Project
*/
import Foundation
public class CNValuePath
{
public enum Element {
case member(String) // member name
case index(Int) // array index to select array element
case keyAndValue(String, CNValue) // key and it's value to select array element
static func isSame(source0 src0: Element, source1 src1: Element) -> Bool {
let result: Bool
switch src0 {
case .member(let memb0):
switch src1 {
case .member(let memb1):
result = memb0 == memb1
case .index(_), .keyAndValue(_, _):
result = false
}
case .index(let idx0):
switch src1 {
case .member(_), .keyAndValue(_, _):
result = false
case .index(let idx1):
result = idx0 == idx1
}
case .keyAndValue(let key0, let val0):
switch src1 {
case .member(_), .index(_):
result = false
case .keyAndValue(let key1, let val1):
if key0 == key1 {
switch CNCompareValue(nativeValue0: val0, nativeValue1: val1){
case .orderedAscending, .orderedDescending:
result = false
case .orderedSame:
result = true
}
} else {
result = false
}
}
}
return result
}
}
private struct Elements {
var firstIdent: String?
var elements: Array<Element>
public init(firstIdentifier fidt: String?, elements elms: Array<Element>){
firstIdent = fidt
elements = elms
}
}
private var mIdentifier: String?
private var mElements: Array<Element>
private var mExpression: String
public var identifier: String? { get {
return mIdentifier
}}
public var elements: Array<Element> { get {
return mElements
}}
public var expression: String { get {
return mExpression
}}
public init(identifier ident: String?, elements elms: Array<Element>){
mIdentifier = ident
mElements = elms
mExpression = CNValuePath.toExpression(identifier: ident, elements: elms)
}
public init(identifier ident: String?, member memb: String){
mIdentifier = ident
mElements = [ .member(memb) ]
mExpression = CNValuePath.toExpression(identifier: ident, elements: mElements)
}
public init(path pth: CNValuePath, subPath subs: Array<Element>){
mIdentifier = pth.identifier
mElements = []
for src in pth.elements {
mElements.append(src)
}
for subs in subs {
mElements.append(subs)
}
mExpression = CNValuePath.toExpression(identifier: pth.identifier, elements: mElements)
}
public func isIncluded(in targ: CNValuePath) -> Bool {
let selms = self.mElements
let telms = targ.mElements
if selms.count <= telms.count {
for i in 0..<selms.count {
if !Element.isSame(source0: selms[i], source1: telms[i]) {
return false
}
}
return true
} else {
return false
}
}
public var description: String { get {
var result = ""
var is1st = true
for elm in mElements {
switch elm {
case .member(let str):
if is1st {
is1st = false
} else {
result += "."
}
result += "\(str)"
case .index(let idx):
result += "[\(idx)]"
case .keyAndValue(let key, let val):
result += "[\(key):\(val.description)]"
}
}
return result
}}
public static func toExpression(identifier ident: String?, elements elms: Array<Element>) -> String {
var result: String = ""
var is1st: Bool = true
if let str = ident {
result = "@" + str
is1st = false
}
for elm in elms {
switch elm {
case .member(let str):
if is1st {
is1st = false
} else {
result += "."
}
result += str
case .index(let idx):
result += "[\(idx)]"
case .keyAndValue(let key, let val):
let path: String
let quote = "\""
switch val {
case .stringValue(let str):
path = quote + str + quote
default:
path = quote + val.description + quote
}
result += "[\(key):\(path)]"
}
}
return result
}
public static func pathExpression(string str: String) -> Result<CNValuePath, NSError> {
let conf = CNParserConfig(allowIdentiferHasPeriod: false)
switch CNStringToToken(string: str, config: conf) {
case .ok(let tokens):
let stream = CNTokenStream(source: tokens)
switch pathExpression(stream: stream) {
case .success(let elms):
let path = CNValuePath(identifier: elms.firstIdent, elements: elms.elements)
return .success(path)
case .failure(let err):
return .failure(err)
}
case .error(let err):
return .failure(err)
}
}
private static func pathExpression(stream strm: CNTokenStream) -> Result<Elements, NSError> {
switch pathExpressionIdentifier(stream: strm) {
case .success(let identp):
switch pathExpressionMembers(stream: strm, hasIdentifier: identp != nil) {
case .success(let elms):
return .success(Elements(firstIdentifier: identp, elements: elms))
case .failure(let err):
return .failure(err)
}
case .failure(let err):
return .failure(err)
}
}
private static func pathExpressionIdentifier(stream strm: CNTokenStream) -> Result<String?, NSError> {
if strm.requireSymbol(symbol: "@") {
if let ident = strm.getIdentifier() {
return .success(ident)
} else {
let _ = strm.unget() // unget symbol
CNLog(logLevel: .error, message: "Identifier is required for label", atFunction: #function, inFile: #file)
}
}
return .success(nil)
}
private static func pathExpressionMembers(stream strm: CNTokenStream, hasIdentifier hasident: Bool) -> Result<Array<Element>, NSError> {
var is1st: Bool = !hasident
var result: Array<Element> = []
while !strm.isEmpty() {
/* Parse comma */
if is1st {
is1st = false
} else if !strm.requireSymbol(symbol: ".") {
return .failure(NSError.parseError(message: "Period is expected between members \(near(stream: strm))"))
}
/* Parse member */
guard let member = strm.getIdentifier() else {
return .failure(NSError.parseError(message: "Member for path expression is required \(near(stream: strm))"))
}
result.append(.member(member))
/* Check "[" symbol */
while strm.requireSymbol(symbol: "[") {
switch pathExpressionIndex(stream: strm) {
case .success(let elm):
result.append(elm)
case .failure(let err):
return .failure(err)
}
if !strm.requireSymbol(symbol: "]") {
return .failure(NSError.parseError(message: "']' is expected"))
}
}
}
return .success(result)
}
private static func pathExpressionIndex(stream strm: CNTokenStream) -> Result<Element, NSError> {
if let index = strm.requireUInt() {
return .success(.index(Int(index)))
} else if let ident = strm.requireIdentifier() {
if strm.requireSymbol(symbol: ":") {
switch requireAnyValue(stream: strm) {
case .success(let val):
return .success(.keyAndValue(ident, val))
case .failure(let err):
return .failure(err)
}
} else {
return .failure(NSError.parseError(message: "':' is required between dictionary key and value \(near(stream: strm))"))
}
} else {
return .failure(NSError.parseError(message: "Invalid index \(near(stream: strm))"))
}
}
private static func requireAnyValue(stream strm: CNTokenStream) -> Result<CNValue, NSError> {
if let ival = strm.requireUInt() {
return .success(.numberValue(NSNumber(integerLiteral: Int(ival))))
} else if let sval = strm.requireIdentifier() {
return .success(.stringValue(sval))
} else if let sval = strm.requireString() {
return .success(.stringValue(sval))
} else {
return .failure(NSError.parseError(message: "immediate value is required for value in key-value index"))
}
}
public static func description(of val: Dictionary<String, Array<CNValuePath.Element>>) -> CNText {
let sect = CNTextSection()
sect.header = "{" ; sect.footer = "}"
for (key, elm) in val {
let subsect = CNTextSection()
subsect.header = "\(key): {" ; subsect.footer = "}"
let desc = toExpression(identifier: nil, elements: elm)
let line = CNTextLine(string: desc)
subsect.add(text: line)
sect.add(text: subsect)
}
return sect
}
private static func near(stream strm: CNTokenStream) -> String {
if let token = strm.peek(offset: 0) {
return "near " + token.toString()
} else {
return ""
}
}
public func compare(_ val: CNValuePath) -> ComparisonResult {
let selfstr = self.mExpression
let srcstr = val.mExpression
if selfstr == srcstr {
return .orderedSame
} else if selfstr > srcstr {
return .orderedDescending
} else {
return .orderedAscending
}
}
}
| lgpl-2.1 |
thehung111/ViSearchSwiftSDK | ViSearchSDK/ViSearchSDKTests/ViSearchSDKTests.swift | 3 | 798 | //
// ViSearchSDKTests.swift
// ViSearchSDKTests
//
// Created by Hung on 3/10/16.
// Copyright © 2016 Hung. All rights reserved.
//
import XCTest
@testable import ViSearchSDK
class ViSearchSDKTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// func testPerformanceExample() {
// // This is an example of a performance test case.
// self.measure {
// // Put the code you want to measure the time of here.
// }
// }
}
| mit |
kang77649119/DouYuDemo | DouYuDemo/DouYuDemo/Classes/Home/View/AmuseViewCell.swift | 1 | 1731 | //
// AmuseViewCell.swift
// DouYuDemo
//
// Created by 也许、 on 16/10/19.
// Copyright © 2016年 K. All rights reserved.
//
import UIKit
private let amuseViewGameCellId = "amuseViewCellId"
class AmuseViewCell: UICollectionViewCell {
@IBOutlet weak var collectionView: UICollectionView!
var anchorGroups:[AnchorGroup]? {
didSet {
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "GameViewCell", bundle: nil), forCellWithReuseIdentifier: amuseViewGameCellId)
collectionView.dataSource = self
}
override func layoutSubviews() {
super.layoutSubviews()
let itemW = collectionView.bounds.width / CGFloat(4)
let itemH = collectionView.bounds.height / CGFloat(2)
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.itemSize = CGSize(width: itemW, height: itemH)
}
}
extension AmuseViewCell : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return anchorGroups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: amuseViewGameCellId, for: indexPath) as! GameViewCell
cell.anchorGroup = self.anchorGroups![indexPath.item]
return cell
}
}
| mit |
kousun12/RxSwift | RxExample/RxExample/Examples/WikipediaImageSearch/Views/CollectionViewImageCell.swift | 6 | 958 | //
// CollectionViewImageCell.swift
// Example
//
// Created by Krunoslav Zaher on 4/4/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
public class CollectionViewImageCell: UICollectionViewCell {
@IBOutlet var imageOutlet: UIImageView!
var disposeBag: DisposeBag!
var downloadableImage: Observable<DownloadableImage>?{
didSet{
let disposeBag = DisposeBag()
self.downloadableImage?
.asDriver(onErrorJustReturn: DownloadableImage.OfflinePlaceholder)
.drive(imageOutlet.rxex_downloadableImageAnimated(kCATransitionFade))
.addDisposableTo(disposeBag)
self.disposeBag = disposeBag
}
}
override public func prepareForReuse() {
super.prepareForReuse()
disposeBag = nil
}
deinit {
}
} | mit |
bengottlieb/ios | FiveCalls/FiveCalls/RemoteImageView.swift | 3 | 3119 | //
// RemoteImageView.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/4/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
typealias RemoteImageCallback = (UIImage) -> Void
@IBDesignable
class RemoteImageView : UIImageView {
@IBInspectable
var defaultImage: UIImage?
lazy var session: URLSession = {
let session = URLSession(configuration: URLSessionConfiguration.default)
return session
}()
var currentTask: URLSessionDataTask?
private var currentImageURL: URL?
func setRemoteImage(url: URL) {
setRemoteImage(url: url) { [weak self] image in
self?.image = image
}
}
func setRemoteImage(url: URL, completion: @escaping RemoteImageCallback) {
setRemoteImage(preferred: defaultImage, url: url, completion: completion)
}
func setRemoteImage(preferred preferredImage: UIImage?, url: URL, completion: @escaping RemoteImageCallback) {
if let cachedImage = ImageCache.shared.image(forKey: url) {
image = cachedImage
return
}
image = preferredImage
guard preferredImage == nil || preferredImage == defaultImage else {
return completion(preferredImage!)
}
currentTask?.cancel()
currentTask = session.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in
guard let strongSelf = self,
strongSelf.currentTask!.state != .canceling else {
return
}
if let e = error as NSError? {
if e.domain == NSURLErrorDomain && e.code == NSURLErrorCancelled {
// ignore cancellation errors
} else {
print("Error loading image: \(e.localizedDescription)")
}
} else {
guard let http = response as? HTTPURLResponse else { return }
if http.statusCode == 200 {
if let data = data, let image = UIImage(data: data) {
strongSelf.currentImageURL = url
ImageCache.shared.set(image: image, forKey: url)
if strongSelf.currentImageURL == url {
DispatchQueue.main.async {
completion(image)
}
}
}
} else {
print("HTTP \(http.statusCode) received for \(url)")
}
}
})
currentTask?.resume()
}
}
private struct ImageCache {
static var shared = ImageCache()
private let cache: NSCache<NSString, UIImage>
init() {
cache = NSCache()
}
func image(forKey key:URL) -> UIImage? {
return cache.object(forKey: key.absoluteString as NSString)
}
func set(image: UIImage, forKey key: URL) {
cache.setObject(image, forKey: key.absoluteString as NSString)
}
}
| mit |
rc2server/appserverSwift | Sources/servermodel/Variable+JSON.swift | 1 | 7324 | //
// Variable+JSON.swift
//
// Copyright ©2017 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
import Rc2Model
import Freddy
import MJLLogger
struct VariableError: Error {
let reason: String
let nestedError: Error?
init(_ reason: String, error: Error? = nil) {
self.reason = reason
self.nestedError = error
}
}
extension Variable {
static let rDateFormatter: ISO8601DateFormatter = { var f = ISO8601DateFormatter(); f.formatOptions = [.withFullDate, .withDashSeparatorInDate]; return f}()
/// Parses a legacy compute json dictionary into a Variable
public static func makeFromLegacy(json: JSON) throws -> Variable {
do {
let vname = try json.getString(at: "name")
let className = try json.getString(at: "class")
let summary = try json.getString(at: "summary", or: "")
let vlen = try json.getInt(at: "length", or: 1)
var vtype: VariableType
if try json.getBool(at: "primitive", or: false) {
vtype = .primitive(try makePrimitive(json: json))
} else if try json.getBool(at: "s4", or: false) {
vtype = .s4Object
} else {
switch className {
case "Date":
do {
guard let vdate = rDateFormatter.date(from: try json.getString(at: "value"))
else { throw VariableError("invalid date value") }
vtype = .date(vdate)
} catch {
throw VariableError("invalid date value", error: error)
}
case "POSIXct", "POSIXlt":
do {
vtype = .dateTime(Date(timeIntervalSince1970: try json.getDouble(at: "value")))
} catch {
throw VariableError("invalid date value", error: error)
}
case "function":
do {
vtype = .function(try json.getString(at: "body"))
} catch {
throw VariableError("function w/o body", error: error)
}
case "factor", "ordered factor":
do {
vtype = .factor(values: try json.decodedArray(at: "value"), levelNames: try json.decodedArray(at: "levels", or: []))
} catch {
throw VariableError("factor missing values", error: error)
}
case "matrix":
vtype = .matrix(try parseMatrix(json: json))
case "environment":
vtype = .environment // FIXME: need to parse key/value pairs sent as value
case "data.frame":
vtype = .dataFrame(try parseDataFrame(json: json))
case "list":
vtype = .list([]) // FIXME: need to parse
default:
//make sure it is an object we can handle
guard try json.getBool(at: "generic", or: false) else { throw VariableError("unknown parsing error \(className)") }
var attrs = [String: Variable]()
let rawValues = try json.getDictionary(at: "value")
for aName in try json.decodedArray(at: "names", type: String.self) {
if let attrJson = rawValues[aName], let value = try? makeFromLegacy(json: attrJson) {
attrs[aName] = value
}
}
vtype = .generic(attrs)
}
}
return Variable(name: vname, length: vlen, type: vtype, className: className, summary: summary)
} catch let verror as VariableError {
throw verror
} catch {
Log.warn("error parsing legacy variable: \(error)")
throw VariableError("error parsing legacy variable", error: error)
}
}
static func parseDataFrame(json: JSON) throws -> DataFrameData {
do {
let numCols = try json.getInt(at: "ncol")
let numRows = try json.getInt(at: "nrow")
let rowNames: [String]? = try json.decodedArray(at: "row.names", alongPath: .missingKeyBecomesNil)
let rawColumns = try json.getArray(at: "columns")
let columns = try rawColumns.map { (colJson: JSON) -> DataFrameData.Column in
let colName = try colJson.getString(at: "name")
return DataFrameData.Column(name: colName, value: try makePrimitive(json: colJson, valueKey: "values"))
}
guard columns.count == numCols
else { throw VariableError("data does not match num cols/rows") }
return DataFrameData(columns: columns, rowCount: numRows, rowNames: rowNames)
} catch let verror as VariableError {
throw verror
} catch {
throw VariableError("error parsing data frame", error: error)
}
}
static func parseMatrix(json: JSON) throws -> MatrixData {
do {
let numCols = try json.getInt(at: "ncol")
let numRows = try json.getInt(at: "nrow")
let rowNames: [String]? = try? json.decodedArray(at: "dimnames", 0)
let colNames: [String]? = try? json.decodedArray(at: "dimnames", 1)
guard rowNames == nil || rowNames!.count == numRows
else { throw VariableError("row names do not match length") }
guard colNames == nil || colNames!.count == numCols
else { throw VariableError("col names do not match length") }
let values = try makePrimitive(json: json)
return MatrixData(value: values, rowCount: numRows, colCount: numCols, colNames: colNames, rowNames: rowNames)
} catch let verror as VariableError {
throw verror
} catch {
throw VariableError("error parsing matrix data", error: error)
}
}
// parses array of doubles, "Inf", "-Inf", and "NaN" into [Double]
static func parseDoubles(json: [JSON]) throws -> [Double?] {
return try json.map { (aVal) in
switch aVal {
case .double(let dval):
return dval
case .int(let ival):
return Double(ival)
case .string(let sval):
switch sval {
case "Inf": return Double.infinity
case "-Inf": return -Double.infinity
case "NaN": return Double.nan
default: throw VariableError("invalid string as double value \(aVal)")
}
case .null:
return nil
default:
throw VariableError("invalid value type in double array")
}
}
}
// returns a PrimitiveValue based on the contents of json
static func makePrimitive(json: JSON, valueKey: String = "value") throws -> PrimitiveValue {
guard let ptype = try? json.getString(at: "type")
else { throw VariableError("invalid primitive type") }
guard let rawValues = try json.getArray(at: valueKey, alongPath: .missingKeyBecomesNil)
else { throw VariableError("invalid value") }
var pvalue: PrimitiveValue
switch ptype {
case "n":
pvalue = .null
case "b":
let bval: [Bool?] = try rawValues.map { (aVal: JSON) -> Bool? in
if case .null = aVal { return nil }
if case let .bool(aBool) = aVal { return aBool }
throw VariableError("invalid bool variable \(aVal)")
}
pvalue = .boolean(bval)
case "i":
let ival: [Int?] = try rawValues.map { (aVal: JSON) -> Int? in
if case .null = aVal { return nil }
if case let .int(anInt) = aVal { return anInt }
throw VariableError("invalid int variable \(aVal)")
}
pvalue = .integer(ival)
case "d":
pvalue = .double(try parseDoubles(json: json.getArray(at: valueKey, alongPath: .nullBecomesNil)!))
case "s":
let sval: [String?] = try rawValues.map { (aVal: JSON) -> String? in
if case .null = aVal { return nil }
if case let .string(aStr) = aVal { return aStr }
throw VariableError("invalid string variable \(aVal)")
}
pvalue = .string(sval)
case "c":
let cval: [String?] = try rawValues.map { (aVal: JSON) -> String? in
if case .null = aVal { return nil }
if case let .string(aStr) = aVal { return aStr }
throw VariableError("invalid complex variable \(aVal)")
}
pvalue = .complex(cval)
case "r":
pvalue = .raw
default:
throw VariableError("unknown primitive type: \(ptype)")
}
return pvalue
}
}
| isc |
groschovskiy/lerigos_music | Mobile/tvOS/Lerigos Music/FirstViewController.swift | 1 | 533 | //
// FirstViewController.swift
// Lerigos Music
//
// Created by Dmitriy Groschovskiy on 25/01/2016.
// Copyright © 2016 Lerigos, Inc. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 |
53ningen/todo | TODO/UI/UIStoryboardExtensions.swift | 1 | 1666 | import UIKit
import RxSwift
extension UIStoryboard {
static func selectLabelsViewController(_ selectedLabels: Variable<[Label]>) -> SelectLabelsViewController {
let vc = UIViewController.of(SelectLabelsViewController.self)
vc.modalTransitionStyle = UIModalTransitionStyle.coverVertical
vc.setViewModel(SelectLabelsViewModel(selected: selectedLabels))
return vc
}
static func issueViewController(_ id: Id<Issue>) -> IssueViewController {
let vc = UIViewController.of(IssueViewController.self)
vc.setViewModel(IssueViewModel(id: id))
vc.hidesBottomBarWhenPushed = true
return vc
}
static func editIssueViewController(_ issue: Issue? = nil) -> EditIssueViewController {
let vc = UIViewController.of(EditIssueViewController.self)
issue.forEach { vc.setViewModel(EditIssueViewModel(issue: $0)) }
return vc
}
static var addLabelViewController: EditLabelViewController {
return UIViewController.of(EditLabelViewController.self)
}
static var addMilestoneViewController: EditMilestoneViewController {
return UIViewController.of(EditMilestoneViewController.self)
}
static func issuesViewController(_ query: IssuesQuery) -> IssuesViewController {
let vc = UIViewController.of(IssuesViewController.self)
vc.setViewModel(IssuesViewModel(query: query))
return vc
}
static var licenseViewController: LicensesViewController {
let vc = UIViewController.of(LicensesViewController.self)
vc.hidesBottomBarWhenPushed = true
return vc
}
}
| mit |
cdmx/MiniMancera | miniMancera/Model/Option/WhistlesVsZombies/Zombie/Item/Type/MOptionWhistlesVsZombiesZombieItemCop.swift | 1 | 1065 | import SpriteKit
class MOptionWhistlesVsZombiesZombieItemCop:MOptionWhistlesVsZombiesZombieItemProtocol
{
private(set) weak var textureStand:MGameTexture!
private(set) weak var animatedWalking:SKAction!
private(set) var animatedDefeat:SKAction!
private(set) var verticalDelta:CGFloat
private(set) var speed:Int
private(set) var intelligence:Int
private(set) var life:Int
private(set) var coins:Int
private let kVerticalDelta:CGFloat = 2
private let kSpeed:Int = 5
private let kIntelligence:Int = 7
private let kLife:Int = 35
private let kCoins:Int = 2
required init(
textures:MOptionWhistlesVsZombiesTextures,
actions:MOptionWhistlesVsZombiesActions)
{
textureStand = textures.zombieCopStand
animatedWalking = actions.actionZombieCopWalkingAnimation
animatedDefeat = actions.actionZombieCopDefeatedAnimation
verticalDelta = kVerticalDelta
speed = kSpeed
intelligence = kIntelligence
life = kLife
coins = kCoins
}
}
| mit |
Nosrac/Dictater | Dictater/DictaterWindow.swift | 1 | 2473 | //
// DictateAssistWindow.swift
// Dictate Assist
//
// Created by Kyle Carson on 9/1/15.
// Copyright © 2015 Kyle Carson. All rights reserved.
//
import Foundation
import Cocoa
class DictaterWindow : NSWindow
{
override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing backingStoreType: NSWindow.BackingStoreType, defer flag: Bool) {
super.init(contentRect: contentRect, styleMask: style, backing: backingStoreType, defer: flag)
// self.styleMask = NSBorderlessWindowMask
self.isOpaque = false
self.backgroundColor = NSColor.clear
self.level = NSWindow.Level.floating
NotificationCenter.default.addObserver(self, selector: #selector(self.didEnterFullScreen), name: NSNotification.Name(rawValue: TeleprompterWindowDelegate.FullScreenEnteredEvent), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.didExitFullScreen), name: NSNotification.Name(rawValue: TeleprompterWindowDelegate.FullScreenExitedEvent), object: nil)
}
@objc func didEnterFullScreen()
{
self.orderOut(self)
}
@objc func didExitFullScreen()
{
self.orderFront(self)
}
// required init?(coder: NSCoder) {
// super.init(coder: coder)
// }
override var contentView : NSView? {
set {
if let view = newValue
{
view.wantsLayer = true
view.layer?.frame = view.frame
view.layer?.cornerRadius = 6.0
view.layer?.masksToBounds = true
}
super.contentView = newValue
}
get {
return super.contentView
}
}
override var canBecomeMain : Bool
{
get {
return true
}
}
override var canBecomeKey : Bool
{
get {
return true
}
}
// Drag Windows
var initialLocation : NSPoint?
override func mouseDown(with event: NSEvent) {
initialLocation = event.locationInWindow
}
override func mouseDragged(with event: NSEvent) {
if let screenVisibleFrame = NSScreen.main?.visibleFrame,
let initialLocation = self.initialLocation
{
let windowFrame = self.frame
var newOrigin = windowFrame.origin
let currentLocation = event.locationInWindow
newOrigin.x += (currentLocation.x - initialLocation.x)
newOrigin.y += (currentLocation.y - initialLocation.y)
if (newOrigin.y + windowFrame.size.height) > (screenVisibleFrame.origin.y + screenVisibleFrame.size.height)
{
newOrigin.y = screenVisibleFrame.origin.y + screenVisibleFrame.size.height - windowFrame.size.height
}
self.setFrameOrigin(newOrigin)
}
}
}
| mit |
dangquochoi2007/cleancodeswift | CleanStore/CleanStore/App/Services/ImageMemoryStore.swift | 1 | 1836 | //
// ImageMemoryStore.swift
// CleanStore
//
// Created by hoi on 1/6/17.
// Copyright © 2017 hoi. All rights reserved.
//
import UIKit
/// _ImageMemoryStore_ is an image store backed by an in-memory cache
class ImageMemoryStore: ImageStoreProtocol {
fileprivate var imageCache = [String: UIImage]()
// MARK: - Initializers
init() {
NotificationCenter.default.addObserver(self, selector: #selector(handleMemoryNotification), name: NSNotification.Name.UIApplicationDidReceiveMemoryWarning, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidReceiveMemoryWarning, object: nil)
}
/// Loads an image from the cache if found otherwise returns nil
///
/// - parameter url: The image URL
/// - parameter completion: The closure to trigger when the image is found or not
func loadImage(url: URL, completion: @escaping (UIImage?, Error?) -> ()) {
let cacheKey = key(url: url)
let image = imageCache[cacheKey]
completion(image, nil)
}
/// Saves an image to the cache
///
/// - parameter image: The image to save (cache)
/// - parameter url: The URL of the image (used as a key)
func saveImage(image: UIImage?, url: URL) {
let cacheKey = key(url: url)
imageCache[cacheKey] = image
}
/// Removes all images from the memory cache
func removeAllImages() {
self.imageCache.removeAll()
}
//
// MARK: - Private
private func key(url: URL) -> String {
return url.absoluteString
}
@objc func handleMemoryNotification() {
self.removeAllImages()
}
}
| mit |
apple/swift-experimental-string-processing | Sources/_RegexParser/Regex/Printing/PrintAsCanonical.swift | 1 | 9703 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// TODO: Round-tripping tests
extension AST {
/// Renders using Swift's preferred regex literal syntax.
public func renderAsCanonical(
showDelimiters delimiters: Bool = false,
terminateLine: Bool = false
) -> String {
var printer = PrettyPrinter()
printer.printAsCanonical(
self,
delimiters: delimiters,
terminateLine: terminateLine)
return printer.finish()
}
}
extension AST.Node {
/// Renders using Swift's preferred regex literal syntax.
public func renderAsCanonical(
showDelimiters delimiters: Bool = false,
terminateLine: Bool = false
) -> String {
AST(self, globalOptions: nil, diags: Diagnostics()).renderAsCanonical(
showDelimiters: delimiters, terminateLine: terminateLine)
}
}
extension PrettyPrinter {
/// Outputs a regular expression abstract syntax tree in canonical form,
/// indenting and terminating the line, and updating its internal state.
///
/// - Parameter ast: The abstract syntax tree of the regular expression being output.
/// - Parameter delimiters: Whether to include commas between items.
/// - Parameter terminateLine: Whether to include terminate the line.
public mutating func printAsCanonical(
_ ast: AST,
delimiters: Bool = false,
terminateLine terminate: Bool = true
) {
indent()
if delimiters { output("'/") }
if let opts = ast.globalOptions {
outputAsCanonical(opts)
}
outputAsCanonical(ast.root)
if delimiters { output("/'") }
if terminate {
terminateLine()
}
}
/// Outputs a regular expression abstract syntax tree in canonical form,
/// without indentation, line termation, or affecting its internal state.
mutating func outputAsCanonical(_ ast: AST.Node) {
switch ast {
case let .alternation(a):
for idx in a.children.indices {
outputAsCanonical(a.children[idx])
if a.children.index(after: idx) != a.children.endIndex {
output("|")
}
}
case let .concatenation(c):
c.children.forEach { outputAsCanonical($0) }
case let .group(g):
output(g.kind.value._canonicalBase)
outputAsCanonical(g.child)
output(")")
case let .conditional(c):
output("(")
outputAsCanonical(c.condition)
outputAsCanonical(c.trueBranch)
output("|")
outputAsCanonical(c.falseBranch)
case let .quantification(q):
outputAsCanonical(q.child)
output(q.amount.value._canonicalBase)
output(q.kind.value._canonicalBase)
case let .quote(q):
output(q._canonicalBase)
case let .trivia(t):
output(t._canonicalBase)
case let .interpolation(i):
output(i._canonicalBase)
case let .atom(a):
output(a._canonicalBase)
case let .customCharacterClass(ccc):
outputAsCanonical(ccc)
case let .absentFunction(abs):
outputAsCanonical(abs)
case .empty:
output("")
}
}
mutating func outputAsCanonical(
_ ccc: AST.CustomCharacterClass
) {
output(ccc.start.value._canonicalBase)
ccc.members.forEach { outputAsCanonical($0) }
output("]")
}
mutating func outputAsCanonical(
_ member: AST.CustomCharacterClass.Member
) {
// TODO: Do we need grouping or special escape rules?
switch member {
case .custom(let ccc):
outputAsCanonical(ccc)
case .range(let r):
output(r.lhs._canonicalBase)
output("-")
output(r.rhs._canonicalBase)
case .atom(let a):
output(a._canonicalBase)
case .quote(let q):
output(q._canonicalBase)
case .trivia(let t):
output(t._canonicalBase)
case .setOperation:
output("/* TODO: set operation \(self) */")
}
}
mutating func outputAsCanonical(_ condition: AST.Conditional.Condition) {
output("(/*TODO: conditional \(condition) */)")
}
mutating func outputAsCanonical(_ abs: AST.AbsentFunction) {
output("(?~")
switch abs.kind {
case .repeater(let a):
outputAsCanonical(a)
case .expression(let a, _, let child):
output("|")
outputAsCanonical(a)
output("|")
outputAsCanonical(child)
case .stopper(let a):
output("|")
outputAsCanonical(a)
case .clearer:
output("|")
}
output(")")
}
mutating func outputAsCanonical(_ opts: AST.GlobalMatchingOptionSequence) {
for opt in opts.options {
output(opt._canonicalBase)
}
}
}
extension AST.Quote {
var _canonicalBase: String {
// TODO: Is this really what we want?
"\\Q\(literal)\\E"
}
}
extension AST.Interpolation {
var _canonicalBase: String {
"<{\(contents)}>"
}
}
extension AST.Group.Kind {
var _canonicalBase: String {
switch self {
case .capture: return "("
case .namedCapture(let n): return "(?<\(n.value)>"
case .balancedCapture(let b): return "(?<\(b._canonicalBase)>"
case .nonCapture: return "(?:"
case .nonCaptureReset: return "(?|"
case .atomicNonCapturing: return "(?>"
case .lookahead: return "(?="
case .negativeLookahead: return "(?!"
case .nonAtomicLookahead: return "(?*"
case .lookbehind: return "(?<="
case .negativeLookbehind: return "(?<!"
case .nonAtomicLookbehind: return "(?<*"
case .scriptRun: return "(*sr:"
case .atomicScriptRun: return "(*asr:"
case .changeMatchingOptions:
return "(/* TODO: matchign options in canonical form */"
}
}
}
extension AST.Quantification.Amount {
var _canonicalBase: String {
switch self {
case .zeroOrMore: return "*"
case .oneOrMore: return "+"
case .zeroOrOne: return "?"
case let .exactly(n): return "{\(n._canonicalBase)}"
case let .nOrMore(n): return "{\(n._canonicalBase),}"
case let .upToN(n): return "{,\(n._canonicalBase)}"
case let .range(lower, upper):
return "{\(lower),\(upper)}"
}
}
}
extension AST.Quantification.Kind {
var _canonicalBase: String { self.rawValue }
}
extension AST.Atom.Number {
var _canonicalBase: String {
value.map { "\($0)" } ?? "<#number#>"
}
}
extension AST.Atom {
var _canonicalBase: String {
if let lit = self.literalStringValue {
// FIXME: We may have to re-introduce escapes
// For example, `\.` will come back as "." instead
// For now, catch the most common offender
if lit == "." { return "\\." }
return lit
}
switch self.kind {
case .caretAnchor:
return "^"
case .dollarAnchor:
return "$"
case .escaped(let e):
return "\\\(e.character)"
case .backreference(let br):
return br._canonicalBase
default:
return "/* TODO: atom \(self) */"
}
}
}
extension AST.Reference {
var _canonicalBase: String {
if self.recursesWholePattern {
return "(?R)"
}
switch kind {
case .absolute(let i):
// TODO: Which should we prefer, this or `\g{n}`?
return "\\\(i)"
case .relative:
return "/* TODO: relative reference \(self) */"
case .named:
return "/* TODO: named reference \(self) */"
}
}
}
extension AST.CustomCharacterClass.Start {
var _canonicalBase: String { self.rawValue }
}
extension AST.Group.BalancedCapture {
var _canonicalBase: String {
"\(name?.value ?? "")-\(priorName.value)"
}
}
extension AST.GlobalMatchingOption.NewlineMatching {
var _canonicalBase: String {
switch self {
case .carriageReturnOnly: return "CR"
case .linefeedOnly: return "LF"
case .carriageAndLinefeedOnly: return "CRLF"
case .anyCarriageReturnOrLinefeed: return "ANYCRLF"
case .anyUnicode: return "ANY"
case .nulCharacter: return "NUL"
}
}
}
extension AST.GlobalMatchingOption.NewlineSequenceMatching {
var _canonicalBase: String {
switch self {
case .anyCarriageReturnOrLinefeed: return "BSR_ANYCRLF"
case .anyUnicode: return "BSR_UNICODE"
}
}
}
extension AST.GlobalMatchingOption.Kind {
var _canonicalBase: String {
switch self {
case .limitDepth(let i): return "LIMIT_DEPTH=\(i._canonicalBase)"
case .limitHeap(let i): return "LIMIT_HEAP=\(i._canonicalBase)"
case .limitMatch(let i): return "LIMIT_MATCH=\(i._canonicalBase)"
case .notEmpty: return "NOTEMPTY"
case .notEmptyAtStart: return "NOTEMPTY_ATSTART"
case .noAutoPossess: return "NO_AUTO_POSSESS"
case .noDotStarAnchor: return "NO_DOTSTAR_ANCHOR"
case .noJIT: return "NO_JIT"
case .noStartOpt: return "NO_START_OPT"
case .utfMode: return "UTF"
case .unicodeProperties: return "UCP"
case .newlineMatching(let m): return m._canonicalBase
case .newlineSequenceMatching(let m): return m._canonicalBase
}
}
}
extension AST.GlobalMatchingOption {
var _canonicalBase: String { "(*\(kind._canonicalBase))"}
}
extension AST.Trivia {
var _canonicalBase: String {
// TODO: We might want to output comments...
""
}
}
| apache-2.0 |
braintree/braintree_ios | UnitTests/BraintreePayPalTests/BTPayPalDriver_Tests.swift | 1 | 32734 | import XCTest
import BraintreePayPal
import BraintreeTestShared
class BTPayPalDriver_Tests: XCTestCase {
var mockAPIClient: MockAPIClient!
var payPalDriver: BTPayPalDriver!
override func setUp() {
super.setUp()
mockAPIClient = MockAPIClient(authorization: "development_tokenization_key")!
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"paypalEnabled": true,
"paypal": [
"environment": "offline"
]
])
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "http://fakeURL.com"
]
])
payPalDriver = BTPayPalDriver(apiClient: mockAPIClient)
}
func testTokenizePayPalAccount_whenAPIClientIsNil_callsBackWithError() {
payPalDriver.apiClient = nil
let request = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Checkout fails with error")
payPalDriver.tokenizePayPalAccount(with: request) { (nonce, error) in
guard let error = error as NSError? else { XCTFail(); return }
XCTAssertNil(nonce)
XCTAssertEqual(error.domain, BTPayPalDriverErrorDomain)
XCTAssertEqual(error.code, BTPayPalDriverErrorType.integration.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func testTokenizePayPalAccount_whenRequestIsNotExpectedSubclass_callsBackWithError() {
let request = BTPayPalRequest() // not one of our subclasses
let expectation = self.expectation(description: "Checkout fails with error")
payPalDriver.tokenizePayPalAccount(with: request) { (nonce, error) in
guard let error = error as NSError? else { XCTFail(); return }
XCTAssertNil(nonce)
XCTAssertEqual(error.domain, BTPayPalDriverErrorDomain)
XCTAssertEqual(error.code, BTPayPalDriverErrorType.integration.rawValue)
XCTAssertEqual(error.localizedDescription, "BTPayPalDriver failed because request is not of type BTPayPalCheckoutRequest or BTPayPalVaultRequest.")
expectation.fulfill()
}
waitForExpectations(timeout: 1)
}
func testTokenizePayPalAccount_whenRemoteConfigurationFetchFails_callsBackWithConfigurationError() {
mockAPIClient.cannedConfigurationResponseBody = nil
mockAPIClient.cannedConfigurationResponseError = NSError(domain: "", code: 0, userInfo: nil)
let request = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Checkout fails with error")
payPalDriver.tokenizePayPalAccount(with: request) { (nonce, error) in
guard let error = error as NSError? else { XCTFail(); return }
XCTAssertNil(nonce)
XCTAssertEqual(error, self.mockAPIClient.cannedConfigurationResponseError)
expectation.fulfill()
}
self.waitForExpectations(timeout: 1)
}
func testTokenizePayPalAccount_whenPayPalNotEnabledInConfiguration_callsBackWithError() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [
"paypalEnabled": false
])
let request = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Checkout fails with error")
payPalDriver.tokenizePayPalAccount(with: request) { (nonce, error) in
guard let error = error as NSError? else { XCTFail(); return }
XCTAssertNil(nonce)
XCTAssertEqual(error.domain, BTPayPalDriverErrorDomain)
XCTAssertEqual(error.code, BTPayPalDriverErrorType.disabled.rawValue)
XCTAssertEqual(error.localizedDescription, "PayPal is not enabled for this merchant")
expectation.fulfill()
}
self.waitForExpectations(timeout: 1)
}
// MARK: - POST request to Hermes endpoint
func testRequestOneTimePayment_whenRemoteConfigurationFetchSucceeds_postsToCorrectEndpoint() {
let request = BTPayPalCheckoutRequest(amount: "1")
request.intent = .sale
payPalDriver.requestOneTimePayment(request) { _,_ -> Void in }
XCTAssertEqual("v1/paypal_hermes/create_payment_resource", mockAPIClient.lastPOSTPath)
guard let lastPostParameters = mockAPIClient.lastPOSTParameters else { XCTFail(); return }
XCTAssertEqual(lastPostParameters["intent"] as? String, "sale")
XCTAssertEqual(lastPostParameters["amount"] as? String, "1")
XCTAssertEqual(lastPostParameters["return_url"] as? String, "sdk.ios.braintree://onetouch/v1/success")
XCTAssertEqual(lastPostParameters["cancel_url"] as? String, "sdk.ios.braintree://onetouch/v1/cancel")
}
func testRequestBillingAgreement_whenRemoteConfigurationFetchSucceeds_postsToCorrectEndpoint() {
let request = BTPayPalVaultRequest()
request.billingAgreementDescription = "description"
payPalDriver.requestBillingAgreement(request) { _,_ -> Void in }
XCTAssertEqual("v1/paypal_hermes/setup_billing_agreement", mockAPIClient.lastPOSTPath)
guard let lastPostParameters = mockAPIClient.lastPOSTParameters else { XCTFail(); return }
XCTAssertEqual(lastPostParameters["description"] as? String, "description")
XCTAssertEqual(lastPostParameters["return_url"] as? String, "sdk.ios.braintree://onetouch/v1/success")
XCTAssertEqual(lastPostParameters["cancel_url"] as? String, "sdk.ios.braintree://onetouch/v1/cancel")
}
func testTokenizePayPalAccount_whenPaymentResourceCreationFails_callsBackWithError() {
mockAPIClient.cannedResponseError = NSError(domain: "", code: 0, userInfo: nil)
let dummyRequest = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Checkout fails with error")
payPalDriver.tokenizePayPalAccount(with: dummyRequest) { (_, error) -> Void in
XCTAssertEqual(error! as NSError, self.mockAPIClient.cannedResponseError!)
expectation.fulfill()
}
self.waitForExpectations(timeout: 1)
}
// MARK: - PayPal approval URL to present in browser
func testTokenizePayPalAccount_checkout_whenUserActionIsNotSet_approvalUrlIsNotModified() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "https://www.paypal.com/checkout?EC-Token=EC-Random-Value"
]
])
let request = BTPayPalCheckoutRequest(amount: "1")
payPalDriver.tokenizePayPalAccount(with: request) { (_, _) in }
XCTAssertEqual("https://www.paypal.com/checkout?EC-Token=EC-Random-Value", payPalDriver.approvalUrl.absoluteString)
}
func testTokenizePayPalAccount_vault_whenUserActionIsNotSet_approvalUrlIsNotModified() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"agreementSetup": [
"approvalUrl": "https://checkout.paypal.com/one-touch-login-sandbox"
]
])
let request = BTPayPalVaultRequest()
payPalDriver.tokenizePayPalAccount(with: request) { (_, _) in }
XCTAssertEqual("https://checkout.paypal.com/one-touch-login-sandbox", payPalDriver.approvalUrl.absoluteString)
}
func testTokenizePayPalAccount_whenUserActionIsSetToDefault_approvalUrlIsNotModified() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "https://www.paypal.com/checkout?EC-Token=EC-Random-Value"
]
])
let request = BTPayPalCheckoutRequest(amount: "1")
request.userAction = BTPayPalRequestUserAction.default
payPalDriver.tokenizePayPalAccount(with: request) { (_, _) in }
XCTAssertEqual("https://www.paypal.com/checkout?EC-Token=EC-Random-Value", payPalDriver.approvalUrl.absoluteString)
}
func testTokenizePayPalAccount_whenUserActionIsSetToCommit_approvalUrlIsModified() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "https://www.paypal.com/checkout?EC-Token=EC-Random-Value"
]
])
let request = BTPayPalCheckoutRequest(amount: "1")
request.userAction = BTPayPalRequestUserAction.commit
payPalDriver.tokenizePayPalAccount(with: request) { (_, _) in }
XCTAssertEqual("https://www.paypal.com/checkout?EC-Token=EC-Random-Value&useraction=commit", payPalDriver.approvalUrl.absoluteString)
}
func testTokenizePayPalAccount_whenUserActionIsSetToCommit_andNoQueryParamsArePresent_approvalUrlIsModified() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "https://www.paypal.com/checkout"
]
])
let request = BTPayPalCheckoutRequest(amount: "1")
request.userAction = BTPayPalRequestUserAction.commit
payPalDriver.tokenizePayPalAccount(with: request) { (_, _) in }
XCTAssertEqual("https://www.paypal.com/checkout?useraction=commit", payPalDriver.approvalUrl.absoluteString)
}
func testTokenizePayPalAccount_whenApprovalUrlIsNotHTTP_returnsError() {
mockAPIClient.cannedResponseBody = BTJSON(value: [
"paymentResource": [
"redirectUrl": "file://some-url.com"
]
])
let request = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Returns error")
payPalDriver.tokenizePayPalAccount(with: request) { (nonce, error) in
XCTAssertNil(nonce)
XCTAssertEqual((error! as NSError).domain, BTPayPalDriverErrorDomain)
XCTAssertEqual((error! as NSError).code, BTPayPalDriverErrorType.unknown.rawValue)
XCTAssertEqual((error! as NSError).localizedDescription, "Attempted to open an invalid URL in ASWebAuthenticationSession: file://")
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
// MARK: - Browser switch
func testTokenizePayPalAccount_whenPayPalPayLaterOffered_performsSwitchCorrectly() {
let request = BTPayPalCheckoutRequest(amount: "1")
request.currencyCode = "GBP"
request.offerPayLater = true
payPalDriver.tokenizePayPalAccount(with: request) { _,_ in }
XCTAssertNotNil(payPalDriver.authenticationSession)
XCTAssertTrue(payPalDriver.isAuthenticationSessionStarted)
// Ensure the payment resource had the correct parameters
XCTAssertEqual("v1/paypal_hermes/create_payment_resource", mockAPIClient.lastPOSTPath)
guard let lastPostParameters = mockAPIClient.lastPOSTParameters else {
XCTFail()
return
}
XCTAssertEqual(lastPostParameters["offer_pay_later"] as? Bool, true)
// Make sure analytics event was sent when switch occurred
let postedAnalyticsEvents = mockAPIClient.postedAnalyticsEvents
XCTAssertTrue(postedAnalyticsEvents.contains("ios.paypal-single-payment.webswitch.paylater.offered.started"))
}
func testTokenizePayPalAccount_whenPayPalCreditOffered_performsSwitchCorrectly() {
let request = BTPayPalVaultRequest()
request.offerCredit = true
payPalDriver.tokenizePayPalAccount(with: request) { _,_ in }
XCTAssertNotNil(payPalDriver.authenticationSession)
XCTAssertTrue(payPalDriver.isAuthenticationSessionStarted)
// Ensure the payment resource had the correct parameters
XCTAssertEqual("v1/paypal_hermes/setup_billing_agreement", mockAPIClient.lastPOSTPath)
guard let lastPostParameters = mockAPIClient.lastPOSTParameters else {
XCTFail()
return
}
XCTAssertEqual(lastPostParameters["offer_paypal_credit"] as? Bool, true)
// Make sure analytics event was sent when switch occurred
let postedAnalyticsEvents = mockAPIClient.postedAnalyticsEvents
XCTAssertTrue(postedAnalyticsEvents.contains("ios.paypal-ba.webswitch.credit.offered.started"))
}
func testTokenizePayPalAccount_whenPayPalPaymentCreationSuccessful_performsAppSwitch() {
let request = BTPayPalCheckoutRequest(amount: "1")
payPalDriver.tokenizePayPalAccount(with: request) { _,_ -> Void in }
XCTAssertNotNil(payPalDriver.authenticationSession)
XCTAssertTrue(payPalDriver.isAuthenticationSessionStarted)
XCTAssertNotNil(payPalDriver.clientMetadataID)
}
// MARK: - handleBrowserSwitchReturn
func testHandleBrowserSwitchReturn_whenBrowserSwitchCancels_callsBackWithNoResultAndError() {
let returnURL = URL(string: "bar://onetouch/v1/cancel?token=hermes_token")!
let expectation = self.expectation(description: "completion block called")
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (nonce, error) in
XCTAssertNil(nonce)
XCTAssertEqual((error! as NSError).domain, BTPayPalDriverErrorDomain)
XCTAssertEqual((error! as NSError).code, BTPayPalDriverErrorType.canceled.rawValue)
expectation.fulfill()
}
self.waitForExpectations(timeout: 1)
}
func testHandleBrowserSwitchReturn_whenBrowserSwitchHasInvalidReturnURL_callsBackWithError() {
let returnURL = URL(string: "bar://onetouch/v1/invalid")!
let continuationExpectation = self.expectation(description: "Continuation called")
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (nonce, error) in
guard let error = error as NSError? else { XCTFail(); return }
XCTAssertNil(nonce)
XCTAssertNotNil(error)
XCTAssertEqual(error.domain, BTPayPalDriverErrorDomain)
XCTAssertEqual(error.code, BTPayPalDriverErrorType.unknown.rawValue)
continuationExpectation.fulfill()
}
self.waitForExpectations(timeout: 1)
}
func testHandleBrowserSwitchReturn_whenBrowserSwitchSucceeds_tokenizesPayPalCheckout() {
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertEqual(mockAPIClient.lastPOSTPath, "/v1/payment_methods/paypal_accounts")
let lastPostParameters = mockAPIClient.lastPOSTParameters!
let paypalAccount = lastPostParameters["paypal_account"] as! [String:Any]
let options = paypalAccount["options"] as! [String:Any]
XCTAssertFalse(options["validate"] as! Bool)
}
func testHandleBrowserSwitchReturn_whenBrowserSwitchSucceeds_intentShouldExistAsPayPalAccountParameter() {
let payPalRequest = BTPayPalCheckoutRequest(amount: "1.34")
payPalRequest.intent = .sale
payPalDriver.payPalRequest = payPalRequest
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertEqual(mockAPIClient.lastPOSTPath, "/v1/payment_methods/paypal_accounts")
let lastPostParameters = mockAPIClient.lastPOSTParameters!
let paypalAccount = lastPostParameters["paypal_account"] as! [String:Any]
XCTAssertEqual(paypalAccount["intent"] as? String, "sale")
let options = paypalAccount["options"] as! [String:Any]
XCTAssertFalse(options["validate"] as! Bool)
}
func testHandleBrowserSwitchReturn_whenBrowserSwitchSucceeds_merchantAccountIdIsSet() {
let merchantAccountID = "alternate-merchant-account-id"
payPalDriver.payPalRequest = BTPayPalCheckoutRequest(amount: "1.34")
payPalDriver.payPalRequest.merchantAccountID = merchantAccountID
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertEqual(mockAPIClient.lastPOSTPath, "/v1/payment_methods/paypal_accounts")
let lastPostParameters = mockAPIClient.lastPOSTParameters!
XCTAssertEqual(lastPostParameters["merchant_account_id"] as? String, merchantAccountID)
}
func testHandleBrowserSwitchReturn_whenCreditFinancingNotReturned_shouldNotSendCreditAcceptedAnalyticsEvent() {
mockAPIClient.cannedResponseBody = BTJSON(value: [ "paypalAccounts":
[
[
"description": "jane.doe@example.com",
"details": [
"email": "jane.doe@example.com",
],
"nonce": "a-nonce",
"type": "PayPalAccount",
]
]
])
payPalDriver.payPalRequest = BTPayPalCheckoutRequest(amount: "1.34")
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertFalse(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal-single-payment.credit.accepted"))
}
func testHandleBrowserSwitchReturn_whenCreditFinancingReturned_shouldSendCreditAcceptedAnalyticsEvent() {
mockAPIClient.cannedResponseBody = BTJSON(value: [ "paypalAccounts":
[
[
"description": "jane.doe@example.com",
"details": [
"email": "jane.doe@example.com",
"creditFinancingOffered": [
"cardAmountImmutable": true,
"monthlyPayment": [
"currency": "USD",
"value": "13.88",
],
"payerAcceptance": true,
"term": 18,
"totalCost": [
"currency": "USD",
"value": "250.00",
],
"totalInterest": [
"currency": "USD",
"value": "0.00",
],
],
],
"nonce": "a-nonce",
"type": "PayPalAccount",
]
]
])
payPalDriver.payPalRequest = BTPayPalCheckoutRequest(amount: "1.34")
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertTrue(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal-single-payment.credit.accepted"))
}
// MARK: - Tokenization
func testHandleBrowserSwitchReturn_whenBrowserSwitchSucceeds_sendsCorrectParametersForTokenization() {
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .vault) { (_, _) in }
XCTAssertEqual(mockAPIClient.lastPOSTPath, "/v1/payment_methods/paypal_accounts")
guard let lastPostParameters = mockAPIClient.lastPOSTParameters else {
XCTFail()
return
}
guard let paypalAccount = lastPostParameters["paypal_account"] as? [String:Any] else {
XCTFail()
return
}
let client = paypalAccount["client"] as? [String:String]
XCTAssertEqual(client?["paypal_sdk_version"], "version")
XCTAssertEqual(client?["platform"], "iOS")
XCTAssertEqual(client?["product_name"], "PayPal")
let response = paypalAccount["response"] as? [String:String]
XCTAssertEqual(response?["webURL"], "bar://onetouch/v1/success?token=hermes_token")
XCTAssertEqual(paypalAccount["response_type"] as? String, "web")
}
func testTokenizedPayPalAccount_containsPayerInfo() {
let checkoutResponse = [
"paypalAccounts": [
[
"nonce": "a-nonce",
"description": "A description",
"details": [
"email": "hello@world.com",
"payerInfo": [
"firstName": "Some",
"lastName": "Dude",
"phone": "867-5309",
"payerId": "FAKE-PAYER-ID",
"accountAddress": [
"street1": "1 Foo Ct",
"street2": "Apt Bar",
"city": "Fubar",
"state": "FU",
"postalCode": "42",
"country": "USA"
],
"billingAddress": [
"recipientName": "Bar Foo",
"line1": "2 Foo Ct",
"line2": "Apt Foo",
"city": "Barfoo",
"state": "BF",
"postalCode": "24",
"countryCode": "ASU"
],
"shippingAddress": [
"recipientName": "Some Dude",
"line1": "3 Foo Ct",
"line2": "Apt 5",
"city": "Dudeville",
"state": "CA",
"postalCode": "24",
"countryCode": "US"
]
]
]
]
]
]
mockAPIClient.cannedResponseBody = BTJSON(value: checkoutResponse as [String : AnyObject])
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (tokenizedPayPalAccount, error) in
XCTAssertEqual(tokenizedPayPalAccount!.nonce, "a-nonce")
XCTAssertEqual(tokenizedPayPalAccount!.firstName, "Some")
XCTAssertEqual(tokenizedPayPalAccount!.lastName, "Dude")
XCTAssertEqual(tokenizedPayPalAccount!.phone, "867-5309")
XCTAssertEqual(tokenizedPayPalAccount!.email, "hello@world.com")
XCTAssertEqual(tokenizedPayPalAccount!.payerID, "FAKE-PAYER-ID")
let billingAddress = tokenizedPayPalAccount!.billingAddress!
XCTAssertEqual(billingAddress.recipientName, "Bar Foo")
XCTAssertEqual(billingAddress.streetAddress, "2 Foo Ct")
XCTAssertEqual(billingAddress.extendedAddress, "Apt Foo")
XCTAssertEqual(billingAddress.locality, "Barfoo")
XCTAssertEqual(billingAddress.region, "BF")
XCTAssertEqual(billingAddress.postalCode, "24")
XCTAssertEqual(billingAddress.countryCodeAlpha2, "ASU")
let shippingAddress = tokenizedPayPalAccount!.shippingAddress!
XCTAssertEqual(shippingAddress.recipientName, "Some Dude")
XCTAssertEqual(shippingAddress.streetAddress, "3 Foo Ct")
XCTAssertEqual(shippingAddress.extendedAddress, "Apt 5")
XCTAssertEqual(shippingAddress.locality, "Dudeville")
XCTAssertEqual(shippingAddress.region, "CA")
XCTAssertEqual(shippingAddress.postalCode, "24")
XCTAssertEqual(shippingAddress.countryCodeAlpha2, "US")
}
}
func testTokenizedPayPalAccount_whenTokenizationResponseDoesNotHaveShippingAddress_returnsAccountAddressAsShippingAddress() {
let checkoutResponse = [
"paypalAccounts": [
[
"nonce": "a-nonce",
"description": "A description",
"details": [
"email": "hello@world.com",
"payerInfo": [
"firstName": "Some",
"lastName": "Dude",
"phone": "867-5309",
"payerId": "FAKE-PAYER-ID",
"accountAddress": [
"recipientName": "Grace Hopper",
"street1": "1 Foo Ct",
"street2": "Apt Bar",
"city": "Fubar",
"state": "FU",
"postalCode": "42",
"country": "USA"
],
"billingAddress": [
"recipientName": "Bar Foo",
"line1": "2 Foo Ct",
"line2": "Apt Foo",
"city": "Barfoo",
"state": "BF",
"postalCode": "24",
"countryCode": "ASU"
]
]
]
]
]
]
mockAPIClient.cannedResponseBody = BTJSON(value: checkoutResponse as [String : AnyObject])
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (tokenizedPayPalAccount, error) in
let shippingAddress = tokenizedPayPalAccount!.shippingAddress!
XCTAssertEqual(shippingAddress.recipientName, "Grace Hopper")
XCTAssertEqual(shippingAddress.streetAddress, "1 Foo Ct")
XCTAssertEqual(shippingAddress.extendedAddress, "Apt Bar")
XCTAssertEqual(shippingAddress.locality, "Fubar")
XCTAssertEqual(shippingAddress.region, "FU")
XCTAssertEqual(shippingAddress.postalCode, "42")
XCTAssertEqual(shippingAddress.countryCodeAlpha2, "USA")
}
}
func testTokenizedPayPalAccount_whenEmailAddressIsNestedInsidePayerInfoJSON_usesNestedEmailAddress() {
let checkoutResponse = [
"paypalAccounts": [
[
"nonce": "fake-nonce",
"details": [
"email": "not-hello@world.com",
"payerInfo": [
"email": "hello@world.com",
]
],
]
]
]
mockAPIClient.cannedResponseBody = BTJSON(value: checkoutResponse as [String : AnyObject])
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (tokenizedPayPalAccount, error) -> Void in
XCTAssertEqual(tokenizedPayPalAccount!.email, "hello@world.com")
}
}
// MARK: - _meta parameter
func testMetadata_whenCheckoutBrowserSwitchIsSuccessful_isPOSTedToServer() {
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { (_, _) in }
XCTAssertEqual(mockAPIClient.lastPOSTPath, "/v1/payment_methods/paypal_accounts")
let lastPostParameters = mockAPIClient.lastPOSTParameters!
let metaParameters = lastPostParameters["_meta"] as! [String:Any]
XCTAssertEqual(metaParameters["source"] as? String, "paypal-browser")
XCTAssertEqual(metaParameters["integration"] as? String, "custom")
XCTAssertEqual(metaParameters["sessionId"] as? String, mockAPIClient.metadata.sessionID)
}
// MARK: - Analytics
func testAPIClientMetadata_hasIntegrationSetToCustom() {
let apiClient = BTAPIClient(authorization: "development_testing_integration_merchant_id")!
let payPalDriver = BTPayPalDriver(apiClient: apiClient)
XCTAssertEqual(payPalDriver.apiClient?.metadata.integration, BTClientMetadataIntegrationType.custom)
}
func testHandleBrowserSwitchReturn_vault_whenCreditFinancingNotReturned_shouldNotSendCreditAcceptedAnalyticsEvent() {
mockAPIClient.cannedResponseBody = BTJSON(value: [ "paypalAccounts":
[
[
"description": "jane.doe@example.com",
"details": [
"email": "jane.doe@example.com",
],
"nonce": "a-nonce",
"type": "PayPalAccount",
]
]
])
payPalDriver.payPalRequest = BTPayPalVaultRequest()
let returnURL = URL(string: "bar://hello/world")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .vault) { (_, _) in }
XCTAssertFalse(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal-ba.credit.accepted"))
}
func testHandleBrowserSwitchReturn_vault_whenCreditFinancingReturned_shouldSendCreditAcceptedAnalyticsEvent() {
mockAPIClient.cannedResponseBody = BTJSON(
value: [ "paypalAccounts": [
[
"description": "jane.doe@example.com",
"details": [
"email": "jane.doe@example.com",
"creditFinancingOffered": [
"cardAmountImmutable": true,
"monthlyPayment": [
"currency": "USD",
"value": "13.88",
],
"payerAcceptance": true,
"term": 18,
"totalCost": [
"currency": "USD",
"value": "250.00",
],
"totalInterest": [
"currency": "USD",
"value": "0.00",
],
],
],
"nonce": "a-nonce",
"type": "PayPalAccount",
]
]
])
payPalDriver.payPalRequest = BTPayPalVaultRequest()
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .vault) { (_, _) in }
XCTAssertTrue(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal-ba.credit.accepted"))
}
func testTokenizePayPalAccountWithPayPalRequest_whenNetworkConnectionLost_sendsAnalytics() {
mockAPIClient.cannedResponseError = NSError(domain: NSURLErrorDomain, code: -1005, userInfo: [NSLocalizedDescriptionKey: "The network connection was lost."])
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [ "paypalEnabled": true ])
let request = BTPayPalCheckoutRequest(amount: "1")
let expectation = self.expectation(description: "Callback envoked")
payPalDriver.tokenizePayPalAccount(with: request) { nonce, error in
XCTAssertNotNil(error)
expectation.fulfill()
}
waitForExpectations(timeout: 2)
XCTAssertTrue(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal.tokenize.network-connection.failure"))
}
func testHandleBrowserSwitchReturnURL_whenNetworkConnectionLost_sendsAnalytics() {
let returnURL = URL(string: "bar://onetouch/v1/success?token=hermes_token")!
mockAPIClient.cannedResponseError = NSError(domain: NSURLErrorDomain, code: -1005, userInfo: [NSLocalizedDescriptionKey: "The network connection was lost."])
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: [ "paypalEnabled": true ])
let expectation = self.expectation(description: "Callback envoked")
payPalDriver.handleBrowserSwitchReturn(returnURL, paymentType: .checkout) { nonce, error in
XCTAssertNotNil(error)
expectation.fulfill()
}
waitForExpectations(timeout: 2)
XCTAssertTrue(mockAPIClient.postedAnalyticsEvents.contains("ios.paypal.handle-browser-switch.network-connection.failure"))
}
}
| mit |
redlock/SwiftyDeepstream | SwiftyDeepstream/Classes/deepstream/client/DeepstreamRuntimeErrorHandler.swift | 1 | 1005 | //
// DeepstreamRuntimeErrorHandler.swift
// deepstreamSwiftTest
//
// Created by Redlock on 4/5/17.
// Copyright © 2017 JiblaTech. All rights reserved.
//
import Foundation
public class DeepstreamRuntimeErrorHandler: DeepstreamListener {
/**
* Triggered whenever a runtime error occurs ( mostly async such as TimeOuts or MergeConflicts ).
* Recieves a topic to indicate if it was e.g. RPC, event and a english error message to simplify
* debugging purposes.
* @param topic The Topic the error occured on
* *
* @param event The Error Event
* *
* @param errorMessage The error message
*/
var onException: (Topic, Event, String) -> Void
init(onException: @escaping (Topic, Event, String) -> Void ){
self.onException = onException
}
func trigger(topic:Topic, event:Event, message:String) {
self.onException(topic, event, message)
}
func trigger(_ data: Any!) {
}
}
| mit |
alblue/swift | test/Runtime/associated_type_demangle_private.swift | 1 | 923 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -parse-stdlib %s -module-name main -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
import Swift
import StdlibUnittest
protocol P {
associatedtype A
}
fileprivate struct Foo {
fileprivate struct Inner: P {
fileprivate struct Innermost { }
typealias A = Innermost
}
}
func getP_A<T: P>(_: T.Type) -> Any.Type {
return T.A.self
}
let AssociatedTypeDemangleTests = TestSuite("AssociatedTypeDemangle")
AssociatedTypeDemangleTests.test("private types") {
expectEqual(Foo.Inner.Innermost.self, getP_A(Foo.Inner.self))
}
private protocol P2 {
associatedtype A
}
struct Bar: P2 {
typealias A = Int
}
class C1<T> { }
private class C2<T: P2>: C1<T.A> { }
AssociatedTypeDemangleTests.test("private protocols") {
expectEqual("C2<Bar>", String(describing: C2<Bar>.self))
}
runAllTests()
| apache-2.0 |
jacobwhite/firefox-ios | Client/Frontend/Browser/TopTabsLayout.swift | 3 | 5884 | /* 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
class TopTabsLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout {
weak var tabSelectionDelegate: TabSelectionDelegate?
let HeaderFooterWidth = TopTabsUX.SeparatorWidth + TopTabsUX.FaderPading
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return TopTabsUX.SeparatorWidth
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: TopTabsUX.TabWidth, height: collectionView.frame.height)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return TopTabsUX.SeparatorWidth
}
@objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: HeaderFooterWidth, height: 0)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: HeaderFooterWidth, height: 0)
}
}
class TopTabsViewLayout: UICollectionViewFlowLayout {
var decorationAttributeArr: [Int: UICollectionViewLayoutAttributes?] = [:]
let separatorYOffset = TopTabsUX.SeparatorYOffset
let separatorSize = TopTabsUX.SeparatorHeight
let SeparatorZIndex = -2 ///Prevent the header/footer from appearing above the Tabs
override var collectionViewContentSize: CGSize {
let tabsWidth = ((CGFloat(collectionView!.numberOfItems(inSection: 0))) * (TopTabsUX.TabWidth + TopTabsUX.SeparatorWidth)) - TopTabsUX.SeparatorWidth
return CGSize(width: tabsWidth + (TopTabsUX.TopTabsBackgroundShadowWidth * 2), height: collectionView!.bounds.height)
}
override func prepare() {
super.prepare()
self.minimumLineSpacing = TopTabsUX.SeparatorWidth
scrollDirection = .horizontal
register(TopTabsSeparator.self, forDecorationViewOfKind: TopTabsSeparatorUX.Identifier)
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
decorationAttributeArr = [:]
return true
}
// MARK: layoutAttributesForElementsInRect
override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard indexPath.row < self.collectionView!.numberOfItems(inSection: 0) else {
let separatorAttr = UICollectionViewLayoutAttributes(forDecorationViewOfKind: TopTabsSeparatorUX.Identifier, with: indexPath)
separatorAttr.frame = .zero
separatorAttr.zIndex = SeparatorZIndex
return separatorAttr
}
if let attr = self.decorationAttributeArr[indexPath.item] {
return attr
} else {
// Compute the separator if it does not exist in the cache
let separatorAttr = UICollectionViewLayoutAttributes(forDecorationViewOfKind: TopTabsSeparatorUX.Identifier, with: indexPath)
let x = TopTabsUX.TopTabsBackgroundShadowWidth + ((CGFloat(indexPath.row) * (TopTabsUX.TabWidth + TopTabsUX.SeparatorWidth)) - TopTabsUX.SeparatorWidth)
separatorAttr.frame = CGRect(x: x, y: separatorYOffset, width: TopTabsUX.SeparatorWidth, height: separatorSize)
separatorAttr.zIndex = SeparatorZIndex
return separatorAttr
}
}
override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = super.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath)
attributes?.zIndex = SeparatorZIndex
return attributes
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes = super.layoutAttributesForElements(in: rect)!
// Create attributes for the Tab Separator.
for i in attributes {
guard i.representedElementKind != UICollectionElementKindSectionHeader && i.representedElementKind != UICollectionElementKindSectionFooter else {
i.zIndex = SeparatorZIndex
continue
}
let sep = UICollectionViewLayoutAttributes(forDecorationViewOfKind: TopTabsSeparatorUX.Identifier, with: i.indexPath)
sep.frame = CGRect(x: i.frame.origin.x - TopTabsUX.SeparatorWidth, y: separatorYOffset, width: TopTabsUX.SeparatorWidth, height: separatorSize)
sep.zIndex = SeparatorZIndex
i.zIndex = 10
// Only add the seperator if it will be shown.
if i.indexPath.row != 0 && i.indexPath.row < self.collectionView!.numberOfItems(inSection: 0) {
attributes.append(sep)
decorationAttributeArr[i.indexPath.item] = sep
}
}
return attributes
}
}
| mpl-2.0 |
Zewo/Reflection | Tests/ReflectionTests/InternalTests.swift | 1 | 3160 | import XCTest
@testable import Reflection
public class InternalTests : XCTestCase {
func testDumbedDownTest() {
struct NominalTypeDescriptor {
let something: Int32
let numberOfProperties: Int32
}
struct StructMetadata {
let kind: Int
let nominalTypeDescriptor: UnsafePointer<NominalTypeDescriptor>
}
let type: Any.Type = Person.self
let numberOfProperties = unsafeBitCast(type, to: UnsafePointer<StructMetadata>.self).pointee.nominalTypeDescriptor.pointee.numberOfProperties
print(numberOfProperties)
}
func testShallowMetadata() {
func testShallowMetadata<T>(type: T.Type, expectedKind: Metadata.Kind) {
let shallowMetadata = Metadata(type: type)
XCTAssert(shallowMetadata.kind == expectedKind, "\(shallowMetadata.kind) does not match expected \(expectedKind)")
XCTAssert(shallowMetadata.valueWitnessTable.size == sizeof(type))
XCTAssert(shallowMetadata.valueWitnessTable.stride == strideof(type))
}
testShallowMetadata(type: Person.self, expectedKind: .struct)
testShallowMetadata(type: Optional<Person>.self, expectedKind: .optional)
testShallowMetadata(type: (String, Int).self, expectedKind: .tuple)
testShallowMetadata(type: ((String) -> Int).self, expectedKind: .function)
testShallowMetadata(type: Any.self, expectedKind: .existential)
testShallowMetadata(type: String.Type.self, expectedKind: .metatype)
testShallowMetadata(type: Any.Type.self, expectedKind: .existentialMetatype)
testShallowMetadata(type: ReferencePerson.self, expectedKind: .class)
}
func testNominalMetadata() {
func testMetadata<T : NominalType>(metadata: T, expectedName: String) {
XCTAssert(metadata.nominalTypeDescriptor.numberOfFields == 3)
}
if let metadata = Metadata.Struct(type: Person.self) {
testMetadata(metadata: metadata, expectedName: "Person")
} else {
XCTFail()
}
}
func testTupleMetadata() {
guard let metadata = Metadata.Tuple(type: (Int, name: String, Float, age: Int).self) else {
return XCTFail()
}
for (label, expected) in zip(metadata.labels, [nil, "name", nil, "age"] as [String?]) {
XCTAssert(label == expected)
}
}
func testSuperclass() {
guard let metadata = Metadata.Class(type: SubclassedPerson.self) else {
return XCTFail()
}
XCTAssertNotNil(metadata.superclass) // ReferencePerson
}
}
func == (lhs: [Any.Type], rhs: [Any.Type]) -> Bool {
return zip(lhs, rhs).reduce(true) { $1.0 != $1.1 ? false : $0 }
}
extension InternalTests {
public static var allTests: [(String, (InternalTests) -> () throws -> Void)] {
return [
("testShallowMetadata", testShallowMetadata),
("testNominalMetadata", testNominalMetadata),
("testTupleMetadata", testTupleMetadata),
("testSuperclass", testSuperclass),
]
}
}
| mit |
taipingeric/Leet-Code-In-Swift | Example/125.Valid Palindrome.playground/Contents.swift | 1 | 369 | import Foundation
class Solution {
func isPalindrome(s: String) -> Bool {
let lowString = s.lowercaseString
let string = lowString.utf8.filter{ char in
let isaToz = char >= 97 && char <= 122
let is0To9 = char >= 48 && char <= 57
return isaToz || is0To9
}
return string == string.reverse()
}
} | mit |
neonichu/SwiftShell | SwiftShellTests/Files_Tests.swift | 1 | 938 | //
// Files_Tests.swift
// SwiftShell
//
// Created by Kåre Morstøl on 25.11.14.
// Copyright (c) 2014 NotTooBad Software. All rights reserved.
//
import SwiftShell
import XCTest
class Files_Tests: XCTestCase {
func testTempDirectory_IsTheSameAfterRepeatedCalls () {
XCTAssertEqual( tempdirectory, tempdirectory )
}
func testWorkDirectory_IsCurrentDirectory () {
XCTAssertEqual( workdirectory, NSFileManager.defaultManager().currentDirectoryPath )
}
func testWorkDirectory_CanChange () {
workdirectory = "/tmp"
XCTAssertEqual( workdirectory, "/private/tmp" )
XCTAssertEqual( $("pwd"), "/tmp" )
}
func testURLConcatenationOperator () {
XCTAssertEqual( "/directory" / "file.extension", "/directory/file.extension" )
XCTAssertEqual( "/root" / "directory" / "file.extension", "/root/directory/file.extension" )
XCTAssertEqual( "directory" / "file.extension", workdirectory + "/directory/file.extension" )
}
}
| mit |
yangxiaodongcn/iOSAppBase | iOSAppBase/Carthage/Checkouts/XCGLogger/DemoApps/tvOSDemo/tvOSDemo/ViewController.swift | 7 | 1197 | //
// ViewController.swift
// tvOSDemo
//
// Created by Dave Wood on 2015-09-09.
// Copyright © 2015 Cerebral Gardens. All rights reserved.
//
import UIKit
import XCGLogger
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func verboseButtonTapped(_ sender: UIButton) {
log.verbose("Verbose tapped on the TV")
}
@IBAction func debugButtonTapped(_ sender: UIButton) {
log.debug("Debug tapped on the TV")
}
@IBAction func infoButtonTapped(_ sender: UIButton) {
log.info("Info tapped on the TV")
}
@IBAction func warningButtonTapped(_ sender: UIButton) {
log.warning("Warning tapped on the TV")
}
@IBAction func errorButtonTapped(_ sender: UIButton) {
log.error("Error tapped on the TV")
}
@IBAction func severeButtonTapped(_ sender: UIButton) {
log.severe("Severe tapped on the TV")
}
}
| mit |
Pole-he/DOFavoriteButton | DOFavoriteButton-DEMO/DOFavoriteButton-DEMO/AppDelegate.swift | 30 | 2164 | //
// AppDelegate.swift
// DOFavoriteButton-DEMO
//
// Created by Daiki Okumura on 2015/07/09.
// Copyright (c) 2015 Daiki Okumura. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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 |
Breinify/brein-api-library-ios | BreinifyApi/engine/URLSessionEngine.swift | 1 | 13122 | //
// Created by Marco Recchioni
// Copyright (c) 2020 Breinify. All rights reserved.
//
import Foundation
public class URLSessionEngine: IRestEngine {
/// some handy aliases
public typealias apiSuccess = (_ result: BreinResult) -> Void
public typealias apiFailure = (_ error: NSDictionary) -> Void
/**
Configures the rest engine
- parameter breinConfig: configuration object
*/
public func configure(_ breinConfig: BreinConfig) {
}
public func executeSavedRequests() {
BreinLogger.shared.log("Breinify executeSavedRequests invoked")
// 1. loop over entries
// contains a copy of the missedRequests from BreinRequestManager
let missedRequests = BreinRequestManager.shared.getMissedRequests()
BreinLogger.shared.log("Breinify number of elements in queue is: \(missedRequests.count)")
for (uuid, entry) in (missedRequests) {
BreinLogger.shared.log("Breinify working on UUID: \(uuid)")
// 1. is this entry in time range?
let considerEntry = BreinRequestManager.shared.checkIfValid(currentEntry: entry)
if considerEntry == true {
let urlString = entry.fullUrl
let jsonData:String = entry.jsonBody
// 2. send it
var request = URLRequest(url: URL(string: urlString!)!)
request.httpMethod = "POST"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// add the uuid to identify the request on response
request.setValue(uuid, forHTTPHeaderField: "uuid")
request.httpBody = jsonData.data(using: .utf8)
// replace start
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
// success
if let resp = response as? HTTPURLResponse {
let uuidEntryAny = resp.allHeaderFields["uuid"]
if let uuidEntry = uuidEntryAny as? String {
BreinLogger.shared.log("Breinify successfully (resend): \(String(describing: jsonData))")
BreinRequestManager.shared.removeEntry(uuidEntry)
}
}
}
}
task.resume()
// replace end
} else {
BreinLogger.shared.log("Breinify removing from queue: \(uuid)")
BreinRequestManager.shared.removeEntry(uuid)
}
}
}
/**
Invokes the post request for activities
- parameter breinActivity: activity object
- parameter success: will be invoked in case of success
- parameter failure: will be invoked in case of an error
*/
public func doRequest(_ breinActivity: BreinActivity,
success: @escaping apiSuccess,
failure: @escaping apiFailure) throws {
try validate(breinActivity)
let url = try getFullyQualifiedUrl(breinActivity)
let body = try getRequestBody(breinActivity)
var jsonString = ""
var jsonData: Data
do {
jsonData = try JSONSerialization.data(withJSONObject: body as Any, options: [.prettyPrinted])
jsonString = String(data: jsonData, encoding: .utf8) ?? ""
let activity:[String: Any] = body?["activity"] as! [String : Any]
let actTyp:String = activity["type"] as! String
BreinLogger.shared.log("Breinify doRequest for activityType: \(actTyp) -- json is: \(String(describing: jsonString))")
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
BreinLogger.shared.log("Breinify doRequest with error: \(error)")
let canResend = breinActivity.getConfig()?.getResendFailedActivities()
// add for resending later..
if canResend == true {
if let data = data, let dataString = String(data: data, encoding: .utf8) {
BreinLogger.shared.log("Breinify response data string: \(dataString)")
let urlRequest = url
let creationTime = Int(NSDate().timeIntervalSince1970)
// add to BreinRequestManager in case of an error
BreinRequestManager.shared.addMissedRequest(timeStamp: creationTime,
fullUrl: urlRequest, json: dataString)
}
}
let httpError: NSError = error as NSError
let statusCode = httpError.code
let error: NSDictionary = ["error": httpError,
"statusCode": statusCode]
DispatchQueue.main.async {
failure(error)
}
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
// success
let jsonDic: NSDictionary = ["success": 200]
let breinResult = BreinResult(dictResult: jsonDic)
DispatchQueue.main.async {
success(breinResult)
}
}
}
task.resume()
}
/**
Invokes the post request for lookups
- parameter breinLookup: lookup object
- parameter success success: will be invoked in case of success
- parameter failure failure: will be invoked in case of an error
*/
public func doLookup(_ breinLookup: BreinLookup,
success: @escaping apiSuccess,
failure: @escaping apiFailure) throws {
try validate(breinLookup)
let url = try getFullyQualifiedUrl(breinLookup)
let body = try getRequestBody(breinLookup)
var jsonString = ""
var jsonData: Data
do {
jsonData = try JSONSerialization.data(withJSONObject: body as Any, options: [.prettyPrinted])
jsonString = String(data: jsonData, encoding: .utf8) ?? ""
BreinLogger.shared.log("Breinify doLookup - json is: \(String(describing: jsonString))")
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData
// Alamofire.request(url, method: .post,
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
BreinLogger.shared.log("Breinify doLookup with error: \(error)")
let httpError: NSError = error as NSError
let statusCode = httpError.code
let error: NSDictionary = ["error": httpError,
"statusCode": statusCode]
DispatchQueue.main.async {
failure(error)
}
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
// success
let jsonDic: NSDictionary = ["success": 200]
let breinResult = BreinResult(dictResult: jsonDic)
DispatchQueue.main.async {
success(breinResult)
}
}
}
task.resume()
}
/**
Invokes the post request for recommendations
- parameter breinRecommendation: recommendation object
- parameter success: will be invoked in case of success
- parameter failure: will be invoked in case of an error
*/
public func doRecommendation(_ breinRecommendation: BreinRecommendation,
success: @escaping (_ result: BreinResult) -> Void,
failure: @escaping (_ error: NSDictionary) -> Void) throws {
try validate(breinRecommendation)
let url = try getFullyQualifiedUrl(breinRecommendation)
let body = try getRequestBody(breinRecommendation)
var jsonData:Data
do {
jsonData = try! JSONSerialization.data(withJSONObject: body as Any, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
BreinLogger.shared.log("Breinify doRecommendation - json is: \(String(describing: jsonString))")
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData
// Alamofire.request(url, method: .post,
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
BreinLogger.shared.log("Breinify doRecommendation with error: \(error)")
let httpError: NSError = error as NSError
let statusCode = httpError.code
let error: NSDictionary = ["error": httpError,
"statusCode": statusCode]
DispatchQueue.main.async {
failure(error)
}
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
// success
let jsonDic: NSDictionary = ["success": 200]
let breinResult = BreinResult(dictResult: jsonDic)
DispatchQueue.main.async {
success(breinResult)
}
}
}
task.resume()
}
/**
Invokes the post request for temporalData
- parameter breinTemporalData: temporalData object
- parameter success successBlock: will be invoked in case of success
- parameter failure failureBlock: will be invoked in case of an error
*/
public func doTemporalDataRequest(_ breinTemporalData: BreinTemporalData,
success successBlock: @escaping apiSuccess,
failure failureBlock: @escaping apiFailure) throws {
try validate(breinTemporalData)
let url = try getFullyQualifiedUrl(breinTemporalData)
let body = try getRequestBody(breinTemporalData)
var jsonData:Data
do {
jsonData = try! JSONSerialization.data(withJSONObject: body as Any, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
BreinLogger.shared.log("Breinify doTemporalDataRequest - json is: \(String(describing: jsonString))")
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData
// Alamofire.request(url, method: .post,
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
BreinLogger.shared.log("Breinify doTemporalDataRequest with error: \(error)")
let httpError: NSError = error as NSError
let statusCode = httpError.code
let error: NSDictionary = ["error": httpError,
"statusCode": statusCode]
DispatchQueue.main.async {
failureBlock(error)
}
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
// success
let jsonDic: NSDictionary = ["success": 200]
let breinResult = BreinResult(dictResult: jsonDic)
DispatchQueue.main.async {
successBlock(breinResult)
}
}
}
task.resume()
}
/// Terminates whatever would need to be stopped
public func terminate() {
}
}
| mit |
KrishMunot/swift | validation-test/compiler_crashers_fixed/00188-swift-removeshadoweddecls.swift | 11 | 732 | // 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
// RUN: not %target-swift-frontend %s -parse
func b<d-> d { class d:b class b
protocol A {
typealias B
func b(B)
}
struct X<Y> : func l
var _ = l
func f() {
({})
}
func ^(d: e, Bool) -> Bool {g !(d)
}
protocol d {
f func g()
f k }
}
protocol n {
class func q()
}
class o: n{ cla) u p).v.c()
k e.w == l> {
}
func p(c: Any, m: Any) -> (((Any, Any) -> Any) {
| apache-2.0 |
tavultesoft/keymanweb | ios/engine/KMEI/KeymanEngineTests/AppDelegate.swift | 1 | 1133 | //
// AppDelegate.swift
// KeymanEngineTests
//
// Created by Joshua Horton on 2/18/20.
// Copyright © 2020 SIL International. All rights reserved.
//
// This AppDelegate is extremely minimal and is designed solely as an app that provides a nice
// sandboxed location for file-system-oriented testing.
import Foundation
import KeymanEngine
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
return true
}
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
return true
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
FontManager.shared.unregisterCustomFonts()
}
func applicationWillEnterForeground(_ application: UIApplication) {
FontManager.shared.registerCustomFonts()
}
}
| apache-2.0 |
Roommate-App/roomy | roomy/Pods/IBAnimatable/Sources/Protocols/Designable/SideImageDesignable.swift | 3 | 3158 | //
// Created by Jake Lin on 12/8/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
/// Protocol for designing side image
public protocol SideImageDesignable: class {
/**
* The left image
*/
var leftImage: UIImage? { get set }
/**
* Left padding of the left image, default value is CGFloat.nan
*/
var leftImageLeftPadding: CGFloat { get set }
/**
* Right padding of the left image, default value is CGFloat.nan
*/
var leftImageRightPadding: CGFloat { get set }
/**
* Top padding of the left image, default value is CGFloat.nan
*/
var leftImageTopPadding: CGFloat { get set }
/**
* The right image
*/
var rightImage: UIImage? { get set }
/**
* Left padding of the right image, default value is CGFloat.nan
*/
var rightImageLeftPadding: CGFloat { get set }
/**
* Right padding of the right image, default value is CGFloat.nan
*/
var rightImageRightPadding: CGFloat { get set }
/**
* Top padding of the right image, default value is CGFloat.nan
*/
var rightImageTopPadding: CGFloat { get set }
}
public extension SideImageDesignable where Self: UITextField {
public func configureImages() {
configureLeftImage()
configureRightImage()
}
}
fileprivate extension SideImageDesignable where Self: UITextField {
func configureLeftImage() {
guard let leftImage = leftImage else {
return
}
let sideView = makeSideView(with: leftImage,
leftPadding: leftImageLeftPadding,
rightPadding: leftImageRightPadding,
topPadding: leftImageTopPadding)
leftViewMode = .always
leftView = sideView
}
func configureRightImage() {
guard let rightImage = rightImage else {
return
}
let sideView = makeSideView(with: rightImage,
leftPadding: rightImageLeftPadding,
rightPadding: rightImageRightPadding,
topPadding: rightImageTopPadding)
rightViewMode = .always
rightView = sideView
}
func makeSideView(with image: UIImage, leftPadding: CGFloat, rightPadding: CGFloat, topPadding: CGFloat) -> UIView {
let imageView = UIImageView(image: image)
// If not set, use 0 as default value
var leftPaddingValue: CGFloat = 0.0
if !leftPadding.isNaN {
leftPaddingValue = leftPadding
}
// If not set, use 0 as default value
var rightPaddingValue: CGFloat = 0.0
if !rightPadding.isNaN {
rightPaddingValue = rightPadding
}
// If does not specify `topPadding`, then center it in the middle
if topPadding.isNaN {
imageView.frame.origin = CGPoint(x: leftPaddingValue, y: (bounds.height - imageView.bounds.height) / 2)
} else {
imageView.frame.origin = CGPoint(x: leftPaddingValue, y: topPadding)
}
let padding = rightPaddingValue + imageView.bounds.size.width + leftPaddingValue
let sideView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: bounds.height))
sideView.addSubview(imageView)
return sideView
}
}
| mit |
kylestew/p5native.js | p5nativeTests/p5nativeTests.swift | 1 | 981 | //
// p5nativeTests.swift
// p5nativeTests
//
// Created by Kyle Stewart on 12/31/15.
// Copyright © 2015 Kyle Stewart. All rights reserved.
//
import XCTest
@testable import p5native
class p5nativeTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| lgpl-2.1 |
djnivek/Fillio-ios | Fillio/FillioTests/Customer.swift | 1 | 563 | //
// Customer.swift
// Fillio
//
// Created by Kévin MACHADO on 04/05/2015.
// Copyright (c) 2015 Kévin MACHADO. All rights reserved.
//
import Foundation
import Fillio
class Customer: FIOApiObject {
var name: String
var tel: String
init(name: String, tel: String) {
self.name = name
self.tel = tel
super.init()
}
}
extension Customer: FIOApiTransferable {
func modelName() -> String {
return "Model_Customer"
}
func ignoreFields() -> [String]? {
return nil
}
} | gpl-2.0 |
ioscreator/ioscreator | SwiftUIBackgroundColorTutorial/SwiftUIBackgroundColorTutorial/ContentView.swift | 1 | 453 | //
// ContentView.swift
// SwiftUIBackgroundColorTutorial
//
// Created by Arthur Knopper on 28/08/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
Color.red
.edgesIgnoringSafeArea(.all)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| mit |
xiantingxinbu/DouYu-ZhiBo | DouYuZhiBo/DouYuZhiBo/AppDelegate.swift | 1 | 2172 | //
// AppDelegate.swift
// DouYuZhiBo
//
// Created by wang jun on 2017/5/5.
// Copyright © 2017年 wang jun. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
WilliamHester/Breadit-iOS | Breadit/ViewControllers/GifViewController.swift | 1 | 1809 | //
// PreviewViewController.swift
// Breadit
//
// Created by William Hester on 5/30/16.
// Copyright © 2016 William Hester. All rights reserved.
//
import UIKit
import Alamofire
import FLAnimatedImage
class GifViewController: UIViewController {
var imageUrl: String!
private var imageView: FLAnimatedImageView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.8)
imageView = FLAnimatedImageView()
view.addSubview(imageView)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(onTap(_:)))
view.addGestureRecognizer(tapRecognizer)
Alamofire.request(.GET, imageUrl).responseData { response in
let image = FLAnimatedImage(animatedGIFData: response.data)
self.fixFrame(image.size)
self.imageView.animatedImage = image
self.imageView.center = self.view.center
}
}
private func fixFrame(imageSize: CGSize) {
var imageFrame = view.frame
let frameSize = imageFrame.size
let frameAspectRatio = frameSize.width / frameSize.height
let imageAspectRatio = imageSize.width / imageSize.height
if frameAspectRatio > imageAspectRatio {
let heightRatio = frameSize.height / imageSize.height
imageFrame.size.width = heightRatio * imageSize.width
} else {
let widthRatio = frameSize.width / imageSize.width
imageFrame.size.height = widthRatio * imageSize.height
}
imageView.frame = imageFrame
}
func onTap(gestureRecognizer: UITapGestureRecognizer) {
dismissViewControllerAnimated(true, completion: nil)
}
}
| apache-2.0 |
sdduursma/Scenic | Scenic/SceneRetainer.swift | 1 | 551 | import Foundation
class SceneRetainer {
let sceneName: String
let scene: Scene
let children: [SceneRetainer]
init(sceneName: String, scene: Scene, children: [SceneRetainer]) {
self.sceneName = sceneName
self.scene = scene
self.children = children
}
}
extension SceneRetainer {
func sceneRetainer(forSceneName name: String) -> SceneRetainer? {
if sceneName == name {
return self
}
return children.flatMap { $0.sceneRetainer(forSceneName: name) } .first
}
}
| mit |
wj2061/ios7ptl-swift3.0 | ch19-UIDynamics/TearOff/TearOff/AppDelegate.swift | 1 | 2155 | //
// AppDelegate.swift
// TearOff
//
// Created by wj on 15/11/19.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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 |
rockarloz/WatchKit-Apps | 9- Table/WatchKit-table WatchKit Extension/TableRow.swift | 8 | 313 | //
// TableRow.swift
// WatchKit-table
//
// Created by Konstantin Koval on 11/03/15.
// Copyright (c) 2015 Kostiantyn Koval. All rights reserved.
//
import Foundation
import WatchKit
class TableRow: NSObject {
@IBOutlet weak var image: WKInterfaceImage!
@IBOutlet weak var label: WKInterfaceLabel!
}
| mit |
NitWitStudios/NWSExtensions | NWSExtensions/Classes/UINavigationController+Extensions.swift | 1 | 669 | //
// UINavigationController+Extensions.swift
// Bobblehead-TV
//
// Created by James Hickman on 7/30/16.
// Copyright © 2016 NitWit Studios. All rights reserved.
//
import UIKit
import Foundation
extension UINavigationController {
open override var preferredStatusBarStyle : UIStatusBarStyle {
return self.visibleViewController!.preferredStatusBarStyle
}
open override var shouldAutorotate : Bool {
return self.visibleViewController!.shouldAutorotate
}
open override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return self.visibleViewController!.supportedInterfaceOrientations
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers/28525-tok-isany-tok-identifier-tok-kw-self-tok-kw-self-tok-kw-throws.swift | 2 | 439 | // 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
// RUN: not --crash %target-swift-frontend %s -emit-ir
// REQUIRES: asserts
func a<rethrows
| apache-2.0 |
gauuni/iOSProjectTemplate | iOSProjectTemplate/iOSProjectTemplate/Utilities/RootNotification.swift | 1 | 240 | //
// FitnessNotification.swift
// Fitness
//
// Created by Duc Nguyen on 11/11/16.
// Copyright © 2016 Reflect Apps Inc. All rights reserved.
//
import Foundation
extension Notification.Name {
// Define notification name here
}
| mit |
eneko/DSAA | Sources/DataStructures/List.swift | 1 | 4186 | //
// List.swift
// DSAA
//
// Created by Eneko Alonso on 2/11/16.
// Copyright © 2016 Eneko Alonso. All rights reserved.
//
/// List is an Abstract Data Type
///
/// Single linked list implementation
class Item<T> {
var value: T
var next: Item<T>?
init(value: T) {
self.value = value
}
}
public struct List<T: Equatable> : Equatable {
var firstItem: Item<T>?
public mutating func append(element: T) {
guard var item = firstItem else {
firstItem = Item<T>(value: element)
return
}
while true {
guard let next = item.next else {
item.next = Item<T>(value: element)
break
}
item = next
}
}
public mutating func insertAt(index: UInt, element: T) {
if index == 0 {
let newItem = Item<T>(value: element)
newItem.next = firstItem
firstItem = newItem
} else if let item = itemAt(index - 1) {
let newItem = Item<T>(value: element)
newItem.next = item.next
item.next = newItem
}
}
public func first() -> T? {
return firstItem?.value
}
public func last() -> T? {
guard var item = firstItem else {
return nil
}
var value: T? = nil
while true {
guard let next = item.next else {
value = item.value
break
}
item = next
}
return value
}
func itemAt(index: UInt) -> Item<T>? {
var current: UInt = 0
var item = firstItem
while current < index {
guard let next = item?.next else {
return nil
}
item = next
current++
}
return item
}
public func elementAt(index: UInt) -> T? {
return itemAt(index)?.value
}
public mutating func removeFirst() -> T? {
let value = firstItem?.value
firstItem = firstItem?.next
return value
}
public mutating func removeLast() -> T? {
if firstItem?.next == nil {
let value = firstItem?.value
firstItem = nil
return value
}
var item = firstItem
var value: T? = nil
while true {
if item?.next?.next == nil {
value = item?.next?.value
item?.next = nil
break
}
item = item?.next
}
return value
}
public mutating func removeAt(index: UInt) -> T? {
if index == 0 {
return removeFirst()
}
let item = itemAt(index - 1)
let value = item?.next?.value
item?.next = item?.next?.next
return value
}
public func count() -> UInt {
guard var item = firstItem else {
return 0
}
var count: UInt = 1
while true {
guard let next = item.next else {
break
}
item = next
count++
}
return count
}
public func isEmpty() -> Bool {
return count() == 0
}
public mutating func reverse() {
guard let item = firstItem else {
return
}
var head = item
while true {
guard let next = item.next else {
firstItem = head
break
}
item.next = next.next
next.next = head
head = next
}
}
public func copy() -> List<T> {
var newList = List<T>()
var item = firstItem
while let value = item?.value {
newList.append(value)
item = item?.next
}
return newList
}
}
public func == <T: Equatable> (lhs: List<T>, rhs: List<T>) -> Bool {
let leftCount = lhs.count()
let rightCount = rhs.count()
if leftCount != rightCount {
return false
}
for i in 0..<leftCount {
if lhs.elementAt(i) != rhs.elementAt(i) {
return false
}
}
return true
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/16975-swift-sourcemanager-getmessage.swift | 11 | 279 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let h = [ {
}
{
}
{
{
}
{
}
{
{
}
}
class a {
{
}
{
{
{ {
}
}
}
}
{
{
}
}
{
}
{
}
{
}
struct B {
class
case ,
| mit |
huangboju/Moots | Examples/SwiftUI/Scrumdinger/Scrumdinger/Models/ScrumTimer.swift | 1 | 3501 | //
// ScrumTimer.swift
// Scrumdinger
//
// Created by jourhuang on 2021/1/3.
//
import Foundation
class ScrumTimer: ObservableObject {
struct Speaker: Identifiable {
let name: String
var isCompleted: Bool
let id = UUID()
}
@Published var activeSpeaker = ""
@Published var secondsElapsed = 0
@Published var secondsRemaining = 0
@Published var speakers: [Speaker] = []
var lengthInMinutes: Int
var speakerChangedAction: (() -> Void)?
private var timer: Timer?
private var timerStopped = false
private var frequency: TimeInterval { 1.0 / 60.0 }
private var lengthInSeconds: Int { lengthInMinutes * 60 }
private var secondsPerSpeaker: Int {
(lengthInMinutes * 60) / speakers.count
}
private var secondsElapsedForSpeaker: Int = 0
private var speakerIndex: Int = 0
private var speakerText: String {
return "Speaker \(speakerIndex + 1): " + speakers[speakerIndex].name
}
private var startDate: Date?
init(lengthInMinutes: Int = 0, attendees: [String] = []) {
self.lengthInMinutes = lengthInMinutes
self.speakers = attendees.isEmpty ? [Speaker(name: "Player 1", isCompleted: false)] : attendees.map { Speaker(name: $0, isCompleted: false) }
secondsRemaining = lengthInSeconds
activeSpeaker = speakerText
}
func startScrum() {
changeToSpeaker(at: 0)
}
func stopScrum() {
timer?.invalidate()
timer = nil
timerStopped = true
}
func skipSpeaker() {
changeToSpeaker(at: speakerIndex + 1)
}
private func changeToSpeaker(at index: Int) {
if index > 0 {
let previousSpeakerIndex = index - 1
speakers[previousSpeakerIndex].isCompleted = true
}
secondsElapsedForSpeaker = 0
guard index < speakers.count else { return }
speakerIndex = index
activeSpeaker = speakerText
secondsElapsed = index * secondsPerSpeaker
secondsRemaining = lengthInSeconds - secondsElapsed
startDate = Date()
timer = Timer.scheduledTimer(withTimeInterval: frequency, repeats: true) { [weak self] timer in
if let self = self, let startDate = self.startDate {
let secondsElapsed = Date().timeIntervalSince1970 - startDate.timeIntervalSince1970
self.update(secondsElapsed: Int(secondsElapsed))
}
}
}
private func update(secondsElapsed: Int) {
secondsElapsedForSpeaker = secondsElapsed
self.secondsElapsed = secondsPerSpeaker * speakerIndex + secondsElapsedForSpeaker
guard secondsElapsed <= secondsPerSpeaker else {
return
}
secondsRemaining = max(lengthInSeconds - self.secondsElapsed, 0)
guard !timerStopped else { return }
if secondsElapsedForSpeaker >= secondsPerSpeaker {
changeToSpeaker(at: speakerIndex + 1)
speakerChangedAction?()
}
}
func reset(lengthInMinutes: Int, attendees: [String]) {
self.lengthInMinutes = lengthInMinutes
self.speakers = attendees.isEmpty ? [Speaker(name: "Player 1", isCompleted: false)] : attendees.map { Speaker(name: $0, isCompleted: false) }
secondsRemaining = lengthInSeconds
activeSpeaker = speakerText
}
}
extension DailyScrum {
var timer: ScrumTimer {
ScrumTimer(lengthInMinutes: lengthInMinutes, attendees: attendees)
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.