repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gerardogrisolini/Webretail
|
refs/heads/master
|
Sources/Webretail/Models/Product.swift
|
apache-2.0
|
1
|
//
// Product.swift
// Webretail
//
// Created by Gerardo Grisolini on 17/02/17.
//
//
import Foundation
import StORM
class Product: PostgresSqlORM, Codable {
public var productId : Int = 0
public var brandId : Int = 0
public var productCode : String = ""
public var productName : String = ""
//public var productType : String = ""
public var productTax : Tax = Tax()
public var productUm : String = ""
public var productPrice : Price = Price()
public var productDiscount : Discount = Discount()
public var productPackaging : Packaging = Packaging()
public var productDescription: [Translation] = [Translation]()
public var productMedias: [Media] = [Media]()
public var productSeo : Seo = Seo()
public var productIsActive : Bool = false
public var productIsValid : Bool = false
public var productCreated : Int = Int.now()
public var productUpdated : Int = Int.now()
public var productAmazonUpdated : Int = 0
public var _brand: Brand = Brand()
public var _categories: [ProductCategory] = [ProductCategory]()
public var _attributes: [ProductAttribute] = [ProductAttribute]()
public var _articles: [Article] = [Article]()
private enum CodingKeys: String, CodingKey {
case productId
case brandId
case productCode
case productName
//case productType
case productTax
case productUm
case productPrice = "price"
case productDiscount = "discount"
case productPackaging = "packaging"
case productDescription = "translations"
case productMedias = "medias"
case productSeo = "seo"
case productIsActive
case _brand = "brand"
case _categories = "categories"
case _attributes = "attributes"
case _articles = "articles"
case productUpdated = "updatedAt"
}
open override func table() -> String { return "products" }
open override func tableIndexes() -> [String] { return ["productCode", "productName"] }
open override func to(_ this: StORMRow) {
productId = this.data["productid"] as? Int ?? 0
brandId = this.data["brandid"] as? Int ?? 0
productCode = this.data["productcode"] as? String ?? ""
productName = this.data["productname"] as? String ?? ""
//productType = this.data["producttype"] as? String ?? ""
productUm = this.data["productum"] as? String ?? ""
let decoder = JSONDecoder()
var jsonData: Data
if let price = this.data["productprice"] {
jsonData = try! JSONSerialization.data(withJSONObject: price, options: [])
productPrice = try! decoder.decode(Price.self, from: jsonData)
}
if let discount = this.data["productdiscount"] {
jsonData = try! JSONSerialization.data(withJSONObject: discount, options: [])
productDiscount = try! decoder.decode(Discount.self, from: jsonData)
}
if let packaging = this.data["productpackaging"] {
jsonData = try! JSONSerialization.data(withJSONObject: packaging, options: [])
productPackaging = try! decoder.decode(Packaging.self, from: jsonData)
}
if let tax = this.data["producttax"] {
jsonData = try! JSONSerialization.data(withJSONObject: tax, options: [])
productTax = try! decoder.decode(Tax.self, from: jsonData)
}
if let descriptions = this.data["productdescription"] {
jsonData = try! JSONSerialization.data(withJSONObject: descriptions, options: [])
productDescription = try! decoder.decode([Translation].self, from: jsonData)
}
if let medias = this.data["productmedias"] {
jsonData = try! JSONSerialization.data(withJSONObject: medias, options: [])
productMedias = try! decoder.decode([Media].self, from: jsonData)
}
if let seo = this.data["productseo"] {
jsonData = try! JSONSerialization.data(withJSONObject: seo, options: [])
productSeo = try! decoder.decode(Seo.self, from: jsonData)
}
productIsActive = this.data["productisactive"] as? Bool ?? false
productIsValid = this.data["productisvalid"] as? Bool ?? false
productCreated = this.data["productcreated"] as? Int ?? 0
productUpdated = this.data["productupdated"] as? Int ?? 0
productAmazonUpdated = this.data["productamazonupdated"] as? Int ?? 0
_brand.to(this)
}
func rows(barcodes: Bool, storeIds: String = "0") throws -> [Product] {
var rows = [Product]()
for i in 0..<self.results.rows.count {
let row = Product()
row.to(self.results.rows[i])
try row.makeCategories();
if barcodes {
try row.makeAttributes();
try row.makeArticles(storeIds);
}
rows.append(row)
}
return rows
}
override init() {
super.init()
}
required init(from decoder: Decoder) throws {
super.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
productId = try container.decode(Int.self, forKey: .productId)
productCode = try container.decode(String.self, forKey: .productCode)
productName = try container.decode(String.self, forKey: .productName)
productDescription = try container.decodeIfPresent([Translation].self, forKey: .productDescription) ?? [Translation]()
//productType = try container.decode(String.self, forKey: .productType)
productUm = try container.decode(String.self, forKey: .productUm)
productTax = try container.decodeIfPresent(Tax.self, forKey: .productTax) ?? Tax()
productPrice = try container.decodeIfPresent(Price.self, forKey: .productPrice) ?? Price()
productDiscount = try container.decodeIfPresent(Discount.self, forKey: .productDiscount) ?? Discount()
productPackaging = try container.decodeIfPresent(Packaging.self, forKey: .productPackaging) ?? Packaging()
productMedias = try container.decodeIfPresent([Media].self, forKey: .productMedias) ?? [Media]()
productSeo = try container.decodeIfPresent(Seo.self, forKey: .productSeo) ?? Seo()
productIsActive = try container.decode(Bool.self, forKey: .productIsActive)
_brand = try container.decodeIfPresent(Brand.self, forKey: ._brand) ?? Brand()
brandId = try container.decodeIfPresent(Int.self, forKey: .brandId) ?? _brand.brandId
_categories = try container.decodeIfPresent([ProductCategory].self, forKey: ._categories) ?? [ProductCategory]()
_attributes = try container.decodeIfPresent([ProductAttribute].self, forKey: ._attributes) ?? [ProductAttribute]()
_articles = try container.decodeIfPresent([Article].self, forKey: ._articles) ?? [Article]()
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(productId, forKey: .productId)
try container.encode(productCode, forKey: .productCode)
try container.encode(productName, forKey: .productName)
try container.encode(productDescription, forKey: .productDescription)
//try container.encode(productType, forKey: .productType)
try container.encode(productUm, forKey: .productUm)
try container.encode(productTax, forKey: .productTax)
try container.encode(productPrice, forKey: .productPrice)
try container.encode(productDiscount, forKey: .productDiscount)
try container.encode(productPackaging, forKey: .productPackaging)
try container.encode(productMedias, forKey: .productMedias)
try container.encode(productSeo, forKey: .productSeo)
try container.encode(productIsActive, forKey: .productIsActive)
try container.encode(_brand, forKey: ._brand)
try container.encode(_categories, forKey: ._categories)
try container.encode(_attributes, forKey: ._attributes)
try container.encode(_articles, forKey: ._articles)
try container.encode(productUpdated, forKey: .productUpdated)
}
func makeCategories() throws {
var categoryJoin = StORMDataSourceJoin()
categoryJoin.table = "categories"
categoryJoin.direction = StORMJoinType.INNER
categoryJoin.onCondition = "productcategories.categoryId = categories.categoryId"
let productCategory = ProductCategory()
try productCategory.query(
whereclause: "productcategories.productId = $1",
params: [self.productId],
orderby: ["categories.categoryId"],
joins: [categoryJoin]
)
self._categories = try productCategory.rows()
}
func addDefaultAttributes() throws {
let productAttribute = ProductAttribute()
productAttribute.productId = self.productId
let attribute = Attribute()
attribute.attributeName = "None"
productAttribute._attribute = attribute
let productAttributeValue = ProductAttributeValue()
let attributeValue = AttributeValue()
attributeValue.attributeValueName = "None"
productAttributeValue._attributeValue = attributeValue
productAttribute._attributeValues = [productAttributeValue]
self._attributes.append(productAttribute)
}
func makeAttributes() throws {
var attributeJoin = StORMDataSourceJoin()
attributeJoin.table = "attributes"
attributeJoin.direction = StORMJoinType.INNER
attributeJoin.onCondition = "productattributes.attributeId = attributes.attributeId"
let productAttribute = ProductAttribute()
try productAttribute.query(
whereclause: "productattributes.productId = $1",
params: [self.productId],
orderby: ["productattributes.productAttributeId"],
joins: [attributeJoin]
)
self._attributes = try productAttribute.rows()
}
func makeArticles(_ storeIds: String = "0") throws {
let article = Article()
article._storeIds = storeIds
try article.query(
whereclause: "productId = $1",
params: [self.productId],
orderby: ["articleId"]
)
self._articles = try article.rows()
}
func makeArticle(barcode: String) throws {
let article = Article()
article.to(self.results.rows[0])
let attributeValue = ArticleAttributeValue()
attributeValue.results = self.results
article._attributeValues = try attributeValue.rows()
self._articles = [article]
}
func get(barcode: String) throws {
let brandJoin = StORMDataSourceJoin(
table: "brands",
onCondition: "products.brandId = brands.brandId",
direction: StORMJoinType.INNER
)
let articleJoin = StORMDataSourceJoin(
table: "articles",
onCondition: "products.productId = articles.productId",
direction: StORMJoinType.INNER
)
let articleAttributeJoin = StORMDataSourceJoin(
table: "articleattributevalues",
onCondition: "articleattributevalues.articleId = articles.articleId",
direction: StORMJoinType.LEFT
)
let param = """
[{"barcode": "\(barcode)"}]
"""
try query(whereclause: "articles.articleBarcodes @> $1::jsonb",
params: [param],
orderby: ["articleattributevalues.articleAttributeValueId"],
joins: [brandJoin, articleJoin, articleAttributeJoin])
if self.results.rows.count == 0 {
return
}
self.to(self.results.rows[0])
try self.makeCategories()
try self.makeAttributes()
try self.makeArticle(barcode: barcode)
}
}
|
9659853f2cde19ec2c1592882b03cfb6
| 41.336957 | 126 | 0.657766 | false | false | false | false |
Lisapple/Closer
|
refs/heads/master
|
Closer WatchKit Extension/ComplicationController.swift
|
mit
|
1
|
//
// ComplicationDataSourceController.swift
// Closer
//
// Created by Max on 02/10/15.
//
//
import ClockKit
import WatchConnectivity
class ComplicationController: NSObject, CLKComplicationDataSource, WCSessionDelegate {
fileprivate var countdown: Countdown?
override init() {
super.init()
let session = WCSession.default()
session.delegate = self
session.activate()
let userDefaults = UserDefaults(suiteName: "group.lisacintosh.closer")!
let glanceType = GlanceType(string: userDefaults.string(forKey: "glance_type"))
countdown = Countdown.with(glanceType)
}
func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) {
handler(.forward)
}
func templateForComplication(_ complication: CLKComplication, date: Date?) -> CLKComplicationTemplate? {
let text = (self.countdown != nil) ? self.countdown!.shortRemainingDescription(forDate: date) : "--"
let textProvider = CLKSimpleTextProvider(text: text, shortText: self.countdown?.shortestRemainingDescription(forDate: date))
let progression: Float = (self.countdown != nil) ? Float(self.countdown!.progression(atDate: date)) : 0
var template: CLKComplicationTemplate?
switch complication.family {
case .circularSmall:
let aTemplate = CLKComplicationTemplateCircularSmallRingText()
aTemplate.ringStyle = .closed
aTemplate.fillFraction = progression
aTemplate.textProvider = textProvider
template = aTemplate
break
case .modularSmall:
let aTemplate = CLKComplicationTemplateModularSmallRingText()
aTemplate.ringStyle = .closed
aTemplate.fillFraction = progression
aTemplate.textProvider = textProvider
template = aTemplate
break
case .modularLarge: break // @TODO: Support it
case .utilitarianSmall:
let aTemplate = CLKComplicationTemplateUtilitarianSmallRingText()
aTemplate.ringStyle = .closed
aTemplate.fillFraction = progression
aTemplate.textProvider = textProvider
template = aTemplate
break
case .utilitarianLarge, .extraLarge, .utilitarianSmallFlat: break // Not supported now
}
return template
}
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
if let template = templateForComplication(complication, date: nil) {
let entry = CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template)
handler(entry)
} else {
handler(nil)
}
}
func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(Date())
}
func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
handler(countdown?.endDate as Date?)
}
func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int,
withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
handler(nil)
}
func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int,
withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
if (countdown?.endDate != nil) {
var timeInterval: TimeInterval = 0
var entries = [CLKComplicationTimelineEntry]()
for _ in 0 ..< limit {
let nextDate = Date(timeIntervalSinceNow: timeInterval)
if (nextDate.timeIntervalSince(countdown!.endDate!) >= 0) {
break
}
let template = templateForComplication(complication, date: nextDate)
let entry = CLKComplicationTimelineEntry(date: nextDate, complicationTemplate: template!)
timeInterval += countdown!.timeIntervalForNextUpdate(forDate: nextDate)
entries.append(entry)
}
handler(entries)
} else {
handler(nil)
}
}
func getPlaceholderTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
let template = templateForComplication(complication, date: nil)
handler(template)
}
@available(watchOSApplicationExtension 2.2, *)
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { }
}
|
ebe275e29bd103e780ccb0ee0c623b93
| 35.689655 | 153 | 0.743186 | false | false | false | false |
PureSwift/Bluetooth
|
refs/heads/master
|
Sources/BluetoothHCI/LowEnergyRfTxPathCompensationValue.swift
|
mit
|
1
|
//
// LowEnergyRfTxPathCompensationValue.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
/// RF_Tx_Path_Compensation_Value
///
/// Size: 2 Octets (signed integer)
/// Range: -128.0 dB (0xFB00) ≤ N ≤ 128.0 dB (0x0500)
/// Units: 0.1 dB
@frozen
public struct LowEnergyRfTxPathCompensationValue: RawRepresentable, Equatable, Hashable, Comparable {
public static let min = LowEnergyRfTxPathCompensationValue(-128)
public static let max = LowEnergyRfTxPathCompensationValue(128)
public let rawValue: Int16
public init?(rawValue: Int16) {
guard rawValue >= LowEnergyRfTxPathCompensationValue.min.rawValue,
rawValue <= LowEnergyRfTxPathCompensationValue.max.rawValue
else { return nil }
assert((LowEnergyRfTxPathCompensationValue.min.rawValue ... LowEnergyRfTxPathCompensationValue.max.rawValue).contains(rawValue))
self.rawValue = rawValue
}
// Private, unsafe
private init(_ rawValue: Int16) {
self.rawValue = rawValue
}
// Comparable
public static func < (lhs: LowEnergyRfTxPathCompensationValue, rhs: LowEnergyRfTxPathCompensationValue) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
|
aff9da6b5065f262a69b5ffadca986ef
| 29.409091 | 136 | 0.675635 | false | false | false | false |
LQJJ/demo
|
refs/heads/master
|
86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/controller/DZMReadAuxiliary.swift
|
apache-2.0
|
1
|
//
// DZMReadAuxiliary.swift
// DZMeBookRead
//
// Created by 邓泽淼 on 2017/12/7.
// Copyright © 2017年 DZM. All rights reserved.
//
import UIKit
class DZMReadAuxiliary: NSObject {
/// 获得触摸位置文字的Location
///
/// - Parameters:
/// - point: 触摸位置
/// - frameRef: CTFrame
/// - Returns: 触摸位置的Index
@objc class func GetTouchLocation(point:CGPoint, frameRef:CTFrame?) ->CFIndex {
var location:CFIndex = -1
let line = GetTouchLine(point: point, frameRef: frameRef)
if line != nil {
location = CTLineGetStringIndexForPosition(line!, point)
}
return location
}
/// 获得触摸位置那一行文字的Range
///
/// - Parameters:
/// - point: 触摸位置
/// - frameRef: CTFrame
/// - Returns: CTLine
@objc class func GetTouchLineRange(point:CGPoint, frameRef:CTFrame?) ->NSRange {
var range:NSRange = NSMakeRange(NSNotFound, 0)
let line = GetTouchLine(point: point, frameRef: frameRef)
if line != nil {
let lineRange = CTLineGetStringRange(line!)
range = NSMakeRange(lineRange.location == kCFNotFound ? NSNotFound : lineRange.location, lineRange.length)
}
return range
}
/// 获得触摸位置在哪一行
///
/// - Parameters:
/// - point: 触摸位置
/// - frameRef: CTFrame
/// - Returns: CTLine
@objc class func GetTouchLine(point:CGPoint, frameRef:CTFrame?) ->CTLine? {
var line:CTLine? = nil
if frameRef == nil { return line }
let frameRef:CTFrame = frameRef!
let path:CGPath = CTFrameGetPath(frameRef)
let bounds:CGRect = path.boundingBox
let lines:[CTLine] = CTFrameGetLines(frameRef) as! [CTLine]
if lines.isEmpty { return line }
let lineCount = lines.count
let origins = malloc(lineCount * MemoryLayout<CGPoint>.size).assumingMemoryBound(to: CGPoint.self)
CTFrameGetLineOrigins(frameRef, CFRangeMake(0, 0), origins)
for i in 0..<lineCount {
let origin:CGPoint = origins[i]
let tempLine:CTLine = lines[i]
var lineAscent:CGFloat = 0
var lineDescent:CGFloat = 0
var lineLeading:CGFloat = 0
CTLineGetTypographicBounds(tempLine, &lineAscent, &lineDescent, &lineLeading)
let lineWidth:CGFloat = bounds.width
let lineheight:CGFloat = lineAscent + lineDescent + lineLeading
var lineFrame = CGRect(x: origin.x, y: bounds.height - origin.y - lineAscent, width: lineWidth, height: lineheight)
lineFrame = lineFrame.insetBy(dx: -DZMSpace_1, dy: -DZMSpace_6)
if lineFrame.contains(point) {
line = tempLine
break
}
}
free(origins)
return line
}
/// 通过 range 返回字符串所覆盖的位置 [CGRect]
///
/// - Parameter range: NSRange
/// - Parameter frameRef: CTFrame
/// - Parameter content: 内容字符串(有值则可以去除选中每一行区域内的 开头空格 - 尾部换行符 - 所占用的区域,不传默认返回每一行实际占用区域)
/// - Returns: 覆盖位置
@objc class func GetRangeRects(range:NSRange, frameRef:CTFrame?, content:String? = nil) -> [CGRect] {
var rects:[CGRect] = []
if frameRef == nil { return rects }
if range.length == 0 || range.location == NSNotFound { return rects }
let frameRef = frameRef!
let lines:[CTLine] = CTFrameGetLines(frameRef) as! [CTLine]
if lines.isEmpty { return rects }
let lineCount:Int = lines.count
let origins = malloc(lineCount * MemoryLayout<CGPoint>.size).assumingMemoryBound(to: CGPoint.self)
CTFrameGetLineOrigins(frameRef, CFRangeMake(0, 0), origins)
for i in 0..<lineCount {
let line:CTLine = lines[i]
let lineCFRange = CTLineGetStringRange(line)
let lineRange = NSMakeRange(lineCFRange.location == kCFNotFound ? NSNotFound : lineCFRange.location, lineCFRange.length)
var contentRange:NSRange = NSMakeRange(NSNotFound, 0)
if (lineRange.location + lineRange.length) > range.location && lineRange.location < (range.location + range.length) {
contentRange.location = max(lineRange.location, range.location)
let end = min(lineRange.location + lineRange.length, range.location + range.length)
contentRange.length = end - contentRange.location
}
if contentRange.length > 0 {
// 去掉 -> 开头空格 - 尾部换行符 - 所占用的区域
if content != nil && !content!.isEmpty {
let tempContent:String = content!.substring(contentRange)
let spaceRanges:[NSTextCheckingResult] = tempContent.matches(pattern: "\\s\\s")
if !spaceRanges.isEmpty {
let spaceRange = spaceRanges.first!.range
contentRange = NSMakeRange(contentRange.location + spaceRange.length, contentRange.length - spaceRange.length)
}
let enterRanges:[NSTextCheckingResult] = tempContent.matches(pattern: "\\n")
if !enterRanges.isEmpty {
let enterRange = enterRanges.first!.range
contentRange = NSMakeRange(contentRange.location, contentRange.length - enterRange.length)
}
}
// 正常使用(如果不需要排除段头空格跟段尾换行符可将上面代码删除)
let xStart:CGFloat = CTLineGetOffsetForStringIndex(line, contentRange.location, nil)
let xEnd:CGFloat = CTLineGetOffsetForStringIndex(line, contentRange.location + contentRange.length, nil)
let origin:CGPoint = origins[i]
var lineAscent:CGFloat = 0
var lineDescent:CGFloat = 0
var lineLeading:CGFloat = 0
CTLineGetTypographicBounds(line, &lineAscent, &lineDescent, &lineLeading)
let contentRect:CGRect = CGRect(x: origin.x + xStart, y: origin.y - lineDescent, width: fabs(xEnd - xStart), height: lineAscent + lineDescent + lineLeading)
rects.append(contentRect)
}
}
free(origins)
return rects
}
/// 通过 range 获得合适的 MenuRect
///
/// - Parameter rects: [CGRect]
/// - Parameter frameRef: CTFrame
/// - Parameter viewFrame: 目标ViewFrame
/// - Parameter content: 内容字符串
/// - Returns: MenuRect
@objc class func GetMenuRect(range:NSRange, frameRef:CTFrame?, viewFrame:CGRect, content:String? = nil) ->CGRect {
let rects = GetRangeRects(range: range, frameRef: frameRef, content: content)
return GetMenuRect(rects: rects, viewFrame: viewFrame)
}
/// 通过 [CGRect] 获得合适的 MenuRect
///
/// - Parameter rects: [CGRect]
/// - Parameter viewFrame: 目标ViewFrame
/// - Returns: MenuRect
@objc class func GetMenuRect(rects:[CGRect], viewFrame:CGRect) ->CGRect {
var menuRect:CGRect = CGRect.zero
if rects.isEmpty { return menuRect }
if rects.count == 1 {
menuRect = rects.first!
}else{
menuRect = rects.first!
let count = rects.count
for i in 1..<count {
let rect = rects[i]
let minX = min(menuRect.origin.x, rect.origin.x)
let maxX = max(menuRect.origin.x + menuRect.size.width, rect.origin.x + rect.size.width)
let minY = min(menuRect.origin.y, rect.origin.y)
let maxY = max(menuRect.origin.y + menuRect.size.height, rect.origin.y + rect.size.height)
menuRect.origin.x = minX
menuRect.origin.y = minY
menuRect.size.width = maxX - minX
menuRect.size.height = maxY - minY
}
}
menuRect.origin.y = viewFrame.height - menuRect.origin.y - menuRect.size.height
return menuRect
}
/// 获取行高
///
/// - Parameter line: CTLine
/// - Returns: 行高
@objc class func GetLineHeight(frameRef:CTFrame?) ->CGFloat {
if frameRef == nil { return 0 }
let frameRef:CTFrame = frameRef!
let lines:[CTLine] = CTFrameGetLines(frameRef) as! [CTLine]
if lines.isEmpty { return 0 }
return GetLineHeight(line: lines.first)
}
/// 获取行高
///
/// - Parameter line: CTLine
/// - Returns: 行高
@objc class func GetLineHeight(line:CTLine?) ->CGFloat {
if line == nil { return 0 }
var lineAscent:CGFloat = 0
var lineDescent:CGFloat = 0
var lineLeading:CGFloat = 0
CTLineGetTypographicBounds(line!, &lineAscent, &lineDescent, &lineLeading)
return lineAscent + lineDescent + lineLeading
}
}
|
4269edf61cd048436ff56d3fa2ea8704
| 30.215873 | 172 | 0.526289 | false | false | false | false |
lixiangzhou/ZZSwiftTool
|
refs/heads/master
|
ZZSwiftTool/ZZSwiftTool/ZZCustom/ZZButton.swift
|
mit
|
1
|
//
// ZZButton.swift
// ZZSwiftTool
//
// Created by lixiangzhou on 17/3/12.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
/// 可以调整图片位置的按钮
open class ZZImagePositionButton: UIButton {
enum ZZImagePosition {
case left, right
case none // 默认,不调整左中右的间距
}
private var leftPadding: CGFloat = 0
private var middlePadding: CGFloat = 0
private var rightPadding: CGFloat = 0
private var imgPosition: ZZImagePosition = .none
override open func layoutSubviews() {
super.layoutSubviews()
if imgPosition == .left {
self.imageView?.zz_x = leftPadding
self.titleLabel?.zz_x = (self.imageView?.zz_width ?? 0) + leftPadding + middlePadding
self.titleLabel?.zz_width = self.zz_width - (self.imageView?.zz_width ?? 0) - leftPadding - middlePadding - rightPadding
} else if imgPosition == .right {
self.titleLabel?.zz_x = leftPadding
let imgX = self.zz_width - (self.imageView?.zz_width ?? 0) - rightPadding
self.imageView?.zz_x = imgX
self.titleLabel?.zz_width = imgX - leftPadding - middlePadding
}
}
convenience init(title: String? = nil,
titleSize: CGFloat = 12,
titleColor: UIColor = UIColor.darkText,
imageName: String? = nil,
hilightedImageName: String? = nil,
selectedImageName: String? = nil,
backgroundImageName: String? = nil,
hilightedBackgroundImageName: String? = nil,
selectedBackgroundImageName: String? = nil,
backgroundColor: UIColor? = nil,
target: Any? = nil,
action: Selector? = nil,
imgPosition: ZZImagePosition = .none,
leftPadding: CGFloat = 0,
middlePadding: CGFloat = 0,
rightPadding: CGFloat = 0) {
self.init(title: title,
titleSize: titleSize,
titleColor: titleColor,
imageName: imageName,
hilightedImageName: hilightedImageName,
selectedImageName: selectedImageName,
backgroundImageName: backgroundImageName,
hilightedBackgroundImageName: hilightedBackgroundImageName,
selectedBackgroundImageName: selectedBackgroundImageName,
backgroundColor: backgroundColor,
target: target,
action: action)
self.imgPosition = imgPosition
self.leftPadding = leftPadding
self.rightPadding = rightPadding
self.middlePadding = middlePadding
if imgPosition != .none {
self.zz_width += leftPadding + rightPadding + middlePadding
}
}
}
|
1f4f7111236f4a7ed46ede8f5c3378ad
| 35.349398 | 132 | 0.55121 | false | false | false | false |
StormXX/SideBarDemos
|
refs/heads/master
|
SideBarWithScrollView/SideBarWithScrollView/LeftViewController.swift
|
mit
|
1
|
//
// LeftViewController.swift
// SideBarWithScrollView
//
// Created by DangGu on 15/9/15.
// Copyright © 2015年 Donggu. All rights reserved.
//
import UIKit
let catogaryCellIdentifier = "catogaryCell"
class LeftViewController: UIViewController {
@IBOutlet var tableView: UITableView! {
didSet {
tableView.backgroundColor = UIColor(red: 255.0/255.0, green: 191.0/255.0, blue: 0, alpha: 1.0)
tableView.tableFooterView = UIView()
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "类别"
// 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.
}
*/
}
extension LeftViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(catogaryCellIdentifier, forIndexPath: indexPath)
if indexPath.row == 0 {
cell.textLabel?.text = "エリザベス"
} else {
cell.textLabel?.text = "さだはる"
}
cell.backgroundColor = UIColor.clearColor()
return cell
}
}
extension LeftViewController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44.0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
|
86c293398c198fd23a696f332c645d21
| 29.821918 | 111 | 0.671854 | false | false | false | false |
jihun-kang/ios_a2big_sdk
|
refs/heads/master
|
A2bigSDK/FunSeasonData.swift
|
apache-2.0
|
1
|
//
// FunSeasonData.swift
// nextpage
//
// Created by a2big on 2016. 11. 12..
// Copyright © 2016년 a2big. All rights reserved.
//
//import SwiftyJSON
public class FunSeasonData {
public var season_no: String!
public var season_name: String!
public var media_no: String!
public var character_no: String!
public var season_ment: String!
public var is_character:String!
// public var is_ment:String!
public var imageArr:[JSON]
required public init(json: JSON, baseUrl:String) {
season_no = json["season_no"].stringValue
season_name = json["season_name"].stringValue
media_no = baseUrl+json["media_no"].stringValue.replacingOccurrences(of: "./", with: "")
imageArr = json["image_list"].arrayValue
character_no = json["character_no"].stringValue
season_ment = json["season_ment"].stringValue
is_character = json["is_character"].stringValue
// is_ment = json["is_ment"].stringValue
}
}
|
4c41266fb4f09f4514155b9b72378741
| 27.054054 | 96 | 0.625241 | false | false | false | false |
tensorflow/swift-models
|
refs/heads/main
|
Support/Text/Tokenization.swift
|
apache-2.0
|
1
|
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import TensorFlow
/// Returns a 3-D attention mask that correspond to the 2-D mask of the provided text batch.
///
/// - Parameters:
/// - text: Text batch for which to create an attention mask. `input.mask` has shape
/// `[batchSize, sequenceLength]`.
///
/// - Returns: Attention mask with shape `[batchSize, sequenceLength, sequenceLength]`.
public func createAttentionMask(forTextBatch text: TextBatch) -> Tensor<Float> {
let batchSize = text.tokenIds.shape[0]
let fromSequenceLength = text.tokenIds.shape[1]
let toSequenceLength = text.mask.shape[1]
let reshapedMask = Tensor<Float>(text.mask.reshaped(to: [batchSize, 1, toSequenceLength]))
// We do not assume that `input.tokenIds` is a mask. We do not actually care if we attend
// *from* padding tokens (only *to* padding tokens) so we create a tensor of all ones.
let broadcastOnes = Tensor<Float>(ones: [batchSize, fromSequenceLength, 1], on: text.mask.device)
// We broadcast along two dimensions to create the mask.
return broadcastOnes * reshapedMask
}
/// Vocabulary that can be used for tokenizing strings.
public struct Vocabulary {
internal let tokensToIds: [String: Int]
internal let idsToTokens: [Int: String]
public var count: Int { tokensToIds.count }
public init(tokensToIds: [String: Int]) {
self.tokensToIds = tokensToIds
self.idsToTokens = [Int: String](uniqueKeysWithValues: tokensToIds.map { ($1, $0) })
}
public init(idsToTokens: [Int: String]) {
self.tokensToIds = [String: Int](uniqueKeysWithValues: idsToTokens.map { ($1, $0) })
self.idsToTokens = idsToTokens
}
public func contains(_ token: String) -> Bool {
tokensToIds.keys.contains(token)
}
public func id(forToken token: String) -> Int? {
tokensToIds[token]
}
public func token(forId id: Int) -> String? {
idsToTokens[id]
}
}
extension Vocabulary {
public init(fromFile fileURL: URL) throws {
self.init(
tokensToIds: [String: Int](
(try String(contentsOfFile: fileURL.path, encoding: .utf8))
.components(separatedBy: .newlines)
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { $0.count > 0 }
.enumerated().map { ($0.element, $0.offset) },
uniquingKeysWith: { (v1, v2) in max(v1, v2) }))
}
public func save(toFile fileURL: URL) throws {
try idsToTokens
.sorted { $0.key < $1.key }
.map { $0.1 }
.joined(separator: "\n")
.write(to: fileURL, atomically: true, encoding: .utf8)
}
}
extension Vocabulary {
public init(fromJSONFile fileURL: URL) throws {
let json = try String(contentsOfFile: fileURL.path)
let tokensToIds = try JSONDecoder().decode(
[String: Int].self,
from: json.data(using: .utf8)!)
self.init(tokensToIds: tokensToIds)
}
}
/// Text tokenizer which is used to split strings into arrays of tokens.
public protocol Tokenizer {
func tokenize(_ text: String) -> [String]
}
/// Basic text tokenizer that performs some simple preprocessing to clean the provided text and
/// then performs tokenization based on whitespaces.
public struct BasicTokenizer: Tokenizer {
public let caseSensitive: Bool
/// Creates a basic text tokenizer.
///
/// Arguments:
/// - caseSensitive: Specifies whether or not to ignore case.
public init(caseSensitive: Bool = false) {
self.caseSensitive = caseSensitive
}
public func tokenize(_ text: String) -> [String] {
clean(text).split(separator: " ").flatMap { token -> [String] in
var processed = String(token)
if !caseSensitive {
processed = processed.lowercased()
// Normalize unicode characters.
processed = processed.decomposedStringWithCanonicalMapping
// Strip accents.
processed = processed.replacingOccurrences(
of: #"\p{Mn}"#,
with: "",
options: .regularExpression)
}
// Split punctuation. We treat all non-letter/number ASCII as punctuation. Characters
// such as "$" are not in the Unicode Punctuation class but we treat them as
// punctuation anyways for consistency.
processed = processed.replacingOccurrences(
of: #"([\p{P}!-/:-@\[-`{-~])"#,
with: " $1 ",
options: .regularExpression)
return processed.split(separator: " ").map(String.init)
}
}
}
/// Greedy subword tokenizer.
///
/// This tokenizer uses a greedy longest-match-first algorithm to perform tokenization using the
/// provided vocabulary. For example, `"unaffable"` could be tokenized as
/// `["un", "##aff", "##able"]`.
public struct GreedySubwordTokenizer: Tokenizer {
public let vocabulary: Vocabulary
public let unknownToken: String
public let maxTokenLength: Int?
/// Creates a subword tokenizer.
///
/// - Parameters:
/// - vocabulary: Vocabulary containing all supported tokens.
/// - unknownToken: Token used to represent unknown tokens (i.e., tokens that are not in the
/// provided vocabulary or whose length is longer than `maxTokenLength`).
/// - maxTokenLength: Maximum allowed token length.
public init(vocabulary: Vocabulary, unknownToken: String = "[UNK]", maxTokenLength: Int?) {
self.vocabulary = vocabulary
self.unknownToken = unknownToken
self.maxTokenLength = maxTokenLength
}
public func tokenize(_ text: String) -> [String] {
clean(text).split(separator: " ").flatMap { token -> [String] in
if let maxLength = maxTokenLength, token.count > maxLength { return [unknownToken] }
var isBad = false
var start = token.startIndex
var subTokens = [String]()
while start < token.endIndex {
// Find the longest matching substring.
var end = token.endIndex
var currentSubstring = ""
while start < end {
var substring = String(token[start..<end])
if start > token.startIndex {
substring = "##" + substring
}
if vocabulary.contains(substring) {
currentSubstring = substring
start = end
} else {
end = token.index(end, offsetBy: -1)
}
}
// Check if the substring is good.
if currentSubstring.isEmpty {
isBad = true
start = token.endIndex
} else {
subTokens.append(currentSubstring)
start = end
}
}
return isBad ? [unknownToken] : subTokens
}
}
}
/// Returns a cleaned version of the provided string. Cleaning in this case consists of normalizing
/// whitespaces, removing control characters and adding whitespaces around CJK characters.
///
/// - Parameters:
/// - text: String to clean.
///
/// - Returns: Cleaned version of `text`.
internal func clean(_ text: String) -> String {
// Normalize whitespaces.
let afterWhitespace = text.replacingOccurrences(
of: #"\s+"#,
with: " ",
options: .regularExpression)
// Remove control characters.
let afterControl = afterWhitespace.replacingOccurrences(
of: #"[\x{0000}\x{fffd}\p{C}]"#,
with: "",
options: .regularExpression)
// Add whitespace around CJK characters.
//
// The regular expression that we use defines a "chinese character" as anything in the
// [CJK Unicode block](https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)).
//
// Note that the CJK Unicode block is not all Japanese and Korean characters, despite its name.
// The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and
// Katakana. Those alphabets are used to write space-separated words, and so they are not
// treated specially and are instead handled like all of the other languages.
let afterCJK = afterControl.replacingOccurrences(
of: #"([\p{InCJK_Unified_Ideographs}"# +
#"\p{InCJK_Unified_Ideographs_Extension_A}"# +
#"\p{InCJK_Compatibility_Ideographs}"# +
#"\x{20000}-\x{2a6df}"# +
#"\x{2a700}-\x{2b73f}"# +
#"\x{2b740}-\x{2b81f}"# +
#"\x{2b820}-\x{2ceaf}"# +
#"\x{2f800}-\x{2fa1f}])"#,
with: " $1 ",
options: .regularExpression)
return afterCJK
}
|
d5f8c64b7dae88ae67f87fd2c16cbb34
| 37.196 | 101 | 0.609697 | false | false | false | false |
gkye/DribbbleSwift
|
refs/heads/master
|
Source/HTTPRequest.swift
|
mit
|
1
|
//
// HTTPRequest.swift
// DribbbleSwift
//
// Created by George on 2016-05-06.
// Copyright © 2016 George. All rights reserved.
//
import Foundation
public struct ClientReturn{
public var error: NSError?
public var json: JSON?
public var response: URLResponse?
init(error: NSError?, json: JSON?, response: URLResponse?){
self.error = error
self.json = json
self.response = response
}
}
enum RequestType: String{
case GET, POST, DELETE, PUT
}
class HTTPRequest{
class func request(_ url: String, parameters: [String: AnyObject]?, requestType: RequestType = .GET, authRequest: Bool = false, completionHandler: @escaping (ClientReturn) -> ()) -> (){
let baseURL = "https://api.dribbble.com/v1"+url
var url: URL!
var params: [String: AnyObject] = [:]
var request: NSMutableURLRequest!
switch requestType {
case .GET:
if(parameters != nil){
params = parameters!
}
if(!authRequest){
params["access_token"] = access_token as AnyObject?
}
let parameterString = params.stringFromHttpParameters()
url = URL(string: "\(baseURL)?\(parameterString)")!
request = NSMutableURLRequest(url: url)
default:
break;
}
if(authRequest){
if(requestType == .GET && parameters != nil){
let parameterString = parameters!.stringFromHttpParameters()
url = URL(string: "\(baseURL)?\(parameterString)")!
}else{
url = URL(string: baseURL)
}
request = NSMutableURLRequest(url: url)
if(OAuth2Token != nil){
request.addValue("Bearer \(OAuth2Token)", forHTTPHeaderField: "Authorization")
}else{
fatalError("OAuth token not set!")
}
}
request.httpMethod = requestType.rawValue
request.addValue("application/vnd.dribbble.v1.text+json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
DispatchQueue.main.async(execute: { () -> Void in
if error == nil{
let json = JSON(data: data!)
completionHandler(ClientReturn.init(error: error as NSError?, json: json, response: response))
}else{
print("Error -> \(error)")
print(error)
completionHandler(ClientReturn.init(error: error as NSError?, json: nil, response: response))
}
})
})
task.resume()
}
}
extension String {
/// Percent escapes values to be added to a URL query as specified in RFC 3986
///
/// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Returns percent-escaped string.
func stringByAddingPercentEncodingForURLQueryValue() -> String? {
let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
}
}
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (String(describing: value)).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joined(separator: "&")
}
}
|
ca9cf97e865f70ff26da5b9929889a46
| 33.48 | 189 | 0.590951 | false | false | false | false |
myfreeweb/SwiftCBOR
|
refs/heads/master
|
Sources/SwiftCBOR/CBORDecoder.swift
|
unlicense
|
1
|
#if canImport(Foundation)
import Foundation
#endif
public enum CBORError : Error {
case unfinishedSequence
case wrongTypeInsideSequence
case tooLongSequence
case incorrectUTF8String
}
extension CBOR {
static public func decode(_ input: [UInt8]) throws -> CBOR? {
return try CBORDecoder(input: input).decodeItem()
}
}
public class CBORDecoder {
private var istream : CBORInputStream
public init(stream: CBORInputStream) {
istream = stream
}
public init(input: ArraySlice<UInt8>) {
istream = ArraySliceUInt8(slice: input)
}
public init(input: [UInt8]) {
istream = ArrayUInt8(array: input)
}
func readBinaryNumber<T>(_ type: T.Type) throws -> T {
Array(try self.istream.popBytes(MemoryLayout<T>.size).reversed()).withUnsafeBytes { ptr in
return ptr.load(as: T.self)
}
}
func readVarUInt(_ v: UInt8, base: UInt8) throws -> UInt64 {
guard v > base + 0x17 else { return UInt64(v - base) }
switch VarUIntSize(rawValue: v) {
case .uint8: return UInt64(try readBinaryNumber(UInt8.self))
case .uint16: return UInt64(try readBinaryNumber(UInt16.self))
case .uint32: return UInt64(try readBinaryNumber(UInt32.self))
case .uint64: return UInt64(try readBinaryNumber(UInt64.self))
}
}
func readLength(_ v: UInt8, base: UInt8) throws -> Int {
let n = try readVarUInt(v, base: base)
guard n <= Int.max else {
throw CBORError.tooLongSequence
}
return Int(n)
}
private func readN(_ n: Int) throws -> [CBOR] {
return try (0..<n).map { _ in
guard let r = try decodeItem() else { throw CBORError.unfinishedSequence }
return r
}
}
func readUntilBreak() throws -> [CBOR] {
var result: [CBOR] = []
var cur = try decodeItem()
while cur != CBOR.break {
guard let curr = cur else { throw CBORError.unfinishedSequence }
result.append(curr)
cur = try decodeItem()
}
return result
}
private func readNPairs(_ n: Int) throws -> [CBOR : CBOR] {
var result: [CBOR: CBOR] = [:]
for _ in (0..<n) {
guard let key = try decodeItem() else { throw CBORError.unfinishedSequence }
guard let val = try decodeItem() else { throw CBORError.unfinishedSequence }
result[key] = val
}
return result
}
func readPairsUntilBreak() throws -> [CBOR : CBOR] {
var result: [CBOR: CBOR] = [:]
var key = try decodeItem()
if key == CBOR.break {
return result
}
var val = try decodeItem()
while key != CBOR.break {
guard let okey = key else { throw CBORError.unfinishedSequence }
guard let oval = val else { throw CBORError.unfinishedSequence }
result[okey] = oval
do { key = try decodeItem() } catch CBORError.unfinishedSequence { key = nil }
guard (key != CBOR.break) else { break } // don't eat the val after the break!
do { val = try decodeItem() } catch CBORError.unfinishedSequence { val = nil }
}
return result
}
public func decodeItem() throws -> CBOR? {
let b = try istream.popByte()
switch b {
// positive integers
case 0x00...0x1b:
return CBOR.unsignedInt(try readVarUInt(b, base: 0x00))
// negative integers
case 0x20...0x3b:
return CBOR.negativeInt(try readVarUInt(b, base: 0x20))
// byte strings
case 0x40...0x5b:
let numBytes = try readLength(b, base: 0x40)
return CBOR.byteString(Array(try istream.popBytes(numBytes)))
case 0x5f:
return CBOR.byteString(try readUntilBreak().flatMap { x -> [UInt8] in
guard case .byteString(let r) = x else { throw CBORError.wrongTypeInsideSequence }
return r
})
// utf-8 strings
case 0x60...0x7b:
let numBytes = try readLength(b, base: 0x60)
return CBOR.utf8String(try Util.decodeUtf8(try istream.popBytes(numBytes)))
case 0x7f:
return CBOR.utf8String(try readUntilBreak().map { x -> String in
guard case .utf8String(let r) = x else { throw CBORError.wrongTypeInsideSequence }
return r
}.joined(separator: ""))
// arrays
case 0x80...0x9b:
let numBytes = try readLength(b, base: 0x80)
return CBOR.array(try readN(numBytes))
case 0x9f:
return CBOR.array(try readUntilBreak())
// pairs
case 0xa0...0xbb:
let numBytes = try readLength(b, base: 0xa0)
return CBOR.map(try readNPairs(numBytes))
case 0xbf:
return CBOR.map(try readPairsUntilBreak())
// tagged values
case 0xc0...0xdb:
let tag = try readVarUInt(b, base: 0xc0)
guard let item = try decodeItem() else { throw CBORError.unfinishedSequence }
#if canImport(Foundation)
if tag == 1 {
var date: Date
switch item {
case .double(let d):
date = Date(timeIntervalSince1970: TimeInterval(d))
case .negativeInt(let n):
date = Date(timeIntervalSince1970: TimeInterval(n))
case .float(let f):
date = Date(timeIntervalSince1970: TimeInterval(f))
case .unsignedInt(let u):
date = Date(timeIntervalSince1970: TimeInterval(u))
default:
throw CBORError.wrongTypeInsideSequence
}
return CBOR.date(date)
}
#endif
return CBOR.tagged(CBOR.Tag(rawValue: tag), item)
case 0xe0...0xf3: return CBOR.simple(b - 0xe0)
case 0xf4: return CBOR.boolean(false)
case 0xf5: return CBOR.boolean(true)
case 0xf6: return CBOR.null
case 0xf7: return CBOR.undefined
case 0xf8: return CBOR.simple(try istream.popByte())
case 0xf9:
return CBOR.half(Util.readFloat16(x: try readBinaryNumber(UInt16.self)))
case 0xfa:
return CBOR.float(try readBinaryNumber(Float32.self))
case 0xfb:
return CBOR.double(try readBinaryNumber(Float64.self))
case 0xff: return CBOR.break
default: return nil
}
}
}
private enum VarUIntSize: UInt8 {
case uint8 = 0
case uint16 = 1
case uint32 = 2
case uint64 = 3
init(rawValue: UInt8) {
switch rawValue & 0b11 {
case 0: self = .uint8
case 1: self = .uint16
case 2: self = .uint32
case 3: self = .uint64
default: fatalError() // mask only allows values from 0-3
}
}
}
|
dd5381ea315237c30f9e92238aaab92c
| 31.981132 | 98 | 0.569937 | false | false | false | false |
AndersHqst/SwiftRestFramework
|
refs/heads/master
|
BikeLane/Socket.swift
|
bsd-3-clause
|
9
|
//
// Socket.swift
// Swifter
// Copyright (c) 2014 Damian Kołakowski. All rights reserved.
//
import Foundation
/* Low level routines for POSIX sockets */
struct Socket {
static func lastErr(reason: String) -> NSError {
let errorCode = errno
if let errorText = String.fromCString(UnsafePointer(strerror(errorCode))) {
return NSError(domain: "SOCKET", code: Int(errorCode), userInfo: [NSLocalizedFailureReasonErrorKey : reason, NSLocalizedDescriptionKey : errorText])
}
return NSError(domain: "SOCKET", code: Int(errorCode), userInfo: nil)
}
static func tcpForListen(port: in_port_t = 8080, error: NSErrorPointer = nil) -> CInt? {
let s = socket(AF_INET, SOCK_STREAM, 0)
if ( s == -1 ) {
if error != nil { error.memory = lastErr("socket(...) failed.") }
return nil
}
var value: Int32 = 1;
if ( setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(sizeof(Int32))) == -1 ) {
release(s)
if error != nil { error.memory = lastErr("setsockopt(...) failed.") }
return nil
}
nosigpipe(s)
var addr = sockaddr_in(sin_len: __uint8_t(sizeof(sockaddr_in)), sin_family: sa_family_t(AF_INET),
sin_port: port_htons(port), sin_addr: in_addr(s_addr: inet_addr("0.0.0.0")), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
var sock_addr = sockaddr(sa_len: 0, sa_family: 0, sa_data: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
memcpy(&sock_addr, &addr, Int(sizeof(sockaddr_in)))
if ( bind(s, &sock_addr, socklen_t(sizeof(sockaddr_in))) == -1 ) {
release(s)
if error != nil { error.memory = lastErr("bind(...) failed.") }
return nil
}
if ( listen(s, 20 /* max pending connection */ ) == -1 ) {
release(s)
if error != nil { error.memory = lastErr("listen(...) failed.") }
return nil
}
return s
}
static func writeUTF8(socket: CInt, string: String, error: NSErrorPointer = nil) -> Bool {
if let nsdata = string.dataUsingEncoding(NSUTF8StringEncoding) {
return writeData(socket, data: nsdata, error: error)
}
return true
}
static func writeASCII(socket: CInt, string: String, error: NSErrorPointer = nil) -> Bool {
if let nsdata = string.dataUsingEncoding(NSASCIIStringEncoding) {
return writeData(socket, data: nsdata, error: error)
}
return true
}
static func writeData(socket: CInt, data: NSData, error: NSErrorPointer = nil) -> Bool {
var sent = 0
let unsafePointer = UnsafePointer<UInt8>(data.bytes)
while ( sent < data.length ) {
let s = write(socket, unsafePointer + sent, Int(data.length - sent))
if ( s <= 0 ) {
if error != nil { error.memory = lastErr("write(...) failed.") }
return false
}
sent += s
}
return true
}
static func acceptClientSocket(socket: CInt, error:NSErrorPointer = nil) -> CInt? {
var addr = sockaddr(sa_len: 0, sa_family: 0, sa_data: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), len: socklen_t = 0
let clientSocket = accept(socket, &addr, &len)
if ( clientSocket != -1 ) {
Socket.nosigpipe(clientSocket)
return clientSocket
}
if error != nil { error.memory = lastErr("accept(...) failed.") }
return nil
}
static func nosigpipe(socket: CInt) {
// prevents crashes when blocking calls are pending and the app is paused ( via Home button )
var no_sig_pipe: Int32 = 1;
setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &no_sig_pipe, socklen_t(sizeof(Int32)));
}
static func port_htons(port: in_port_t) -> in_port_t {
let isLittleEndian = Int(OSHostByteOrder()) == OSLittleEndian
return isLittleEndian ? _OSSwapInt16(port) : port
}
static func release(socket: CInt) {
shutdown(socket, SHUT_RDWR)
close(socket)
}
static func peername(socket: CInt, error: NSErrorPointer = nil) -> String? {
var addr = sockaddr(), len: socklen_t = socklen_t(sizeof(sockaddr))
if getpeername(socket, &addr, &len) != 0 {
if error != nil { error.memory = lastErr("getpeername(...) failed.") }
return nil
}
var hostBuffer = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
if getnameinfo(&addr, len, &hostBuffer, socklen_t(hostBuffer.count), nil, 0, NI_NUMERICHOST) != 0 {
if error != nil { error.memory = lastErr("getnameinfo(...) failed.") }
return nil
}
return String.fromCString(hostBuffer)
}
}
|
56ffafbe057fbe5ac5c91c6ba7587317
| 39.391667 | 160 | 0.565504 | false | false | false | false |
blstream/StudyBox_iOS
|
refs/heads/master
|
StudyBox_iOS/RemoteDataManager.swift
|
apache-2.0
|
1
|
//
// RemoteDataManager.swift
// StudyBox_iOS
//
// Created by Kacper Cz on 04.05.2016.
// Copyright © 2016 BLStream. All rights reserved.
//
import Alamofire
import SwiftyJSON
import Reachability
enum ServerError: ErrorType {
case ErrorWithMessage(text: String), NoInternetAccess, NoUser, FetchError
}
enum ServerResultType<T> {
case Success(obj: T)
case Error(err: ErrorType)
}
class RemoteDataManager {
var user: User?
private var basicAuth: String? {
if let user = user {
if let basicEncoded = "\(user.email):\(user.password)".base64Encoded() {
return "Basic \(basicEncoded)"
}
}
return nil
}
// Metoda sprawdza czy odpowiedź serwera zawiera pole 'message' - jeśli tak oznacza to, że coś poszło nie tak,
// w przypadku jego braku dostajemy dane o które prosiliśmy
private func performGenericRequest<ObjectType>(
request: URLRequestConvertible,
completion: (ServerResultType<ObjectType>)->(),
successAction: (JSON) -> (ObjectType)) {
guard Reachability.isConnected() else {
completion(.Error(err: ServerError.NoInternetAccess))
return
}
let mutableRequest = request.URLRequest
if let basic = basicAuth {
mutableRequest.addValue(basic, forHTTPHeaderField: "Authorization")
}
Alamofire.request(mutableRequest).responseJSON { response in
switch response.result {
case .Success(let val):
let json = JSON(val)
if let message = json.dictionary?["message"]?.string {
completion(.Error(err: ServerError.ErrorWithMessage(text: message)))
} else {
completion(.Success(obj: successAction(json)))
}
case .Failure(let err):
completion(.Error(err: err))
}
}
}
//convenience method when ServerResultType is JSON
private func performRequest(
request: URLRequestConvertible,
completion: (ServerResultType<JSON>)->()) {
performGenericRequest(request, completion: completion) { $0 }
}
//convenience method when ServerResultType is [JSON]
private func performRequest(
request: URLRequestConvertible,
completion: (ServerResultType<[JSON]>)->()) {
performGenericRequest(request, completion: completion) { $0.arrayValue }
}
//MARK: Users
func login(email: String, password: String, completion: (ServerResultType<JSON>)->()) {
guard let basicAuth = "\(email):\(password)".base64Encoded() else {
completion(.Error(err: (ServerError.ErrorWithMessage(text: "Niepoprawne dane"))))
return
}
let loginRequest = Router.GetCurrentUser.URLRequest
loginRequest.addValue("Basic \(basicAuth)", forHTTPHeaderField: "Authorization")
performRequest(loginRequest, completion: completion)
}
func register(email: String, password: String, completion: (ServerResultType<JSON>) -> ()) {
performRequest(Router.AddUser(email: email, password: password), completion: completion)
}
func logout() {
user = nil
let defaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey(Utils.NSUserDefaultsKeys.LoggedUserEmail)
defaults.removeObjectForKey(Utils.NSUserDefaultsKeys.LoggedUserPassword)
}
func saveEmailPassInDefaults(email: String, pass: String) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(email, forKey: Utils.NSUserDefaultsKeys.LoggedUserEmail)
defaults.setObject(pass, forKey: Utils.NSUserDefaultsKeys.LoggedUserPassword)
}
func getEmailPassFromDefaults() -> (email: String, password: String)? {
let defaults = NSUserDefaults.standardUserDefaults()
let email = defaults.objectForKey(Utils.NSUserDefaultsKeys.LoggedUserEmail) as? String
let password = defaults.objectForKey(Utils.NSUserDefaultsKeys.LoggedUserPassword) as? String
if let email = email, password = password {
return (email, password)
} else {
return nil
}
}
func gravatar(saveURL: NSURL, completion: (ServerResultType<NSData>) -> ()) {
guard let user = user else {
completion(.Error(err: ServerError.NoUser))
return
}
let emailHash = user.email.lowercaseString.md5
if let url = NSURL(string: "https://www.gravatar.com/avatar/\(emailHash)") {
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request = ParameterEncoding.URL.encode(request, parameters: ["d":"retro"]).0
Alamofire.download(request) { _, _ in
return saveURL
}.response { _, _, _, err in
if err == nil, let contents = NSData(contentsOfURL: saveURL) {
completion(.Success(obj: contents))
} else {
completion(.Error(err: ServerError.FetchError))
}
}
}
}
//MARK: Decks
func findDecks(includeOwn includeOwn: Bool? = nil, flashcardsCount: Bool? = nil, name: String? = nil, completion: (ServerResultType<[JSON]>)->()) {
performRequest(Router.GetAllDecks(includeOwn: includeOwn, flashcardsCount: flashcardsCount, name: name), completion: completion)
}
func deck(deckID: String, completion: (ServerResultType<JSON>) -> ()) {
performRequest(Router.GetSingleDeck(ID: deckID), completion: completion)
}
func findRandomDeck(flashcardsCount: Bool? = nil, completion: (ServerResultType<JSON>)->()) {
performRequest(Router.GetRandomDeck(flashcardsCount: flashcardsCount), completion: completion)
}
func userDecks(flashcardsCount flashcardsCount: Bool? = nil, completion: (ServerResultType<[JSON]>) -> ()) {
performRequest(Router.GetAllUsersDecks(flashcardsCount: flashcardsCount), completion: completion)
}
func addDeck(deck: Deck, completion: (ServerResultType<JSON>) -> ()) {
performRequest(Router.AddSingleDeck(name: deck.name, isPublic: deck.isPublic), completion: completion)
}
func removeDeck(deckID: String, completion: (ServerResultType<Void>) -> ()) {
performGenericRequest(Router.RemoveSingleDeck(ID: deckID), completion: completion){ _ in
return
}
}
func updateDeck(deck: Deck, completion: (ServerResultType<JSON>) -> ()) {
performRequest(Router.UpdateDeck(ID: deck.serverID, name: deck.name, isPublic: deck.isPublic), completion: completion)
}
func changeAccessToDeck(deckID: String, isPublic: Bool, completion: (ServerResultType<Void>) -> ()) {
performGenericRequest(Router.ChangeAccessToDeck(ID: deckID, isPublic: isPublic), completion: completion){ _ in
return
}
}
//MARK: Flashcards
func findFlashcards(deckID: String, completion: (ServerResultType<[JSON]>) -> ()) {
performRequest(Router.GetAllFlashcards(deckID: deckID), completion: completion)
}
func flashcard(deckID: String, flashcardID: String, completion: (ServerResultType<JSON>) -> ()) {
performRequest(Router.GetSingleFlashcard(ID: flashcardID, deckID: deckID), completion: completion)
}
func addFlashcard(flashcard: Flashcard, completion: (ServerResultType<JSON>) -> ()) {
performRequest(Router.AddSingleFlashcard(deckID: flashcard.deckId, question: flashcard.question, answer: flashcard.answer, isHidden: flashcard.hidden),
completion: completion)
}
func removeFlashcard(deckID: String, flashcardID: String, completion: (ServerResultType<Void>) -> ()) {
performGenericRequest(Router.RemoveSingleFlashcard(ID: flashcardID, deckID: deckID), completion: completion){ _ in
return
}
}
func updateFlashcard(flashcard: Flashcard, completion: (ServerResultType<JSON>) -> ()) {
performRequest(Router.UpdateFlashcard(ID: flashcard.serverID, deckID: flashcard.deckId,
question: flashcard.question, answer: flashcard.answer, isHidden: flashcard.hidden),
completion: completion)
}
//MARK: Tips
// swiftlint:disable:next function_parameter_count
func addTip(deckID deckID: String, flashcardID: String, tipID: String, content: String, difficulty: Int, completion: (ServerResultType<JSON>)->()) {
performRequest(Router.AddTip(deckID: deckID, flashcardID: flashcardID, content: content, difficulty: difficulty), completion: completion)
}
func tip(deckID deckID: String, flashcardID: String, tipID: String, completion: (ServerResultType<JSON>)->()) {
performRequest(Router.GetTip(deckID: deckID, flashcardID: flashcardID, tipID: tipID), completion: completion)
}
func allTips(deckID deckID: String, flashcardID: String, completion: (ServerResultType<[JSON]>) -> ()) {
performRequest(Router.GetAllTips(deckID: deckID, flashcardID: flashcardID), completion: completion)
}
// swiftlint:disable:next function_parameter_count
func updateTip(deckID deckID: String, flashcardID: String, tipID: String,
content: String, difficulty: Int, completion: (ServerResultType<JSON>)->()) {
performRequest(Router.UpdateTip(deckID: deckID, flashcardID: flashcardID, tipID: tipID,
content: content, difficulty: difficulty), completion: completion)
}
func removeTip(deckID deckID: String, flashcardID: String, tipID: String, completion: (ServerResultType<Void>)->()) {
performGenericRequest(Router.RemoveTip(deckID: deckID, flashcardID: flashcardID, tipID: tipID), completion: completion){ _ in
return
}
}
func addTip(tip: Tip, completion: (ServerResultType<JSON>)->()) {
addTip(deckID: tip.deckID, flashcardID: tip.flashcardID, tipID: tip.serverID, content: tip.content, difficulty: tip.difficulty, completion: completion)
}
func tip(tip: Tip, completion: (ServerResultType<JSON>)->()) {
performRequest(Router.GetTip(deckID: tip.deckID, flashcardID: tip.flashcardID, tipID: tip.serverID), completion: completion)
}
func updateTip(tip: Tip, completion: (ServerResultType<JSON>)->()) {
updateTip(deckID: tip.deckID, flashcardID: tip.flashcardID, tipID: tip.serverID,
content: tip.content, difficulty: tip.difficulty, completion: completion)
}
func removeTip(tip: Tip, completion: (ServerResultType<Void>) -> ()) {
removeTip(deckID: tip.deckID, flashcardID: tip.flashcardID, tipID: tip.serverID, completion: completion)
}
}
|
ae8d196f111d8e39e695d2502a94a2bc
| 41.921569 | 159 | 0.650891 | false | false | false | false |
seungprk/PenguinJump
|
refs/heads/master
|
PenguinJump/PenguinJump/GameScene+Updates.swift
|
bsd-2-clause
|
1
|
//
// GameScene+Updates.swift: Collects all the update functions run in every rendering loop into one file.
// PenguinJump
//
// Created by Matthew Tso on 6/18/16.
// Copyright © 2016 De Anza. All rights reserved.
//
import SpriteKit
extension GameScene {
/// Updates the difficulty modifier based on y distance traveled.
func trackDifficulty() {
// Difficulty:
// minimum 0.0
// maximum 1.0
difficulty = -1.0 * pow(0.9995, Double(penguin.position.y)) + 1.0
}
override func update(currentTime: NSTimeInterval) {
updateGameTime(currentTime)
// Stage is created whether a game session is in play or not because it serves as the background for the menu scene.
stage.update()
waves.update()
coinLabel.text = "\(totalCoins) coins"
if gameRunning {
penguin.userInteractionEnabled = true
scoreLabel.text = "Score: " + String(intScore)
checkGameOver()
if gameOver {
runGameOver()
}
trackDifficulty()
penguinUpdate()
coinUpdate()
chargeBarUpdate()
updateStorm()
updateRain()
updateLightning()
updateShark()
centerCamera()
} else {
penguin.userInteractionEnabled = false
penguin.removeAllActions()
for child in penguin.children {
child.removeAllActions()
}
}
}
/// Corrects game time upon exiting a pause state.
func updateGameTime(currentTime: NSTimeInterval) {
if shouldCorrectAfterPause {
timeSinceLastUpdate = 0.0
shouldCorrectAfterPause = false
previousTime = currentTime
} else {
// previousTime is nil before the first time it is assigned to currentTime.
if let previousTime = previousTime {
timeSinceLastUpdate = currentTime - previousTime
self.previousTime = currentTime
} else {
self.previousTime = currentTime
}
}
}
func updateShark() {
for child in sharkLayer!.children {
let shark = child as! Shark
if shark.position.y < cam.position.y - view!.frame.height * 1.2 {
shark.removeFromParent()
if sharkLayer!.children.count < 1 {
lurkingSound?.stop()
}
}
}
}
func updateLightning() {
if let lightningLayer = lightningLayer{
for child in lightningLayer.children {
let lightning = child as! Lightning
let difference = lightning.position.y - penguin.position.y
if difference < 40 {
if !lightning.didBeginStriking {
lightning.didBeginStriking = true
lightning.beginStrike()
}
}
}
}
}
func updateRain() {
if stormMode {
let maxRaindropsPerSecond = 80.0
// Storm start ease in
var raindropsPerSecond = 0.1 * pow(5.3, stormTimeElapsed) - 0.1
// Cap at 80 maximum
if raindropsPerSecond > maxRaindropsPerSecond {
raindropsPerSecond = maxRaindropsPerSecond
}
// Storm ending rain ease out
if stormTimeElapsed > stormDuration - 2 {
raindropsPerSecond = 0.1 * pow(5.3, abs(stormTimeElapsed - stormDuration)) - 0.1
}
let numberOfRainDrops = Int(timeSinceLastUpdate * raindropsPerSecond /* * stormIntensity */) + 1// + randomRaindrops
for _ in 0..<numberOfRainDrops {
let randomX = 3.0 * CGFloat(random()) % view!.frame.width - view!.frame.width / 2
let randomY = 2.0 * CGFloat(random()) % view!.frame.height - view!.frame.height / 4
let raindrop = Raindrop()
addChild(raindrop)
raindrop.drop(CGPoint(x: penguin.position.x + CGFloat(randomX), y: penguin.position.y + CGFloat(randomY)), windSpeed: windSpeed * 2)
// Attempt to avoid dropping a raindrop over an iceberg.
for child in stage.children {
let berg = child as! Iceberg
if berg.containsPoint(convertPoint(CGPoint(x: penguin.position.x + CGFloat(randomX), y: penguin.position.y + CGFloat(randomY)), toNode: stage)) {
raindrop.zPosition = 0
} else {
raindrop.zPosition = 24000
}
}
}
}
}
func updateWinds() {
if windEnabled {
windSpeed = windDirectionRight ? stormIntensity * 70 : -stormIntensity * 70
var deltaX = penguin.inAir ? windSpeed * timeSinceLastUpdate * difficulty : windSpeed * 0.5 * timeSinceLastUpdate * difficulty
if penguin.type == PenguinType.shark {
deltaX = deltaX * 0.75
}
let push = SKAction.moveBy(CGVector(dx: deltaX, dy: 0), duration: timeSinceLastUpdate)
penguin.runAction(push)
}
}
func updateStorm() {
if stormMode {
updateWinds()
// Update storm intensity during storm mode.
if stormTimeElapsed < stormDuration - stormTransitionDuration {
stormTimeElapsed += timeSinceLastUpdate
if stormIntensity < 0.99 {
// Begin storm gradually
stormIntensity += 1.0 * (timeSinceLastUpdate / stormTransitionDuration) * 0.3
} else {
// Enter full storm intensity
stormIntensity = 1.0
}
} else {
// Begin ending storm mode.
if stormIntensity > 0.01 {
// Exit storm gradually
stormIntensity -= 1.0 * (timeSinceLastUpdate / stormTransitionDuration) * 0.3
} else {
// End of storm mode.
stormIntensity = 0.0
stormTimeElapsed = 0.0
stormMode = false
waves.stormMode = self.stormMode
waves.bob()
for child in stage.children {
let berg = child as! Iceberg
berg.stormMode = self.stormMode
berg.bob()
}
chargeBar.barFlash.removeAllActions()
}
}
}
backgroundColor = SKColor(red: bgColorValues.red, green: bgColorValues.green - CGFloat(40 / 255 * stormIntensity), blue: bgColorValues.blue - CGFloat(120 / 255 * stormIntensity), alpha: bgColorValues.alpha)
}
func penguinUpdate() {
for child in stage.children {
let berg = child as! Iceberg
if penguin.shadow.intersectsNode(berg)
&& penguin.onBerg
&& !penguin.inAir
&& !berg.landed
&& berg.name != "firstBerg" {
// Penguin landed on an iceberg if check is true
if gameData.soundEffectsOn == true { landingSound?.play() }
berg.land()
stage.updateCurrentBerg(berg)
shakeScreen()
let sinkDuration = 7.0 - (3.0 * difficulty)
berg.sink(sinkDuration, completion: nil)
penguin.land(sinkDuration)
intScore += 1
let scoreBumpUp = SKAction.scaleTo(1.2, duration: 0.1)
let scoreBumpDown = SKAction.scaleTo(1.0, duration: 0.1)
scoreLabel.runAction(SKAction.sequence([scoreBumpUp, scoreBumpDown]))
}
}
if !penguin.hitByLightning && penguin.contactingLightning {
for child in lightningLayer!.children {
let lightning = child as! Lightning
if lightning.activated && lightning.shadow.intersectsNode(penguin.shadow) {
// Penguin hit by lightning strike.
penguin.hitByLightning = true
let shadowPositionInLayer = lightningLayer!.convertPoint(lightning.shadow.position, fromNode: lightning)
let lightningShadowPositionInScene = convertPoint(shadowPositionInLayer, fromNode: lightningLayer!)
let penguinShadowPositionInScene = convertPoint(penguin.shadow.position, fromNode: penguin)
let deltaX = penguinShadowPositionInScene.x - lightningShadowPositionInScene.x
let deltaY = penguinShadowPositionInScene.y - lightningShadowPositionInScene.y
let maxDelta = lightning.shadow.size.width / 2
let maxPushDistance = penguin.size.height * 1.5
let pushX = (deltaX / maxDelta) * maxPushDistance
let pushY = (deltaY / maxDelta) * maxPushDistance
let push = SKAction.moveBy(CGVector(dx: pushX, dy: pushY), duration: 1.0)
push.timingMode = .EaseOut
penguin.removeAllActions()
penguin.runAction(push, completion: {
self.penguin.hitByLightning = false
})
}
}
}
}
func chargeBarUpdate() {
chargeBar.mask.size.width = scoreLabel.frame.width * 0.95
if chargeBar.bar.position.x >= chargeBar.mask.size.width {
shouldFlash = true
if shouldFlash && !stormMode {
shouldFlash = false
beginStorm()
chargeBar.flash(completion: {
let chargeDown = SKAction.moveToX(0, duration: self.stormDuration - self.stormTimeElapsed)
self.chargeBar.bar.runAction(chargeDown)
})
}
} else if chargeBar.bar.position.x > 0 && !stormMode {
let decrease = SKAction.moveBy(CGVector(dx: -5 * timeSinceLastUpdate, dy: 0), duration: timeSinceLastUpdate)
chargeBar.bar.runAction(decrease)
if !stormMode && !chargeBar.flashing {
chargeBar.barFlash.alpha = 0.0
}
}
}
func coinUpdate() {
if let coinLayer = coinLayer {
for child in coinLayer.children {
let coin = child as! Coin
let coinShadowPositionInLayer = coinLayer.convertPoint(coin.shadow.position, fromNode: coin)
let coinPositionInScene = convertPoint(coinShadowPositionInLayer, fromNode: coinLayer)
let penguinPositionInScene = convertPoint(penguin.shadow.position, fromNode: penguin)
if penguinPositionInScene.y > coinPositionInScene.y {
coin.body.zPosition = 90000
}
}
}
}
func incrementBarWithCoinParticles(coin: Coin) {
for particle in coin.particles {
let chargeBarPositionInCam = cam.convertPoint(chargeBar.position, fromNode: scoreLabel)
let randomX = CGFloat(random()) % (chargeBar.bar.position.x + 1)
let move = SKAction.moveTo(CGPoint(x: chargeBarPositionInCam.x + randomX, y: chargeBarPositionInCam.y), duration: 1.0)
move.timingMode = .EaseOut
let wait = SKAction.waitForDuration(0.2 * Double(coin.particles.indexOf(particle)!))
particle.runAction(wait, completion: {
particle.runAction(move, completion: {
particle.removeFromParent()
if self.gameData.soundEffectsOn as Bool {
let charge = SKAction.playSoundFileNamed("charge.wav", waitForCompletion: false)
self.runAction(charge)
}
self.chargeBar.flashOnce()
if !self.stormMode {
let incrementAction = SKAction.moveBy(CGVector(dx: self.chargeBar.increment, dy: 0), duration: 0.5)
incrementAction.timingMode = .EaseOut
self.chargeBar.bar.runAction(incrementAction)
} else {
// Coin collected during storm mode.
// Increment bar but add to time elapsed too.
}
if coin.particles.isEmpty {
coin.removeFromParent()
}
})
})
}
}
func incrementTotalCoins() {
totalCoins += 1
// Increment coin total in game data
if gameData != nil {
let totalCoins = gameData.totalCoins as Int
gameData.totalCoins = totalCoins + 1
do { try managedObjectContext.save() } catch { print(error) }
}
}
func checkGameOver() {
if !penguin.inAir && !penguin.onBerg {
gameOver = true
}
}
}
|
4ef61df0f7e38d5d784efb9dd81bcb43
| 36.933511 | 214 | 0.499264 | false | false | false | false |
pixelkind/FUX
|
refs/heads/master
|
FUX/FUXEasingCombinators.swift
|
mit
|
1
|
//
// FUXEasingCombinators.swift
// FUX
//
// Created by Garrit Schaap on 06.02.15.
// Copyright (c) 2015 Garrit UG (haftungsbeschränkt). All rights reserved.
//
import UIKit
public func easeInCubic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time * time * time }
}
public func easeOutCubic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
let t = time - 1.0
return t * t * t + 1
}
}
public func easeInOutCubic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
if t < 1 {
return 0.5 * t * t * t
}
t -= 2
return 0.5 * (t * t * t + 2)
}
}
public func easeInCircular(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in -(sqrtf(1 - time * time) - 1) }
}
public func easeOutCircular(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
let t = time - 1.0
return sqrtf(1 - t * t)
}
}
public func easeInOutCircular(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
if t < 1 {
return -0.5 * (sqrtf(1 - t * t) - 1)
}
t -= 2
return 0.5 * (sqrtf(1 - t * t) + 1)
}
}
public func easeInSine(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in 1 - cosf(time * Float(M_PI_2)) }
}
public func easeOutSine(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in sinf(time * Float(M_PI_2)) }
}
public func easeInOutSine(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in -0.5 * (cosf(Float(M_PI) * time) - 1) }
}
public func easeInQuadratic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time * time }
}
public func easeOutQuadratic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in -time * (time - 2) }
}
public func easeInOutQuadratic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
if t < 1 {
return 0.5 * t * t
}
return -0.5 * (--t * (t - 2) - 1)
}
}
public func easeInQuartic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time * time * time * time }
}
public func easeOutQuartic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
let t = time - 1
return -(t * t * t * t - 1)
}
}
public func easeInOutQuartic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
if t < 1 {
return 0.5 * t * t * t * t
}
t -= 2
return -0.5 * (t * t * t * t - 2)
}
}
public func easeInQuintic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time * time * time * time * time }
}
public func easeOutQuintic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
let t = time - 1
return -(t * t * t * t * t - 1)
}
}
public func easeInOutQuintic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
if t < 1 {
return 0.5 * t * t * t * t * t
}
t -= 2
return -0.5 * (t * t * t * t * t - 2)
}
}
public func easeInExpo(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time == 0 ? 0 : powf(2, 10 * (time - 1)) }
}
public func easeOutExpo(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time == 1 ? 1 : -powf(2, -10 * time) + 1 }
}
public func easeInOutExpo(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
if time == 0 {
return 0
} else if time == 1 {
return 1
}
var t = time * 2
if t < 1 {
return 0.5 * powf(2, 10 * (t - 1))
} else {
return 0.5 * (-powf(2, -10 * --t) + 2)
}
}
}
let easeBackSValue: Float = 1.70158;
public func easeInBack(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in time * time * ((easeBackSValue + 1) * time - easeBackSValue) }
}
public func easeOutBack(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
let t = time - 1
return t * t * ((easeBackSValue + 1) * t + easeBackSValue) + 1
}
}
public func easeInOutBack(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)){ time in
var t = time * 2
let s = easeBackSValue * 1.525
if t < 1 {
return 0.5 * (t * t * ((s + 1) * t - s))
}
t -= 2
return 0.5 * (t * t * ((s + 1) * t + s) + 2)
}
}
public func easeInBounce(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
var t = 1 - time
if t < 1.0 / 2.75 {
return 1 - 7.5625 * t * t
} else if t < 2.0 / 2.75 {
t -= (1.5 / 2.75)
return 1 - Float(7.5625 * t * t + 0.75)
} else if t < 2.5 / 2.75 {
t -= (2.25 / 2.75)
return 1 - Float(7.5625 * t * t + 0.9375)
} else {
t -= (2.625 / 2.75)
return 1 - Float(7.5625 * t * t + 0.984375)
}
}
}
public func easeOutBounce(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
var t = time
if t < 1.0 / 2.75 {
return 7.5625 * t * t
} else if t < 2.0 / 2.75 {
t -= (1.5 / 2.75)
return Float(7.5625 * t * t + 0.75)
} else if t < 2.5 / 2.75 {
t -= (2.25 / 2.75)
return Float(7.5625 * t * t + 0.9375)
} else {
t -= (2.625 / 2.75)
return Float(7.5625 * t * t + 0.984375)
}
}
}
public func easeInOutBounce(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
var t = time * 2
if t < 1 {
return (1 - easeOutBounceWithTime(1 - t, 1)) * 0.5
} else {
return easeOutBounceWithTime(t - 1, 1) * 0.5 + 0.5
}
}
}
func easeOutBounceWithTime(time: Float, duration: Float) -> Float {
var t = time / duration
if t < 1.0 / 2.75 {
return 7.5625 * t * t
} else if t < 2.0 / 2.75 {
t -= (1.5 / 2.75)
return Float(7.5625 * t * t + 0.75)
} else if t < 2.5 / 2.75 {
t -= (2.25 / 2.75)
return Float(7.5625 * t * t + 0.9375)
} else {
t -= (2.625 / 2.75)
return Float(7.5625 * t * t + 0.984375)
}
}
var easeElasticPValue: Float = 0.3
var easeElasticSValue: Float = 0.3 / 4
var easeElasticAValue : Float = 1
public func setEaseElasticPValue(value: Float) {
easeElasticPValue = value
if easeElasticAValue < 1 {
easeElasticSValue = easeElasticPValue / 4
} else {
easeElasticSValue = easeElasticPValue / (Float(M_PI) * 2) * asinf(1 / easeElasticAValue)
}
}
public func setEaseElasticAValue(value: Float) {
if easeElasticAValue >= 1 {
easeElasticAValue = value
easeElasticSValue = easeElasticPValue / (Float(M_PI) * 2) * asinf(1 / easeElasticAValue)
}
}
public func easeInElastic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
if time == 0 {
return 0
} else if time == 1 {
return 1
}
let t = time - 1
return -(powf(2, 10 * t) * sinf((t - easeElasticSValue) * (Float(M_PI) * 2) / easeElasticPValue))
}
}
public func easeOutElastic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
if time == 0 {
return 0
} else if time == 1 {
return 1
}
return powf(2, (-10 * time)) * sinf((time - easeElasticSValue) * (Float(M_PI) * 2) / easeElasticPValue) + 1
}
}
public func easeInOutElastic(tween: FUXTween) -> FUXTween {
return FUXTween.Easing(Box(tween)) { time in
if time == 0 {
return 0
} else if time == 1 {
return 1
}
var t = time * 2
if t < 1 {
t -= 1
return -0.5 * (powf(2, 10 * t) * sinf((t - easeElasticSValue) * (Float(M_PI) * 2) / easeElasticPValue))
}
t -= 1
return powf(2, -10 * t) * sinf((t - easeElasticSValue) * (Float(M_PI) * 2) / easeElasticPValue) * 0.5 + 1
}
}
|
e0f178567075d0868ad0736ac9c9e0a0
| 26.805195 | 115 | 0.536144 | false | false | false | false |
m4rr/MosCoding
|
refs/heads/master
|
Flashcards/Flashcards/Deck.swift
|
mit
|
1
|
//
// Deck.swift
// Flashcards
//
// Created by Marat S. on 19/11/2016.
// Copyright © 2016 m4rr. All rights reserved.
//
import Foundation
class Deck {
private var cards: [Flashcard] = [ ]
init() {
let cardData = [
"controller outlet" : "A controller view property, marked with IBOutlet",
"controller action" : "A controller method, marked with IBAction, that is triggered by an interface event."
]
// for (term, definition) in cardData {
// cards.append(Flashcard(term: term, definition: definition))
// }
//
// cards = cardData.map { (key: String, value: String) -> Flashcard in
// return Flashcard(term: key, definition: value)
// }
cards = cardData.map { Flashcard(term: $0, definition: $1) }
}
func randomCard() -> Optional<Flashcard> { // -> Flashcard?
if cards.isEmpty {
return nil
} else {
let randomIndex =
Int(
arc4random_uniform(
UInt32(
cards.count)))
return cards[randomIndex]
}
}
var numberOfCards: Int {
return cards.count
}
func card(number: Int) -> Flashcard? {
if number < numberOfCards {
return cards[number]
}
return nil
}
}
|
aa81c9bb67aea538f38dd71cc87f5719
| 19.5 | 113 | 0.593496 | false | false | false | false |
wangshengjia/LeeGo
|
refs/heads/master
|
Demo/LeeGo/MainViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// PlaygroundProject
//
// Created by Victor WANG on 12/11/15.
// Copyright © 2015 Le Monde. All rights reserved.
//
import UIKit
import LeeGo
class MainViewController: UITableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
switch indexPath.row {
case 0:
cell.textLabel?.text = "Layout Samples"
case 1:
cell.textLabel?.text = "Le Monde"
case 2:
cell.textLabel?.text = "Twitter"
case 3:
cell.textLabel?.text = "Details Page"
default:
break
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.row {
case 0:
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "SamplesViewController") as? SamplesViewController {
self.navigationController?.pushViewController(viewController, animated: true)
}
case 1:
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "LeMondeNewsFeedViewController") as? LeMondeNewsFeedViewController {
self.navigationController?.pushViewController(viewController, animated: true)
}
case 2:
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "TwitterFeedViewController") as? TwitterFeedViewController {
self.navigationController?.pushViewController(viewController, animated: true)
}
case 3:
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "DetailsViewController") as? DetailsViewController {
self.navigationController?.pushViewController(viewController, animated: true)
}
default:
break
}
}
}
|
948df196f0370f1ce7a356231cac41c7
| 33.5 | 163 | 0.654809 | false | false | false | false |
marty-suzuki/HoverConversion
|
refs/heads/master
|
HoverConversion/HCDefaultAnimatedTransitioning.swift
|
mit
|
1
|
//
// HCDefaultAnimatedTransitioning.swift
// HoverConversion
//
// Created by Taiki Suzuki on 2016/09/11.
// Copyright © 2016年 marty-suzuki. All rights reserved.
//
//
import UIKit
class HCDefaultAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
fileprivate struct Const {
static let defaultDuration: TimeInterval = 0.25
static let rootDuration: TimeInterval = 0.4
static let scaling: CGFloat = 0.95
}
let operation: UINavigationControllerOperation
fileprivate let alphaView = UIView()
init(operation: UINavigationControllerOperation) {
self.operation = operation
super.init()
}
@objc func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
guard
let toVC = transitionContext?.viewController(forKey: UITransitionContextViewControllerKey.to),
let fromVC = transitionContext?.viewController(forKey: UITransitionContextViewControllerKey.from)
else {
return 0
}
switch (fromVC, toVC) {
case (_ as HCPagingViewController, _ as HCRootViewController): return Const.rootDuration
case (_ as HCRootViewController, _ as HCPagingViewController): return Const.rootDuration
default: return Const.defaultDuration
}
}
// This method can only be a nop if the transition is interactive and not a percentDriven interactive transition.
@objc func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to),
let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
else {
transitionContext.completeTransition(true)
return
}
let containerView = transitionContext.containerView
containerView.backgroundColor = .black
alphaView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
alphaView.frame = containerView.bounds
switch operation {
case .pop: popAnimation(transitionContext, toVC: toVC, fromVC: fromVC, containerView: containerView)
case .push: pushAnimation(transitionContext, toVC: toVC, fromVC: fromVC, containerView: containerView)
case .none: transitionContext.completeTransition(true)
}
}
fileprivate func popAnimation(_ transitionContext: UIViewControllerContextTransitioning, toVC: UIViewController, fromVC: UIViewController, containerView: UIView) {
containerView.insertSubview(toVC.view, belowSubview: fromVC.view)
containerView.insertSubview(alphaView, belowSubview: fromVC.view)
if let pagingVC = fromVC as? HCPagingViewController, let rootVC = toVC as? HCRootViewController {
let indexPath = pagingVC.currentIndexPath
//pagingVC.homeViewTalkContainerView.backgroundColor = .whiteColor()
if rootVC.tableView?.cellForRow(at: indexPath as IndexPath) == nil {
//rootVC.tableView?.scrollToRowAtIndexPath(indexPath, atScrollPosition: pagingVC.scrollDirection, animated: false)
}
rootVC.tableView?.selectRow(at: indexPath as IndexPath, animated: false, scrollPosition: .none)
}
alphaView.alpha = 1
toVC.view.frame = containerView.bounds
toVC.view.transform = CGAffineTransform(scaleX: Const.scaling, y: Const.scaling)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveLinear, animations: {
toVC.view.transform = CGAffineTransform.identity
fromVC.view.frame.origin.x = containerView.bounds.size.width
self.alphaView.alpha = 0
}) { finished in
let canceled = transitionContext.transitionWasCancelled
if canceled {
toVC.view.removeFromSuperview()
} else {
fromVC.view.removeFromSuperview()
}
toVC.view.transform = CGAffineTransform.identity
self.alphaView.removeFromSuperview()
if let pagingVC = fromVC as? HCPagingViewController, let rootVC = toVC as? HCRootViewController {
let indexPath = pagingVC.currentIndexPath
rootVC.tableView?.deselectRow(at: indexPath as IndexPath, animated: true)
}
transitionContext.completeTransition(!canceled)
}
}
fileprivate func pushAnimation(_ transitionContext: UIViewControllerContextTransitioning, toVC: UIViewController, fromVC: UIViewController, containerView: UIView) {
containerView.addSubview(alphaView)
containerView.addSubview(toVC.view)
toVC.view.frame = containerView.bounds
toVC.view.frame.origin.x = containerView.bounds.size.width
alphaView.alpha = 0
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveLinear, animations: {
fromVC.view.transform = CGAffineTransform(scaleX: Const.scaling, y: Const.scaling)
self.alphaView.alpha = 1
toVC.view.frame.origin.x = 0
}) { finished in
let canceled = transitionContext.transitionWasCancelled
if canceled {
toVC.view.removeFromSuperview()
}
self.alphaView.removeFromSuperview()
fromVC.view.transform = CGAffineTransform.identity
transitionContext.completeTransition(!canceled)
}
}
}
|
96ad103f7f6b045f4f77f129e4407973
| 44.322835 | 168 | 0.671473 | false | false | false | false |
outfoxx/CryptoSecurity
|
refs/heads/master
|
Sources/SecIdentity.swift
|
mit
|
1
|
//
// SecIdentity.swift
// CryptoSecurity
//
// Copyright © 2019 Outfox, inc.
//
//
// Distributed under the MIT License, See LICENSE for details.
//
import Foundation
import Security
public enum SecIdentityError: Int, Error {
case loadFailed
case saveFailed
case copyPrivateKeyFailed
case copyCertificateFailed
public static func build(error: SecIdentityError, message: String, status: OSStatus? = nil, underlyingError: Error? = nil) -> NSError {
let error = error as NSError
var userInfo = [
NSLocalizedDescriptionKey: message,
] as [String: Any]
if let status = status {
userInfo["status"] = Int(status) as NSNumber
}
if let underlyingError = underlyingError {
userInfo[NSUnderlyingErrorKey] = underlyingError as NSError
}
return NSError(domain: error.domain, code: error.code, userInfo: userInfo)
}
}
public extension SecIdentity {
static func load(certificate: SecCertificate) throws -> SecIdentity {
let attrs = try certificate.attributes()
let query: [String: Any] = [
kSecClass as String: kSecClassIdentity,
kSecAttrLabel as String: attrs[kSecAttrLabel as String]!,
kSecReturnRef as String: kCFBooleanTrue!,
]
var result: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)
if status != errSecSuccess || result == nil {
throw SecIdentityError.loadFailed
}
return result as! SecIdentity
}
func privateKey() throws -> SecKey {
var key: SecKey?
let status = SecIdentityCopyPrivateKey(self, &key)
if status != errSecSuccess {
throw SecIdentityError.copyPrivateKeyFailed
}
return key!
}
func certificate() throws -> SecCertificate {
var crt: SecCertificate?
let status = SecIdentityCopyCertificate(self, &crt)
if status != errSecSuccess {
throw SecIdentityError.copyCertificateFailed
}
return crt!
}
}
public class SecIdentityBuilder {
public let certificateSigningRequest: Data
public let keyPair: SecKeyPair
private init(certificateSigningRequest: Data, keyPair: SecKeyPair) {
self.certificateSigningRequest = certificateSigningRequest
self.keyPair = keyPair
}
public static func generate(subject: [X501NameEntry], keySize: Int, usage: SecKeyUsage) throws -> SecIdentityBuilder {
let keyPair = try SecKeyPairFactory(type: .RSA, keySize: keySize).generate()
let certificateSigningRequestFactory = SecCertificateRequestFactory()
certificateSigningRequestFactory.subject = subject
certificateSigningRequestFactory.publicKey = try keyPair.encodedPublicKey() as Data
let certificateSigningRequest = try certificateSigningRequestFactory.build(signingKey: keyPair.privateKey,
signingAlgorithm: .SHA256)
return SecIdentityBuilder(certificateSigningRequest: certificateSigningRequest, keyPair: keyPair)
}
public func save(withCertificate certificate: SecCertificate) throws {
do {
try keyPair.save()
}
catch SecKeyError.saveDuplicate {
// Allowable...
}
catch {
throw SecIdentityError.build(error: .saveFailed, message: "Unable to save key pair")
}
let query: [String: Any] = [
kSecClass as String: kSecClassCertificate,
kSecAttrLabel as String: UUID().uuidString,
kSecValueRef as String: certificate,
]
var data: CFTypeRef?
let status = SecItemAdd(query as CFDictionary, &data)
if status != errSecSuccess {
do { try keyPair.delete() } catch {}
throw SecIdentityError.build(error: .saveFailed, message: "Unable to add certificate", status: status)
}
}
}
|
77bd1cc9e008c24646d21d14867c9e32
| 24.875 | 137 | 0.695384 | false | false | false | false |
wikimedia/wikipedia-ios
|
refs/heads/main
|
Widgets/Widgets/OnThisDayWidget.swift
|
mit
|
1
|
import WidgetKit
import SwiftUI
import WMF
// MARK: - Widget
struct OnThisDayWidget: Widget {
private let kind: String = WidgetController.SupportedWidget.onThisDay.identifier
public var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: OnThisDayProvider(), content: { entry in
OnThisDayView(entry: entry)
})
.configurationDisplayName(CommonStrings.onThisDayTitle)
.description(WMFLocalizedString("widget-onthisday-description", value: "Explore what happened on this day in history.", comment: "Description for 'On this day' view in iOS widget gallery"))
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
// MARK: - TimelineProvider
struct OnThisDayProvider: TimelineProvider {
// MARK: Nested Types
public typealias Entry = OnThisDayEntry
// MARK: Properties
private let dataStore = OnThisDayData.shared
// MARK: TimelineProvider
func placeholder(in: Context) -> OnThisDayEntry {
return dataStore.placeholderEntryFromLanguage(nil)
}
func getTimeline(in context: Context, completion: @escaping (Timeline<OnThisDayEntry>) -> Void) {
dataStore.fetchLatestAvailableOnThisDayEntry { entry in
let currentDate = Date()
let nextUpdate: Date
if entry.error == nil && entry.isCurrent {
nextUpdate = currentDate.randomDateShortlyAfterMidnight() ?? currentDate
} else {
let components = DateComponents(hour: 2)
nextUpdate = Calendar.current.date(byAdding: components, to: currentDate) ?? currentDate
}
let timeline = Timeline(entries: [entry], policy: .after(nextUpdate))
completion(timeline)
}
}
func getSnapshot(in context: Context, completion: @escaping (OnThisDayEntry) -> Void) {
dataStore.fetchLatestAvailableOnThisDayEntry(usingCache: context.isPreview) { entry in
completion(entry)
}
}
}
/// A data source and operation helper for all On This Day of the day widget data
final class OnThisDayData {
enum ErrorType {
case noInternet, featureNotSupportedInLanguage
var errorColor: Color {
switch self {
case .featureNotSupportedInLanguage:
return Color(UIColor.base30)
case .noInternet:
return Color(white: 22/255)
}
}
var errorText: String {
/// These are intentionally in the iOS system language, not the app's primary language. Everything else in this widget is in the app's primary language.
switch self {
case .featureNotSupportedInLanguage:
return WMFLocalizedString("on-this-day-language-does-not-support-error", value: "Your primary Wikipedia language does not support On this day. You can update your primary Wikipedia in the app’s Settings menu.", comment: "Error message shown when the user's primary language Wikipedia does not have the 'On this day' feature.")
case .noInternet:
return WMFLocalizedString("on-this-day-no-internet-error", value: "No data available", comment: "error message shown when device is not connected to internet")
}
}
}
// MARK: Properties
static let shared = OnThisDayData()
// From https://en.wikipedia.org/api/rest_v1/feed/onthisday/events/01/15, taken on 03 Sept 2020.
func placeholderEntryFromLanguage(_ language: MWKLanguageLink?) -> OnThisDayEntry {
let locale = NSLocale.wmf_locale(for: language?.languageCode)
let isRTL = MWKLanguageLinkController.isLanguageRTL(forContentLanguageCode: language?.contentLanguageCode)
let fullDate: String
let eventYear: String
let monthDay: String
let calendar = NSCalendar.wmf_utcGregorian()
let date = calendar?.date(from: DateComponents(year: 2001, month: 01, day: 15, hour: 0, minute: 0, second: 0))
if let date = date {
let fullDateFormatter = DateFormatter.wmf_longDateGMTFormatter(for: language?.languageCode)
fullDate = fullDateFormatter.string(from: date)
let yearWithEraFormatter = DateFormatter.wmf_yearGMTDateFormatter(for: language?.languageCode)
eventYear = yearWithEraFormatter.string(from: date)
let monthDayFormatter = DateFormatter.wmf_monthNameDayNumberGMTFormatter(for: language?.languageCode)
monthDay = monthDayFormatter.string(from: date)
} else {
fullDate = "January 15, 2001"
eventYear = "2001"
monthDay = "January 15"
}
let eventSnippet = WMFLocalizedString("widget-onthisday-placeholder-event-snippet", languageCode: language?.languageCode, value: "Wikipedia, a free wiki content encyclopedia, goes online.", comment: "Placeholder text for On This Day widget: Event describing launch of Wikipedia")
let articleSnippet = WMFLocalizedString("widget-onthisday-placeholder-article-snippet", languageCode: language?.languageCode, value: "Free online encyclopedia that anyone can edit", comment: "Placeholder text for On This Day widget: Article description for an article about Wikipedia")
// It seems that projects whose article is not titled "Wikipedia" (Arabic, for instance) all redirect this URL appropriately.
let articleURL = URL(string: ((language?.siteURL.absoluteString ?? "https://en.wikipedia.org") + "/wiki/Wikipedia"))
let entry: OnThisDayEntry = OnThisDayEntry(isRTLLanguage: isRTL,
error: nil,
onThisDayTitle: CommonStrings.onThisDayTitle(with: language?.languageCode),
monthDay: monthDay,
fullDate: fullDate,
otherEventsText: CommonStrings.onThisDayFooterWith(with: 49, languageCode: language?.languageCode),
contentURL: URL(string: "https://en.wikipedia.org/wiki/Wikipedia:On_this_day/Today"),
eventSnippet: eventSnippet,
eventYear: eventYear,
eventYearsAgo: String(format: WMFLocalizedDateFormatStrings.yearsAgo(forWikiLanguage: language?.languageCode), locale: locale, (Calendar.current.component(.year, from: Date()) - 2001)),
articleTitle: CommonStrings.plainWikipediaName(with: language?.languageCode),
articleSnippet: articleSnippet,
articleImage: UIImage(named: "W"),
articleURL: articleURL,
yearRange: CommonStrings.onThisDayHeaderDateRangeMessage(with: language?.languageCode, locale: locale, lastEvent: "69", firstEvent: "2019"))
return entry
}
// MARK: Public
func fetchLatestAvailableOnThisDayEntry(usingCache: Bool = false, _ userCompletion: @escaping (OnThisDayEntry) -> Void) {
let widgetController = WidgetController.shared
widgetController.startWidgetUpdateTask(userCompletion) { (dataStore, widgetTaskCompletion) in
guard let appLanguage = dataStore.languageLinkController.appLanguage,
WMFOnThisDayEventsFetcher.isOnThisDaySupported(by: appLanguage.languageCode) else {
let errorEntry = OnThisDayEntry.errorEntry(for: .featureNotSupportedInLanguage)
widgetTaskCompletion(errorEntry)
return
}
widgetController.fetchNewestWidgetContentGroup(with: .onThisDay, in: dataStore, isNetworkFetchAllowed: !usingCache) { (contentGroup) in
guard let contentGroup = contentGroup else {
widgetTaskCompletion(self.placeholderEntryFromLanguage(dataStore.languageLinkController.appLanguage))
return
}
self.assembleOnThisDayFromContentGroup(contentGroup, dataStore: dataStore, usingImageCache: usingCache, completion: widgetTaskCompletion)
}
}
}
private func assembleOnThisDayFromContentGroup(_ contentGroup: WMFContentGroup, dataStore: MWKDataStore, usingImageCache: Bool = false, completion: @escaping (OnThisDayEntry) -> Void) {
guard let previewEvents = contentGroup.contentPreview as? [WMFFeedOnThisDayEvent],
let previewEvent = previewEvents.first,
let entry = OnThisDayEntry(contentGroup)
else {
let language = dataStore.languageLinkController.appLanguage
completion(placeholderEntryFromLanguage(language))
return
}
let sendDataToWidget: (UIImage?) -> Void = { image in
var entryWithImage = entry
entryWithImage.articleImage = image
completion(entryWithImage)
}
let imageURLRaw = previewEvent.articlePreviews?.first?.thumbnailURL
guard let imageURL = imageURLRaw, !usingImageCache else {
/// The argument sent to `sendDataToWidget` on the next line could be nil because `imageURLRaw` is nil, or `cachedImage` returns nil.
/// `sendDataToWidget` will appropriately handle a nil image, so we don't need to worry about that here.
let cachedImage = dataStore.cacheController.imageCache.cachedImage(withURL: imageURLRaw)?.staticImage
sendDataToWidget(cachedImage)
return
}
dataStore.cacheController.imageCache.fetchImage(withURL: imageURL, failure: { _ in
sendDataToWidget(nil)
}, success: { fetchedImage in
sendDataToWidget(fetchedImage.image.staticImage)
})
}
private func handleNoInternetError(_ completion: @escaping (OnThisDayEntry) -> Void) {
let errorEntry = OnThisDayEntry.errorEntry(for: .noInternet)
completion(errorEntry)
}
}
// MARK: - Model
struct OnThisDayEntry: TimelineEntry {
let date = Date()
var isCurrent: Bool = false
let isRTLLanguage: Bool
let error: OnThisDayData.ErrorType?
let onThisDayTitle: String
let monthDay: String
let fullDate: String
let otherEventsText: String
let contentURL: URL?
let eventSnippet: String?
let eventYear: String
let eventYearsAgo: String?
let articleTitle: String?
let articleSnippet: String?
var articleImage: UIImage?
let articleURL: URL?
let yearRange: String
}
extension OnThisDayEntry {
init?(_ contentGroup: WMFContentGroup) {
guard
let midnightUTCDate = contentGroup.midnightUTCDate,
let calendar = NSCalendar.wmf_utcGregorian(),
let previewEvents = contentGroup.contentPreview as? [WMFFeedOnThisDayEvent],
let previewEvent = previewEvents.first,
let allEvents = contentGroup.fullContent?.object as? [WMFFeedOnThisDayEvent],
let earliestEventYear = allEvents.last?.yearString,
let latestEventYear = allEvents.first?.yearString,
let article = previewEvents.first?.articlePreviews?.first,
let year = previewEvent.year?.intValue,
let eventsCount = contentGroup.countOfFullContent?.intValue
else {
return nil
}
let language = contentGroup.siteURL?.wmf_languageCode
let monthDayFormatter = DateFormatter.wmf_monthNameDayNumberGMTFormatter(for: language)
monthDay = monthDayFormatter.string(from: midnightUTCDate)
var components = calendar.components([.month, .year, .day], from: midnightUTCDate)
components.year = year
if let date = calendar.date(from: components) {
let fullDateFormatter = DateFormatter.wmf_longDateGMTFormatter(for: language)
fullDate = fullDateFormatter.string(from: date)
let yearWithEraFormatter = DateFormatter.wmf_yearGMTDateFormatter(for: language)
eventYear = yearWithEraFormatter.string(from: date)
} else {
fullDate = ""
eventYear = ""
}
onThisDayTitle = CommonStrings.onThisDayTitle(with: language)
isRTLLanguage = contentGroup.isRTL
error = nil
otherEventsText = CommonStrings.onThisDayFooterWith(with: (eventsCount - 1), languageCode: language)
eventSnippet = previewEvent.text
articleTitle = article.displayTitle
articleSnippet = article.descriptionOrSnippet
articleURL = article.articleURL
let locale = NSLocale.wmf_locale(for: language)
let currentYear = Calendar.current.component(.year, from: Date())
let yearsSinceEvent = currentYear - year
eventYearsAgo = String(format: WMFLocalizedDateFormatStrings.yearsAgo(forWikiLanguage: language), locale: locale, yearsSinceEvent)
yearRange = CommonStrings.onThisDayHeaderDateRangeMessage(with: language, locale: locale, lastEvent: earliestEventYear, firstEvent: latestEventYear)
if let previewEventIndex = allEvents.firstIndex(of: previewEvent),
let dynamicURL = URL(string: "https://en.wikipedia.org/wiki/Wikipedia:On_this_day/Today?\(previewEventIndex)") {
contentURL = dynamicURL
} else {
contentURL = URL(string: "https://en.wikipedia.org/wiki/Wikipedia:On_this_day/Today")
}
isCurrent = contentGroup.isForToday
}
static func errorEntry(for error: OnThisDayData.ErrorType) -> OnThisDayEntry {
let isRTL = Locale.lineDirection(forLanguage: Locale.autoupdatingCurrent.languageCode ?? "en") == .rightToLeft
let destinationURL = URL(string: "wikipedia://explore")
return OnThisDayEntry(isRTLLanguage: isRTL, error: error, onThisDayTitle: "", monthDay: "", fullDate: "", otherEventsText: "", contentURL: destinationURL, eventSnippet: nil, eventYear: "", eventYearsAgo: nil, articleTitle: nil, articleSnippet: nil, articleImage: nil, articleURL: nil, yearRange: "")
}
}
|
df64f007cf501477165d965caf1a92dc
| 49.647687 | 342 | 0.659219 | false | false | false | false |
wscqs/QSWB
|
refs/heads/master
|
DSWeibo/DSWeibo/Classes/Home/Popover/PopoverAnimator.swift
|
mit
|
1
|
//
// PopoverAnimator.swift
// DSWeibo
//
// Created by xiaomage on 15/9/9.
// Copyright © 2015年 小码哥. All rights reserved.
//
import UIKit
// 定义常量保存通知的名称
let XMGPopoverAnimatorWillShow = "XMGPopoverAnimatorWillShow"
let XMGPopoverAnimatorWilldismiss = "XMGPopoverAnimatorWilldismiss"
class PopoverAnimator: NSObject , UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning
{
/// 记录当前是否是展开
var isPresent: Bool = false
/// 定义属性保存菜单的大小
var presentFrame = CGRectZero
// 实现代理方法, 告诉系统谁来负责转场动画
// UIPresentationController iOS8推出的专门用于负责转场动画的
func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController?
{
let pc = PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting)
// 设置菜单的大小
pc.presentFrame = presentFrame
return pc
}
// MARK: - 只要实现了一下方法, 那么系统自带的默认动画就没有了, "所有"东西都需要程序员自己来实现
/**
告诉系统谁来负责Modal的展现动画
:param: presented 被展现视图
:param: presenting 发起的视图
:returns: 谁来负责
*/
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
isPresent = true
// 发送通知, 通知控制器即将展开
NSNotificationCenter.defaultCenter().postNotificationName(XMGPopoverAnimatorWillShow, object: self)
return self
}
/**
告诉系统谁来负责Modal的消失动画
:param: dismissed 被关闭的视图
:returns: 谁来负责
*/
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
isPresent = false
// 发送通知, 通知控制器即将消失
NSNotificationCenter.defaultCenter().postNotificationName(XMGPopoverAnimatorWilldismiss, object: self)
return self
}
// MARK: - UIViewControllerAnimatedTransitioning
/**
返回动画时长
:param: transitionContext 上下文, 里面保存了动画需要的所有参数
:returns: 动画时长
*/
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval
{
return 0.5
}
/**
告诉系统如何动画, 无论是展现还是消失都会调用这个方法
:param: transitionContext 上下文, 里面保存了动画需要的所有参数
*/
func animateTransition(transitionContext: UIViewControllerContextTransitioning)
{
// 1.拿到展现视图
if isPresent
{
// 展开
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
toView.transform = CGAffineTransformMakeScale(1.0, 0.0);
// 注意: 一定要将视图添加到容器上
transitionContext.containerView()?.addSubview(toView)
// 设置锚点
toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
// 2.执行动画
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
// 2.1清空transform
toView.transform = CGAffineTransformIdentity
}) { (_) -> Void in
// 2.2动画执行完毕, 一定要告诉系统
// 如果不写, 可能导致一些未知错误
transitionContext.completeTransition(true)
}
}else
{
// 关闭
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
// 注意:由于CGFloat是不准确的, 所以如果写0.0会没有动画
// 压扁
fromView?.transform = CGAffineTransformMakeScale(1.0, 0.000001)
}, completion: { (_) -> Void in
// 如果不写, 可能导致一些未知错误
transitionContext.completeTransition(true)
})
}
}
}
|
925a209baf24f650433e71aaacff1770
| 31.842975 | 217 | 0.645194 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Pages/PageListTableViewHandler.swift
|
gpl-2.0
|
2
|
import Foundation
final class PageListTableViewHandler: WPTableViewHandler {
var isSearching: Bool = false
var status: PostListFilter.Status = .published
var groupResults: Bool {
if isSearching {
return true
}
return status == .scheduled
}
private var pages: [Page] = []
private let blog: Blog
private lazy var publishedResultController: NSFetchedResultsController<NSFetchRequestResult> = {
let publishedFilter = PostListFilter.publishedFilter()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Page.entityName())
let predicate = NSPredicate(format: "\(#keyPath(Page.blog)) = %@ && \(#keyPath(Page.revision)) = nil", blog)
let predicates = [predicate, publishedFilter.predicateForFetchRequest]
fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
fetchRequest.sortDescriptors = publishedFilter.sortDescriptors
return resultsController(with: fetchRequest, context: managedObjectContext(), performFetch: false)
}()
private lazy var searchResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
return resultsController(with: fetchRequest(), context: managedObjectContext(), keyPath: BasePost.statusKeyPath, performFetch: false)
}()
private lazy var groupedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
return resultsController(with: fetchRequest(), context: managedObjectContext(), keyPath: sectionNameKeyPath())
}()
private lazy var flatResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
return resultsController(with: fetchRequest(), context: managedObjectContext())
}()
init(tableView: UITableView, blog: Blog) {
self.blog = blog
super.init(tableView: tableView)
}
override var resultsController: NSFetchedResultsController<NSFetchRequestResult> {
if isSearching {
return searchResultsController
}
return groupResults ? groupedResultsController : flatResultsController
}
override func refreshTableView() {
refreshTableView(at: nil)
}
func refreshTableView(at indexPath: IndexPath?) {
super.clearCachedRowHeights()
do {
try resultsController.performFetch()
pages = setupPages()
} catch {
DDLogError("Error fetching pages after refreshing the table: \(error)")
}
if let indexPath = indexPath {
tableView.reloadSections(IndexSet(integer: indexPath.section), with: .fade)
} else {
tableView.reloadData()
}
}
// MARK: - Public methods
func page(at indexPath: IndexPath) -> Page {
guard groupResults else {
return pages[indexPath.row]
}
guard let page = resultsController.object(at: indexPath) as? Page else {
// Retrieveing anything other than a post object means we have an app with an invalid
// state. Ignoring this error would be counter productive as we have no idea how this
// can affect the App. This controlled interruption is intentional.
//
// - Diego Rey Mendez, May 18 2016
//
fatalError("Expected a Page object.")
}
return page
}
func index(for page: Page) -> Int? {
return pages.firstIndex(of: page)
}
func removePage(from index: Int?) -> [Page] {
guard let index = index, status == .published else {
do {
try publishedResultController.performFetch()
if let pages = publishedResultController.fetchedObjects as? [Page] {
return pages.setHomePageFirst().hierarchySort()
}
} catch {
DDLogError("Error fetching pages after refreshing the table: \(error)")
}
return []
}
return pages.remove(from: index)
}
// MARK: - Override TableView Datasource
override func numberOfSections(in tableView: UITableView) -> Int {
return groupResults ? super.numberOfSections(in: tableView) : 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groupResults ? super.tableView(tableView, numberOfRowsInSection: section) : pages.count
}
// MARK: - Private methods
private func resultsController(with request: NSFetchRequest<NSFetchRequestResult>?,
context: NSManagedObjectContext?,
keyPath: String? = nil,
performFetch: Bool = true) -> NSFetchedResultsController<NSFetchRequestResult> {
guard let request = request, let context = context else {
fatalError("A request and a context must exist")
}
let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: keyPath, cacheName: nil)
if performFetch {
do {
try controller.performFetch()
} catch {
DDLogError("Error fetching pages after refreshing the table: \(error)")
}
}
return controller
}
private func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>? {
return delegate?.fetchRequest()
}
private func managedObjectContext() -> NSManagedObjectContext? {
return delegate?.managedObjectContext()
}
private func sectionNameKeyPath() -> String? {
return delegate?.sectionNameKeyPath!()
}
private func setupPages() -> [Page] {
guard !groupResults, let pages = resultsController.fetchedObjects as? [Page] else {
return []
}
return status == .published ? pages.setHomePageFirst().hierarchySort() : pages
}
}
|
bfd283a2d51ab3f89fb6bb8e0e3226a4
| 34.672619 | 150 | 0.64008 | false | false | false | false |
ObjectAlchemist/OOUIKit
|
refs/heads/master
|
Sources/_UIKitDelegate/UIApplicationDelegate/ContinuingUserActivityAndHandlingQuickActions/UIApplicationDelegateUserActivityPrinting.swift
|
mit
|
1
|
//
// UIApplicationDelegateUserActivityPrinting.swift
// OOSwift
//
// Created by Karsten Litsche on 28.10.17.
//
//
import UIKit
/**
Print the UIApplicationDelegate section:
- Continuing User Activity and Handling Quick Actions
Use this decorator to log the print outputs while development/debugging. Define a filterKey if you need a
clear identification of this instance.
For more informations see UIPrintOverload.swift and UIApplicationDelegate documentation
*/
public final class UIApplicationDelegateUserActivityPrinting: UIResponder, UIApplicationDelegate {
// MARK: - init
convenience override init() {
fatalError("Not supported!")
}
public init(_ decorated: UIApplicationDelegate, filterKey: String = "") {
self.decorated = decorated
// add space if exist to separate following log
self.filterKey = filterKey.count == 0 ? "" : "\(filterKey) "
}
// MARK: - protocol: UIApplicationDelegate
public func application(_ application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool {
printUI("\(filterKey)application willContinueUserActivity called (\n userActivityType=\(userActivityType)\n)")
return decorated.application?(application, willContinueUserActivityWithType: userActivityType) ?? false
}
public func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Swift.Void) -> Bool {
// Note: calling the handler is optional
printUI("\(filterKey)application continueUserActivity called (\n userActivityType=\(userActivity.activityType)\n)")
return decorated.application?(application, continue: userActivity, restorationHandler: restorationHandler) ?? false
}
public func application(_ application: UIApplication, didUpdate userActivity: NSUserActivity) {
printUI("\(filterKey)application didUpdate called (\n userActivityType=\(userActivity.activityType)\n)")
decorated.application?(application, didUpdate: userActivity)
}
public func application(_ application: UIApplication, didFailToContinueUserActivityWithType userActivityType: String, error: Error) {
printUI("\(filterKey)application didFailToContinueUserActivity called (\n userActivityType=\(userActivityType)\n error=\(error.localizedDescription)\n)")
decorated.application?(application, didFailToContinueUserActivityWithType: userActivityType, error: error)
}
public func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Swift.Void) {
printUI("\(filterKey)application performActionForShortcutItem called (\n shortcutItemType=\(shortcutItem.type)\n)")
if decorated.application?(application, performActionFor: shortcutItem, completionHandler: completionHandler) == nil {
completionHandler(true)
}
}
// MARK: - private
private let decorated: UIApplicationDelegate
private let filterKey: String
}
|
e62d0300ac8ae4440e099a55c749c82e
| 44.913043 | 180 | 0.734533 | false | false | false | false |
mactive/rw-courses-note
|
refs/heads/master
|
advanced-swift-types-and-operations/TypesAndOps.playground/Pages/Equality.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
import Foundation
struct Email: Equatable {
// add some validation
init?(_ raw: String) {
guard raw.contains("@") else {
return nil
}
address = raw
}
private(set) var address: String
}
class User: Equatable {
var id: Int?
var name: String
var email: Email
init(id: Int?, name: String, email: Email) {
self.id = id
self.name = name
self.email = email
}
static func ==(lhs: User, rhs: User) -> Bool {
return lhs.id == rhs.id &&
lhs.email == rhs.email &&
lhs.name == rhs.name
}
}
guard let email = Email("[email protected]") else {
fatalError("Not valid email")
}
email.address
let user1 = User(id: nil, name: "Ray", email: email)
let user2 = User(id: nil, name: "Ray", email: email)
user1 == user2
user1 === user2
//: [Next](@next)
|
15d58938ab102916622df8ed18134deb
| 19 | 52 | 0.554444 | false | false | false | false |
shepting/AutoLayout
|
refs/heads/master
|
AutoLayoutDemo/AutoLayoutDemo/KeyboardAvoider.swift
|
mit
|
1
|
//
// KeyboardAvoider.swift
// AutoLayoutDemo
//
// Created by Steven Hepting on 8/22/14.
// Copyright (c) 2014 Protospec. All rights reserved.
//
import UIKit
class KeyboardAvoider: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init () {
super.init()
commonInit()
}
weak var scrollView: UIScrollView?
var heightConstraint: NSLayoutConstraint = NSLayoutConstraint()
func commonInit() {
setTranslatesAutoresizingMaskIntoConstraints(false)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
heightConstraint = self.constraintWithFormat("V:[self(0)]", views:["self": self])
addConstraint(heightConstraint)
self.addVisualConstraints("H:[self(300@250)]", views: ["self":self]) // Low priority default width
}
func keyboardWillShow(notification: NSNotification) {
// Save the height of keyboard and animation duration
let userInfo: NSDictionary = notification.userInfo!
let endFrame: NSValue = userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue
let keyboardRect: CGRect = endFrame.CGRectValue()
let convertedRect = convertRect(keyboardRect, fromView: nil) // Convert from window coordinates
let height = CGRectGetHeight(convertedRect)
heightConstraint.constant = height
if let scrollView = scrollView {
scrollView.contentInset = UIEdgeInsetsMake(0, 0, height, 0)
}
animateSizeChange()
}
func keyboardWillHide(notification: NSNotification) {
heightConstraint.constant = 0.0
animateSizeChange()
}
override func intrinsicContentSize() -> CGSize {
return CGSizeMake(320, UIViewNoIntrinsicMetric)
}
func animateSizeChange() {
self.setNeedsUpdateConstraints()
// Animate transition
UIView.animateWithDuration(0.3, animations: {
self.superview!.layoutIfNeeded()
})
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
|
b4906bb231f8f0f1ac12d20119d4f65d
| 32.472222 | 154 | 0.66971 | false | false | false | false |
breadwallet/breadwallet-core
|
refs/heads/develop
|
Swift/BRCrypto/BRCryptoAddress.swift
|
mit
|
1
|
//
// BRCryptoAddress.swift
// BRCrypto
//
// Created by Ed Gamble on 6/7/19.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
//
import BRCryptoC
///
/// An Address for transferring an amount. Addresses are network specific.
///
public final class Address: Equatable, CustomStringConvertible {
let core: BRCryptoAddress
internal init (core: BRCryptoAddress, take: Bool) {
self.core = take ? cryptoAddressTake(core) : core
}
internal convenience init (core: BRCryptoAddress) {
self.init (core: core, take: true)
}
public private(set) lazy var description: String = {
return asUTF8String (cryptoAddressAsString (core), true)
}()
///
/// Create an Addres from `string` and `network`. The provided `string` must be valid for
/// the provided `network` - that is, an ETH address (as a string) differs from a BTC address
/// and a BTC mainnet address differs from a BTC testnet address. If `string` is not
/// appropriate for `network`, then `nil` is returned.
///
/// This function is typically used to convert User input - of a 'target address' as a string -
/// into an Address.
///
/// - Parameters:
/// - string: A string representing a crypto address
/// - network: The network for which the string is value
///
/// - Returns: An address or nil if `string` is invalide for `network`
///
public static func create (string: String, network: Network) -> Address? {
return cryptoAddressCreateFromString (network.core, string)
.map { Address (core: $0, take: false) }
}
deinit {
cryptoAddressGive (core)
}
public static func == (lhs: Address, rhs: Address) -> Bool {
return CRYPTO_TRUE == cryptoAddressIsIdentical (lhs.core, rhs.core)
}
}
///
/// An AddressScheme determines the from of wallet-generated address. For example, a Bitcoin wallet
/// can have a 'Segwit/BECH32' address scheme or a 'Legacy' address scheme. The address, which is
/// ultimately a sequence of bytes, gets formatted as a string based on the scheme.
///
/// The WalletManager holds an array of AddressSchemes as well as the preferred AddressScheme.
///
public enum AddressScheme: Equatable, CustomStringConvertible {
case btcLegacy
case btcSegwit
case ethDefault
case genDefault
internal init (core: BRCryptoAddressScheme) {
switch core {
case CRYPTO_ADDRESS_SCHEME_BTC_LEGACY: self = .btcLegacy
case CRYPTO_ADDRESS_SCHEME_BTC_SEGWIT: self = .btcSegwit
case CRYPTO_ADDRESS_SCHEME_ETH_DEFAULT: self = .ethDefault
case CRYPTO_ADDRESS_SCHEME_GEN_DEFAULT: self = .genDefault
default: self = .genDefault; preconditionFailure()
}
}
internal var core: BRCryptoAddressScheme {
switch self {
case .btcLegacy: return CRYPTO_ADDRESS_SCHEME_BTC_LEGACY
case .btcSegwit: return CRYPTO_ADDRESS_SCHEME_BTC_SEGWIT
case .ethDefault: return CRYPTO_ADDRESS_SCHEME_ETH_DEFAULT
case .genDefault: return CRYPTO_ADDRESS_SCHEME_GEN_DEFAULT
}
}
public var description: String {
switch self {
case .btcLegacy: return "BTC Legacy"
case .btcSegwit: return "BTC Segwit"
case .ethDefault: return "ETH Default"
case .genDefault: return "GEN Default"
}
}
}
|
66bdb55c509b571872f49b733fd1bef1
| 34.47 | 100 | 0.664787 | false | false | false | false |
ephread/Instructions
|
refs/heads/main
|
Examples/Example/Unit Tests/Managers/Internal/OverlayStyleManager/BlurringOverlayStyleManagerTest.swift
|
mit
|
1
|
// Copyright (c) 2017-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import XCTest
@testable import Instructions
class BlurringOverlayStyleManagerTest: XCTestCase {
private let overlayView = OverlayView()
private let blurringStyleManager = BlurringOverlayStyleManager(style: .extraLight)
private let snapshotDelegate = SnapshotDelegate() // swiftlint:disable:this weak_delegate
var viewIsVisibleExpectation: XCTestExpectation?
override func setUp() {
super.setUp()
overlayView.frame = CGRect(x: 0, y: 0, width: 365, height: 667)
overlayView.alpha = 0.0
blurringStyleManager.overlayView = overlayView
blurringStyleManager.snapshotDelegate = snapshotDelegate
}
override func tearDown() {
super.tearDown()
viewIsVisibleExpectation = nil
}
func testThatOverlayIsShown() {
self.viewIsVisibleExpectation = self.expectation(description: "viewIsVisible")
blurringStyleManager.showOverlay(true, withDuration: 1.0) { _ in
XCTAssertEqual(self.overlayView.alpha, 1.0)
XCTAssertEqual(self.overlayView.isHidden, false)
let containsBlur = self.overlayView.holder.subviews
.filter { $0 is UIVisualEffectView }
.count == 2
XCTAssertTrue(containsBlur)
self.viewIsVisibleExpectation?.fulfill()
}
self.waitForExpectations(timeout: 1.1) { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func testThatOverlayIsHidden() {
viewIsVisibleExpectation = expectation(description: "viewIsVisible")
blurringStyleManager.showOverlay(false, withDuration: 1.0) { _ in
XCTAssertEqual(self.overlayView.alpha, 0.0)
XCTAssertTrue(self.overlayView.holder.subviews.count == 1)
self.viewIsVisibleExpectation?.fulfill()
}
self.waitForExpectations(timeout: 1.1) { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
}
}
}
private class SnapshotDelegate: Snapshottable {
func snapshot() -> UIView? {
return UIView()
}
}
|
81be7946bc64ae1d81ee13a2039a4f5b
| 30.88 | 93 | 0.63279 | false | true | false | false |
zhiquan911/CHSlideSwitchView
|
refs/heads/master
|
CHSlideSwitchView/Classes/CHSlideItem.swift
|
mit
|
1
|
//
// CHSlideItem.swift
// Pods
//
// Created by Chance on 2017/6/5.
//
//
import Foundation
///
/// 标签元素类型
///
/// - view: 视图
/// - viewController: 视图控制器
public enum CHSlideItemType {
public typealias GetViewController = () -> UIViewController
public typealias GetView = () -> UIView
case view(GetView)
case viewController(GetViewController)
/// 通过block获取实体
var entity: AnyObject {
switch self {
case let .view(block):
return block()
case let .viewController(block):
return block()
}
}
}
/// Tab实体类型
///
/// - text: 文字,组件使用默认的View样式展示文字,默认颜色,选中效果
/// - view: 自定义View
public enum CHSlideTabType {
case text
case view
}
/// 标签元素定义
public class CHSlideItem {
// /// 标签
// public var key: Int = 0
/// 标题
public var title: String = ""
/// 标签View
public var tabView: UIView?
/// 类型
public var content: CHSlideItemType!
public convenience init(title: String = "", tabView: UIView? = nil, content: CHSlideItemType) {
self.init()
// self.key = key
self.title = title
self.tabView = tabView
self.content = content
}
}
|
87b7168597dd6701cc58527fd9b4a6a6
| 15.773333 | 99 | 0.556439 | false | false | false | false |
paulofaria/swift-apex
|
refs/heads/master
|
Sources/Apex/Reflection/Construct.swift
|
mit
|
1
|
/// Create a class or struct with a constructor method. Return a value of `property.type` for each property. Classes must conform to `Initializable`.
public func construct<T>(_ type: T.Type = T.self, constructor: (Property.Description) throws -> Any) throws -> T {
if Metadata(type: T.self)?.kind == .struct {
return try constructValueType(constructor)
} else {
throw ReflectionError.notStruct(type: T.self)
}
}
private func constructValueType<T>(_ constructor: (Property.Description) throws -> Any) throws -> T {
guard Metadata(type: T.self)?.kind == .struct else { throw ReflectionError.notStruct(type: T.self) }
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
defer { pointer.deallocate(capacity: 1) }
var values: [Any] = []
let p = UnsafeMutableRawPointer(pointer).assumingMemoryBound(to: UInt8.self)
try constructType(storage: p, values: &values, properties: properties(T.self), constructor: constructor)
return pointer.move()
}
private func constructType(storage: UnsafeMutablePointer<UInt8>, values: inout [Any], properties: [Property.Description], constructor: (Property.Description) throws -> Any) throws {
for property in properties {
var anyValue = try constructor(property)
guard value(anyValue, is: property.type) else { throw ReflectionError.valueIsNotType(value: anyValue, type: property.type) }
values.append(anyValue)
storage.advanced(by: property.offset).consume(buffer: buffer(instance: &anyValue))
}
}
/// Create a class or struct from a dictionary. Classes must conform to `Initializable`.
public func construct<T>(_ type: T.Type = T.self, dictionary: [String: Any]) throws -> T {
return try construct(constructor: constructorForDictionary(dictionary))
}
private func constructorForDictionary(_ dictionary: [String: Any]) -> (Property.Description) throws -> Any {
return { property in
if let value = dictionary[property.key] {
return value
} else if let expressibleByNilLiteral = property.type as? ExpressibleByNilLiteral.Type {
return expressibleByNilLiteral.init(nilLiteral: ())
} else {
throw ReflectionError.requiredValueMissing(key: property.key)
}
}
}
|
4a444b443c36350972018c6ef168068d
| 50.613636 | 181 | 0.704535 | false | false | false | false |
kosicki123/eidolon
|
refs/heads/master
|
Kiosk/Admin/AdminCardTestingViewController.swift
|
mit
|
1
|
import Foundation
class AdminCardTestingViewController: UIViewController {
lazy var keys = EidolonKeys()
var cardHandler: CardHandler!
@IBOutlet weak var logTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
self.logTextView.text = ""
let merchantToken = AppSetup.sharedState.useStaging ? self.keys.cardflightMerchantAccountStagingToken() : self.keys.cardflightMerchantAccountToken()
cardHandler = CardHandler(apiKey: self.keys.cardflightAPIClientKey(), accountToken:merchantToken)
cardHandler.cardSwipedSignal.subscribeNext({ (message) -> Void in
self.log("\(message)")
return
}, error: { (error) -> Void in
self.log("\n====Error====\n\(error)\n\n")
if self.cardHandler.card != nil {
self.log("==\n\(self.cardHandler.card!)\n\n")
}
}, completed: {
if let card = self.cardHandler.card {
let cardDetails = "Card: \(card.name) - \(card.encryptedSwipedCardNumber) \n \(card.cardToken)"
self.log(cardDetails)
}
self.cardHandler.startSearching()
})
cardHandler.startSearching()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
cardHandler.end()
}
func log(string: String) {
self.logTextView.text = "\(self.logTextView.text)\n\(string)"
}
@IBAction func backTapped(sender: AnyObject) {
navigationController?.popViewControllerAnimated(true)
}
}
|
ffd74ecc54188626f2fec0db48e8acda
| 27.305085 | 156 | 0.596165 | false | false | false | false |
mcjcloud/Show-And-Sell
|
refs/heads/master
|
Show And Sell/FindGroupTableViewController.swift
|
apache-2.0
|
1
|
//
// FindGroupViewController.swift
// Show And Sell
//
// Created by Brayden Cloud on 10/21/16.
// Copyright © 2016 Brayden Cloud. All rights reserved.
//
import UIKit
import CoreLocation
class FindGroupTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate, CLLocationManagerDelegate {
// reference
var loginVC: LoginViewController! // reference to prevent garbage collection
// UI Elements
@IBOutlet var doneButton: UIBarButtonItem!
@IBOutlet var addButton: UIBarButtonItem!
var searchController: UISearchController!
var oldGroup: Group?
var currentGroup: Group? {
willSet {
oldGroup = currentGroup
}
didSet {
print("done button enabled: \(doneButton)")
doneButton.isEnabled = currentGroup != nil
}
}
var groups: [Group] = [Group]()
var filteredGroups: [Group] = [Group]()
var searchedGroups: [Group] = [Group]()
// segue -
var previousVC: UIViewController?
// location
var locationManager: CLLocationManager!
// data
let loadInterval = 10
let groupRadius: Float = 10.0
var locationAuth = false
var coordinates: CLLocationCoordinate2D?
var overlay = OverlayView(type: .loading, text: nil)
override func viewDidLoad() {
print()
print("finder view did load")
super.viewDidLoad()
// set current group
currentGroup = AppData.group
oldGroup = currentGroup
if currentGroup == nil {
doneButton.isEnabled = false
}
// setup search bar
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
// request location
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
overlay.showOverlay(view: UIApplication.shared.keyWindow!, position: .center) // display loading while we get location
// get other groups and use activity indicator.
self.refreshControl = UIRefreshControl()
self.refreshControl?.backgroundColor = UIColor(colorLiteralRed: 0.871, green: 0.788, blue: 0.380, alpha: 1.0) // Gold
self.refreshControl!.addTarget(self, action: #selector(handleRefresh(_:)), for: .valueChanged)
}
override func viewWillAppear(_ animated: Bool) {
// when the view appears, check if the addButton should be enabled
addButton.isEnabled = shouldEnableAddButton()
}
// MARK: Tableview
override func numberOfSections(in tableView: UITableView) -> Int {
return currentGroup != nil ? 2 : 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView.numberOfSections > 1 {
if searchController.isActive && searchController.searchBar.text! != "" {
return section == 0 ? 1 : filteredGroups.count
}
else {
return section == 0 ? 1 : groups.count
}
}
else {
return (searchController.isActive && searchController.searchBar.text! != "") ? filteredGroups.count : groups.count
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// if there's more than one section, titles are "Current Group" and "Groups", respectively
if tableView.numberOfSections > 1 {
return section == 0 ? "Current Group" : "Groups"
}
// if there's only one section, it's just "Groups"
else {
return "Groups"
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> FindGroupTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "findGroupCell") as! FindGroupTableViewCell
cell.checkBox.image = nil
if tableView.numberOfSections > 1 { // if the table view has more than one section
if indexPath.section == 0 { // if its the first row.
cell.nameLabel.text = currentGroup?.name
cell.checkBox.image = UIImage(named: "green-check")
}
else {
if (searchController.isActive && searchController.searchBar.text! != "") {
cell.nameLabel.text = filteredGroups[indexPath.row].name
cell.checkBox.image = nil
}
else {
cell.nameLabel.text = groups[indexPath.row].name
cell.checkBox.image = nil
}
}
}
else { // if there is only one section.
cell.nameLabel.text = groups[indexPath.row].name
cell.checkBox.image = nil
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// return if you select the current group
if currentGroup != nil && indexPath.section == 0 {
print("current group section selected")
tableView.reloadData()
return
}
// make the selected cell the current group, reload the table.
currentGroup = (searchController.isActive && searchController.searchBar.text! != "") ? filteredGroups[indexPath.row] : groups[indexPath.row]
AppData.group = currentGroup
self.tableView.reloadData()
}
// MARK: Location
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("did change authorization")
if status == .authorizedWhenInUse {
if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) && CLLocationManager.isRangingAvailable() {
// location is working
locationAuth = true
locationManager.startUpdatingLocation()
}
}
else {
overlay.hideOverlayView()
locationAuth = false
}
}
// when the location is recieved, update the global variable
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last?.coordinate
self.coordinates = location
manager.stopUpdatingLocation()
// stop loading
overlay.hideOverlayView()
locationAuth = true
// start refresh manually
self.refreshControl!.beginRefreshing()
handleRefresh(self.refreshControl!)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// an error occurred getting location. Use non-location group loading.
// stop loading
overlay.hideOverlayView()
locationAuth = false
// start refresh
self.refreshControl!.beginRefreshing()
handleRefresh(self.refreshControl!)
}
// MARK: IBAction
@IBAction func donePressed(_ sender: UIBarButtonItem) {
print("done pressed")
print("previousVC: \(self.previousVC)")
// determine where to go
if let _ = previousVC as? LoginViewController {
// the last screen was the login or create, so go to tabs
if currentGroup != oldGroup {
// clear the data
AppDelegate.tabVC?.clearBrowseData()
}
self.performSegue(withIdentifier: "finderToTabs", sender: self)
}
else if let _ = previousVC as? IntroViewController {
// the last screen was the login or create, so go to tabs
if currentGroup != oldGroup {
// clear the data
AppDelegate.tabVC?.clearBrowseData()
}
self.performSegue(withIdentifier: "finderToTabs", sender: self)
}
else {
// dismiss to whatever you were previously at
self.dismiss(animated: true, completion: nil)
}
}
// function to handle the data refreshing
func handleRefresh(_ refreshControl: UIRefreshControl) {
if locationAuth {
if let loc = coordinates {
print("getting by location")
print("lat: \(loc.latitude) long: \(loc.longitude)")
HttpRequestManager.groups(inRadius: groupRadius, fromLatitude: loc.latitude, longitude: loc.longitude) { groups, response, error in
self.groups = groups
DispatchQueue.main.async {
self.refreshControl!.endRefreshing()
self.tableView.reloadData()
}
}
return
}
}
print("getting all groups")
HttpRequestManager.groups { groups, response, error in
print("error: \(error)")
self.groups = groups
// update the UI in the main thread
DispatchQueue.main.async {
self.refreshControl!.endRefreshing()
self.tableView.reloadData()
}
}
}
// MARK: Navigation
@IBAction func unwindToFinder(_ segue: UIStoryboardSegue) {
print("finder unwind")
}
// MARK: Searchbar
func filterGroups(for searchText: String) {
filteredGroups = groups.filter {
return $0.name.lowercased().contains(searchText.lowercased())
}
}
func updateSearchResults(for searchController: UISearchController) {
//filterGroups(for: searchController.searchBar.text!)
//tableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
// make search request
HttpRequestManager.groups(matching: searchBar.text ?? "") { groups, response, error in
print("searched: \(groups)")
self.filteredGroups = groups
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
// MARK: Helper
// returns if true if there is the user doesn't have a group
func shouldEnableAddButton() -> Bool {
return AppData.myGroup == nil
}
}
|
c72feb502949c16672e5ea676020e68e
| 35.79661 | 148 | 0.594012 | false | false | false | false |
quadro5/swift3_L
|
refs/heads/master
|
swift_question.playground/Pages/Let88 Merge Sorted Array.xcplaygroundpage/Contents.swift
|
unlicense
|
1
|
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
class Solution {
func merge2(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {
var index = m + n - 1
var indexNum1 = m - 1
var indexNum2 = n - 1
while index >= 0 {
//nums1[index] = nums1[indexNum1] > nums2[indexNum2] ? nums1[indexNum1] : nums2[indexNum2]
if indexNum1 >= 0, indexNum2 >= 0 {
if nums1[indexNum1] > nums2[indexNum2] {
nums1[index] = nums1[indexNum1]
indexNum1 -= 1
} else {
nums1[index] = nums2[indexNum2]
indexNum2 -= 1
}
} else if indexNum1 >= 0 {
nums1[index] = nums1[indexNum1]
indexNum1 -= 1
} else {
nums1[index] = nums2[indexNum2]
indexNum2 -= 1
}
index -= 1
}
}
func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {
var index = m + n - 1
var indexNum1 = m - 1
var indexNum2 = n - 1
// replace x > y ? ... : ...;
func calculate(index1: inout Int, index2: inout Int) -> Int {
var res = 0
if nums1[indexNum1] > nums2[indexNum2] {
res = nums1[indexNum1]
indexNum1 -= 1
return res
}
res = nums2[indexNum2]
indexNum2 -= 1
return res
}
while index >= 0 {
if indexNum1 >= 0, indexNum2 >= 0 {
nums1[index] = calculate(index1: &indexNum1, index2: &indexNum2)
} else if indexNum2 >= 0 {
nums1[index] = nums2[indexNum2]
indexNum2 -= 1
}
index -= 1
}
}
}
|
a459de760c1e46578048765d5840ec3d
| 28.227273 | 102 | 0.427386 | false | false | false | false |
MKGitHub/JSONX
|
refs/heads/master
|
JSONX.playground/Sources/JSONX.swift
|
apache-2.0
|
2
|
//
// JSONX
// Copyright © 2016/2017/2018 Mohsan Khan. All rights reserved.
//
//
// https://github.com/MKGitHub/JSONX
// http://www.xybernic.com
//
//
// Copyright 2016/2017/2018 Mohsan Khan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/**
The core class of `JSONX`.
*/
public final class JSONX
{
// MARK: Private Members
private let mJSONDictionary:Dictionary<String, Any>!
private let mJSONNSDictionary:NSDictionary!
// MARK:- Life Cycle
/**
Init with a `String`.
- Parameter string: The string to init `JSONX` with e.g. "{'name':'Khan Solo'}".
- Parameter usesSingleQuotes: Set to true and use single quotes in the string without the need to escape double quotes.
*/
public convenience init?(string:String, usesSingleQuotes:Bool=false)
{
// must have a string
guard (string.count > 0) else { return nil }
var stringToUse:String = string
if (usesSingleQuotes) {
stringToUse = JSONX.convertSingleQuotesToDoubleQuotes(stringToUse)
}
guard let data:Data = stringToUse.data(using:.utf8) else
{
print("🎭 JSONX failed: Could not convert string to JSON!")
return nil
}
self.init(data:data)
}
/**
Init with a file path.
- Parameter filepath: A path to a file.
*/
public convenience init?(filepath:String)
{
do
{
let fileContents:String = try String(contentsOfFile:filepath, encoding:.utf8)
if let data:Data = fileContents.data(using:.utf8)
{
self.init(data:data)
return
}
return nil
}
catch let error
{
print("🎭 JSONX failed: \(error.localizedDescription)")
return nil
}
}
/**
Init with a file `URL`.
- Parameter url: An `URL` to a file.
*/
public convenience init?(url:URL)
{
do
{
let data:Data = try Data(contentsOf:url)
self.init(data:data)
}
catch let error
{
print("🎭 JSONX failed: \(error.localizedDescription)")
return nil
}
}
/**
Init with `Data`.
- Parameter data: A `Data` object.
*/
public init?(data:Data)
{
do
{
let dictionary:Dictionary<String, Any> = try JSONSerialization.jsonObject(with:data, options:[.allowFragments]) as! Dictionary<String, Any>
// must have a dictionary
guard (dictionary.count > 0) else { return nil }
mJSONDictionary = dictionary
mJSONNSDictionary = dictionary as NSDictionary
}
catch let error
{
print("🎭 JSONX failed: \(error.localizedDescription)")
return nil
}
}
/**
Init with a `Dictionary`.
- Parameter dictionary: A `Dictionary` object.
*/
public init?(dictionary:Dictionary<String, Any>)
{
// must have a dictionary
guard (dictionary.count > 0) else { return nil }
mJSONDictionary = dictionary
mJSONNSDictionary = dictionary as NSDictionary
}
// MARK:- Accessors:Key
/**
The value as it is in its raw uncasted format.
I.e. there is no casting to a specific type like in the other "as" functions.
- Parameters:
- key: The key.
- `default`: Default value if the key is not found.
- Returns: The value for the key, or the default value.
*/
public func asRaw(_ key:String, `default`:Any?=nil) -> Any?
{
// if key exists and value is a Any return Any
// if key exists and value is null return `default`
// if key does not exist, return `default`
let v:Any? = mJSONDictionary[key]
if (!(v is NSNull) && (v != nil))
{
return v
}
return `default`
}
/**
The value as a `Bool`.
- Parameters:
- key: The key.
- `default`: Default value if the key is not found.
- Returns: The value for the key, or the default value.
*/
public func asBool(_ key:String, `default`:Bool?=nil) -> Bool?
{
// if key exists and value is a Bool return Bool
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Bool = mJSONDictionary[key] as? Bool
{
return v
}
return `default`
}
/**
The value as a `UInt`.
- Parameters:
- key: The key.
- `default`: Default value if the key is not found.
- Returns: The value for the key, or the default value.
*/
public func asUInt(_ key:String, `default`:UInt?=nil) -> UInt?
{
// if key exists and value is a UInt return UInt
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Int = mJSONDictionary[key] as? Int, (v >= 0)
{
return UInt(v)
}
return `default`
}
/**
The value as a `Int`.
- Parameters:
- key: The key.
- `default`: Default value if the key is not found.
- Returns: The value for the key, or the default value.
*/
public func asInt(_ key:String, `default`:Int?=nil) -> Int?
{
// if key exists and value is a Int return Int
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Int = mJSONDictionary[key] as? Int
{
return v
}
return `default`
}
/**
The value as a `Float`.
- Parameters:
- key: The key.
- `default`: Default value if the key is not found.
- Returns: The value for the key, or the default value.
*/
public func asFloat(_ key:String, `default`:Float?=nil) -> Float?
{
// if key exists and value is a Float return Float
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Double = mJSONDictionary[key] as? Double
{
return Float(v) // loss of precision
}
return `default`
}
/**
The value as a `Double`.
- Parameters:
- key: The key.
- `default`: Default value if the key is not found.
- Returns: The value for the key, or the default value.
*/
public func asDouble(_ key:String, `default`:Double?=nil) -> Double?
{
// if key exists and value is a Double return Double
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Double = mJSONDictionary[key] as? Double
{
return v
}
return `default`
}
/**
The value as a `String`.
- Parameters:
- key: The key.
- `default`: Default value if the key is not found.
- Returns: The value for the key, or the default value.
*/
public func asString(_ key:String, `default`:String?=nil) -> String?
{
// if key exists and value is a String return String
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:String = mJSONDictionary[key] as? String
{
return v
}
return `default`
}
/**
The value as a `Array`.
- Parameters:
- key: The key.
- `default`: Default value if the key is not found.
- Returns: The value for the key, or the default value.
*/
public func asArray(_ key:String, `default`:Array<Any>?=nil) -> Array<Any>?
{
// if key exists and value is a Array<Any> return Array<Any>
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Array<Any> = mJSONDictionary[key] as? Array<Any>
{
return v
}
return `default`
}
/**
The value as a `Dictionary`.
- Parameters:
- key: The key.
- `default`: Default value if the key is not found.
- Returns: The value for the key, or the default value.
*/
public func asDictionary(_ key:String, `default`:Dictionary<String, Any>?=nil) -> Dictionary<String, Any>?
{
// if key exists and value is a Dictionary<String, Any> return Dictionary<String, Any>
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Dictionary<String, Any> = mJSONDictionary[key] as? Dictionary<String, Any>
{
return v
}
return `default`
}
// MARK:- Accessors:Key Path
/**
The value as it is in its raw uncasted format.
I.e. there is no casting to a specific type like in the other "as" functions.
- Parameters:
- keyPath: The key path.
- `default`: Default value if the key in the path is not found.
- Returns: The value for the key path, or the default value.
*/
public func asRaw(inKeyPath keyPath:String, `default`:Any?=nil) -> Any?
{
//
// NOTE!
// We can't use NSDictionary.value(forKeyPath:keyPath) here since there may be non-existing keys in the path,
// and that will make the call crash. Until future fix by Apple.
//
// must have a key path
guard (keyPath.count > 0) else { return `default` }
// key path must not begin with the delimiter
guard (keyPath.hasPrefix(".") == false) else { return `default` }
// key path must not end with the delimiter
guard (keyPath.hasSuffix(".") == false) else { return `default` }
let keyPathComponents:[String] = keyPath.components(separatedBy:".")
// if key exists and value is a Any return Any
// if key exists and value is null return `default`
// if key does not exist, return `default`
let v:Any? = searchDictionary(keyPathComponents:keyPathComponents, keyPathIndex:0, dictionary:mJSONDictionary)
if (!(v is NSNull) && (v != nil))
{
return v
}
return `default`
}
/**
The value as a `Bool`.
- Parameters:
- key: The key path.
- `default`: Default value if the key in the path is not found.
- Returns: The value for the key path, or the default value.
*/
public func asBool(inKeyPath keyPath:String, `default`:Bool?=nil) -> Bool?
{
// if key exists and value is a Bool return Bool
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Bool = asRaw(inKeyPath:keyPath) as? Bool
{
return v
}
return `default`
}
/**
The value as a `UInt`.
- Parameters:
- key: The key path.
- `default`: Default value if the key in the path is not found.
- Returns: The value for the key path, or the default value.
*/
public func asUInt(inKeyPath keyPath:String, `default`:UInt?=nil) -> UInt?
{
// if key exists and value is a UInt return UInt
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Int = asRaw(inKeyPath:keyPath) as? Int, (v >= 0)
{
return UInt(v)
}
return `default`
}
/**
The value as a `Int`.
- Parameters:
- key: The key path.
- `default`: Default value if the key in the path is not found.
- Returns: The value for the key path, or the default value.
*/
public func asInt(inKeyPath keyPath:String, `default`:Int?=nil) -> Int?
{
// if key exists and value is a Int return Int
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Int = asRaw(inKeyPath:keyPath) as? Int
{
return v
}
return `default`
}
/**
The value as a `Float`.
- Parameters:
- key: The key path.
- `default`: Default value if the key in the path is not found.
- Returns: The value for the key path, or the default value.
*/
public func asFloat(inKeyPath keyPath:String, `default`:Float?=nil) -> Float?
{
// if key exists and value is a Float return Float
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Double = asRaw(inKeyPath:keyPath) as? Double
{
return Float(v) // loss of precision
}
return `default`
}
/**
The value as a `Double`.
- Parameters:
- key: The key path.
- `default`: Default value if the key in the path is not found.
- Returns: The value for the key path, or the default value.
*/
public func asDouble(inKeyPath keyPath:String, `default`:Double?=nil) -> Double?
{
// if key exists and value is a Double return Double
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Double = asRaw(inKeyPath:keyPath) as? Double
{
return v
}
return `default`
}
/**
The value as a `String`.
- Parameters:
- key: The key path.
- `default`: Default value if the key in the path is not found.
- Returns: The value for the key path, or the default value.
*/
public func asString(inKeyPath keyPath:String, `default`:String?=nil) -> String?
{
// if key exists and value is a String return String
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:String = asRaw(inKeyPath:keyPath) as? String
{
return v
}
return `default`
}
/**
The value as a `Array`.
- Parameters:
- key: The key path.
- `default`: Default value if the key in the path is not found.
- Returns: The value for the key path, or the default value.
*/
public func asArray(inKeyPath keyPath:String, `default`:Array<Any>?=nil) -> Array<Any>?
{
// if key exists and value is a Array<Any> return Array<Any>
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Array<Any> = asRaw(inKeyPath:keyPath) as? Array<Any>
{
return v
}
return `default`
}
/**
The value as a `Dictionary`.
- Parameters:
- key: The key path.
- `default`: Default value if the key in the path is not found.
- Returns: The value for the key path, or the default value.
*/
public func asDictionary(inKeyPath keyPath:String, `default`:Dictionary<String, Any>?=nil) -> Dictionary<String, Any>?
{
// if key exists and value is a Dictionary<String, Any> return Dictionary<String, Any>
// if key exists and value is null return `default`
// if key does not exist, return `default`
if let v:Dictionary<String, Any> = asRaw(inKeyPath:keyPath) as? Dictionary<String, Any>
{
return v
}
return `default`
}
// MARK:- Helpers
/**
Convert all single quotes to escaped double quotes.
- Parameter string: A string containing single quotes.
- Returns: The string containing escaped double quotes.
*/
public class func convertSingleQuotesToDoubleQuotes(_ string:String) -> String
{
return string.replacingOccurrences(of:"'", with:"\"")
}
// MARK:- Info
/**
A description of the `JSONX` contents.
- Returns: String description of the `JSONX` contents.
*/
public func description() -> String
{
return mJSONDictionary.description
}
// MARK:- Private
private func searchDictionary(keyPathComponents:[String], keyPathIndex:Int, dictionary:Dictionary<String, Any>) -> Any?
{
let currentComponentKey:String = keyPathComponents[keyPathIndex]
let numOfKeyPathComponentIndexes:Int = (keyPathComponents.count - 1)
for (dictKey, dictValue) in dictionary
{
//print("keyPathIndex: \(keyPathIndex) / \(keyPathComponents.count - 1)")
//print("Component At Level:\(currentComponentKey) Test = dictKey:\(dictKey) dictValue:\(dictValue)")
// key found/match in key path
if (currentComponentKey == dictKey)
{
//print("Matches key path component √\n")
if (keyPathIndex < numOfKeyPathComponentIndexes)
{
if let d:Dictionary<String, Any> = dictValue as? Dictionary<String, Any>
{
//print("Continue search…\n")
return searchDictionary(keyPathComponents:keyPathComponents, keyPathIndex:(keyPathIndex + 1), dictionary:d)
}
else
{
//print("Keypath wants to continue, but dictionary has run out of values…\n")
}
}
else
{
// found it
return dictValue
}
}
else
{
// Key not found in key path. //
//print("No match in key path, continue search…\n")
}
}
return nil
}
}
// MARK:- Dictionary
extension Dictionary where Key:ExpressibleByStringLiteral, Value:Any
{
/**
Initializes a new `JSONX` object from this dictionary.
- Parameter context: In case of failure, logging will print the context in which the initialization is occuring.
- Returns: A new `JSONX` object.
*/
func toJSONX(context:String) -> JSONX?
{
let selfDict = (self as Any) as! Dictionary<String, Any>
guard let jsonx = JSONX(dictionary:selfDict) else
{
print("🎭 \(context): Failed, could not convert dictionary to JSONX object!")
return nil
}
return jsonx
}
}
|
f5a3fbe2a1aec150001f48b81ee43663
| 26.494334 | 151 | 0.557261 | false | false | false | false |
IngmarStein/swift
|
refs/heads/master
|
validation-test/stdlib/SwiftNativeNSBase.swift
|
apache-2.0
|
4
|
//===--- SwiftNativeNSBase.swift - Test _SwiftNativeNS*Base classes -------===//
//
// 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: rm -rf %t && mkdir -p %t
//
// RUN: %target-clang %S/Inputs/SwiftNativeNSBase/SwiftNativeNSBase.m -c -o %t/SwiftNativeNSBase.o -g
// RUN: %target-build-swift %s -I %S/Inputs/SwiftNativeNSBase/ -Xlinker %t/SwiftNativeNSBase.o -o %t/SwiftNativeNSBase
// RUN: %target-run %t/SwiftNativeNSBase
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
@_silgen_name("TestSwiftNativeNSBase")
func TestSwiftNativeNSBase()
TestSwiftNativeNSBase()
// does not return
|
5ad63798764919a49496ec735c2f6862
| 35 | 118 | 0.668651 | false | true | false | false |
anders617/ABCSV
|
refs/heads/master
|
ABCSVTests/ABCSVTests.swift
|
mit
|
1
|
//
// ABCSVTests.swift
// ABCSV
//
// Created by Anders Boberg on 1/9/16.
// Copyright © 2016 Anders boberg. All rights reserved.
//
import XCTest
@testable import ABCSV
import ABMatrices
class ABCSVTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
func testFile() {
let csv = ABCSV.fromFile(NSURL(fileURLWithPath: "/Users/Anders/Downloads/companylist.csv"))
print(csv)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSwap() {
var csv = ABCSV(fromMatrix: [
[1,2,3],
[4,5,6],
[7,8,9]
])
csv.swapColumns(0,2)
XCTAssert(csv.content == [
[3,2,1],
[6,5,4],
[9,8,7]
],
"Column swap failed.")
csv = ABCSV(fromMatrix: [
[1,2,3],
[4,5,6],
[7,8,9]
])
csv.swapRows(0,1)
XCTAssert(csv.content == [
[4,5,6],
[1,2,3],
[7,8,9]
], "Row swap failed.")
}
func testInsertion() {
let csv = ABCSV(fromMatrix: [
[1,2,3,4,5]
])
csv.insertRow(["a","b","c","d","e"], atIndex: 1)
XCTAssert(csv.content == [
[1,2,3,4,5],
["a","b","c","d","e"]
],
"Insertion failed.")
}
func testMatrixInit() {
let csv = ABCSV(fromMatrix: [
[1,2,3,4,5],
["a","b","c","d","e"]
])
XCTAssert(csv.content == [
[1,2,3,4,5],
["a","b","c","d","e"]
],
"Matrix init failed")
}
func testMultipleInitialization() {
var csvs:[ABCSV] = []
let text = "1,2,3,4,5\na,b,c,d,e\n\n5,4,3,2,1\ne,d,c,b,a"
csvs = ABCSV.fromText(text, range: nil)
let expected1:ABMatrix<ABCSVCell> = [
[1,2,3,4,5],
["a","b","c","d","e"]
]
let expected2:ABMatrix<ABCSVCell> = [
[5,4,3,2,1],
["e","d","c","b","a"]
]
XCTAssert(csvs[0].content == expected1, "Failed Multiple Initialization")
XCTAssert(csvs[1].content == expected2, "Failed Multiple Initialization")
}
func testEmptyInit() {
let test = ABCSV()
XCTAssert(test.content == [[.Empty]], "no param init failed")
}
func testRowColumnInit() {
let test = ABCSV(rowCount: 3, columnCount: 3, withValue: 4)
XCTAssert(test.content == ABMatrix<ABCSVCell>(rowCount: 3,
columnCount: 3,
withValue: .Integer(contents: 4)),
"rowCount:columnCount:withValue init failed")
}
func testHeaderInit() {
let test = ABCSV(
withHeaders: ["First", "Second", "Third"])
XCTAssert(test.content ==
[
[.Header(contents: "First"), .Header(contents: "Second"), .Header(contents: "Third")]
],
"headers init failed")
}
func testStringInit() {
let test = ABCSV(fromString: "Head1,Head2,Head3\nCell1,Cell2,Cell3")
XCTAssert(test.content == [
["Head1", "Head2", "Head3"],
["Cell1", "Cell2", "Cell3"]
]
, "String init failed.")
}
}
|
34e99b4b8322e47eb2f69a7d8f465e4f
| 27.692913 | 111 | 0.467618 | false | true | false | false |
divljiboy/IOSChatApp
|
refs/heads/master
|
Quick-Chat/Pods/BulletinBoard/Sources/Support/Animations/BulletinSwipeInteractionController.swift
|
mit
|
1
|
/**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/**
* An interaction controller that handles swipe-to-dismiss for bulletins.
*/
class BulletinSwipeInteractionController: UIPercentDrivenInteractiveTransition, UIGestureRecognizerDelegate {
/// Whether a panning interaction is in progress.
var isInteractionInProgress = false
var panGestureRecognizer: UIPanGestureRecognizer?
// MARK: - State
private var isFinished = false
private var currentPercentage: CGFloat = -1
private weak var viewController: BulletinViewController!
private var snapshotView: UIView? {
return viewController.activeSnapshotView
}
private var contentView: UIView {
return viewController.contentView
}
private var activityIndicatorView: UIView {
return viewController.activityIndicator
}
// MARK: - Preparation
/**
* Sets up the interaction recognizer for the given view controller and content view.
*/
func wire(to viewController: BulletinViewController) {
self.viewController = viewController
prepareGestureRecognizer()
}
private func prepareGestureRecognizer() {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture))
panGesture.maximumNumberOfTouches = 1
panGesture.cancelsTouchesInView = false
panGesture.delegate = self
self.panGestureRecognizer = panGesture
contentView.addGestureRecognizer(panGesture)
}
// MARK: - Gesture Recognizer
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return !(touch.view is UIControl)
}
@objc func handlePanGesture(gestureRecognizer: UIPanGestureRecognizer) {
/// Constants
let screenHeight = viewController.view.bounds.height
let distanceFactor: CGFloat = screenHeight >= 500 ? 3/4 : 2/3
let dismissThreshold: CGFloat = 256 * distanceFactor
let elasticThreshold: CGFloat = 128 * distanceFactor
let trackScreenPercentage = dismissThreshold / contentView.bounds.height
switch gestureRecognizer.state {
case .began:
isFinished = false
gestureRecognizer.setTranslation(.zero, in: contentView)
let isCompactWidth = viewController.traitCollection.horizontalSizeClass == .compact
guard viewController.isDismissable && isCompactWidth else {
isInteractionInProgress = false
return
}
isInteractionInProgress = true
viewController.dismiss(animated: true) {
guard self.isFinished else {
return
}
self.viewController.manager?.completeDismissal()
}
case .changed:
guard !isFinished else {
return
}
let translation = gestureRecognizer.translation(in: contentView)
let verticalTranslation = translation.y
isFinished = false
guard (verticalTranslation > 0) && isInteractionInProgress else {
update(0)
updateCardViews(forTranslation: translation)
return
}
snapshotView?.transform = .identity
let adaptativeTranslation = self.adaptativeTranslation(for: verticalTranslation, elasticThreshold: elasticThreshold)
let newPercentage = (adaptativeTranslation / dismissThreshold) * trackScreenPercentage
guard currentPercentage != newPercentage else {
return
}
currentPercentage = newPercentage
update(currentPercentage)
case .cancelled, .failed:
isInteractionInProgress = false
if !isFinished {
resetCardViews()
}
panGestureRecognizer?.isEnabled = true
case .ended:
guard isInteractionInProgress else {
resetCardViews()
isFinished = false
return
}
let translation = gestureRecognizer.translation(in: contentView).y
if translation >= dismissThreshold {
isFinished = true
isInteractionInProgress = false
finish()
} else {
resetCardViews()
cancel()
isFinished = false
}
default:
break
}
}
// MARK: - Math
// Source: https://github.com/HarshilShah/DeckTransition
let elasticTranslationCurve = { (translation: CGFloat, translationFactor: CGFloat) -> CGFloat in
return 30 * atan(translation/120) + translation/10
}
private func adaptativeTranslation(for translation: CGFloat, elasticThreshold: CGFloat) -> CGFloat {
let translationFactor: CGFloat = 2/3
if translation >= elasticThreshold {
let frictionLength = translation - elasticThreshold
let frictionTranslation = elasticTranslationCurve(frictionLength, translationFactor)
return frictionTranslation + (elasticThreshold * translationFactor)
} else {
return translation * translationFactor
}
}
private func transform(forTranslation translation: CGPoint) -> CGAffineTransform {
let translationFactor: CGFloat = 1/3
var adaptedTranslation = translation
// Vertical
if translation.y < 0 || !(isInteractionInProgress) {
adaptedTranslation.y = elasticTranslationCurve(translation.y, translationFactor)
}
let yTransform = adaptedTranslation.y * translationFactor
if viewController.traitCollection.horizontalSizeClass == .compact {
return CGAffineTransform(translationX: 0, y: yTransform)
}
// Horizontal
adaptedTranslation.x = elasticTranslationCurve(translation.x, translationFactor)
let xTransform = adaptedTranslation.x * translationFactor
return CGAffineTransform(translationX: xTransform, y: yTransform)
}
// MARK: - Position Management
private func updateCardViews(forTranslation translation: CGPoint) {
let transform = self.transform(forTranslation: translation)
snapshotView?.transform = transform
contentView.transform = transform
activityIndicatorView.transform = transform
}
private func resetCardViews() {
let options: UIViewAnimationOptions = UIViewAnimationOptions(rawValue: 6 << 7)
let animations = {
self.snapshotView?.transform = .identity
self.contentView.transform = .identity
self.activityIndicatorView.transform = .identity
}
viewController.backgroundView.show()
UIView.animate(withDuration: 0.15, delay: 0, options: options, animations: animations) { _ in
self.update(0)
self.cancel()
}
}
// MARK: - Cancellation
/**
* Resets the view if needed.
*/
func cancelIfNeeded() {
if panGestureRecognizer?.state == .changed {
panGestureRecognizer?.isEnabled = false
}
}
}
|
aff1fd1cf6089ef9eef1ee57209b3b09
| 27.3 | 128 | 0.635363 | false | false | false | false |
maitruonghcmus/QuickChat
|
refs/heads/master
|
QuickChat/Model/Conversation.swift
|
mit
|
1
|
// MIT License
// Copyright (c) 2017 Haik Aslanyan
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
import Firebase
class Conversation {
//MARK: Properties
let user: User
var lastMessage: Message
var locked : Bool
//MARK: Methods
class func showConversations(completion: @escaping ([Conversation]) -> Swift.Void) {
if let currentUserID = FIRAuth.auth()?.currentUser?.uid {
var conversations = [Conversation]()
FIRDatabase.database().reference().child("users").child(currentUserID).child("conversations").observe(.childAdded, with: { (snapshot) in
if snapshot.exists() {
let fromID = snapshot.key
let values = snapshot.value as! [String: String]
let location = values["location"]!
let locked = values["locked"] != nil && values["locked"] == "1" ? true : false
User.info(forUserID: fromID, completion: { (user) in
let emptyMessage = Message.init(type: .text, content: "loading", owner: .sender, timestamp: 0, isRead: true)
let conversation = Conversation.init(user: user, lastMessage: emptyMessage, locked: locked)
conversations.append(conversation)
conversation.lastMessage.downloadLastMessage(forLocation: location, completion: { (_) in
completion(conversations)
})
})
}
})
}
}
//MARK: Inits
init(user: User, lastMessage: Message, locked: Bool) {
self.user = user
self.lastMessage = lastMessage
self.locked = locked
}
//MARK: Delete
//MARK: Methods
class func delete(conv:Conversation, completion: @escaping (Bool) -> Swift.Void) {
if let currentUserID = FIRAuth.auth()?.currentUser?.uid {
FIRDatabase.database().reference().child("users").child(currentUserID).child("conversations").child(conv.user.id).removeValue(completionBlock: { (error, ref) in
if error == nil {
completion(true)
} else {
completion(false)
}
})
}
else {
completion(false)
}
}
//MARK: Lock
class func checkLocked(uid: String, completion: @escaping (Bool) -> Swift.Void) {
if FIRAuth.auth()?.currentUser?.uid != nil {
FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("conversations").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if let data = snapshot.value as? [String: String] {
let locked = data["locked"] != nil && data["locked"] == "1" ? true : false
completion(locked)
}
else {
completion(false)
}
})
}
else {
completion(false)
}
}
class func setLocked(uid: String, locked: Bool, completion: @escaping (Bool) -> Swift.Void) {
if FIRAuth.auth()?.currentUser?.uid != nil {
let values = ["locked": locked ? "1" : "0"]
FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("conversations").child(uid).updateChildValues(values, withCompletionBlock: { (errr, _) in
if errr == nil {
completion(true)
}
else {
completion(false)
}
})
}
else {
completion(false)
}
}
}
|
9b207fa64d205358442eebb35d02b5bd
| 40.715517 | 200 | 0.577805 | false | false | false | false |
Draveness/RbSwift
|
refs/heads/master
|
Sources/String+Inflections.swift
|
mit
|
1
|
//
// Inflections.swift
// SwiftPatch
//
// Created by draveness on 18/03/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
// MARK: - Inflections
public extension String {
/// An enum used to control the output of camelize as parameter
///
/// - upper: Return the UppcaseCamelCase when specified
/// - lower: Return the lowerCamelCase when specified
public enum LetterCase {
case upper
case lower
}
/// By default, `camelize` converts strings to UpperCamelCase.
///
/// "os_version".camelize #=> "OsVersion"
/// "os_version_ten".camelize #=> "OsVersionTen"
/// "os_version_TEn".camelize #=> "OsVersionTen"
///
/// If the argument to camelize is set to `.lower` then camelize produces lowerCamelCase.
///
/// "os_version".camelize(.lower) #=> "osVersion"
///
/// - Parameter firstLetter: A flag to control result between UpperCamelCase(.upper) and lowerCamelCase(.lower), See also LetterCase
/// - Returns: A string converts to camel case
/// - SeeAlso: LetterCase
func camelize(_ firstLetter: LetterCase = .upper) -> String {
let source = gsub("[-_]", " ")
if source.characters.contains(" ") {
var first = source.substring(to: 1)
first = firstLetter == .upper ? first.upcase : first.downcase
let camel = source.capitalized.gsub(" ", "")
let rest = String(camel.characters.dropFirst())
return "\(first)\(rest)"
} else {
var first = source.substring(to: 1)
first = firstLetter == .upper ? first.upcase : first.downcase
let rest = String(source.characters.dropFirst())
return "\(first)\(rest)"
}
}
/// Creates a foreign key name from a class name.
///
/// "people".foreignKey #=> "people_id"
/// "people".foreignKey #=> "people_id"
/// "MessageQueue".foreignKey #=> "message_queue_id"
///
/// Separate flag sets whether the method should put '_' between the name and 'id'.
///
/// "MessageQueue".foreignKey(false) #=> "message_queueid"
///
/// - Parameter separate: A bool value sets whether the method should put '_' between the name and 'id'
/// - Returns: A foreign key name string
func foreignKey(_ separate: Bool = true) -> String {
if separate {
return underscore + "_id"
} else {
return underscore + "id"
}
}
/// Converts strings to UpperCamelCase.
///
/// "os_version".camelize #=> "OsVersion"
/// "os_version_ten".camelize #=> "OsVersionTen"
/// "os_version_TEn".camelize #=> "OsVersionTen"
///
/// - See Also: `String#camelize(firstLetter:)`
var camelize: String {
return camelize()
}
/// Returns the plural form of the word in the string.
var pluralize: String {
return inflector.pluralize(string: self)
}
/// Returns the plural form of the word in the string.
///
/// "person".pluralize #=> "people"
/// "monkey".pluralize #=> "monkeys"
/// "user".pluralize #=> "users"
/// "man".pluralize #=> "men"
///
/// If the parameter count is specified, the singular form will be returned if count == 1.
///
/// "men".pluralize(1) #=> "man"
///
/// For any other value of count the plural will be returned.
///
/// - Parameter count: If specified, the singular form will be returned if count == 1
/// - Returns: A string in plural form of the word
func pluralize(_ count: Int = 2) -> String {
if count == 1 { return singularize }
return pluralize
}
/// The reverse of `pluralize`, returns the singular form of a word in a string.
///
/// "people".singularize #=> "person"
/// "monkeys".singularize #=> "monkey"
/// "users".singularize #=> "user"
/// "men".singularize #=> "man"
///
var singularize: String {
return inflector.singularize(string: self)
}
/// The reverse of `camelize`. Makes an underscored, lowercase form from the expression in the string.
///
/// "OsVersionTen".underscore #=> "os_version_ten"
/// "osVersionTen".underscore #=> "os_version_ten"
/// "osVerSionTen".underscore #=> "os_ver_sion_ten"
///
var underscore: String {
var word = self.gsub("([A-Z\\d]+)([A-Z][a-z])", "$1_$2")
word.gsubed("([a-z\\d])([A-Z])", "$1_$2")
// word.tr("-".freeze, "_".freeze)
word.downcased()
return word
}
/// Creates the name of a table.
/// This method uses the `String#pluralize` method on the last word in the string.
///
/// "RawScaledScorer".tableize #=> "raw_scaled_scorers"
/// "egg_and_ham".tableize #=> "egg_and_hams"
/// "fancyCategory".tableize #=> "fancy_categories"
///
var tableize: String {
return underscore.pluralize
}
/// Creates a foreign key name from a class name.
///
/// "people".foreignKey #=> "people_id"
/// "people".foreignKey #=> "people_id"
/// "MessageQueue".foreignKey #=> "message_queue_id"
///
var foreignKey: String {
return foreignKey()
}
}
|
6ea4901bff3563cffcdbde4efe0e48c1
| 34.322368 | 136 | 0.564723 | false | false | false | false |
whitepixelstudios/Material
|
refs/heads/master
|
Sources/iOS/PulseAnimation.swift
|
bsd-3-clause
|
1
|
/*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Motion
@objc(PulseAnimation)
public enum PulseAnimation: Int {
case none
case center
case centerWithBacking
case centerRadialBeyondBounds
case radialBeyondBounds
case backing
case point
case pointWithBacking
}
public protocol Pulseable {
/// A reference to the PulseAnimation.
var pulseAnimation: PulseAnimation { get set }
/// A UIColor.
var pulseColor: UIColor { get set }
/// The opcaity value for the pulse animation.
var pulseOpacity: CGFloat { get set }
}
internal protocol PulseableLayer {
/// A reference to the pulse layer.
var pulseLayer: CALayer? { get }
}
public struct Pulse {
/// A UIView that is Pulseable.
fileprivate weak var pulseView: UIView?
/// The layer the pulse layers are added to.
internal weak var pulseLayer: CALayer?
/// Pulse layers.
fileprivate var layers = [CAShapeLayer]()
/// A reference to the PulseAnimation.
public var animation = PulseAnimation.pointWithBacking
/// A UIColor.
public var color = Color.grey.base
/// The opcaity value for the pulse animation.
public var opacity: CGFloat = 0.18
/**
An initializer that takes a given view and pulse layer.
- Parameter pulseView: An optional UIView.
- Parameter pulseLayer: An optional CALayer.
*/
public init(pulseView: UIView?, pulseLayer: CALayer?) {
self.pulseView = pulseView
self.pulseLayer = pulseLayer
}
/**
Triggers the expanding animation.
- Parameter point: A point to pulse from.
*/
public mutating func expand(point: CGPoint) {
guard let view = pulseView else {
return
}
guard let layer = pulseLayer else {
return
}
guard .none != animation else {
return
}
let bLayer = CAShapeLayer()
let pLayer = CAShapeLayer()
bLayer.addSublayer(pLayer)
layer.addSublayer(bLayer)
bLayer.zPosition = 0
pLayer.zPosition = 0
layers.insert(bLayer, at: 0)
layer.masksToBounds = !(.centerRadialBeyondBounds == animation || .radialBeyondBounds == animation)
let w = view.bounds.width
let h = view.bounds.height
Motion.disable { [
n = .center == animation ? min(w, h) : max(w, h),
bounds = layer.bounds,
animation = animation,
color = color,
opacity = opacity
] in
bLayer.frame = bounds
pLayer.frame = CGRect(x: 0, y: 0, width: n, height: n)
switch animation {
case .center, .centerWithBacking, .centerRadialBeyondBounds:
pLayer.position = CGPoint(x: w / 2, y: h / 2)
default:
pLayer.position = point
}
pLayer.cornerRadius = n / 2
pLayer.backgroundColor = color.withAlphaComponent(opacity).cgColor
pLayer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(scaleX: 0, y: 0))
}
bLayer.setValue(false, forKey: "animated")
let t: TimeInterval = .center == animation ? 0.16125 : 0.325
switch animation {
case .centerWithBacking, .backing, .pointWithBacking:
bLayer.animate(.background(color: color.withAlphaComponent(opacity / 2)), .duration(t))
default:break
}
switch animation {
case .center, .centerWithBacking, .centerRadialBeyondBounds, .radialBeyondBounds, .point, .pointWithBacking:
pLayer.animate(.scale(1), .duration(t))
default:break
}
Motion.delay(t) {
bLayer.setValue(true, forKey: "animated")
}
}
/// Triggers the contracting animation.
public mutating func contract() {
guard let bLayer = layers.popLast() else {
return
}
guard let animated = bLayer.value(forKey: "animated") as? Bool else {
return
}
Motion.delay(animated ? 0 : 0.15) { [animation = animation, color = color] in
guard let pLayer = bLayer.sublayers?.first as? CAShapeLayer else {
return
}
let t: TimeInterval = 0.325
switch animation {
case .centerWithBacking, .backing, .pointWithBacking:
bLayer.animate(.background(color: color.withAlphaComponent(0)), .duration(t))
default:break
}
switch animation {
case .center, .centerWithBacking, .centerRadialBeyondBounds, .radialBeyondBounds, .point, .pointWithBacking:
pLayer.animate(.background(color: color.withAlphaComponent(0)))
default:break
}
Motion.delay(t) {
pLayer.removeFromSuperlayer()
bLayer.removeFromSuperlayer()
}
}
}
}
|
a7a0e3d997ffec36526e073ca69cd743
| 32.470297 | 120 | 0.616625 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/SILOptimizer/di-loadable-by-addr-scope.swift
|
apache-2.0
|
34
|
// Make sure we don't crash when verifying.
// RUN: %target-swift-frontend -emit-ir %s -Onone -sil-verify-all \
// RUN: -Xllvm -sil-print-debuginfo -o - 2>&1 | %FileCheck %s
// CHECK: define hidden swiftcc {{.*}} @"$s4main18DependencyResolverC14resolveSubtree_9excludings11AnySequenceVyAA20VersionAssignmentSetVy9ContainerQzGGAK_SDyAJ_10IdentifierQZShyAA0I0VGGtF"
public struct Version {
public let major: Int
public let minor: Int
public let patch: Int
public let prereleaseIdentifiers: [String]
public let buildMetadataIdentifiers: [String]
public init(
_ major: Int,
_ minor: Int,
_ patch: Int,
prereleaseIdentifiers: [String] = [],
buildMetadataIdentifiers: [String] = []
) {
self.major = major
self.minor = minor
self.patch = patch
self.prereleaseIdentifiers = prereleaseIdentifiers
self.buildMetadataIdentifiers = buildMetadataIdentifiers
}
}
extension Version: Hashable {
static public func == (lhs: Version, rhs: Version) -> Bool {
return lhs.major == rhs.major &&
lhs.buildMetadataIdentifiers == rhs.buildMetadataIdentifiers
}
public func hash(into hasher: inout Hasher) {
hasher.combine(major)
hasher.combine(buildMetadataIdentifiers)
}
}
public protocol PackageContainerIdentifier: Hashable { }
public protocol PackageContainer {
associatedtype Identifier: PackageContainerIdentifier
var identifier: Identifier { get }
}
public protocol PackageContainerProvider {
associatedtype Container: PackageContainer
func getContainer(
)
}
public struct PackageContainerConstraint<T: PackageContainerIdentifier> {
public enum Requirement: Hashable {
}
}
public enum BoundVersion {
case version(Version)
}
struct VersionAssignmentSet<C: PackageContainer> {
typealias Container = C
typealias Identifier = Container.Identifier
fileprivate var assignments: [Identifier: (container: Container, binding: BoundVersion)]
init() {
assignments = [:]
}
subscript(identifier: Identifier) -> BoundVersion? {
get {
return assignments[identifier]?.binding
}
}
subscript(container: Container) -> BoundVersion? {
get {
return self[container.identifier]
}
set {
}
}
}
public class DependencyResolver<P: PackageContainerProvider> {
public typealias Provider = P
public typealias Container = Provider.Container
public typealias Identifier = Container.Identifier
public typealias Constraint = PackageContainerConstraint<Identifier>
typealias AssignmentSet = VersionAssignmentSet<Container>
public let provider: Provider
private let isPrefetchingEnabled: Bool
private let skipUpdate: Bool
public init(
_ provider: Provider,
isPrefetchingEnabled: Bool = false,
skipUpdate: Bool = false
) {
self.provider = provider
self.isPrefetchingEnabled = isPrefetchingEnabled
self.skipUpdate = skipUpdate
}
func resolveSubtree(
_ container: Container,
excluding allExclusions: [Identifier: Set<Version>]
) -> AnySequence<AssignmentSet> {
func merge(constraints: [Constraint], binding: BoundVersion) -> AnySequence<AssignmentSet> {
var assignment = AssignmentSet()
assignment[container] = binding
return AnySequence([])
}
return AnySequence([])
}
}
|
153086871ce1d50a66e2dc01c54cd8a7
| 32.169811 | 189 | 0.67975 | false | false | false | false |
JGiola/swift-package-manager
|
refs/heads/master
|
Tests/BuildTests/BuildPlanTests.swift
|
apache-2.0
|
1
|
/*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import Utility
import TestSupport
import PackageModel
@testable import Build
private struct MockToolchain: Toolchain {
let swiftCompiler = AbsolutePath("/fake/path/to/swiftc")
let extraCCFlags: [String] = []
let extraSwiftCFlags: [String] = []
#if os(macOS)
let extraCPPFlags: [String] = ["-lc++"]
#else
let extraCPPFlags: [String] = ["-lstdc++"]
#endif
#if os(macOS)
let dynamicLibraryExtension = "dylib"
#else
let dynamicLibraryExtension = "so"
#endif
func getClangCompiler() throws -> AbsolutePath {
return AbsolutePath("/fake/path/to/clang")
}
func _isClangCompilerVendorApple() throws -> Bool? {
#if os(macOS)
return true
#else
return false
#endif
}
}
final class BuildPlanTests: XCTestCase {
/// The j argument.
private var j: String {
return "-j\(SwiftCompilerTool.numThreads)"
}
func mockBuildParameters(
buildPath: AbsolutePath = AbsolutePath("/path/to/build"),
config: BuildConfiguration = .debug,
flags: BuildFlags = BuildFlags(),
shouldLinkStaticSwiftStdlib: Bool = false,
destinationTriple: Triple = Triple.hostTriple,
indexStoreMode: BuildParameters.IndexStoreMode = .off
) -> BuildParameters {
return BuildParameters(
dataPath: buildPath,
configuration: config,
toolchain: MockToolchain(),
destinationTriple: destinationTriple,
flags: flags,
shouldLinkStaticSwiftStdlib: shouldLinkStaticSwiftStdlib,
indexStoreMode: indexStoreMode
)
}
func testBasicSwiftPackage() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.swift",
"/Pkg/Sources/lib/lib.swift"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
targets: [
TargetDescription(name: "exe", dependencies: ["lib"]),
TargetDescription(name: "lib", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(
buildParameters: mockBuildParameters(shouldLinkStaticSwiftStdlib: true),
graph: graph, diagnostics: diagnostics, fileSystem: fs)
)
result.checkProductsCount(1)
result.checkTargetsCount(2)
let exe = try result.target(for: "exe").swiftTarget().compileArguments()
XCTAssertMatch(exe, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-g", "-enable-testing", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "/path/to/build/debug/ModuleCache", .anySequence])
let lib = try result.target(for: "lib").swiftTarget().compileArguments()
XCTAssertMatch(lib, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-g", "-enable-testing", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "/path/to/build/debug/ModuleCache", .anySequence])
#if os(macOS)
let linkArguments = [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/exe", "-module-name", "exe",
"-static-stdlib", "-emit-executable",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
]
#else
let linkArguments = [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/exe", "-module-name", "exe",
"-emit-executable",
"-Xlinker", "-rpath=$ORIGIN",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
]
#endif
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), linkArguments)
}
func testBasicExtPackages() throws {
let fileSystem = InMemoryFileSystem(emptyFiles:
"/A/Sources/ATarget/foo.swift",
"/A/Tests/ATargetTests/foo.swift",
"/A/Tests/LinuxMain.swift",
"/B/Sources/BTarget/foo.swift",
"/B/Tests/BTargetTests/foo.swift",
"/B/Tests/LinuxMain.swift"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/A", fs: fileSystem, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "A",
path: "/A",
url: "/A",
dependencies: [
PackageDependencyDescription(url: "/B", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "ATarget", dependencies: ["BLibrary"]),
TargetDescription(name: "ATargetTests", dependencies: ["ATarget"], type: .test),
]),
Manifest.createV4Manifest(
name: "B",
path: "/B",
url: "/B",
products: [
ProductDescription(name: "BLibrary", targets: ["BTarget"]),
],
targets: [
TargetDescription(name: "BTarget", dependencies: []),
TargetDescription(name: "BTargetTests", dependencies: ["BTarget"], type: .test),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(
buildParameters: mockBuildParameters(),
graph: graph, diagnostics: diagnostics,
fileSystem: fileSystem))
XCTAssertEqual(Set(result.productMap.keys), ["APackageTests"])
#if os(macOS)
XCTAssertEqual(Set(result.targetMap.keys), ["ATarget", "BTarget", "ATargetTests"])
#else
XCTAssertEqual(Set(result.targetMap.keys), [
"APackageTests",
"ATarget",
"ATargetTests",
"BTarget"
])
#endif
}
func testBasicReleasePackage() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.swift"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
targets: [
TargetDescription(name: "exe", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(buildParameters: mockBuildParameters(config: .release), graph: graph, diagnostics: diagnostics, fileSystem: fs))
result.checkProductsCount(1)
result.checkTargetsCount(1)
let exe = try result.target(for: "exe").swiftTarget().compileArguments()
XCTAssertMatch(exe, ["-swift-version", "4", "-O", .equal(j), "-DSWIFT_PACKAGE", "-module-cache-path", "/path/to/build/release/ModuleCache", .anySequence])
#if os(macOS)
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-L", "/path/to/build/release",
"-o", "/path/to/build/release/exe", "-module-name", "exe", "-emit-executable",
"@/path/to/build/release/exe.product/Objects.LinkFileList",
])
#else
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-L", "/path/to/build/release",
"-o", "/path/to/build/release/exe", "-module-name", "exe", "-emit-executable",
"-Xlinker", "-rpath=$ORIGIN",
"@/path/to/build/release/exe.product/Objects.LinkFileList",
])
#endif
}
func testBasicClangPackage() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.c",
"/Pkg/Sources/lib/lib.c",
"/Pkg/Sources/lib/lib.S",
"/Pkg/Sources/lib/include/lib.h",
"/ExtPkg/Sources/extlib/extlib.c",
"/ExtPkg/Sources/extlib/include/ext.h"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
dependencies: [
PackageDependencyDescription(url: "/ExtPkg", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "exe", dependencies: ["lib"]),
TargetDescription(name: "lib", dependencies: ["ExtPkg"]),
]),
Manifest.createV4Manifest(
name: "ExtPkg",
path: "/ExtPkg",
url: "/ExtPkg",
products: [
ProductDescription(name: "ExtPkg", targets: ["extlib"]),
],
targets: [
TargetDescription(name: "extlib", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(buildParameters: mockBuildParameters(), graph: graph, diagnostics: diagnostics, fileSystem: fs))
result.checkProductsCount(1)
result.checkTargetsCount(3)
let ext = try result.target(for: "extlib").clangTarget()
var args: [String] = []
#if os(macOS)
args += ["-fobjc-arc", "-target", "x86_64-apple-macosx10.10"]
#else
args += ["-target", "x86_64-unknown-linux"]
#endif
args += ["-g", "-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1"]
args += ["-fblocks", "-fmodules", "-fmodule-name=extlib",
"-I", "/ExtPkg/Sources/extlib/include", "-fmodules-cache-path=/path/to/build/debug/ModuleCache"]
XCTAssertEqual(ext.basicArguments(), args)
XCTAssertEqual(ext.objects, [AbsolutePath("/path/to/build/debug/extlib.build/extlib.c.o")])
XCTAssertEqual(ext.moduleMap, AbsolutePath("/path/to/build/debug/extlib.build/module.modulemap"))
let exe = try result.target(for: "exe").clangTarget()
args = []
#if os(macOS)
args += ["-fobjc-arc", "-target", "x86_64-apple-macosx10.10"]
#else
args += ["-target", "x86_64-unknown-linux"]
#endif
args += ["-g", "-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1"]
args += ["-fblocks", "-fmodules", "-fmodule-name=exe",
"-I", "/Pkg/Sources/exe/include", "-I", "/Pkg/Sources/lib/include", "-I", "/ExtPkg/Sources/extlib/include",
"-fmodules-cache-path=/path/to/build/debug/ModuleCache"]
XCTAssertEqual(exe.basicArguments(), args)
XCTAssertEqual(exe.objects, [AbsolutePath("/path/to/build/debug/exe.build/main.c.o")])
XCTAssertEqual(exe.moduleMap, nil)
#if os(macOS)
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/exe", "-module-name", "exe", "-emit-executable",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
])
#else
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/exe", "-module-name", "exe", "-emit-executable",
"-Xlinker", "-rpath=$ORIGIN",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
])
#endif
let linkedFileList = try fs.readFileContents(AbsolutePath("/path/to/build/debug/exe.product/Objects.LinkFileList"))
XCTAssertEqual(linkedFileList, """
/path/to/build/debug/exe.build/main.c.o
/path/to/build/debug/extlib.build/extlib.c.o
/path/to/build/debug/lib.build/lib.c.o
""")
}
func testCLanguageStandard() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.cpp",
"/Pkg/Sources/lib/lib.c",
"/Pkg/Sources/lib/libx.cpp",
"/Pkg/Sources/lib/include/lib.h"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
cLanguageStandard: "gnu99",
cxxLanguageStandard: "c++1z",
targets: [
TargetDescription(name: "exe", dependencies: ["lib"]),
TargetDescription(name: "lib", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let plan = try BuildPlan(buildParameters: mockBuildParameters(), graph: graph, diagnostics: diagnostics, fileSystem: fs)
let result = BuildPlanResult(plan: plan)
result.checkProductsCount(1)
result.checkTargetsCount(2)
#if os(macOS)
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-lc++", "-g", "-L", "/path/to/build/debug", "-o",
"/path/to/build/debug/exe", "-module-name", "exe", "-emit-executable",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
])
#else
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-lstdc++", "-g", "-L", "/path/to/build/debug", "-o",
"/path/to/build/debug/exe", "-module-name", "exe", "-emit-executable",
"-Xlinker", "-rpath=$ORIGIN",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
])
#endif
mktmpdir { path in
let yaml = path.appending(component: "debug.yaml")
let llbuild = LLBuildManifestGenerator(plan, client: "swift-build", resolvedFile: path.appending(component: "Package.resolved"))
try llbuild.generateManifest(at: yaml)
let contents = try localFileSystem.readFileContents(yaml).asString!
XCTAssertTrue(contents.contains("-std=gnu99\",\"-c\",\"/Pkg/Sources/lib/lib.c"))
XCTAssertTrue(contents.contains("-std=c++1z\",\"-c\",\"/Pkg/Sources/lib/libx.cpp"))
}
}
func testSwiftCMixed() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.swift",
"/Pkg/Sources/lib/lib.c",
"/Pkg/Sources/lib/include/lib.h"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
targets: [
TargetDescription(name: "exe", dependencies: ["lib"]),
TargetDescription(name: "lib", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(buildParameters: mockBuildParameters(), graph: graph, diagnostics: diagnostics, fileSystem: fs))
result.checkProductsCount(1)
result.checkTargetsCount(2)
let lib = try result.target(for: "lib").clangTarget()
var args: [String] = []
#if os(macOS)
args += ["-fobjc-arc", "-target", "x86_64-apple-macosx10.10"]
#else
args += ["-target", "x86_64-unknown-linux"]
#endif
args += ["-g", "-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1"]
args += ["-fblocks", "-fmodules", "-fmodule-name=lib", "-I", "/Pkg/Sources/lib/include",
"-fmodules-cache-path=/path/to/build/debug/ModuleCache"]
XCTAssertEqual(lib.basicArguments(), args)
XCTAssertEqual(lib.objects, [AbsolutePath("/path/to/build/debug/lib.build/lib.c.o")])
XCTAssertEqual(lib.moduleMap, AbsolutePath("/path/to/build/debug/lib.build/module.modulemap"))
let exe = try result.target(for: "exe").swiftTarget().compileArguments()
XCTAssertMatch(exe, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-g", "-enable-testing", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG","-Xcc", "-fmodule-map-file=/path/to/build/debug/lib.build/module.modulemap", "-I", "/Pkg/Sources/lib/include", "-module-cache-path", "/path/to/build/debug/ModuleCache", .anySequence])
#if os(macOS)
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/exe", "-module-name", "exe", "-emit-executable",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
])
#else
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/exe", "-module-name", "exe", "-emit-executable",
"-Xlinker", "-rpath=$ORIGIN",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
])
#endif
}
func testSwiftCAsmMixed() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.swift",
"/Pkg/Sources/lib/lib.c",
"/Pkg/Sources/lib/lib.S",
"/Pkg/Sources/lib/include/lib.h"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(
root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createManifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
v: .v5,
targets: [
TargetDescription(name: "exe", dependencies: ["lib"]),
TargetDescription(name: "lib", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(buildParameters: mockBuildParameters(), graph: graph, diagnostics: diagnostics, fileSystem: fs))
result.checkProductsCount(1)
result.checkTargetsCount(2)
let lib = try result.target(for: "lib").clangTarget()
XCTAssertEqual(lib.objects, [
AbsolutePath("/path/to/build/debug/lib.build/lib.S.o"),
AbsolutePath("/path/to/build/debug/lib.build/lib.c.o")
])
}
func testREPLArguments() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.swift",
"/Pkg/Sources/swiftlib/lib.swift",
"/Pkg/Sources/lib/lib.c",
"/Pkg/Sources/lib/include/lib.h",
"/Dep/Sources/Dep/dep.swift",
"/Dep/Sources/CDep/cdep.c",
"/Dep/Sources/CDep/include/head.h",
"/Dep/Sources/CDep/include/module.modulemap"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
dependencies: [
PackageDependencyDescription(url: "/Dep", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "exe", dependencies: ["swiftlib"]),
TargetDescription(name: "swiftlib", dependencies: ["lib"]),
TargetDescription(name: "lib", dependencies: ["Dep"]),
]),
Manifest.createV4Manifest(
name: "Dep",
path: "/Dep",
url: "/Dep",
products: [
ProductDescription(name: "Dep", targets: ["Dep"]),
],
targets: [
TargetDescription(name: "Dep", dependencies: ["CDep"]),
TargetDescription(name: "CDep", dependencies: []),
]),
],
createREPLProduct: true
)
XCTAssertNoDiagnostics(diagnostics)
let plan = try BuildPlan(buildParameters: mockBuildParameters(), graph: graph, diagnostics: diagnostics, fileSystem: fs)
XCTAssertEqual(plan.createREPLArguments().sorted(), ["-I/Dep/Sources/CDep/include", "-I/path/to/build/debug", "-I/path/to/build/debug/lib.build", "-L/path/to/build/debug", "-lPkg__REPL"])
let replProduct = plan.graph.allProducts.first(where: { $0.name.contains("REPL") })
XCTAssertEqual(replProduct?.name, "Pkg__REPL")
}
func testTestModule() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/Foo/foo.swift",
"/Pkg/Tests/LinuxMain.swift",
"/Pkg/Tests/FooTests/foo.swift"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
targets: [
TargetDescription(name: "Foo", dependencies: []),
TargetDescription(name: "FooTests", dependencies: ["Foo"], type: .test),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(buildParameters: mockBuildParameters(), graph: graph, diagnostics: diagnostics, fileSystem: fs))
result.checkProductsCount(1)
#if os(macOS)
result.checkTargetsCount(2)
#else
// We have an extra LinuxMain target on linux.
result.checkTargetsCount(3)
#endif
let foo = try result.target(for: "Foo").swiftTarget().compileArguments()
XCTAssertMatch(foo, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-g", "-enable-testing", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "/path/to/build/debug/ModuleCache", .anySequence])
let fooTests = try result.target(for: "FooTests").swiftTarget().compileArguments()
XCTAssertMatch(fooTests, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-g", "-enable-testing", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "/path/to/build/debug/ModuleCache", .anySequence])
#if os(macOS)
XCTAssertEqual(try result.buildProduct(for: "PkgPackageTests").linkArguments(), [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug", "-o",
"/path/to/build/debug/PkgPackageTests.xctest/Contents/MacOS/PkgPackageTests", "-module-name",
"PkgPackageTests", "-Xlinker", "-bundle",
"@/path/to/build/debug/PkgPackageTests.product/Objects.LinkFileList",
])
#else
XCTAssertEqual(try result.buildProduct(for: "PkgPackageTests").linkArguments(), [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug", "-o",
"/path/to/build/debug/PkgPackageTests.xctest", "-module-name", "PkgPackageTests", "-emit-executable",
"-Xlinker", "-rpath=$ORIGIN",
"@/path/to/build/debug/PkgPackageTests.product/Objects.LinkFileList",
])
#endif
}
func testCModule() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.swift",
"/Clibgit/module.modulemap"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
dependencies: [
PackageDependencyDescription(url: "Clibgit", requirement: .upToNextMajor(from: "1.0.0"))
],
targets: [
TargetDescription(name: "exe", dependencies: []),
]),
Manifest.createV4Manifest(
name: "Clibgit",
path: "/Clibgit",
url: "/Clibgit"),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(buildParameters: mockBuildParameters(), graph: graph, diagnostics: diagnostics, fileSystem: fs))
result.checkProductsCount(1)
result.checkTargetsCount(1)
XCTAssertMatch(try result.target(for: "exe").swiftTarget().compileArguments(), ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-g", "-enable-testing", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-Xcc", "-fmodule-map-file=/Clibgit/module.modulemap", "-module-cache-path", "/path/to/build/debug/ModuleCache", .anySequence])
#if os(macOS)
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/exe", "-module-name", "exe", "-emit-executable",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
])
#else
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/exe", "-module-name", "exe", "-emit-executable",
"-Xlinker", "-rpath=$ORIGIN",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
])
#endif
}
func testCppModule() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.swift",
"/Pkg/Sources/lib/lib.cpp",
"/Pkg/Sources/lib/include/lib.h"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
targets: [
TargetDescription(name: "lib", dependencies: []),
TargetDescription(name: "exe", dependencies: ["lib"]),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(buildParameters: mockBuildParameters(), graph: graph, diagnostics: diagnostics, fileSystem: fs))
result.checkProductsCount(1)
result.checkTargetsCount(2)
let linkArgs = try result.buildProduct(for: "exe").linkArguments()
#if os(macOS)
XCTAssertTrue(linkArgs.contains("-lc++"))
#else
XCTAssertTrue(linkArgs.contains("-lstdc++"))
#endif
}
func testDynamicProducts() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/Sources/Foo/main.swift",
"/Bar/Source/Bar/source.swift"
)
let diagnostics = DiagnosticsEngine()
let g = loadPackageGraph(root: "/Foo", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Bar",
path: "/Bar",
url: "/Bar",
products: [
ProductDescription(name: "Bar-Baz", type: .library(.dynamic), targets: ["Bar"]),
],
targets: [
TargetDescription(name: "Bar", dependencies: []),
]),
Manifest.createV4Manifest(
name: "Foo",
path: "/Foo",
url: "/Foo",
dependencies: [
PackageDependencyDescription(url: "/Bar", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "Foo", dependencies: ["Bar-Baz"]),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(buildParameters: mockBuildParameters(), graph: g, diagnostics: diagnostics, fileSystem: fs))
result.checkProductsCount(2)
result.checkTargetsCount(2)
let fooLinkArgs = try result.buildProduct(for: "Foo").linkArguments()
let barLinkArgs = try result.buildProduct(for: "Bar-Baz").linkArguments()
#if os(macOS)
XCTAssertEqual(fooLinkArgs, [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/Foo", "-module-name", "Foo", "-lBar-Baz", "-emit-executable",
"@/path/to/build/debug/Foo.product/Objects.LinkFileList",
])
XCTAssertEqual(barLinkArgs, [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug", "-o",
"/path/to/build/debug/libBar-Baz.dylib",
"-module-name", "Bar_Baz", "-emit-library",
"@/path/to/build/debug/Bar-Baz.product/Objects.LinkFileList",
])
#else
XCTAssertEqual(fooLinkArgs, [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/Foo", "-module-name", "Foo", "-lBar-Baz", "-emit-executable",
"-Xlinker", "-rpath=$ORIGIN",
"@/path/to/build/debug/Foo.product/Objects.LinkFileList",
])
XCTAssertEqual(barLinkArgs, [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug", "-o",
"/path/to/build/debug/libBar-Baz.so",
"-module-name", "Bar_Baz", "-emit-library",
"-Xlinker", "-rpath=$ORIGIN",
"@/path/to/build/debug/Bar-Baz.product/Objects.LinkFileList",
])
#endif
}
func testExecAsDependency() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.swift",
"/Pkg/Sources/lib/lib.swift"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
products: [
ProductDescription(name: "lib", type: .library(.dynamic), targets: ["lib"]),
],
targets: [
TargetDescription(name: "lib", dependencies: []),
TargetDescription(name: "exe", dependencies: ["lib"]),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(
buildParameters: mockBuildParameters(),
graph: graph, diagnostics: diagnostics, fileSystem: fs)
)
result.checkProductsCount(2)
result.checkTargetsCount(2)
let exe = try result.target(for: "exe").swiftTarget().compileArguments()
XCTAssertMatch(exe, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-g", "-enable-testing", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "/path/to/build/debug/ModuleCache", .anySequence])
let lib = try result.target(for: "lib").swiftTarget().compileArguments()
XCTAssertMatch(lib, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-g", "-enable-testing", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG", "-module-cache-path", "/path/to/build/debug/ModuleCache", .anySequence])
#if os(macOS)
let linkArguments = [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/liblib.dylib", "-module-name", "lib",
"-emit-library",
"@/path/to/build/debug/lib.product/Objects.LinkFileList",
]
#else
let linkArguments = [
"/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug",
"-o", "/path/to/build/debug/liblib.so", "-module-name", "lib",
"-emit-library", "-Xlinker", "-rpath=$ORIGIN",
"@/path/to/build/debug/lib.product/Objects.LinkFileList",
]
#endif
XCTAssertEqual(try result.buildProduct(for: "lib").linkArguments(), linkArguments)
}
func testClangTargets() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.c",
"/Pkg/Sources/lib/include/lib.h",
"/Pkg/Sources/lib/lib.cpp"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
products: [
ProductDescription(name: "lib", type: .library(.dynamic), targets: ["lib"]),
],
targets: [
TargetDescription(name: "lib", dependencies: []),
TargetDescription(name: "exe", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(
buildParameters: mockBuildParameters(),
graph: graph, diagnostics: diagnostics,
fileSystem: fs)
)
result.checkProductsCount(2)
result.checkTargetsCount(2)
let exe = try result.target(for: "exe").clangTarget()
#if os(macOS)
XCTAssertEqual(exe.basicArguments(), ["-fobjc-arc", "-target", "x86_64-apple-macosx10.10", "-g", "-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1", "-fblocks", "-fmodules", "-fmodule-name=exe", "-I", "/Pkg/Sources/exe/include", "-fmodules-cache-path=/path/to/build/debug/ModuleCache"])
#else
XCTAssertEqual(exe.basicArguments(), ["-target", "x86_64-unknown-linux", "-g", "-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1", "-fblocks", "-fmodules", "-fmodule-name=exe", "-I", "/Pkg/Sources/exe/include", "-fmodules-cache-path=/path/to/build/debug/ModuleCache"])
#endif
XCTAssertEqual(exe.objects, [AbsolutePath("/path/to/build/debug/exe.build/main.c.o")])
XCTAssertEqual(exe.moduleMap, nil)
let lib = try result.target(for: "lib").clangTarget()
#if os(macOS)
XCTAssertEqual(lib.basicArguments(), ["-fobjc-arc", "-target", "x86_64-apple-macosx10.10", "-g", "-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1", "-fblocks", "-fmodules", "-fmodule-name=lib", "-I", "/Pkg/Sources/lib/include", "-fmodules-cache-path=/path/to/build/debug/ModuleCache"])
#else
XCTAssertEqual(lib.basicArguments(), ["-target", "x86_64-unknown-linux", "-g", "-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1", "-fblocks", "-fmodules", "-fmodule-name=lib", "-I", "/Pkg/Sources/lib/include", "-fmodules-cache-path=/path/to/build/debug/ModuleCache"])
#endif
XCTAssertEqual(lib.objects, [AbsolutePath("/path/to/build/debug/lib.build/lib.cpp.o")])
XCTAssertEqual(lib.moduleMap, AbsolutePath("/path/to/build/debug/lib.build/module.modulemap"))
#if os(macOS)
XCTAssertEqual(try result.buildProduct(for: "lib").linkArguments(), ["/fake/path/to/swiftc", "-lc++", "-g", "-L", "/path/to/build/debug", "-o", "/path/to/build/debug/liblib.dylib", "-module-name", "lib", "-emit-library", "@/path/to/build/debug/lib.product/Objects.LinkFileList"])
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), ["/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug", "-o", "/path/to/build/debug/exe", "-module-name", "exe", "-emit-executable", "@/path/to/build/debug/exe.product/Objects.LinkFileList"])
#else
XCTAssertEqual(try result.buildProduct(for: "lib").linkArguments(), ["/fake/path/to/swiftc", "-lstdc++", "-g", "-L", "/path/to/build/debug", "-o", "/path/to/build/debug/liblib.so", "-module-name", "lib", "-emit-library", "-Xlinker", "-rpath=$ORIGIN", "@/path/to/build/debug/lib.product/Objects.LinkFileList"])
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), ["/fake/path/to/swiftc", "-g", "-L", "/path/to/build/debug", "-o", "/path/to/build/debug/exe", "-module-name", "exe", "-emit-executable", "-Xlinker", "-rpath=$ORIGIN", "@/path/to/build/debug/exe.product/Objects.LinkFileList"])
#endif
}
func testNonReachableProductsAndTargets() throws {
let fileSystem = InMemoryFileSystem(emptyFiles:
"/A/Sources/ATarget/main.swift",
"/B/Sources/BTarget1/BTarget1.swift",
"/B/Sources/BTarget2/main.swift",
"/C/Sources/CTarget/main.swift"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/A", fs: fileSystem, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "A",
path: "/A",
url: "/A",
dependencies: [
PackageDependencyDescription(url: "/B", requirement: .upToNextMajor(from: "1.0.0")),
PackageDependencyDescription(url: "/C", requirement: .upToNextMajor(from: "1.0.0")),
],
products: [
ProductDescription(name: "aexec", type: .executable, targets: ["ATarget"])
],
targets: [
TargetDescription(name: "ATarget", dependencies: ["BLibrary"]),
]),
Manifest.createV4Manifest(
name: "B",
path: "/B",
url: "/B",
products: [
ProductDescription(name: "BLibrary", type: .library(.static), targets: ["BTarget1"]),
ProductDescription(name: "bexec", type: .executable, targets: ["BTarget2"]),
],
targets: [
TargetDescription(name: "BTarget1", dependencies: []),
TargetDescription(name: "BTarget2", dependencies: []),
]),
Manifest.createV4Manifest(
name: "C",
path: "/C",
url: "/C",
products: [
ProductDescription(name: "cexec", type: .executable, targets: ["CTarget"])
],
targets: [
TargetDescription(name: "CTarget", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
XCTAssertEqual(Set(graph.reachableProducts.map({ $0.name })), ["aexec", "BLibrary"])
XCTAssertEqual(Set(graph.reachableTargets.map({ $0.name })), ["ATarget", "BTarget1"])
XCTAssertEqual(Set(graph.allProducts.map({ $0.name })), ["aexec", "BLibrary", "bexec", "cexec"])
XCTAssertEqual(Set(graph.allTargets.map({ $0.name })), ["ATarget", "BTarget1", "BTarget2", "CTarget"])
let result = BuildPlanResult(plan: try BuildPlan(
buildParameters: mockBuildParameters(),
graph: graph, diagnostics: diagnostics,
fileSystem: fileSystem))
XCTAssertEqual(Set(result.productMap.keys), ["aexec", "BLibrary", "bexec", "cexec"])
XCTAssertEqual(Set(result.targetMap.keys), ["ATarget", "BTarget1", "BTarget2", "CTarget"])
}
func testSystemPackageBuildPlan() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/module.modulemap"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg"
),
]
)
XCTAssertNoDiagnostics(diagnostics)
XCTAssertThrows(BuildPlan.Error.noBuildableTarget) {
_ = try BuildPlan(
buildParameters: mockBuildParameters(),
graph: graph, diagnostics: diagnostics, fileSystem: fs)
}
}
func testPkgConfigHintDiagnostic() throws {
let fileSystem = InMemoryFileSystem(emptyFiles:
"/A/Sources/ATarget/foo.swift",
"/A/Sources/BTarget/module.modulemap"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/A", fs: fileSystem, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "A",
path: "/A",
url: "/A",
targets: [
TargetDescription(name: "ATarget", dependencies: ["BTarget"]),
TargetDescription(
name: "BTarget",
type: .system,
pkgConfig: "BTarget",
providers: [
.brew(["BTarget"]),
.apt(["BTarget"]),
]
)
]),
]
)
_ = try BuildPlan(buildParameters: mockBuildParameters(),
graph: graph, diagnostics: diagnostics, fileSystem: fileSystem)
XCTAssertTrue(diagnostics.diagnostics.contains(where: { ($0.data is PkgConfigHintDiagnostic) }))
}
func testPkgConfigGenericDiagnostic() throws {
let fileSystem = InMemoryFileSystem(emptyFiles:
"/A/Sources/ATarget/foo.swift",
"/A/Sources/BTarget/module.modulemap"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/A", fs: fileSystem, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "A",
path: "/A",
url: "/A",
targets: [
TargetDescription(name: "ATarget", dependencies: ["BTarget"]),
TargetDescription(
name: "BTarget",
type: .system,
pkgConfig: "BTarget"
)
]),
]
)
_ = try BuildPlan(buildParameters: mockBuildParameters(),
graph: graph, diagnostics: diagnostics, fileSystem: fileSystem)
let diagnostic = diagnostics.diagnostics.first(where: { ($0.data is PkgConfigGenericDiagnostic) })!
XCTAssertEqual(diagnostic.localizedDescription, "couldn't find pc file")
XCTAssertEqual(diagnostic.behavior, .warning)
XCTAssertEqual(diagnostic.location.localizedDescription, "'BTarget' BTarget.pc")
}
func testWindowsTarget() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.swift",
"/Pkg/Sources/lib/lib.c",
"/Pkg/Sources/lib/include/lib.h"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(
root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
targets: [
TargetDescription(name: "exe", dependencies: ["lib"]),
TargetDescription(name: "lib", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(buildParameters: mockBuildParameters(destinationTriple: .windows), graph: graph, diagnostics: diagnostics, fileSystem: fs))
result.checkProductsCount(1)
result.checkTargetsCount(2)
let lib = try result.target(for: "lib").clangTarget()
var args = ["-target", "x86_64-unknown-windows-msvc", "-g", "-gcodeview", "-O0", "-DSWIFT_PACKAGE=1", "-DDEBUG=1"]
args += ["-fblocks", "-I", "/Pkg/Sources/lib/include"]
XCTAssertEqual(lib.basicArguments(), args)
XCTAssertEqual(lib.objects, [AbsolutePath("/path/to/build/debug/lib.build/lib.c.o")])
XCTAssertEqual(lib.moduleMap, AbsolutePath("/path/to/build/debug/lib.build/module.modulemap"))
let exe = try result.target(for: "exe").swiftTarget().compileArguments()
XCTAssertMatch(exe, ["-swift-version", "4", "-enable-batch-mode", "-Onone", "-g", "-enable-testing", .equal(j), "-DSWIFT_PACKAGE", "-DDEBUG","-Xcc", "-fmodule-map-file=/path/to/build/debug/lib.build/module.modulemap", "-I", "/Pkg/Sources/lib/include", "-module-cache-path", "/path/to/build/debug/ModuleCache", .anySequence])
XCTAssertEqual(try result.buildProduct(for: "exe").linkArguments(), [
"/fake/path/to/swiftc", "-Xlinker", "-debug",
"-L", "/path/to/build/debug", "-o", "/path/to/build/debug/exe.exe",
"-module-name", "exe", "-emit-executable",
"@/path/to/build/debug/exe.product/Objects.LinkFileList",
])
}
func testIndexStore() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Pkg/Sources/exe/main.swift",
"/Pkg/Sources/lib/lib.c",
"/Pkg/Sources/lib/include/lib.h"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/Pkg", fs: fs, diagnostics: diagnostics,
manifests: [
Manifest.createV4Manifest(
name: "Pkg",
path: "/Pkg",
url: "/Pkg",
targets: [
TargetDescription(name: "exe", dependencies: ["lib"]),
TargetDescription(name: "lib", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
func check(for mode: BuildParameters.IndexStoreMode, config: BuildConfiguration) throws {
let result = BuildPlanResult(plan: try BuildPlan(buildParameters: mockBuildParameters(config: config, indexStoreMode: mode), graph: graph, diagnostics: diagnostics, fileSystem: fs))
let lib = try result.target(for: "lib").clangTarget()
let path = StringPattern.equal(result.plan.buildParameters.indexStore.asString)
#if os(macOS)
XCTAssertMatch(lib.basicArguments(), [.anySequence, "-index-store-path", path, .anySequence])
#else
XCTAssertNoMatch(lib.basicArguments(), [.anySequence, "-index-store-path", path, .anySequence])
#endif
let exe = try result.target(for: "exe").swiftTarget().compileArguments()
XCTAssertMatch(exe, [.anySequence, "-index-store-path", path, .anySequence])
}
try check(for: .auto, config: .debug)
try check(for: .on, config: .debug)
try check(for: .on, config: .release)
}
func testPlatforms() throws {
let fileSystem = InMemoryFileSystem(emptyFiles:
"/A/Sources/ATarget/foo.swift",
"/B/Sources/BTarget/foo.swift"
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/A", fs: fileSystem, diagnostics: diagnostics,
manifests: [
Manifest.createManifest(
name: "A",
platforms: [
PlatformDescription(name: "macos", version: "10.13"),
],
path: "/A",
url: "/A",
v: .v5,
dependencies: [
PackageDependencyDescription(url: "/B", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(name: "ATarget", dependencies: ["BLibrary"]),
]),
Manifest.createManifest(
name: "B",
platforms: [
PlatformDescription(name: "macos", version: "10.12"),
],
path: "/B",
url: "/B",
v: .v5,
products: [
ProductDescription(name: "BLibrary", targets: ["BTarget"]),
],
targets: [
TargetDescription(name: "BTarget", dependencies: []),
]),
]
)
XCTAssertNoDiagnostics(diagnostics)
let result = BuildPlanResult(plan: try BuildPlan(
buildParameters: mockBuildParameters(),
graph: graph, diagnostics: diagnostics,
fileSystem: fileSystem))
let aTarget = try result.target(for: "ATarget").swiftTarget().compileArguments()
#if os(macOS)
XCTAssertMatch(aTarget, ["-target", "x86_64-apple-macosx10.13", .anySequence])
#else
XCTAssertMatch(aTarget, ["-target", "x86_64-unknown-linux", .anySequence])
#endif
let bTarget = try result.target(for: "BTarget").swiftTarget().compileArguments()
#if os(macOS)
XCTAssertMatch(bTarget, ["-target", "x86_64-apple-macosx10.12", .anySequence])
#else
XCTAssertMatch(bTarget, ["-target", "x86_64-unknown-linux", .anySequence])
#endif
}
func testBuildSettings() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/A/Sources/exe/main.swift",
"/A/Sources/bar/bar.swift",
"/A/Sources/cbar/barcpp.cpp",
"/A/Sources/cbar/bar.c",
"/A/Sources/cbar/include/bar.h",
"/B/Sources/t1/dep.swift",
"/B/Sources/t2/dep.swift",
"<end>"
)
let aManifest = Manifest.createManifest(
name: "A",
path: "/A",
url: "/A",
v: .v5,
dependencies: [
PackageDependencyDescription(url: "/B", requirement: .upToNextMajor(from: "1.0.0")),
],
targets: [
TargetDescription(
name: "cbar",
settings: [
.init(tool: .c, name: .headerSearchPath, value: ["Sources/headers"]),
.init(tool: .cxx, name: .headerSearchPath, value: ["Sources/cppheaders"]),
.init(tool: .c, name: .define, value: ["CCC=2"]),
.init(tool: .cxx, name: .define, value: ["RCXX"], condition: .init(config: "release")),
.init(tool: .c, name: .unsafeFlags, value: ["-Icfoo", "-L", "cbar"]),
.init(tool: .cxx, name: .unsafeFlags, value: ["-Icxxfoo", "-L", "cxxbar"]),
]
),
TargetDescription(
name: "bar", dependencies: ["cbar", "Dep"],
settings: [
.init(tool: .swift, name: .define, value: ["LINUX"], condition: .init(platformNames: ["linux"])),
.init(tool: .swift, name: .define, value: ["RLINUX"], condition: .init(platformNames: ["linux"], config: "release")),
.init(tool: .swift, name: .define, value: ["DMACOS"], condition: .init(platformNames: ["macos"], config: "debug")),
.init(tool: .swift, name: .unsafeFlags, value: ["-Isfoo", "-L", "sbar"]),
]
),
TargetDescription(
name: "exe", dependencies: ["bar"],
settings: [
.init(tool: .swift, name: .define, value: ["FOO"]),
.init(tool: .linker, name: .linkedLibrary, value: ["sqlite3"]),
.init(tool: .linker, name: .linkedFramework, value: ["CoreData"], condition: .init(platformNames: ["macos"])),
.init(tool: .linker, name: .unsafeFlags, value: ["-Ilfoo", "-L", "lbar"]),
]
),
]
)
let bManifest = Manifest.createManifest(
name: "B",
path: "/B",
url: "/B",
v: .v5,
products: [
ProductDescription(name: "Dep", targets: ["t1", "t2"]),
],
targets: [
TargetDescription(
name: "t1",
settings: [
.init(tool: .swift, name: .define, value: ["DEP"]),
.init(tool: .linker, name: .linkedLibrary, value: ["libz"]),
]
),
TargetDescription(
name: "t2",
settings: [
.init(tool: .linker, name: .linkedLibrary, value: ["libz"]),
]
),
])
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/A", fs: fs, diagnostics: diagnostics,
manifests: [aManifest, bManifest]
)
XCTAssertNoDiagnostics(diagnostics)
func createResult(for dest: Triple) throws -> BuildPlanResult {
return BuildPlanResult(plan: try BuildPlan(
buildParameters: mockBuildParameters(destinationTriple: dest),
graph: graph, diagnostics: diagnostics,
fileSystem: fs)
)
}
do {
let result = try createResult(for: .x86_64Linux)
let dep = try result.target(for: "t1").swiftTarget().compileArguments()
XCTAssertMatch(dep, [.anySequence, "-DDEP", .end])
let cbar = try result.target(for: "cbar").clangTarget().basicArguments()
XCTAssertMatch(cbar, [.anySequence, "-DCCC=2", "-I/A/Sources/cbar/Sources/headers", "-I/A/Sources/cbar/Sources/cppheaders", "-Icfoo", "-L", "cbar", "-Icxxfoo", "-L", "cxxbar", .end])
let bar = try result.target(for: "bar").swiftTarget().compileArguments()
XCTAssertMatch(bar, [.anySequence, "-DLINUX", "-Isfoo", "-L", "sbar", .end])
let exe = try result.target(for: "exe").swiftTarget().compileArguments()
XCTAssertMatch(exe, [.anySequence, "-DFOO", .end])
let linkExe = try result.buildProduct(for: "exe").linkArguments()
XCTAssertMatch(linkExe, [.anySequence, "-lsqlite3", "-llibz", "-Ilfoo", "-L", "lbar", .end])
}
do {
let result = try createResult(for: .macOS)
let cbar = try result.target(for: "cbar").clangTarget().basicArguments()
XCTAssertMatch(cbar, [.anySequence, "-DCCC=2", "-I/A/Sources/cbar/Sources/headers", "-I/A/Sources/cbar/Sources/cppheaders", "-Icfoo", "-L", "cbar", "-Icxxfoo", "-L", "cxxbar", .end])
let bar = try result.target(for: "bar").swiftTarget().compileArguments()
XCTAssertMatch(bar, [.anySequence, "-DDMACOS", "-Isfoo", "-L", "sbar", .end])
let exe = try result.target(for: "exe").swiftTarget().compileArguments()
XCTAssertMatch(exe, [.anySequence, "-DFOO", "-framework", "CoreData", .end])
let linkExe = try result.buildProduct(for: "exe").linkArguments()
XCTAssertMatch(linkExe, [.anySequence, "-lsqlite3", "-llibz", "-framework", "CoreData", "-Ilfoo", "-L", "lbar", .end])
}
}
func testExtraBuildFlags() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/A/Sources/exe/main.swift",
"<end>"
)
let aManifest = Manifest.createManifest(
name: "A",
path: "/A",
url: "/A",
v: .v5,
targets: [
TargetDescription(name: "exe", dependencies: []),
]
)
let diagnostics = DiagnosticsEngine()
let graph = loadPackageGraph(root: "/A", fs: fs, diagnostics: diagnostics,
manifests: [aManifest]
)
XCTAssertNoDiagnostics(diagnostics)
var flags = BuildFlags()
flags.linkerFlags = ["-L", "/path/to/foo", "-L/path/to/foo", "-rpath=foo", "-rpath", "foo"]
let result = BuildPlanResult(plan: try BuildPlan(
buildParameters: mockBuildParameters(flags: flags),
graph: graph, diagnostics: diagnostics,
fileSystem: fs)
)
let exe = try result.buildProduct(for: "exe").linkArguments()
XCTAssertMatch(exe, [.anySequence, "-L", "/path/to/foo", "-L/path/to/foo", "-Xlinker", "-rpath=foo", "-Xlinker", "-rpath", "-Xlinker", "foo", .anySequence])
}
}
// MARK:- Test Helpers
private enum Error: Swift.Error {
case error(String)
}
private struct BuildPlanResult {
let plan: BuildPlan
let targetMap: [String: TargetBuildDescription]
let productMap: [String: ProductBuildDescription]
init(plan: BuildPlan) {
self.plan = plan
self.productMap = Dictionary(items: plan.buildProducts.map{ ($0.product.name, $0) })
self.targetMap = Dictionary(items: plan.targetMap.map{ ($0.0.name, $0.1) })
}
func checkTargetsCount(_ count: Int, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(plan.targetMap.count, count, file: file, line: line)
}
func checkProductsCount(_ count: Int, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(plan.productMap.count, count, file: file, line: line)
}
func target(for name: String) throws -> TargetBuildDescription {
guard let target = targetMap[name] else {
throw Error.error("Target \(name) not found.")
}
return target
}
func buildProduct(for name: String) throws -> ProductBuildDescription {
guard let product = productMap[name] else {
// <rdar://problem/30162871> Display the thrown error on macOS
throw Error.error("Product \(name) not found.")
}
return product
}
}
fileprivate extension TargetBuildDescription {
func swiftTarget() throws -> SwiftTargetBuildDescription {
switch self {
case .swift(let target):
return target
default:
throw Error.error("Unexpected \(self) type found")
}
}
func clangTarget() throws -> ClangTargetBuildDescription {
switch self {
case .clang(let target):
return target
default:
throw Error.error("Unexpected \(self) type")
}
}
}
|
010941232222db66e830c6d77e2edbfd
| 42.320863 | 336 | 0.539375 | false | true | false | false |
flockoffiles/FFDataWrapper
|
refs/heads/master
|
FFDataWrapper/FFDataWrapper+InitializationWithInfo.swift
|
mit
|
1
|
//
// FFDataWrapper+InitializationWithInfo.swift
// FFDataWrapper
//
// Created by Sergey Novitsky on 19/02/2019.
// Copyright © 2019 Flock of Files. All rights reserved.
//
import Foundation
extension FFDataWrapper.CodersEnum {
init(infoCoders: FFDataWrapper.InfoCoders?) {
if let infoCoders = infoCoders {
self = .infoCoders(encoder: infoCoders.encoder, decoder: infoCoders.decoder)
} else {
let coders = FFDataWrapperEncoders.xorWithRandomVectorOfLength(0).infoCoders
self = .infoCoders(encoder: coders.encoder, decoder: coders.decoder)
}
}
}
extension Optional where Wrapped == FFDataWrapper.InfoCoders {
func unwrapWithDefault(length: Int) -> FFDataWrapper.InfoCoders {
switch self {
case .some(let encoder, let decoder):
return (encoder, decoder)
case .none:
return FFDataWrapperEncoders.xorWithRandomVectorOfLength(length).infoCoders
}
}
}
extension FFDataWrapper {
/// Create a wrapper of the given length and the given initializer closure.
/// The initializer closure is used to set the initial data contents.
/// - Parameters:
/// - length: The desired length.
/// - infoCoders: Pair of coders to use to convert to/from the internal representation. If nil, the default coders will be used.
/// - info: Additional info to pass to the coders.
/// - encode: If true (default), the initial data constructed with the initializer closure will be encoded; if false, it won't be encoded
/// and will be assumed to be already encoded.
/// - initializer: Initializer closure to set initial contents.
public init(length: Int,
infoCoders: FFDataWrapper.InfoCoders? = nil,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>) throws -> Void) rethrows {
guard length > 0 else {
self.storedCoders = CodersEnum(infoCoders: infoCoders.unwrapWithDefault(length: 0))
self.dataRef = FFDataRef(length: 0)
return
}
let unwrappedCoders = infoCoders.unwrapWithDefault(length: length)
self.storedCoders = CodersEnum(infoCoders: unwrappedCoders)
self.dataRef = FFDataRef(length: length)
let tempBufferPtr = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
defer {
tempBufferPtr.initialize(repeating: 0, count: length)
tempBufferPtr.deallocate()
}
try initializer(UnsafeMutableBufferPointer(start: tempBufferPtr, count: length))
let initialEncoder = encode ? unwrappedCoders.encoder : FFDataWrapperEncoders.identity.infoCoders.encoder
initialEncoder(UnsafeBufferPointer(start: tempBufferPtr, count: length),
UnsafeMutableBufferPointer(start: self.dataRef.dataBuffer.baseAddress!, count: length), info)
}
/// Create a wrapper of the given length and the given initializer closure.
/// The initializer closure is used to set the initial data contents.
/// - Parameters:
/// - length: The desired length.
/// - coder: Coder to convert to and from the internal representation.
/// - info: Additional info to pass to the coders.
/// - encode: If true (default), the initial data constructed with the initializer closure will be encoded; if false, it won't be encoded
/// and will be assumed to be already encoded.
/// - initializer: Initializer closure to set initial contents.
public init(length: Int,
infoCoder: @escaping FFDataWrapper.InfoCoder,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>) throws -> Void) throws {
let coders: FFDataWrapper.InfoCoders? = FFDataWrapper.InfoCoders(infoCoder, infoCoder)
try self.init(length: length, infoCoders: coders, info: info, encode: encode, initializer: initializer)
}
/// Create a wrapper of the given length and the given initializer closure.
/// The initializer closure is used to set the initial data contents.
/// - Parameters:
/// - length: The desired length.
/// - coder: Coder to convert to and from the internal representation.
/// - info: Additional info to pass to the coders.
/// - encode: If true (default), the initial data constructed with the initializer closure will be encoded; if false, it won't be encoded
/// and will be assumed to be already encoded.
/// - initializer: Initializer closure to set initial contents.
public init(length: Int,
infoCoder: @escaping FFDataWrapper.InfoCoder,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>) -> Void) {
let coders: FFDataWrapper.InfoCoders? = FFDataWrapper.InfoCoders(infoCoder, infoCoder)
try! self.init(length: length, infoCoders: coders, info: info, encode: encode, initializer: initializer)
}
/// Create a wrapper with the given maximum capacity (in bytes).
///
/// - Parameters:
/// - capacity: The desired capacity (in bytes)
/// - infoCoders: Pair of coders to use to convert to/from the internal representation. If nil, the default XOR coders will be used.
/// - info: Additional info to pass to the coders.
/// - encode: If true (default), the initial data constructed with the initializer closure will be encoded; if false, it won't be encoded
/// and will be assumed to be already encoded.
/// - initializer: Initializer closure to create initial data contents. The size of created data can be smaller (but never greater)
/// than the capacity. The initializer closure must return the actual length of the data in its second parameter.
/// - Throws: Error if capacity is >= 0 or if the actual length turns out to exceed the capacity.
public init(capacity: Int,
infoCoders: FFDataWrapper.InfoCoders? = nil,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>, UnsafeMutablePointer<Int>) throws -> Void) rethrows {
guard capacity > 0 else {
self.storedCoders = CodersEnum(infoCoders: infoCoders.unwrapWithDefault(length: 0))
self.dataRef = FFDataRef(length: 0)
return
}
let tempBufferPtr = UnsafeMutablePointer<UInt8>.allocate(capacity: capacity)
defer {
// Securely wipe the temp buffer.
tempBufferPtr.initialize(repeating: 0, count: capacity)
tempBufferPtr.deallocate()
}
var actualLength = capacity
try initializer(UnsafeMutableBufferPointer(start: tempBufferPtr, count: capacity), &actualLength)
guard actualLength > 0 && actualLength <= capacity else {
self.storedCoders = CodersEnum(infoCoders: infoCoders.unwrapWithDefault(length: 0))
self.dataRef = FFDataRef(length: 0)
return
}
let unwrappedCoders = infoCoders.unwrapWithDefault(length: actualLength)
self.storedCoders = CodersEnum(infoCoders: unwrappedCoders)
self.dataRef = FFDataRef(length: actualLength)
let encoder = encode ? unwrappedCoders.encoder : FFDataWrapperEncoders.identity.infoCoders.encoder
encoder(UnsafeBufferPointer(start: tempBufferPtr, count: actualLength),
UnsafeMutableBufferPointer(start: self.dataRef.dataBuffer.baseAddress!, count: self.dataRef.dataBuffer.count), info)
}
public init(capacity: Int,
infoCoder: @escaping FFDataWrapper.InfoCoder,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>, UnsafeMutablePointer<Int>) throws -> Void) throws {
let coders = FFDataWrapper.InfoCoders(infoCoder, infoCoder)
try self.init(capacity: capacity, infoCoders: coders, encode: encode, initializer: initializer)
}
public init(capacity: Int,
infoCoder: @escaping FFDataWrapper.InfoCoder,
info: Any? = nil,
encode: Bool = true,
initializer: (UnsafeMutableBufferPointer<UInt8>, UnsafeMutablePointer<Int>) -> Void) {
let coders = FFDataWrapper.InfoCoders(infoCoder, infoCoder)
try! self.init(capacity: capacity, infoCoders: coders, encode: encode, initializer: initializer)
}
}
|
ab0e92e4a3c37f706ea6cdf61dadb990
| 49.344828 | 143 | 0.650457 | false | false | false | false |
SirapatBoonyasiwapong/grader
|
refs/heads/master
|
Sources/App/ViewRenderers/ViewWrapper.swift
|
mit
|
1
|
import Vapor
func render(_ viewName: String, _ data: [String: NodeRepresentable] = [:], for request: HTTP.Request, with renderer: ViewRenderer) throws -> View {
var wrappedData = wrap(data, request: request)
if let user = request.user {
wrappedData = wrap(wrappedData, user: user)
}
return try renderer.make(viewName, wrappedData, for: request)
}
fileprivate func wrap(_ data: [String: NodeRepresentable], user: User) -> [String: NodeRepresentable] {
var result = data
result["authenticated"] = true
result["authenticatedUser"] = user
result["authenticatedUserHasTeacherRole"] = user.has(role: .teacher)
result["acceptUserHasTeacherRole"] = user.has(role: .teacher)
result["authenticatedUserHasAdminRole"] = user.has(role: .admin)
return result
}
fileprivate func wrap(_ data: [String: NodeRepresentable], request: HTTP.Request) -> [String: NodeRepresentable] {
var result = data
let path: String = request.uri.path
let pathComponents: [String] = path.components(separatedBy: "/").filter { $0 != "" }
result["path"] = pathComponents
return result
}
|
0db2bd08e86c8d7312b363c701c34960
| 39.178571 | 147 | 0.694222 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS Tests/Routers/URLActionRouterTests.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import Wire
final class URLActionRouterTests: XCTestCase {
// MARK: Presenting Alerts
func testThatAlertIsPresented_WhenCanDisplayAlertsReturnsTrue() {
// GIVEN
let alert = UIAlertController.alertWithOKButton(message: "Hello World")
let viewController = RootViewController()
let delegate = MockURLActionRouterDelegate()
let router = TestableURLActionRouter(viewController: viewController)
router.delegate = delegate
// WHEN
router.presentAlert(alert)
// THEN
XCTAssertEqual(router.presentedAlert, alert)
}
func testThatAlertIsNotPresented_WhenCanDisplayAlertsReturnsFalse() {
// GIVEN
let alert = UIAlertController.alertWithOKButton(message: "Hello World")
let viewController = RootViewController()
let delegate = MockURLActionRouterDelegate()
delegate.canDisplayAlerts = false
let router = TestableURLActionRouter(viewController: viewController)
router.delegate = delegate
// WHEN
router.presentAlert(alert)
// THEN
XCTAssertEqual(router.presentedAlert, nil)
}
func testThatPendingAlertIsPresented_WhenPerformPendingActionsIsCalled() {
// GIVEN
let alert = UIAlertController.alertWithOKButton(message: "Hello World")
let viewController = RootViewController()
let delegate = MockURLActionRouterDelegate()
delegate.canDisplayAlerts = false
let router = TestableURLActionRouter(viewController: viewController)
router.delegate = delegate
router.presentAlert(alert)
// WHEN
delegate.canDisplayAlerts = true
router.performPendingActions()
// THEN
XCTAssertEqual(router.presentedAlert, alert)
}
// MARK: Navigation
func testThatNavigationPerformed_WhenAuthenticatedRouterIsAvailable() {
// GIVEN
let authenticatedRouter = MockAuthenticatedRouter()
let router = TestableURLActionRouter(viewController: RootViewController())
router.authenticatedRouter = authenticatedRouter
// WHEN
router.navigate(to: .conversationList)
// THEN
guard case .conversationList = authenticatedRouter.didNavigateToDestination else {
return XCTFail("Failed to perform navigation")
}
}
func testThatNavigationPerformed_WhenAuthenticatedRouterBecomesAvailable() {
// GIVEN
let authenticatedRouter = MockAuthenticatedRouter()
let router = TestableURLActionRouter(viewController: RootViewController())
router.navigate(to: .conversationList)
// WHEN
router.authenticatedRouter = authenticatedRouter
router.performPendingActions()
// THEN
guard case .conversationList = authenticatedRouter.didNavigateToDestination else {
return XCTFail("Failed to perform navigation")
}
}
}
class MockAuthenticatedRouter: AuthenticatedRouterProtocol {
func updateActiveCallPresentationState() { }
func minimizeCallOverlay(animated: Bool, withCompletion completion: Completion?) { }
var didNavigateToDestination: NavigationDestination?
func navigate(to destination: NavigationDestination) {
didNavigateToDestination = destination
}
}
class MockURLActionRouterDelegate: URLActionRouterDelegate {
var didCallWillShowCompanyLoginError: Bool = false
func urlActionRouterWillShowCompanyLoginError() {
didCallWillShowCompanyLoginError = true
}
var canDisplayAlerts: Bool = true
func urlActionRouterCanDisplayAlerts() -> Bool {
return canDisplayAlerts
}
}
class TestableURLActionRouter: URLActionRouter {
var presentedAlert: UIAlertController?
override func internalPresentAlert(_ alert: UIAlertController) {
presentedAlert = alert
}
}
|
7fa634556617fd30eee70419ce75f065
| 31.471831 | 90 | 0.710041 | false | true | false | false |
ra1028/FloatingActionSheetController
|
refs/heads/master
|
FloatingActionSheetController/FloatingActionSheetController.swift
|
mit
|
1
|
//
// FloatingActionSheetController.swift
// FloatingActionSheetController
//
// Created by Ryo Aoyama on 10/25/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
open class FloatingActionSheetController: UIViewController, UIViewControllerTransitioningDelegate {
// MARK: Public
public enum AnimationStyle {
case slideUp
case slideDown
case slideLeft
case slideRight
case pop
}
open var animationStyle = AnimationStyle.slideUp
open var itemTintColor = UIColor(red:0.13, green:0.13, blue:0.17, alpha:1)
open var font = UIFont.boldSystemFont(ofSize: 14)
open var textColor = UIColor.white
open var dimmingColor = UIColor(white: 0, alpha: 0.7)
open var pushBackScale: CGFloat = 0.85
public convenience init(animationStyle: AnimationStyle) {
self.init(nibName: nil, bundle: nil)
self.animationStyle = animationStyle
}
public convenience init(actionGroup: FloatingActionGroup..., animationStyle: AnimationStyle = .slideUp) {
self.init(nibName: nil, bundle: nil)
self.animationStyle = animationStyle
actionGroup.forEach { add(actionGroup: $0) }
}
public convenience init(actionGroups: [FloatingActionGroup], animationStyle: AnimationStyle = .slideUp) {
self.init(nibName: nil, bundle: nil)
self.animationStyle = animationStyle
add(actionGroups: actionGroups)
}
public convenience init(actions: [FloatingAction], animationStyle: AnimationStyle = .slideUp) {
self.init(nibName: nil, bundle: nil)
self.animationStyle = animationStyle
add(actions: actions)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
configure()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
open override var prefersStatusBarHidden: Bool {
return UIApplication.shared.isStatusBarHidden
}
open override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .fade
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !isShowing {
showActionSheet()
}
if originalStatusBarStyle == nil {
originalStatusBarStyle = UIApplication.shared.statusBarStyle
}
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
}
open override func viewWillDisappear(_ animated: Bool) {
if let style = originalStatusBarStyle {
UIApplication.shared.setStatusBarStyle(style, animated: true)
}
}
@discardableResult
public func present(in inViewController: UIViewController, completion: (() -> Void)? = nil) -> Self {
inViewController.present(self, animated: true, completion: completion)
return self
}
@discardableResult
public func dismiss() -> Self {
dismissActionSheet()
return self
}
@discardableResult
public func add(actionGroup: FloatingActionGroup...) -> Self {
actionGroups += actionGroup
return self
}
@discardableResult
public func add(actionGroups: [FloatingActionGroup]) -> Self {
self.actionGroups += actionGroups
return self
}
@discardableResult
public func add(action: FloatingAction..., newGroup: Bool = false) -> Self {
if let lastGroup = actionGroups.last, !newGroup {
action.forEach { lastGroup.add(action: $0) }
} else {
let actionGroup = FloatingActionGroup()
action.forEach { actionGroup.add(action: $0) }
add(actionGroup: actionGroup)
}
return self
}
@discardableResult
public func add(actions: [FloatingAction], newGroup: Bool = false) -> Self {
if let lastGroup = actionGroups.last, !newGroup {
lastGroup.add(actions: actions)
} else {
let actionGroup = FloatingActionGroup(actions: actions)
add(actionGroup: actionGroup)
}
return self
}
// MARK: Private
fileprivate class ActionButton: UIButton {
fileprivate var action: FloatingAction?
private var defaultBackgroundColor: UIColor?
override fileprivate var isHighlighted: Bool {
didSet {
guard oldValue != isHighlighted else { return }
if isHighlighted {
defaultBackgroundColor = backgroundColor
backgroundColor = highlightedColor(defaultBackgroundColor)
} else {
backgroundColor = defaultBackgroundColor
defaultBackgroundColor = nil
}
}
}
func configure(_ action: FloatingAction) {
self.action = action
setTitle(action.title, for: .normal)
if let color = action.tintColor {
backgroundColor = color
}
if let color = action.textColor {
setTitleColor(color, for: .normal)
}
if let font = action.font {
titleLabel?.font = font
}
}
private func highlightedColor(_ originalColor: UIColor?) -> UIColor? {
guard let originalColor = originalColor else { return nil }
var hue: CGFloat = 0, saturatioin: CGFloat = 0,
brightness: CGFloat = 0, alpha: CGFloat = 0
if originalColor.getHue(
&hue,
saturation: &saturatioin,
brightness: &brightness,
alpha: &alpha) {
return UIColor(hue: hue, saturation: saturatioin, brightness: brightness * 0.75, alpha: alpha)
}
return originalColor
}
}
private var actionGroups = [FloatingActionGroup]()
private var actionButtons = [ActionButton]()
private var isShowing = false
private var originalStatusBarStyle: UIStatusBarStyle?
fileprivate weak var dimmingView: UIControl!
private func showActionSheet() {
isShowing = true
dimmingView.backgroundColor = dimmingColor
let itemHeight: CGFloat = 50
let itemSpacing: CGFloat = 10
let groupSpacing: CGFloat = 30
var previousGroupLastButton: ActionButton?
actionGroups.reversed().forEach {
var previousButton: ActionButton?
$0.actions.reversed().forEach {
let button = createSheetButton($0)
view.addSubview(button)
var constraints = NSLayoutConstraint.constraints(
withVisualFormat: "H:|-(spacing)-[button]-(spacing)-|",
options: [],
metrics: ["spacing": itemSpacing],
views: ["button": button]
)
if let previousButton = previousButton {
constraints +=
NSLayoutConstraint.constraints(
withVisualFormat: "V:[button(height)]-spacing-[previous]",
options: [],
metrics: ["height": itemHeight,"spacing": itemSpacing],
views: ["button": button, "previous": previousButton]
)
} else if let previousGroupLastButton = previousGroupLastButton {
constraints +=
NSLayoutConstraint.constraints(
withVisualFormat: "V:[button(height)]-spacing-[previous]",
options: [],
metrics: ["height": itemHeight, "spacing": groupSpacing],
views: ["button": button, "previous": previousGroupLastButton]
)
} else {
if #available(iOS 11.0, *) {
constraints += [button.heightAnchor.constraint(equalToConstant: itemHeight),
button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -itemSpacing)
]
} else {
constraints +=
NSLayoutConstraint.constraints(
withVisualFormat: "V:[button(height)]-spacing-|",
options: [],
metrics: ["height": itemHeight,"spacing": itemSpacing],
views: ["button": button]
)
}
}
view.addConstraints(constraints)
previousButton = button
previousGroupLastButton = button
actionButtons.append(button)
}
}
view.layoutIfNeeded()
if let topButton = actionButtons.last {
let buttons: [ActionButton]
let preTransform: CATransform3D
let transform: CATransform3D
let topButtonY = topButton.frame.origin.y
assert(topButtonY > 0, "[FloatingActionSheetController] Too many action items error.")
switch animationStyle {
case .slideUp:
let bottomPad = view.bounds.height - topButtonY
buttons = actionButtons.reversed()
preTransform = CATransform3DMakeTranslation(0, bottomPad, 0)
transform = CATransform3DMakeTranslation(0, -10, 0)
case .slideDown:
let topPad = actionButtons[0].frame.maxY
buttons = actionButtons
preTransform = CATransform3DMakeTranslation(0, -topPad, 0)
transform = CATransform3DMakeTranslation(0, 10, 0)
case .slideLeft:
let rightPad = view.bounds.width - topButton.frame.origin.x
buttons = actionButtons.reversed()
preTransform = CATransform3DMakeTranslation(rightPad, 0, 0)
transform = CATransform3DMakeTranslation(-10, 0, 0)
case .slideRight:
let leftPad = topButton.frame.maxX
buttons = actionButtons.reversed()
preTransform = CATransform3DMakeTranslation(-leftPad, 0, 0)
transform = CATransform3DMakeTranslation(10, 0, 0)
case .pop:
buttons = actionButtons.reversed()
preTransform = CATransform3DMakeScale(0, 0, 1)
transform = CATransform3DMakeScale(1.1, 1.1, 1)
}
buttons.enumerated().forEach { index, button in
button.layer.transform = preTransform
UIView.animate(withDuration: 0.25, delay: TimeInterval(index) * 0.05 + 0.05,
options: .beginFromCurrentState,
animations: {
button.layer.transform = transform
}) { _ in
UIView.animate(withDuration: 0.2, delay: 0,
options: [.beginFromCurrentState, .curveEaseOut],
animations: {
button.layer.transform = CATransform3DIdentity
}, completion: nil)
}
}
}
}
private func dismissActionSheet(_ completion: (() -> Void)? = nil) {
self.dismiss(animated: true, completion: completion)
if let topButton = actionButtons.last {
let buttons: [ActionButton]
let transform: CATransform3D
var completion: ((ActionButton) -> Void)?
switch animationStyle {
case .slideUp:
let bottomPad = view.bounds.height - topButton.frame.origin.y
buttons = actionButtons
transform = CATransform3DMakeTranslation(0, bottomPad, 0)
case .slideDown:
let topPad = actionButtons[0].frame.maxY
buttons = actionButtons.reversed()
transform = CATransform3DMakeTranslation(0, -topPad, 0)
case .slideLeft:
let leftPad = topButton.frame.maxX
buttons = actionButtons.reversed()
transform = CATransform3DMakeTranslation(-leftPad, 0, 0)
case .slideRight:
let rightPad = view.bounds.width - topButton.frame.origin.x
buttons = actionButtons.reversed()
transform = CATransform3DMakeTranslation(rightPad, 0, 0)
case .pop:
buttons = actionButtons
transform = CATransform3DMakeScale(0.01, 0.01, 1) // 0.01 = Swift bug
completion = { $0.layer.transform = CATransform3DMakeScale(0, 0, 1) }
}
buttons.enumerated().forEach { index, button in
UIView.animate(withDuration: 0.2, delay: TimeInterval(index) * 0.05 + 0.05,
options: .beginFromCurrentState,
animations: {
button.layer.transform = transform
}) { _ in
completion?(button)
}
}
}
}
private func createSheetButton(_ action: FloatingAction) -> ActionButton {
let button = ActionButton(type: .custom)
button.layer.cornerRadius = 4
button.backgroundColor = itemTintColor
button.titleLabel?.textAlignment = .center
button.titleLabel?.font = font
button.setTitleColor(textColor, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.configure(action)
button.addTarget(self, action: #selector(FloatingActionSheetController.didSelectItem(_:)), for: .touchUpInside)
return button
}
@objc private dynamic func didSelectItem(_ button: ActionButton) {
guard let action = button.action else { return }
if action.handleImmediately {
action.handler?(action)
}
dismissActionSheet {
if !action.handleImmediately {
action.handler?(action)
}
}
}
private func configure() {
view.backgroundColor = .clear
modalPresentationStyle = .custom
transitioningDelegate = self
let dimmingView = UIControl()
dimmingView.addTarget(self, action: #selector(FloatingActionSheetController.handleTapDimmingView), for: .touchUpInside)
dimmingView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(dimmingView)
self.dimmingView = dimmingView
view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[dimmingView]-0-|",
options: [],
metrics: nil,
views: ["dimmingView": dimmingView]
)
+ NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[dimmingView]-0-|",
options: [],
metrics: nil,
views: ["dimmingView": dimmingView]
)
)
}
@objc private dynamic func handleTapDimmingView() {
dismissActionSheet()
}
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return FloatingTransitionAnimator(dimmingView: dimmingView, pushBackScale: pushBackScale)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let delay = TimeInterval(actionButtons.count) * 0.03
return FloatingTransitionAnimator(dimmingView: dimmingView, pushBackScale: pushBackScale, delay: delay, forwardTransition: false)
}
}
private final class FloatingTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var forwardTransition = true
let dimmingView: UIView
let pushBackScale: CGFloat
var delay: TimeInterval = 0
init(dimmingView: UIView, pushBackScale: CGFloat, delay: TimeInterval = 0, forwardTransition: Bool = true) {
self.dimmingView = dimmingView
self.pushBackScale = pushBackScale
super.init()
self.delay = delay
self.forwardTransition = forwardTransition
}
@objc func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
@objc func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
else { return }
let containerView = transitionContext.containerView
let duration = transitionDuration(using: transitionContext)
if forwardTransition {
containerView.addSubview(toVC.view)
UIView.animate(withDuration: duration, delay: 0,
usingSpringWithDamping: 1, initialSpringVelocity: 0,
options: .beginFromCurrentState,
animations: {
fromVC.view.layer.transform = CATransform3DMakeScale(self.pushBackScale, self.pushBackScale, 1)
self.dimmingView.alpha = 0
self.dimmingView.alpha = 1
}) { _ in
transitionContext.completeTransition(true)
}
} else {
UIView.animate(withDuration: duration, delay: delay,
usingSpringWithDamping: 1, initialSpringVelocity: 0,
options: .beginFromCurrentState,
animations: {
toVC.view.layer.transform = CATransform3DIdentity
self.dimmingView.alpha = 0
}) { _ in
transitionContext.completeTransition(true)
}
}
}
}
|
9ea5ad35e61fa1786b763cddc4eb10fe
| 38.941685 | 175 | 0.58195 | false | false | false | false |
alex-p/avr
|
refs/heads/master
|
AugmentedVirtualReality/ViewController.swift
|
gpl-2.0
|
1
|
//
// ViewController.swift
// AugmentedVirtualReality
//
// Created by Alex Prevoteau on 8/2/15.
// Copyright (c) 2015 Alex Prevoteau. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
// Set the varible for the Camera View (as "cv")
let cv = UIView()
let captureSession = AVCaptureSession()
var previewLayer : AVCaptureVideoPreviewLayer?
var captureDevice : AVCaptureDevice?
//Prevent the status bar from displaying
override func prefersStatusBarHidden() -> Bool {
return true
}
//Request autorotate not to be invoked
override func shouldAutorotate() -> Bool {
return false
}
//Force Landscape Left orientation
override func supportedInterfaceOrientations() -> Int {
return UIInterfaceOrientation.LandscapeLeft.rawValue
}
//Setup after loading the attached view
override func viewDidLoad() {
super.viewDidLoad()
//Set a CGRect variable to hold the device screen dimensions
let screenRect = UIScreen.mainScreen().bounds
//Create a Core Animation Replicator Layer and set its position
let r = CAReplicatorLayer()
r.bounds = CGRect(x: 0.0, y: 0.0, width: screenRect.width, height: screenRect.height)
r.position = view.center
//Add the replicator layer as a subview
view.layer.addSublayer(r)
//Add the camera view as a subview
view.addSubview(cv)
//Add the camera view's Core Animation layer as a sublayer to the replicator view's CALayer
//creating two streaming images with an offset to create a "3D" effect when the phone viewed
//within a mobile VR enclosure.
r.addSublayer(cv.layer)
r.instanceCount = 2
r.instanceTransform = CATransform3DMakeTranslation(0.0, 353.0, 0.0)
//Position the camera view appropriately
cv.layer.bounds = CGRect(x: 0.0, y: 0.0, width: screenRect.width, height: screenRect.height * 1.06)
cv.layer.position = CGPoint(x: 187, y: 335)
cv.layer.backgroundColor = UIColor.blackColor().CGColor
// Do any additional setup after loading the view, typically from a nib.
captureSession.sessionPreset = AVCaptureSessionPresetHigh
//Set a varibale to hold all capture found
let devices = AVCaptureDevice.devices()
//Find the back camera and start streaming video
for device in devices {
if (device.hasMediaType(AVMediaTypeVideo)) {
if(device.position == AVCaptureDevicePosition.Back) {
captureDevice = device as? AVCaptureDevice
if captureDevice != nil {
println("Capture device found")
beginSession()
UIApplication.sharedApplication().idleTimerDisabled = true
}
}
}
}
}
//Function to begin camera capture session
func beginSession() {
var err : NSError? = nil
captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
if err != nil {
println("error: \(err?.localizedDescription)")
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
cv.layer.addSublayer(previewLayer)
previewLayer?.frame = cv.layer.frame
captureSession.startRunning()
}
}
|
7243d27fdd7f2ddf0c4f02db3b3b4551
| 33.76699 | 107 | 0.620497 | false | false | false | false |
lemberg/obd2-swift-lib
|
refs/heads/master
|
OBD2-Swift/Classes/Stream/StreamWriter.swift
|
mit
|
1
|
//
// StreamWriter.swift
// OBD2Swift
//
// Created by Sergiy Loza on 30.05.17.
// Copyright © 2017 Lemberg. All rights reserved.
//
import Foundation
class StreamWriter {
private(set) var stream:OutputStream
private(set) var data:Data
init(stream: OutputStream, data: Data) {
self.stream = stream
self.data = data
}
func write() throws {
print("Write to OBD \(String(describing: String(data: data, encoding: .ascii)))")
while data.count > 0 {
let bytesWritten = write(data: data)
if bytesWritten == -1 {
print("Write Error")
throw WriterError.writeError
} else if bytesWritten > 0 && data.count > 0 {
print("Wrote \(bytesWritten) bytes")
data.removeSubrange(0..<bytesWritten)
}
}
}
private func write(data: Data) -> Int {
var bytesRemaining = data.count
var totalBytesWritten = 0
while bytesRemaining > 0 {
let bytesWritten = data.withUnsafeBytes {
stream.write(
$0.advanced(by: totalBytesWritten),
maxLength: bytesRemaining
)
}
if bytesWritten < 0 {
print("Can not OutputStream.write() \(stream.streamError?.localizedDescription ?? "")")
return -1
} else if bytesWritten == 0 {
print("OutputStream.write() returned 0")
return totalBytesWritten
}
bytesRemaining -= bytesWritten
totalBytesWritten += bytesWritten
}
return totalBytesWritten
}
}
|
3f47d6417e40084d188dc1dd317b46e7
| 27.222222 | 105 | 0.517435 | false | false | false | false |
fantast1k/Swiftent
|
refs/heads/master
|
Swiftent/Swiftent/Source/UIKit/UIButton+Contentable.swift
|
gpl-3.0
|
1
|
//
// UIButton.swift
// Swiftent
//
// Created by Dmitry Fa[n]tastik on 18/07/2016.
// Copyright © 2016 Fantastik Solution. All rights reserved.
//
import UIKit
extension UIButton : Contentable {
public typealias Content = UIButtonContent
public func installContent(_ content: UIButtonContent) {
let c = content
let states : [UIControlState] = [.normal, .disabled, .highlighted, .selected]
let vals : [UIButtonStateContent?] = [c.normal, c.disabled, c.highlighted, c.selected]
for (val, state) in zip(vals, states) {
if let value = val {
switch value.text {
case .Raw(let txt):
if let txt = txt {
setTitle(txt, for: state)
}
case .Attributed(let txt):
if let txt = txt {
setAttributedTitle(txt, for: state)
}
}
if let image = value.image {
setImage(image, for: state)
}
if let backgroundImage = value.backgroundImage {
setBackgroundImage(backgroundImage, for: state)
}
if let titleColor = value.titleColor {
setTitleColor(titleColor, for: state)
}
if let titleShadowColor = value.titleShadowColor {
setTitleShadowColor(titleShadowColor, for: state)
}
}
}
}
}
|
f3dd6830d281a6491d1a633593b0f009
| 31.851064 | 94 | 0.505181 | false | false | false | false |
Sajjon/Zeus
|
refs/heads/master
|
Examples/SpotifyAPI/SpotifyAPI/ZeusConfigurator.swift
|
apache-2.0
|
1
|
//
// ZeusConfigurator.swift
// SpotifyAPI
//
// Created by Cyon Alexander (Ext. Netlight) on 23/08/16.
// Copyright © 2016 com.cyon. All rights reserved.
//
import Foundation
import Zeus
private let baseUrl = "https://api.spotify.com/v1/"
class ZeusConfigurator {
var store: DataStoreProtocol!
var modelManager: ModelManagerProtocol!
init() {
setup()
}
fileprivate func setup() {
setupCoreDataStack()
setupLogging()
setupMapping()
}
fileprivate func setupLogging() {
Zeus.logLevel = .Warning
}
fileprivate func setupCoreDataStack() {
store = DataStore()
modelManager = ModelManager(baseUrl: baseUrl, store: store)
DataStore.sharedInstance = store
ModelManager.sharedInstance = modelManager
}
fileprivate func setupMapping() {
modelManager.map(Artist.entityMapping(store), Album.entityMapping(store)) {
artist, album in
artist == APIPath.artistById(noId)
album == APIPath.albumById(noId)
album == APIPath.albumsByArtist(noId) << "items"
}
}
}
|
6dd22e6a46e60d43178a9d76fb524de9
| 23.234043 | 83 | 0.632133 | false | false | false | false |
fluidsonic/JetPack
|
refs/heads/master
|
Sources/Extensions/Foundation/NSLocale.swift
|
mit
|
1
|
import Foundation
public extension Locale {
internal typealias PluralCategoryResolver = (_ f: NSNumber, _ fMod: Int, _ i: NSNumber, _ iMod: Int, _ n: NSNumber, _ nMod: Int, _ t: NSNumber, _ v: Int) -> PluralCategory
@nonobjc
static let defaultDecimalFormatterForResolvingPluralCategory: NumberFormatter = {
let formatter = NumberFormatter()
formatter.locale = Locale.englishUnitedStatesComputer
formatter.numberStyle = .decimal
return formatter
}()
@nonobjc
static let display = Bundle.main.preferredLocalizations.first.map { Locale(identifier: Locale.canonicalLanguageIdentifier(from: $0)) } ?? .autoupdatingCurrent
@nonobjc
static let englishUnitedStatesComputer = Locale(identifier: "en_US_POSIX")
func pluralCategoryForNumber(_ number: NSNumber, formatter: NumberFormatter = defaultDecimalFormatterForResolvingPluralCategory) -> PluralCategory {
guard let formatter = formatter.copy() as? NumberFormatter else {
return .other
}
formatter.locale = Locale.englishUnitedStatesComputer
formatter.currencyDecimalSeparator = "."
formatter.decimalSeparator = "."
formatter.maximumIntegerDigits = max(formatter.maximumIntegerDigits, 1)
formatter.minimumIntegerDigits = 1
formatter.usesGroupingSeparator = false
guard let formattedNumber = formatter.string(from: number) else {
return .other
}
guard let match = formattedNumber.firstMatchForRegularExpression(Locale.pluralCategoryNumberPattern) else {
return .other
}
let simpleDecimalFormatter = Locale.defaultDecimalFormatterForResolvingPluralCategory
guard let
wholeNumber = match[0],
let integerPart = match[1],
let f = simpleDecimalFormatter.number(from: match[2]?.toString() ?? "0"),
let i = simpleDecimalFormatter.number(from: integerPart.toString()),
let n = simpleDecimalFormatter.number(from: wholeNumber.toString()),
let t = simpleDecimalFormatter.number(from: match[3]?.toString() ?? "0")
else {
return .other
}
let v = match[2]?.count ?? 0
return pluralCategoryForOperands(f: f, i: i, n: n, t: t, v: v)
}
fileprivate func pluralCategoryForOperands(f: NSNumber, i: NSNumber, n: NSNumber, t: NSNumber, v: Int) -> PluralCategory {
/*
http://unicode.org/reports/tr35/tr35-numbers.html#Operands
n absolute value of the source number (integer and decimals).
i integer digits of n.
v number of visible fraction digits in n, with trailing zeros.
w number of visible fraction digits in n, without trailing zeros. (not yet used)
f visible fractional digits in n, with trailing zeros.
t visible fractional digits in n, without trailing zeros.
*/
let fMod = f.modulo(1_000_000_000)
let iMod = i.modulo(1_000_000_000)
let nMod = n.modulo(1_000_000_000)
if let resolver = Locale.pluralCategoryResolversByLocaleIdentifier[identifier] {
return resolver(f, fMod, i, iMod, n, nMod, t, v)
}
var components = Locale.canonicalIdentifier(from: identifier).components(separatedBy: "_")
components.removeLast()
while !components.isEmpty {
let localeIdentifier = components.joined(separator: "_")
if let resolver = Locale.pluralCategoryResolversByLocaleIdentifier[localeIdentifier] {
return resolver(f, fMod, i, iMod, n, nMod, t, v)
}
components.removeLast()
}
return .other
}
@nonobjc
fileprivate static let pluralCategoryNumberPattern = try! NSRegularExpression(pattern: "(\\d+)(?:\\.((\\d+?)0*)(?![0-9]))?", options: [])
@nonobjc
var uses24HourFormat: Bool {
return !(DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: self)?.contains("a") ?? false)
}
@nonobjc
var usesMetricSystem9: Bool {
return (self as NSLocale).object(forKey: NSLocale.Key.usesMetricSystem) as? Bool ?? false
}
// Swift bug - cannot nest type at the moment
typealias PluralCategory = _Locale_PluralCategory
}
public enum _Locale_PluralCategory {
case few
case many
case one
case other
case two
case zero
}
|
a6beccca2d3fe3da85db626c1af3c0b0
| 29.457364 | 172 | 0.734793 | false | false | false | false |
TheTekton/Malibu
|
refs/heads/master
|
MalibuTests/Specs/Helpers/UtilsSpec.swift
|
mit
|
1
|
@testable import Malibu
import Quick
import Nimble
class UtilsSpec: QuickSpec {
override func spec() {
describe("Utils") {
let fileManager = NSFileManager.defaultManager()
afterSuite {
do {
try fileManager.removeItemAtPath(Utils.storageDirectory)
} catch {}
}
describe(".documentDirectory") {
it("returns document directory") {
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
.UserDomainMask, true).first!
expect(Utils.documentDirectory).to(equal(documentDirectory))
}
}
describe(".storageDirectory") {
it("returns a test storage directory path") {
let directory = "\(Utils.documentDirectory)/Malibu"
var isDir: ObjCBool = true
expect(Utils.storageDirectory).to(equal(directory))
expect(fileManager.fileExistsAtPath(Utils.storageDirectory, isDirectory: &isDir)).to(beTrue())
}
}
describe(".filePath") {
it("returns a full file path") {
let name = "filename"
let path = "\(Utils.storageDirectory)/\(name)"
expect(Utils.filePath(name)).to(equal(path))
}
}
}
}
}
|
b600959645ed5d7b8b64519f128d4938
| 26.043478 | 104 | 0.610932 | false | false | false | false |
GabrielGhe/HackTheNorth
|
refs/heads/master
|
NoteCopy/NoteCopy/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// NoteCopy
//
// Created by Gabriel Gheorghian on 2014-09-20.
// Copyright (c) 2014 genunine. All rights reserved.
//
import UIKit
import MobileCoreServices
extension UIView {
func center(otherView: UIView) {
self.center = otherView.center
}
}
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var imageView: UIImageView!
var cameraUI = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
}
func action(name:String){
var tv = self.textView
// Spinner
tv.text = ""
var spinner = UIActivityIndicatorView()
spinner.hidesWhenStopped = true
spinner.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
spinner.center(tv)
tv.addSubview(spinner)
spinner.startAnimating()
Agent.post("http://localhost:3000/")
.attachImage(name)
.end({ (response: NSHTTPURLResponse!, data: Agent.Data!, error: NSError!) -> Void in
if(error == nil) {
dispatch_sync(dispatch_get_main_queue(), {
var text = data as String
tv.text = text
spinner.stopAnimating()
})
println(data)
}
})
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
imageView.image = image
action("test")
self.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func convert(sender: AnyObject) {
var picker:UIImagePickerController = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(picker, animated: true, completion: nil)
}
}
|
28fb6232beb99646dbd2650fc4ab66f2
| 30.535211 | 143 | 0.623493 | false | false | false | false |
flodolo/firefox-ios
|
refs/heads/main
|
Client/Frontend/Widgets/DrawerViewController.swift
|
mpl-2.0
|
2
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import SnapKit
struct DrawerViewControllerUX {
static let HandleAlpha: CGFloat = 0.25
static let HandleWidth: CGFloat = 35
static let HandleHeight: CGFloat = 5
static let HandleMargin: CGFloat = 20
static let DrawerCornerRadius: CGFloat = 10
static let DrawerTopStop: CGFloat = 60
static let DrawerPadWidth: CGFloat = 380
}
public class DrawerView: UIView {
override public func layoutSubviews() {
super.layoutSubviews()
if traitCollection.userInterfaceIdiom == .pad &&
traitCollection.horizontalSizeClass == .regular {
// Remove any layer mask to prevent rounded corners for iPad layout.
layer.mask = nil
} else {
// Apply a layer mask to round the top corners of the drawer.
let shapeLayer = CAShapeLayer()
let cornerRadii = CGSize(width: DrawerViewControllerUX.DrawerCornerRadius, height: DrawerViewControllerUX.DrawerCornerRadius)
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: cornerRadii)
shapeLayer.frame = bounds
shapeLayer.path = path.cgPath
layer.mask = shapeLayer
}
}
}
public class DrawerViewController: UIViewController, NotificationThemeable {
public let childViewController: UIViewController
public let drawerView = DrawerView()
fileprivate(set) open var isOpen: Bool = false
fileprivate var drawerViewTopConstraint: Constraint?
fileprivate var drawerViewRightConstraint: Constraint?
fileprivate let backgroundOverlayView = UIView()
fileprivate let handleView = UIView()
// Only used in iPad layout.
fileprivate var xPosition: CGFloat = 0 {
didSet {
let maxX = DrawerViewControllerUX.DrawerPadWidth
if xPosition < maxX - DrawerViewControllerUX.DrawerPadWidth {
xPosition = maxX - DrawerViewControllerUX.DrawerPadWidth
} else if xPosition > maxX {
xPosition = maxX
}
backgroundOverlayView.alpha = (1 - (xPosition / maxX)) / 2
drawerViewRightConstraint?.update(offset: xPosition)
view.layoutIfNeeded()
}
}
// Only used in non-iPad layout.
fileprivate var yPosition: CGFloat = DrawerViewControllerUX.DrawerTopStop {
didSet {
let maxY = view.frame.maxY
if yPosition < DrawerViewControllerUX.DrawerTopStop {
yPosition = DrawerViewControllerUX.DrawerTopStop
} else if yPosition > maxY {
yPosition = maxY
}
backgroundOverlayView.alpha = (maxY - yPosition) / maxY / 2
drawerViewTopConstraint?.update(offset: yPosition)
view.layoutIfNeeded()
}
}
fileprivate var showingPadLayout: Bool {
return traitCollection.userInterfaceIdiom == .pad &&
traitCollection.horizontalSizeClass == .regular
}
public init(childViewController: UIViewController) {
self.childViewController = childViewController
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
backgroundOverlayView.backgroundColor = .black
backgroundOverlayView.alpha = 0
view.addSubview(backgroundOverlayView)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didRecognizeTapGesture))
backgroundOverlayView.addGestureRecognizer(tapGestureRecognizer)
drawerView.backgroundColor = LegacyThemeManager.instance.currentName == .dark ? UIColor.theme.tableView.rowBackground : UIColor.theme.tableView.headerBackground
view.addSubview(drawerView)
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didRecognizePanGesture))
panGestureRecognizer.delegate = self
drawerView.addGestureRecognizer(panGestureRecognizer)
handleView.backgroundColor = .black
handleView.alpha = DrawerViewControllerUX.HandleAlpha
handleView.layer.cornerRadius = DrawerViewControllerUX.HandleHeight / 2
drawerView.addSubview(handleView)
addChild(childViewController)
drawerView.addSubview(childViewController.view)
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
backgroundOverlayView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
drawerView.snp.remakeConstraints(constraintsForDrawerView)
childViewController.view.snp.remakeConstraints(constraintsForChildViewController)
handleView.snp.remakeConstraints(constraintsForHandleView)
if showingPadLayout {
xPosition = DrawerViewControllerUX.DrawerPadWidth
} else {
yPosition = view.frame.maxY
}
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
open()
}
public func applyTheme() {
drawerView.backgroundColor = LegacyThemeManager.instance.currentName == .dark ? UIColor.theme.tableView.rowBackground : UIColor.theme.tableView.headerBackground
}
override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
drawerView.snp.remakeConstraints(constraintsForDrawerView)
childViewController.view.snp.remakeConstraints(constraintsForChildViewController)
handleView.snp.remakeConstraints(constraintsForHandleView)
}
fileprivate func constraintsForDrawerView(_ make: SnapKit.ConstraintMaker) {
if showingPadLayout {
make.width.equalTo(DrawerViewControllerUX.DrawerPadWidth)
make.height.equalTo(view)
drawerViewTopConstraint = make.top.equalTo(view).constraint
drawerViewRightConstraint = make.right.equalTo(xPosition).constraint
} else {
make.width.equalTo(view)
make.height.equalTo(view).offset(-DrawerViewControllerUX.DrawerTopStop)
drawerViewTopConstraint = make.top.equalTo(yPosition).constraint
drawerViewRightConstraint = make.right.equalTo(view).constraint
}
}
fileprivate func constraintsForChildViewController(_ make: SnapKit.ConstraintMaker) {
if showingPadLayout {
make.height.equalTo(drawerView)
make.top.equalTo(drawerView)
} else {
make.height.equalTo(drawerView).offset(-DrawerViewControllerUX.HandleMargin)
make.top.equalTo(drawerView).offset(DrawerViewControllerUX.HandleMargin)
}
make.width.equalTo(drawerView)
make.centerX.equalTo(drawerView)
}
fileprivate func constraintsForHandleView(_ make: SnapKit.ConstraintMaker) {
if showingPadLayout {
make.width.height.equalTo(0)
} else {
make.width.equalTo(DrawerViewControllerUX.HandleWidth)
make.height.equalTo(DrawerViewControllerUX.HandleHeight)
}
make.centerX.equalTo(drawerView)
make.top.equalTo(drawerView).offset((DrawerViewControllerUX.HandleMargin - DrawerViewControllerUX.HandleHeight) / 2)
}
@objc fileprivate func didRecognizeTapGesture(_ gestureRecognizer: UITapGestureRecognizer) {
guard gestureRecognizer.state == .ended else { return }
close()
}
@objc fileprivate func didRecognizePanGesture(_ gestureRecognizer: UIPanGestureRecognizer) {
// Drawer is not draggable on iPad layout.
guard !showingPadLayout else { return }
let translation = gestureRecognizer.translation(in: drawerView)
yPosition += translation.y
gestureRecognizer.setTranslation(CGPoint.zero, in: drawerView)
guard gestureRecognizer.state == .ended else { return }
let velocity = gestureRecognizer.velocity(in: drawerView).y
let landingYPosition = yPosition + velocity / 10
let nextYPosition: CGFloat
let duration: TimeInterval
if landingYPosition > view.frame.maxY / 2 {
nextYPosition = view.frame.maxY
duration = 0.25
} else {
nextYPosition = 0
duration = 0.25
}
UIView.animate(
withDuration: duration,
animations: {
self.yPosition = nextYPosition
}) { _ in
if nextYPosition > 0 {
self.view.removeFromSuperview()
self.removeFromParent()
}
}
}
public func open() {
isOpen = true
UIView.animate(withDuration: 0.25) {
if self.showingPadLayout {
self.xPosition = 0
} else {
self.yPosition = DrawerViewControllerUX.DrawerTopStop
}
}
}
public func close(immediately: Bool = false) {
let duration = immediately ? 0.0 : 0.25
UIView.animate(
withDuration: duration,
animations: {
if self.showingPadLayout {
self.xPosition = DrawerViewControllerUX.DrawerPadWidth
} else {
self.yPosition = self.view.frame.maxY
}
}) { _ in
self.isOpen = false
self.view.removeFromSuperview()
self.removeFromParent()
}
}
}
extension DrawerViewController: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// Don't recognize touches for the pan gesture
// if they occurred on a `UITableView*` view.
let description = touch.view?.description ?? ""
return !description.starts(with: "<UITableView") && !description.starts(with: "<UITextField")
}
}
|
4aecfae06b378359bcbaaf4ab2b35dbf
| 35.992832 | 168 | 0.660692 | false | false | false | false |
NemProject/NEMiOSApp
|
refs/heads/develop
|
NEMWallet/Models/TransactionMetaDataModel.swift
|
mit
|
1
|
//
// TransactionMetaDataModel.swift
//
// This file is covered by the LICENSE file in the root of this project.
// Copyright (c) 2016 NEM
//
import Foundation
import SwiftyJSON
/**
Represents a transaction meta data object on the NEM blockchain.
Visit the [documentation](http://bob.nem.ninja/docs/#transactionMetaData)
for more information.
*/
public struct TransactionMetaData: SwiftyJSONMappable {
// MARK: - Model Properties
/// The id of the transaction.
public var id: Int?
/// The hash of the transaction.
public var hash: String?
/// The height of the block in which the transaction was included.
public var height: Int?
/// The transaction hash of the multisig transaction.
public var data: String?
// MARK: - Model Lifecycle
public init?(jsonData: JSON) {
id = jsonData["id"].int
height = jsonData["height"].int
data = jsonData["data"].string
if jsonData["innerHash"]["data"].string == nil {
hash = jsonData["hash"]["data"].stringValue
} else {
hash = jsonData["innerHash"]["data"].stringValue
}
}
}
|
b8aea641a891186168c3bde412f78daa
| 25.130435 | 77 | 0.617304 | false | false | false | false |
howardhsien/EasyTaipei-iOS
|
refs/heads/master
|
EasyTaipei/EasyTaipei/view/TabButtonView.swift
|
mit
|
2
|
//
// TabButtonView.swift
// EasyTaipei
//
// Created by howard hsien on 2016/7/7.
// Copyright © 2016年 AppWorks School Hsien. All rights reserved.
//
import UIKit
class TabButtonView: UIView {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var label: UILabel!
class func viewFromNib(frame : CGRect? = nil) -> TabButtonView{
let view = loadFromNibNamed("TabButtonView") as? TabButtonView
if let frame = frame{
view?.frame = frame
}
return view!
}
func setImage(image: UIImage){
imageView.image = image
imageView.tintColor = UIColor.esyOffWhiteColor()
}
func setLabelText(text: String){
label.text = text
}
override func awakeFromNib() {
super.awakeFromNib()
self.userInteractionEnabled = false
}
// //MARK: test for overriding init
// override init (frame : CGRect) {
// super.init(frame : frame)
// }
//
// convenience init () {
// self.init(frame:CGRect.zero)
// }
//
// required init(coder aDecoder: NSCoder) {
// fatalError("This class does not support NSCoding")
// }
}
|
d3cb9c0da0f83da77a1b91b60dbd668b
| 20.263158 | 70 | 0.588284 | false | false | false | false |
wuyingminhui/HiPay
|
refs/heads/master
|
HiPay/Classes/HiPayCore/HiPayWxOrder.swift
|
mit
|
1
|
//
// HiPayWxOrder.swift
// HiPay
//
// Created by Jason on 16/6/17.
// Copyright © 2016年 [email protected]. All rights reserved.
//
// 微信支付订单
import Foundation
/**
* 微信订单
*/
public struct HiPayWxOrder {
/// 商家appid
public var appid: String
/// 商家id
public var partnerId: String
/// 订单id
public var prepayid: String
/// 随机字符串
public var nonceStr: String
/// 时间戳
public var timeStamp: UInt32
/// 扩展字段
public var package: String
/// 签名
public var sign: String
public init(appid: String, partnerId: String, prepayid: String, nonceStr: String, timeStamp: UInt32, package: String, sign: String) {
self.appid = appid
self.partnerId = partnerId
self.prepayid = prepayid
self.nonceStr = nonceStr
self.timeStamp = timeStamp
self.package = package
self.sign = sign
}
}
|
40e57ebfa181ed1a33ba4963fbf1a533
| 21.65 | 137 | 0.616575 | false | false | false | false |
mattermost/mattermost-mobile
|
refs/heads/main
|
ios/MattermostShare/Views/ContentViews/AttachmentsViews/MultipleAttachmentView.swift
|
apache-2.0
|
1
|
//
// MultipleAttachmentView.swift
// MattermostShare
//
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
import SwiftUI
struct MultipleAttachmentView: View {
@EnvironmentObject var shareViewModel: ShareViewModel
@Binding var attachments: [AttachmentModel]
var body: some View {
VStack (alignment: .leading) {
ScrollView (.horizontal, showsIndicators: true) {
HStack(spacing: 12) {
ForEach(attachments.indices, id: \.self) { index in
let attachment = attachments[index]
let hasError = attachment.sizeError(server: shareViewModel.server) || attachment.resolutionError(server: shareViewModel.server)
let isFirst = index == 0
let isLast = index == attachments.count - 1
VStack {
if attachment.type == .image {
AttachmentWrapperView(isFirst: isFirst, isLast: isLast) {
ImageThumbnail(
small: true,
attachment: attachment,
hasError: hasError
)
.overlay(
RemoveAttachmentView(attachments: $attachments, index: index),
alignment: .topTrailing
)
}
} else if attachment.type == .video {
AttachmentWrapperView(isFirst: isFirst, isLast: isLast) {
VideoThumbnail(
small: true,
attachment: attachment,
hasError: hasError
)
.overlay(
RemoveAttachmentView(attachments: $attachments, index: index),
alignment: .topTrailing
)
}
} else if attachment.type == .file {
AttachmentWrapperView(isFirst: isFirst, isLast: isLast) {
FileThumbnail(
attachment: attachment,
hasError: hasError
)
.overlay(
RemoveAttachmentView(attachments: $attachments, index: index),
alignment: .topTrailing
)
}
}
}
}
}
.frame(height: 116)
}
if (attachments.count > 1) {
Text("\(attachments.count) attachments")
.foregroundColor(Color.theme.centerChannelColor.opacity(0.64))
.font(Font.custom("OpenSans", size: 12))
.padding(.leading, 20)
}
}
}
}
|
dc6675ef96cb4691bbfe28a1a8ce8bcd
| 33.986667 | 139 | 0.514482 | false | false | false | false |
marmelroy/PeekPop
|
refs/heads/master
|
examples/InstaPreview/Sample/ImagesCollectionViewController.swift
|
mit
|
1
|
//
// ImagesCollectionViewController.swift
// Sample
//
// Created by Roy Marmelstein on 13/03/2016.
// Copyright © 2016 Roy Marmelstein. All rights reserved.
//
import UIKit
import PeekPop
private let reuseIdentifier = "ImageCollectionViewCell"
class ImagesCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PeekPopPreviewingDelegate {
var peekPop: PeekPop?
var previewingContext: PreviewingContext?
var images = [UIImage(named: "IMG_5441.JPG"), UIImage(named: "IMG_5311.JPG"), UIImage(named: "IMG_5291.JPG"), UIImage(named: "IMG_5290.JPG"), UIImage(named: "IMG_5155.JPG"), UIImage(named: "IMG_5153.JPG"), UIImage(named: "IMG_4976.JPG")]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "InstaPreview"
self.collectionView!.register(ImageCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
peekPop = PeekPop(viewController: self)
previewingContext = peekPop?.registerForPreviewingWithDelegate(self, sourceView: collectionView!)
}
// MARK: UICollectionView DataSource and Delegate
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
if let imageCell = cell as? ImageCollectionViewCell {
imageCell.image = images[indexPath.item]
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = (self.view.bounds.size.width - 5*5)/4
return CGSize(width: size, height: size)
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name:"Main", bundle:nil)
if let previewViewController = storyboard.instantiateViewController(withIdentifier: "PreviewViewController") as? PreviewViewController {
self.navigationController?.pushViewController(previewViewController, animated: true)
previewViewController.image = images[indexPath.item]
}
}
// MARK: PeekPopPreviewingDelegate
func previewingContext(_ previewingContext: PreviewingContext, viewControllerForLocation location: CGPoint) -> UIViewController? {
let storyboard = UIStoryboard(name:"Main", bundle:nil)
if let previewViewController = storyboard.instantiateViewController(withIdentifier: "PreviewViewController") as? PreviewViewController {
if let indexPath = collectionView!.indexPathForItem(at: location) {
let selectedImage = images[indexPath.item]
if let layoutAttributes = collectionView!.layoutAttributesForItem(at: indexPath) {
previewingContext.sourceRect = layoutAttributes.frame
}
previewViewController.image = selectedImage
return previewViewController
}
}
return nil
}
func previewingContext(_ previewingContext: PreviewingContext, commitViewController viewControllerToCommit: UIViewController) {
self.navigationController?.pushViewController(viewControllerToCommit, animated: false)
}
}
|
a4211ca388ad16cf40acdabfa08013fe
| 41.494253 | 241 | 0.71274 | false | false | false | false |
totomo/sushikit
|
refs/heads/master
|
Source/UIButton+SushiKit.swift
|
mit
|
1
|
//
// UIButton+SushiKit.swift
// SushiKit
//
// Created by Kenta Tokumoto on 2015/07/04.
// Copyright (c) 2015年 Kenta Tokumoto. All rights reserved.
//
import Foundation
import UIKit
private var kObjectKeyForButtonColor = 0
private class ButtonColorManager {
private var normalColor:UIColor?
private var highlightedColor:UIColor?
convenience init(normalColor:UIColor?, highlightedColor:UIColor?){
self.init()
self.normalColor = normalColor
self.highlightedColor = highlightedColor
}
}
public extension UIButton {
private var buttonColor:ButtonColorManager?{
get {
return objc_getAssociatedObject(self, &kObjectKeyForButtonColor) as? ButtonColorManager
}
set {
if let unoptionalValue = newValue {
objc_setAssociatedObject(self, &kObjectKeyForButtonColor, unoptionalValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
}
override public var highlighted:Bool {
get {
return super.highlighted
}
set {
self.backgroundColor = newValue ? buttonColor?.highlightedColor : buttonColor?.normalColor
super.highlighted = newValue
}
}
public func setBackgroundColor(#color:UIColor?, forState state:UIControlState){
switch state {
case UIControlState.Normal:
self.backgroundColor = color
case UIControlState.Highlighted:
self.buttonColor = ButtonColorManager(normalColor: self.backgroundColor, highlightedColor: color)
default:
break
}
}
}
|
fbb06c4572023ae92a40969695f5cc86
| 27.368421 | 121 | 0.655941 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new
|
refs/heads/master
|
Source/NSAttributedString+Combination.swift
|
apache-2.0
|
3
|
//
// NSAttributedString+Combination.swift
// edX
//
// Created by Akiva Leffert on 6/22/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
extension NSAttributedString {
class func joinInNaturalLayout(attributedStrings : [NSAttributedString]) -> NSAttributedString {
var attributedStrings = attributedStrings
if UIApplication.sharedApplication().userInterfaceLayoutDirection == .RightToLeft {
attributedStrings = Array(attributedStrings.reverse())
}
let blankSpace = NSAttributedString(string : " ")
let resultString = NSMutableAttributedString()
for (index,attrString) in attributedStrings.enumerate() {
if index != 0 { resultString.appendAttributedString(blankSpace) }
resultString.appendAttributedString(attrString)
}
return resultString
}
func singleLineWidth() -> CGFloat {
let boundingRect = self.boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max), options: [.UsesLineFragmentOrigin, .UsesFontLeading], context: nil)
return boundingRect.width
}
}
extension String {
static func joinInNaturalLayout(nullableStrings : [String?], separator : String = " ") -> String {
var strings = nullableStrings.mapSkippingNils({return $0})
if UIApplication.sharedApplication().userInterfaceLayoutDirection == .RightToLeft {
strings = strings.reverse()
}
return strings.joinWithSeparator(separator)
}
}
|
77d736cdd4e04a983ad2159bc2b8e9c5
| 32.913043 | 158 | 0.669872 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
refs/heads/master
|
TranslationEditor/Key.swift
|
mit
|
1
|
//
// Key.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 13.12.2016.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// Keys are used for specifying query ranges
struct Key
{
let min: Any
let max: Any
let isDefined: Bool
var inverted: Key
{
return Key(min: max, max: min, defined: isDefined)
}
static var undefined = Key(nil)
private init(min: Any, max: Any, defined: Bool = true)
{
self.min = min
self.max = max
self.isDefined = defined
}
init(_ key: Any?)
{
var min: Any = NSNull()
var max: Any = [:]
var defined = false
if let key = key
{
// Array type keys are handled differently
if let key = key as? [Any?]
{
if key.count > 0, let first = key[0]
{
min = first
defined = true
}
if key.count > 1, let second = key[1]
{
max = second
defined = true
}
}
// Other type values allow only single value range
else
{
min = key
max = key
defined = true
}
}
self.min = min
self.max = max
self.isDefined = defined
}
}
|
31ee84819fc246917b27ebb5612629c1
| 15.19403 | 55 | 0.589862 | false | false | false | false |
realm/SwiftLint
|
refs/heads/main
|
Source/SwiftLintFramework/Rules/Idiomatic/XCTFailMessageRule.swift
|
mit
|
1
|
import SwiftSyntax
struct XCTFailMessageRule: SwiftSyntaxRule, ConfigurationProviderRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "xctfail_message",
name: "XCTFail Message",
description: "An XCTFail call should include a description of the assertion.",
kind: .idiomatic,
nonTriggeringExamples: [
Example("""
func testFoo() {
XCTFail("bar")
}
"""),
Example("""
func testFoo() {
XCTFail(bar)
}
""")
],
triggeringExamples: [
Example("""
func testFoo() {
↓XCTFail()
}
"""),
Example("""
func testFoo() {
↓XCTFail("")
}
""")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
}
private extension XCTFailMessageRule {
final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: FunctionCallExprSyntax) {
guard
let expression = node.calledExpression.as(IdentifierExprSyntax.self),
expression.identifier.text == "XCTFail",
node.argumentList.isEmptyOrEmptyString
else {
return
}
violations.append(node.positionAfterSkippingLeadingTrivia)
}
}
}
private extension TupleExprElementListSyntax {
var isEmptyOrEmptyString: Bool {
if isEmpty {
return true
}
return count == 1 && first?.expression.as(StringLiteralExprSyntax.self)?.isEmptyString == true
}
}
|
d8b67fb0f3425c2faadef8a900a34a1e
| 26.223881 | 102 | 0.541667 | false | true | false | false |
ben-ng/swift
|
refs/heads/master
|
benchmark/single-source/XorLoop.swift
|
apache-2.0
|
1
|
//===--- XorLoop.swift ----------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
public func run_XorLoop(_ N: Int) {
for _ in 1...5*N {
let size = 100000
let ref_result = 47813324
var x = [Int](repeating: 0xA05FD, count: size)
for i in 0..<size {
x[i] = x[i] ^ 12345678
}
let res = x[10]+x[100]+x[1000]+x[10000]
CheckResults(res == ref_result,
"Incorrect results in XorLoop: \(res) != \(ref_result)")
}
}
|
ce175e1b6d5e9fcb9e3079c4d5939ae1
| 32.321429 | 80 | 0.546624 | false | false | false | false |
lucdion/aide-devoir
|
refs/heads/master
|
sources/AideDevoir/Classes/UI/Common/TextField.swift
|
apache-2.0
|
1
|
import UIKit
class TextField: UITextField {
fileprivate var defaultSidePadding = 20.f
fileprivate var leftImageView = UIImageView()
fileprivate var defaultTextColor: UIColor?
fileprivate var inError = false
static let preferredHeight = 44.f
override var placeholder: String? {
didSet {
refreshPlaceholder()
}
}
override var font: UIFont? {
didSet {
refreshPlaceholder()
}
}
init(imageName: String? = nil) {
super.init(frame: CGRect.zero)
// font = .semiBold(13)
// backgroundColor = .bannerBackgroundColor()
textColor = .backgroundColor()
if let imageName = imageName {
let imageTintColor = UIColor.gray
leftImageView.setImageAndFit(UIImage(namedRetina: imageName, tintColor: imageTintColor))
leftView = leftImageView
leftViewMode = .always
}
setShadow(radius: 0.5, offset: CGSize(width: 0, height: 1), opacity: 0.1)
clipsToBounds = false
}
deinit {
NotificationCenter.default.removeObserver(self)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: size.width, height: TextField.preferredHeight)
}
func isInError() -> Bool {
return inError
}
override var isEnabled: Bool {
didSet {
textColor = isEnabled ? .backgroundColor() : UIColor.black
}
}
}
// PMARK: Rects override
extension TextField {
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
guard let leftView = leftView else { return CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: defaultSidePadding, height: defaultSidePadding)) }
let topMargin = round((height - leftView.height) / 2.0)
return CGRect(x: 20, y: topMargin, width: leftView.width, height: leftView.height)
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
let textRect = super.textRect(forBounds: bounds)
let leftViewRect = self.leftViewRect(forBounds: bounds)
let xPos = 2 * (leftViewRect.origin.x - 1) + leftViewRect.width
return CGRect(x: xPos, y: textRect.origin.y, width: bounds.width - xPos, height: textRect.size.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds: bounds)
}
}
// PMARK: Placeholder
extension TextField {
fileprivate func refreshPlaceholder() {
// let placeholderTextColor = UIColor.black.withAlphaComponent(0.2)
attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [:])
}
}
|
e98874a320b2f2b20262a23c138aacb5
| 29.225806 | 158 | 0.63963 | false | false | false | false |
davejlin/treehouse
|
refs/heads/master
|
swift/swift2/selfie-photo/SelfiePhoto/MediaPickerManager.swift
|
unlicense
|
1
|
//
// MediaPickerManager.swift
// SelfiePhoto
//
// Created by Lin David, US-205 on 11/8/16.
// Copyright © 2016 Lin David. All rights reserved.
//
import UIKit
import MobileCoreServices
protocol MediaPickerManagerDelegate: class {
func mediaPickerManager(manager: MediaPickerManager, didFinishPickingImage image: UIImage)
}
class MediaPickerManager: NSObject {
private let imagePickerController = UIImagePickerController()
private let presentingViewController: UIViewController
weak var delegate: MediaPickerManagerDelegate?
init(presentingViewController: UIViewController) {
self.presentingViewController = presentingViewController
super.init()
imagePickerController.delegate = self
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
imagePickerController.sourceType = .Camera
imagePickerController.cameraDevice = .Front
} else {
imagePickerController.sourceType = .PhotoLibrary
}
imagePickerController.mediaTypes = [kUTTypeImage as String]
}
func presentImagePickerController(animated animated: Bool) {
presentingViewController.presentViewController(imagePickerController, animated: animated, completion: nil)
}
func dismissImagePickerController(animated animated:Bool, completion: (() -> Void)) {
presentingViewController.dismissViewControllerAnimated(animated, completion: completion)
}
}
extension MediaPickerManager: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
delegate?.mediaPickerManager(self, didFinishPickingImage: image)
}
}
|
f073569ac781d47eaa9325e864a55b8c
| 35.038462 | 123 | 0.742659 | false | false | false | false |
deepestblue/Lipika_IME
|
refs/heads/master
|
Keyboard/LipikaBoardSettings.swift
|
gpl-3.0
|
1
|
/*
* LipikaIME is a user-configurable phonetic Input Method Engine for Mac OS X.
* Copyright (C) 2017 Ranganath Atreya
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
import Foundation
class LipikaBoardSettings {
static let kAppGroupName = "group.LipikaBoard"
static let kLanguagesKey = "languages"
static let kLanguagesEnabledKey = "languagesEnabled"
static let kLanguageTypes = "languageTypes"
class func register() {
let path = getParentBundlePath()!.appendingPathComponent("UserSettings.plist").path
var defaults = NSDictionary(contentsOfFile: path) as? [String : AnyObject]
if defaults == nil {
assert(false, "Unable to load defaults from \(path)")
}
// Add our values into the defaults
let langList = getFullLanguageList()
defaults?.updateValue(langList?.map({$0.0}) as AnyObject, forKey: kLanguagesKey)
defaults?.updateValue(langList?.map({$0.1.rawValue}) as AnyObject, forKey: kLanguageTypes)
defaults?.updateValue(Array(repeating: true, count: langList?.count ?? 0) as AnyObject, forKey: kLanguagesEnabledKey)
UserDefaults.init(suiteName: kAppGroupName)?.register(defaults: defaults!)
}
private class func getParentBundlePath() -> URL? {
if Bundle.main.bundleIdentifier == "com.daivajnanam.LipikaBoard" {
return Bundle.main.bundleURL
}
else if Bundle.main.bundleIdentifier == "com.daivajnanam.LipikaBoard.Keyboard"
|| Bundle.main.bundleIdentifier == "com.daivajnanam.LipikaBoard.CustomScheme" {
return Bundle.main.bundleURL.deletingLastPathComponent().deletingLastPathComponent()
}
else {
assert(false, "Unknown bundle identifier \(Bundle.main.bundleIdentifier ?? "unknown")")
return nil
}
}
private class func getFullLanguageList() -> [(String, DJSchemeType)]? {
var lipikaScripts: [String]?
let lipikaScriptsPath = getSchemesURL()!.appendingPathComponent("Script").path
do {
let files = try FileManager.default.contentsOfDirectory(atPath: lipikaScriptsPath)
lipikaScripts = files.filter({$0.hasSuffix(".map")}).map({($0 as NSString).deletingPathExtension})
}
catch let error {
assert(false, "Unable to fetch file list from \(lipikaScriptsPath) due to: \(error)")
}
var customSchemes: [String]?
let customSchemesPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!.path
do {
let files = try FileManager.default.contentsOfDirectory(atPath: customSchemesPath)
customSchemes = files.filter({$0.hasSuffix(".scm")}).map({($0 as NSString).deletingPathExtension})
}
catch let error {
assert(false, "Unable to fetch file list from \(customSchemesPath) due to: \(error)")
}
var response: [(String, DJSchemeType)] = []
for script in customSchemes ?? [] {
response.append((script, DJ_GOOGLE))
}
for script in lipikaScripts ?? [] {
response.append((script, DJ_LIPIKA))
}
return response
}
class func getSchemesURL() -> URL? {
if Bundle.main.bundleIdentifier == "com.daivajnanam.LipikaBoard" {
return Bundle.main.bundleURL.appendingPathComponent("PlugIns/Keyboard.appex/Schemes")
}
else if Bundle.main.bundleIdentifier == "com.daivajnanam.LipikaBoard.Keyboard" {
return Bundle.main.bundleURL.appendingPathComponent("Schemes")
}
else if Bundle.main.bundleIdentifier == "com.daivajnanam.LipikaBoard.CustomScheme" {
return Bundle.main.bundleURL.deletingLastPathComponent().appendingPathComponent("Keyboard.appex/Schemes")
}
else {
assert(false, "Unknown bundle identifier \(Bundle.main.bundleIdentifier ?? "unknown")")
return nil
}
}
class func getLanguages() -> [(String, Bool, DJSchemeType)] {
let defaults = UserDefaults.init(suiteName: kAppGroupName)
let enabledList = defaults?.value(forKey: kLanguagesEnabledKey) as! [Bool]
let languages = defaults?.value(forKey: kLanguagesKey) as! [String]
let types = (defaults?.value(forKey: kLanguageTypes) as! [NSNumber]).map({DJSchemeType.init(rawValue: $0.uint32Value)})
var response: [(String, Bool, DJSchemeType)] = []
for i in 0..<languages.count {
response.append((languages[i], enabledList[i], types[i]))
}
return response
}
class func storeLanguages(_ languages: [(String, Bool, DJSchemeType)]) {
let defaults = UserDefaults.init(suiteName: kAppGroupName)
defaults?.setValue(languages.map({$0.0}), forKey: kLanguagesKey)
defaults?.setValue(languages.map({$0.1}), forKey: kLanguagesEnabledKey)
defaults?.setValue(languages.map({$0.2.rawValue}), forKey: kLanguageTypes)
}
class func getSchemes() -> [String]? {
let path = getSchemesURL()!.appendingPathComponent("Transliteration").path
do {
let files = try FileManager.default.contentsOfDirectory(atPath: path)
return files.filter({$0.hasSuffix(".tlr")}).map({($0 as NSString).deletingPathExtension})
}
catch let error {
assert(false, "Unable to fetch file list from \(path) due to: \(error)")
return nil
}
}
}
|
8fb5d3344c2369991f3bea80e3be8226
| 45.237705 | 127 | 0.650594 | false | false | false | false |
coinbase/coinbase-ios-sdk
|
refs/heads/master
|
Example/Source/ViewControllers/SpotPrices/SpotPricesViewController.swift
|
apache-2.0
|
1
|
//
// SpotPricesViewController.swift
// iOS Example
//
// Copyright © 2018 Coinbase All rights reserved.
//
import UIKit
import CoinbaseSDK
class SpotPricesViewController: UIViewController {
private static let kSpotPriceCellID = "spotPriceCell"
public var selectedCurrency: String = Locale.current.currencyCode ?? "USD"
@IBOutlet weak var currencyLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
private weak var activityIndicator: UIActivityIndicatorView?
private let coinbase = Coinbase.default
private let refreshControl = ThemeRefreshControll()
private var prices: [Price] = []
// MARK: - Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
currencyLabel.text = selectedCurrency
setupTableView()
activityIndicator = view.addCenteredActivityIndicator()
loadSpotPrices()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Clear shadow image.
navigationController?.navigationBar.shadowImage = UIImage()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Restore system shadow image.
navigationController?.navigationBar.shadowImage = nil
}
// MARK: - Private Methods
private func setupTableView() {
tableView.tableFooterView = UIView()
refreshControl.addTarget(self, action: #selector(loadSpotPrices), for: .valueChanged)
tableView.addSubview(refreshControl)
}
@objc private func loadSpotPrices() {
coinbase.pricesResource.spotPrices(fiat: selectedCurrency) { [weak self] result in
switch result {
case .success(let prices):
self?.update(with: prices)
case .failure(let error):
self?.present(error: error)
}
self?.activityIndicator?.removeFromSuperview()
self?.refreshControl.endRefreshing()
}
}
private func update(with prices: [Price]) {
self.prices = prices
tableView.reloadData()
}
}
extension SpotPricesViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return prices.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SpotPricesViewController.kSpotPriceCellID,
for: indexPath) as! SpotPricesTableViewCell
cell.setup(with: prices[indexPath.row])
return cell
}
}
|
9a586fadc7d95ba28de0bc88e13d9c36
| 29.333333 | 107 | 0.639844 | false | false | false | false |
ipmobiletech/firefox-ios
|
refs/heads/master
|
UITests/ClearPrivateDataTests.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
import UIKit
// Needs to be in sync with Client Clearables.
private enum Clearable: String {
case History = "Browsing History"
case Logins = "Saved Logins"
case Cache = "Cache"
case OfflineData = "Offline Website Data"
case Cookies = "Cookies"
}
private let AllClearables = Set([Clearable.History, Clearable.Logins, Clearable.Cache, Clearable.OfflineData, Clearable.Cookies])
class ClearPrivateDataTests: KIFTestCase, UITextFieldDelegate {
private var webRoot: String!
override func setUp() {
webRoot = SimplePageServer.start()
}
override func tearDown() {
BrowserUtils.clearHistoryItems(tester())
}
private func clearPrivateData(clearables: Set<Clearable>) {
let webView = tester().waitForViewWithAccessibilityLabel("Web content") as! WKWebView
let lastTabLabel = webView.title!.isEmpty ? "home" : webView.title!
tester().tapViewWithAccessibilityLabel("Show Tabs")
tester().tapViewWithAccessibilityLabel("Settings")
tester().tapViewWithAccessibilityLabel("Clear Private Data")
// Disable all items that we don't want to clear.
for clearable in AllClearables.subtract(clearables) {
// If we don't wait here, setOn:forSwitchWithAccessibilityLabel tries to use the UITableViewCell
// instead of the UISwitch. KIF bug?
tester().waitForViewWithAccessibilityLabel(clearable.rawValue)
tester().setOn(false, forSwitchWithAccessibilityLabel: clearable.rawValue)
}
tester().tapViewWithAccessibilityLabel("Clear Private Data", traits: UIAccessibilityTraitButton)
tester().tapViewWithAccessibilityLabel("Settings")
tester().tapViewWithAccessibilityLabel("Done")
tester().tapViewWithAccessibilityLabel(lastTabLabel)
}
func visitSites(noOfSites noOfSites: Int) -> [(title: String, domain: String, url: String)] {
var urls: [(title: String, domain: String, url: String)] = []
for pageNo in 1...noOfSites {
tester().tapViewWithAccessibilityIdentifier("url")
let url = "\(webRoot)/numberedPage.html?page=\(pageNo)"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page \(pageNo)")
let tuple: (title: String, domain: String, url: String) = ("Page \(pageNo)", NSURL(string: url)!.normalizedHost()!, url)
urls.append(tuple)
}
BrowserUtils.resetToAboutHome(tester())
return urls
}
func anyDomainsExistOnTopSites(domains: Set<String>) {
for domain in domains {
if self.tester().viewExistsWithLabel(domain) {
return
}
}
XCTFail("Couldn't find any domains in top sites.")
}
func testClearsTopSitesPanel() {
let urls = visitSites(noOfSites: 2)
let domains = Set<String>(urls.map { $0.domain })
tester().tapViewWithAccessibilityLabel("Top sites")
// Only one will be found -- we collapse by domain.
anyDomainsExistOnTopSites(domains)
clearPrivateData([Clearable.History])
XCTAssertFalse(tester().viewExistsWithLabel(urls[0].title), "Expected to have removed top site panel \(urls[0])")
XCTAssertFalse(tester().viewExistsWithLabel(urls[1].title), "We shouldn't find the other URL, either.")
}
func testDisabledHistoryDoesNotClearTopSitesPanel() {
let urls = visitSites(noOfSites: 2)
let domains = Set<String>(urls.map { $0.domain })
anyDomainsExistOnTopSites(domains)
clearPrivateData(AllClearables.subtract([Clearable.History]))
anyDomainsExistOnTopSites(domains)
}
func testClearsHistoryPanel() {
let urls = visitSites(noOfSites: 2)
tester().tapViewWithAccessibilityLabel("History")
let url1 = "\(urls[0].title), \(urls[0].url)"
let url2 = "\(urls[1].title), \(urls[1].url)"
XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to have history row \(url1)")
XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to have history row \(url2)")
clearPrivateData([Clearable.History])
tester().tapViewWithAccessibilityLabel("History")
XCTAssertFalse(tester().viewExistsWithLabel(url1), "Expected to have removed history row \(url1)")
XCTAssertFalse(tester().viewExistsWithLabel(url2), "Expected to have removed history row \(url2)")
}
func testDisabledHistoryDoesNotClearHistoryPanel() {
let urls = visitSites(noOfSites: 2)
tester().tapViewWithAccessibilityLabel("History")
let url1 = "\(urls[0].title), \(urls[0].url)"
let url2 = "\(urls[1].title), \(urls[1].url)"
XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to have history row \(url1)")
XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to have history row \(url2)")
clearPrivateData(AllClearables.subtract([Clearable.History]))
XCTAssertTrue(tester().viewExistsWithLabel(url1), "Expected to not have removed history row \(url1)")
XCTAssertTrue(tester().viewExistsWithLabel(url2), "Expected to not have removed history row \(url2)")
}
func testClearsCookies() {
tester().tapViewWithAccessibilityIdentifier("url")
let url = "\(webRoot)/numberedPage.html?page=1"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
let webView = tester().waitForViewWithAccessibilityLabel("Web content") as! WKWebView
// Set and verify a dummy cookie value.
setCookies(webView, cookie: "foo=bar")
var cookies = getCookies(webView)
XCTAssertEqual(cookies.cookie, "foo=bar")
XCTAssertEqual(cookies.localStorage, "foo=bar")
XCTAssertEqual(cookies.sessionStorage, "foo=bar")
// Verify that cookies are not cleared when Cookies is deselected.
clearPrivateData(AllClearables.subtract([Clearable.Cookies]))
cookies = getCookies(webView)
XCTAssertEqual(cookies.cookie, "foo=bar")
XCTAssertEqual(cookies.localStorage, "foo=bar")
XCTAssertEqual(cookies.sessionStorage, "foo=bar")
// Verify that cookies are cleared when Cookies is selected.
clearPrivateData([Clearable.Cookies])
cookies = getCookies(webView)
XCTAssertEqual(cookies.cookie, "")
XCTAssertNil(cookies.localStorage)
XCTAssertNil(cookies.sessionStorage)
}
@available(iOS 9.0, *)
func testClearsCache() {
let cachedServer = CachedPageServer()
let cacheRoot = cachedServer.start()
let url = "\(cacheRoot)/cachedPage.html"
tester().tapViewWithAccessibilityIdentifier("url")
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Cache test")
let webView = tester().waitForViewWithAccessibilityLabel("Web content") as! WKWebView
let requests = cachedServer.requests
// Verify that clearing non-cache items will keep the page in the cache.
clearPrivateData(AllClearables.subtract([Clearable.Cache]))
webView.reload()
XCTAssertEqual(cachedServer.requests, requests)
// Verify that clearing the cache will fire a new request.
clearPrivateData([Clearable.Cache])
webView.reload()
XCTAssertEqual(cachedServer.requests, requests + 1)
}
func testClearsLogins() {
tester().tapViewWithAccessibilityIdentifier("url")
let url = "\(webRoot)/loginForm.html"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Submit")
// The form should be empty when we first load it.
XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("foo"))
XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("bar"))
// Fill it in and submit.
tester().enterText("foo", intoWebViewInputWithName: "username")
tester().enterText("bar", intoWebViewInputWithName: "password")
tester().tapWebViewElementWithAccessibilityLabel("Submit")
// Say "Yes" to the remember password prompt.
tester().tapViewWithAccessibilityLabel("Yes")
// Verify that the form is autofilled after reloading.
tester().tapViewWithAccessibilityLabel("Reload")
XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("foo"))
XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("bar"))
// Ensure that clearing other data has no effect on the saved logins.
clearPrivateData(AllClearables.subtract([Clearable.Logins]))
tester().tapViewWithAccessibilityLabel("Reload")
XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("foo"))
XCTAssert(tester().hasWebViewElementWithAccessibilityLabel("bar"))
// Ensure that clearing logins clears the form.
clearPrivateData([Clearable.Logins])
tester().tapViewWithAccessibilityLabel("Reload")
XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("foo"))
XCTAssertFalse(tester().hasWebViewElementWithAccessibilityLabel("bar"))
}
private func setCookies(webView: WKWebView, cookie: String) {
let expectation = expectationWithDescription("Set cookie")
webView.evaluateJavaScript("document.cookie = \"\(cookie)\"; localStorage.cookie = \"\(cookie)\"; sessionStorage.cookie = \"\(cookie)\";") { result, _ in
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
private func getCookies(webView: WKWebView) -> (cookie: String, localStorage: String?, sessionStorage: String?) {
var cookie: (String, String?, String?)!
let expectation = expectationWithDescription("Got cookie")
webView.evaluateJavaScript("JSON.stringify([document.cookie, localStorage.cookie, sessionStorage.cookie])") { result, _ in
let cookies = JSON.parse(result as! String).asArray!
cookie = (cookies[0].asString!, cookies[1].asString, cookies[2].asString)
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
return cookie
}
}
/// Server that keeps track of requests.
private class CachedPageServer {
var requests = 0
func start() -> String {
let webServer = GCDWebServer()
webServer.addHandlerForMethod("GET", path: "/cachedPage.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
self.requests++
return GCDWebServerDataResponse(HTML: "<html><head><title>Cached page</title></head><body>Cache test</body></html>")
}
webServer.startWithPort(0, bonjourName: nil)
// We use 127.0.0.1 explicitly here, rather than localhost, in order to avoid our
// history exclusion code (Bug 1188626).
let webRoot = "http://127.0.0.1:\(webServer.port)"
return webRoot
}
}
|
d758a510a5bca9eb6eb4248e4768f947
| 43.088123 | 161 | 0.681151 | false | true | false | false |
5lucky2xiaobin0/PandaTV
|
refs/heads/master
|
PandaTV/PandaTV/Classes/Main/VIew/IndexTitleView.swift
|
mit
|
1
|
//
// IndexTitleView.swift
// PandaTV
//
// Created by 钟斌 on 2017/3/24.
// Copyright © 2017年 xiaobin. All rights reserved.
//
import UIKit
private let titleVCW : CGFloat = 240
private let titleVCH : CGFloat = 40
private let titleButtonW : CGFloat = 55
private let titleButtonH : CGFloat = 32
protocol IndexTitleViewDetegate : class {
func indexTitleView(index : Int)
func indexTitleViewToSearch()
}
class IndexTitleView: UIView {
weak var delegate : IndexTitleViewDetegate?
var selected : UIButton?
var titles : [String]?
var line : UIView = UIView()
var titleVC : UIView = UIView()
var titleBtns : [UIButton] = [UIButton]()
lazy var searchBtn : UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named : "search_new"), for: .normal)
btn.addTarget(self, action: #selector(search), for: .touchUpInside)
return btn
}()
init(frame: CGRect, titles : [String]) {
self.titles = titles
super.init(frame: frame)
//界面设置
setUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension IndexTitleView {
fileprivate func setUI(){
//添加查询按钮
self.addSubview(searchBtn)
//添加标题框
setTitleChooseView()
}
func setTitleChooseView(){
let x = (self.bounds.width - titleVCW)/2
let y = self.bounds.height - titleVCH
titleVC.frame = CGRect(x: x, y: y, width: titleVCW, height: titleVCH)
self.addSubview(titleVC)
//添加底部线段
line.frame = CGRect(x: 0, y: titleVC.bounds.height - 2, width: titleButtonW, height: 2)
line.backgroundColor = UIColor.getGreenColor()
titleVC.addSubview(line)
var titleX : CGFloat = 0
var i : CGFloat = 0
//添加标题按钮
for title in titles! {
titleX = i * titleButtonW + (i+1) * 15
let titleButton = UIButton(frame: CGRect(x: titleX, y: 4, width: titleButtonW, height: titleButtonH))
titleButton.setTitle(title, for: .normal)
titleButton.setTitleColor(UIColor.black, for: .normal)
titleButton.setTitleColor(UIColor.getGreenColor(), for: .selected)
titleButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
titleButton.tag = Int(i)
titleButton.addTarget(self, action: #selector(titleClick(btn:)), for: .touchUpInside)
if i == 1 {
titleClick(btn: titleButton)
}
titleBtns.append(titleButton)
titleVC.addSubview(titleButton)
i+=1
}
}
override func layoutSubviews() {
let x = self.bounds.width - 52
let y = self.bounds.height - 35
searchBtn.frame = CGRect(x: x, y: y, width: 32, height: 32)
}
}
// MARK: - 事件处理
extension IndexTitleView {
@objc fileprivate func search() {
delegate?.indexTitleViewToSearch()
}
@objc fileprivate func titleClick(btn : UIButton) {
self.selected?.isSelected = false
btn.isSelected = true
self.selected = btn
UIView.animate(withDuration: 0.2) {
self.line.frame = CGRect(x: btn.frame.origin.x, y: self.titleVC.bounds.height - 2, width: titleButtonW, height: 2)
}
delegate?.indexTitleView(index: btn.tag)
}
func scrollToTitle(index : Int) {
let btn = titleBtns[index]
titleClick(btn: btn)
}
}
|
09de04de1d3866b5c36108d0892420ab
| 26.736842 | 126 | 0.574139 | false | false | false | false |
xwu/swift
|
refs/heads/master
|
tools/swift-inspect/Sources/swift-inspect/main.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import SwiftRemoteMirror
func argFail(_ message: String) -> Never {
print(message, to: &Std.err)
exit(EX_USAGE)
}
func machErrStr(_ kr: kern_return_t) -> String {
let errStr = String(cString: mach_error_string(kr))
let errHex = String(kr, radix: 16)
return "\(errStr) (0x\(errHex))"
}
func dumpConformanceCache(context: SwiftReflectionContextRef) throws {
try context.iterateConformanceCache { type, proto in
let typeName = context.name(metadata: type) ?? "<unknown>"
let protoName = context.name(proto: proto) ?? "<unknown>"
print("Conformance: \(typeName): \(protoName)")
}
}
func dumpRawMetadata(
context: SwiftReflectionContextRef,
inspector: Inspector,
backtraceStyle: Backtrace.Style?
) throws {
let backtraces = backtraceStyle != nil ? context.allocationBacktraces : [:]
for allocation in context.allocations {
let tagName = context.metadataTagName(allocation.tag) ?? "<unknown>"
print("Metadata allocation at: \(hex: allocation.ptr) " +
"size: \(allocation.size) tag: \(allocation.tag) (\(tagName))")
printBacktrace(style: backtraceStyle, for: allocation.ptr, in: backtraces, inspector: inspector)
}
}
func dumpGenericMetadata(
context: SwiftReflectionContextRef,
inspector: Inspector,
backtraceStyle: Backtrace.Style?
) throws {
let allocations = context.allocations.sorted()
let metadatas = allocations.findGenericMetadata(in: context)
let backtraces = backtraceStyle != nil ? context.allocationBacktraces : [:]
print("Address","Allocation","Size","Offset","Name", separator: "\t")
for metadata in metadatas {
print("\(hex: metadata.ptr)", terminator: "\t")
if let allocation = metadata.allocation, let offset = metadata.offset {
print("\(hex: allocation.ptr)\t\(allocation.size)\t\(offset)",
terminator: "\t")
} else {
print("???\t???\t???", terminator: "\t")
}
print(metadata.name)
if let allocation = metadata.allocation {
printBacktrace(style: backtraceStyle, for: allocation.ptr, in: backtraces, inspector: inspector)
}
}
}
func dumpMetadataCacheNodes(
context: SwiftReflectionContextRef,
inspector: Inspector
) throws {
print("Address","Tag","Tag Name","Size","Left","Right", separator: "\t")
for allocation in context.allocations {
guard let node = context.metadataAllocationCacheNode(allocation.allocation_t) else {
continue
}
let tagName = context.metadataTagName(allocation.tag) ?? "<unknown>"
print("\(hex: allocation.ptr)\t\(allocation.tag)\t\(tagName)\t" +
"\(allocation.size)\t\(hex: node.Left)\t\(hex: node.Right)")
}
}
func printBacktrace(
style: Backtrace.Style?,
for ptr: swift_reflection_ptr_t,
in backtraces: [swift_reflection_ptr_t: Backtrace],
inspector: Inspector
) {
if let style = style {
if let backtrace = backtraces[ptr] {
print(backtrace.symbolicated(style: style, inspector: inspector))
} else {
print("Unknown backtrace.")
}
}
}
func makeReflectionContext(
nameOrPid: String
) -> (Inspector, SwiftReflectionContextRef) {
guard let pid = pidFromHint(nameOrPid) else {
argFail("Cannot find pid/process \(nameOrPid)")
}
guard let inspector = Inspector(pid: pid) else {
argFail("Failed to inspect pid \(pid) (are you running as root?)")
}
guard let reflectionContext = swift_reflection_createReflectionContextWithDataLayout(
inspector.passContext(),
Inspector.Callbacks.QueryDataLayout,
Inspector.Callbacks.Free,
Inspector.Callbacks.ReadBytes,
Inspector.Callbacks.GetStringLength,
Inspector.Callbacks.GetSymbolAddress
) else {
argFail("Failed to create reflection context")
}
return (inspector, reflectionContext)
}
func withReflectionContext(
nameOrPid: String,
_ body: (SwiftReflectionContextRef, Inspector) throws -> Void
) throws {
let (inspector, context) = makeReflectionContext(nameOrPid: nameOrPid)
defer {
swift_reflection_destroyReflectionContext(context)
inspector.destroyContext()
}
try body(context, inspector)
}
struct SwiftInspect: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Swift runtime debug tool",
subcommands: [
DumpConformanceCache.self,
DumpRawMetadata.self,
DumpGenericMetadata.self,
DumpCacheNodes.self,
])
}
struct UniversalOptions: ParsableArguments {
@Argument(help: "The pid or partial name of the target process")
var nameOrPid: String
}
struct BacktraceOptions: ParsableArguments {
@Flag(help: "Show the backtrace for each allocation")
var backtrace: Bool = false
@Flag(help: "Show a long-form backtrace for each allocation")
var backtraceLong: Bool = false
var style: Backtrace.Style? {
backtrace ? .oneLine :
backtraceLong ? .long :
nil
}
}
struct DumpConformanceCache: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Print the contents of the target's protocol conformance cache.")
@OptionGroup()
var options: UniversalOptions
func run() throws {
try withReflectionContext(nameOrPid: options.nameOrPid) { context, _ in
try dumpConformanceCache(context: context)
}
}
}
struct DumpRawMetadata: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Print the target's metadata allocations.")
@OptionGroup()
var universalOptions: UniversalOptions
@OptionGroup()
var backtraceOptions: BacktraceOptions
func run() throws {
try withReflectionContext(nameOrPid: universalOptions.nameOrPid) {
try dumpRawMetadata(context: $0,
inspector: $1,
backtraceStyle: backtraceOptions.style)
}
}
}
struct DumpGenericMetadata: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Print the target's generic metadata allocations.")
@OptionGroup()
var universalOptions: UniversalOptions
@OptionGroup()
var backtraceOptions: BacktraceOptions
func run() throws {
try withReflectionContext(nameOrPid: universalOptions.nameOrPid) {
try dumpGenericMetadata(context: $0,
inspector: $1,
backtraceStyle: backtraceOptions.style)
}
}
}
struct DumpCacheNodes: ParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Print the target's metadata cache nodes.")
@OptionGroup()
var options: UniversalOptions
func run() throws {
try withReflectionContext(nameOrPid: options.nameOrPid) {
try dumpMetadataCacheNodes(context: $0,
inspector: $1)
}
}
}
SwiftInspect.main()
|
78d0cc064d8d097b7a1dac2111a2c5ce
| 29.008299 | 102 | 0.685564 | false | false | false | false |
jeffreybergier/WaterMe2
|
refs/heads/master
|
WaterMe/Frameworks/Datum/Datum/Wrapper/ReminderCollection/RLM_ReminderCollection.swift
|
gpl-3.0
|
1
|
//
// RLM_ReminderCollection.swift
// Datum
//
// Created by Jeffrey Bergier on 2020/05/21.
// Copyright © 2020 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import RealmSwift
internal class RLM_ReminderCollection: BaseCollection {
private let collection: AnyRealmCollection<RLM_Reminder>
private let transform: (RLM_Reminder) -> Reminder = { RLM_ReminderWrapper($0) }
internal init(_ collection: AnyRealmCollection<RLM_Reminder>) {
self.collection = collection
}
subscript(index: Int) -> Reminder? { self.transform(self.collection[index]) }
func count(at index: Int?) -> Int? {
guard index != nil else { return 1 }
return self.collection.count
}
func compactMap<NewElement>(_ transform: (Element?) throws -> NewElement?) rethrows -> [NewElement] {
return try self.collection.compactMap { try transform(self.transform($0)) }
}
func index(of item: Reminder) -> Int? {
let reminder = (item as! RLM_ReminderWrapper).wrappedObject
return self.collection.index(of: reminder)
}
func indexOfItem(with identifier: Identifier) -> Int? {
return self.collection.index(matching: "\(#keyPath(RLM_Reminder.uuid)) == %@", identifier.uuid)
}
}
internal class RLM_ReminderQuery: CollectionQuery {
private let collection: AnyRealmCollection<RLM_Reminder>
init(_ collection: AnyRealmCollection<RLM_Reminder>) {
self.collection = collection
}
func observe(_ block: @escaping (ReminderCollectionChange) -> Void) -> ObservationToken {
return self.collection.observe { realmChange in
switch realmChange {
case .initial(let data):
block(.initial(data: AnyCollection(RLM_ReminderCollection(data))))
case .update(_, let deletions, let insertions, let modifications):
block(.update(.init(insertions: insertions, deletions: deletions, modifications: modifications)))
case .error:
block(.error(error: .readError))
}
}
}
}
|
9749fb99329b4374893d1790e9ad3d97
| 35.907895 | 113 | 0.665241 | false | false | false | false |
serp1412/LazyTransitions
|
refs/heads/master
|
LazyTransitions/InteractiveTransitioner.swift
|
bsd-2-clause
|
1
|
//
// InteractiveTransitioner.swift
// LazyTransitions
//
// Created by Serghei Catraniuc on 11/30/16.
// Copyright © 2016 BeardWare. All rights reserved.
//
import Foundation
public class InteractiveTransitioner: InteractiveTransitionerType {
//MARK: Initializers
public required init(with gestureHandler: TransitionGestureHandlerType,
with animator: TransitionAnimatorType = DismissAnimator(orientation: .topToBottom),
with interactor: TransitionInteractor = TransitionInteractor.default()) {
self.gestureHandler = gestureHandler
self.animator = animator
self.animator.delegate = self
self.gestureHandler.delegate = self
self.interactor = interactor
}
//MARK: InteractiveTransitioner Protocol
public var gestureHandler: TransitionGestureHandlerType
public weak var delegate: TransitionerDelegate?
public var animator: TransitionAnimatorType
public var interactor: TransitionInteractor?
}
extension InteractiveTransitioner: TransitionGestureHandlerDelegate {
public func beginInteractiveTransition(with orientation: TransitionOrientation) {
guard animator.allowedOrientations?.contains(orientation) ?? true else { return }
guard animator.supportedOrientations.contains(orientation) else { return }
animator.orientation = orientation
delegate?.beginTransition(with: self)
}
public func updateInteractiveTransitionWithProgress(_ progress: CGFloat) {
interactor?.update(progress)
}
public func finishInteractiveTransition() {
interactor?.setCompletionSpeedForFinish()
interactor?.finish()
}
public func cancelInteractiveTransition() {
interactor?.setCompletionSpeedForCancel()
interactor?.cancel()
}
}
extension InteractiveTransitioner: TransitionAnimatorDelegate {
public func transitionDidFinish(_ completed: Bool) {
delegate?.finishedInteractiveTransition(completed)
}
}
|
f31231ccb205b7675b687c99f12116b2
| 32.75 | 92 | 0.729877 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/CryptoAssets/Sources/BitcoinKit/Account/BitcoinAsset.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BitcoinChainKit
import Combine
import DIKit
import FeatureCryptoDomainDomain
import MoneyKit
import PlatformKit
import RxSwift
import ToolKit
private struct AccountsPayload {
let defaultAccount: BitcoinWalletAccount
let accounts: [BitcoinWalletAccount]
}
final class BitcoinAsset: CryptoAsset {
let asset: CryptoCurrency = .bitcoin
var defaultAccount: AnyPublisher<SingleAccount, CryptoAssetError> {
repository.defaultAccount
.mapError(CryptoAssetError.failedToLoadDefaultAccount)
.map { account in
BitcoinCryptoAccount(
walletAccount: account,
isDefault: true
)
}
.eraseToAnyPublisher()
}
var canTransactToCustodial: AnyPublisher<Bool, Never> {
cryptoAssetRepository.canTransactToCustodial
}
// MARK: - Private properties
private lazy var cryptoAssetRepository: CryptoAssetRepositoryAPI = CryptoAssetRepository(
asset: asset,
errorRecorder: errorRecorder,
kycTiersService: kycTiersService,
defaultAccountProvider: { [defaultAccount] in
defaultAccount
},
exchangeAccountsProvider: exchangeAccountProvider,
addressFactory: addressFactory
)
private let addressFactory: ExternalAssetAddressFactory
private let errorRecorder: ErrorRecording
private let exchangeAccountProvider: ExchangeAccountsProviderAPI
private let repository: BitcoinWalletAccountRepository
private let kycTiersService: KYCTiersServiceAPI
init(
addressFactory: ExternalAssetAddressFactory = resolve(
tag: BitcoinChainCoin.bitcoin
),
errorRecorder: ErrorRecording = resolve(),
exchangeAccountProvider: ExchangeAccountsProviderAPI = resolve(),
kycTiersService: KYCTiersServiceAPI = resolve(),
repository: BitcoinWalletAccountRepository = resolve()
) {
self.addressFactory = addressFactory
self.errorRecorder = errorRecorder
self.exchangeAccountProvider = exchangeAccountProvider
self.kycTiersService = kycTiersService
self.repository = repository
}
// MARK: - Methods
func initialize() -> AnyPublisher<Void, AssetError> {
// Run wallet renaming procedure on initialization.
cryptoAssetRepository
.nonCustodialGroup
.compactMap { $0 }
.map(\.accounts)
.flatMap { [upgradeLegacyLabels] accounts in
upgradeLegacyLabels(accounts)
}
.mapError()
.eraseToAnyPublisher()
}
func accountGroup(filter: AssetFilter) -> AnyPublisher<AccountGroup?, Never> {
var groups: [AnyPublisher<AccountGroup?, Never>] = []
if filter.contains(.custodial) {
groups.append(custodialGroup)
}
if filter.contains(.interest) {
groups.append(interestGroup)
}
if filter.contains(.nonCustodial) {
groups.append(nonCustodialGroup)
}
if filter.contains(.exchange) {
groups.append(exchangeGroup)
}
return groups
.zip()
.eraseToAnyPublisher()
.flatMapAllAccountGroup()
}
func parse(address: String) -> AnyPublisher<ReceiveAddress?, Never> {
cryptoAssetRepository.parse(address: address)
}
func parse(
address: String,
label: String,
onTxCompleted: @escaping (TransactionResult) -> Completable
) -> Result<CryptoReceiveAddress, CryptoReceiveAddressFactoryError> {
cryptoAssetRepository.parse(address: address, label: label, onTxCompleted: onTxCompleted)
}
// MARK: - Private methods
private var allAccountsGroup: AnyPublisher<AccountGroup?, Never> {
[
nonCustodialGroup,
custodialGroup,
interestGroup,
exchangeGroup
]
.zip()
.eraseToAnyPublisher()
.flatMapAllAccountGroup()
}
private var exchangeGroup: AnyPublisher<AccountGroup?, Never> {
cryptoAssetRepository.exchangeGroup
}
private var interestGroup: AnyPublisher<AccountGroup?, Never> {
cryptoAssetRepository.interestGroup
}
private var custodialGroup: AnyPublisher<AccountGroup?, Never> {
cryptoAssetRepository.custodialGroup
}
private var custodialAndInterestGroup: AnyPublisher<AccountGroup?, Never> {
cryptoAssetRepository.custodialAndInterestGroup
}
private var nonCustodialGroup: AnyPublisher<AccountGroup?, Never> {
repository.activeAccounts
.eraseToAnyPublisher()
.eraseError()
.flatMap { [repository] accounts -> AnyPublisher<AccountsPayload, Error> in
repository.defaultAccount
.map { .init(defaultAccount: $0, accounts: accounts) }
.eraseError()
.eraseToAnyPublisher()
}
.map { accountPayload -> [SingleAccount] in
accountPayload.accounts.map { account in
BitcoinCryptoAccount(
walletAccount: account,
isDefault: account.publicKeys.default == accountPayload.defaultAccount.publicKeys.default
)
}
}
.map { [asset] accounts -> AccountGroup? in
if accounts.isEmpty {
return nil
}
return CryptoAccountNonCustodialGroup(asset: asset, accounts: accounts)
}
.recordErrors(on: errorRecorder)
.replaceError(with: nil)
.eraseToAnyPublisher()
}
}
extension BitcoinAsset: DomainResolutionRecordProviderAPI {
var resolutionRecord: AnyPublisher<ResolutionRecord, Error> {
resolutionRecordAccount
.eraseError()
.flatMap { account in
account.firstReceiveAddress.eraseError()
}
.map { [asset] receiveAddress in
ResolutionRecord(symbol: asset.code, walletAddress: receiveAddress.address)
}
.eraseToAnyPublisher()
}
private var resolutionRecordAccount: AnyPublisher<BitcoinCryptoAccount, BitcoinWalletRepositoryError> {
repository
.accounts
.map { accounts -> BitcoinWalletAccount? in
accounts.first(where: { $0.index == 0 })
}
.onNil(.missingWallet)
.map { account in
BitcoinCryptoAccount(
walletAccount: account,
isDefault: false
)
}
.eraseToAnyPublisher()
}
}
|
914e742e5107b0c5b38abf4a366525f3
| 31.122066 | 113 | 0.622625 | false | false | false | false |
hkellaway/Gloss
|
refs/heads/develop
|
Sources/Encoder.swift
|
mit
|
2
|
//
// Encoder.swift
// Gloss
//
// Copyright (c) 2015 Harlan Kellaway
//
// 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
/**
Encodes objects to JSON.
*/
public struct Encoder {
/**
Encodes a generic value to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T>(key: String) -> (T?) -> JSON? {
return {
property in
if let property = property {
return [key : property]
}
return nil
}
}
/**
Encodes a generic value array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T>(arrayForKey key: String) -> ([T]?) -> JSON? {
return {
array in
if let array = array {
return [key : array]
}
return nil
}
}
/**
Encodes a date to JSON.
- parameter key: Key used in JSON for decoded value.
- parameter dateFormatter: Date formatter used to encode date.
- returns: JSON encoded from value.
*/
public static func encode(dateForKey key: String, dateFormatter: DateFormatter) -> (Date?) -> JSON? {
return {
date in
if let date = date {
return [key : dateFormatter.string(from: date)]
}
return nil
}
}
/**
Encodes a date array to JSON.
- parameter key: Key used in JSON for decoded value.
- parameter dateFormatter: Date formatter used to encode date.
- returns: JSON encoded from value.
*/
public static func encode(dateArrayForKey key: String, dateFormatter: DateFormatter) -> ([Date]?) -> JSON? {
return {
dates in
if let dates = dates {
var dateStrings: [String] = []
for date in dates {
let dateString = dateFormatter.string(from: date)
dateStrings.append(dateString)
}
return [key : dateStrings]
}
return nil
}
}
/**
Encodes an ISO8601 date to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(dateISO8601ForKey key: String) -> (Date?) -> JSON? {
return Encoder.encode(dateForKey: key, dateFormatter: GlossDateFormatterISO8601)
}
/**
Encodes an ISO8601 date array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(dateISO8601ArrayForKey key: String) -> ([Date]?) -> JSON? {
return Encoder.encode(dateArrayForKey: key, dateFormatter: GlossDateFormatterISO8601)
}
/**
Encodes an JSONEncodable object to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: JSONEncodable>(encodableForKey key: String) -> (T?) -> JSON? {
return {
model in
if let model = model, let json = model.toJSON() {
return [key : json]
}
return nil
}
}
/**
Encodes an JSONEncodable array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: JSONEncodable>(encodableArrayForKey key: String) -> ([T]?) -> JSON? {
return {
array in
if let array = array {
var encodedArray: [JSON] = []
for model in array {
guard let json = model.toJSON() else {
return nil
}
encodedArray.append(json)
}
return [key : encodedArray]
}
return nil
}
}
/**
Encodes a dictionary of String to JSONEncodable to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: JSONEncodable>(encodableDictionaryForKey key: String) -> ([String : T]?) -> JSON? {
return {
dictionary in
guard let dictionary = dictionary else {
return nil
}
let encoded : [String : JSON] = dictionary.flatMap { (key, value) in
guard let json = value.toJSON() else {
return nil
}
return (key, json)
}
return [key : encoded]
}
}
/**
Encodes a dictionary of String to JSONEncodable array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: JSONEncodable>(encodableDictionaryForKey key: String) -> ([String : [T]]?) -> JSON? {
return {
dictionary in
guard let dictionary = dictionary else {
return nil
}
let encoded : [String : [JSON]] = dictionary.flatMap {
(key, value) in
guard let jsonArray = value.toJSONArray() else {
return nil
}
return (key, jsonArray)
}
return [key : encoded]
}
}
/**
Encodes an enum value to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: RawRepresentable>(enumForKey key: String) -> (T?) -> JSON? {
return {
enumValue in
if let enumValue = enumValue {
return [key : enumValue.rawValue]
}
return nil
}
}
/**
Encodes an enum value array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode<T: RawRepresentable>(enumArrayForKey key: String) -> ([T]?) -> JSON? {
return {
enumValues in
if let enumValues = enumValues {
var rawValues: [T.RawValue] = []
for enumValue in enumValues {
rawValues.append(enumValue.rawValue)
}
return [key : rawValues]
}
return nil
}
}
/**
Encodes an Int32 to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(int32ForKey key: String) -> (Int32?) -> JSON? {
return {
int32 in
if let int32 = int32 {
return [key : NSNumber(value: int32)]
}
return nil
}
}
/**
Encodes an Int32 array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(int32ArrayForKey key: String) -> ([Int32]?) -> JSON? {
return {
int32Array in
if let int32Array = int32Array {
let numbers: [NSNumber] = int32Array.map { NSNumber(value: $0) }
return [key : numbers]
}
return nil
}
}
/**
Encodes an UInt32 to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(uint32ForKey key: String) -> (UInt32?) -> JSON? {
return {
uint32 in
if let uint32 = uint32 {
return [key : NSNumber(value: uint32)]
}
return nil
}
}
/**
Encodes an UInt32 array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(uint32ArrayForKey key: String) -> ([UInt32]?) -> JSON? {
return {
uInt32Array in
if let uInt32Array = uInt32Array {
let numbers: [NSNumber] = uInt32Array.map { NSNumber(value: $0) }
return [key : numbers]
}
return nil
}
}
/**
Encodes an Int64 to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(int64ForKey key: String) -> (Int64?) -> JSON? {
return {
int64 in
if let int64 = int64 {
return [key : NSNumber(value: int64)]
}
return nil
}
}
/**
Encodes an Int64 array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(int64ArrayForKey key: String) -> ([Int64]?) -> JSON? {
return {
int64Array in
if let int64Array = int64Array {
let numbers: [NSNumber] = int64Array.map { NSNumber(value: $0) }
return [key : numbers]
}
return nil
}
}
/**
Encodes an UInt64 to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(uint64ForKey key: String) -> (UInt64?) -> JSON? {
return {
uInt64 in
if let uInt64 = uInt64 {
return [key : NSNumber(value: uInt64)]
}
return nil
}
}
/**
Encodes an UInt64 array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(uint64ArrayForKey key: String) -> ([UInt64]?) -> JSON? {
return {
uInt64Array in
if let uInt64Array = uInt64Array {
let numbers: [NSNumber] = uInt64Array.map { NSNumber(value: $0) }
return [key : numbers]
}
return nil
}
}
/**
Encodes a URL to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(urlForKey key: String) -> (URL?) -> JSON? {
return {
url in
if let absoluteURLString = url?.absoluteString {
return [key : absoluteURLString]
}
return nil
}
}
/**
Encodes a UUID to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(uuidForKey key: String) -> (UUID?) -> JSON? {
return {
uuid in
if let uuidString = uuid?.uuidString {
return [key : uuidString]
}
return nil
}
}
/**
Encodes a Double array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(doubleForKey key: String) -> (Double?) -> JSON? {
return {
double in
if let double = double {
return [key : NSNumber(value: double)]
}
return nil
}
}
/**
Encodes a Double array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(doubleArrayForKey key: String) -> ([Double]?) -> JSON? {
return {
doubleArray in
if let doubleArray = doubleArray {
let numbers: [NSNumber] = doubleArray.map { NSNumber(value: $0) }
return [key : numbers]
}
return nil
}
}
/**
Encodes a Double to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(decimalForKey key: String) -> (Decimal?) -> JSON? {
return {
decimal in
if let decimal = decimal {
return [key : NSDecimalNumber(decimal: decimal)]
}
return nil
}
}
/**
Encodes a Decimal array to JSON.
- parameter key: Key used in JSON for decoded value.
- returns: JSON encoded from value.
*/
public static func encode(decimalArrayForKey key: String) -> ([Decimal]?) -> JSON? {
return {
decimalArray in
if let decimalArray = decimalArray {
let numbers: [NSDecimalNumber] = decimalArray.map { NSDecimalNumber(decimal: $0) }
return [key : numbers]
}
return nil
}
}
}
|
672821cc72a865efe514f4524d41d18b
| 25.038869 | 118 | 0.513435 | false | false | false | false |
thatseeyou/SpriteKitExamples.playground
|
refs/heads/master
|
Pages/Explosion.xcplaygroundpage/Contents.swift
|
isc
|
1
|
/*:
### 특점 지점에서의 폭파 효과
참고 : iOS Swift Game Development Cookbook
*/
import UIKit
import SpriteKit
class GameScene: SKScene {
var contentCreated = false
let pi:CGFloat = CGFloat(M_PI)
override func didMove(to view: SKView) {
if self.contentCreated != true {
// SKScene의 경계에 physicsbody 설정
self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
// Simulation 속도를 느리게 (디폴트는 1.0)
self.physicsWorld.speed = 0.4
for x in 0..<5 {
for y in 0..<10 {
addBall(CGPoint(x: CGFloat(160 + x * 11), y: CGFloat(y * 11)))
addBall(CGPoint(x: CGFloat(160 - x * 11), y: CGFloat(y * 11)))
}
}
Utility.runActionAfterTime(3) { () in
self.applyExplosionAtPoint(CGPoint(x: 160, y: 0), radius: 100, power: 70)
}
self.contentCreated = true
}
}
func addBall(_ position:CGPoint) {
let ball = SKSpriteNode(color: #colorLiteral(red: 0.7540004253387451, green: 0, blue: 0.2649998068809509, alpha: 1), size: CGSize(width: 10,height: 10))
ball.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 10,height: 10))
ball.position = position
ball.physicsBody!.density = 1
addChild(ball)
}
func applyExplosionAtPoint(_ point: CGPoint,
radius:CGFloat, power:CGFloat) {
// Work out which bodies are in range of the explosion // by creating a rectangle
let explosionRect = CGRect(x: point.x - radius,
y: point.y - radius,
width: radius*2, height: radius*2)
// For each body, apply an explosion force
self.physicsWorld.enumerateBodies(in: explosionRect, using:{ (body, stop) in
// Work out if the body has a node that we can use
if let bodyPosition = body.node?.position {
// Work out the direction that we should apply // the force in for this body
let explosionOffset =
CGVector(dx: bodyPosition.x - point.x,
dy: bodyPosition.y - point.y)
// Work out the distance from the explosion point
let explosionDistance =
sqrt(explosionOffset.dx * explosionOffset.dx +
explosionOffset.dy * explosionOffset.dy)
// Normalize the explosion force
var explosionForce = explosionOffset
explosionForce.dx /= explosionDistance
explosionForce.dy /= explosionDistance
// Multiply by explosion power
explosionForce.dx *= power
explosionForce.dy *= power
// Finally, apply the force
body.applyForce(explosionForce)
}
})
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// add SKView
do {
let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480))
skView.showsFPS = true
//skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
let scene = GameScene(size: CGSize(width: 320, height: 480))
scene.scaleMode = .aspectFit
skView.presentScene(scene)
self.view.addSubview(skView)
}
}
}
PlaygroundHelper.showViewController(ViewController())
|
30b727670858a452e5fda042a7294134
| 35.377551 | 160 | 0.5554 | false | false | false | false |
viteinfinite/Nabigeta
|
refs/heads/master
|
Nabigeta/Navigation/Strategy/SegueStrategy.swift
|
mit
|
1
|
//
// SegueStrategy.swift
// Nabigeta
//
// Created by JC on 06/11/14.
// Copyright (c) 2014 fr.milkshake. All rights reserved.
//
import Foundation
import UIKit
public class SegueStrategy: NavigationStrategy {
private let route: SegueRoute
public init(route: SegueRoute) {
self.route = route
}
public func navigate(navigationContext: NavigationContext) {
let handler = SegueNavigationHandler()
let source = navigationContext.sourceViewController
handler.prepareSegueHandler = { segue in
var destination = segue.destinationViewController as UIViewController
if let navigationController = destination as? UINavigationController {
destination = navigationController.topViewController
}
navigationContext.updateContext(destination)
}
source.segueHandler = handler
source.performSegueWithIdentifier(self.route.segueIdentifier, sender: source)
}
public func navigateBack(sender: UIViewController) {
}
}
|
c1f28c0fabba7078370f588d5e256b8e
| 26.153846 | 85 | 0.690926 | false | false | false | false |
ddki/my_study_project
|
refs/heads/master
|
language/swift/SimpleTunnelCustomizedNetworkingUsingtheNetworkExtensionFramework/SimpleTunnel/StringListController.swift
|
mit
|
1
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file contains the StringListController class, which controls a list of strings.
*/
import UIKit
/// A view controller of a view that displays an editable list of strings.
class StringListController: ListViewController {
// MARK: Properties
/// The current list of strings.
var targetStrings = [String]()
/// The text to display in the "add a string" text field.
var addText: String?
/// The title to display for the list.
var listTitle: String?
/// The block to execute when the list of strings changes.
var stringsChangedHandler: ([String]) -> Void = { strings in return }
/// A table view cell containing a text field used to enter new strings to be added to the list.
@IBOutlet weak var addStringCell: TextFieldCell!
/// The number of strings in the list.
override var listCount: Int {
return targetStrings.count
}
/// Returns UITableViewCellSelectionStyle.None
override var listCellSelectionStyle: UITableViewCellSelectionStyle {
return .none
}
// MARK: UIViewController
/// Handle the event when the view is loaded into memory.
override func viewDidLoad() {
isAddEnabled = true
isAlwaysEditing = true
addStringCell.valueChanged = {
guard let enteredText = self.addStringCell.textField.text else { return }
self.targetStrings.append(enteredText)
self.listInsertItemAtIndex(self.targetStrings.count - 1)
self.addStringCell.textField.text = ""
self.stringsChangedHandler(self.targetStrings)
}
// Set addStringCell as a custom "add a new item" cell.
addCell = addStringCell
super.viewDidLoad()
}
/// Handle the event when the view is being displayed.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addStringCell.textField.placeholder = addText
navigationItem.title = listTitle
}
// MARK: ListViewController
/// Return the string at the given index.
override func listTextForItemAtIndex(_ index: Int) -> String {
return targetStrings[index]
}
/// Remove the string at the given index.
override func listRemoveItemAtIndex(_ index: Int) {
targetStrings.remove(at: index)
stringsChangedHandler(targetStrings)
}
// MARK: Interface
/// Set the list of strings, the title to display for the list, the text used to prompt the user for a new string, and a block to execute when the list of strings changes.
func setTargetStrings(_ strings: [String]?, title: String, addTitle: String, saveHandler: @escaping ([String]) -> Void) {
targetStrings = strings ?? [String]()
listTitle = title
addText = addTitle
stringsChangedHandler = saveHandler
}
}
|
b007f56f04e0be3aba324a92e299de60
| 28.478261 | 172 | 0.74115 | false | false | false | false |
mlilback/rc2SwiftClient
|
refs/heads/master
|
Networking/NetworkingError.swift
|
isc
|
1
|
//
// NetworkingError.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Rc2Common
import Foundation
import Model
public enum NetworkingError: LocalizedError, Rc2DomainError {
case unauthorized
case unsupportedFileType
case timeout
case connectionError(Error)
case canceled
case uploadFailed(Error)
case invalidHttpStatusCode(HTTPURLResponse)
case restError(DetailedError)
static func errorFor(response: HTTPURLResponse, data: Data) -> NetworkingError {
switch response.statusCode {
case 500:
guard let error = try? JSONDecoder().decode(DetailedError.self, from: data)
else { return .invalidHttpStatusCode(response) }
return .restError(error)
default:
return .invalidHttpStatusCode(response)
}
}
public var localizedDescription: String {
return errorDescription ?? "unknown netorking error"
}
public var errorDescription: String? {
switch self {
case .unauthorized:
return localizedNetworkString("unauthorized")
case .unsupportedFileType:
return localizedNetworkString("unsupportedFileType")
case .restError(let derror):
return derror.details
case .invalidHttpStatusCode(let rsp):
return localizedNetworkString("server returned \(rsp.statusCode)")
default:
return localizedNetworkString("unknown")
}
}
}
public struct WebSocketError: LocalizedError, Rc2DomainError, CustomDebugStringConvertible {
public enum ErrorType: Int {
case unknown = 0
case noSuchFile = 1001
case fileVersionMismatch = 1002
case databaseUpdateFailed = 1003
case computeEngineUnavailable = 1005
case invalidRequest = 1006
case computeError = 1007
}
let code: Int
let type: ErrorType
let message: String
init(code: Int, message: String) {
self.code = code
self.message = message
self.type = ErrorType(rawValue: code) ?? .unknown
}
public var errorDescription: String? { return message }
public var debugDescription: String { return "ws error: \(message) (\(code))" }
}
|
7a320d79a474870388fcaa2fb8888a93
| 25.447368 | 92 | 0.751244 | false | false | false | false |
RCacheaux/Bitbucket-iOS
|
refs/heads/master
|
Carthage/Checkouts/Swinject/Tests/SwinjectTests/Animal.swift
|
apache-2.0
|
4
|
//
// Animal.swift
// Swinject
//
// Created by Yoichi Tagaya on 7/27/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Foundation
internal protocol Animal {
var name: String? { get set }
}
internal class Cat: Animal {
var name: String?
var sleeping = false
var favoriteFood: Food?
init() {
}
init(name: String) {
self.name = name
}
init(name: String, sleeping: Bool) {
self.name = name
self.sleeping = sleeping
}
}
internal class Siamese: Cat {
}
internal class Dog: Animal {
var name: String?
init() {
}
init(name: String) {
self.name = name
}
}
internal struct Turtle: Animal {
var name: String?
}
|
51715daf7f48a2338f18237ef41c8f83
| 14.510204 | 64 | 0.577632 | false | false | false | false |
maletzt/Alien-Adventure
|
refs/heads/master
|
Alien Adventure/Settings.swift
|
mit
|
1
|
//
// Settings.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 9/18/15.
// Copyright © 2015 Udacity. All rights reserved.
//
import UIKit
// MARK: - Settings
struct Settings {
// MARK: Common
struct Common {
static let GameDataURL = NSBundle.mainBundle().URLForResource("GameData", withExtension: "plist")!
static let Font = "Superclarendon-Italic"
static let FontColor = UIColor.whiteColor()
static var Level = 2
static var ShowBadges = false
static let RequestsToSkip = 0
}
// MARK: Dialogue (Set by UDDataLoader)
struct Dialogue {
static var StartingDialogue = ""
static var RequestingDialogue = ""
static var TransitioningDialogue = ""
static var WinningDialogue = ""
static var LosingDialogue = ""
}
// MARK: Names
struct Names {
static let Hero = "Hero"
static let Background = "Background"
static let Treasure = "Treasure"
}
}
|
3489970d1145f32abb200c22b29cc1d5
| 23.232558 | 106 | 0.597889 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
refs/heads/trunk
|
WordPress/WordPressTest/NotificationTests.swift
|
gpl-2.0
|
1
|
import Foundation
import XCTest
@testable import WordPress
/// Notifications Tests
///
class NotificationTests: CoreDataTestCase {
private var utility: NotificationUtility!
override func setUp() {
utility = NotificationUtility(coreDataStack: contextManager)
}
override func tearDown() {
utility = nil
}
func testBadgeNotificationHasBadgeFlagSetToTrue() throws {
let note = try loadBadgeNotification()
XCTAssertTrue(note.isBadge)
}
func testBadgeNotificationHasRegularFieldsSet() throws {
let note = try loadBadgeNotification()
XCTAssertNotNil(note.type)
XCTAssertNotNil(note.noticon)
XCTAssertNotNil(note.iconURL)
XCTAssertNotNil(note.resourceURL)
XCTAssertNotNil(note.timestampAsDate)
}
func testBadgeNotificationProperlyLoadsItsSubjectContent() throws {
let note = try utility.loadBadgeNotification()
XCTAssert(note.subjectContentGroup?.blocks.count == 1)
XCTAssertNotNil(note.subjectContentGroup?.blocks.first)
XCTAssertNotNil(note.renderSubject())
}
func testBadgeNotificationContainsOneImageContentGroup() throws {
let note = try utility.loadBadgeNotification()
let group = note.contentGroup(ofKind: .image)
XCTAssertNotNil(group)
let imageBlock = group?.blocks.first as? FormattableMediaContent
XCTAssertNotNil(imageBlock)
let media = imageBlock?.media.first
XCTAssertNotNil(media)
XCTAssertNotNil(media?.mediaURL)
}
func testLikeNotificationReturnsTheProperKindValue() throws {
let note = try loadLikeNotification()
XCTAssert(note.kind == .like)
}
func testLikeNotificationContainsHeaderContent() throws {
let note = try loadLikeNotification()
let header = note.headerContentGroup
XCTAssertNotNil(header)
let gravatarBlock: NotificationTextContent? = header?.blockOfKind(.image)
XCTAssertNotNil(gravatarBlock?.text)
let media = gravatarBlock?.media.first
XCTAssertNotNil(media?.mediaURL)
let snippetBlock: NotificationTextContent? = header?.blockOfKind(.text)
XCTAssertNotNil(snippetBlock?.text)
}
func testLikeNotificationContainsUserContentGroupsInTheBody() throws {
let note = try utility.loadLikeNotification()
for group in note.bodyContentGroups {
XCTAssertTrue(group.kind == .user)
}
}
func testLikeNotificationContainsPostAndSiteID() throws {
let note = try loadLikeNotification()
XCTAssertNotNil(note.metaSiteID)
XCTAssertNotNil(note.metaPostID)
}
func testFollowerNotificationReturnsTheProperKindValue() throws {
let note = try loadFollowerNotification()
XCTAssert(note.kind == .follow)
}
func testFollowerNotificationHasFollowFlagSetToTrue() throws {
let note = try loadFollowerNotification()
XCTAssertTrue(note.kind == .follow)
}
func testFollowerNotificationContainsOneSubjectContent() throws {
let note = try loadFollowerNotification()
let content = note.subjectContentGroup?.blocks.first
XCTAssertNotNil(content)
XCTAssertNotNil(content?.text)
}
func testFollowerNotificationContainsSiteID() throws {
let note = try loadFollowerNotification()
XCTAssertNotNil(note.metaSiteID)
}
func testFollowerNotificationContainsUserAndFooterGroupsInTheBody() throws {
let note = try utility.loadFollowerNotification()
// Note: Account for 'View All Followers'
for group in note.bodyContentGroups {
XCTAssertTrue(group.kind == .user || group.kind == .footer)
}
}
func testFollowerNotificationContainsFooterContentWithFollowRangeAtTheEnd() throws {
let note = try loadFollowerNotification()
let lastGroup = note.bodyContentGroups.last
XCTAssertNotNil(lastGroup)
XCTAssertTrue(lastGroup!.kind == .footer)
let block = lastGroup?.blocks.first
XCTAssertNotNil(block)
XCTAssertNotNil(block?.text)
XCTAssertNotNil(block?.ranges)
let range = block?.ranges.last
XCTAssertNotNil(range)
XCTAssert(range?.kind == .follow)
}
func testCommentNotificationReturnsTheProperKindValue() throws {
let note = try loadCommentNotification()
XCTAssert(note.kind == .comment)
}
func testCommentNotificationHasCommentFlagSetToTrue() throws {
let note = try loadCommentNotification()
XCTAssertTrue(note.kind == .comment)
}
func testCommentNotificationRendersSubjectWithSnippet() throws {
let note = try loadCommentNotification()
XCTAssertNotNil(note.renderSubject())
XCTAssertNotNil(note.renderSnippet())
}
func testCommentNotificationContainsHeaderContent() throws {
let note = try loadCommentNotification()
let header = note.headerContentGroup
XCTAssertNotNil(header)
let gravatarBlock: NotificationTextContent? = header?.blockOfKind(.image)
XCTAssertNotNil(gravatarBlock)
XCTAssertNotNil(gravatarBlock?.text)
let media = gravatarBlock!.media.first
XCTAssertNotNil(media)
XCTAssertNotNil(media!.mediaURL)
let snippetBlock: NotificationTextContent? = header?.blockOfKind(.text)
XCTAssertNotNil(snippetBlock)
XCTAssertNotNil(snippetBlock?.text)
}
func testCommentNotificationContainsCommentAndSiteID() throws {
let note = try loadCommentNotification()
XCTAssertNotNil(note.metaSiteID)
XCTAssertNotNil(note.metaCommentID)
}
func testCommentNotificationProperlyChecksIfItWasRepliedTo() throws {
let note = try loadCommentNotification()
XCTAssert(note.isRepliedComment)
}
func testCommentNotificationIsUnapproved() throws {
let note = try utility.loadUnapprovedCommentNotification()
XCTAssertTrue(note.isUnapprovedComment)
}
func testCommentNotificationIsApproved() throws {
let note = try utility.loadCommentNotification()
XCTAssertFalse(note.isUnapprovedComment)
}
func testFooterContentIsIdentifiedAndCreated() throws {
let note = try loadCommentNotification()
let footerBlock: FooterTextContent? = note.contentGroup(ofKind: .footer)?.blockOfKind(.text)
XCTAssertNotNil(footerBlock)
}
func testFindingContentRangeSearchingByURL() throws {
let note = try loadBadgeNotification()
let targetURL = URL(string: "http://www.wordpress.com")!
let range = note.contentRange(with: targetURL)
XCTAssertNotNil(range)
}
func testPingbackNotificationIsPingback() throws {
let notification = try utility.loadPingbackNotification()
XCTAssertTrue(notification.isPingback)
}
func testPingbackBodyContainsFooter() throws {
let notification = try utility.loadPingbackNotification()
let footer = notification.bodyContentGroups.filter { $0.kind == .footer }
XCTAssertEqual(footer.count, 1)
}
func testHeaderAndBodyContentGroups() throws {
let note = try utility.loadCommentNotification()
let headerGroupsCount = note.headerContentGroup != nil ? 1 : 0
let bodyGroupsCount = note.bodyContentGroups.count
let totalGroupsCount = headerGroupsCount + bodyGroupsCount
XCTAssertEqual(note.headerAndBodyContentGroups.count, totalGroupsCount)
}
func testNotificationCacheIsInvalidated() throws {
let commentNotificationId = "44444"
let _ = try utility.loadCommentNotification()
contextManager.saveContextAndWait(mainContext)
let fetchRequest = NSFetchRequest<WordPress.Notification>(entityName: WordPress.Notification.entityName())
fetchRequest.predicate = NSPredicate(format: "notificationId == %@", commentNotificationId)
let note = try XCTUnwrap(mainContext.fetch(fetchRequest).first)
XCTAssertEqual(note.timestamp, "2015-03-10T18:57:37+00:00")
XCTAssertEqual(note.timestampAsDate.timeIntervalSince1970, 1426013857)
note.timestamp = "2015-03-10T18:57:38+00:00"
XCTAssertEqual(note.timestampAsDate.timeIntervalSince1970, 1426013858)
mainContext.reset()
contextManager.performAndSave { context in
let notification = (try? context.fetch(fetchRequest))?.first
XCTAssertNotNil(notification)
XCTAssertEqual(notification?.timestampAsDate.timeIntervalSince1970, 1426013857)
XCTExpectFailure("""
This assertion failure is problematic.
When timestamp (or any other cached attribute) is changed, the cache still should be invalidated
even though the notification is associated with a non-main context.
""")
note.timestamp = "2015-03-10T18:57:38+00:00"
XCTAssertEqual(notification?.timestampAsDate.timeIntervalSince1970, 1426013858)
}
}
// MARK: - Helpers
func loadBadgeNotification() throws -> WordPress.Notification {
return try utility.loadBadgeNotification()
}
func loadLikeNotification() throws -> WordPress.Notification {
return try utility.loadLikeNotification()
}
func loadFollowerNotification() throws -> WordPress.Notification {
return try utility.loadFollowerNotification()
}
func loadCommentNotification() throws -> WordPress.Notification {
return try utility.loadCommentNotification()
}
}
|
2f4a3fef7f946ada1ef911f81b7c5351
| 33.359431 | 114 | 0.69798 | false | true | false | false |
Connorrr/ParticleAlarm
|
refs/heads/master
|
IOS/Alarm/Splash/OvalLayer.swift
|
mit
|
1
|
//
// OvalLayer.swift
// SBLoader
//
// Created by Satraj Bambra on 2015-03-19.
// Copyright (c) 2015 Satraj Bambra. All rights reserved.
//
import UIKit
class OvalLayer: CAShapeLayer {
let animationDuration: CFTimeInterval = 0.4
override init() {
super.init()
fillColor = Colours.white.cgColor
path = ovalPathSmall.cgPath
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var ovalPathSmall: UIBezierPath {
return UIBezierPath(ovalIn: CGRect(x: frame.width/2, y: frame.height/2, width: 0.0, height: 0.0))
}
var ovalPathLarge: UIBezierPath {
return UIBezierPath(ovalIn: CGRect(x: frame.width/4, y: (frame.height/2)-frame.width/4, width: frame.width/2, height: frame.width/2))
}
var ovalPathSquishVertical: UIBezierPath {
return UIBezierPath(ovalIn: CGRect(x: 2.5, y: 20.0, width: 95.0, height: 90.0))
}
var ovalPathSquishHorizontal: UIBezierPath {
return UIBezierPath(ovalIn: CGRect(x: 5.0, y: 20.0, width: 90.0, height: 90.0))
}
func expand() {
let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
expandAnimation.fromValue = ovalPathSmall.cgPath
expandAnimation.toValue = ovalPathLarge.cgPath
expandAnimation.duration = animationDuration
expandAnimation.fillMode = kCAFillModeForwards
expandAnimation.isRemovedOnCompletion = false;
add(expandAnimation, forKey: nil)
}
func wobble() {
// 1
let wobbleAnimation1: CABasicAnimation = CABasicAnimation(keyPath: "path")
wobbleAnimation1.fromValue = ovalPathLarge.cgPath
wobbleAnimation1.toValue = ovalPathSquishVertical.cgPath
wobbleAnimation1.beginTime = 0.0
wobbleAnimation1.duration = animationDuration
// 2
let wobbleAnimation2: CABasicAnimation = CABasicAnimation(keyPath: "path")
wobbleAnimation2.fromValue = ovalPathSquishVertical.cgPath
wobbleAnimation2.toValue = ovalPathSquishHorizontal.cgPath
wobbleAnimation2.beginTime = wobbleAnimation1.beginTime + wobbleAnimation1.duration
wobbleAnimation2.duration = animationDuration
// 3
let wobbleAnimation3: CABasicAnimation = CABasicAnimation(keyPath: "path")
wobbleAnimation3.fromValue = ovalPathSquishHorizontal.cgPath
wobbleAnimation3.toValue = ovalPathSquishVertical.cgPath
wobbleAnimation3.beginTime = wobbleAnimation2.beginTime + wobbleAnimation2.duration
wobbleAnimation3.duration = animationDuration
// 4
let wobbleAnimation4: CABasicAnimation = CABasicAnimation(keyPath: "path")
wobbleAnimation4.fromValue = ovalPathSquishVertical.cgPath
wobbleAnimation4.toValue = ovalPathLarge.cgPath
wobbleAnimation4.beginTime = wobbleAnimation3.beginTime + wobbleAnimation3.duration
wobbleAnimation4.duration = animationDuration
// 5
let wobbleGroupAnimation: CAAnimationGroup = CAAnimationGroup()
wobbleGroupAnimation.animations = [wobbleAnimation1,wobbleAnimation2,wobbleAnimation3,wobbleAnimation4]
wobbleGroupAnimation.duration = wobbleAnimation4.beginTime + wobbleAnimation4.duration
wobbleGroupAnimation.repeatCount = 2
add(wobbleGroupAnimation, forKey: nil)
}
func contract() {
let contractAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
contractAnimation.fromValue = ovalPathLarge.cgPath
contractAnimation.toValue = ovalPathSmall.cgPath
contractAnimation.duration = animationDuration
contractAnimation.fillMode = kCAFillModeForwards
contractAnimation.isRemovedOnCompletion = false
add(contractAnimation, forKey: nil)
}
}
|
b5d98996bc881b76e0482697fc24d799
| 39.134021 | 141 | 0.697662 | false | false | false | false |
TrustWallet/trust-wallet-ios
|
refs/heads/master
|
Trust/Wallet/ViewControllers/VerifyPassphraseViewController.swift
|
gpl-3.0
|
1
|
// Copyright DApps Platform Inc. All rights reserved.
import Foundation
import UIKit
import TrustKeystore
protocol VerifyPassphraseViewControllerDelegate: class {
func didFinish(in controller: VerifyPassphraseViewController, with account: Wallet)
func didSkip(in controller: VerifyPassphraseViewController, with account: Wallet)
}
enum VerifyStatus {
case empty
case progress
case invalid
case correct
var text: String {
switch self {
case .empty, .progress: return ""
case .invalid: return NSLocalizedString("verify.passphrase.invalidOrder.title", value: "Invalid order. Try again!", comment: "")
case .correct:
return String(format: NSLocalizedString("verify.passphrase.welldone.title", value: "Well done! %@", comment: ""), "✅")
}
}
var textColor: UIColor {
switch self {
case .empty, .progress, .correct: return Colors.black
case .invalid: return Colors.red
}
}
static func from(initialWords: [String], progressWords: [String]) -> VerifyStatus {
guard !progressWords.isEmpty else { return .empty }
if initialWords == progressWords && initialWords.count == progressWords.count {
return .correct
}
if progressWords == Array(initialWords.prefix(progressWords.count)) {
return .progress
}
return .invalid
}
}
class DarkVerifyPassphraseViewController: VerifyPassphraseViewController {
}
class SubtitleBackupLabel: UILabel {
init() {
super.init(frame: .zero)
translatesAutoresizingMaskIntoConstraints = false
textAlignment = .center
numberOfLines = 0
font = AppStyle.paragraph.font
textColor = Colors.gray
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class VerifyPassphraseViewController: UIViewController {
let contentView = PassphraseView()
let proposalView = PassphraseView()
let account: Wallet
let words: [String]
let shuffledWords: [String]
weak var delegate: VerifyPassphraseViewControllerDelegate?
lazy var doneButton: UIButton = {
let button = Button(size: .large, style: .solid)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(R.string.localizable.done(), for: .normal)
button.addTarget(self, action: #selector(doneAction(_:)), for: .touchUpInside)
return button
}()
lazy var subTitleLabel: SubtitleBackupLabel = {
let label = SubtitleBackupLabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = NSLocalizedString("verifyPassphrase.label.title", value: "Tap the words to put them next to each other in the correct order.", comment: "")
return label
}()
lazy var statusLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
return label
}()
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.text = R.string.localizable.verifyBackupPhrase()
titleLabel.font = UIFont.systemFont(ofSize: 18, weight: .regular)
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.textAlignment = .center
return titleLabel
}()
private struct Layout {
static let contentSize: CGFloat = 140
}
init(
account: Wallet,
words: [String]
) {
self.account = account
self.words = words
self.shuffledWords = words.shuffled()
super.init(nibName: nil, bundle: nil)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: R.string.localizable.skip(), style: .plain, target: self, action: #selector(skipAction))
view.backgroundColor = .white
contentView.isEditable = true
contentView.words = []
contentView.didDeleteItem = { item in
self.proposalView.words.append(item)
self.refresh()
}
contentView.backgroundColor = .clear
contentView.collectionView.backgroundColor = .clear
proposalView.isEditable = true
proposalView.words = shuffledWords
proposalView.didDeleteItem = { item in
self.contentView.words.append(item)
self.refresh()
}
let image = UIImageView()
image.translatesAutoresizingMaskIntoConstraints = false
image.contentMode = .scaleAspectFit
image.image = R.image.verify_passphrase()
let stackView = UIStackView(arrangedSubviews: [
image,
titleLabel,
.spacer(),
subTitleLabel,
.spacer(),
contentView,
proposalView,
statusLabel,
])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 12
stackView.backgroundColor = .clear
let wordBackgroundView = PassphraseBackgroundShadow()
wordBackgroundView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(wordBackgroundView)
view.addSubview(stackView)
view.addSubview(doneButton)
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(greaterThanOrEqualTo: view.readableContentGuide.topAnchor, constant: StyleLayout.sideMargin),
stackView.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor),
stackView.centerYAnchor.constraint(greaterThanOrEqualTo: view.readableContentGuide.centerYAnchor, constant: -80),
wordBackgroundView.topAnchor.constraint(equalTo: contentView.topAnchor),
wordBackgroundView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
wordBackgroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
wordBackgroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
contentView.heightAnchor.constraint(greaterThanOrEqualToConstant: 48),
proposalView.heightAnchor.constraint(greaterThanOrEqualToConstant: 48),
image.heightAnchor.constraint(equalToConstant: 32),
statusLabel.heightAnchor.constraint(equalToConstant: 34),
doneButton.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor),
doneButton.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor),
doneButton.bottomAnchor.constraint(equalTo: view.readableContentGuide.bottomAnchor, constant: -StyleLayout.sideMargin),
])
refresh()
}
@objc func skipAction() {
// TODO: Add confirm warning
delegate?.didSkip(in: self, with: account)
}
func refresh() {
let progressWords = contentView.words
let status = VerifyStatus.from(initialWords: words, progressWords: progressWords)
doneButton.isEnabled = status == .correct
statusLabel.text = status.text
statusLabel.textColor = status.textColor
}
@objc private func doneAction(_ sender: UIButton) {
delegate?.didFinish(in: self, with: account)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension MutableCollection {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
// Change `Int` in the next line to `IndexDistance` in < Swift 4.1
let d: Int = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
let i = index(firstUnshuffled, offsetBy: d)
swapAt(firstUnshuffled, i)
}
}
}
extension Sequence {
/// Returns an array with the contents of this sequence, shuffled.
func shuffled() -> [Element] {
var result = Array(self)
result.shuffle()
return result
}
}
|
0fc7730739d74a431b4ddada9539f147
| 33.564315 | 160 | 0.666867 | false | false | false | false |
ktustanowski/DurationReporter
|
refs/heads/master
|
Playground.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import Foundation
import DurationReporter
DurationReporter.begin(event: "Application Start", action: "Loading", payload: "🚀")
sleep(1)
DurationReporter.end(event: "Application Start", action: "Loading", payload: "💥")
DurationReporter.begin(event: "Application Start", action: "Loading Home")
sleep(2)
DurationReporter.end(event: "Application Start", action: "Loading Home")
DurationReporter.begin(event: "Application Start", action: "Preparing Home")
usleep(200000)
DurationReporter.end(event: "Application Start", action: "Preparing Home")
DurationReporter.begin(event: "Problematic Code", action: "Executing 💥")
/* no end event for Problematic Code on purpose */
// Print regular / default report
print(":: Default report")
print(DurationReporter.generateReport())
print("\n:: Custom report")
// Print regular / default report
DurationReporter.reportGenerator = { collectedData in
var output = ""
collectedData.forEach { eventName, reports in
reports.enumerated().forEach { index, report in
if let reportDuration = report.duration {
output += "\(eventName) → \(index). \(report.title) \(reportDuration)s\n"
} else {
output += "\(eventName) → \(index). 🔴 \(report.title) - ?\n"
}
}
}
return output
}
print(DurationReporter.generateReport())
print(":: Report from raw collected data")
// Print regular / default report
let collectedData = DurationReporter.reportData()
collectedData.forEach { eventName, reports in
reports.enumerated().forEach { index, report in
if let reportDuration = report.duration {
print("\(eventName) → \(index). \(report.title) \(reportDuration)s \((report.beginPayload as? String) ?? "") \((report.endPayload as? String) ?? "")")
} else {
print("\(eventName) → \(index). 🔴 \(report.title) - ?\n")
}
}
}
|
2a83777102b44032dce3e9e3ace7d9e0
| 34.563636 | 162 | 0.665133 | false | false | false | false |
eggheadgames/apple-receipt
|
refs/heads/develop
|
ReceiptKit/Classes/Receipt.swift
|
mit
|
1
|
// Copyright © 2016 Egghead Games LLC. All rights reserved.
import Foundation
// MARK: Main
public struct Receipt {
fileprivate let dictionaryRepresentation: NSDictionary
init?(JSONObject: AnyObject) {
guard let dictionaryRepresentation = JSONObject as? NSDictionary else { return nil }
self.dictionaryRepresentation = dictionaryRepresentation
if status != 0 { return nil }
}
}
// MARK: Get status
public extension Receipt {
var status: Int? {
let key = Receipt.statusKey
return dictionaryRepresentation[key] as? Int
}
fileprivate static let statusKey = "status"
}
// MARK: Parse environment
public extension Receipt {
var environment: String? {
let key = Receipt.environmentKey
return dictionaryRepresentation[key] as? String
}
fileprivate static let environmentKey = "environment"
}
// MARK: Parse purchase date
public extension Receipt {
var purchaseAt: Date? {
let keys = Receipt.purchaseDateKeys
guard let rawReceipt = dictionaryRepresentation[keys.0] as? NSDictionary else { return nil }
guard let rawDate = rawReceipt[keys.1] as? String else { return nil }
return ReceiptDateFormatter.date(from: rawDate)
}
fileprivate static let purchaseDateKeys = ("receipt", "original_purchase_date")
}
|
c3ca911c36daf45b2b89579f003be595
| 22.344828 | 100 | 0.691285 | false | false | false | false |
Yummypets/YPImagePicker
|
refs/heads/master
|
Source/Helpers/Extensions/UIImage+Extensions.swift
|
mit
|
1
|
//
// UIImage+ResetOrientation.swift
// YPImagePicker
//
// Created by Sacha DSO on 20/02/2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
internal extension UIImage {
func resized(to size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
// Kudos to Trevor Harmon and his UIImage+Resize category from
// which this code is heavily inspired.
func resetOrientation() -> UIImage {
// Image has no orientation, so keep the same
if imageOrientation == .up {
return self
}
// Process the transform corresponding to the current orientation
var transform = CGAffineTransform.identity
switch imageOrientation {
case .down, .downMirrored: // EXIF = 3, 4
transform = transform.translatedBy(x: size.width, y: size.height)
transform = transform.rotated(by: CGFloat(Double.pi))
case .left, .leftMirrored: // EXIF = 6, 5
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.rotated(by: CGFloat(Double.pi / 2))
case .right, .rightMirrored: // EXIF = 8, 7
transform = transform.translatedBy(x: 0, y: size.height)
transform = transform.rotated(by: -CGFloat((Double.pi / 2)))
default:
()
}
switch imageOrientation {
case .upMirrored, .downMirrored: // EXIF = 2, 4
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored: // EXIF = 5, 7
transform = transform.translatedBy(x: size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
default:
()
}
// Draw a new image with the calculated transform
let context = CGContext(data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: cgImage!.bitsPerComponent,
bytesPerRow: 0,
space: cgImage!.colorSpace!,
bitmapInfo: cgImage!.bitmapInfo.rawValue)
context?.concatenate(transform)
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
context?.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
default:
context?.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
if let newImageRef = context?.makeImage() {
let newImage = UIImage(cgImage: newImageRef)
return newImage
}
// In case things go wrong, still return self.
return self
}
// Reduce image size further if needed targetImageSize is capped.
func resizedImageIfNeeded() -> UIImage {
if case let YPImageSize.cappedTo(size: capped) = YPConfig.targetImageSize {
let size = cappedSize(for: self.size, cappedAt: capped)
if let resizedImage = self.resized(to: size) {
return resizedImage
}
}
return self
}
fileprivate func cappedSize(for size: CGSize, cappedAt: CGFloat) -> CGSize {
var cappedWidth: CGFloat = 0
var cappedHeight: CGFloat = 0
if size.width > size.height {
// Landscape
let heightRatio = size.height / size.width
cappedWidth = min(size.width, cappedAt)
cappedHeight = cappedWidth * heightRatio
} else if size.height > size.width {
// Portrait
let widthRatio = size.width / size.height
cappedHeight = min(size.height, cappedAt)
cappedWidth = cappedHeight * widthRatio
} else {
// Squared
cappedWidth = min(size.width, cappedAt)
cappedHeight = min(size.height, cappedAt)
}
return CGSize(width: cappedWidth, height: cappedHeight)
}
func toCIImage() -> CIImage? {
return self.ciImage ?? CIImage(cgImage: self.cgImage!)
}
}
|
d1616c17040175fe2ab4dcb954d6b911
| 37.398305 | 99 | 0.563231 | false | false | false | false |
Zewo/TodoBackend
|
refs/heads/master
|
Sources/TodoBackend/Models/Todo.swift
|
mit
|
1
|
import Axis
import SQL
struct Todo {
let title: String
let completed: Bool
let order: Int
}
extension Todo : ModelProtocol {
typealias PrimaryKey = Int
enum Field: String, ModelField {
static let tableName = "todo"
static let primaryKey = Field.id
case id
case title
case completed
// "order" is reserved in psql
case order = "order_"
}
func serialize() -> [Field: ValueConvertible?] {
return [
.title: title,
.completed: completed ? 1 : 0,
.order: order
]
}
init<Row: RowProtocol>(row: TableRow<Todo, Row>) throws {
try self.init(
title: row.value(.title),
completed: row.value(.completed) == 1,
order: row.value(.order)
)
}
}
extension Todo {
static func createTable<Connection : ConnectionProtocol>(connection: Connection) throws {
//TODO: make a nice dsl for this in sql
let query = "CREATE TABLE IF NOT EXISTS todo (" +
"id serial PRIMARY KEY NOT NULL," +
"title text NOT NULL," +
"completed integer NOT NULL DEFAULT 0," +
"order_ integer NOT NULL" +
");"
try connection.execute(query)
}
}
extension Todo {
func update(title: String? = nil, completed: Bool? = nil, order: Int? = nil) -> Todo {
return Todo.init(
title: title ?? self.title,
completed: completed ?? self.completed,
order: order ?? self.order
)
}
func update(map: Map) -> Todo {
return self.update(
title: map["title"].string,
completed: map["completed"].bool,
order: map["order"].int
)
}
}
extension Todo : MapConvertible {
init(map: Map) throws {
try self.init(
title: map.get("title"),
completed: map["completed"].bool ?? false,
order: map["order"].int ?? 0
)
}
}
|
f455599b0bf66f4f3dca2308a38a81ed
| 24.617284 | 93 | 0.520482 | false | false | false | false |
alessiobrozzi/firefox-ios
|
refs/heads/development
|
Account/FxAState.swift
|
mpl-2.0
|
5
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import FxA
import Shared
import SwiftyJSON
// The version of the state schema we persist.
let StateSchemaVersion = 1
// We want an enum because the set of states is closed. However, each state has state-specific
// behaviour, and the state's behaviour accumulates, so each state is a class. Switch on the
// label to get exhaustive cases.
public enum FxAStateLabel: String {
case engagedBeforeVerified = "engagedBeforeVerified"
case engagedAfterVerified = "engagedAfterVerified"
case cohabitingBeforeKeyPair = "cohabitingBeforeKeyPair"
case cohabitingAfterKeyPair = "cohabitingAfterKeyPair"
case married = "married"
case separated = "separated"
case doghouse = "doghouse"
// See http://stackoverflow.com/a/24137319
static let allValues: [FxAStateLabel] = [
engagedBeforeVerified,
engagedAfterVerified,
cohabitingBeforeKeyPair,
cohabitingAfterKeyPair,
married,
separated,
doghouse,
]
}
public enum FxAActionNeeded {
case none
case needsVerification
case needsPassword
case needsUpgrade
}
func state(fromJSON json: JSON) -> FxAState? {
if json.error != nil {
return nil
}
if let version = json["version"].int {
if version == StateSchemaVersion {
return stateV1(fromJSON:json)
}
}
return nil
}
func stateV1(fromJSON json: JSON) -> FxAState? {
if let labelString = json["label"].string {
if let label = FxAStateLabel(rawValue: labelString) {
switch label {
case .engagedBeforeVerified:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let keyFetchToken = json["keyFetchToken"].string?.hexDecodedData,
let unwrapkB = json["unwrapkB"].string?.hexDecodedData,
let knownUnverifiedAt = json["knownUnverifiedAt"].int64,
let lastNotifiedUserAt = json["lastNotifiedUserAt"].int64 {
return EngagedBeforeVerifiedState(
knownUnverifiedAt: UInt64(knownUnverifiedAt), lastNotifiedUserAt: UInt64(lastNotifiedUserAt),
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
case .engagedAfterVerified:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let keyFetchToken = json["keyFetchToken"].string?.hexDecodedData,
let unwrapkB = json["unwrapkB"].string?.hexDecodedData {
return EngagedAfterVerifiedState(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
case .cohabitingBeforeKeyPair:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kA = json["kA"].string?.hexDecodedData,
let kB = json["kB"].string?.hexDecodedData {
return CohabitingBeforeKeyPairState(sessionToken: sessionToken, kA: kA, kB: kB)
}
case .cohabitingAfterKeyPair:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kA = json["kA"].string?.hexDecodedData,
let kB = json["kB"].string?.hexDecodedData,
let keyPairJSON = json["keyPair"].dictionaryObject as? [String: AnyObject],
let keyPair = RSAKeyPair(jsonRepresentation: keyPairJSON),
let keyPairExpiresAt = json["keyPairExpiresAt"].int64 {
return CohabitingAfterKeyPairState(sessionToken: sessionToken, kA: kA, kB: kB,
keyPair: keyPair, keyPairExpiresAt: UInt64(keyPairExpiresAt))
}
case .married:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kA = json["kA"].string?.hexDecodedData,
let kB = json["kB"].string?.hexDecodedData,
let keyPairJSON = json["keyPair"].dictionaryObject as? [String: AnyObject],
let keyPair = RSAKeyPair(jsonRepresentation: keyPairJSON),
let keyPairExpiresAt = json["keyPairExpiresAt"].int64,
let certificate = json["certificate"].string,
let certificateExpiresAt = json["certificateExpiresAt"].int64 {
return MarriedState(sessionToken: sessionToken, kA: kA, kB: kB,
keyPair: keyPair, keyPairExpiresAt: UInt64(keyPairExpiresAt),
certificate: certificate, certificateExpiresAt: UInt64(certificateExpiresAt))
}
case .separated:
return SeparatedState()
case .doghouse:
return DoghouseState()
}
}
}
return nil
}
// Not an externally facing state!
open class FxAState: JSONLiteralConvertible {
open var label: FxAStateLabel { return FxAStateLabel.separated } // This is bogus, but we have to do something!
open var actionNeeded: FxAActionNeeded {
// Kind of nice to have this in one place.
switch label {
case .engagedBeforeVerified: return .needsVerification
case .engagedAfterVerified: return .none
case .cohabitingBeforeKeyPair: return .none
case .cohabitingAfterKeyPair: return .none
case .married: return .none
case .separated: return .needsPassword
case .doghouse: return .needsUpgrade
}
}
open func asJSON() -> JSON {
return JSON([
"version": StateSchemaVersion,
"label": self.label.rawValue,
] as NSDictionary)
}
}
open class SeparatedState: FxAState {
override open var label: FxAStateLabel { return FxAStateLabel.separated }
override public init() {
super.init()
}
}
// Not an externally facing state!
open class TokenState: FxAState {
let sessionToken: Data
init(sessionToken: Data) {
self.sessionToken = sessionToken
super.init()
}
open override func asJSON() -> JSON {
var d: [String: JSON] = super.asJSON().dictionary!
d["sessionToken"] = JSON(sessionToken.hexEncodedString as NSString)
return JSON(d as NSDictionary)
}
}
// Not an externally facing state!
open class ReadyForKeys: TokenState {
let keyFetchToken: Data
let unwrapkB: Data
init(sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
self.keyFetchToken = keyFetchToken
self.unwrapkB = unwrapkB
super.init(sessionToken: sessionToken)
}
open override func asJSON() -> JSON {
var d: [String: JSON] = super.asJSON().dictionary!
d["keyFetchToken"] = JSON(keyFetchToken.hexEncodedString as NSString)
d["unwrapkB"] = JSON(unwrapkB.hexEncodedString as NSString)
return JSON(d as NSDictionary)
}
}
open class EngagedBeforeVerifiedState: ReadyForKeys {
override open var label: FxAStateLabel { return FxAStateLabel.engagedBeforeVerified }
// Timestamp, in milliseconds after the epoch, when we first knew the account was unverified.
// Use this to avoid nagging the user to verify her account immediately after connecting.
let knownUnverifiedAt: Timestamp
let lastNotifiedUserAt: Timestamp
public init(knownUnverifiedAt: Timestamp, lastNotifiedUserAt: Timestamp, sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
self.knownUnverifiedAt = knownUnverifiedAt
self.lastNotifiedUserAt = lastNotifiedUserAt
super.init(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["knownUnverifiedAt"] = JSON(NSNumber(value: knownUnverifiedAt))
d["lastNotifiedUserAt"] = JSON(NSNumber(value: lastNotifiedUserAt))
return JSON(d as NSDictionary)
}
func withUnwrapKey(_ unwrapkB: Data) -> EngagedBeforeVerifiedState {
return EngagedBeforeVerifiedState(
knownUnverifiedAt: knownUnverifiedAt, lastNotifiedUserAt: lastNotifiedUserAt,
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
}
open class EngagedAfterVerifiedState: ReadyForKeys {
override open var label: FxAStateLabel { return FxAStateLabel.engagedAfterVerified }
override public init(sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
super.init(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
func withUnwrapKey(_ unwrapkB: Data) -> EngagedAfterVerifiedState {
return EngagedAfterVerifiedState(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
}
// Not an externally facing state!
open class TokenAndKeys: TokenState {
open let kA: Data
open let kB: Data
init(sessionToken: Data, kA: Data, kB: Data) {
self.kA = kA
self.kB = kB
super.init(sessionToken: sessionToken)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["kA"] = JSON(kA.hexEncodedString as NSString)
d["kB"] = JSON(kB.hexEncodedString as NSString)
return JSON(d as NSDictionary)
}
}
open class CohabitingBeforeKeyPairState: TokenAndKeys {
override open var label: FxAStateLabel { return FxAStateLabel.cohabitingBeforeKeyPair }
}
// Not an externally facing state!
open class TokenKeysAndKeyPair: TokenAndKeys {
let keyPair: KeyPair
// Timestamp, in milliseconds after the epoch, when keyPair expires. After this time, generate a new keyPair.
let keyPairExpiresAt: Timestamp
init(sessionToken: Data, kA: Data, kB: Data, keyPair: KeyPair, keyPairExpiresAt: Timestamp) {
self.keyPair = keyPair
self.keyPairExpiresAt = keyPairExpiresAt
super.init(sessionToken: sessionToken, kA: kA, kB: kB)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["keyPair"] = JSON(keyPair.jsonRepresentation() as NSDictionary)
d["keyPairExpiresAt"] = JSON(NSNumber(value: keyPairExpiresAt))
return JSON(d as NSDictionary)
}
func isKeyPairExpired(_ now: Timestamp) -> Bool {
return keyPairExpiresAt < now
}
}
open class CohabitingAfterKeyPairState: TokenKeysAndKeyPair {
override open var label: FxAStateLabel { return FxAStateLabel.cohabitingAfterKeyPair }
}
open class MarriedState: TokenKeysAndKeyPair {
override open var label: FxAStateLabel { return FxAStateLabel.married }
let certificate: String
let certificateExpiresAt: Timestamp
init(sessionToken: Data, kA: Data, kB: Data, keyPair: KeyPair, keyPairExpiresAt: Timestamp, certificate: String, certificateExpiresAt: Timestamp) {
self.certificate = certificate
self.certificateExpiresAt = certificateExpiresAt
super.init(sessionToken: sessionToken, kA: kA, kB: kB, keyPair: keyPair, keyPairExpiresAt: keyPairExpiresAt)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["certificate"] = JSON(certificate as NSString)
d["certificateExpiresAt"] = JSON(NSNumber(value: certificateExpiresAt))
return JSON(d as NSDictionary)
}
func isCertificateExpired(_ now: Timestamp) -> Bool {
return certificateExpiresAt < now
}
func withoutKeyPair() -> CohabitingBeforeKeyPairState {
let newState = CohabitingBeforeKeyPairState(sessionToken: sessionToken,
kA: kA, kB: kB)
return newState
}
func withoutCertificate() -> CohabitingAfterKeyPairState {
let newState = CohabitingAfterKeyPairState(sessionToken: sessionToken,
kA: kA, kB: kB,
keyPair: keyPair, keyPairExpiresAt: keyPairExpiresAt)
return newState
}
open func generateAssertionForAudience(_ audience: String, now: Timestamp) -> String {
let assertion = JSONWebTokenUtils.createAssertionWithPrivateKeyToSign(with: keyPair.privateKey,
certificate: certificate,
audience: audience,
issuer: "127.0.0.1",
issuedAt: now,
duration: OneHourInMilliseconds)
return assertion!
}
}
open class DoghouseState: FxAState {
override open var label: FxAStateLabel { return FxAStateLabel.doghouse }
override public init() {
super.init()
}
}
|
ef2b8ab55c0e93841c4a6a5359d911a8
| 37.118343 | 151 | 0.654533 | false | false | false | false |
rporzuc/FindFriends
|
refs/heads/master
|
FindFriends/FindFriends/Begin Views/SignInViewController.swift
|
gpl-3.0
|
1
|
import UIKit
class SignInViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var viewWithFields: UIView!
@IBOutlet var textFieldLogin: UITextField!
@IBOutlet var textFieldPassword: UITextField!
@IBOutlet var btnSignIn: UIButton!
@IBOutlet var activityIndicator: UIActivityIndicatorView!
weak var findFriendsDelegate : FindFriendsViewController?
@IBAction func btnSignInClicked(_ sender: UIButton)
{
if ( textFieldLogin.text == "" || textFieldPassword.text == "")
{
let alertView = UIAlertController(title: "Alert", message: "Please enter a valid login and password.", preferredStyle: UIAlertControllerStyle.alert)
alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alertView, animated: true, completion: nil)
}else
{
self.view.endEditing(true)
self.view.isUserInteractionEnabled = false
self.btnSignIn.isEnabled = false
self.btnSignIn.backgroundColor = UIColor(red: 140/255, green: 175/255, blue: 80/255, alpha: 1)
self.activityIndicator.isHidden = false
self.activityIndicator.startAnimating()
let connectionToServer = ConnectionToServer.shared
connectionToServer.signIn(u_login: textFieldLogin.text!, u_password: textFieldPassword.text!, completion:
{
boolValue, message in
print("\(boolValue), \(message)")
self.btnSignIn.isEnabled = true
self.btnSignIn.backgroundColor = UIColor(red: 140/255, green: 175/255, blue: 30/255, alpha: 1)
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()
self.view.isUserInteractionEnabled = true
if boolValue
{
self.findFriendsDelegate?.restoreNormalBackground()
self.dismiss(animated: true, completion: {
controlNavigationController?.loadMainNavigationController()
})
}else
{
let alertView = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.alert)
alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alertView, animated: true, completion: nil)
}
})
}
}
@IBAction func btnForgotPasswordClicked(_ sender: UIButton)
{
self.dismiss(animated: true, completion: {
let forgotPasswordViewController = self.storyboard?.instantiateViewController(withIdentifier: "forgotPasswordViewController") as! ForgotPasswordViewController
forgotPasswordViewController.modalPresentationStyle = .overCurrentContext
findFriendsViewController.present(forgotPasswordViewController, animated: true, completion: nil)
})
}
func closeSignInViewController()
{
findFriendsViewController.restoreNormalBackground()
self.view.endEditing(true)
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()
self.view.backgroundColor = UIColor.clear
self.view.isUserInteractionEnabled = true
for txtField in [textFieldLogin, textFieldPassword]
{
txtField?.layer.borderColor = UIColor.lightGray.cgColor
txtField?.layer.borderWidth = 1
txtField?.layer.cornerRadius = 2
txtField?.delegate = self
}
btnSignIn.layer.cornerRadius = 4
viewWithFields.layer.cornerRadius = 5
NotificationCenter.default.addObserver(self, selector: #selector(SignInViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SignInViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let tagTouch = touches.first?.view?.tag
if tagTouch == 99
{
closeSignInViewController()
}
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
}
|
f39069ad2ac158f057870b748518c718
| 35.675159 | 171 | 0.587878 | false | false | false | false |
BigxMac/firefox-ios
|
refs/heads/master
|
Mates/Utilities/JSON.swift
|
gpl-2.0
|
25
|
//
// json.swift
// json
//
// Created by Dan Kogai on 7/15/14.
// Copyright (c) 2014 Dan Kogai. All rights reserved.
//
import Foundation
/// init
public class JSON {
private let _value:AnyObject
/// unwraps the JSON object
public class func unwrap(obj:AnyObject) -> AnyObject {
switch obj {
case let json as JSON:
return json._value
case let ary as NSArray:
var ret = [AnyObject]()
for v in ary {
ret.append(unwrap(v))
}
return ret
case let dict as NSDictionary:
var ret = [String:AnyObject]()
for (ko, v) in dict {
if let k = ko as? String {
ret[k] = unwrap(v)
}
}
return ret
default:
return obj
}
}
/// pass the object that was returned from
/// NSJSONSerialization
public init(_ obj:AnyObject) { self._value = JSON.unwrap(obj) }
/// pass the JSON object for another instance
public init(_ json:JSON){ self._value = json._value }
}
/// class properties
extension JSON {
public typealias NSNull = Foundation.NSNull
public typealias NSError = Foundation.NSError
public class var null:NSNull { return NSNull() }
/// constructs JSON object from data
public convenience init(data:NSData) {
var err:NSError?
var obj:AnyObject? = NSJSONSerialization.JSONObjectWithData(
data, options:nil, error:&err
)
self.init(err != nil ? err! : obj!)
}
/// constructs JSON object from string
public convenience init(string:String) {
let enc:NSStringEncoding = NSUTF8StringEncoding
self.init(data: string.dataUsingEncoding(enc)!)
}
/// parses string to the JSON object
/// same as JSON(string:String)
public class func parse(string:String)->JSON {
return JSON(string:string)
}
/// constructs JSON object from the content of NSURL
public convenience init(nsurl:NSURL) {
var enc:NSStringEncoding = NSUTF8StringEncoding
var err:NSError?
let str =
String(NSString(
contentsOfURL:nsurl, usedEncoding:&enc, error:&err
)!)
if err != nil { self.init(err!) }
else { self.init(string:str) }
}
/// fetch the JSON string from NSURL and parse it
/// same as JSON(nsurl:NSURL)
public class func fromNSURL(nsurl:NSURL) -> JSON {
return JSON(nsurl:nsurl)
}
/// constructs JSON object from the content of URL
public convenience init(url:String) {
if let nsurl = NSURL(string:url) as NSURL? {
self.init(nsurl:nsurl)
} else {
self.init(NSError(
domain:"JSONErrorDomain",
code:400,
userInfo:[NSLocalizedDescriptionKey: "malformed URL"]
)
)
}
}
/// fetch the JSON string from URL in the string
public class func fromURL(url:String) -> JSON {
return JSON(url:url)
}
/// does what JSON.stringify in ES5 does.
/// when the 2nd argument is set to true it pretty prints
public class func stringify(obj:AnyObject, pretty:Bool=false) -> String! {
if !NSJSONSerialization.isValidJSONObject(obj) {
JSON(NSError(
domain:"JSONErrorDomain",
code:422,
userInfo:[NSLocalizedDescriptionKey: "not an JSON object"]
))
return nil
}
return JSON(obj).toString(pretty:pretty)
}
}
/// instance properties
extension JSON {
/// access the element like array
public subscript(idx:Int) -> JSON {
switch _value {
case let err as NSError:
return self
case let ary as NSArray:
if 0 <= idx && idx < ary.count {
return JSON(ary[idx])
}
return JSON(NSError(
domain:"JSONErrorDomain", code:404, userInfo:[
NSLocalizedDescriptionKey:
"[\(idx)] is out of range"
]))
default:
return JSON(NSError(
domain:"JSONErrorDomain", code:500, userInfo:[
NSLocalizedDescriptionKey: "not an array"
]))
}
}
/// access the element like dictionary
public subscript(key:String)->JSON {
switch _value {
case let err as NSError:
return self
case let dic as NSDictionary:
if let val:AnyObject = dic[key] { return JSON(val) }
return JSON(NSError(
domain:"JSONErrorDomain", code:404, userInfo:[
NSLocalizedDescriptionKey:
"[\"\(key)\"] not found"
]))
default:
return JSON(NSError(
domain:"JSONErrorDomain", code:500, userInfo:[
NSLocalizedDescriptionKey: "not an object"
]))
}
}
/// access json data object
public var data:AnyObject? {
return self.isError ? nil : self._value
}
/// Gives the type name as string.
/// e.g. if it returns "Double"
/// .asDouble returns Double
public var type:String {
switch _value {
case is NSError: return "NSError"
case is NSNull: return "NSNull"
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C": return "Bool"
case "q", "l", "i", "s": return "Int"
case "Q", "L", "I", "S": return "UInt"
default: return "Double"
}
case is NSString: return "String"
case is NSArray: return "Array"
case is NSDictionary: return "Dictionary"
default: return "NSError"
}
}
/// check if self is NSError
public var isError: Bool { return _value is NSError }
/// check if self is NSNull
public var isNull: Bool { return _value is NSNull }
/// check if self is Bool
public var isBool: Bool { return type == "Bool" }
/// check if self is Int
public var isInt: Bool { return type == "Int" }
/// check if self is UInt
public var isUInt: Bool { return type == "UInt" }
/// check if self is Double
public var isDouble: Bool { return type == "Double" }
/// check if self is any type of number
public var isNumber: Bool {
if let o = _value as? NSNumber {
let t = String.fromCString(o.objCType)!
return t != "c" && t != "C"
}
return false
}
/// check if self is String
public var isString: Bool { return _value is NSString }
/// check if self is Array
public var isArray: Bool { return _value is NSArray }
/// check if self is Dictionary
public var isDictionary: Bool { return _value is NSDictionary }
/// check if self is a valid leaf node.
public var isLeaf: Bool {
return !(isArray || isDictionary || isError)
}
/// gives NSError if it holds the error. nil otherwise
public var asError:NSError? {
return _value as? NSError
}
/// gives NSNull if self holds it. nil otherwise
public var asNull:NSNull? {
return _value is NSNull ? JSON.null : nil
}
/// gives Bool if self holds it. nil otherwise
public var asBool:Bool? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C": return Bool(o.boolValue)
default:
return nil
}
default: return nil
}
}
/// gives Int if self holds it. nil otherwise
public var asInt:Int? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Int(o.longLongValue)
}
default: return nil
}
}
/// gives Int32 if self holds it. nil otherwise
public var asInt32:Int32? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Int32(o.longLongValue)
}
default: return nil
}
}
/// gives Int64 if self holds it. nil otherwise
public var asInt64:Int64? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Int64(o.longLongValue)
}
default: return nil
}
}
/// gives Float if self holds it. nil otherwise
public var asFloat:Float? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Float(o.floatValue)
}
default: return nil
}
}
/// gives Double if self holds it. nil otherwise
public var asDouble:Double? {
switch _value {
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return nil
default:
return Double(o.doubleValue)
}
default: return nil
}
}
// an alias to asDouble
public var asNumber:Double? { return asDouble }
/// gives String if self holds it. nil otherwise
public var asString:String? {
switch _value {
case let o as NSString:
return o as String
default: return nil
}
}
/// if self holds NSArray, gives a [JSON]
/// with elements therein. nil otherwise
public var asArray:[JSON]? {
switch _value {
case let o as NSArray:
var result = [JSON]()
for v:AnyObject in o { result.append(JSON(v)) }
return result
default:
return nil
}
}
/// if self holds NSDictionary, gives a [String:JSON]
/// with elements therein. nil otherwise
public var asDictionary:[String:JSON]? {
switch _value {
case let o as NSDictionary:
var result = [String:JSON]()
for (ko:AnyObject, v:AnyObject) in o {
if let k = ko as? String {
result[k] = JSON(v)
}
}
return result
default: return nil
}
}
/// Yields date from string
public var asDate:NSDate? {
if let dateString = _value as? String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
return dateFormatter.dateFromString(dateString)
}
return nil
}
/// gives the number of elements if an array or a dictionary.
/// you can use this to check if you can iterate.
public var length:Int {
switch _value {
case let o as NSArray: return o.count
case let o as NSDictionary: return o.count
default: return 0
}
}
// gives all values content in JSON object.
public var allValues:JSON{
if(self._value.allValues == nil) {
return JSON([])
}
return JSON(self._value.allValues)
}
// gives all keys content in JSON object.
public var allKeys:JSON{
if(self._value.allKeys == nil) {
return JSON([])
}
return JSON(self._value.allKeys)
}
}
extension JSON : SequenceType {
public func generate()->GeneratorOf<(AnyObject,JSON)> {
switch _value {
case let o as NSArray:
var i = -1
return GeneratorOf<(AnyObject, JSON)> {
if ++i == o.count { return nil }
return (i, JSON(o[i]))
}
case let o as NSDictionary:
var ks = o.allKeys.reverse()
return GeneratorOf<(AnyObject, JSON)> {
if ks.isEmpty { return nil }
if let k = ks.removeLast() as? String {
return (k, JSON(o.valueForKey(k)!))
} else {
return nil
}
}
default:
return GeneratorOf<(AnyObject, JSON)>{ nil }
}
}
public func mutableCopyOfTheObject() -> AnyObject {
return _value.mutableCopy()
}
}
extension JSON : Printable {
/// stringifies self.
/// if pretty:true it pretty prints
public func toString(pretty:Bool=false)->String {
switch _value {
case is NSError: return "\(_value)"
case is NSNull: return "null"
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return o.boolValue.description
case "q", "l", "i", "s":
return o.longLongValue.description
case "Q", "L", "I", "S":
return o.unsignedLongLongValue.description
default:
switch o.doubleValue {
case 0.0/0.0: return "0.0/0.0" // NaN
case -1.0/0.0: return "-1.0/0.0" // -infinity
case +1.0/0.0: return "+1.0/0.0" // infinity
default:
return o.doubleValue.description
}
}
case let o as NSString:
return o.debugDescription
default:
let opts = pretty
? NSJSONWritingOptions.PrettyPrinted : nil
if let data = NSJSONSerialization.dataWithJSONObject(
_value, options:opts, error:nil
) as NSData? {
if let result = NSString(
data:data, encoding:NSUTF8StringEncoding
) as? String {
return result
}
}
return "YOU ARE NOT SUPPOSED TO SEE THIS!"
}
}
public var description:String { return toString() }
}
|
5fd72d44160769fa1834ee003d6f71bb
| 31.535963 | 78 | 0.5394 | false | false | false | false |
Ferrari-lee/firefox-ios
|
refs/heads/master
|
Client/Frontend/Settings/Clearables.swift
|
mpl-2.0
|
3
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
// A base protocol for something that can be cleared.
protocol Clearable {
func clear() -> Success
var label: String { get }
}
class ClearableError: MaybeErrorType {
private let msg: String
init(msg: String) {
self.msg = msg
}
var description: String { return msg }
}
// Clears our browsing history, including favicons and thumbnails.
class HistoryClearable: Clearable {
let profile: Profile
init(profile: Profile) {
self.profile = profile
}
var label: String {
return NSLocalizedString("Browsing History", comment: "Settings item for clearing browsing history")
}
func clear() -> Success {
return profile.history.clearHistory().bind { success in
SDImageCache.sharedImageCache().clearDisk()
SDImageCache.sharedImageCache().clearMemory()
NSNotificationCenter.defaultCenter().postNotificationName(NotificationPrivateDataClearedHistory, object: nil)
return Deferred(value: success)
}
}
}
// Clear all stored passwords. This will clear both Firefox's SQLite storage and the system shared
// Credential storage.
class PasswordsClearable: Clearable {
let profile: Profile
init(profile: Profile) {
self.profile = profile
}
var label: String {
return NSLocalizedString("Saved Logins", comment: "Settings item for clearing passwords and login data")
}
func clear() -> Success {
// Clear our storage
return profile.logins.removeAll() >>== { res in
let storage = NSURLCredentialStorage.sharedCredentialStorage()
let credentials = storage.allCredentials
for (space, credentials) in credentials {
for (_, credential) in credentials {
storage.removeCredential(credential, forProtectionSpace: space)
}
}
return succeed()
}
}
}
struct ClearableErrorType: MaybeErrorType {
let err: ErrorType
init(err: ErrorType) {
self.err = err
}
var description: String {
return "Couldn't clear: \(err)."
}
}
// Clear the web cache. Note, this has to close all open tabs in order to ensure the data
// cached in them isn't flushed to disk.
class CacheClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Cache", comment: "Settings item for clearing the cache")
}
func clear() -> Success {
// First ensure we close all open tabs first.
tabManager.removeAll()
// Reset the process pool to ensure no cached data is written back
tabManager.resetProcessPool()
// Remove the basic cache.
NSURLCache.sharedURLCache().removeAllCachedResponses()
// Now lets finish up by destroying our Cache directory.
do {
try deleteLibraryFolderContents("Caches")
} catch {
return deferMaybe(ClearableErrorType(err: error))
}
return succeed()
}
}
private func deleteLibraryFolderContents(folder: String) throws {
let manager = NSFileManager.defaultManager()
let library = manager.URLsForDirectory(NSSearchPathDirectory.LibraryDirectory, inDomains: .UserDomainMask)[0]
let dir = library.URLByAppendingPathComponent(folder)
let contents = try manager.contentsOfDirectoryAtPath(dir.path!)
for content in contents {
try manager.removeItemAtURL(dir.URLByAppendingPathComponent(content))
}
}
private func deleteLibraryFolder(folder: String) throws {
let manager = NSFileManager.defaultManager()
let library = manager.URLsForDirectory(NSSearchPathDirectory.LibraryDirectory, inDomains: .UserDomainMask)[0]
let dir = library.URLByAppendingPathComponent(folder)
try manager.removeItemAtURL(dir)
}
// Removes all site data stored for sites. This should include things like IndexedDB or websql storage.
class SiteDataClearable : Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Offline Website Data", comment: "Settings item for clearing website data")
}
func clear() -> Success {
// First, close all tabs to make sure they don't hold any thing in memory.
tabManager.removeAll()
// Then we just wipe the WebKit directory from our Library.
do {
try deleteLibraryFolder("WebKit")
} catch {
return deferMaybe(ClearableErrorType(err: error))
}
return succeed()
}
}
// Remove all cookies stored by the site.
class CookiesClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Cookies", comment: "Settings item for clearing cookies")
}
func clear() -> Success {
// First close all tabs to make sure they aren't holding anything in memory.
tabManager.removeAll()
// Now we wipe the system cookie store (for our app).
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
if let cookies = storage.cookies {
for cookie in cookies {
storage.deleteCookie(cookie )
}
}
// And just to be safe, we also wipe the Cookies directory.
do {
try deleteLibraryFolderContents("Cookies")
} catch {
return deferMaybe(ClearableErrorType(err: error))
}
return succeed()
}
}
|
204be6f1eb534b75cd2c975cc5e4b8d7
| 30.125654 | 121 | 0.658311 | false | false | false | false |
heilb1314/500px_Challenge
|
refs/heads/master
|
PhotoWall_500px_challenge/PhotoWall_500px_challenge/PhotoDetailViewController.swift
|
mit
|
1
|
//
// PhotoDetailViewController.swift
// demo_500px
//
// Created by Jianxiong Wang on 1/29/17.
// Copyright © 2017 JianxiongWang. All rights reserved.
//
import UIKit
import Kingfisher
class PhotoDetailViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var blurView: UIVisualEffectView!
@IBOutlet weak var textView: UITextView!
internal var photo: Photo!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupNavigationBar()
}
override func viewDidLoad() {
super.viewDidLoad()
setupPhotoDetail()
let url = URL(string: photo.images[photo.images.count - 1].url)
imageView.kf.setImage(with: url)
self.imageView.isUserInteractionEnabled = true
setupTapGestures()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setupNavigationBar() {
self.navigationController?.navigationBar.barStyle = .blackTranslucent
self.navigationController?.navigationBar.tintColor = Color.white
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: Color.white]
self.navigationItem.title = photo.name
}
private func setupPhotoDetail() {
var detail = ""
detail += "Name: " + (photo.name ?? "") + "\n"
if let user = photo.attributes[PhotoFields.user] as? [String:Any] {
detail += "User: " + (user[UserFields.fullname] as? String ?? (user[UserFields.username] as? String) ?? "") + "\n"
}
if let fav = photo.attributes[PhotoFields.favoritesCount] as? Int {
detail += "Favored: " + fav.description + "\n"
}
if let viewed = photo.attributes[PhotoFields.timesViewed] as? Int {
detail += "Viewed: " + viewed.description + "\n"
}
detail += "Description: " + (photo.description ?? "") + "\n"
self.textView.text = detail
}
private func setupTapGestures() {
let singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(toggleDetail))
singleTapGestureRecognizer.numberOfTapsRequired = 1
let doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(toggleImageSize))
doubleTapGestureRecognizer.numberOfTapsRequired = 2
singleTapGestureRecognizer.delegate = self
doubleTapGestureRecognizer.delegate = self
self.imageView.addGestureRecognizer(singleTapGestureRecognizer)
self.imageView.addGestureRecognizer(doubleTapGestureRecognizer)
singleTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer)
}
/// hide/show detail and nav bar when tap once
func toggleDetail(gest: UITapGestureRecognizer) {
self.blurView.isHidden = !self.blurView.isHidden
self.navigationController?.navigationBar.isHidden = self.blurView.isHidden
}
// toggle imageView aspectFit/aspectFill when tap twice
func toggleImageSize(gest: UITapGestureRecognizer) {
if self.imageView.contentMode == .scaleAspectFit {
self.imageView.contentMode = .scaleAspectFill
} else {
self.imageView.contentMode = .scaleAspectFit
}
}
}
|
43a84f3874656ffa26521762b64700a2
| 35.216495 | 126 | 0.663535 | false | false | false | false |
fluidsonic/JetPack
|
refs/heads/master
|
Sources/Extensions/Swift/CollectionType.swift
|
mit
|
1
|
public extension Collection {
func lastIndexOf(predicate: (Element) throws -> Bool) rethrows -> Index? {
for index in indices.reversed() where try predicate(self[index]) {
return index
}
return nil
}
var nonEmpty: Self? {
return isEmpty ? nil : self
}
subscript(safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
public extension Collection where Element: AnyObject {
func indexOfIdentical(_ element: Element) -> Index? {
for index in indices where self[index] === element {
return index
}
return nil
}
}
public extension Collection where Element: Equatable {
func lastIndexOf(_ element: Element) -> Index? {
for index in indices.reversed() where self[index] == element {
return index
}
return nil
}
}
|
d26308cef280d602e63a17014afab4b2
| 17.045455 | 75 | 0.68262 | false | false | false | false |
artemstepanenko/Dekoter
|
refs/heads/master
|
Dekoter/Classes/Koter.swift
|
mit
|
1
|
//
// Koter.swift
// Dekoter
//
// Created by Artem Stepanenko on 26/12/16.
// Copyright (c) 2016 Artem Stepanenko <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Collects a content of an object to be converted to Data and back – from Data to the initial type.
public class Koter {
// MARK: - Property
private(set) var objects: [AnyHashable: Any]
// MARK: - Koting / Dekoting
/// Decodes and returns an object that was previously encoded and associated with the string key.
///
/// - Parameter key: The string key.
/// - Returns: The object that was previously encoded.
public func dekotObject<T>(forKey key: AnyHashable) -> T? {
return objects[key] as? T
}
/// Decodes and returns an object which implements Koting that was previously encoded and associated with the string key.
///
/// - Parameter key: The string key.
/// - Returns: The object which implements the `Koting` protocol that was previously encoded.
public func dekotObject<T: Koting>(forKey key: AnyHashable) -> T? {
guard let dict = objects[key] as? [AnyHashable: Any] else {
return nil
}
return object(from: dict)
}
/// Decodes and returns an array of objects which implement Koting that was previously encoded and associated with the string key.
///
/// - Parameter key: The string key.
/// - Returns: The array of objects which implement the `Koting` protocol that was previously encoded.
public func dekotObject<T: Koting>(forKey key: AnyHashable) -> [T]? {
guard let objects = objects[key] as? [Any] else {
return nil
}
return objects.flatMap { object(from: $0 as? [AnyHashable: Any]) }
}
/// Encodes an object which implements the `Koting` protocol and associates it with the string key.
///
/// - Parameters:
/// - object: The object which implements Koting.
/// - key: The string key.
public func enkotObject(_ object: Koting?, forKey key: AnyHashable) {
guard let object = object else {
return
}
objects[key] = dict(from: object)
}
/// Encodes an array of objects which implement the `Koting` protocol and associates it with the string key.
///
/// - Parameters:
/// - object: The array of objects which implement the `Koting` protocol.
/// - key: The string key.
public func enkotObject(_ object: [Koting]?, forKey key: AnyHashable) {
guard let object = object else {
return
}
objects[key] = object.map { dict(from: $0) }
}
/// Encodes an object and associates it with the string key.
///
/// - Parameters:
/// - object: The object.
/// - key: The string key.
public func enkotObject(_ object: Any?, forKey key: AnyHashable) {
guard let object = object else {
return
}
objects[key] = object
}
// MARK: - Initializer
/// An initializer without params
public convenience init() {
self.init(objects: [:])
}
/// An initializer which takes objects to store.
public required init(objects: [AnyHashable: Any]) {
self.objects = objects
}
}
// MARK: - Private
fileprivate extension Koter {
func object<T: Koting>(from dict: [AnyHashable: Any]?) -> T? {
guard let dict = dict else {
return nil
}
let koter = Koter(objects: dict)
return T(koter: koter)
}
func dict(from object: Koting?) -> [AnyHashable: Any]? {
guard let object = object else {
return nil
}
let koter = Koter()
object.enkot(with: koter)
return koter.objects
}
}
|
4942859fafcdb93a8c73d1f2444565ea
| 34.80292 | 134 | 0.633843 | false | false | false | false |
IngmarStein/swift
|
refs/heads/master
|
test/decl/func/keyword-argument-labels.swift
|
apache-2.0
|
4
|
// RUN: %target-parse-verify-swift
struct SomeRange { }
// Function declarations.
func paramName(_ func: Int, in: SomeRange) { }
func firstArgumentLabelWithParamName(in range: SomeRange) { }
func firstArgumentLabelWithParamName2(range in: SomeRange) { }
func escapedInout(`inout` value: SomeRange) { }
struct SomeType {
// Initializers
init(func: () -> ()) { }
init(init func: () -> ()) { }
// Subscripts
subscript (class index: AnyClass) -> Int {
return 0
}
subscript (class: AnyClass) -> Int {
return 0
}
subscript (struct: Any.Type) -> Int {
return 0
}
}
class SomeClass { }
// Function types.
typealias functionType = (_ in: SomeRange) -> Bool
// Calls
func testCalls(_ range: SomeRange) {
paramName(0, in: range)
firstArgumentLabelWithParamName(in: range)
firstArgumentLabelWithParamName2(range: range)
var st = SomeType(func: {})
st = SomeType(init: {})
_ = st[class: SomeClass.self]
_ = st[SomeClass.self]
_ = st[SomeType.self]
escapedInout(`inout`: range)
// Fix-Its
paramName(0, `in`: range) // expected-warning{{keyword 'in' does not need to be escaped in argument list}}{{16-17=}}{{19-20=}}
}
|
5ace29347cd8e9b4906caf4537de68fc
| 22 | 128 | 0.657289 | false | false | false | false |
Mindera/Alicerce
|
refs/heads/master
|
Sources/DeepLinking/Route+TrieRouter.swift
|
mit
|
1
|
import Foundation
#if canImport(AlicerceCore)
import AlicerceCore
#endif
extension Route {
/// An error produced by `TrieRouter` instances.
public enum TrieRouterError: Error {
/// The route already exists.
case duplicateRoute
/// The route is invalid.
case invalidRoute(InvalidRouteError)
/// The route conflicts with an existing route.
case conflictingRoute(ConflictingRouteError)
// The route can't been found.
case routeNotFound
/// An error detailing an invalid route.
public enum InvalidRouteError: Error {
/// The route contains a duplicate parameter name.
case duplicateParameterName(String)
/// The route contains a catchAll component in an invalid position (must be the last in the route).
case misplacedCatchAllComponent(String?)
// The route is not a valid URL.
case invalidURL
// The route contains an invalid component.
case invalidComponent(InvalidComponentError)
/// An unexpected error has occured.
case unexpected(Error)
}
// An error detailing a conflict between a route and existing routes.
public enum ConflictingRouteError: Error {
/// A route already exists in the router containing a parameter at the same position, with a different name.
case parameterComponent(existing: String, new: String)
/// A route already exists in the router containing a catchAll at the same position, with a different name.
case catchAllComponent(existing: String?, new: String?)
}
}
/// A URL router that is backed by a **trie** tree and forwards route handling to registered handlers.
///
/// Routes are registered with an associated handler, which on match handles the event and optionally invokes a
/// completion closure with an arbitrary payload of type `T`. This allows handlers to perform asynchronous work even
/// though route matching is made synchronously.
///
/// - Remark: Access to the backing trie tree data structure *is* synchronized, so all operations can safely be
/// called from different threads.
///
/// - Note: https://en.wikipedia.org/wiki/Trie for more information.
public final class TrieRouter<R: Routable, T>: Router {
/// A type representing the router's trie tree node.
fileprivate typealias TrieNode = Route.TrieNode<AnyRouteHandler<R, T>>
/// A type representing a route to match.
private typealias MatchRoute = (components: [String], queryItems : [URLQueryItem])
/// A type representing a matched route,.
private typealias Match = (parameters: Route.Parameters, handler: AnyRouteHandler<R, T>)
/// The router's trie tree.
fileprivate var trie: Atomic<TrieNode> = Atomic(TrieNode())
/// Creates an instance of a trie router.
public init() {}
/// Registers a new *annotated URL* route in the router with the given handler.
///
/// Annotated URLs contain additional information in their path components that allow matching routes as:
///
/// - constant values (`value`)
/// - arbitrary parameters (`:variable`)
/// - any value (wildcard, `*`)
/// - any remaining route (catchAll, `**` or `**variable`)
///
/// - Parameters:
/// - route: The URL route to register.
/// - handler: The handler to associate with the route and handle it on match.
/// - Throws: A `TrieRouterError` error if the route is invalid or a conflict exists.
public func register(_ route: URL, handler: AnyRouteHandler<R, T>) throws {
let routeComponents = try parseAnnotatedRoute(route)
try trie.modify { node in
do {
try node.add(routeComponents, handler: handler)
} catch Route.TrieNodeError.conflictingNodeHandler {
throw TrieRouterError.duplicateRoute
} catch Route.TrieNodeError.duplicateParameterName(let parameterName) {
throw TrieRouterError.invalidRoute(.duplicateParameterName(parameterName))
} catch Route.TrieNodeError.conflictingParameterName(let existing, let new) {
throw TrieRouterError.conflictingRoute(.parameterComponent(existing: existing, new: new))
} catch Route.TrieNodeError.conflictingCatchAllComponent(let existing, let new) {
throw TrieRouterError.conflictingRoute(.catchAllComponent(existing: existing, new: new))
} catch Route.TrieNodeError.misplacedCatchAllComponent(let catchAllName) {
throw TrieRouterError.invalidRoute(.misplacedCatchAllComponent(catchAllName))
} catch {
assertionFailure("🔥 Unexpected error when registering \(route)! Error: \(error)")
throw TrieRouterError.invalidRoute(.unexpected(error))
}
}
}
/// Unregisters the given *annotated URL* route from the router, and returns the associated handler if found.
///
/// Annotated URLs contain additional information in their path components that allow matching routes as:
///
/// - constant values (`value`)
/// - arbitrary parameters (`:variable`)
/// - any value (wildcard, `*`)
/// - any remaining route (catchAll, `**` or `**variable`)
///
/// - Parameter route: The URL route to unregister
/// - Throws: A `TrieRouterError` error if the route is invalid or wasn't found.
/// - Returns: The unregistered handler associated with the route.
@discardableResult
public func unregister(_ route: URL) throws -> AnyRouteHandler<R, T> {
let routeComponents = try parseAnnotatedRoute(route)
return try trie.modify { node in
do {
return try node.remove(routeComponents)
} catch Route.TrieNodeError.routeNotFound {
throw TrieRouterError.routeNotFound
} catch Route.TrieNodeError.misplacedCatchAllComponent(let catchAllName) {
throw TrieRouterError.invalidRoute(.misplacedCatchAllComponent(catchAllName))
} catch {
assertionFailure("🔥 Unexpected error when unregistering \(route)! Error: \(error)")
throw TrieRouterError.routeNotFound
}
}
}
/// Routes the given `R` route by matching it against the current trie, and optionally notifies routing success
/// with a custom payload from the route handler.
///
/// - Important: `R` routes should **not** return *annotated URL* routes. Those should only be used in
/// `register`/`unregister`.
///
/// - Parameters:
/// - route: The route to route.
/// - handleCompletion: The closure to notify routing success with custom payload from the route handler.
/// - Throws: A `TrieRouterError` error if the route wasn't found.
public func route(_ route: R, handleCompletion: ((T) -> Void)? = nil) throws {
let (pathComponents, queryItems) = try parseMatchRoute(route.route)
let match: Match = try trie.withValue { node in
var parameters: Route.Parameters = [:]
guard let handler = node.match(pathComponents, parameters: ¶meters) else {
throw TrieRouterError.routeNotFound
}
return (parameters: parameters, handler: handler)
}
match.handler.handle(
route: route,
parameters: match.parameters,
queryItems: queryItems,
completion: handleCompletion
)
}
// MARK: - Private methods
/// Parses the given *annotated* route into an array of type safe route components, to be registered or
/// unregistered.
///
/// Annotated routes contain additional information that allow matching routes as:
///
/// - constant values (`value`)
/// - arbitrary parameters (`:variable`)
/// - any value (wildcard, `*`)
/// - any remaining route (catchAll, `**` or `**variable`)
///
/// - Parameter route: The annotated route to parsed.
/// - Throws: A `TrieRouterError` error if a route component is invalid.
/// - Returns: The annotated route's parsed route components.
private func parseAnnotatedRoute(_ route: URL) throws -> [Route.Component] {
// use a wildcard for empty schemes/hosts, to match any scheme/host
// URL scheme and host comparison should be case insensitive in conformance to RFC-3986
let schemeComponent = (route.scheme?.lowercased()).constantOrWildcardComponent
let hostComponent = (route.host?.lowercased()).constantOrWildcardComponent
do {
let pathComponents = try route.pathComponents.filter { $0 != "/" }.map(Route.Component.init(component:))
assert(route.query == nil, "🔥 URL query items are ignored when registering/unregistering routes!")
return [schemeComponent, hostComponent] + pathComponents
} catch let error as InvalidComponentError {
throw TrieRouterError.invalidRoute(.invalidComponent(error))
} catch {
assertionFailure("🔥 Unexpected error when parsing route \(route)! Error: \(error)")
throw TrieRouterError.invalidRoute(.unexpected(error))
}
}
/// Parses the given route into an array of route components and query items to be matched by the router and
/// forwarded to the handler on success, respectively.
///
/// - Parameter route: The route to be parsed.
/// - Throws: A `TrieRouterError` error if the URL is invalid.
/// - Returns: The route's parsed route components and query items.
private func parseMatchRoute(_ route: URL) throws -> MatchRoute {
// use an empty string for empty scheme/host, to match wildcard scheme/host
// URL scheme and host comparison should be case insensitive in conformance to RFC-3986
let schemeComponent = route.scheme?.lowercased() ?? ""
let hostComponent = route.host?.lowercased() ?? ""
let pathComponents = route.pathComponents.filter { $0 != "/" }
let routeComponents = [schemeComponent, hostComponent] + pathComponents
guard let urlComponents = URLComponents(url: route, resolvingAgainstBaseURL: false) else {
throw TrieRouterError.invalidRoute(.invalidURL)
}
return (components: routeComponents, queryItems: urlComponents.queryItems ?? [])
}
}
}
// MARK: - CustomStringConvertible
extension Route.TrieRouter: CustomStringConvertible {
public var description: String { trie.value.description }
}
// MARK: - Helpers
private extension Optional where Wrapped == String {
/// A `.constant` route component if not `nil` nor empty (`""`), `.wildcard` otherwise.
var constantOrWildcardComponent: Route.Component {
guard let value = self, value != "" else { return .wildcard }
return .constant(value)
}
}
@available(*, unavailable, renamed: "Route.TrieRouter")
public typealias TreeRouter<Handler> = Route.TrieRouter<URL, Handler>
|
fe21b7179997f03963218ad76a92467b
| 43.078947 | 120 | 0.623625 | false | false | false | false |
dusanIntellex/backend-operation-layer
|
refs/heads/master
|
Example/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift
|
mit
|
2
|
//
// PrimitiveSequence.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/5/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/// Observable sequences containing 0 or 1 element.
public struct PrimitiveSequence<Trait, Element> {
let source: Observable<Element>
init(raw: Observable<Element>) {
self.source = raw
}
}
/// Observable sequences containing 0 or 1 element
public protocol PrimitiveSequenceType {
/// Additional constraints
associatedtype TraitType
/// Sequence element type
associatedtype ElementType
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
var primitiveSequence: PrimitiveSequence<TraitType, ElementType> { get }
}
extension PrimitiveSequence: PrimitiveSequenceType {
/// Additional constraints
public typealias TraitType = Trait
/// Sequence element type
public typealias ElementType = Element
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
public var primitiveSequence: PrimitiveSequence<TraitType, ElementType> {
return self
}
}
extension PrimitiveSequence: ObservableConvertibleType {
/// Type of elements in sequence.
public typealias E = Element
/// Converts `self` to `Observable` sequence.
///
/// - returns: Observable sequence that represents `self`.
public func asObservable() -> Observable<E> {
return source
}
}
extension PrimitiveSequence {
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.deferred {
try observableFactory().asObservable()
})
}
/**
Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the source by.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: the source Observable shifted in time by the specified delay.
*/
public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: primitiveSequence.source.delay(dueTime, scheduler: scheduler))
}
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.delaySubscription(dueTime, scheduler: scheduler))
}
/**
Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription
actions have side-effects that require to be run on a scheduler, use `subscribeOn`.
- seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html)
- parameter scheduler: Scheduler to notify observers on.
- returns: The source sequence whose observations happen on the specified scheduler.
*/
public func observeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.observeOn(scheduler))
}
/**
Wraps the source sequence in order to run its subscription and unsubscription logic on the specified
scheduler.
This operation is not commonly used.
This only performs the side-effects of subscription and unsubscription on the specified scheduler.
In order to invoke observer callbacks on a `scheduler`, use `observeOn`.
- seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html)
- parameter scheduler: Scheduler to perform subscription and unsubscription actions on.
- returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
public func subscribeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.subscribeOn(scheduler))
}
/**
Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter handler: Error handler function, producing another observable sequence.
- returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred.
*/
public func catchError(_ handler: @escaping (Swift.Error) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.catchError { try handler($0).asObservable() })
}
/**
If the initial subscription to the observable sequence emits an error event, try repeating it up to the specified number of attempts (inclusive of the initial attempt) or until is succeeds. For example, if you want to retry a sequence once upon failure, you should use retry(2) (once for the initial attempt, and once for the retry).
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter maxAttemptCount: Maximum number of times to attempt the sequence subscription.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
public func retry(_ maxAttemptCount: Int)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retry(maxAttemptCount))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retryWhen(notificationHandler))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retryWhen(notificationHandler))
}
/**
Prints received events for all observers on standard output.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter identifier: Identifier that is printed together with event description to standard output.
- parameter trimOutput: Should output be trimmed to max 40 characters.
- returns: An observable sequence whose events are printed to standard output.
*/
public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function))
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html)
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter primitiveSequenceFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
public static func using<Resource: Disposable>(_ resourceFactory: @escaping () throws -> Resource, primitiveSequenceFactory: @escaping (Resource) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.using(resourceFactory, observableFactory: { (resource: Resource) throws -> Observable<E> in
return try primitiveSequenceFactory(resource).asObservable()
}))
}
/**
Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: An observable sequence with a `RxError.timeout` in case of a timeout.
*/
public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence<Trait, Element>(raw: primitiveSequence.source.timeout(dueTime, scheduler: scheduler))
}
/**
Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter other: Sequence to return in case of a timeout.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: The source sequence switching to the other sequence in case of a timeout.
*/
public func timeout(_ dueTime: RxTimeInterval,
other: PrimitiveSequence<Trait, Element>,
scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence<Trait, Element>(raw: primitiveSequence.source.timeout(dueTime, other: other.source, scheduler: scheduler))
}
}
extension PrimitiveSequenceType where ElementType: RxAbstractInteger
{
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
public static func timer(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable<ElementType>.timer(dueTime, scheduler: scheduler))
}
}
|
72add45e3f54451e80443efbf0466abc
| 50.764045 | 338 | 0.732798 | false | false | false | false |
5lucky2xiaobin0/PandaTV
|
refs/heads/master
|
PandaTV/PandaTV/Classes/Main/VIew/CycleView.swift
|
mit
|
1
|
//
// CycleView.swift
// PandaTV
//
// Created by 钟斌 on 2017/3/25.
// Copyright © 2017年 xiaobin. All rights reserved.
//
import UIKit
private let cycleCell = "cycleCell"
class CycleView: UIView {
@IBOutlet weak var scrollView: UICollectionView!
@IBOutlet weak var pageCon: UIPageControl!
var items : [CycleItem]? {
didSet {
guard let image = items else {return}
if image.count == 0 {return}
pageCon.numberOfPages = image.count
scrollView.reloadData()
//默认滚动到中间
let indexpath = IndexPath(item: image.count * 20, section: 0)
scrollView.scrollToItem(at: indexpath, at: .left, animated: false)
removeToScroll()
if image.count > 1 {
pageCon.isHidden = false
addTimeToScroll()
}else{
pageCon.isHidden = true
}
}
}
var time : Timer?
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = UIViewAutoresizing()
scrollView.register(UINib(nibName: "CycleCell", bundle: nil), forCellWithReuseIdentifier: cycleCell)
scrollView.isPagingEnabled = true
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
}
override func layoutSubviews() {
super.layoutSubviews()
// 设置collectionView的layout
let layout = scrollView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = scrollView.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
}
static func getView() -> CycleView {
return Bundle.main.loadNibNamed("CycleView", owner: nil, options: nil)?.first as!CycleView
}
}
// MARK: - 事件处理
extension CycleView {
func addTimeToScroll() {
time = Timer(timeInterval: 3, target: self, selector: #selector(timeToScroll), userInfo: nil, repeats: true)
RunLoop.main.add(time!, forMode: RunLoopMode.commonModes)
}
func removeToScroll() {
time?.invalidate()
time = nil
}
@objc fileprivate func timeToScroll(){
var x = scrollView.contentOffset.x
x += scrollView.bounds.width
scrollView.setContentOffset(CGPoint(x: x, y: 0), animated: true)
}
}
// MARK: - collectionView 数据源和代理
extension CycleView : UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (items?.count ?? 0) * 2000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cycleCell, for: indexPath) as! CycleCell
cell.item = items?[indexPath.item%(items?.count)!]
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
// 2.计算pageControl的currentIndex
pageCon.currentPage = Int(offsetX / scrollView.bounds.width) % (items?.count ?? 1)
}
//手动拖拽时停止定时器
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeToScroll()
}
//滚动结束开启定时器
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addTimeToScroll()
}
}
|
19fe32d4f7e978c5b487fb8bfc0cf355
| 28.408 | 121 | 0.62704 | false | false | false | false |
frootloops/swift
|
refs/heads/master
|
test/Prototypes/CollectionTransformers.swift
|
apache-2.0
|
3
|
//===----------------------------------------------------------------------===//
//
// 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: %target-run-stdlib-swift
// REQUIRES: executable_test
// FIXME: This test runs very slowly on watchOS.
// UNSUPPORTED: OS=watchos
public enum ApproximateCount {
case Unknown
case Precise(IntMax)
case Underestimate(IntMax)
case Overestimate(IntMax)
}
public protocol ApproximateCountableSequence : Sequence {
/// Complexity: amortized O(1).
var approximateCount: ApproximateCount { get }
}
/// A collection that provides an efficient way to split its index ranges.
public protocol SplittableCollection : Collection {
// We need this protocol so that collections with only forward or bidirectional
// traversals could customize their splitting behavior.
//
// FIXME: all collections with random access should conform to this protocol
// automatically.
/// Splits a given range of indices into a set of disjoint ranges covering
/// the same elements.
///
/// Complexity: amortized O(1).
///
/// FIXME: should that be O(log n) to cover some strange collections?
///
/// FIXME: index invalidation rules?
///
/// FIXME: a better name. Users will never want to call this method
/// directly.
///
/// FIXME: return an optional for the common case when split() cannot
/// subdivide the range further.
func split(_ range: Range<Index>) -> [Range<Index>]
}
internal func _splitRandomAccessIndexRange<
C : RandomAccessCollection
>(
_ elements: C,
_ range: Range<C.Index>
) -> [Range<C.Index>] {
let startIndex = range.lowerBound
let endIndex = range.upperBound
let length = elements.distance(from: startIndex, to: endIndex)
if length < 2 {
return [range]
}
let middle = elements.index(startIndex, offsetBy: length / 2)
return [startIndex ..< middle, middle ..< endIndex]
}
/// A helper object to build a collection incrementally in an efficient way.
///
/// Using a builder can be more efficient than creating an empty collection
/// instance and adding elements one by one.
public protocol CollectionBuilder {
associatedtype Destination : Collection
associatedtype Element = Destination.Iterator.Element
init()
/// Gives a hint about the expected approximate number of elements in the
/// collection that is being built.
mutating func sizeHint(_ approximateSize: Int)
/// Append `element` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(1).
mutating func append(_ element: Destination.Iterator.Element)
/// Append `elements` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(n), where `n` is equal to `count(elements)`.
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element
/// Append elements from `otherBuilder` to `self`, emptying `otherBuilder`.
///
/// Equivalent to::
///
/// self.append(contentsOf: otherBuilder.takeResult())
///
/// but is more efficient.
///
/// Complexity: O(1).
mutating func moveContentsOf(_ otherBuilder: inout Self)
/// Build the collection from the elements that were added to this builder.
///
/// Once this function is called, the builder may not be reused and no other
/// methods should be called.
///
/// Complexity: O(n) or better (where `n` is the number of elements that were
/// added to this builder); typically O(1).
mutating func takeResult() -> Destination
}
public protocol BuildableCollectionProtocol : Collection {
associatedtype Builder : CollectionBuilder
}
extension Array : SplittableCollection {
public func split(_ range: Range<Int>) -> [Range<Int>] {
return _splitRandomAccessIndexRange(self, range)
}
}
public struct ArrayBuilder<T> : CollectionBuilder {
// FIXME: the compiler didn't complain when I remove public on 'Collection'.
// File a bug.
public typealias Destination = Array<T>
public typealias Element = T
internal var _resultParts = [[T]]()
internal var _resultTail = [T]()
public init() {}
public mutating func sizeHint(_ approximateSize: Int) {
_resultTail.reserveCapacity(approximateSize)
}
public mutating func append(_ element: T) {
_resultTail.append(element)
}
public mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == T {
_resultTail.append(contentsOf: elements)
}
public mutating func moveContentsOf(_ otherBuilder: inout ArrayBuilder<T>) {
// FIXME: do something smart with the capacity set in this builder and the
// other builder.
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: not O(1)!
_resultParts.append(contentsOf: otherBuilder._resultParts)
otherBuilder._resultParts = []
swap(&_resultTail, &otherBuilder._resultTail)
}
public mutating func takeResult() -> Destination {
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: optimize. parallelize.
return Array(_resultParts.joined())
}
}
extension Array : BuildableCollectionProtocol {
public typealias Builder = ArrayBuilder<Element>
}
//===----------------------------------------------------------------------===//
// Fork-join
//===----------------------------------------------------------------------===//
// As sad as it is, I think for practical performance reasons we should rewrite
// the inner parts of the fork-join framework in C++. In way too many cases
// than necessary Swift requires an extra allocation to pin objects in memory
// for safe multithreaded access. -Dmitri
import SwiftShims
import SwiftPrivate
import Darwin
import Dispatch
// FIXME: port to Linux.
// XFAIL: linux
// A wrapper for pthread_t with platform-independent interface.
public struct _stdlib_pthread_t : Equatable, Hashable {
internal let _value: pthread_t
public var hashValue: Int {
return _value.hashValue
}
}
public func == (lhs: _stdlib_pthread_t, rhs: _stdlib_pthread_t) -> Bool {
return lhs._value == rhs._value
}
public func _stdlib_pthread_self() -> _stdlib_pthread_t {
return _stdlib_pthread_t(_value: pthread_self())
}
struct _ForkJoinMutex {
var _mutex: UnsafeMutablePointer<pthread_mutex_t>
init() {
_mutex = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_mutex_init(_mutex, nil) != 0 {
fatalError("pthread_mutex_init")
}
}
func `deinit`() {
if pthread_mutex_destroy(_mutex) != 0 {
fatalError("pthread_mutex_init")
}
_mutex.deinitialize(count: 1)
_mutex.deallocate()
}
func withLock<Result>(_ body: () -> Result) -> Result {
if pthread_mutex_lock(_mutex) != 0 {
fatalError("pthread_mutex_lock")
}
let result = body()
if pthread_mutex_unlock(_mutex) != 0 {
fatalError("pthread_mutex_unlock")
}
return result
}
}
struct _ForkJoinCond {
var _cond: UnsafeMutablePointer<pthread_cond_t>
init() {
_cond = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_cond_init(_cond, nil) != 0 {
fatalError("pthread_cond_init")
}
}
func `deinit`() {
if pthread_cond_destroy(_cond) != 0 {
fatalError("pthread_cond_destroy")
}
_cond.deinitialize(count: 1)
_cond.deallocate()
}
func signal() {
pthread_cond_signal(_cond)
}
func wait(_ mutex: _ForkJoinMutex) {
pthread_cond_wait(_cond, mutex._mutex)
}
}
final class _ForkJoinOneShotEvent {
var _mutex: _ForkJoinMutex = _ForkJoinMutex()
var _cond: _ForkJoinCond = _ForkJoinCond()
var _isSet: Bool = false
init() {}
deinit {
_cond.`deinit`()
_mutex.`deinit`()
}
func set() {
_mutex.withLock {
if !_isSet {
_isSet = true
_cond.signal()
}
}
}
/// Establishes a happens-before relation between calls to set() and wait().
func wait() {
_mutex.withLock {
while !_isSet {
_cond.wait(_mutex)
}
}
}
/// If the function returns true, it establishes a happens-before relation
/// between calls to set() and isSet().
func isSet() -> Bool {
return _mutex.withLock {
return _isSet
}
}
}
final class _ForkJoinWorkDeque<T> {
// FIXME: this is just a proof-of-concept; very inefficient.
// Implementation note: adding elements to the head of the deque is common in
// fork-join, so _deque is stored reversed (appending to an array is cheap).
// FIXME: ^ that is false for submission queues though.
var _deque: ContiguousArray<T> = []
var _dequeMutex: _ForkJoinMutex = _ForkJoinMutex()
init() {}
deinit {
precondition(_deque.isEmpty)
_dequeMutex.`deinit`()
}
var isEmpty: Bool {
return _dequeMutex.withLock {
return _deque.isEmpty
}
}
func prepend(_ element: T) {
_dequeMutex.withLock {
_deque.append(element)
}
}
func tryTakeFirst() -> T? {
return _dequeMutex.withLock {
let result = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return result
}
}
func tryTakeFirstTwo() -> (T?, T?) {
return _dequeMutex.withLock {
let result1 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
let result2 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return (result1, result2)
}
}
func append(_ element: T) {
_dequeMutex.withLock {
_deque.insert(element, at: 0)
}
}
func tryTakeLast() -> T? {
return _dequeMutex.withLock {
let result = _deque.first
if _deque.count > 0 {
_deque.remove(at: 0)
}
return result
}
}
func takeAll() -> ContiguousArray<T> {
return _dequeMutex.withLock {
let result = _deque
_deque = []
return result
}
}
func tryReplace(
_ value: T,
makeReplacement: @escaping () -> T,
isEquivalent: @escaping (T, T) -> Bool
) -> Bool {
return _dequeMutex.withLock {
for i in _deque.indices {
if isEquivalent(_deque[i], value) {
_deque[i] = makeReplacement()
return true
}
}
return false
}
}
}
final class _ForkJoinWorkerThread {
internal var _tid: _stdlib_pthread_t?
internal let _pool: ForkJoinPool
internal let _submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal let _workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal init(
_pool: ForkJoinPool,
submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>,
workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
) {
self._tid = nil
self._pool = _pool
self._submissionQueue = submissionQueue
self._workDeque = workDeque
}
internal func startAsync() {
var queue: DispatchQueue?
if #available(OSX 10.10, iOS 8.0, *) {
queue = DispatchQueue.global(qos: .background)
} else {
queue = DispatchQueue.global(priority: .background)
}
queue!.async {
self._thread()
}
}
internal func _thread() {
print("_ForkJoinWorkerThread begin")
_tid = _stdlib_pthread_self()
outer: while !_workDeque.isEmpty || !_submissionQueue.isEmpty {
_pool._addRunningThread(self)
while true {
if _pool._tryStopThread() {
print("_ForkJoinWorkerThread detected too many threads")
_pool._removeRunningThread(self)
_pool._submitTasksToRandomWorkers(_workDeque.takeAll())
_pool._submitTasksToRandomWorkers(_submissionQueue.takeAll())
print("_ForkJoinWorkerThread end")
return
}
// Process tasks in FIFO order: first the work queue, then the
// submission queue.
if let task = _workDeque.tryTakeFirst() {
task._run()
continue
}
if let task = _submissionQueue.tryTakeFirst() {
task._run()
continue
}
print("_ForkJoinWorkerThread stealing tasks")
if let task = _pool._stealTask() {
task._run()
continue
}
// FIXME: steal from submission queues?
break
}
_pool._removeRunningThread(self)
}
assert(_workDeque.isEmpty)
assert(_submissionQueue.isEmpty)
_ = _pool._totalThreads.fetchAndAdd(-1)
print("_ForkJoinWorkerThread end")
}
internal func _forkTask(_ task: ForkJoinTaskBase) {
// Try to inflate the pool.
if !_pool._tryCreateThread({ task }) {
_workDeque.prepend(task)
}
}
internal func _waitForTask(_ task: ForkJoinTaskBase) {
while true {
if task._isComplete() {
return
}
// If the task is in work queue of the current thread, run the task.
if _workDeque.tryReplace(
task,
makeReplacement: { ForkJoinTask<()>() {} },
isEquivalent: { $0 === $1 }) {
// We found the task. Run it in-place.
task._run()
return
}
// FIXME: also check the submission queue, maybe the task is there?
// FIXME: try to find the task in other threads' queues.
// FIXME: try to find tasks that were forked from this task in other
// threads' queues. Help thieves by stealing those tasks back.
// At this point, we can't do any work to help with running this task.
// We can't start new work either (if we do, we might end up creating
// more in-flight work than we can chew, and crash with out-of-memory
// errors).
_pool._compensateForBlockedWorkerThread() {
task._blockingWait()
// FIXME: do a timed wait, and retry stealing.
}
}
}
}
internal protocol _Future {
associatedtype Result
/// Establishes a happens-before relation between completing the future and
/// the call to wait().
func wait()
func tryGetResult() -> Result?
func tryTakeResult() -> Result?
func waitAndGetResult() -> Result
func waitAndTakeResult() -> Result
}
public class ForkJoinTaskBase {
final internal var _pool: ForkJoinPool?
// FIXME(performance): there is no need to create heavy-weight
// synchronization primitives every time. We could start with a lightweight
// atomic int for the flag and inflate to a full event when needed. Unless
// we really need to block in wait(), we would avoid creating an event.
final internal let _completedEvent: _ForkJoinOneShotEvent =
_ForkJoinOneShotEvent()
final internal func _isComplete() -> Bool {
return _completedEvent.isSet()
}
final internal func _blockingWait() {
_completedEvent.wait()
}
internal func _run() {
fatalError("implement")
}
final public func fork() {
precondition(_pool == nil)
if let thread = ForkJoinPool._getCurrentThread() {
thread._forkTask(self)
} else {
// FIXME: decide if we want to allow this.
precondition(false)
ForkJoinPool.commonPool.forkTask(self)
}
}
final public func wait() {
if let thread = ForkJoinPool._getCurrentThread() {
thread._waitForTask(self)
} else {
_blockingWait()
}
}
}
final public class ForkJoinTask<Result> : ForkJoinTaskBase, _Future {
internal let _task: () -> Result
internal var _result: Result?
public init(_task: @escaping () -> Result) {
self._task = _task
}
override internal func _run() {
_complete(_task())
}
/// It is not allowed to call _complete() in a racy way. Only one thread
/// should ever call _complete().
internal func _complete(_ result: Result) {
precondition(!_completedEvent.isSet())
_result = result
_completedEvent.set()
}
public func tryGetResult() -> Result? {
if _completedEvent.isSet() {
return _result
}
return nil
}
public func tryTakeResult() -> Result? {
if _completedEvent.isSet() {
let result = _result
_result = nil
return result
}
return nil
}
public func waitAndGetResult() -> Result {
wait()
return tryGetResult()!
}
public func waitAndTakeResult() -> Result {
wait()
return tryTakeResult()!
}
}
final public class ForkJoinPool {
internal static var _threadRegistry: [_stdlib_pthread_t : _ForkJoinWorkerThread] = [:]
internal static var _threadRegistryMutex: _ForkJoinMutex = _ForkJoinMutex()
internal static func _getCurrentThread() -> _ForkJoinWorkerThread? {
return _threadRegistryMutex.withLock {
return _threadRegistry[_stdlib_pthread_self()]
}
}
internal let _maxThreads: Int
/// Total number of threads: number of running threads plus the number of
/// threads that are preparing to start).
internal let _totalThreads: _stdlib_AtomicInt = _stdlib_AtomicInt(0)
internal var _runningThreads: [_ForkJoinWorkerThread] = []
internal var _runningThreadsMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _submissionQueues: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _submissionQueuesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _workDeques: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _workDequesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal init(_commonPool: ()) {
self._maxThreads = _stdlib_getHardwareConcurrency()
}
deinit {
_runningThreadsMutex.`deinit`()
_submissionQueuesMutex.`deinit`()
_workDequesMutex.`deinit`()
}
internal func _addRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
ForkJoinPool._threadRegistry[thread._tid!] = thread
_runningThreads.append(thread)
_submissionQueues.append(thread._submissionQueue)
_workDeques.append(thread._workDeque)
}
}
}
}
}
internal func _removeRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
let i = _runningThreads.index { $0 === thread }!
ForkJoinPool._threadRegistry[thread._tid!] = nil
_runningThreads.remove(at: i)
_submissionQueues.remove(at: i)
_workDeques.remove(at: i)
}
}
}
}
}
internal func _compensateForBlockedWorkerThread(_ blockingBody: @escaping () -> ()) {
// FIXME: limit the number of compensating threads.
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
blockingBody()
_ = _totalThreads.fetchAndAdd(1)
}
internal func _tryCreateThread(
_ makeTask: () -> ForkJoinTaskBase?
) -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
if oldNumThreads >= _maxThreads {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads + 1)
} while !success
if let task = makeTask() {
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
workDeque.prepend(task)
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
} else {
_ = _totalThreads.fetchAndAdd(-1)
}
return true
}
internal func _stealTask() -> ForkJoinTaskBase? {
return _workDequesMutex.withLock {
let randomOffset = pickRandom(_workDeques.indices)
let count = _workDeques.count
for i in _workDeques.indices {
let index = (i + randomOffset) % count
if let task = _workDeques[index].tryTakeLast() {
return task
}
}
return nil
}
}
/// Check if the pool has grown too large because of compensating
/// threads.
internal func _tryStopThread() -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
// FIXME: magic number 2.
if oldNumThreads <= _maxThreads + 2 {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads - 1)
} while !success
return true
}
internal func _submitTasksToRandomWorkers<
C : Collection
>(_ tasks: C)
where C.Iterator.Element == ForkJoinTaskBase {
if tasks.isEmpty {
return
}
_submissionQueuesMutex.withLock {
precondition(!_submissionQueues.isEmpty)
for task in tasks {
pickRandom(_submissionQueues).append(task)
}
}
}
public func forkTask(_ task: ForkJoinTaskBase) {
while true {
// Try to inflate the pool first.
if _tryCreateThread({ task }) {
return
}
// Looks like we can't create more threads. Submit the task to
// a random thread.
let done = _submissionQueuesMutex.withLock {
() -> Bool in
if !_submissionQueues.isEmpty {
pickRandom(_submissionQueues).append(task)
return true
}
return false
}
if done {
return
}
}
}
// FIXME: return a Future instead?
public func forkTask<Result>(task: @escaping () -> Result) -> ForkJoinTask<Result> {
let forkJoinTask = ForkJoinTask(_task: task)
forkTask(forkJoinTask)
return forkJoinTask
}
public static var commonPool = ForkJoinPool(_commonPool: ())
public static func invokeAll(_ tasks: ForkJoinTaskBase...) {
ForkJoinPool.invokeAll(tasks)
}
public static func invokeAll(_ tasks: [ForkJoinTaskBase]) {
if tasks.isEmpty {
return
}
if ForkJoinPool._getCurrentThread() != nil {
// Run the first task in this thread, fork the rest.
let first = tasks.first
for t in tasks.dropFirst() {
// FIXME: optimize forking in bulk.
t.fork()
}
first!._run()
} else {
// FIXME: decide if we want to allow this.
precondition(false)
}
}
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: implementation
//===----------------------------------------------------------------------===//
internal protocol _CollectionTransformerStepProtocol /*: class*/ {
associatedtype PipelineInputElement
associatedtype OutputElement
func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
}
internal class _CollectionTransformerStep<PipelineInputElement_, OutputElement_>
: _CollectionTransformerStepProtocol {
typealias PipelineInputElement = PipelineInputElement_
typealias OutputElement = OutputElement_
func map<U>(_ transform: @escaping (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
fatalError("abstract method")
}
func filter(_ isIncluded: @escaping (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
fatalError("abstract method")
}
func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
fatalError("abstract method")
}
func collectTo<
C : BuildableCollectionProtocol
>(_: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
fatalError("abstract method")
}
func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
fatalError("abstract method")
}
}
final internal class _CollectionTransformerStepCollectionSource<
PipelineInputElement
> : _CollectionTransformerStep<PipelineInputElement, PipelineInputElement> {
typealias InputElement = PipelineInputElement
override func map<U>(_ transform: @escaping (InputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
return _CollectionTransformerStepOneToMaybeOne(self) {
transform($0)
}
}
override func filter(_ isIncluded: @escaping (InputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, InputElement> {
return _CollectionTransformerStepOneToMaybeOne(self) {
isIncluded($0) ? $0 : nil
}
}
override func reduce<U>(_ initial: U, _ combine: @escaping (U, InputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
var i = range.lowerBound
while i != range.upperBound {
let e = c[i]
collector.append(e)
c.formIndex(after: &i)
}
}
}
final internal class _CollectionTransformerStepOneToMaybeOne<
PipelineInputElement,
OutputElement,
InputStep : _CollectionTransformerStepProtocol
> : _CollectionTransformerStep<PipelineInputElement, OutputElement>
where InputStep.PipelineInputElement == PipelineInputElement {
typealias _Self = _CollectionTransformerStepOneToMaybeOne
typealias InputElement = InputStep.OutputElement
let _input: InputStep
let _transform: (InputElement) -> OutputElement?
init(_ input: InputStep, _ transform: @escaping (InputElement) -> OutputElement?) {
self._input = input
self._transform = transform
super.init()
}
override func map<U>(_ transform: @escaping (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, U, InputStep>(_input) {
(input: InputElement) -> U? in
if let e = localTransform(input) {
return transform(e)
}
return nil
}
}
override func filter(_ isIncluded: @escaping (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, OutputElement, InputStep>(_input) {
(input: InputElement) -> OutputElement? in
if let e = localTransform(input) {
return isIncluded(e) ? e : nil
}
return nil
}
}
override func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
var collectorWrapper =
_ElementCollectorOneToMaybeOne(collector, _transform)
_input.transform(c, range, &collectorWrapper)
collector = collectorWrapper._baseCollector
}
}
struct _ElementCollectorOneToMaybeOne<
BaseCollector : _ElementCollector,
Element_
> : _ElementCollector {
typealias Element = Element_
var _baseCollector: BaseCollector
var _transform: (Element) -> BaseCollector.Element?
init(
_ baseCollector: BaseCollector,
_ transform: @escaping (Element) -> BaseCollector.Element?
) {
self._baseCollector = baseCollector
self._transform = transform
}
mutating func sizeHint(_ approximateSize: Int) {}
mutating func append(_ element: Element) {
if let e = _transform(element) {
_baseCollector.append(e)
}
}
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element {
for e in elements {
append(e)
}
}
}
protocol _ElementCollector {
associatedtype Element
mutating func sizeHint(_ approximateSize: Int)
mutating func append(_ element: Element)
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element
}
class _CollectionTransformerFinalizer<PipelineInputElement, Result> {
func transform<
InputCollection : Collection
>(_ c: InputCollection) -> Result
where InputCollection.Iterator.Element == PipelineInputElement {
fatalError("implement")
}
}
final class _CollectionTransformerFinalizerReduce<
PipelineInputElement,
U,
InputElementTy,
InputStep : _CollectionTransformerStepProtocol
> : _CollectionTransformerFinalizer<PipelineInputElement, U>
where
InputStep.OutputElement == InputElementTy,
InputStep.PipelineInputElement == PipelineInputElement {
var _input: InputStep
var _initial: U
var _combine: (U, InputElementTy) -> U
init(_ input: InputStep, _ initial: U, _ combine: @escaping (U, InputElementTy) -> U) {
self._input = input
self._initial = initial
self._combine = combine
}
override func transform<
InputCollection : Collection
>(_ c: InputCollection) -> U
where InputCollection.Iterator.Element == PipelineInputElement {
var collector = _ElementCollectorReduce(_initial, _combine)
_input.transform(c, c.startIndex..<c.endIndex, &collector)
return collector.takeResult()
}
}
struct _ElementCollectorReduce<Element_, Result> : _ElementCollector {
typealias Element = Element_
var _current: Result
var _combine: (Result, Element) -> Result
init(_ initial: Result, _ combine: @escaping (Result, Element) -> Result) {
self._current = initial
self._combine = combine
}
mutating func sizeHint(_ approximateSize: Int) {}
mutating func append(_ element: Element) {
_current = _combine(_current, element)
}
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element {
for e in elements {
append(e)
}
}
mutating func takeResult() -> Result {
return _current
}
}
final class _CollectionTransformerFinalizerCollectTo<
PipelineInputElement,
U : BuildableCollectionProtocol,
InputElementTy,
InputStep : _CollectionTransformerStepProtocol
> : _CollectionTransformerFinalizer<PipelineInputElement, U>
where
InputStep.OutputElement == InputElementTy,
InputStep.PipelineInputElement == PipelineInputElement,
U.Builder.Destination == U,
U.Builder.Element == U.Iterator.Element,
U.Iterator.Element == InputStep.OutputElement {
var _input: InputStep
init(_ input: InputStep, _: U.Type) {
self._input = input
}
override func transform<
InputCollection : Collection
>(_ c: InputCollection) -> U
where InputCollection.Iterator.Element == PipelineInputElement {
var collector = _ElementCollectorCollectTo<U>()
_input.transform(c, c.startIndex..<c.endIndex, &collector)
return collector.takeResult()
}
}
struct _ElementCollectorCollectTo<
BuildableCollection : BuildableCollectionProtocol
> : _ElementCollector
where
BuildableCollection.Builder.Destination == BuildableCollection,
BuildableCollection.Builder.Element == BuildableCollection.Iterator.Element {
typealias Element = BuildableCollection.Iterator.Element
var _builder: BuildableCollection.Builder
init() {
self._builder = BuildableCollection.Builder()
}
mutating func sizeHint(_ approximateSize: Int) {
_builder.sizeHint(approximateSize)
}
mutating func append(_ element: Element) {
_builder.append(element)
}
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element {
_builder.append(contentsOf: elements)
}
mutating func takeResult() -> BuildableCollection {
return _builder.takeResult()
}
}
internal func _optimizeCollectionTransformer<PipelineInputElement, Result>(
_ transformer: _CollectionTransformerFinalizer<PipelineInputElement, Result>
) -> _CollectionTransformerFinalizer<PipelineInputElement, Result> {
return transformer
}
internal func _runCollectionTransformer<
InputCollection : Collection, Result
>(
_ c: InputCollection,
_ transformer: _CollectionTransformerFinalizer<InputCollection.Iterator.Element, Result>
) -> Result {
dump(transformer)
let optimized = _optimizeCollectionTransformer(transformer)
dump(optimized)
return transformer.transform(c)
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: public interface
//===----------------------------------------------------------------------===//
public struct CollectionTransformerPipeline<
InputCollection : Collection, T
> {
internal var _input: InputCollection
internal var _step: _CollectionTransformerStep<InputCollection.Iterator.Element, T>
public func map<U>(_ transform: @escaping (T) -> U)
-> CollectionTransformerPipeline<InputCollection, U> {
return CollectionTransformerPipeline<InputCollection, U>(
_input: _input,
_step: _step.map(transform)
)
}
public func filter(_ isIncluded: @escaping (T) -> Bool)
-> CollectionTransformerPipeline<InputCollection, T> {
return CollectionTransformerPipeline<InputCollection, T>(
_input: _input,
_step: _step.filter(isIncluded)
)
}
public func reduce<U>(
_ initial: U, _ combine: @escaping (U, T) -> U
) -> U {
return _runCollectionTransformer(_input, _step.reduce(initial, combine))
}
public func collectTo<
C : BuildableCollectionProtocol
>(_ c: C.Type) -> C
where
C.Builder.Destination == C,
C.Iterator.Element == T,
C.Builder.Element == T {
return _runCollectionTransformer(_input, _step.collectTo(c))
}
public func toArray() -> [T] {
return collectTo(Array<T>.self)
}
}
public func transform<C : Collection>(_ c: C)
-> CollectionTransformerPipeline<C, C.Iterator.Element> {
return CollectionTransformerPipeline<C, C.Iterator.Element>(
_input: c,
_step: _CollectionTransformerStepCollectionSource<C.Iterator.Element>())
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: tests
//===----------------------------------------------------------------------===//
import StdlibUnittest
var t = TestSuite("t")
t.test("fusion/map+reduce") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.reduce(0, { $0 + $1 })
expectEqual(12, result)
}
t.test("fusion/map+filter+reduce") {
let xs = [ 1, 2, 3 ]
let result = transform(xs)
.map { $0 * 2 }
.filter { $0 != 0 }
.reduce(0, { $0 + $1 })
expectEqual(12, result)
}
t.test("fusion/map+collectTo") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.collectTo(Array<Int>.self)
expectEqual([ 2, 4, 6 ], result)
}
t.test("fusion/map+toArray") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.toArray()
expectEqual([ 2, 4, 6 ], result)
}
t.test("ForkJoinPool.forkTask") {
var tasks: [ForkJoinTask<()>] = []
for i in 0..<100 {
tasks.append(ForkJoinPool.commonPool.forkTask {
() -> () in
var result = 1
for i in 0..<10000 {
result = result &* i
_blackHole(result)
}
return ()
})
}
for t in tasks {
t.wait()
}
}
func fib(_ n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
if n == 38 {
print("\(pthread_self()) fib(\(n))")
}
if n < 39 {
let r = fib(n - 1) + fib(n - 2)
_blackHole(r)
return r
}
print("fib(\(n))")
let t1 = ForkJoinTask() { fib(n - 1) }
let t2 = ForkJoinTask() { fib(n - 2) }
ForkJoinPool.invokeAll(t1, t2)
return t2.waitAndGetResult() + t1.waitAndGetResult()
}
t.test("ForkJoinPool.forkTask/Fibonacci") {
let t = ForkJoinPool.commonPool.forkTask { fib(40) }
expectEqual(102334155, t.waitAndGetResult())
}
func _parallelMap(_ input: [Int], transform: @escaping (Int) -> Int, range: Range<Int>)
-> Array<Int>.Builder {
var builder = Array<Int>.Builder()
if range.count < 1_000 {
builder.append(contentsOf: input[range].map(transform))
} else {
let tasks = input.split(range).map {
(subRange) in
ForkJoinTask<Array<Int>.Builder> {
_parallelMap(input, transform: transform, range: subRange)
}
}
ForkJoinPool.invokeAll(tasks)
for t in tasks {
var otherBuilder = t.waitAndGetResult()
builder.moveContentsOf(&otherBuilder)
}
}
return builder
}
func parallelMap(_ input: [Int], transform: @escaping (Int) -> Int) -> [Int] {
let t = ForkJoinPool.commonPool.forkTask {
_parallelMap(
input,
transform: transform,
range: input.startIndex..<input.endIndex)
}
var builder = t.waitAndGetResult()
return builder.takeResult()
}
t.test("ForkJoinPool.forkTask/MapArray") {
expectEqual(
Array(2..<1_001),
parallelMap(Array(1..<1_000)) { $0 + 1 }
)
}
/*
* FIXME: reduce compiler crasher
t.test("ForkJoinPool.forkTask") {
func fib(_ n: Int) -> Int {
if n == 0 || n == 1 {
return 1
}
let t1 = ForkJoinPool.commonPool.forkTask { fib(n - 1) }
let t2 = ForkJoinPool.commonPool.forkTask { fib(n - 2) }
return t2.waitAndGetResult() + t1.waitAndGetResult()
}
expectEqual(0, fib(10))
}
*/
/*
Useful links:
http://habrahabr.ru/post/255659/
*/
runAllTests()
|
c3a8563b113a95578d1a92b22a567b40
| 26.112414 | 108 | 0.65355 | false | false | false | false |
vector-im/vector-ios
|
refs/heads/master
|
Riot/Modules/SplitView/SplitViewUserIndicatorPresentationContext.swift
|
apache-2.0
|
1
|
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import CommonKit
class SplitViewUserIndicatorPresentationContext: UserIndicatorPresentationContext {
private weak var splitViewController: UISplitViewController?
private weak var tabBarCoordinator: TabBarCoordinator?
private weak var detailNavigationController: UINavigationController?
init(
splitViewController: UISplitViewController,
tabBarCoordinator: TabBarCoordinator,
detailNavigationController: UINavigationController
) {
self.splitViewController = splitViewController
self.tabBarCoordinator = tabBarCoordinator
self.detailNavigationController = detailNavigationController
}
var indicatorPresentingViewController: UIViewController? {
guard
let splitViewController = splitViewController,
let tabBarCoordinator = tabBarCoordinator,
let detailNavigationController = detailNavigationController
else {
MXLog.debug("[SplitViewCoordinator]: Missing tab bar or detail coordinator, cannot update user indicator presenter")
return nil
}
return splitViewController.isCollapsed ? tabBarCoordinator.toPresentable() : detailNavigationController
}
}
|
f671aaaa91492db5976e3fad7ef079c9
| 38.956522 | 128 | 0.743743 | false | false | false | false |
FTChinese/iPhoneApp
|
refs/heads/master
|
A2bigSDK/Element.swift
|
apache-2.0
|
8
|
//
// Element.swift
//
// Copyright (c) 2014-2016 Marko Tadić <[email protected]> http://tadija.net
//
// 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
/**
This is base class for holding XML structure.
You can access its structure by using subscript like this: `element["foo"]["bar"]` which would
return `<bar></bar>` element from `<element><foo><bar></bar></foo></element>` XML as an `AEXMLElement` object.
*/
open class AEXMLElement {
// MARK: - Properties
/// Every `AEXMLElement` should have its parent element instead of `AEXMLDocument` which parent is `nil`.
open internal(set) weak var parent: AEXMLElement?
/// Child XML elements.
open internal(set) var children = [AEXMLElement]()
/// XML Element name.
open var name: String
/// XML Element value.
open var value: String?
/// XML Element attributes.
open var attributes: [String : String]
/// Error value (`nil` if there is no error).
open var error: AEXMLError?
/// String representation of `value` property (if `value` is `nil` this is empty String).
open var string: String { return value ?? String() }
/// Boolean representation of `value` property (if `value` is "true" or 1 this is `True`, otherwise `False`).
open var bool: Bool { return string.lowercased() == "true" || Int(string) == 1 ? true : false }
/// Integer representation of `value` property (this is **0** if `value` can't be represented as Integer).
open var int: Int { return Int(string) ?? 0 }
/// Double representation of `value` property (this is **0.00** if `value` can't be represented as Double).
open var double: Double { return Double(string) ?? 0.00 }
// MARK: - Lifecycle
/**
Designated initializer - all parameters are optional.
- parameter name: XML element name.
- parameter value: XML element value (defaults to `nil`).
- parameter attributes: XML element attributes (defaults to empty dictionary).
- returns: An initialized `AEXMLElement` object.
*/
public init(name: String, value: String? = nil, attributes: [String : String] = [String : String]()) {
self.name = name
self.value = value
self.attributes = attributes
}
// MARK: - XML Read
/// The first element with given name **(Empty element with error if not exists)**.
open subscript(key: String) -> AEXMLElement {
guard let
first = children.filter({ $0.name == key }).first
else {
let errorElement = AEXMLElement(name: key)
errorElement.error = AEXMLError.elementNotFound
return errorElement
}
return first
}
/// Returns all of the elements with equal name as `self` **(nil if not exists)**.
open var all: [AEXMLElement]? { return parent?.children.filter { $0.name == self.name } }
/// Returns the first element with equal name as `self` **(nil if not exists)**.
open var first: AEXMLElement? { return all?.first }
/// Returns the last element with equal name as `self` **(nil if not exists)**.
open var last: AEXMLElement? { return all?.last }
/// Returns number of all elements with equal name as `self`.
open var count: Int { return all?.count ?? 0 }
fileprivate func filter(withCondition condition: (AEXMLElement) -> Bool) -> [AEXMLElement]? {
guard let elements = all else { return nil }
var found = [AEXMLElement]()
for element in elements {
if condition(element) {
found.append(element)
}
}
return found.count > 0 ? found : nil
}
/**
Returns all elements with given value.
- parameter value: XML element value.
- returns: Optional Array of found XML elements.
*/
open func all(withValue value: String) -> [AEXMLElement]? {
let found = filter { (element) -> Bool in
return element.value == value
}
return found
}
/**
Returns all elements with given attributes.
- parameter attributes: Dictionary of Keys and Values of attributes.
- returns: Optional Array of found XML elements.
*/
open func all(withAttributes attributes: [String : String]) -> [AEXMLElement]? {
let found = filter { (element) -> Bool in
var countAttributes = 0
for (key, value) in attributes {
if element.attributes[key] == value {
countAttributes += 1
}
}
return countAttributes == attributes.count
}
return found
}
// MARK: - XML Write
/**
Adds child XML element to `self`.
- parameter child: Child XML element to add.
- returns: Child XML element with `self` as `parent`.
*/
@discardableResult open func addChild(_ child: AEXMLElement) -> AEXMLElement {
child.parent = self
children.append(child)
return child
}
/**
Adds child XML element to `self`.
- parameter name: Child XML element name.
- parameter value: Child XML element value (defaults to `nil`).
- parameter attributes: Child XML element attributes (defaults to empty dictionary).
- returns: Child XML element with `self` as `parent`.
*/
@discardableResult open func addChild(name: String,
value: String? = nil,
attributes: [String : String] = [String : String]()) -> AEXMLElement
{
let child = AEXMLElement(name: name, value: value, attributes: attributes)
return addChild(child)
}
/// Removes `self` from `parent` XML element.
open func removeFromParent() {
parent?.removeChild(self)
}
fileprivate func removeChild(_ child: AEXMLElement) {
if let childIndex = children.index(where: { $0 === child }) {
children.remove(at: childIndex)
}
}
fileprivate var parentsCount: Int {
var count = 0
var element = self
while let parent = element.parent {
count += 1
element = parent
}
return count
}
fileprivate func indent(withDepth depth: Int) -> String {
var count = depth
var indent = String()
while count > 0 {
indent += "\t"
count -= 1
}
return indent
}
/// Complete hierarchy of `self` and `children` in **XML** escaped and formatted String
open var xml: String {
var xml = String()
// open element
xml += indent(withDepth: parentsCount - 1)
xml += "<\(name)"
if attributes.count > 0 {
// insert attributes
for (key, value) in attributes {
xml += " \(key)=\"\(value.xmlEscaped)\""
}
}
if value == nil && children.count == 0 {
// close element
xml += " />"
} else {
if children.count > 0 {
// add children
xml += ">\n"
for child in children {
xml += "\(child.xml)\n"
}
// add indentation
xml += indent(withDepth: parentsCount - 1)
xml += "</\(name)>"
} else {
// insert string value and close element
xml += ">\(string.xmlEscaped)</\(name)>"
}
}
return xml
}
/// Same as `xmlString` but without `\n` and `\t` characters
open var xmlCompact: String {
let chars = CharacterSet(charactersIn: "\n\t")
return xml.components(separatedBy: chars).joined(separator: "")
}
}
public extension String {
/// String representation of self with XML special characters escaped.
public var xmlEscaped: String {
// we need to make sure "&" is escaped first. Not doing this may break escaping the other characters
var escaped = replacingOccurrences(of: "&", with: "&", options: .literal)
// replace the other four special characters
let escapeChars = ["<" : "<", ">" : ">", "'" : "'", "\"" : """]
for (char, echar) in escapeChars {
escaped = escaped.replacingOccurrences(of: char, with: echar, options: .literal)
}
return escaped
}
}
|
de89c69cf0b77dcfe2e0b7a72ecb75ed
| 33.224561 | 114 | 0.578634 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.