repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
patr1ck/SQLite.swift
|
SQLite/Typed/CoreFunctions.swift
|
3
|
24621
|
//
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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.NSData
extension ExpressionType where UnderlyingType : Number {
/// Builds a copy of the expression wrapped with the `abs` function.
///
/// let x = Expression<Int>("x")
/// x.absoluteValue
/// // abs("x")
///
/// - Returns: A copy of the expression wrapped with the `abs` function.
public var absoluteValue : Expression<UnderlyingType> {
return "abs".wrap(self)
}
}
extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Number {
/// Builds a copy of the expression wrapped with the `abs` function.
///
/// let x = Expression<Int?>("x")
/// x.absoluteValue
/// // abs("x")
///
/// - Returns: A copy of the expression wrapped with the `abs` function.
public var absoluteValue : Expression<UnderlyingType> {
return "abs".wrap(self)
}
}
extension ExpressionType where UnderlyingType == Double {
/// Builds a copy of the expression wrapped with the `round` function.
///
/// let salary = Expression<Double>("salary")
/// salary.round()
/// // round("salary")
/// salary.round(2)
/// // round("salary", 2)
///
/// - Returns: A copy of the expression wrapped with the `round` function.
@warn_unused_result public func round(precision: Int? = nil) -> Expression<UnderlyingType> {
guard let precision = precision else {
return wrap([self])
}
return wrap([self, Int(precision)])
}
}
extension ExpressionType where UnderlyingType == Double? {
/// Builds a copy of the expression wrapped with the `round` function.
///
/// let salary = Expression<Double>("salary")
/// salary.round()
/// // round("salary")
/// salary.round(2)
/// // round("salary", 2)
///
/// - Returns: A copy of the expression wrapped with the `round` function.
@warn_unused_result public func round(precision: Int? = nil) -> Expression<UnderlyingType> {
guard let precision = precision else {
return wrap(self)
}
return wrap([self, Int(precision)])
}
}
extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype == Int64 {
/// Builds an expression representing the `random` function.
///
/// Expression<Int>.random()
/// // random()
///
/// - Returns: An expression calling the `random` function.
@warn_unused_result public static func random() -> Expression<UnderlyingType> {
return "random".wrap([])
}
}
extension ExpressionType where UnderlyingType == NSData {
/// Builds an expression representing the `randomblob` function.
///
/// Expression<Int>.random(16)
/// // randomblob(16)
///
/// - Parameter length: Length in bytes.
///
/// - Returns: An expression calling the `randomblob` function.
@warn_unused_result public static func random(length: Int) -> Expression<UnderlyingType> {
return "randomblob".wrap([])
}
/// Builds an expression representing the `zeroblob` function.
///
/// Expression<Int>.allZeros(16)
/// // zeroblob(16)
///
/// - Parameter length: Length in bytes.
///
/// - Returns: An expression calling the `zeroblob` function.
@warn_unused_result public static func allZeros(length: Int) -> Expression<UnderlyingType> {
return "zeroblob".wrap([])
}
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let data = Expression<NSData>("data")
/// data.length
/// // length("data")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int> {
return wrap(self)
}
}
extension ExpressionType where UnderlyingType == NSData? {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let data = Expression<NSData?>("data")
/// data.length
/// // length("data")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int?> {
return wrap(self)
}
}
extension ExpressionType where UnderlyingType == String {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let name = Expression<String>("name")
/// name.length
/// // length("name")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int> {
return wrap(self)
}
/// Builds a copy of the expression wrapped with the `lower` function.
///
/// let name = Expression<String>("name")
/// name.lowercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `lower` function.
public var lowercaseString: Expression<UnderlyingType> {
return "lower".wrap(self)
}
/// Builds a copy of the expression wrapped with the `upper` function.
///
/// let name = Expression<String>("name")
/// name.uppercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `upper` function.
public var uppercaseString: Expression<UnderlyingType> {
return "upper".wrap(self)
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// email.like("%@example.com")
/// // "email" LIKE '%@example.com'
/// email.like("99\\%@%", escape: "\\")
/// // "email" LIKE '99\%@%' ESCAPE '\'
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
@warn_unused_result public func like(pattern: String, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}
/// Builds a copy of the expression appended with a `GLOB` query against the
/// given pattern.
///
/// let path = Expression<String>("path")
/// path.glob("*.png")
/// // "path" GLOB '*.png'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `GLOB` query against
/// the given pattern.
@warn_unused_result public func glob(pattern: String) -> Expression<Bool> {
return "GLOB".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `MATCH` query against
/// the given pattern.
///
/// let title = Expression<String>("title")
/// title.match("swift AND programming")
/// // "title" MATCH 'swift AND programming'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `MATCH` query
/// against the given pattern.
@warn_unused_result public func match(pattern: String) -> Expression<Bool> {
return "MATCH".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `REGEXP` query against
/// the given pattern.
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `REGEXP` query
/// against the given pattern.
@warn_unused_result public func regexp(pattern: String) -> Expression<Bool> {
return "REGEXP".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `COLLATE` clause with
/// the given sequence.
///
/// let name = Expression<String>("name")
/// name.collate(.Nocase)
/// // "name" COLLATE NOCASE
///
/// - Parameter collation: A collating sequence.
///
/// - Returns: A copy of the expression appended with a `COLLATE` clause
/// with the given sequence.
@warn_unused_result public func collate(collation: Collation) -> Expression<UnderlyingType> {
return "COLLATE".infix(self, collation)
}
/// Builds a copy of the expression wrapped with the `ltrim` function.
///
/// let name = Expression<String>("name")
/// name.ltrim()
/// // ltrim("name")
/// name.ltrim([" ", "\t"])
/// // ltrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `ltrim` function.
@warn_unused_result public func ltrim(characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `rtrim` function.
///
/// let name = Expression<String>("name")
/// name.rtrim()
/// // rtrim("name")
/// name.rtrim([" ", "\t"])
/// // rtrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `rtrim` function.
@warn_unused_result public func rtrim(characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `trim` function.
///
/// let name = Expression<String>("name")
/// name.trim()
/// // trim("name")
/// name.trim([" ", "\t"])
/// // trim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `trim` function.
@warn_unused_result public func trim(characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap([self])
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `replace` function.
///
/// let email = Expression<String>("email")
/// email.replace("@mac.com", with: "@icloud.com")
/// // replace("email", '@mac.com', '@icloud.com')
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - replacement: The replacement string.
///
/// - Returns: A copy of the expression wrapped with the `replace` function.
@warn_unused_result public func replace(pattern: String, with replacement: String) -> Expression<UnderlyingType> {
return "replace".wrap([self, pattern, replacement])
}
@warn_unused_result public func substring(location: Int, length: Int? = nil) -> Expression<UnderlyingType> {
guard let length = length else {
return "substr".wrap([self, location])
}
return "substr".wrap([self, location, length])
}
public subscript(range: Range<Int>) -> Expression<UnderlyingType> {
return substring(range.startIndex, length: range.endIndex - range.startIndex)
}
}
extension ExpressionType where UnderlyingType == String? {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let name = Expression<String?>("name")
/// name.length
/// // length("name")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int?> {
return wrap(self)
}
/// Builds a copy of the expression wrapped with the `lower` function.
///
/// let name = Expression<String?>("name")
/// name.lowercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `lower` function.
public var lowercaseString: Expression<UnderlyingType> {
return "lower".wrap(self)
}
/// Builds a copy of the expression wrapped with the `upper` function.
///
/// let name = Expression<String?>("name")
/// name.uppercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `upper` function.
public var uppercaseString: Expression<UnderlyingType> {
return "upper".wrap(self)
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String?>("email")
/// email.like("%@example.com")
/// // "email" LIKE '%@example.com'
/// email.like("99\\%@%", escape: "\\")
/// // "email" LIKE '99\%@%' ESCAPE '\'
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
@warn_unused_result public func like(pattern: String, escape character: Character? = nil) -> Expression<Bool?> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}
/// Builds a copy of the expression appended with a `GLOB` query against the
/// given pattern.
///
/// let path = Expression<String?>("path")
/// path.glob("*.png")
/// // "path" GLOB '*.png'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `GLOB` query against
/// the given pattern.
@warn_unused_result public func glob(pattern: String) -> Expression<Bool?> {
return "GLOB".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `MATCH` query against
/// the given pattern.
///
/// let title = Expression<String?>("title")
/// title.match("swift AND programming")
/// // "title" MATCH 'swift AND programming'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `MATCH` query
/// against the given pattern.
@warn_unused_result public func match(pattern: String) -> Expression<Bool> {
return "MATCH".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `REGEXP` query against
/// the given pattern.
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `REGEXP` query
/// against the given pattern.
@warn_unused_result public func regexp(pattern: String) -> Expression<Bool?> {
return "REGEXP".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `COLLATE` clause with
/// the given sequence.
///
/// let name = Expression<String?>("name")
/// name.collate(.Nocase)
/// // "name" COLLATE NOCASE
///
/// - Parameter collation: A collating sequence.
///
/// - Returns: A copy of the expression appended with a `COLLATE` clause
/// with the given sequence.
@warn_unused_result public func collate(collation: Collation) -> Expression<UnderlyingType> {
return "COLLATE".infix(self, collation)
}
/// Builds a copy of the expression wrapped with the `ltrim` function.
///
/// let name = Expression<String?>("name")
/// name.ltrim()
/// // ltrim("name")
/// name.ltrim([" ", "\t"])
/// // ltrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `ltrim` function.
@warn_unused_result public func ltrim(characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `rtrim` function.
///
/// let name = Expression<String?>("name")
/// name.rtrim()
/// // rtrim("name")
/// name.rtrim([" ", "\t"])
/// // rtrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `rtrim` function.
@warn_unused_result public func rtrim(characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `trim` function.
///
/// let name = Expression<String?>("name")
/// name.trim()
/// // trim("name")
/// name.trim([" ", "\t"])
/// // trim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `trim` function.
@warn_unused_result public func trim(characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `replace` function.
///
/// let email = Expression<String?>("email")
/// email.replace("@mac.com", with: "@icloud.com")
/// // replace("email", '@mac.com', '@icloud.com')
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - replacement: The replacement string.
///
/// - Returns: A copy of the expression wrapped with the `replace` function.
@warn_unused_result public func replace(pattern: String, with replacement: String) -> Expression<UnderlyingType> {
return "replace".wrap([self, pattern, replacement])
}
/// Builds a copy of the expression wrapped with the `substr` function.
///
/// let title = Expression<String?>("title")
/// title.substr(-100)
/// // substr("title", -100)
/// title.substr(0, length: 100)
/// // substr("title", 0, 100)
///
/// - Parameters:
///
/// - location: The substring’s start index.
///
/// - length: An optional substring length.
///
/// - Returns: A copy of the expression wrapped with the `substr` function.
@warn_unused_result public func substring(location: Int, length: Int? = nil) -> Expression<UnderlyingType> {
guard let length = length else {
return "substr".wrap([self, location])
}
return "substr".wrap([self, location, length])
}
/// Builds a copy of the expression wrapped with the `substr` function.
///
/// let title = Expression<String?>("title")
/// title[0..<100]
/// // substr("title", 0, 100)
///
/// - Parameter range: The character index range of the substring.
///
/// - Returns: A copy of the expression wrapped with the `substr` function.
public subscript(range: Range<Int>) -> Expression<UnderlyingType> {
return substring(range.startIndex, length: range.endIndex - range.startIndex)
}
}
extension CollectionType where Generator.Element : Value, Index.Distance == Int {
/// Builds a copy of the expression prepended with an `IN` check against the
/// collection.
///
/// let name = Expression<String>("name")
/// ["alice", "betty"].contains(name)
/// // "name" IN ('alice', 'betty')
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression prepended with an `IN` check against
/// the collection.
@warn_unused_result public func contains(expression: Expression<Generator.Element>) -> Expression<Bool> {
let templates = [String](count: count, repeatedValue: "?").joinWithSeparator(", ")
return "IN".infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue }))
}
/// Builds a copy of the expression prepended with an `IN` check against the
/// collection.
///
/// let name = Expression<String?>("name")
/// ["alice", "betty"].contains(name)
/// // "name" IN ('alice', 'betty')
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression prepended with an `IN` check against
/// the collection.
@warn_unused_result public func contains(expression: Expression<Generator.Element?>) -> Expression<Bool?> {
let templates = [String](count: count, repeatedValue: "?").joinWithSeparator(", ")
return "IN".infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue }))
}
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let name = Expression<String?>("name")
/// name ?? "An Anonymous Coward"
/// // ifnull("name", 'An Anonymous Coward')
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback value for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: V) -> Expression<V> {
return "ifnull".wrap([optional, defaultValue])
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let nick = Expression<String?>("nick")
/// let name = Expression<String>("name")
/// nick ?? name
/// // ifnull("nick", "name")
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback expression for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: Expression<V>) -> Expression<V> {
return "ifnull".wrap([optional, defaultValue])
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let nick = Expression<String?>("nick")
/// let name = Expression<String?>("name")
/// nick ?? name
/// // ifnull("nick", "name")
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback expression for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: Expression<V?>) -> Expression<V> {
return "ifnull".wrap([optional, defaultValue])
}
|
mit
|
9f71ba62cd058cbe5c99ae66834985b6
| 35.043924 | 118 | 0.597043 | 4.264334 | false | false | false | false |
AngryLi/note-iOS
|
iOS/Demos/Assignments_swift/assignment-1-calculator/Calculator_assignment/Calculator/GraphViewController.swift
|
3
|
935
|
//
// GraphViewController.swift
// Calculator
//
// Created by 李亚洲 on 15/4/30.
// Copyright (c) 2015年 liyazhou. All rights reserved.
//
import Foundation
import UIKit
class GraphViewController: UIViewController, GraphViewDelegate
{
@IBOutlet weak var grapgView: GraphView! {
didSet {
grapgView.delegate = self
grapgView.setNeedsDisplay()
}
}
var brain : CalculatorBrain?
{
didSet
{
grapgView.setNeedsDisplay()
}
}
func graphView(graphView: GraphView, getValueFromX x: Float) -> Float {
if let variable = brain?.variableValues["M"]
{
if let result = brain?.pushOperandVariable(Double(x))
{
println("x=\(x) y=\(result)")
return Float(result)
}
}else
{
return 0
}
return 0
}
}
|
mit
|
c0dad39db3e456a3364bf2ae6a966384
| 22.175 | 75 | 0.533981 | 4.372642 | false | false | false | false |
johnpatrickmorgan/wtfautolayout
|
Sources/App/Models/Parser Models/Attribute.swift
|
1
|
4870
|
import Foundation
enum Attribute: String {
enum Axis: String {
case horizontal
case vertical
}
enum PinPoint {
case start
case end
case center
case extent
case firstBaseline
case lastBaseline
}
case leading
case trailing
case top
case bottom
case centerX
case centerY
case width
case height
case leadingMargin
case trailingMargin
case topMargin
case bottomMargin
case centerXWithinMargins
case centerYWithinMargins
case firstBaseline
case lastBaseline
static let allCases: [Attribute] = [
.leading,
.trailing,
.top,
.bottom,
.centerX,
.centerY,
.width,
.height,
.leadingMargin,
.trailingMargin,
.topMargin,
.bottomMargin,
.centerXWithinMargins,
.centerYWithinMargins,
.firstBaseline,
.lastBaseline,
]
var alternativeLabels: [String] {
switch self {
case .leading:
return ["left", "minX"]
case .trailing:
return ["right", "maxX"]
case .centerX:
return ["midX"]
case .centerY:
return ["midY"]
case .top:
return ["minY"]
case .bottom:
return ["maxY"]
case .leadingMargin:
return ["leftMargin", "minXMargin"]
case .trailingMargin:
return ["rightMargin", "maxXMargin"]
case .centerXWithinMargins:
return ["midXWithinMargins"]
case .centerYWithinMargins:
return ["midYWithinMargins"]
case .topMargin:
return ["minYMargin"]
case .bottomMargin:
return ["maxYMargin"]
case .lastBaseline:
return ["baseline"]
default:
return []
}
}
var labels: [String] {
return [rawValue] + alternativeLabels
}
init(axis: Axis, pinPoint: PinPoint, includesMargin: Bool = false) throws {
switch (pinPoint, axis, includesMargin) {
case (.start, .horizontal, false): self = .leading
case (.end, .horizontal, false): self = .trailing
case (.start, .vertical, false): self = .top
case (.end, .vertical, false): self = .bottom
case (.center, .horizontal, false): self = .centerX
case (.center, .vertical, false): self = .centerY
case (.extent, .horizontal, _): self = .width
case (.extent, .vertical, _): self = .height
case (.start, .horizontal, true): self = .leadingMargin
case (.end, .horizontal, true): self = .trailingMargin
case (.start, .vertical, true): self = .topMargin
case (.end, .vertical, true): self = .bottomMargin
case (.center, .horizontal, true): self = .centerXWithinMargins
case (.center, .vertical, true): self = .centerYWithinMargins
case (.firstBaseline, .vertical, _): self = .firstBaseline
case (.lastBaseline, .vertical, _): self = .lastBaseline
default:
throw InvalidConstraintError("\(axis) \(pinPoint)\(includesMargin ? "Margin" : "") is not a valid attribute")
}
}
private var info: (pinPoint: PinPoint, axis: Axis, includesMargin: Bool) {
switch self {
case .leading: return (.start, .horizontal, false)
case .trailing: return (.end, .horizontal, false)
case .top: return (.start, .vertical, false)
case .bottom: return (.end, .vertical, false)
case .centerX: return (.center, .horizontal, false)
case .centerY: return (.center, .vertical, false)
case .width: return (.extent, .horizontal, false)
case .height: return (.extent, .vertical, false)
case .leadingMargin: return (.start, .horizontal, true)
case .trailingMargin: return (.end, .horizontal, true)
case .topMargin: return (.start, .vertical, true)
case .bottomMargin: return (.end, .vertical, true)
case .centerXWithinMargins: return (.center, .horizontal, true)
case .centerYWithinMargins: return (.center, .vertical, true)
case .firstBaseline: return (.firstBaseline, .vertical, false)
case .lastBaseline: return (.lastBaseline, .vertical, false)
}
}
var pinPoint: PinPoint {
return info.pinPoint
}
var axis: Axis {
return info.axis
}
var includesMargin: Bool {
return info.includesMargin
}
}
|
mit
|
867ed80a169b70d666c0e29f3a7042b7
| 31.684564 | 121 | 0.539425 | 4.974464 | false | false | false | false |
smartystreets/smartystreets-ios-sdk
|
Sources/SmartyStreets/SmartySerializer.swift
|
1
|
1005
|
import Foundation
public class SmartySerializer: NSObject {
func Serialize(obj: Any?, error: inout NSError!) -> Data! {
return Data()
}
public func Deserialize(payload: Data?, error: inout NSError!) -> Any! {
let smartyErrors = SmartyErrors()
if payload == nil {
let details = [NSLocalizedDescriptionKey: "The payload is nil."]
error = NSError(domain: smartyErrors.SSErrorDomain, code: SmartyErrors.SSErrors.ObjectNilError.rawValue, userInfo: details)
return nil
}
do {
let result = try JSONSerialization.jsonObject(with: payload!, options: []) as? [String:Any]
return result
} catch let jsonError {
let details = [NSLocalizedDescriptionKey:jsonError.localizedDescription]
error = NSError(domain: smartyErrors.SSErrorDomain, code: SmartyErrors.SSErrors.ObjectInvalidTypeError.rawValue, userInfo: details)
return nil
}
}
}
|
apache-2.0
|
2a8a9abc1b864d4121871e7bea0cc497
| 39.2 | 143 | 0.635821 | 4.785714 | false | false | false | false |
rsyncOSX/RsyncOSX
|
RsyncOSX/ViewControllerInformation.swift
|
1
|
1719
|
//
// ViewControllerInformation.swift
// RsyncOSXver30
//
// Created by Thomas Evensen on 24/08/2016.
// Copyright © 2016 Thomas Evensen. All rights reserved.
//
// swiftlint:disable line_length force_cast
import Cocoa
import Foundation
class ViewControllerInformation: NSViewController, SetDismisser, OutPut {
@IBOutlet var detailsTable: NSTableView!
var output: [String]?
override func viewDidLoad() {
super.viewDidLoad()
detailsTable.delegate = self
detailsTable.dataSource = self
}
override func viewDidAppear() {
super.viewDidAppear()
output = getinfo()
globalMainQueue.async { () in
self.detailsTable.reloadData()
}
}
@IBAction func close(_: NSButton) {
dismissview(viewcontroller: self, vcontroller: .vctabmain)
}
@IBAction func pastetabeltomacospasteboard(_: NSButton) {
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
for i in 0 ..< (output?.count ?? 0) {
pasteboard.writeObjects([output?[i] as! NSPasteboardWriting])
}
}
}
extension ViewControllerInformation: NSTableViewDataSource {
func numberOfRows(in _: NSTableView) -> Int {
return output?.count ?? 0
}
}
extension ViewControllerInformation: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor _: NSTableColumn?, row: Int) -> NSView? {
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "outputID"), owner: nil) as? NSTableCellView {
cell.textField?.stringValue = output?[row] ?? ""
return cell
} else {
return nil
}
}
}
|
mit
|
45dee18d3d23eb6aa1a8d309c6ca5d60
| 27.633333 | 143 | 0.651921 | 4.706849 | false | false | false | false |
WestlakeAPC/game-off-2016
|
external/Fiber2D/Fiber2D/PhysicsShapeBox.swift
|
1
|
1468
|
//
// PhysicsShapeBox.swift
// Fiber2D
//
// Created by Andrey Volodin on 22.09.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
import SwiftMath
public class PhysicsShapeBox: PhysicsShapePolygon {
/**
* Get this box's width and height.
*
* @return An Size object.
*/
public var size: Size {
let shape = chipmunkShapes.first!
return Size(cpv(cpvdist(cpPolyShapeGetVert(shape, 1), cpPolyShapeGetVert(shape, 2)),
cpvdist(cpPolyShapeGetVert(shape, 0), cpPolyShapeGetVert(shape, 1))))
}
/**
* Creates a PhysicsShapeBox with specified value.
*
* @param size Size contains this box's width and height.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates.
* @return An autoreleased PhysicsShapeBox object pointer.
*/
init(size: Size, material: PhysicsMaterial = PhysicsMaterial.default, offset: Vector2f = Vector2f.zero, radius: Float = 0.0) {
let wh = size
let verts = [p2d(x: -wh.x/2.0, y: -wh.y/2.0),
p2d(x: -wh.x/2.0, y: wh.y/2.0),
p2d(x: wh.x/2.0, y: wh.y/2.0),
p2d(x: wh.x/2.0, y: -wh.y/2.0)]
super.init(points: verts, material: material, offset: offset, radius: radius)
}
}
|
apache-2.0
|
b6207666f260ad86e1ae87af504280c4
| 34.780488 | 130 | 0.607362 | 3.311512 | false | false | false | false |
digoreis/swift-proposal-analyzer
|
swift-proposal-analyzer.playground/Pages/SE-0004.xcplaygroundpage/Contents.swift
|
1
|
4363
|
/*:
# Remove the `++` and `--` operators
* Proposal: [SE-0004](0004-remove-pre-post-inc-decrement.md)
* Author: [Chris Lattner](https://github.com/lattner)
* Status: **Implemented (Swift 3)**
* Commit: [apple/swift@8e12008](https://github.com/apple/swift/commit/8e12008d2b34a605f8766310f53d5668f3d50955)
## Introduction
The increment/decrement operators in Swift were added very early in the
development of Swift, as a carry-over from C. These were added without much
consideration, and haven't been thought about much since then. This document
provides a fresh look at them, and ultimately recommends we just remove them
entirely, since they are confusing and not carrying their weight.
As a quick refresher, there are four operators in this family:
```swift
let a = ++x // pre-increment - returns input value after mutation
let b = x++ // post-increment - returns copy of input value before mutation
let c = --x // pre-decrement - returns input value after mutation
let d = x-- // post-decrement - returns copy of input value before mutation
```
However, the result value of these operators are frequently ignored.
## Advantages of These Operators
The primary advantage of these operators is their expressive capability. They
are shorthand for (e.g.) `x += 1` on a numeric type, or `x.advance()` on an
iterator-like value. When the return value is needed, the Swift `+=` operator
cannot be used in-line, since (unlike C) it returns `Void`.
The second advantage of Swift supporting this family of operators is continuity
with C, and other common languages in the extended C family (C++, Objective-C,
Java, C#, Javascript, etc). People coming to Swift from these other languages
may reasonably expect these operators to exist. That said, there are also
popular languages which have kept the majority of C operators but dropped these
(e.g. Python).
## Disadvantages of These Operators
1. These operators increase the burden to learn Swift as a first programming
language - or any other case where you don't already know these operators from a
different language.
2. Their expressive advantage is minimal - `x++` is not much shorter
than `x += 1`.
3. Swift already deviates from C in that the `=`, `+=` and other assignment-like
operations returns `Void` (for a number of reasons). These operators are
inconsistent with that model.
4. Swift has powerful features that eliminate many of the common reasons you'd
use `++i` in a C-style for loop in other languages, so these are relatively
infrequently used in well-written Swift code. These features include
the `for-in` loop, ranges, `enumerate`, `map`, etc.
5. Code that actually uses the result value of these operators is often
confusing and subtle to a reader/maintainer of code. They encourage "overly
tricky" code which may be cute, but difficult to understand.
6. While Swift has well defined order of evaluation, any code that depended on
it (like `foo(++a, a++)`) would be undesirable even if it was well-defined.
7. These operators are applicable to relatively few types: integer and floating
point scalars, and iterator-like concepts. They do not apply to complex numbers,
matrices, etc.
Finally, these fail the metric of "if we didn't already have these, would we add
them to Swift 3?"
## Proposed Approach
We should just drop these operators entirely. In terms of roll-out, we should
deprecate them in the Spring Swift 2.x release (with a nice Fixit hint to cover
common cases), and remove them completely in Swift 3.
## Alternatives considered
Simplest alternative: we could keep them. More interesting to consider, we could
change these operators to return Void. This solves some of the problems above,
but introduces a new question: once the result is gone, the difference between
the prefix and postfix form also vanishes. Given that, we would have to pick
between these unfortunate choices:
1) Keep both `x++` and `++x` in the language, even though they do the same
thing.
2) Drop one of `x++` or `++x`. C++ programmers generally prefer the prefix
forms, but everyone else generally prefers the postfix forms. Dropping either
one would be a significant deviation from C.
Despite considering these options carefully, they still don't justify the
complexity that the operators add to Swift.
----------
[Previous](@previous) | [Next](@next)
*/
|
mit
|
e8c6e9106e0403e648e65d73c5e27446
| 39.775701 | 111 | 0.758194 | 3.923561 | false | false | false | false |
zwaldowski/ParksAndRecreation
|
Swift-2/DispatchBlock.playground/Sources/DispatchBlock.swift
|
1
|
16632
|
import Dispatch
import Foundation
@available(OSX 10.10, iOS 8.0, *)
extension dispatch_block_flags_t: OptionSetType {
/// Flag indicating that a dispatch block should act as a barrier when
/// submitted to a concurrent dispatch queue, such that the queue delays
/// execution of the barrier block until all blocks submitted before the
/// barrier finish executing.
/// - note: This flag has no effect when the block is invoked directly.
/// - seealso: dispatch_barrier_async(_:_:)
public static let Barrier = DISPATCH_BLOCK_BARRIER
/// Flag indicating that a dispatch block should execute disassociated
/// from current execution context attributes such as QOS class.
///
/// - If invoked directly, the block object will remove these attributes
/// from the calling queue for the duration of the block.
/// - If submitted to a queue, the block object will be executed with the
/// attributes of the queue (or any attributes specifically assigned to
/// the dispatch block).
public static let DetachContext = DISPATCH_BLOCK_DETACHED
/// Flag indicating that a dispatch block should be assigned the execution
/// context attributes that are current at the time the block is created.
/// This applies to attributes such as QOS class.
///
/// - If invoked directly, the block will apply the attributes to the
/// calling queue for the duration of the block body.
/// - If the block object is submitted to a queue, this flag replaces the
/// default behavior of associating the submitted block instance with the
/// current execution context attributes at the time of submission.
///
/// If a specific QOS class is added or removed during block creation, that
/// QOS class takes precedence over the QOS class assignment indicated by
/// this flag.
/// - seealso: DispatchBlock.Flags.RemoveQOS
/// - seealso: DispatchBlock(flags:QOS:priority:body:)
public static let CurrentContext = DISPATCH_BLOCK_ASSIGN_CURRENT
/// Flag indicating that a dispatch block should be not be assigned a QOS
/// class.
///
/// - If invoked directly, the block object will be executed with the QOS
/// class of the calling queue.
/// - If the block is submitted to a queue, this replaces the default
/// behavior of associating the submitted block instance with the QOS
/// class current at the time of submission.
///
/// This flag is ignored if a specific QOS class is added during block
/// creation.
/// - seealso: DispatchBlock(flags:QOS:priority:body:)
public static let RemoveQOS = DISPATCH_BLOCK_NO_QOS_CLASS
/// Flag indicating that execution of a dispatch block submitted to a queue
/// should prefer the QOS class assigned to the queue over the QOS class
/// assigned during block creation. The latter will only be used if the
/// queue in question does not have an assigned QOS class, as long as doing
/// so does not result in a QOS class lower than the QOS class inherited
/// from the queue's target queue.
///
/// This flag is the default when a dispatch block is submitted to a queue
/// for asynchronous execution and has no effect when the dispatch block
/// is invoked directly.
/// - note: This flag is ignored if `EnforceQOS` is also passed.
/// - seealso: DispatchBlock.Flags.Enforce
public static let InheritQOS = DISPATCH_BLOCK_INHERIT_QOS_CLASS
/// Flag indicating that execution of a dispatch block submitted to a queue
/// should prefer the QOS class assigned to the block at the time of
/// submission over the QOS class assigned to the queue, as long as doing so
/// will not result in a lower QOS class.
///
/// This flag is the default when a dispatch block is submitted to a queue
/// for synchronous execution or when the dispatch block object is invoked
/// directly.
/// - seealso: dispatch_sync(_:_:)
public static let EnforceQOS = DISPATCH_BLOCK_ENFORCE_QOS_CLASS
}
/// A cancellable wrapper for a GCD block.
// Does some trickery to work around <rdar://22432170>. Swift 2.1 should
// hopefully remove the `@convention(c)`
@available(iOS 8.0, *)
public struct DispatchBlock {
public typealias Flags = dispatch_block_flags_t
typealias Block = @convention(block) () -> Void
private static let cCreate: @convention(c) (Flags, dispatch_block_t) -> Block! = dispatch_block_create
private static let cCreateQOS: @convention(c) (Flags, dispatch_qos_class_t, Int32, dispatch_block_t) -> Block! = dispatch_block_create_with_qos_class
private static let cPerform: @convention(c) (Flags, dispatch_block_t) -> Void = dispatch_block_perform
private static let cWait: @convention(c) (Block, dispatch_time_t) -> Int = dispatch_block_wait
private static let cNotify: @convention(c) (Block, dispatch_queue_t, dispatch_block_t) -> Void = dispatch_block_notify
private static let cCancel: @convention(c) (Block) -> Void = dispatch_block_cancel
private static let cTestCancel: @convention(c) (Block) -> Int = dispatch_block_testcancel
private static let cSync: @convention(c) (dispatch_queue_t, Block) -> Void = dispatch_sync
private static let cAsync: @convention(c) (dispatch_queue_t, Block) -> Void = dispatch_async
private static let cAfter: @convention(c) (dispatch_time_t, dispatch_queue_t, Block) -> Void = dispatch_after
private let block: Block
/// Create a new dispatch block from an existing function and flags.
///
/// The dispatch block is intended to be submitted to a dispatch queue, but
/// may also be invoked directly. Both operations can be performed an
/// arbitrary number of times, but only the first completed execution of a
/// dispatch block can be waited on or notified for.
///
/// If a dispatch block is submitted to a dispatch queue, the submitted
/// instance will be associated with the QOS class current at the time of
/// submission, unless a `DispatchBlock.Flag` is specified to the contrary.
///
/// If a dispatch block is submitted to a serial queue and is configured
/// to execute with a specific QOS, the system will make a best effort to
/// apply the necessary QOS overrides to ensure that blocks submitted
/// earlier to the serial queue are executed at that same QOS class or
/// higher.
///
/// - parameter flags: Configuration flags for the block
/// - parameter function: The body of the dispatch block
public init(flags: dispatch_block_flags_t = [], body: dispatch_block_t) {
block = DispatchBlock.cCreate(flags, body)
}
/// Create a new dispatch block from an existing block and flags, assigning
/// it the given QOS class and priority.
///
/// The dispatch block is intended to be submitted to a dispatch queue, but
/// may also be invoked directly. Both operations can be performed an
/// arbitrary number of times, but only the first completed execution of a
/// dispatch block can be waited on or notified for.
///
/// If a dispatch block is submitted to a dispatch queue, the submitted
/// instance will be associated with the QOS class current at the time of
/// submission, unless a `DispatchBlock.Flag` is specified to the contrary.
///
/// If a dispatch block is submitted to a serial queue and is configured
/// to execute with a specific QOS, the system will make a best effort to
/// apply the necessary QOS overrides to ensure that blocks submitted
/// earlier to the serial queue are executed at that same QOS class or
/// higher.
///
/// - parameter flags: Configuration flags for the block
/// - parameter QOS: A QOS class value. Passing `QOS_CLASS_UNSPECIFIED` is
/// equivalent to specifying the `DispatchBlock.Flags.RemoveQOS` flag.
/// - parameter priority: A relative priority within the QOS class.
/// This value is an offset in the range `QOS_MIN_RELATIVE_PRIORITY...0`.
/// - parameter function: The body of the dispatch block
public init(flags: dispatch_block_flags_t, QOS: dispatch_qos_class_t, priority: Int32, body: dispatch_block_t) {
assert(priority <= 0 && priority > QOS_MIN_RELATIVE_PRIORITY)
block = DispatchBlock.cCreateQOS(flags, QOS, priority, body)
}
/// Create and synchronously execute a dispatch block with override flags.
///
/// This method behaves identically to creating a new `DispatchBlock`
/// instance and calling `callAndWait(upon:)`, but may be implemented
/// more efficiently.
///
/// - parameter flags: Configuration flags for the temporary dispatch block
public func callAndWait(flags: dispatch_block_flags_t = []) {
DispatchBlock.cPerform(flags, block)
}
/// Wait synchronously until execution of the dispatch block has completed,
/// or until the given timeout has elapsed.
///
/// This function will return immediately if execution of the block has
/// already completed.
///
/// It is not possible to wait for multiple executions of the same block
/// with this function; use a dispatch group for that purpose. A single
/// dispatch block may either be waited on once and executed once, or it
/// may be executed any number of times. The behavior of any other
/// combination is undefined.
///
/// Submission to a dispatch queue counts as an execution, even if a
/// cancellation means the block's code never runs.
///
/// The result of calling this function from multiple threads simultaneously
/// is undefined.
///
/// If this function returns indicating that the timeout has elapsed, the
/// one allowed wait has not been met.
///
/// If at the time this function is called, the dispatch block has been
/// submitted directly to a serial queue, the system will make a best effort
/// to apply necessary overrides to ensure that the blocks on the serial
/// queue are executed at the QOS class or higher of the calling queue.
///
/// - parameter timeout: When to timeout. As a convenience, there are the
/// `DISPATCH_TIME_NOW` and `DISPATCH_TIME_FOREVER` constants.
/// - seealso: dispatch_time_t
/// - seealso: dispatch_group_t
public func waitUntilFinished(timeout: dispatch_time_t = DISPATCH_TIME_FOREVER) -> Bool {
return DispatchBlock.cWait(block, timeout) == 0
}
/// Schedule a notification handler to be submitted to a queue when the
/// dispatch block has completed execution.
///
/// The notification handler will be submitted immediately if execution of
/// the dispatch block has already completed.
///
/// It is not possible to be notifiied of multiple executions of the same
/// block with this function; use a dispatch group for that purpose. A
/// single dispatch block may either be waited on once and executed once, or
/// it may be executed any number of times. The behavior of any other
/// combination is undefined.
///
/// Submission to a dispatch queue counts as an execution, even if a
/// cancellation means the block's code never runs.
///
/// If multiple notification handlers are scheduled for a single block,
/// there is no defined order in which the handlers will be submitted to
/// their associated queues.
///
/// - parameter queue: The dispatch queue to which the `handler` will be
/// submitted when the observed block completes.
/// - parameter handler: The notification handler to submit when the
/// observed block completes.
/// - seealso: dispatch_group_t
public func upon(queue: dispatch_queue_t, handler: dispatch_block_t) {
DispatchBlock.cNotify(block, queue, handler)
}
/// Asynchronously cancel the dispatch block.
///
/// Cancellation causes any future execution of the dispatch block to
/// return immediately, but does not affect any execution of the block
/// that is already in progress.
///
/// Release of any resources associated with the block will be delayed until
/// until execution of the block is next attempted, or any execution already
/// in progress completes.
///
/// - warning: Care needs to be taken to ensure that a block that may be
/// cancelled does not capture any resources that require execution of the
/// block body in order to be released. Such resources will be leaked if
/// the block body is never executed due to cancellation.
public func cancel() {
DispatchBlock.cCancel(block)
}
/// Tests whether the dispatch block has been cancelled.
public var isCancelled: Bool {
return DispatchBlock.cTestCancel(block) != 0
}
/// Submits the block for asynchronous execution on a dispatch queue.
///
/// Calls to submit a block always return immediately, and never wait for
/// the block to be invoked.
///
/// The queue determines whether the block will be invoked serially or
/// concurrently with respect to other blocks submitted to that same queue.
/// Serial queues are processed concurrently with respect to each other.
///
/// - parameter queue: The target dispatch queue to which the block is submitted
/// - seealso: dispatch_async(_:_:)
public func callUponQueue(queue: dispatch_queue_t, afterDelay delay: NSTimeInterval = 0) {
if delay <= 0 {
DispatchBlock.cAsync(queue, block)
} else {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
DispatchBlock.cAfter(time, queue, block)
}
}
/// Submits a block for synchronous execution on a dispatch queue.
///
/// Submits a block to a dispatch queue like `callUponQueue`, but will not
/// return until the block has finished.
///
/// Calls targeting the current queue will result in deadlock. Use is also
/// subject to the same multi-party deadlock problems that may result from
/// the use of a mutex. Use of `callUponQueue` is preferred.
///
/// - parameter queue: The target dispatch queue to which the block is submitted
/// - seealso: dispatch_sync(_:_:)
public func callUponQueueAndWait(queue: dispatch_queue_t) {
DispatchBlock.cSync(queue, block)
}
/// Enqueues a dispatch block on a given runloop to be executed as the
/// runloop cycles next.
public func callInRunLoop(runLoop: NSRunLoop) {
CFRunLoopPerformBlock(runLoop.getCFRunLoop(), NSRunLoopCommonModes, block)
}
}
extension DispatchBlock: CustomStringConvertible, CustomReflectable, CustomPlaygroundQuickLookable {
/// A textual representation of `self`.
public var description: String {
return String(block)
}
/// Return the `Mirror` for `self`.
public func customMirror() -> Mirror {
return Mirror(reflecting: block)
}
/// Return the `PlaygroundQuickLook` for `self`.
public func customPlaygroundQuickLook() -> PlaygroundQuickLook {
return .Text("() -> ()")
}
}
// MARK: - Compatibility aliases
/// Submits the block for asynchronous execution on a dispatch queue.
///
/// The `dispatch_async` function is the fundamental mechanism for submitting
/// blocks to a dispatch queue.
///
/// Calls to submit a block always return immediately, and never wait for
/// the block to be invoked.
///
/// The queue determines whether the block will be invoked serially or
/// concurrently with respect to other blocks submitted to that same queue.
/// Serial queues are processed concurrently with respect to each other.
///
/// - parameter queue: The target dispatch queue to which the block is submitted
public func dispatch_async(queue: dispatch_queue_t, _ block: DispatchBlock) {
block.callUponQueue(queue)
}
/// Submits a block for synchronous execution on a dispatch queue.
///
/// Submits a block to a dispatch queue like `dispatch_async`, but will not
/// return until the block has finished.
///
/// Calls targeting the current queue will result in deadlock. Use is also
/// subject to the same multi-party deadlock problems that may result from
/// the use of a mutex. Use of `dispatch_async` is preferred.
///
/// - parameter queue: The target dispatch queue to which the block is submitted
public func dispatch_sync(queue: dispatch_queue_t, _ block: DispatchBlock) {
block.callUponQueueAndWait(queue)
}
|
mit
|
46cf7755cda0ebaa8ad8de61021f1f91
| 47.069364 | 154 | 0.690356 | 4.609756 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/View/Abstract/Game/Node/ViewGameNodeGameOverTitleExit.swift
|
1
|
1405
|
import SpriteKit
class ViewGameNodeGameOverTitleExit:SKLabelNode
{
private let orientation:UIInterfaceOrientation
private let kPositionY:CGFloat = 55
private let kFontSize:CGFloat = 12
init(
text:String,
zPosition:CGFloat,
orientation:UIInterfaceOrientation = UIInterfaceOrientation.portrait)
{
self.orientation = orientation
super.init()
self.text = text
self.zPosition = zPosition
fontName = UIFont.kFontRegular
fontSize = kFontSize
fontColor = SKColor.white
positionStart()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: private
private func positionStart()
{
let width:CGFloat = orientationSceneWidth()
let width_2:CGFloat = width / 2.0
position = CGPoint(x:width_2, y:kPositionY)
}
private func orientationSceneWidth() -> CGFloat
{
switch orientation
{
case UIInterfaceOrientation.portrait,
UIInterfaceOrientation.portraitUpsideDown,
UIInterfaceOrientation.unknown:
return MGame.sceneSize.width
case UIInterfaceOrientation.landscapeLeft,
UIInterfaceOrientation.landscapeRight:
return MGame.sceneSize.height
}
}
}
|
mit
|
b39c1306936cd8cb0b26c91928039a4b
| 23.649123 | 77 | 0.600712 | 5.781893 | false | false | false | false |
moukail/phonertc
|
src/ios/Session.swift
|
9
|
9724
|
import Foundation
class Session {
var plugin: PhoneRTCPlugin
var config: SessionConfig
var constraints: RTCMediaConstraints
var peerConnection: RTCPeerConnection!
var pcObserver: PCObserver!
var queuedRemoteCandidates: [RTCICECandidate]?
var peerConnectionFactory: RTCPeerConnectionFactory
var callbackId: String
var stream: RTCMediaStream?
var videoTrack: RTCVideoTrack?
var sessionKey: String
init(plugin: PhoneRTCPlugin,
peerConnectionFactory: RTCPeerConnectionFactory,
config: SessionConfig,
callbackId: String,
sessionKey: String) {
self.plugin = plugin
self.queuedRemoteCandidates = []
self.config = config
self.peerConnectionFactory = peerConnectionFactory
self.callbackId = callbackId
self.sessionKey = sessionKey
// initialize basic media constraints
self.constraints = RTCMediaConstraints(
mandatoryConstraints: [
RTCPair(key: "OfferToReceiveAudio", value: "true"),
RTCPair(key: "OfferToReceiveVideo", value:
self.plugin.videoConfig == nil ? "false" : "true"),
],
optionalConstraints: [
RTCPair(key: "internalSctpDataChannels", value: "true"),
RTCPair(key: "DtlsSrtpKeyAgreement", value: "true")
]
)
}
func call() {
// create a list of ICE servers
var iceServers: [RTCICEServer] = []
iceServers.append(RTCICEServer(
URI: NSURL(string: "stun:stun.l.google.com:19302"),
username: "",
password: ""))
iceServers.append(RTCICEServer(
URI: NSURL(string: self.config.turn.host),
username: self.config.turn.username,
password: self.config.turn.password))
// initialize a PeerConnection
self.pcObserver = PCObserver(session: self)
self.peerConnection =
peerConnectionFactory.peerConnectionWithICEServers(iceServers,
constraints: self.constraints,
delegate: self.pcObserver)
// create a media stream and add audio and/or video tracks
createOrUpdateStream()
// create offer if initiator
if self.config.isInitiator {
self.peerConnection.createOfferWithDelegate(SessionDescriptionDelegate(session: self),
constraints: constraints)
}
}
func createOrUpdateStream() {
if self.stream != nil {
self.peerConnection.removeStream(self.stream)
self.stream = nil
}
self.stream = peerConnectionFactory.mediaStreamWithLabel("ARDAMS")
if self.config.streams.audio {
// init local audio track if needed
if self.plugin.localAudioTrack == nil {
self.plugin.initLocalAudioTrack()
}
self.stream!.addAudioTrack(self.plugin.localAudioTrack!)
}
if self.config.streams.video {
// init local video track if needed
if self.plugin.localVideoTrack == nil {
self.plugin.initLocalVideoTrack()
}
self.stream!.addVideoTrack(self.plugin.localVideoTrack!)
}
self.peerConnection.addStream(self.stream)
}
func receiveMessage(message: String) {
// Parse the incoming JSON message.
var error : NSError?
let data : AnyObject? = NSJSONSerialization.JSONObjectWithData(
message.dataUsingEncoding(NSUTF8StringEncoding)!,
options: NSJSONReadingOptions.allZeros,
error: &error)
if let object: AnyObject = data {
// Log the message to console.
println("Received Message: \(object)")
// If the message has a type try to handle it.
if let type = object.objectForKey("type") as? String {
switch type {
case "candidate":
let mid: String = data?.objectForKey("id") as! NSString as String
let sdpLineIndex: Int = (data?.objectForKey("label") as! NSNumber).integerValue
let sdp: String = data?.objectForKey("candidate") as! NSString as String
let candidate = RTCICECandidate(
mid: mid,
index: sdpLineIndex,
sdp: sdp
)
if self.queuedRemoteCandidates != nil {
self.queuedRemoteCandidates?.append(candidate)
} else {
self.peerConnection.addICECandidate(candidate)
}
case "offer", "answer":
if let sdpString = object.objectForKey("sdp") as? String {
let sdp = RTCSessionDescription(type: type, sdp: self.preferISAC(sdpString))
self.peerConnection.setRemoteDescriptionWithDelegate(SessionDescriptionDelegate(session: self),
sessionDescription: sdp)
}
case "bye":
self.disconnect(false)
default:
println("Invalid message \(message)")
}
}
} else {
// If there was an error parsing then print it to console.
if let parseError = error {
println("There was an error parsing the client message: \(parseError.localizedDescription)")
}
// If there is no data then exit.
return
}
}
func disconnect(sendByeMessage: Bool) {
if self.videoTrack != nil {
self.removeVideoTrack(self.videoTrack!)
}
if self.peerConnection != nil {
if sendByeMessage {
let json: AnyObject = [
"type": "bye"
]
let data = NSJSONSerialization.dataWithJSONObject(json,
options: NSJSONWritingOptions.allZeros,
error: nil)
self.sendMessage(data!)
}
self.peerConnection.close()
self.peerConnection = nil
self.queuedRemoteCandidates = nil
}
let json: AnyObject = [
"type": "__disconnected"
]
let data = NSJSONSerialization.dataWithJSONObject(json,
options: NSJSONWritingOptions.allZeros,
error: nil)
self.sendMessage(data!)
self.plugin.onSessionDisconnect(self.sessionKey)
}
func addVideoTrack(videoTrack: RTCVideoTrack) {
self.videoTrack = videoTrack
self.plugin.addRemoteVideoTrack(videoTrack)
}
func removeVideoTrack(videoTrack: RTCVideoTrack) {
self.plugin.removeRemoteVideoTrack(videoTrack)
}
func preferISAC(sdpDescription: String) -> String {
var mLineIndex = -1
var isac16kRtpMap: String?
let origSDP = sdpDescription.stringByReplacingOccurrencesOfString("\r\n", withString: "\n")
var lines = origSDP.componentsSeparatedByString("\n")
let isac16kRegex = NSRegularExpression(
pattern: "^a=rtpmap:(\\d+) ISAC/16000[\r]?$",
options: NSRegularExpressionOptions.allZeros,
error: nil)
for var i = 0;
(i < lines.count) && (mLineIndex == -1 || isac16kRtpMap == nil);
++i {
let line = lines[i]
if line.hasPrefix("m=audio ") {
mLineIndex = i
continue
}
isac16kRtpMap = self.firstMatch(isac16kRegex!, string: line)
}
if mLineIndex == -1 {
println("No m=audio line, so can't prefer iSAC")
return origSDP
}
if isac16kRtpMap == nil {
println("No ISAC/16000 line, so can't prefer iSAC")
return origSDP
}
let origMLineParts = lines[mLineIndex].componentsSeparatedByString(" ")
var newMLine: [String] = []
var origPartIndex = 0;
// Format is: m=<media> <port> <proto> <fmt> ...
newMLine.append(origMLineParts[origPartIndex++])
newMLine.append(origMLineParts[origPartIndex++])
newMLine.append(origMLineParts[origPartIndex++])
newMLine.append(isac16kRtpMap!)
for ; origPartIndex < origMLineParts.count; ++origPartIndex {
if isac16kRtpMap != origMLineParts[origPartIndex] {
newMLine.append(origMLineParts[origPartIndex])
}
}
lines[mLineIndex] = " ".join(newMLine)
return "\r\n".join(lines)
}
func firstMatch(pattern: NSRegularExpression, string: String) -> String? {
var nsString = string as NSString
let result = pattern.firstMatchInString(string,
options: NSMatchingOptions.allZeros,
range: NSMakeRange(0, nsString.length))
if result == nil {
return nil
}
return nsString.substringWithRange(result!.rangeAtIndex(1))
}
func sendMessage(message: NSData) {
self.plugin.sendMessage(self.callbackId, message: message)
}
}
|
apache-2.0
|
0a8f42b4bce491effd60ae78796e0f8c
| 34.881919 | 123 | 0.54494 | 5.222342 | false | false | false | false |
fernandomarins/food-drivr-pt
|
Pods/JSONCodable/JSONCodable/JSONEncodable.swift
|
1
|
9874
|
//
// JSONEncodable.swift
// JSONCodable
//
// Created by Matthew Cheok on 17/7/15.
// Copyright © 2015 matthewcheok. All rights reserved.
//
// Encoding Errors
public enum JSONEncodableError: ErrorType, CustomStringConvertible {
case IncompatibleTypeError(
elementType: Any.Type
)
case ArrayIncompatibleTypeError(
elementType: Any.Type
)
case DictionaryIncompatibleTypeError(
elementType: Any.Type
)
case ChildIncompatibleTypeError(
key: String,
elementType: Any.Type
)
case TransformerFailedError(
key: String
)
public var description: String {
switch self {
case let .IncompatibleTypeError(elementType: elementType):
return "JSONEncodableError: Incompatible type \(elementType)"
case let .ArrayIncompatibleTypeError(elementType: elementType):
return "JSONEncodableError: Got an array of incompatible type \(elementType)"
case let .DictionaryIncompatibleTypeError(elementType: elementType):
return "JSONEncodableError: Got an dictionary of incompatible type \(elementType)"
case let .ChildIncompatibleTypeError(key: key, elementType: elementType):
return "JSONEncodableError: Got incompatible type \(elementType) for key \(key)"
case let .TransformerFailedError(key: key):
return "JSONEncodableError: Transformer failed for key \(key)"
}
}
}
// Struct -> Dictionary
public protocol JSONEncodable {
func toJSON() throws -> AnyObject
}
public extension JSONEncodable {
func toJSON() throws -> AnyObject {
let mirror = Mirror(reflecting: self)
guard let style = mirror.displayStyle where style == .Struct || style == .Class else {
throw JSONEncodableError.IncompatibleTypeError(elementType: self.dynamicType)
}
return try JSONEncoder.create({ (encoder) -> Void in
// loop through all properties (instance variables)
for (labelMaybe, valueMaybe) in mirror.children {
guard let label = labelMaybe else {
continue
}
let value: Any
// unwrap optionals
if let v = valueMaybe as? JSONOptional {
guard let unwrapped = v.wrapped else {
continue
}
value = unwrapped
}
else {
value = valueMaybe
}
switch (value) {
case let value as JSONEncodable:
try encoder.encode(value, key: label)
case let value as JSONArray:
try encoder.encode(value, key: label)
case let value as JSONDictionary:
try encoder.encode(value, key: label)
default:
throw JSONEncodableError.ChildIncompatibleTypeError(key: label, elementType: value.dynamicType)
}
}
})
}
}
public extension Array {//where Element: JSONEncodable {
private var wrapped: [Any] { return self.map{$0} }
public func toJSON() throws -> AnyObject {
var results: [AnyObject] = []
for item in self.wrapped {
if let item = item as? JSONEncodable {
results.append(try item.toJSON())
}
else {
throw JSONEncodableError.ArrayIncompatibleTypeError(elementType: item.dynamicType)
}
}
return results
}
}
// Dictionary convenience methods
public extension Dictionary {//where Key: String, Value: JSONEncodable {
public func toJSON() throws -> AnyObject {
var result: [String: AnyObject] = [:]
for (k, item) in self {
if let item = item as? JSONEncodable {
result[String(k)] = try item.toJSON()
}
else {
throw JSONEncodableError.DictionaryIncompatibleTypeError(elementType: item.dynamicType)
}
}
return result
}
}
// JSONEncoder - provides utility methods for encoding
public class JSONEncoder {
var object = JSONObject()
public static func create(@noescape setup: (encoder: JSONEncoder) throws -> Void) rethrows -> JSONObject {
let encoder = JSONEncoder()
try setup(encoder: encoder)
return encoder.object
}
/*
Note:
There is some duplication because methods with generic constraints need to
take a concrete type conforming to the constraint are unable to take a parameter
typed to the protocol. Hence we need non-generic versions so we can cast from
Any to JSONEncodable in the default implementation for toJSON().
*/
// JSONEncodable
public func encode<Encodable: JSONEncodable>(value: Encodable, key: String) throws {
let result = try value.toJSON()
object[key] = result
}
private func encode(value: JSONEncodable, key: String) throws {
let result = try value.toJSON()
object[key] = result
}
// JSONEncodable?
public func encode<Encodable: JSONEncodable>(value: Encodable?, key: String) throws {
guard let actual = value else {
return
}
let result = try actual.toJSON()
object[key] = result
}
// Enum
public func encode<Enum: RawRepresentable>(value: Enum, key: String) throws {
guard let compatible = value.rawValue as? JSONCompatible else {
return
}
let result = try compatible.toJSON()
object[key] = result
}
// Enum?
public func encode<Enum: RawRepresentable>(value: Enum?, key: String) throws {
guard let actual = value else {
return
}
guard let compatible = actual.rawValue as? JSONCompatible else {
return
}
let result = try compatible.toJSON()
object[key] = result
}
// [JSONEncodable]
public func encode<Encodable: JSONEncodable>(array: [Encodable], key: String) throws {
guard array.count > 0 else {
return
}
let result = try array.toJSON()
object[key] = result
}
public func encode(array: [JSONEncodable], key: String) throws {
guard array.count > 0 else {
return
}
let result = try array.toJSON()
object[key] = result
}
private func encode(array: JSONArray, key: String) throws {
guard array.count > 0 && array.elementsAreJSONEncodable() else {
return
}
let encodable = array.elementsMadeJSONEncodable()
let result = try encodable.toJSON()
object[key] = result
}
// [JSONEncodable]?
public func encode<Encodable: JSONEncodable>(value: [Encodable]?, key: String) throws {
guard let actual = value else {
return
}
guard actual.count > 0 else {
return
}
let result = try actual.toJSON()
object[key] = result
}
// [Enum]
public func encode<Enum: RawRepresentable>(value: [Enum], key: String) throws {
guard value.count > 0 else {
return
}
let result = try value.flatMap {
try ($0.rawValue as? JSONCompatible)?.toJSON()
}
object[key] = result
}
// [Enum]?
public func encode<Enum: RawRepresentable>(value: [Enum]?, key: String) throws {
guard let actual = value else {
return
}
guard actual.count > 0 else {
return
}
let result = try actual.flatMap {
try ($0.rawValue as? JSONCompatible)?.toJSON()
}
object[key] = result
}
// [String:JSONEncodable]
public func encode<Encodable: JSONEncodable>(dictionary: [String:Encodable], key: String) throws {
guard dictionary.count > 0 else {
return
}
let result = try dictionary.toJSON()
object[key] = result
}
public func encode(dictionary: [String:JSONEncodable], key: String) throws {
guard dictionary.count > 0 else {
return
}
let result = try dictionary.toJSON()
object[key] = result
}
private func encode(dictionary: JSONDictionary, key: String) throws {
guard dictionary.count > 0 && dictionary.valuesAreJSONEncodable() else {
return
}
let encodable = dictionary.valuesMadeJSONEncodable()
let result = try encodable.toJSON()
object[key] = result
}
// [String:JSONEncodable]?
public func encode<Encodable: JSONEncodable>(value: [String:Encodable]?, key: String) throws {
guard let actual = value else {
return
}
guard actual.count > 0 else {
return
}
let result = try actual.toJSON()
object[key] = result
}
// JSONTransformable
public func encode<EncodedType, DecodedType>(value: DecodedType, key: String, transformer: JSONTransformer<EncodedType, DecodedType>) throws {
guard let result = transformer.encoding(value) else {
throw JSONEncodableError.TransformerFailedError(key: key)
}
object[key] = (result as! AnyObject)
}
// JSONTransformable?
public func encode<EncodedType, DecodedType>(value: DecodedType?, key: String, transformer: JSONTransformer<EncodedType, DecodedType>) throws {
guard let actual = value else {
return
}
guard let result = transformer.encoding(actual) else {
return
}
object[key] = (result as! AnyObject)
}
}
|
mit
|
123c67b78cb00df9b7620e2e9e545a27
| 31.692053 | 147 | 0.585536 | 5.057889 | false | false | false | false |
lorentey/swift
|
test/SILGen/opaque_result_type.swift
|
3
|
3609
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -I %t -disable-availability-checking -emit-silgen %s | %FileCheck %s
import resilient_struct
protocol P {}
protocol Q: AnyObject {}
extension String: P {}
struct AddrOnly: P { var field: P }
class C: Q {}
// CHECK-LABEL: sil hidden {{.*}}11valueToAddr1xQr
func valueToAddr(x: String) -> some P {
// CHECK: bb0([[ARG0:%.*]] : $*String, [[ARG1:%.*]] : @guaranteed $String):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[ARG1]]
// CHECK: store [[VALUE_COPY]] to [init] [[ARG0]]
return x
}
// CHECK-LABEL: sil hidden {{.*}}10addrToAddr1xQr
func addrToAddr(x: AddrOnly) -> some P {
// CHECK: bb0([[ARG0:%.*]] : $*AddrOnly, [[ARG1:%.*]] : $*AddrOnly):
// CHECK: copy_addr [[ARG1]] to [initialization] [[ARG0]]
return x
}
// CHECK-LABEL: sil hidden {{.*}}13genericAddrToE01xQr
func genericAddrToAddr<T: P>(x: T) -> some P {
// CHECK: bb0([[ARG0:%.*]] : $*T, [[ARG1:%.*]] : $*T):
// CHECK: copy_addr [[ARG1]] to [initialization] [[ARG0]]
return x
}
// CHECK-LABEL: sil hidden {{.*}}12valueToValue1xQr
func valueToValue(x: C) -> some Q {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $C):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[ARG]]
// CHECK: return [[VALUE_COPY]]
return x
}
// CHECK-LABEL: sil hidden {{.*}}13reabstraction1xQr
func reabstraction(x: @escaping () -> ()) -> some Any {
// CHECK: bb0([[ARG0:%.*]] : $*@callee_guaranteed () -> @out (), [[ARG1:%.*]] : @guaranteed $@callee_guaranteed () -> ()):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[ARG1]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @$sIeg_ytIegr_TR
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[VALUE_COPY]])
// CHECK: store [[THUNK]] to [init] [[ARG0]]
return x
}
protocol X {
associatedtype A
func foo() -> A
}
extension Int : P {}
extension ResilientInt : P {}
class K : P {}
func useClosure2(_ cl: () -> ()) {}
func useClosure(_ cl: @escaping () -> ()) {
cl()
}
struct S : X {
func foo() -> some P {
return returnTrivial()
}
func returnTrivial() -> some P {
return 1
}
func returnClass() -> some P {
return K()
}
func returnResilient() -> some P {
return ResilientInt(i: 1)
}
func testCapture() {
var someP = returnTrivial()
var someK = returnClass()
var someR = returnResilient()
useClosure {
someP = self.returnTrivial()
someK = self.returnClass()
someR = self.returnResilient()
}
print(someP)
print(someK)
print(someR)
}
func testCapture2() {
var someP = returnTrivial()
var someK = returnClass()
var someR = returnResilient()
useClosure2 {
someP = self.returnTrivial()
someK = self.returnClass()
someR = self.returnResilient()
}
print(someP)
print(someK)
print(someR)
}
func testCapture3() {
let someP = returnTrivial()
let someK = returnClass()
let someR = returnResilient()
useClosure {
print(someP)
print(someK)
print(someR)
}
}
func testCapture4() {
let someP = returnTrivial()
let someK = returnClass()
let someR = returnResilient()
useClosure {
print(someP)
print(someK)
print(someR)
}
}
}
extension Optional : P { }
struct S2 : X {
func foo() -> some P {
let x : Optional = 1
return x
}
func returnFunctionType() -> () -> A {
return foo
}
}
|
apache-2.0
|
1f7fcf0de77abb1b8e43b4a604451e2d
| 22.900662 | 185 | 0.593793 | 3.372897 | false | false | false | false |
AlexanderMazaletskiy/SAHistoryNavigationViewController
|
SAHistoryNavigationViewController/NSLayoutConstraint+Fit.swift
|
2
|
1830
|
//
// NSLayoutConstraint+Fit.swift
// SAHistoryNavigationViewController
//
// Created by 鈴木大貴 on 2015/03/26.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
extension NSLayoutConstraint {
class func applyAutoLayout(superview: UIView, target: UIView, index: Int?, top: Float?, left: Float?, right: Float?, bottom: Float?, height: Float?, width: Float?) {
target.translatesAutoresizingMaskIntoConstraints = false
if let index = index {
superview.insertSubview(target, atIndex: index)
} else {
superview.addSubview(target)
}
var verticalFormat = "V:"
if let top = top {
verticalFormat += "|-(\(top))-"
}
verticalFormat += "[target"
if let height = height {
verticalFormat += "(\(height))"
}
verticalFormat += "]"
if let bottom = bottom {
verticalFormat += "-(\(bottom))-|"
}
let verticalConstrains = NSLayoutConstraint.constraintsWithVisualFormat(verticalFormat, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "target" : target ])
superview.addConstraints(verticalConstrains)
var horizonFormat = "H:"
if let left = left {
horizonFormat += "|-(\(left))-"
}
horizonFormat += "[target"
if let width = width {
horizonFormat += "(\(width))"
}
horizonFormat += "]"
if let right = right {
horizonFormat += "-(\(right))-|"
}
let horizonConstrains = NSLayoutConstraint.constraintsWithVisualFormat(horizonFormat, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: [ "target" : target ])
superview.addConstraints(horizonConstrains)
}
}
|
mit
|
c963d60ba7bae47d5c4b08cfd8f03272
| 35.24 | 184 | 0.593819 | 4.870968 | false | false | false | false |
J-Mendes/Bliss-Assignement
|
Bliss-Assignement/Bliss-Assignement/Views/NetworkUnreachableView.swift
|
1
|
1068
|
//
// NetworkUnreachableView.swift
// Bliss-Assignement
//
// Created by Jorge Mendes on 13/10/16.
// Copyright © 2016 Jorge Mendes. All rights reserved.
//
import UIKit
class NetworkUnreachableView: UIView {
private(set) var isShowing: Bool = false
@IBOutlet weak var messageLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.frame = UIScreen.mainScreen().bounds
self.messageLabel.text = "Your network connection is disabled.\nPlease enable it!"
}
internal func show() {
self.endEditing(true)
self.alpha = 0.0
UIApplication.sharedApplication().keyWindow!.addSubview(self)
UIView.animateWithDuration(0.3) {
self.alpha = 1.0
}
self.isShowing = true
}
internal func dismiss() {
UIView.animateWithDuration(0.3, animations: {
self.alpha = 0.0
}) { (success: Bool) in
self.isShowing = false
self.removeFromSuperview()
}
}
}
|
lgpl-3.0
|
6506538fc7eecdba92f55741d5d322c3
| 23.25 | 90 | 0.595127 | 4.445833 | false | false | false | false |
ihanken/SimpleAWS
|
SimpleAWS/Classes/S3.swift
|
1
|
2790
|
//
// S3.swift
// Pods
//
// Created by Ian Hanken on Wednesday, January 11, 2017.
//
//
import Foundation
import AWSS3
public class S3 {
public static let shared = S3()
private init() {} // This prevents others from using the default '()' initializer.
private var S3BucketName: String = ""
private var manager: AWSS3TransferManager? = nil
public func initializeS3(region: AWSRegionType, identityPoolID: String, bucketName: String) {
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: region, identityPoolId: identityPoolID)
let configuration = AWSServiceConfiguration(region: region, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
S3BucketName = bucketName
manager = AWSS3TransferManager.default()
}
// MARK: - Type Aliases, closures, and closure functions
public typealias Response = (AWSTask<AnyObject>) -> ()
public var success: Response?
public var failure: Response?
public func onSuccess(closure: Response?) {
success = closure
}
public func onFailure(closure: Response?) -> Self {
failure = closure
return self
}
public func doSuccess(params: AWSTask<AnyObject>) {
if let closure = success { closure(params) }
}
public func doFailure(params: AWSTask<AnyObject>) {
if let closure = failure { closure(params) }
}
public func handleBlock(task: AWSTask<AnyObject>) {
if task.error != nil {
print(task.error!)
self.doFailure(params: task)
}
else {
print(task.result!)
self.doSuccess(params: task)
}
}
public func download(key: String, downloadPath: URL) -> Self {
let downloadRequest = AWSS3TransferManagerDownloadRequest()
downloadRequest?.bucket = S3BucketName
downloadRequest?.key = key
downloadRequest?.downloadingFileURL = downloadPath
manager?.download(downloadRequest).continue({(task: AWSTask!) -> AnyObject! in
self.handleBlock(task: task)
return nil
})
return self
}
public func upload(key: String, imagePath: URL) -> Self {
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest?.bucket = S3BucketName
uploadRequest?.key = key
uploadRequest?.body = imagePath
manager?.upload(uploadRequest).continue({(task: AWSTask!) -> AnyObject! in
self.handleBlock(task: task)
return nil
})
return self
}
}
|
mit
|
3c3a2b15dadf3e75c5ddb33af9afc02d
| 28.0625 | 115 | 0.611828 | 5.147601 | false | false | false | false |
benlangmuir/swift
|
SwiftCompilerSources/Sources/SIL/VTable.swift
|
1
|
1886
|
//===--- VTable.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SILBridging
public struct VTable : CustomStringConvertible, CustomReflectable {
let bridged: BridgedVTable
public init(bridged: BridgedVTable) { self.bridged = bridged }
public struct Entry : CustomStringConvertible, CustomReflectable {
fileprivate let bridged: BridgedVTableEntry
public var function: Function { SILVTableEntry_getFunction(bridged).function }
public var description: String {
let stdString = SILVTableEntry_debugDescription(bridged)
return String(_cxxString: stdString)
}
public var customMirror: Mirror { Mirror(self, children: []) }
}
public struct EntryArray : BridgedRandomAccessCollection {
fileprivate let bridgedArray: BridgedArrayRef
public var startIndex: Int { return 0 }
public var endIndex: Int { return Int(bridgedArray.numElements) }
public subscript(_ index: Int) -> Entry {
precondition(index >= 0 && index < endIndex)
return Entry(bridged: BridgedVTableEntry(ptr: bridgedArray.data! + index &* BridgedVTableEntrySize))
}
}
public var entries: EntryArray {
EntryArray(bridgedArray: SILVTable_getEntries(bridged))
}
public var description: String {
let stdString = SILVTable_debugDescription(bridged)
return String(_cxxString: stdString)
}
public var customMirror: Mirror { Mirror(self, children: []) }
}
|
apache-2.0
|
e53641c3be85e22e8f297fd9c79fa546
| 33.290909 | 106 | 0.671792 | 4.898701 | false | false | false | false |
JALsnipe/VideoCore
|
sample/SampleBroadcaster-Swift/SampleBroadcaster-Swift/ViewController.swift
|
2
|
1779
|
//
// ViewController.swift
// SampleBroadcaster-Swift
//
// Created by Josh Lieberman on 4/11/15.
// Copyright (c) 2015 videocore. All rights reserved.
//
import UIKit
class ViewController: UIViewController, VCSessionDelegate
{
@IBOutlet weak var previewView: UIView!
@IBOutlet weak var btnConnect: UIButton!
var session:VCSimpleSession = VCSimpleSession(videoSize: CGSize(width: 1280, height: 720), frameRate: 30, bitrate: 1000000, useInterfaceOrientation: false)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
previewView.addSubview(session.previewView)
session.previewView.frame = previewView.bounds
session.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
btnConnect = nil
previewView = nil
}
@IBAction func btnConnectTouch(sender: AnyObject) {
switch session.rtmpSessionState {
case .None, .PreviewStarted, .Ended, .Error:
session.startRtmpSessionWithURL("rtmp://192.168.1.151/live", andStreamKey: "myStream")
default:
session.endRtmpSession()
break
}
}
func connectionStatusChanged(sessionState: VCSessionState) {
switch session.rtmpSessionState {
case .Starting:
btnConnect.setTitle("Connecting", forState: .Normal)
case .Started:
btnConnect.setTitle("Disconnect", forState: .Normal)
default:
btnConnect.setTitle("Connect", forState: .Normal)
}
}
}
|
mit
|
1b0e016fa7ee9c3e112a35fcb59591eb
| 27.693548 | 159 | 0.63575 | 4.756684 | false | false | false | false |
AlexRamey/mbird-iOS
|
Pods/Nuke/Sources/CancellationToken.swift
|
1
|
3005
|
// The MIT License (MIT)
//
// Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean).
import Foundation
/// Manages cancellation tokens and signals them when cancellation is requested.
///
/// All `CancellationTokenSource` methods are thread safe.
public final class CancellationTokenSource {
/// Returns `true` if cancellation has been requested.
public var isCancelling: Bool {
return _lock.sync { _observers == nil }
}
/// Creates a new token associated with the source.
public var token: CancellationToken {
return CancellationToken(source: self)
}
private var _observers: ContiguousArray<() -> Void>? = []
/// Initializes the `CancellationTokenSource` instance.
public init() {}
fileprivate func register(_ closure: @escaping () -> Void) {
if !_register(closure) {
closure()
}
}
private func _register(_ closure: @escaping () -> Void) -> Bool {
_lock.lock(); defer { _lock.unlock() }
_observers?.append(closure)
return _observers != nil
}
/// Communicates a request for cancellation to the managed tokens.
public func cancel() {
if let observers = _cancel() {
observers.forEach { $0() }
}
}
private func _cancel() -> ContiguousArray<() -> Void>? {
_lock.lock(); defer { _lock.unlock() }
let observers = _observers
_observers = nil // transition to `isCancelling` state
return observers
}
}
// We use the same lock across different tokens because the design of CTS
// prevents potential issues. For example, closures registered with a token
// are never executed inside a lock.
private let _lock = NSLock()
/// Enables cooperative cancellation of operations.
///
/// You create a cancellation token by instantiating a `CancellationTokenSource`
/// object and calling its `token` property. You then pass the token to any
/// number of threads, tasks, or operations that should receive notice of
/// cancellation. When the owning object calls `cancel()`, the `isCancelling`
/// property on every copy of the cancellation token is set to `true`.
/// The registered objects can respond in whatever manner is appropriate.
///
/// All `CancellationToken` methods are thread safe.
public struct CancellationToken {
fileprivate let source: CancellationTokenSource? // no-op when `nil`
/// Returns `true` if cancellation has been requested for this token.
public var isCancelling: Bool {
return source?.isCancelling ?? false
}
/// Registers the closure that will be called when the token is canceled.
/// If this token is already cancelled, the closure will be run immediately
/// and synchronously.
public func register(_ closure: @escaping () -> Void) {
source?.register(closure)
}
/// Special no-op token which does nothing.
internal static var noOp: CancellationToken {
return CancellationToken(source: nil)
}
}
|
mit
|
3bd22d128d9367f34e6de0547a1f5663
| 33.54023 | 80 | 0.668885 | 4.687988 | false | false | false | false |
Matthijn/swift8
|
Swift8/Keyboard.swift
|
1
|
1063
|
//
// Keyboard.swift
// Swift8
//
// Created by Matthijn Dijkstra on 18/08/15.
// Copyright © 2015 Matthijn Dijkstra. All rights reserved.
//
import Cocoa
class Keyboard
{
// Mapping ASCII keycodes to the Chip8 key codes
let mapping : [UInt8: Int8] = [
18: 0x1, // 1
19: 0x2, // 2
20: 0x3, // 3
21: 0xC, // 4
12: 0x4, // q
13: 0x5, // w
14: 0x6, // e
15: 0xD, // r
0: 0x7, // a
1: 0x8, // s
2: 0x9, // d
3: 0xE, // f
6: 0xA, // z
7: 0x0, // x
8: 0xB, // c
9: 0xF, // v
]
var currentKey : Int8 = -1
func keyUp(_ event: NSEvent)
{
// Key stopped being pressed so setting current key to -1 to represent nothing
self.currentKey = -1
}
func keyDown(_ event: NSEvent)
{
// Setting the current key as the mapped key
if let mappedKey = self.mapping[UInt8(event.keyCode)]
{
self.currentKey = mappedKey
}
}
}
|
mit
|
aee80872e84634daab248bbb28b23913
| 19.823529 | 86 | 0.475518 | 3.227964 | false | false | false | false |
horizon-institute/babyface-ios
|
src/net/NetData.swift
|
2
|
1389
|
//
// NetData.swift
// Net
//
// Created by Le Van Nghia on 8/3/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import Foundation
import UIKit
enum MimeType: String {
case ImageJpeg = "image/jpeg"
case ImagePng = "image/png"
case ImageGif = "image/gif"
case Json = "application/json"
case Unknown = ""
func getString() -> String? {
switch self {
case .ImagePng:
fallthrough
case .ImageJpeg:
fallthrough
case .ImageGif:
fallthrough
case .Json:
return self.rawValue
case .Unknown:
fallthrough
default:
return nil
}
}
}
class NetData
{
let data: NSData
let mimeType: MimeType
let filename: String
init(data: NSData, mimeType: MimeType, filename: String) {
self.data = data
self.mimeType = mimeType
self.filename = filename
}
init(pngImage: UIImage, filename: String) {
data = UIImagePNGRepresentation(pngImage)!
self.mimeType = MimeType.ImagePng
self.filename = filename
}
init(jpegImage: UIImage, compressionQuanlity: CGFloat, filename: String) {
data = UIImageJPEGRepresentation(jpegImage, compressionQuanlity)!
self.mimeType = MimeType.ImageJpeg
self.filename = filename
}
}
|
gpl-3.0
|
a79803ba1a59df1a94643fdb57e2ae0d
| 22.166667 | 78 | 0.593952 | 4.354232 | false | false | false | false |
LeLuckyVint/MessageKit
|
Sources/Extensions/UICollectionView+Extensions.swift
|
1
|
3869
|
/*
MIT License
Copyright (c) 2017 MessageKit
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
/// Optional Cell Protocol to Simplify registration/cell type loading in a generic way
public protocol CollectionViewReusable: class {
static func reuseIdentifier() -> String
}
public extension MessagesCollectionView {
/// Registers a particular cell using its reuse-identifier
func register<CellType: UICollectionViewCell & CollectionViewReusable>(_ cellClass: CellType.Type) {
register(cellClass, forCellWithReuseIdentifier: CellType.reuseIdentifier())
}
/// Registers a reusable view for a specific SectionKind
func register<ViewType: UICollectionReusableView & CollectionViewReusable>(_ headerFooterClass: ViewType.Type, forSupplementaryViewOfKind kind: String) {
register(headerFooterClass,
forSupplementaryViewOfKind: kind,
withReuseIdentifier: ViewType.reuseIdentifier())
}
/// Generically dequeues a cell of the correct type allowing you to avoid scattering your code with guard-let-else-fatal
func dequeueReusableCell<CellType: UICollectionViewCell & CollectionViewReusable>(_ cellClass: CellType.Type, for indexPath: IndexPath) -> CellType {
guard let cell = dequeueReusableCell(withReuseIdentifier: cellClass.reuseIdentifier(), for: indexPath) as? CellType else {
fatalError("Unable to dequeue \(String(describing: cellClass)) with reuseId of \(cellClass.reuseIdentifier())")
}
return cell
}
/// Generically dequeues a header of the correct type allowing you to avoid scattering your code with guard-let-else-fatal
func dequeueReusableHeaderView<ViewType: UICollectionReusableView & CollectionViewReusable>(_ viewClass: ViewType.Type, for indexPath: IndexPath) -> ViewType {
let view = dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: viewClass.reuseIdentifier(), for: indexPath)
guard let viewType = view as? ViewType else {
fatalError("Unable to dequeue \(String(describing: viewClass)) with reuseId of \(viewClass.reuseIdentifier())")
}
return viewType
}
/// Generically dequeues a footer of the correct type allowing you to avoid scattering your code with guard-let-else-fatal
func dequeueReusableFooterView<ViewType: UICollectionReusableView & CollectionViewReusable>(_ viewClass: ViewType.Type, for indexPath: IndexPath) -> ViewType {
let view = dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: viewClass.reuseIdentifier(), for: indexPath)
guard let viewType = view as? ViewType else {
fatalError("Unable to dequeue \(String(describing: viewClass)) with reuseId of \(viewClass.reuseIdentifier())")
}
return viewType
}
}
|
mit
|
14b4b2b1cd2e9908e286d1196e76482b
| 54.271429 | 163 | 0.761696 | 5.53505 | false | false | false | false |
frankcjw/CJWUtilsS
|
CJWUtilsS/QPLib/UI/QPExamTableViewController.swift
|
1
|
2212
|
//
// QPExamTableViewController.swift
// CJWUtilsS
//
// Created by Frank on 17/02/2017.
// Copyright © 2017 cen. All rights reserved.
//
import UIKit
class QPExamTableViewController: QPTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton()
button.setTitle("hello", forState: UIControlState.Normal)
self.floatView.addSubview(button)
button.leadingAlign(self.floatView, predicate: "0")
button.bottomAlign(self.floatView, predicate: "0")
button.aspectRatio()
button.debug(false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func cellForRow(atIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = QPTipsTableViewCell()
cell.titleLabel.debug()
return cell
}
let cell = QPImageTableViewCell()
cell.contentImageView.debug()
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
}
class QPTipsTableViewCell: QPTableViewCell {
let titleLabel = QPEmojiLabel()
override func setupViews(view: UIView) {
super.setupViews(view)
view.addSubview(titleLabel)
view.backgroundColor = UIColor.lightGrayColor()
titleLabel.textColor = UIColor.darkGrayColor()
titleLabel.font = FONT_SMALL
titleLabel.text = "[色]你可以转积分给别人\n你可以转积分给别人\nhttp://ww3.sinaimg.cn/mw690/005Ko17Djw1fctevehff5j315o6li4qr.jpg"
titleLabel.numberOfLines = 0
titleLabel.textAlignmentCenter()
}
override func setupConstrains(view: UIView) {
super.setupConstrains(view)
titleLabel.paddingConstrain()
}
}
class QPImageTableViewCell: QPTableViewCell {
let contentImageView = UIImageView()
override func setupViews(view: UIView) {
super.setupViews(view)
view.addSubview(contentImageView)
}
override func setupConstrains(view: UIView) {
super.setupConstrains(view)
let scale: Float = Float(4) / Float(3)
contentImageView.aspectRatio("*\(scale)")
contentImageView.paddingConstrain()
// imageView.as
}
}
|
mit
|
36b92b7c9e65a70370981bec9c0b7803
| 23.155556 | 111 | 0.749655 | 3.676819 | false | false | false | false |
TMTBO/TTAImagePickerController
|
Example/TTAImagePickerController/ViewController.swift
|
1
|
3993
|
//
// ViewController.swift
// TTAImagePickerController
//
// Created by TMTBO on 05/03/2017.
// Copyright (c) 2017 TMTBO. All rights reserved.
//
import UIKit
import TTAImagePickerController
class ViewController: UIViewController {
@IBOutlet weak var maxImageCountTextField: UITextField!
@IBOutlet weak var imagesCollectionView: UICollectionView!
@IBOutlet weak var allowTakePickerSwitch: UISwitch!
@IBOutlet weak var allowDeleteImageSwitch: UISwitch!
@IBOutlet weak var showLargeTitles: UISwitch!
var selectedImages = [UIImage]()
var selectedAssets = [TTAAsset]()
override func viewDidLoad() {
super.viewDidLoad()
URLSession.shared.dataTask(with: URL(string: "https://www.tobyotenma.top/blog")!).resume()
}
@IBAction func didClickShowImagePickerButton(_ sender: UIButton) {
// Create the image picket with the assets that you had selected which will show as selected in the picker
let imagePicker = TTAImagePickerController(selectedAsset: selectedAssets)
// Set pickerDelegate
imagePicker.pickerDelegate = self
// Set allow take picture in the picker
imagePicker.allowTakePicture = allowTakePickerSwitch.isOn
// Set allow user delete images in the picker
imagePicker.allowDeleteImage = allowDeleteImageSwitch.isOn
// Set support large titles for iOS 11
imagePicker.supportLargeTitles = showLargeTitles.isOn
// Set the max pick number, default is 9
imagePicker.maxPickerNum = Int(maxImageCountTextField.text ?? "9") ?? 9
// You can custom the picker apperance
// imagePicker.selectItemTintColor = .red
// imagePicker.barTintColor = .orange
// imagePicker.tintColor = .cyan
present(imagePicker, animated: true, completion: nil)
}
}
// Confirm the `TTAImagePickerControllerDelegate`
extension ViewController: TTAImagePickerControllerDelegate {
// implement the delegate method and when finished picking, you will get the images and assets that you have selected
func imagePickerController(_ picker: TTAImagePickerControllerCompatiable, didFinishPicking images: [UIImage], assets: [TTAAsset]) {
print("got the images")
selectedImages = images
selectedAssets = assets
// Export Video and get the path
var filePaths = [String?]()
_ = assets.map {
if $0.assetInfo.isVideo {
TTAImagePickerController.fetchVideo(with: $0, completionHandler: { (outputPath) in
filePaths.append(outputPath)
})
}
}
imagesCollectionView.reloadData()
}
}
// On the other hand, you can preview the images directly and deselected some of them
// What you need to do:
// Create a instance of `TTAPreviewViewController`
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
let previewVc = TTAPreviewViewController(selected: selectedAssets, index: indexPath.item, delegate: self)
present(previewVc, animated: true, completion: nil)
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return selectedImages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(UICollectionViewCell.self)", for: indexPath)
cell.layer.contents = selectedImages[indexPath.item].cgImage
cell.layer.contentsScale = UIScreen.main.scale
cell.layer.contentsGravity = CALayerContentsGravity(rawValue: "resizeAspectFill")
return cell
}
}
|
mit
|
8a448204a1717f1a227e215148eb5e91
| 40.59375 | 135 | 0.701728 | 5.288742 | false | false | false | false |
paulz/NameBook
|
NameBook/FaceCollectionViewCell.swift
|
1
|
839
|
import UIKit
import Contacts
class FaceCollectionViewCell: UICollectionViewCell {
@IBOutlet var photoView: UIImageView!
@IBOutlet var resultLabel: UILabel!
func configure(with contact: CNContact) {
resultLabel.alpha = 0
if let imageData = contact.thumbnailImageData {
photoView.image = UIImage(data: imageData)
} else {
photoView.image = nil
}
}
func showResult(correct:Bool, onComplete:@escaping ()->Void) {
resultLabel.alpha = 0
resultLabel.text = correct ? "✔︎" : "✘"
resultLabel.textColor = correct ? UIColor.green : UIColor.red
UIView.animate(withDuration: 0.25, animations: {
self.resultLabel.alpha = 1
}) { _ in
self.resultLabel.alpha = 0
onComplete()
}
}
}
|
mit
|
5cc12b9e19126a132433ad97b30f515e
| 28.75 | 69 | 0.603842 | 4.76 | false | false | false | false |
J3D1-WARR10R/WikiRaces
|
WikiRaces/Shared/Other/GameKit Support/GKMatchRequest+WKR.swift
|
2
|
2129
|
//
// GKMatchRequest+WKR.swift
// WikiRaces
//
// Created by Andrew Finke on 6/26/20.
// Copyright © 2020 Andrew Finke. All rights reserved.
//
import GameKit
import WKRKit
import os.log
extension GKMatchRequest {
static func hostRequest(raceCode: String, isInital: Bool) -> GKMatchRequest {
let request = GKMatchRequest()
request.minPlayers = 2
request.maxPlayers = isInital ? 2 : min(GKMatchRequest.maxPlayersAllowedForMatch(of: .peerToPeer), WKRKitConstants.current.maxGlobalRacePlayers)
request.playerGroup = RaceCodeGenerator.playerGroup(for: raceCode)
request.playerAttributes = 0xFFFF0000
os_log("%{public}s: %{public}s, %{public}ld, %{public}ld-%{public}ld, %{public}ld, %{public}ld",
log: .matchSupport,
type: .info,
#function,
raceCode,
isInital ? 1 : 0,
request.minPlayers,
request.maxPlayers,
request.playerGroup,
request.playerAttributes
)
return request
}
static func joinRequest(raceCode: String?) -> GKMatchRequest {
let request = GKMatchRequest()
request.minPlayers = 2
if let code = raceCode {
request.maxPlayers = min(GKMatchRequest.maxPlayersAllowedForMatch(of: .peerToPeer), WKRKitConstants.current.maxGlobalRacePlayers)
request.playerGroup = RaceCodeGenerator.playerGroup(for: code)
request.playerAttributes = 0x0000FFFF
} else {
request.maxPlayers = 2
request.playerGroup = publicRacePlayerGroup()
}
os_log("%{public}s: %{public}s, %{public}ld-%{public}ld, %{public}ld, %{public}ld",
log: .matchSupport,
type: .info,
#function,
raceCode ?? "-",
request.minPlayers,
request.maxPlayers,
request.playerGroup,
request.playerAttributes
)
return request
}
private static func publicRacePlayerGroup() -> Int {
return 11
}
}
|
mit
|
77ee4f88461aff5b18571bcf8d4bd48e
| 31.242424 | 152 | 0.593985 | 4.247505 | false | false | false | false |
gfiumara/TwentyOne
|
TwentyOne/ViewController.swift
|
1
|
4603
|
/*
* ViewController.swift
* Part of https://github.com/gfiumara/TwentyOne by Gregory Fiumara.
* See LICENSE for details.
*/
import SafariServices
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var headLabel: UILabel!
@IBOutlet weak var subheadLabel: UILabel!
@IBOutlet weak var listLastUpdatedLabel: UILabel!
@IBOutlet weak var listLastCheckedLabel: UILabel!
@IBOutlet weak var enableTwentyOneLabel: UILabel!
@IBOutlet weak var forceUpdateButton: UIButton!
@IBOutlet weak var openSettingsAppButton: UIButton!
var enterForegroundObserver:NSObjectProtocol?
private lazy var dateFormatter:DateFormatter = {
let df = DateFormatter()
df.dateStyle = .medium
df.timeStyle = .short
df.doesRelativeDateFormatting = true
return (df)
}()
override func viewDidLoad()
{
super.viewDidLoad()
var appName:String? = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String?
if appName == nil {
appName = "Twenty One"
} else {
self.headLabel.text = appName!
self.enableTwentyOneLabel.text = "Enable \(appName!)"
}
self.enterForegroundObserver = NotificationCenter.default.addObserver(forName:UIApplication.willEnterForegroundNotification, object:nil, queue:OperationQueue.main, using:{[weak self] (Notification) in
self?.updateInstructions()
})
self.updateInstructions()
self.openSettingsAppButton.isEnabled = UIApplication.shared.canOpenURL(Constants.SettingsAppURL as URL)
self.updateDates()
}
deinit
{
if let observer = self.enterForegroundObserver {
NotificationCenter.default.removeObserver(observer, name:UIApplication.willEnterForegroundNotification, object:nil)
}
}
func updateDates()
{
let defaults = UserDefaults.init(suiteName:Constants.AppGroupID)
if let lastUpdatedDate = defaults?.object(forKey:Constants.BlockerListUpdatedDateKey) {
self.listLastUpdatedLabel.text = "List last updated \(self.dateFormatter.string(from: lastUpdatedDate as! Date))."
} else {
self.listLastUpdatedLabel.text = "Using default list."
}
if let lastCheckedDate = defaults?.object(forKey:Constants.BlockerListRetrievedDateKey) {
self.listLastCheckedLabel.text = "Last checked for list updates \(self.dateFormatter.string(from: lastCheckedDate as! Date))."
} else {
self.listLastCheckedLabel.text = "Never checked for list updates."
}
}
@IBAction func openSettingsAppButtonPressed(_ button:UIButton)
{
if UIApplication.shared.canOpenURL(Constants.SettingsAppURL) {
UIApplication.shared.open(Constants.SettingsAppURL)
}
}
override var prefersStatusBarHidden : Bool
{
return (false)
}
@IBAction func forceUpdateButtonPressed(_ button:UIButton)
{
self.forceUpdateButton.isEnabled = false
self.forceUpdateButton.setTitle("Fetching update...", for:UIControl.State())
ForegroundDownloader.updateBlocklist({(data, response) in
BlockListUpdater.saveAndRecompileNewBlockListData(data, completionHandler:{(result) in
Logger.log("Retrieved block list data from remote")
DispatchQueue.main.async(execute: {
self.updateDates()
self.forceUpdateButton.setTitle("Successfully Forced Update", for:UIControl.State())
})
})
}, failure:{(error, response) in
Logger.log("ERROR (update blocklist): \(error.localizedDescription)")
DispatchQueue.main.async(execute: {
self.forceUpdateButton.setAttributedTitle(NSAttributedString.init(string:"An Error Occurred", attributes:[NSAttributedString.Key.foregroundColor:UIColor.red]), for:UIControl.State())
self.forceUpdateButton.isEnabled = true
self.updateDates()
let delayTime = DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.forceUpdateButton.setTitle("Force Update", for:UIControl.State())
}
})
})
}
func updateInstructions()
{
SFContentBlockerManager.getStateOfContentBlocker(withIdentifier:Constants.ContentBlockerBundleID, completionHandler:{(state, error) in
if let e = error {
Logger.log("ERROR (get blocker state): \(e.localizedDescription)")
return
}
DispatchQueue.main.async {
if let enabled = state?.isEnabled {
if enabled {
self.subheadLabel.text = "Twenty One is currently enabled. To disable, follow these instructions."
self.enableTwentyOneLabel.text = "Disable Twenty One"
} else {
self.subheadLabel.text = "Follow these instructions to block many (but not all) age gates on alcohol-related websites."
self.enableTwentyOneLabel.text = "Enable Twenty One"
}
}
}
});
}
}
|
bsd-3-clause
|
c6e73da2c14b7980fa54767ff593a7a2
| 32.845588 | 202 | 0.748642 | 3.971527 | false | false | false | false |
huangboju/Moots
|
Examples/URLSession/URLSession/PullToRefresh/CurveView.swift
|
1
|
918
|
//
// CurveView.swift
// AnimatedCurveDemo-Swift
//
// Created by Kitten Yang on 1/18/16.
// Copyright © 2016 Kitten Yang. All rights reserved.
//
class CurveView: UIView {
var progress: CGFloat = 0.0 {
didSet {
curveLayer.progress = progress
curveLayer.setNeedsDisplay()
}
}
fileprivate var curveLayer: CurveLayer!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
curveLayer = CurveLayer()
curveLayer.frame = bounds
curveLayer.contentsScale = UIScreen.main.scale
curveLayer.progress = 0.0
curveLayer.setNeedsDisplay()
layer.addSublayer(curveLayer)
}
}
|
mit
|
d481f4cf130e998126a2d171b319b835
| 24.472222 | 63 | 0.636859 | 4.38756 | false | false | false | false |
atrick/swift
|
test/AutoDiff/SILOptimizer/activity_analysis.swift
|
1
|
46536
|
// RUN: %target-swift-emit-sil -verify -Xllvm -debug-only=differentiation 2>&1 %s | %FileCheck %s
// REQUIRES: asserts
import _Differentiation
// Check that `@noDerivative` struct projections have "NONE" activity.
struct HasNoDerivativeProperty: Differentiable {
var x: Float
@noDerivative var y: Float
}
@differentiable(reverse)
func testNoDerivativeStructProjection(_ s: HasNoDerivativeProperty) -> Float {
var tmp = s
tmp.y = tmp.x
return tmp.x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testNoDerivativeStructProjection{{.*}} at parameter indices (0) and result indices (0):
// CHECK: [ACTIVE] %0 = argument of bb0 : $HasNoDerivativeProperty
// CHECK: [ACTIVE] %2 = alloc_stack [lexical] $HasNoDerivativeProperty, var, name "tmp"
// CHECK: [ACTIVE] %4 = begin_access [read] [static] %2 : $*HasNoDerivativeProperty
// CHECK: [ACTIVE] %5 = struct_element_addr %4 : $*HasNoDerivativeProperty, #HasNoDerivativeProperty.x
// CHECK: [VARIED] %6 = load [trivial] %5 : $*Float
// CHECK: [ACTIVE] %8 = begin_access [modify] [static] %2 : $*HasNoDerivativeProperty
// CHECK: [NONE] %9 = struct_element_addr %8 : $*HasNoDerivativeProperty, #HasNoDerivativeProperty.y
// CHECK: [ACTIVE] %12 = begin_access [read] [static] %2 : $*HasNoDerivativeProperty
// CHECK: [ACTIVE] %13 = struct_element_addr %12 : $*HasNoDerivativeProperty, #HasNoDerivativeProperty.x
// CHECK: [ACTIVE] %14 = load [trivial] %13 : $*Float
// Check that non-differentiable `tuple_element_addr` projections are non-varied.
@differentiable(reverse where T : Differentiable)
func testNondifferentiableTupleElementAddr<T>(_ x: T) -> T {
var tuple = (1, 1, (x, 1), 1)
tuple.0 = 1
tuple.2.0 = x
tuple.3 = 1
return tuple.2.0
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testNondifferentiableTupleElementAddr{{.*}} at parameter indices (0) and result indices (0):
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*T
// CHECK: [ACTIVE] %3 = alloc_stack [lexical] $(Int, Int, (T, Int), Int), var, name "tuple"
// CHECK: [USEFUL] %4 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 0
// CHECK: [USEFUL] %5 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 1
// CHECK: [ACTIVE] %6 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 2
// CHECK: [USEFUL] %7 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 3
// CHECK: [ACTIVE] %18 = tuple_element_addr %6 : $*(T, Int), 0
// CHECK: [USEFUL] %19 = tuple_element_addr %6 : $*(T, Int), 1
// CHECK: [ACTIVE] %35 = begin_access [modify] [static] %3 : $*(Int, Int, (T, Int), Int)
// CHECK: [USEFUL] %36 = tuple_element_addr %35 : $*(Int, Int, (T, Int), Int), 0
// CHECK: [ACTIVE] %41 = begin_access [modify] [static] %3 : $*(Int, Int, (T, Int), Int)
// CHECK: [ACTIVE] %42 = tuple_element_addr %41 : $*(Int, Int, (T, Int), Int), 2
// CHECK: [ACTIVE] %43 = tuple_element_addr %42 : $*(T, Int), 0
// CHECK: [ACTIVE] %51 = begin_access [modify] [static] %3 : $*(Int, Int, (T, Int), Int)
// CHECK: [USEFUL] %52 = tuple_element_addr %51 : $*(Int, Int, (T, Int), Int), 3
// CHECK: [ACTIVE] %55 = begin_access [read] [static] %3 : $*(Int, Int, (T, Int), Int)
// CHECK: [ACTIVE] %56 = tuple_element_addr %55 : $*(Int, Int, (T, Int), Int), 2
// CHECK: [ACTIVE] %57 = tuple_element_addr %56 : $*(T, Int), 0
// TF-781: check active local address + nested conditionals.
@differentiable(reverse, wrt: x)
func TF_781(_ x: Float, _ y: Float) -> Float {
var result = y
if true {
if true {
result = result * x // check activity of `result` and this `apply`
}
}
return result
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}TF_781{{.*}} at parameter indices (0) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [USEFUL] %1 = argument of bb0 : $Float
// CHECK: [ACTIVE] %4 = alloc_stack [lexical] $Float, var, name "result"
// CHECK: [ACTIVE] %19 = begin_access [read] [static] %4 : $*Float
// CHECK: [ACTIVE] %20 = load [trivial] %19 : $*Float
// CHECK: [ACTIVE] %23 = apply %22(%20, %0, %18) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %24 = begin_access [modify] [static] %4 : $*Float
// CHECK: [ACTIVE] %31 = begin_access [read] [static] %4 : $*Float
// CHECK: [ACTIVE] %32 = load [trivial] %31 : $*Float
// TF-954: check nested conditionals and addresses.
@differentiable(reverse)
func TF_954(_ x: Float) -> Float {
var outer = x
outerIf: if true {
var inner = outer
inner = inner * x // check activity of this `apply`
if false {
break outerIf
}
outer = inner
}
return outer
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}TF_954{{.*}} at parameter indices (0) and result indices (0)
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Float, var, name "outer"
// CHECK: bb1:
// CHECK: [ACTIVE] %10 = alloc_stack [lexical] $Float, var, name "inner"
// CHECK: [ACTIVE] %11 = begin_access [read] [static] %2 : $*Float
// CHECK: [USEFUL] %14 = metatype $@thin Float.Type
// CHECK: [ACTIVE] %15 = begin_access [read] [static] %10 : $*Float
// CHECK: [ACTIVE] %16 = load [trivial] %15 : $*Float
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: %18 = function_ref @$sSf1moiyS2f_SftFZ : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %19 = apply %18(%16, %0, %14) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %20 = begin_access [modify] [static] %10 : $*Float
// CHECK: bb3:
// CHECK: [ACTIVE] %31 = begin_access [read] [static] %10 : $*Float
// CHECK: [ACTIVE] %32 = load [trivial] %31 : $*Float
// CHECK: [ACTIVE] %34 = begin_access [modify] [static] %2 : $*Float
// CHECK: bb5:
// CHECK: [ACTIVE] %40 = begin_access [read] [static] %2 : $*Float
// CHECK: [ACTIVE] %41 = load [trivial] %40 : $*Float
//===----------------------------------------------------------------------===//
// Branching cast instructions
//===----------------------------------------------------------------------===//
@differentiable(reverse)
func checked_cast_branch(_ x: Float) -> Float {
// expected-warning @+1 {{'is' test is always true}}
if Int.self is Any.Type {
return x + x
}
return x * x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}checked_cast_branch{{.*}} at parameter indices (0) and result indices (0)
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [NONE] %2 = metatype $@thin Int.Type
// CHECK: [NONE] %3 = metatype $@thick Int.Type
// CHECK: bb1:
// CHECK: [NONE] %5 = argument of bb1 : $@thick Any.Type
// CHECK: [NONE] %6 = integer_literal $Builtin.Int1, -1
// CHECK: bb2:
// CHECK: [NONE] %8 = argument of bb2 : $@thick Int.Type
// CHECK: [NONE] %9 = integer_literal $Builtin.Int1, 0
// CHECK: bb3:
// CHECK: [NONE] %11 = argument of bb3 : $Builtin.Int1
// CHECK: [NONE] %12 = metatype $@thin Bool.Type
// CHECK: [NONE] // function_ref Bool.init(_builtinBooleanLiteral:)
// CHECK: [NONE] %14 = apply %13(%11, %12) : $@convention(method) (Builtin.Int1, @thin Bool.Type) -> Bool
// CHECK: [NONE] %15 = struct_extract %14 : $Bool, #Bool._value
// CHECK: bb4:
// CHECK: [USEFUL] %17 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref static Float.+ infix(_:_:)
// CHECK: [ACTIVE] %19 = apply %18(%0, %0, %17) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: bb5:
// CHECK: [USEFUL] %21 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: [ACTIVE] %23 = apply %22(%0, %0, %21) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK-LABEL: sil hidden [ossa] @${{.*}}checked_cast_branch{{.*}} : $@convention(thin) (Float) -> Float {
// CHECK: checked_cast_br %3 : $@thick Int.Type to Any.Type, bb1, bb2
// CHECK: }
@differentiable(reverse)
func checked_cast_addr_nonactive_result<T: Differentiable>(_ x: T) -> T {
if let _ = x as? Float {
// Do nothing with `y: Float?` value.
}
return x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}checked_cast_addr_nonactive_result{{.*}} at parameter indices (0) and result indices (0)
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*T
// CHECK: [VARIED] %3 = alloc_stack $T
// CHECK: [VARIED] %5 = alloc_stack $Float
// CHECK: bb1:
// CHECK: [VARIED] %7 = load [trivial] %5 : $*Float
// CHECK: [VARIED] %8 = enum $Optional<Float>, #Optional.some!enumelt, %7 : $Float
// CHECK: bb2:
// CHECK: [NONE] %11 = enum $Optional<Float>, #Optional.none!enumelt
// CHECK: bb3:
// CHECK: [VARIED] %14 = argument of bb3 : $Optional<Float>
// CHECK: bb4:
// CHECK: bb5:
// CHECK: [VARIED] %18 = argument of bb5 : $Float
// CHECK: bb6:
// CHECK: [NONE] %22 = tuple ()
// CHECK-LABEL: sil hidden [ossa] @${{.*}}checked_cast_addr_nonactive_result{{.*}} : $@convention(thin) <T where T : Differentiable> (@in_guaranteed T) -> @out T {
// CHECK: checked_cast_addr_br take_always T in %3 : $*T to Float in %5 : $*Float, bb1, bb2
// CHECK: }
// expected-error @+1 {{function is not differentiable}}
@differentiable(reverse)
// expected-note @+1 {{when differentiating this function definition}}
func checked_cast_addr_active_result<T: Differentiable>(x: T) -> T {
// expected-note @+1 {{expression is not differentiable}}
if let y = x as? Float {
// Use `y: Float?` value in an active way.
return y as! T
}
return x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}checked_cast_addr_active_result{{.*}} at parameter indices (0) and result indices (0)
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*T
// CHECK: [ACTIVE] %3 = alloc_stack $T
// CHECK: [ACTIVE] %5 = alloc_stack $Float
// CHECK: bb1:
// CHECK: [ACTIVE] %7 = load [trivial] %5 : $*Float
// CHECK: [ACTIVE] %8 = enum $Optional<Float>, #Optional.some!enumelt, %7 : $Float
// CHECK: bb2:
// CHECK: [USEFUL] %11 = enum $Optional<Float>, #Optional.none!enumelt
// CHECK: bb3:
// CHECK: [ACTIVE] %14 = argument of bb3 : $Optional<Float>
// CHECK: bb4:
// CHECK: [ACTIVE] %16 = argument of bb4 : $Float
// CHECK: [ACTIVE] %19 = alloc_stack $Float
// CHECK: bb5:
// CHECK: bb6:
// CHECK: [NONE] %27 = tuple ()
// CHECK-LABEL: sil hidden [ossa] @${{.*}}checked_cast_addr_active_result{{.*}} : $@convention(thin) <T where T : Differentiable> (@in_guaranteed T) -> @out T {
// CHECK: checked_cast_addr_br take_always T in %3 : $*T to Float in %5 : $*Float, bb1, bb2
// CHECK: }
//===----------------------------------------------------------------------===//
// Array literal differentiation
//===----------------------------------------------------------------------===//
// Check `array.uninitialized_intrinsic` applications.
@differentiable(reverse)
func testArrayUninitializedIntrinsic(_ x: Float, _ y: Float) -> [Float] {
return [x, y]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsic{{.*}} at parameter indices (0, 1) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %1 = argument of bb0 : $Float
// CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %6 = apply %5<Float>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [VARIED] %11 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %12 = index_addr %9 : $*Float, %11 : $Builtin.Word
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %15 = apply %14<Float>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
@differentiable(reverse where T: Differentiable)
func testArrayUninitializedIntrinsicGeneric<T>(_ x: T, _ y: T) -> [T] {
return [x, y]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicGeneric{{.*}} at parameter indices (0, 1) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*T
// CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %6 = apply %5<T>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<T>, Builtin.RawPointer)
// CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<T>, Builtin.RawPointer)
// CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*T
// CHECK: [VARIED] %11 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %12 = index_addr %9 : $*T, %11 : $Builtin.Word
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %15 = apply %14<T>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// TF-952: Test array literal initialized from an address (e.g. `var`).
@differentiable(reverse)
func testArrayUninitializedIntrinsicAddress(_ x: Float, _ y: Float) -> [Float] {
var result = x
result = result * y
return [result, result]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicAddress{{.*}} at parameter indices (0, 1) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %1 = argument of bb0 : $Float
// CHECK: [ACTIVE] %4 = alloc_stack [lexical] $Float, var, name "result"
// CHECK: [ACTIVE] %7 = begin_access [read] [static] %4 : $*Float
// CHECK: [ACTIVE] %8 = load [trivial] %7 : $*Float
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: [ACTIVE] %11 = apply %10(%8, %1, %6) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %12 = begin_access [modify] [static] %4 : $*Float
// CHECK: [USEFUL] %15 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %17 = apply %16<Float>(%15) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%18**, %19) = destructure_tuple %17 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [VARIED] (%18, **%19**) = destructure_tuple %17 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [ACTIVE] %20 = pointer_to_address %19 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [ACTIVE] %21 = begin_access [read] [static] %4 : $*Float
// CHECK: [VARIED] %24 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %25 = index_addr %20 : $*Float, %24 : $Builtin.Word
// CHECK: [ACTIVE] %26 = begin_access [read] [static] %4 : $*Float
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %30 = apply %29<Float>(%18) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// TF-952: Test array literal initialized with `apply` direct results.
@differentiable(reverse)
func testArrayUninitializedIntrinsicFunctionResult(_ x: Float, _ y: Float) -> [Float] {
return [x * y, x * y]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicFunctionResult{{.*}} at parameter indices (0, 1) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %1 = argument of bb0 : $Float
// CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %6 = apply %5<Float>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: [ACTIVE] %12 = apply %11(%0, %1, %10) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [VARIED] %14 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %15 = index_addr %9 : $*Float, %14 : $Builtin.Word
// CHECK: [USEFUL] %16 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: [ACTIVE] %18 = apply %17(%0, %1, %16) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %21 = apply %20<Float>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// TF-975: Test nested array literals.
@differentiable(reverse)
func testArrayUninitializedIntrinsicNested(_ x: Float, _ y: Float) -> [Float] {
let array = [x, y]
return [array[0], array[1]]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicNested{{.*}} at parameter indices (0, 1) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %1 = argument of bb0 : $Float
// CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %6 = apply %5<Float>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [VARIED] %11 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %12 = index_addr %9 : $*Float, %11 : $Builtin.Word
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] [[ARRAY:%.*]] = apply %14<Float>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// CHECK: [USEFUL] [[INT_LIT:%.*]] = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] [[TUP:%.*]] = apply %19<Float>([[INT_LIT]]) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**[[LHS:%.*]]**, [[RHS:%.*]]) = destructure_tuple [[TUP]] : $(Array<Float>, Builtin.RawPointer)
// CHECK: [VARIED] ([[LHS]], **[[RHS]]**) = destructure_tuple [[TUP]] : $(Array<Float>, Builtin.RawPointer)
// CHECK: [ACTIVE] [[FLOAT_PTR:%.*]] = pointer_to_address [[RHS]] : $Builtin.RawPointer to [strict] $*Float
// CHECK: [USEFUL] [[ZERO_LITERAL:%.*]] = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] [[META:%.*]] = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] [[RESULT_2:%.*]] = apply %26([[ZERO_LITERAL]], [[META]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [NONE] // function_ref Array.subscript.getter
// CHECK: [NONE] %29 = apply %28<Float>([[FLOAT_PTR]], [[RESULT_2]], %16) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0
// CHECK: [VARIED] [[ONE_LITERAL:%.*]] = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] [[INDEX_ADDR:%.*]] = index_addr [[FLOAT_PTR]] : $*Float, [[ONE_LITERAL]] : $Builtin.Word
// CHECK: [USEFUL] [[ONE_LITERAL_AGAIN:%.*]] = integer_literal $Builtin.IntLiteral, 1
// CHECK: [USEFUL] [[META_AGAIN:%.*]] = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %35 = apply %34([[ONE_LITERAL_AGAIN]], [[META_AGAIN]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [NONE] // function_ref Array.subscript.getter
// CHECK: [NONE] %37 = apply %36<Float>(%31, %35, %16) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %39 = apply %38<Float>(%21) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// TF-978: Test array literal initialized with `apply` indirect results.
struct Wrapper<T: Differentiable>: Differentiable {
var value: T
}
@differentiable(reverse)
func testArrayUninitializedIntrinsicApplyIndirectResult<T>(_ x: T, _ y: T) -> [Wrapper<T>] {
return [Wrapper(value: x), Wrapper(value: y)]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicApplyIndirectResult{{.*}} at parameter indices (0, 1) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*T
// CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %6 = apply %5<Wrapper<T>>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Wrapper<T>>, Builtin.RawPointer)
// CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Wrapper<T>>, Builtin.RawPointer)
// CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Wrapper<T>
// CHECK: [USEFUL] %10 = metatype $@thin Wrapper<T>.Type
// CHECK: [ACTIVE] %11 = alloc_stack $T
// CHECK: [NONE] // function_ref Wrapper.init(value:)
// CHECK: [NONE] %14 = apply %13<T>(%9, %11, %10) : $@convention(method) <τ_0_0 where τ_0_0 : Differentiable> (@in τ_0_0, @thin Wrapper<τ_0_0>.Type) -> @out Wrapper<τ_0_0>
// CHECK: [VARIED] %16 = integer_literal $Builtin.Word, 1
// CHECK: [ACTIVE] %17 = index_addr %9 : $*Wrapper<T>, %16 : $Builtin.Word
// CHECK: [USEFUL] %18 = metatype $@thin Wrapper<T>.Type
// CHECK: [ACTIVE] %19 = alloc_stack $T
// CHECK: [NONE] // function_ref Wrapper.init(value:)
// CHECK: [NONE] %22 = apply %21<T>(%17, %19, %18) : $@convention(method) <τ_0_0 where τ_0_0 : Differentiable> (@in τ_0_0, @thin Wrapper<τ_0_0>.Type) -> @out Wrapper<τ_0_0>
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [ACTIVE] %25 = apply %24<Wrapper<T>>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
//===----------------------------------------------------------------------===//
// `inout` argument differentiation
//===----------------------------------------------------------------------===//
struct Mut: Differentiable {}
extension Mut {
@differentiable(reverse, wrt: x)
mutating func mutatingMethod(_ x: Mut) {}
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}3MutV14mutatingMethodyyACF at parameter indices (0) and result indices (0)
// CHECK: [VARIED] %0 = argument of bb0 : $Mut
// CHECK: [USEFUL] %1 = argument of bb0 : $*Mut
// TODO(TF-985): Find workaround to avoid marking non-wrt `inout` argument as
// active.
@differentiable(reverse, wrt: x)
func nonActiveInoutArg(_ nonactive: inout Mut, _ x: Mut) {
nonactive.mutatingMethod(x)
nonactive = x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}17nonActiveInoutArgyyAA3MutVz_ADtF at parameter indices (1) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $*Mut
// CHECK: [ACTIVE] %1 = argument of bb0 : $Mut
// CHECK: [ACTIVE] %4 = begin_access [modify] [static] %0 : $*Mut
// CHECK: [NONE] // function_ref Mut.mutatingMethod(_:)
// CHECK: [NONE] %6 = apply %5(%1, %4) : $@convention(method) (Mut, @inout Mut) -> ()
// CHECK: [ACTIVE] %8 = begin_access [modify] [static] %0 : $*Mut
@differentiable(reverse, wrt: x)
func activeInoutArgMutatingMethod(_ x: Mut) -> Mut {
var result = x
result.mutatingMethod(result)
return result
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}28activeInoutArgMutatingMethodyAA3MutVADF at parameter indices (0) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $Mut
// CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Mut, var, name "result"
// CHECK: [ACTIVE] %4 = begin_access [read] [static] %2 : $*Mut
// CHECK: [ACTIVE] %5 = load [trivial] %4 : $*Mut
// CHECK: [ACTIVE] %7 = begin_access [modify] [static] %2 : $*Mut
// CHECK: [NONE] // function_ref Mut.mutatingMethod(_:)
// CHECK: [NONE] %9 = apply %8(%5, %7) : $@convention(method) (Mut, @inout Mut) -> ()
// CHECK: [ACTIVE] %11 = begin_access [read] [static] %2 : $*Mut
// CHECK: [ACTIVE] %12 = load [trivial] %11 : $*Mut
@differentiable(reverse, wrt: x)
func activeInoutArgMutatingMethodVar(_ nonactive: inout Mut, _ x: Mut) {
var result = nonactive
result.mutatingMethod(x)
nonactive = result
}
// CHECK_LABEL: [AD] Activity info for ${{.*}}31activeInoutArgMutatingMethodVaryyAA3MutVz_ADtF at (parameters=(1) results=(0))
// CHECK: [ACTIVE] %0 = argument of bb0 : $*Mut
// CHECK: [ACTIVE] %1 = argument of bb0 : $Mut
// CHECK: [ACTIVE] %4 = alloc_stack [lexical] $Mut, var, name "result"
// CHECK: [ACTIVE] %5 = begin_access [read] [static] %0 : $*Mut
// CHECK: [ACTIVE] %8 = begin_access [modify] [static] %4 : $*Mut
// CHECK: [NONE] // function_ref Mut.mutatingMethod(_:)
// CHECK: %9 = function_ref @${{.*}}3MutV14mutatingMethodyyACF : $@convention(method) (Mut, @inout Mut) -> ()
// CHECK: [NONE] %10 = apply %9(%1, %8) : $@convention(method) (Mut, @inout Mut) -> ()
// CHECK: [ACTIVE] %12 = begin_access [read] [static] %4 : $*Mut
// CHECK: [ACTIVE] %13 = load [trivial] %12 : $*Mut
// CHECK: [ACTIVE] %15 = begin_access [modify] [static] %0 : $*Mut
// CHECK: [NONE] %19 = tuple ()
@differentiable(reverse, wrt: x)
func activeInoutArgMutatingMethodTuple(_ nonactive: inout Mut, _ x: Mut) {
var result = (nonactive, x)
result.0.mutatingMethod(result.0)
nonactive = result.0
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}33activeInoutArgMutatingMethodTupleyyAA3MutVz_ADtF at parameter indices (1) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $*Mut
// CHECK: [ACTIVE] %1 = argument of bb0 : $Mut
// CHECK: [ACTIVE] %4 = alloc_stack [lexical] $(Mut, Mut), var, name "result"
// CHECK: [ACTIVE] %5 = tuple_element_addr %4 : $*(Mut, Mut), 0
// CHECK: [ACTIVE] %6 = tuple_element_addr %4 : $*(Mut, Mut), 1
// CHECK: [ACTIVE] %7 = begin_access [read] [static] %0 : $*Mut
// CHECK: [ACTIVE] %11 = begin_access [read] [static] %4 : $*(Mut, Mut)
// CHECK: [ACTIVE] %12 = tuple_element_addr %11 : $*(Mut, Mut), 0
// CHECK: [ACTIVE] %13 = load [trivial] %12 : $*Mut
// CHECK: [ACTIVE] %15 = begin_access [modify] [static] %4 : $*(Mut, Mut)
// CHECK: [ACTIVE] %16 = tuple_element_addr %15 : $*(Mut, Mut), 0
// CHECK: [NONE] // function_ref Mut.mutatingMethod(_:)
// CHECK: [NONE] %18 = apply %17(%13, %16) : $@convention(method) (Mut, @inout Mut) -> ()
// CHECK: [ACTIVE] %20 = begin_access [read] [static] %4 : $*(Mut, Mut)
// CHECK: [ACTIVE] %21 = tuple_element_addr %20 : $*(Mut, Mut), 0
// CHECK: [ACTIVE] %22 = load [trivial] %21 : $*Mut
// CHECK: [ACTIVE] %24 = begin_access [modify] [static] %0 : $*Mut
// Check `inout` arguments.
@differentiable(reverse)
func activeInoutArg(_ x: Float) -> Float {
var result = x
result += x
return result
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}activeInoutArg{{.*}} at parameter indices (0) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Float, var, name "result"
// CHECK: [ACTIVE] %5 = begin_access [modify] [static] %2 : $*Float
// CHECK: [NONE] // function_ref static Float.+= infix(_:_:)
// CHECK: [NONE] %7 = apply %6(%5, %0, %4) : $@convention(method) (@inout Float, Float, @thin Float.Type) -> ()
// CHECK: [ACTIVE] %9 = begin_access [read] [static] %2 : $*Float
// CHECK: [ACTIVE] %10 = load [trivial] %9 : $*Float
@differentiable(reverse)
func activeInoutArgNonactiveInitialResult(_ x: Float) -> Float {
var result: Float = 1
result += x
return result
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}activeInoutArgNonactiveInitialResult{{.*}} at parameter indices (0) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Float, var, name "result"
// CHECK: [NONE] // function_ref Float.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %6 = apply %5(%3, %4) : $@convention(method) (Builtin.IntLiteral, @thin Float.Type) -> Float
// CHECK: [USEFUL] %8 = metatype $@thin Float.Type
// CHECK: [ACTIVE] %9 = begin_access [modify] [static] %2 : $*Float
// CHECK: [NONE] // function_ref static Float.+= infix(_:_:)
// CHECK: [NONE] %11 = apply %10(%9, %0, %8) : $@convention(method) (@inout Float, Float, @thin Float.Type) -> ()
// CHECK: [ACTIVE] %13 = begin_access [read] [static] %2 : $*Float
// CHECK: [ACTIVE] %14 = load [trivial] %13 : $*Float
//===----------------------------------------------------------------------===//
// Throwing function differentiation (`try_apply`)
//===----------------------------------------------------------------------===//
// TF-433: Test `try_apply`.
func rethrowing(_ x: () throws -> Void) rethrows -> Void {}
@differentiable(reverse)
func testTryApply(_ x: Float) -> Float {
rethrowing({})
return x
}
// TF-433: differentiation diagnoses `try_apply` before activity info is printed.
// CHECK-LABEL: [AD] Activity info for ${{.*}}testTryApply{{.*}} at parameter indices (0) and result indices (0)
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [NONE] // function_ref closure #1 in testTryApply(_:)
// CHECK: [NONE] %3 = thin_to_thick_function %2 : $@convention(thin) () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [NONE] %4 = convert_function %3 : $@noescape @callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> @error Error
// CHECK: [NONE] // function_ref rethrowing(_:)
// CHECK: bb1:
// CHECK: [NONE] %7 = argument of bb1 : $()
// CHECK: bb2:
// CHECK: [NONE] %9 = argument of bb2 : $Error
//===----------------------------------------------------------------------===//
// Coroutine differentiation (`begin_apply`)
//===----------------------------------------------------------------------===//
struct HasCoroutineAccessors: Differentiable {
var stored: Float
var computed: Float {
// `_read` is a coroutine: `(Self) -> () -> ()`.
_read { yield stored }
// `_modify` is a coroutine: `(inout Self) -> () -> ()`.
_modify { yield &stored }
}
}
// expected-error @+1 {{function is not differentiable}}
@differentiable(reverse)
// expected-note @+1 {{when differentiating this function definition}}
func testAccessorCoroutines(_ x: HasCoroutineAccessors) -> HasCoroutineAccessors {
var x = x
// expected-note @+1 {{differentiation of coroutine calls is not yet supported}}
x.computed = x.computed
return x
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testAccessorCoroutines{{.*}} at parameter indices (0) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $HasCoroutineAccessors
// CHECK: [ACTIVE] %2 = alloc_stack [lexical] $HasCoroutineAccessors, var, name "x"
// CHECK: [ACTIVE] %4 = begin_access [read] [static] %2 : $*HasCoroutineAccessors
// CHECK: [ACTIVE] %5 = load [trivial] %4 : $*HasCoroutineAccessors
// CHECK: [NONE] // function_ref HasCoroutineAccessors.computed.read
// CHECK: [ACTIVE] (**%7**, %8) = begin_apply %6(%5) : $@yield_once @convention(method) (HasCoroutineAccessors) -> @yields Float
// CHECK: [VARIED] (%7, **%8**) = begin_apply %6(%5) : $@yield_once @convention(method) (HasCoroutineAccessors) -> @yields Float
// CHECK: [ACTIVE] %9 = alloc_stack $Float
// CHECK: [ACTIVE] %11 = load [trivial] %9 : $*Float
// CHECK: [ACTIVE] %14 = begin_access [modify] [static] %2 : $*HasCoroutineAccessors
// CHECK: [NONE] // function_ref HasCoroutineAccessors.computed.modify
// CHECK: %15 = function_ref @${{.*}}21HasCoroutineAccessorsV8computedSfvM : $@yield_once @convention(method) (@inout HasCoroutineAccessors) -> @yields @inout Float
// CHECK: [ACTIVE] (**%16**, %17) = begin_apply %15(%14) : $@yield_once @convention(method) (@inout HasCoroutineAccessors) -> @yields @inout Float
// CHECK: [VARIED] (%16, **%17**) = begin_apply %15(%14) : $@yield_once @convention(method) (@inout HasCoroutineAccessors) -> @yields @inout Float
// CHECK: [ACTIVE] %22 = begin_access [read] [static] %2 : $*HasCoroutineAccessors
// CHECK: [ACTIVE] %23 = load [trivial] %22 : $*HasCoroutineAccessors
// TF-1078: Test `begin_apply` active `inout` argument.
// `Array.subscript.modify` is the applied coroutine.
// expected-error @+1 {{function is not differentiable}}
@differentiable(reverse)
// expected-note @+1 {{when differentiating this function definition}}
func testBeginApplyActiveInoutArgument(array: [Float], x: Float) -> Float {
var array = array
// Array subscript assignment below calls `Array.subscript.modify`.
// expected-note @+1 {{differentiation of coroutine calls is not yet supported}}
array[0] = x
return array[0]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testBeginApplyActiveInoutArgument{{.*}} at parameter indices (0, 1) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $Array<Float>
// CHECK: [ACTIVE] %1 = argument of bb0 : $Float
// CHECK: [ACTIVE] %4 = alloc_stack [lexical] $Array<Float>, var, name "array"
// CHECK: [ACTIVE] %5 = copy_value %0 : $Array<Float>
// CHECK: [USEFUL] %7 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %8 = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %10 = apply %9(%7, %8) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [ACTIVE] %11 = begin_access [modify] [static] %4 : $*Array<Float>
// CHECK: [NONE] // function_ref Array.subscript.modify
// CHECK: [ACTIVE] (**%13**, %14) = begin_apply %12<Float>(%10, %11) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: [VARIED] (%13, **%14**) = begin_apply %12<Float>(%10, %11) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: [USEFUL] %18 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %19 = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %21 = apply %20(%18, %19) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [ACTIVE] %22 = begin_access [read] [static] %4 : $*Array<Float>
// CHECK: [ACTIVE] %23 = load_borrow %22 : $*Array<Float>
// CHECK: [ACTIVE] %24 = alloc_stack $Float
// CHECK: [NONE] // function_ref Array.subscript.getter
// CHECK: [NONE] %26 = apply %25<Float>(%24, %21, %23) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0
// CHECK: [ACTIVE] %27 = load [trivial] %24 : $*Float
// TF-1115: Test `begin_apply` active `inout` argument with non-active initial result.
// expected-error @+1 {{function is not differentiable}}
@differentiable(reverse)
// expected-note @+1 {{when differentiating this function definition}}
func testBeginApplyActiveButInitiallyNonactiveInoutArgument(x: Float) -> Float {
// `var array` is initially non-active.
var array: [Float] = [0]
// Array subscript assignment below calls `Array.subscript.modify`.
// expected-note @+1 {{differentiation of coroutine calls is not yet supported}}
array[0] = x
return array[0]
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testBeginApplyActiveButInitiallyNonactiveInoutArgument{{.*}} at parameter indices (0) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Array<Float>, var, name "array"
// CHECK: [USEFUL] %3 = integer_literal $Builtin.Word, 1
// CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:)
// CHECK: [USEFUL] %5 = apply %4<Float>(%3) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [USEFUL] (**%6**, %7) = destructure_tuple %5 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [NONE] (%6, **%7**) = destructure_tuple %5 : $(Array<Float>, Builtin.RawPointer)
// CHECK: [USEFUL] %8 = pointer_to_address %7 : $Builtin.RawPointer to [strict] $*Float
// CHECK: [USEFUL] %9 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %10 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref Float.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %12 = apply %11(%9, %10) : $@convention(method) (Builtin.IntLiteral, @thin Float.Type) -> Float
// CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:)
// CHECK: [USEFUL] %15 = apply %14<Float>(%6) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0>
// CHECK: [USEFUL] %17 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %18 = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %20 = apply %19(%17, %18) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [ACTIVE] %21 = begin_access [modify] [static] %2 : $*Array<Float>
// CHECK: [NONE] // function_ref Array.subscript.modify
// CHECK: [ACTIVE] (**%23**, %24) = begin_apply %22<Float>(%20, %21) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: [VARIED] (%23, **%24**) = begin_apply %22<Float>(%20, %21) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0
// CHECK: [USEFUL] %28 = integer_literal $Builtin.IntLiteral, 0
// CHECK: [USEFUL] %29 = metatype $@thin Int.Type
// CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %31 = apply %30(%28, %29) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [ACTIVE] %32 = begin_access [read] [static] %2 : $*Array<Float>
// CHECK: [ACTIVE] %33 = load_borrow %32 : $*Array<Float>
// CHECK: [ACTIVE] %34 = alloc_stack $Float
// CHECK: [NONE] // function_ref Array.subscript.getter
// CHECK: [NONE] %36 = apply %35<Float>(%34, %31, %33) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0
// CHECK: [ACTIVE] %37 = load [trivial] %34 : $*Float
//===----------------------------------------------------------------------===//
// Class differentiation
//===----------------------------------------------------------------------===//
class C: Differentiable {
@differentiable(reverse)
var float: Float
init(_ float: Float) {
self.float = float
}
@differentiable(reverse)
func method(_ x: Float) -> Float {
x * float
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}1CC6methodyS2fF at parameter indices (0, 1) and result indices (0)
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %1 = argument of bb0 : $C
// CHECK: [USEFUL] %4 = metatype $@thin Float.Type
// CHECK: [VARIED] %5 = class_method %1 : $C, #C.float!getter : (C) -> () -> Float, $@convention(method) (@guaranteed C) -> Float
// CHECK: [ACTIVE] %6 = apply %5(%1) : $@convention(method) (@guaranteed C) -> Float
// CHECK: [NONE] // function_ref static Float.* infix(_:_:)
// CHECK: %7 = function_ref @$sSf1moiyS2f_SftFZ : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %8 = apply %7(%0, %6, %4) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
}
// TF-1176: Test class property `modify` accessor.
@differentiable(reverse)
func testClassModifyAccessor(_ c: inout C) {
c.float *= c.float
}
// FIXME(TF-1176): Some values are incorrectly not marked as active: `%16`, etc.
// CHECK-LABEL: [AD] Activity info for ${{.*}}testClassModifyAccessor{{.*}} at parameter indices (0) and result indices (0)
// CHECK: [ACTIVE] %0 = argument of bb0 : $*C
// CHECK: [NONE] %2 = metatype $@thin Float.Type
// CHECK: [ACTIVE] %3 = begin_access [read] [static] %0 : $*C
// CHECK: [VARIED] %4 = load [copy] %3 : $*C
// CHECK: [ACTIVE] %6 = begin_access [read] [static] %0 : $*C
// CHECK: [VARIED] %7 = load [copy] %6 : $*C
// CHECK: [VARIED] %9 = class_method %7 : $C, #C.float!getter : (C) -> () -> Float, $@convention(method) (@guaranteed C) -> Float
// CHECK: [VARIED] %10 = apply %9(%7) : $@convention(method) (@guaranteed C) -> Float
// CHECK: [VARIED] %12 = class_method %4 : $C, #C.float!modify : (C) -> () -> (), $@yield_once @convention(method) (@guaranteed C) -> @yields @inout Float
// CHECK: [VARIED] (**%13**, %14) = begin_apply %12(%4) : $@yield_once @convention(method) (@guaranteed C) -> @yields @inout Float
// CHECK: [VARIED] (%13, **%14**) = begin_apply %12(%4) : $@yield_once @convention(method) (@guaranteed C) -> @yields @inout Float
// CHECK: [NONE] // function_ref static Float.*= infix(_:_:)
// CHECK: [NONE] %16 = apply %15(%13, %10, %2) : $@convention(method) (@inout Float, Float, @thin Float.Type) -> ()
//===----------------------------------------------------------------------===//
// Enum differentiation
//===----------------------------------------------------------------------===//
// expected-error @+1 {{function is not differentiable}}
@differentiable(reverse)
// expected-note @+1 {{when differentiating this function definition}}
func testActiveOptional(_ x: Float) -> Float {
var maybe: Float? = 10
// expected-note @+1 {{expression is not differentiable}}
maybe = x
return maybe!
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testActiveOptional{{.*}} at parameter indices (0) and result indices (0)
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $Float
// CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Optional<Float>, var, name "maybe"
// CHECK: [USEFUL] %3 = integer_literal $Builtin.IntLiteral, 10
// CHECK: [USEFUL] %4 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref Float.init(_builtinIntegerLiteral:)
// CHECK: [USEFUL] %6 = apply %5(%3, %4) : $@convention(method) (Builtin.IntLiteral, @thin Float.Type) -> Float
// CHECK: [USEFUL] %7 = enum $Optional<Float>, #Optional.some!enumelt, %6 : $Float
// CHECK: [ACTIVE] %9 = enum $Optional<Float>, #Optional.some!enumelt, %0 : $Float
// CHECK: [ACTIVE] %10 = begin_access [modify] [static] %2 : $*Optional<Float>
// CHECK: [ACTIVE] %13 = begin_access [read] [static] %2 : $*Optional<Float>
// CHECK: [ACTIVE] %14 = load [trivial] %13 : $*Optional<Float>
// CHECK: bb1:
// CHECK: [NONE] // function_ref _diagnoseUnexpectedNilOptional(_filenameStart:_filenameLength:_filenameIsASCII:_line:_isImplicitUnwrap:)
// CHECK: [NONE] %24 = apply %23(%17, %18, %19, %20, %22) : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, Builtin.Word, Builtin.Int1) -> ()
// CHECK: bb2:
// CHECK: [ACTIVE] %26 = argument of bb2 : $Float
enum DirectEnum: Differentiable & AdditiveArithmetic {
case case0
case case1(Float)
case case2(Float, Float)
typealias TangentVector = Self
static var zero: Self { fatalError() }
static func +(_ lhs: Self, _ rhs: Self) -> Self { fatalError() }
static func -(_ lhs: Self, _ rhs: Self) -> Self { fatalError() }
}
// expected-error @+1 {{function is not differentiable}}
@differentiable(reverse, wrt: e)
// expected-note @+2 {{when differentiating this function definition}}
// expected-note @+1 {{differentiating enum values is not yet supported}}
func testActiveEnumValue(_ e: DirectEnum, _ x: Float) -> Float {
switch e {
case .case0: return x
case let .case1(y1): return y1
case let .case2(y1, y2): return y1 + y2
}
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testActiveEnumValue{{.*}} at parameter indices (0) and result indices (0)
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $DirectEnum
// CHECK: [USEFUL] %1 = argument of bb0 : $Float
// CHECK: bb1:
// CHECK: bb2:
// CHECK: [ACTIVE] %6 = argument of bb2 : $Float
// CHECK: bb3:
// CHECK: [ACTIVE] %9 = argument of bb3 : $(Float, Float)
// CHECK: [ACTIVE] (**%10**, %11) = destructure_tuple %9 : $(Float, Float)
// CHECK: [ACTIVE] (%10, **%11**) = destructure_tuple %9 : $(Float, Float)
// CHECK: [USEFUL] %14 = metatype $@thin Float.Type
// CHECK: [NONE] // function_ref static Float.+ infix(_:_:)
// CHECK: %15 = function_ref @$sSf1poiyS2f_SftFZ : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: [ACTIVE] %16 = apply %15(%10, %11, %14) : $@convention(method) (Float, Float, @thin Float.Type) -> Float
// CHECK: bb4:
// CHECK: [ACTIVE] %18 = argument of bb4 : $Float
enum IndirectEnum<T: Differentiable>: Differentiable & AdditiveArithmetic {
case case1(T)
case case2(Float, T)
typealias TangentVector = Self
static func ==(_ lhs: Self, _ rhs: Self) -> Bool { fatalError() }
static var zero: Self { fatalError() }
static func +(_ lhs: Self, _ rhs: Self) -> Self { fatalError() }
static func -(_ lhs: Self, _ rhs: Self) -> Self { fatalError() }
}
// expected-error @+1 {{function is not differentiable}}
@differentiable(reverse, wrt: e)
// expected-note @+2 {{when differentiating this function definition}}
// expected-note @+1 {{differentiating enum values is not yet supported}}
func testActiveEnumAddr<T>(_ e: IndirectEnum<T>) -> T {
switch e {
case let .case1(y1): return y1
case let .case2(_, y2): return y2
}
}
// CHECK-LABEL: [AD] Activity info for ${{.*}}testActiveEnumAddr{{.*}} at parameter indices (0) and result indices (0)
// CHECK: bb0:
// CHECK: [ACTIVE] %0 = argument of bb0 : $*T
// CHECK: [ACTIVE] %1 = argument of bb0 : $*IndirectEnum<T>
// CHECK: [ACTIVE] %3 = alloc_stack $IndirectEnum<T>
// CHECK: bb1:
// CHECK: [ACTIVE] %6 = unchecked_take_enum_data_addr %3 : $*IndirectEnum<T>, #IndirectEnum.case1!enumelt
// CHECK: [ACTIVE] %7 = alloc_stack [lexical] $T, let, name "y1"
// CHECK: bb2:
// CHECK: [ACTIVE] {{.*}} = unchecked_take_enum_data_addr {{.*}} : $*IndirectEnum<T>, #IndirectEnum.case2!enumelt
// CHECK: [ACTIVE] {{.*}} = tuple_element_addr {{.*}} : $*(Float, T), 0
// CHECK: [VARIED] {{.*}} = load [trivial] {{.*}} : $*Float
// CHECK: [ACTIVE] {{.*}} = tuple_element_addr {{.*}} : $*(Float, T), 1
// CHECK: [ACTIVE] {{.*}} = alloc_stack [lexical] $T, let, name "y2"
// CHECK: bb3:
// CHECK: [NONE] {{.*}} = tuple ()
|
apache-2.0
|
02b0d441b9604d90c2f2b8f41c7c8d05
| 53.405152 | 174 | 0.615664 | 3.12014 | false | false | false | false |
karstengresch/rw_studies
|
CoreData/Bow Ties/Bow Ties/ViewController.swift
|
1
|
7417
|
/*
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import CoreData
class ViewController: UIViewController {
var managedContext: NSManagedObjectContext!
var currentBowtie: Bowtie!
// MARK: - IBOutlets
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var timesWornLabel: UILabel!
@IBOutlet weak var lastWornLabel: UILabel!
@IBOutlet weak var favoriteLabel: UILabel!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
insertSampleData()
let fetchRequest = NSFetchRequest<Bowtie>(entityName: "Bowtie")
let firstTitle = segmentedControl.titleForSegment(at: 0)!
fetchRequest.predicate = NSPredicate(format: "searchKey == %@", firstTitle)
do {
let results = try managedContext.fetch(fetchRequest)
currentBowtie = results.first
populate(bowtie: results.first!)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
// MARK: - IBActions
@IBAction func segmentedControl(_ sender: AnyObject) {
guard let segmentedControl = sender as? UISegmentedControl else {
return
}
let selectedValue = segmentedControl.titleForSegment(at: segmentedControl.selectedSegmentIndex)
let fetchRequest = NSFetchRequest<Bowtie>(entityName: "Bowtie")
fetchRequest.predicate = NSPredicate(format: "searchKey == %@", selectedValue!)
do {
let results =
try managedContext.fetch(fetchRequest)
currentBowtie = results.first
populate(bowtie: currentBowtie)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
@IBAction func wear(_ sender: AnyObject) {
let timesWorn = currentBowtie.timesWorn
currentBowtie.timesWorn = timesWorn + 1
currentBowtie.lastWorn = NSDate()
do {
try managedContext.save()
populate(bowtie: currentBowtie)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
@IBAction func rate(_ sender: AnyObject) {
let rateAlert = UIAlertController(title: "New Rating", message: "Rate this bow tie", preferredStyle: .alert)
rateAlert.addTextField { (textField) in textField.keyboardType = .decimalPad }
let cancelAction = UIAlertAction(title: "Cancel", style: .default)
let saveAction = UIAlertAction(title: "Save", style: .default) {
[unowned self] action in
guard let textField = rateAlert.textFields?.first else {
return
}
self.update(rating: textField.text)
}
rateAlert.addAction(cancelAction)
rateAlert.addAction(saveAction)
present(rateAlert, animated: true)
}
func update(rating: String?) {
guard let ratingString = rating, let rating = Double(ratingString) else {
return
}
do {
currentBowtie.rating = rating
try managedContext.save()
populate(bowtie: currentBowtie)
} catch let error as NSError {
if error.domain == NSCocoaErrorDomain && error.code == NSValidationNumberTooLargeError {
update(rating: "5")
} else if error.domain == NSCocoaErrorDomain && error.code == NSValidationNumberTooSmallError {
update(rating: "0")
}
else {
print("Could not fetch \(error), \(error.userInfo)")
}
}
}
func insertSampleData() {
let fetchRequest = NSFetchRequest<Bowtie>(entityName: "Bowtie")
fetchRequest.predicate = NSPredicate(format: "searchKey != nil")
let count = try! managedContext.count(for: fetchRequest)
if count > 0 {
return
}
let sampleDataPath = Bundle.main.path(forResource: "SampleData", ofType: "plist")
let dataArray = NSArray(contentsOfFile: sampleDataPath!)!
for dict in dataArray {
let entity = NSEntityDescription.entity(forEntityName: "Bowtie", in: managedContext)!
let bowtie = Bowtie(entity: entity, insertInto: managedContext)
let bowtieDictionary = dict as! [String: AnyObject]
bowtie.name = bowtieDictionary["name"] as? String
bowtie.searchKey = bowtieDictionary["searchKey"] as? String
bowtie.rating = bowtieDictionary["rating"] as! Double
let colorDictionary = bowtieDictionary["tintColor"] as! [String: AnyObject]
bowtie.tintColor = UIColor.color(colorDictionary: colorDictionary)
let imageName = bowtieDictionary["imageName"] as? String
let image = UIImage(named: imageName!)
let photoData = UIImagePNGRepresentation(image!)!
bowtie.photoData = NSData(data: photoData)
bowtie.lastWorn = bowtieDictionary["lastWorn"] as? NSDate
let timesNumber = bowtieDictionary["timesWorn"] as! NSNumber
bowtie.timesWorn = timesNumber.int32Value
bowtie.isFavorite = bowtieDictionary["isFavorite"] as! Bool
}
try! managedContext.save()
}
func populate(bowtie: Bowtie) {
guard let imageData = bowtie.photoData as Data?,
let lastWorn = bowtie.lastWorn as Date?,
let tintColor = bowtie.tintColor as? UIColor
else {
return
}
imageView.image = UIImage(data: imageData)
nameLabel.text = bowtie.name
ratingLabel.text = "Rating: \(bowtie.rating)/5"
timesWornLabel.text = "# times worn: \(bowtie.timesWorn)"
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
lastWornLabel.text = "Last worn: \(dateFormatter.string(from: lastWorn))"
favoriteLabel.isHidden = !bowtie.isFavorite
view.tintColor = tintColor
}
}
private extension UIColor {
static func color(colorDictionary: [String : AnyObject]) -> UIColor? {
guard let red = colorDictionary["red"] as? NSNumber,
let green = colorDictionary["green"] as? NSNumber,
let blue = colorDictionary["blue"] as? NSNumber
else {
return nil
}
return UIColor(red: CGFloat(red)/255.0,
green: CGFloat(green)/255.0,
blue: CGFloat(blue)/255.0,
alpha: 1)
}
}
|
unlicense
|
7672f2c9308f5c0b91d707a4b5ba8d79
| 31.818584 | 112 | 0.671835 | 4.528083 | false | false | false | false |
SmallPlanetSwift/PlanetSwift
|
Sources/PlanetSwift/Views/PlanetNetworkImageView.swift
|
1
|
1616
|
//
// PlanetNetworkImageView.swift
// PlanetSwift
//
// Created by Brad Bambara on 1/20/15.
// Copyright (c) 2015 Small Planet. All rights reserved.
//
import UIKit
public class PlanetNetworkImageView: UIImageView {
public var placeholderContentMode: UIView.ContentMode = .scaleToFill
public var downloadedContentMode: UIView.ContentMode = .scaleToFill
public func setImageWithPath(_ path: String?,
placeholder: UIImage? = nil,
completion: ((_ success: Bool) -> Void)? = nil) {
guard let urlPath = path, let url = NSURL(string: urlPath) else {
setImage(nil, placeholder: placeholder, completion: completion)
return
}
setImage(url as URL, placeholder: placeholder, completion: completion)
}
public func setImage(_ imageUrl: URL?,
placeholder: UIImage? = nil,
completion: ((_ success: Bool) -> Void)? = nil) {
contentMode = placeholderContentMode
image = placeholder
guard let imageUrl = imageUrl else {
completion?(false)
return
}
ImageCache.sharedInstance.get(imageUrl) { [weak self] (image: UIImage?) in
if let image = image {
if let downloadedContentMode = self?.downloadedContentMode {
self?.contentMode = downloadedContentMode
}
self?.image = image
completion?(true)
} else {
completion?(false)
}
}
}
}
|
mit
|
90861f9cfe483e919bb0159fd01f8cbc
| 30.686275 | 82 | 0.563119 | 5.263844 | false | false | false | false |
radex/DiffyTables
|
Source/WatchKitUpdatable.swift
|
1
|
795
|
import WatchKit
//
// Updatable WatchKit interface objects
//
extension WKInterfaceImage {
func updateImageName(from old: String?, to new: String) {
if old != new {
setImageNamed(new)
}
}
}
extension WKInterfaceLabel {
func updateText(from old: String?, to new: String) {
if old != new {
setText(new)
}
}
}
class WKUpdatableButton {
private(set) var button: WKInterfaceButton
private(set) var hidden: Bool
init(_ button: WKInterfaceButton, defaultHidden: Bool) {
self.button = button
self.hidden = defaultHidden
}
func updateHidden(_ hidden: Bool) {
if hidden != self.hidden {
button.setHidden(hidden)
self.hidden = hidden
}
}
}
|
mit
|
84539525f03ee51043d5fed282e6762e
| 19.921053 | 61 | 0.584906 | 4.416667 | false | false | false | false |
midoks/Swift-Learning
|
GitHubStar/GitHubStar/GitHubStar/Controllers/me/setting/GsSettingLanguageViewController.swift
|
1
|
4304
|
//
// GsSettingLanguageViewController.swift
// GitHubStar
//
// Created by midoks on 16/2/15.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
class GsSettingLanguageViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate {
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
return cell
}
var _tableView: UITableView?
//系统语言改变
var currentLang:String = MDLangLocalizable.singleton().currentLanguage()
var currentSelectedLang:String?
override func viewDidLoad() {
super.viewDidLoad()
//print(self.currentLang)
self.initView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//初始化视图
func initView(){
self.title = sysLang(key: "Language")
//左边
let leftButton = UIBarButtonItem(title: sysLang(key: "Cancel"), style: UIBarButtonItemStyle.plain, target: self, action: Selector(("close:")))
self.navigationItem.leftBarButtonItem = leftButton
//右边
let rightButton = UIBarButtonItem(title: sysLang(key: "Save"), style: UIBarButtonItemStyle.plain, target: self, action: Selector(("save:")))
self.navigationItem.rightBarButtonItem = rightButton
_tableView = UITableView(frame: self.view.frame, style: UITableViewStyle.plain)
_tableView?.dataSource = self
_tableView?.delegate = self
self.view.addSubview(_tableView!)
}
//MARK: - UITableViewDataSource && UITableViewDelegate -
private func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
private func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
let v = self.currentLang
if indexPath.row == 0 {
cell.textLabel?.text = "简体中文"
if v.hasPrefix("zh-Hans") {
cell.accessoryType = .checkmark
}
} else if indexPath.row == 1 {
cell.textLabel?.text = "English"
if v.hasPrefix("en") {
cell.accessoryType = .checkmark
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let cells = tableView.indexPathsForVisibleRows
var rowCell = UITableViewCell()
for i in cells! {
rowCell = tableView.cellForRow(at: i)!
rowCell.accessoryType = .none
}
let cell = tableView.cellForRow(at: indexPath as IndexPath)
cell?.accessoryType = .checkmark
let lang = cell?.textLabel?.text
if lang == "English" {
self.currentSelectedLang = "en"
} else if lang == "简体中文" {
self.currentSelectedLang = "zh-Hans"
}
}
//MARK: - Private Method -
//设置语言
func setLang(lang:String) {
MDLangLocalizable.singleton().setCurrentLanguage(lang: lang)
}
//关闭
func close(button: UIButton){
self.dismiss(animated: true) { () -> Void in
}
}
//保存当前值
func save(button: UIButton){
if self.currentSelectedLang != nil {
MDLangLocalizable.singleton().setCurrentLanguage(lang: self.currentSelectedLang!)
}
self.dismiss(animated: true) { () -> Void in
let delegate = UIApplication.shared.delegate
delegate?.window!!.rootViewController = RootViewController()
//delegate?.window!!.rootViewController?.tabBarController?.selectedIndex = 2
}
}
}
|
apache-2.0
|
e58896f395ed95976b846ae393dc5fc5
| 29.235714 | 150 | 0.600047 | 5.232386 | false | false | false | false |
sora0077/iTunesMusic
|
Sources/Model/Reviews.swift
|
1
|
3774
|
//
// Reviews.swift
// iTunesMusic
//
// Created by 林達也 on 2016/07/28.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import Foundation
import APIKit
import RealmSwift
import RxSwift
import Timepiece
import ErrorEventHandler
private func getOrCreateCache(collectionId: Int, realm: Realm) -> _ReviewCache {
if let cache = realm.object(ofType: _ReviewCache.self, forPrimaryKey: collectionId) {
return cache
}
let cache = _ReviewCache()
cache.collectionId = collectionId
// swiftlint:disable:next force_try
try! realm.write {
realm.add(cache)
}
return cache
}
extension Model {
public final class Reviews: Fetchable, ObservableList, _ObservableList {
fileprivate let collectionId: Int
fileprivate let caches: Results<_ReviewCache>
private var token: NotificationToken!
private var objectsToken: NotificationToken!
public init(collection: iTunesMusic.Collection) {
collectionId = collection.id
let realm = iTunesRealm()
_ = getOrCreateCache(collectionId: collectionId, realm: realm)
caches = realm.objects(_ReviewCache.self).filter("collectionId = \(collectionId)")
token = caches.observe { [weak self] changes in
guard let `self` = self else { return }
func updateObserver(with results: Results<_ReviewCache>) {
self.objectsToken = results[0].objects.observe { [weak self] changes in
self?._changes.onNext(CollectionChange(changes))
}
}
switch changes {
case .initial(let results):
updateObserver(with: results)
case .update(let results, deletions: _, insertions: let insertions, modifications: _):
if !insertions.isEmpty {
updateObserver(with: results)
}
case .error(let error):
fatalError("\(error)")
}
}
}
}
}
extension Model.Reviews: _Fetchable {
var _refreshAt: Date { return caches[0].refreshAt }
var _refreshDuration: Duration { return 6.hours }
}
extension Model.Reviews: _FetchableSimple {
typealias Request = ListReviews<_Review>
func makeRequest(refreshing: Bool) -> Request? {
let cache = caches[0]
if !refreshing && cache.fetched {
return nil
}
return ListReviews(id: collectionId, page: refreshing ? 1 : UInt(cache.page))
}
func doResponse(_ response: Request.Response, request: Request, refreshing: Bool) -> RequestState {
let realm = iTunesRealm()
// swiftlint:disable:next force_try
try! realm.write {
realm.add(response, update: true)
let cache = getOrCreateCache(collectionId: collectionId, realm: realm)
if refreshing {
cache.refreshAt = Date()
cache.page = 1
cache.fetched = false
cache.objects.removeAll()
}
cache.updateAt = Date()
cache.fetched = response.isEmpty
cache.page += 1
cache.objects.append(objectsIn: response)
}
return response.isEmpty ? .done : .none
}
}
extension Model.Reviews: Swift.Collection {
private var objects: List<_Review> { return caches[0].objects }
public var startIndex: Int { return objects.startIndex }
public var endIndex: Int { return objects.endIndex }
public subscript (index: Int) -> Review { return objects[index] }
public func index(after i: Int) -> Int {
return objects.index(after: i)
}
}
|
mit
|
52f9c224b302907dd6f755b3f2ceaa9b
| 29.12 | 103 | 0.597344 | 4.808429 | false | false | false | false |
abelsanchezali/ViewBuilder
|
ViewBuilderDemo/ViewBuilderDemo/ViewControllers/OnboardingPhoneScreenView.swift
|
1
|
3108
|
//
// OnboardingPhoneScreenView.swift
// ViewBuilderDemo
//
// Created by Abel Sanchez on 10/9/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import UIKit
import ViewBuilder
public class OnboardingPhoneScreenView: Panel {
weak var messageContainer: StackPanel!
weak var container: UIScrollView!
init() {
super.init(frame: CGRect.zero)
self.loadFromDocument(Constants.bundle.path(forResource: "OnboardingPhoneScreenView", ofType: "xml")!)
container = self.documentReferences!["container"] as! UIScrollView
messageContainer = self.documentReferences!["messageContainer"] as! StackPanel
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension OnboardingPhoneScreenView {
public func gotoIntialState() {
messageContainer.subviews.forEach() {
$0.isHidden = true
$0.alpha = 0
}
}
public func playAnimation() {
var index = 0
func showNextMessage() {
showMesageIndex(index) { (completed) in
if completed {
index += 1
AnimationHelper.delayedBlock(1.0, block: {
showNextMessage()
})
}
}
}
showNextMessage()
}
public func showMesageIndex(_ index: Int, comletion: ((Bool) -> Void)?) {
if index >= messageContainer.subviews.count {
comletion?(false)
return
}
let subview = messageContainer.subviews[index]
let delay = Double(subview.tag) / 1000.0
UIView.animate(withDuration: 0.75,
delay: 0.0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.1,
options: [.curveEaseOut, .beginFromCurrentState],
animations: {
subview.isHidden = false
self.layoutIfNeeded()
self.container.scrollToBottom(false)
}, completion: nil)
subview.layer.removeAllAnimations()
subview.transform = CGAffineTransform(translationX: 0, y: 50)
UIView.animate(withDuration: 0.75,
delay: 0.25,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.1,
options: [.curveEaseOut, .beginFromCurrentState],
animations: {
subview.alpha = 1
subview.transform = CGAffineTransform.identity
}, completion: {(completed) in
if !completed {
comletion?(false)
} else {
AnimationHelper.delayedBlock(delay, block: {
comletion?(true)
})
}
})
}
}
|
mit
|
871104746688618bbe6ddef9245c5c87
| 34.712644 | 110 | 0.509173 | 5.55814 | false | false | false | false |
VirgilSecurity/virgil-sdk-keys-ios
|
Source/JsonWebToken/JwtSignatureContent.swift
|
1
|
3199
|
//
// Copyright (C) 2015-2020 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder 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 AUTHOR ''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 AUTHOR 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.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
//
import Foundation
/// Declares error types and codes
///
/// - base64UrlStrIsInvalid: Given base64 string is invalid
@objc(VSSJwtSignatureContentError) public enum JwtSignatureContentError: Int, LocalizedError {
case base64UrlStrIsInvalid = 1
/// Human-readable localized description
public var errorDescription: String? {
switch self {
case .base64UrlStrIsInvalid:
return "Given base64 string is invalid"
}
}
}
/// Class representing JWT Signature content
@objc(VSSJwtSignatureContent) public final class JwtSignatureContent: NSObject {
/// Signature date
@objc public let signature: Data
/// String representation
@objc public let stringRepresentation: String
/// Imports JwtBodyContent from base64Url encoded string
///
/// - Parameter base64UrlEncoded: base64Url encoded string with JwtBodyContent
/// - Throws: JwtBodyContentError.base64UrlStrIsInvalid If given base64 string is invalid
@objc public init(base64UrlEncoded: String) throws {
guard let data = Data(base64UrlEncoded: base64UrlEncoded) else {
throw JwtSignatureContentError.base64UrlStrIsInvalid
}
self.signature = data
self.stringRepresentation = base64UrlEncoded
super.init()
}
/// Initializer
///
/// - Parameter signature: Signature data
@objc public init(signature: Data) {
self.signature = signature
self.stringRepresentation = signature.base64UrlEncodedString()
super.init()
}
}
|
bsd-3-clause
|
b2fcb223e8bdd752eb8a7a3fa8119fb2
| 36.635294 | 94 | 0.722413 | 4.649709 | false | false | false | false |
adapter00/ADTouchTracker
|
Example/ADTouchTracker/ViewController.swift
|
1
|
2841
|
//
// ViewController.swift
// ADTouchTracker
//
// Created by adapter00 on 11/06/2016.
// Copyright (c) 2016 adapter00. All rights reserved.
//
import UIKit
import ADTouchTracker
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var dataSource:[TestCell] = [.alert,.resetTracking,.modalViewController,.pushNaviagtion]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "Identifer") {
cell.textLabel?.text = dataSource[indexPath.row].rawValue
return cell
}else {
let cell = UITableViewCell(style: .default, reuseIdentifier: "Identifier")
cell.textLabel?.text = dataSource[indexPath.row].rawValue
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dataSource[indexPath.row].testAction(viewController: self)
}
}
enum TestCell:String {
case alert = "alert", resetTracking="resetTracking",modalViewController="modalViewController",pushNaviagtion = "pushNavigation"
func testAction(viewController:UIViewController) {
switch self {
case .alert:
let alert = UIAlertController(title: "Alert", message: "Test message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "close", style: UIAlertActionStyle.cancel, handler: {_ in}))
viewController.present(alert, animated: true, completion: nil)
case .pushNaviagtion:
if let next = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PushViewController") as? PushViewController {
viewController.navigationController?.pushViewController(next, animated: true)
}
case .modalViewController:
if let next = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NextViewController") as? NextViewController {
next.title = self.rawValue
viewController.present(next, animated: true, completion: nil)
}
case .resetTracking:
ADTouchTracker.tracking ? ADTouchTracker.stopTracking():ADTouchTracker.startTracking()
}
}
}
|
mit
|
5c5b943c9edb9931418c34ddba238076
| 41.402985 | 154 | 0.680394 | 5.15608 | false | true | false | false |
mislavjavor/Kandinsky
|
Sources/CanvasHelpers.swift
|
1
|
4218
|
//
// Constrainable.swift
// Kandinsky
//
// Created by Mislav Javor on 28/04/2017.
// Copyright © 2017 Mislav Javor. All rights reserved.
//
import Foundation
import SnapKit
extension Canvas {
public func alignParentTop(offset: Int = 0) {
deferToAfterRender.append { _ in
self.view.snp.makeConstraints { $0.top.equalToSuperview().offset(offset) }
}
}
public func alignParentTrailing() {
deferToAfterRender.append { _ in
self.view.snp.makeConstraints { $0.trailing.equalToSuperview() }
}
}
public func alignParentLeading() {
deferToAfterRender.append { _ in
self.view.snp.makeConstraints { $0.leading.equalToSuperview() }
}
}
public func alignParentBottom() {
deferToAfterRender.append { _ in
self.view.snp.makeConstraints { $0.bottom.equalToSuperview() }
}
}
public func offset(_ top: Int, _ leading: Int, _ bottom: Int, _ trailing: Int) {
deferToAfterRender.append { _ in
self.view.snp.makeConstraints { make in
make.topMargin.equalTo(top)
make.leadingMargin.equalTo(leading)
make.trailingMargin.equalTo(trailing)
make.bottomMargin.equalTo(bottom)
}
}
}
public var height: UInt {
get {
return self.height
}
set {
self.view.snp.makeConstraints { make in
make.height.equalTo(height)
}
}
}
public func toRightOf(_ view: String) {
deferToAfterRender.append { controller in
guard
let rightView = controller[view]
else {
fatalError("Failed to add view \(self.id ?? "unknown") 'toRightOf' view \(view)")
}
self.view.snp.makeConstraints { make in
make.leading.equalTo(rightView.snp.trailing)
}
}
}
public func toLeftOf(_ view: String) {
deferToAfterRender.append { controller in
guard
let leftView = controller[view]
else {
fatalError("Failed to add view \(self.id ?? "unknown") 'toLeftOf' view \(view)")
}
self.view.snp.makeConstraints { make in
make.trailing.equalTo(leftView.snp.leading)
}
}
}
public func under(_ view: String, offset: Int = 0) {
deferToAfterRender.append { controller in
guard
let underView = controller[view]
else {
fatalError("Failed to add view \(self.id ?? "unknown") 'under' view \(view)")
}
self.view.snp.makeConstraints { make in
make.top.equalTo(underView.snp.bottom).offset(offset)
}
}
}
public func above(_ view: String, offset: Int = 0) {
deferToAfterRender.append { controller in
guard
let overView = controller[view]
else {
fatalError("Failed to add view \(self.id ?? "unknown") 'above' view \(view)")
}
self.view.snp.makeConstraints { make in
make.bottom.equalTo(overView.snp.top).offset(offset)
}
}
}
public func centerInParent(xOffset: Int = 0, yOffset: Int = 0) {
deferToAfterRender.append { _ in
self.view.snp.makeConstraints {
$0.centerX.equalToSuperview().offset(xOffset)
$0.centerY.equalToSuperview().offset(yOffset)
}
}
}
public func centerHorizontallyInParent() {
deferToAfterRender.append { _ in
self.view.snp.makeConstraints { $0.centerX.equalToSuperview() }
}
}
public func matchHeightToParent(dividedBy factor: Int) {
deferToAfterRender.append { _ in
self.view.snp.makeConstraints { make in
make.height.equalToSuperview().dividedBy(factor)
}
}
}
}
|
mit
|
9d993a9818b0a32902334995aba66d7d
| 26.562092 | 100 | 0.52976 | 4.628979 | false | false | false | false |
kenada/advent-of-code
|
tests/2015/Day_15_Tests.swift
|
1
|
6114
|
//
// Day_15_Tests.swift
// Advent of Code 2015
//
// Copyright © 2017 Randy Eckenrode
//
// 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.
//
@testable import Advent_of_Code_2015
import XCTest
class Day_15_Tests: XCTestCase {
func testSolution() {
let ingredients = [
Ingredient(name: "Butterscotch", capacity: -1, durability: -2, flavor: 6, texture: 3, calories: 8),
Ingredient(name: "Cinnamon", capacity: 2, durability: 3, flavor: -2, texture: -1, calories: 3)
]
let expectedResults = [
ingredients[0]: 44,
ingredients[1]: 56
]
let solution = findingBestCookie(for: ingredients, teaspoons: 100)
for (ingredient, quantity) in expectedResults {
let solutionQuantity = solution[ingredient]
XCTAssertNotNil(solutionQuantity)
if let solutionQuantity = solutionQuantity {
XCTAssertEqual(solutionQuantity, quantity)
}
}
}
func testCappedSolution() {
let ingredients = [
Ingredient(name: "Butterscotch", capacity: -1, durability: -2, flavor: 6, texture: 3, calories: 8),
Ingredient(name: "Cinnamon", capacity: 2, durability: 3, flavor: -2, texture: -1, calories: 3)
]
let expectedResults = [
ingredients[0]: 40,
ingredients[1]: 60
]
let solution = findingBestCookie(for: ingredients, teaspoons: 100, calories: 500)
for (ingredient, quantity) in expectedResults {
let solutionQuantity = solution[ingredient]
XCTAssertNotNil(solutionQuantity)
if let solutionQuantity = solutionQuantity {
XCTAssertEqual(solutionQuantity, quantity)
}
}
}
func testParsing() {
let ingredients = [
"Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8",
"Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3",
"A man, a plan, a canal, Panama",
"Cinnamon: capacity 2, durability 🤔, flavor -2, texture -1, calories 3",
]
let expectedResults = [
Ingredient(name: "Butterscotch", capacity: -1, durability: -2, flavor: 6, texture: 3, calories: 8),
Ingredient(name: "Cinnamon", capacity: 2, durability: 3, flavor: -2, texture: -1, calories: 3),
nil,
nil
]
for (test, result) in zip(ingredients, expectedResults) {
let ingredient = Ingredient(from: test)
switch (ingredient, result) {
case let (.some(ingredient), .some(result)):
XCTAssertEqual(ingredient.name, result.name)
XCTAssertEqual(ingredient.capacity, result.capacity)
XCTAssertEqual(ingredient.durability, result.durability)
XCTAssertEqual(ingredient.flavor, result.flavor)
XCTAssertEqual(ingredient.texture, result.texture)
XCTAssertEqual(ingredient.calories, result.calories)
case (.none, .none):
XCTAssertTrue(true, "Both are nil")
default:
XCTAssertFalse(true, "\(String(describing: ingredient)) ≠ \(String(describing: result))")
}
}
}
func testNeighborsAtBounds() {
let input = (collection: [100, 0, 0, 0], bounds: 0..<100 as Range)
let expectedResult = [
[99, 0, 0, 1],
[99, 1, 0, 0],
[99, 0, 1, 0]
].sorted(by: Day_15_Tests.arrayLessThan)
let result = input.collection.neighbors(boundedBy: input.bounds).sorted(by: Day_15_Tests.arrayLessThan)
XCTAssertEqual(result.count, expectedResult.count)
for (collection, expectedCollection) in zip(result, expectedResult) {
XCTAssertEqual(collection, expectedCollection)
}
}
func testNeighborsUnbounded() {
let input = (collection: [25, 25, 25, 25], bounds: 0..<100 as Range)
let expectedResult = [
[24, 25, 25, 26],
[24, 25, 26, 25],
[24, 26, 25, 25],
[25, 24, 25, 26],
[25, 24, 26, 25],
[25, 25, 24, 26],
[25, 25, 26, 24],
[25, 26, 24, 25],
[25, 26, 25, 24],
[26, 24, 25, 25],
[26, 25, 24, 25],
[26, 25, 25, 24]
].sorted(by: Day_15_Tests.arrayLessThan)
let result = input.collection.neighbors(boundedBy: input.bounds).sorted(by: Day_15_Tests.arrayLessThan)
XCTAssertEqual(result.count, expectedResult.count)
for (collection, expectedCollection) in zip(result, expectedResult) {
XCTAssertEqual(collection, expectedCollection)
}
}
private static func arrayLessThan(lhs: [Int], rhs: [Int]) -> Bool {
guard let (lhsElement, rhsElement) = zip(lhs, rhs).first(where: { $0.0 != $0.1 }) else {
return lhs.count < rhs.count
}
return lhsElement < rhsElement
}
}
|
mit
|
bb8c2e8676a78d6f4d1996c60b28c9d7
| 41.416667 | 113 | 0.602489 | 4.177839 | false | true | false | false |
noppoMan/aws-sdk-swift
|
Sources/Soto/Services/IoTEventsData/IoTEventsData_Error.swift
|
1
|
2566
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for IoTEventsData
public struct IoTEventsDataErrorType: AWSErrorType {
enum Code: String {
case internalFailureException = "InternalFailureException"
case invalidRequestException = "InvalidRequestException"
case resourceNotFoundException = "ResourceNotFoundException"
case serviceUnavailableException = "ServiceUnavailableException"
case throttlingException = "ThrottlingException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize IoTEventsData
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// An internal failure occured.
public static var internalFailureException: Self { .init(.internalFailureException) }
/// The request was invalid.
public static var invalidRequestException: Self { .init(.invalidRequestException) }
/// The resource was not found.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// The service is currently unavailable.
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
/// The request could not be completed due to throttling.
public static var throttlingException: Self { .init(.throttlingException) }
}
extension IoTEventsDataErrorType: Equatable {
public static func == (lhs: IoTEventsDataErrorType, rhs: IoTEventsDataErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension IoTEventsDataErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
|
apache-2.0
|
8d138e6496fac1c077b9b1024d3fd109
| 36.188406 | 117 | 0.671083 | 5.041257 | false | false | false | false |
menlatin/jalapeno
|
digeocache/mobile/iOS/diGeo/diGeo/DrawerController/MapViewController.swift
|
1
|
4647
|
//
// MapViewController.swift
// diGeo
//
// Created by Elliott Richerson on 3/6/15.
// Copyright (c) 2015 Elliott Richerson. All rights reserved.
//
import MapKit
enum CenterViewControllerSection: Int {
case LeftViewState
case LeftDrawerAnimation
case RightViewState
case RightDrawerAnimation
}
class MapViewController: ExampleViewController, MKMapViewDelegate {//UITableViewDataSource, UITableViewDelegate {
var mapView: MKMapView!
var leftGestureMarginView: UIView!
var rightGestureMarginView: UIView!
// var tableView: UI TableView!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.restorationIdentifier = "MapViewControllerRestorationKey"
}
override init() {
super.init()
self.restorationIdentifier = "MapViewControllerRestorationKey"
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "DiGeoCache"
self.setupNavigationBar()
self.setupMapAndControls()
self.setupSideGestureMargins()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("Center will appear")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
println("Center did appear")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
println("Center will disappear")
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
println("Center did disappear")
}
func setupLeftMenuButton() {
let leftDrawerButton = DrawerBarButtonItem(target: self, action: "leftDrawerButtonPress:")
self.navigationItem.setLeftBarButtonItem(leftDrawerButton, animated: true)
}
func setupRightMenuButton() {
let rightDrawerButton = DrawerBarButtonItem(target: self, action: "rightDrawerButtonPress:")
self.navigationItem.setRightBarButtonItem(rightDrawerButton, animated: true)
}
func setupNavigationBar() {
self.setupLeftMenuButton()
self.setupRightMenuButton()
let barColor = DiGeoColors.MapBarColor()
self.navigationController?.navigationBar.barTintColor = barColor
self.navigationController?.view.layer.cornerRadius = 10.0
}
func setupMapAndControls() {
// Frame the MKMapView and Controls
let yOffset: CGFloat = 10 + self.navigationController!.navigationBar.frame.maxY
let mapViewInset: CGRect = CGRect(x: self.view.bounds.minX, y: yOffset, width: self.view.bounds.width, height: self.view.bounds.height-yOffset-20)
self.mapView = MKMapView(frame: mapViewInset)
self.mapView.delegate = self
self.view.addSubview(self.mapView)
self.mapView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
}
func setupSideGestureMargins() {
// Provide Left/Right UIView Edge Margins to Allow Gesture Interaction with Side Menus
let menuMarginWidth: CGFloat = 45.0
let leftGestureMarginRect: CGRect = CGRect(x: self.mapView.bounds.minX, y: self.mapView.bounds.minY, width: menuMarginWidth, height: self.mapView.bounds.height)
let rightGestureMarginRect: CGRect = CGRect(x: self.mapView.bounds.maxX - menuMarginWidth, y: self.mapView.bounds.minY, width: menuMarginWidth, height: self.mapView.bounds.height)
self.leftGestureMarginView = UIView(frame: leftGestureMarginRect)
self.rightGestureMarginView = UIView(frame: rightGestureMarginRect)
self.leftGestureMarginView.backgroundColor = UIColor.clearColor()
self.rightGestureMarginView.backgroundColor = UIColor.clearColor()
self.mapView.addSubview(self.leftGestureMarginView)
self.leftGestureMarginView.autoresizingMask = .FlexibleHeight
self.mapView.addSubview(self.rightGestureMarginView)
self.rightGestureMarginView.autoresizingMask = .FlexibleHeight
}
override func contentSizeDidChange(size: String) {
// self.tableView.reloadData()
}
// MARK: - Button Handlers
func leftDrawerButtonPress(sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.Left, animated: true, completion: nil)
}
func rightDrawerButtonPress(sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.Right, animated: true, completion: nil)
}
}
|
mit
|
bd63679f15ee870ac0aba63627ccda84
| 35.590551 | 187 | 0.693781 | 4.948882 | false | false | false | false |
ztolley/VideoStationViewer
|
VideoStationViewer/TabBarViewController.swift
|
1
|
1680
|
import UIKit
class TabBarViewController: UITabBarController {
var moviePosterCollectionViewController:MovieGenresViewController!
var tvPosterCollectionViewController:TVShowsViewController!
var searchViewController:UIViewController!
var settingsViewController:SettingsViewController!
let sessionAPI = SessionAPI.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
resetView()
}
// Call this on initial startup and when settings are changed
// If the user has a valid session, show the movies, otherwise just show settings
func resetView() {
let listDetailStoryboard = UIStoryboard(name: "Movies", bundle: NSBundle.mainBundle())
let settingsStoryboard = UIStoryboard(name: "Settings", bundle: NSBundle.mainBundle())
if let _ = self.sessionAPI.getSid() {
moviePosterCollectionViewController = listDetailStoryboard.instantiateViewControllerWithIdentifier("MoviePosterCollection") as! MovieGenresViewController
moviePosterCollectionViewController.title = "Movies"
tvPosterCollectionViewController = listDetailStoryboard.instantiateViewControllerWithIdentifier("TVShowPosterCollection") as! TVShowsViewController
settingsViewController = settingsStoryboard.instantiateViewControllerWithIdentifier("Settings") as! SettingsViewController
self.setViewControllers([moviePosterCollectionViewController, tvPosterCollectionViewController, settingsViewController], animated: true)
} else {
settingsViewController = settingsStoryboard.instantiateViewControllerWithIdentifier("Settings") as! SettingsViewController
self.setViewControllers([settingsViewController], animated: true)
}
}
}
|
gpl-3.0
|
158f3c3912f4febd66a609350f2d4523
| 36.333333 | 156 | 0.810119 | 5.675676 | false | false | false | false |
xxxAIRINxxx/Cmg
|
Sources/VectorInput.swift
|
1
|
4458
|
//
// VectorInput.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/20.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
public enum VectorType {
case position(maximumSize: Vector2)
case extent(extent: Vector4)
case color
case colorOffset
case other(count: Int)
}
public final class VectorInput: FilterInputable {
public let type: VectorType
public let key: String
public fileprivate(set) var values: [CGFloat] = []
public fileprivate(set) var ranges: [Range] = []
fileprivate var initialValue: CIVector?
init(_ type: VectorType, _ filter: CIFilter, _ key: String) {
self.type = type
self.key = key
let attributes = filter.attributes[key] as? [String : AnyObject]
let vector = attributes?[kCIAttributeDefault] as? CIVector
if let _vector = vector {
self.setVector(_vector)
self.initialValue = _vector
}
}
public func setVector(_ vector: CIVector) {
self.values.removeAll()
self.ranges.removeAll()
for i in 0..<vector.count {
let v: CGFloat = vector.value(at: i)
self.values.append(v)
switch type {
case .position(let maximumSize):
switch i {
case 0: self.ranges.append(Range(0.0, Float(maximumSize.x), Float(v)))
case 1: self.ranges.append(Range(0.0, Float(maximumSize.y), Float(v)))
default: break
}
case .extent(let extent):
switch i {
case 0: self.ranges.append(Range(0.0, Float(extent.z), Float(v)))
case 1: self.ranges.append(Range(0.0, Float(extent.w), Float(v)))
case 2: self.ranges.append(Range(0.0, Float(extent.z), Float(v)))
case 3: self.ranges.append(Range(0.0, Float(extent.w), Float(v)))
default: break
}
case .color:
self.ranges.append(Range(0.0, 1.0, Float(v)))
case .colorOffset:
self.ranges.append(Range(0.0, 1.0, Float(v)))
case .other:
self.ranges.append(Range(0.0, 1.0, Float(v)))
}
}
}
internal func setValue(_ index: Int, value: CGFloat) {
self.values[index] = value
}
public func sliders() -> [Slider] {
var names: [String]
switch type {
case .position(_):
names = ["\(self.key) x", "\(self.key) y"]
case .extent(_):
names = ["\(self.key) x", "\(self.key) y", "\(self.key) z" , "\(self.key) w"]
case .color:
names = ["\(self.key) red", "\(self.key) green", "\(self.key) blue", "\(self.key) alpha"]
case .colorOffset:
names = ["\(self.key) x", "\(self.key) y"]
case .other:
names = []
self.values.enumerated().forEach() {
names.append("\(self.key) \($0.0)")
}
}
return []
// return self.values.enumerated().map { i in
// return Slider(names[i.1], self.ranges[i.0]) { [weak self] value in
// self?.setValue(i.index, value: CGFloat(value))
// }
// }
}
public func setInput(_ filter: CIFilter) {
filter.setValue(CIVector(values: self.values, count: self.values.count), forKey: self.key)
}
public func resetValue() {
guard let _initialValue = self.initialValue else { return }
self.setVector(_initialValue)
}
}
extension VectorInput {
public var vector2: Vector2 {
get { return Vector2(values: self.values) }
}
public var vector4: Vector4 {
get { return Vector4(values: self.values) }
}
public var vectorAny: VectorAny {
get { return VectorAny(count: self.values.count, values: self.values) }
}
}
extension CGSize {
public var vector2 : Vector2 {
get { return Vector2(size: self) }
}
public var vector4 : Vector4 {
get { return Vector4(x: 0, y: 0, z: self.width, w: self.height) }
}
}
extension CGRect {
public var vector2 : Vector2 {
get { return Vector2(size: self.size) }
}
public var vector4 : Vector4 {
get { return Vector4(rect: self) }
}
}
|
mit
|
bd2eb588fe150547c3566a68c1ef685e
| 28.713333 | 101 | 0.536908 | 3.930335 | false | false | false | false |
pawrsccouk/Stereogram
|
Stereogram-iPad/NSError+Alert.swift
|
1
|
3841
|
//
// NSError+Alert.swift
// Stereogram-iPad
//
// Created by Patrick Wallace on 16/01/2015.
// Copyright (c) 2015 Patrick Wallace. All rights reserved.
//
import UIKit
private let kLocation = "Location", kCaller = "Caller", kTarget = "Target", kSelector = "Selector"
extension NSError {
/// Display the error in an alert view.
///
/// Gets the error text from some known places in the NSError description.
/// The alert will just have a close button and no extra specifications.
///
/// :param: title The title to display above the alert.
/// :param: parent The view controller to present the alert on top of.
func showAlertWithTitle(title: String, parentViewController parent: UIViewController) {
var errorText = self.localizedDescription
if let t = self.helpAnchor { errorText = t }
else if let t = self.localizedFailureReason { errorText = t }
NSLog("Showing error \(self) final text \(errorText)")
let alertController = UIAlertController(title: title
, message: errorText
, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Close", style: .Default, handler: nil))
parent.presentViewController(alertController, animated: true, completion: nil)
}
/// Convenience initializer.
/// Create a new error object using the photo store error domain and code.
///
/// :param: errorCode The PhotoStore error code to return.
/// :param: userInfo NSDicationary with info to associate with this error.
convenience init(errorCode code: ErrorCode
, userInfo: [String: AnyObject]?) {
self.init(domain: ErrorDomain.PhotoStore.rawValue
, code: code.rawValue
, userInfo: userInfo)
}
/// Class function to create an error to return when something failed but didn't say why.
///
/// :param: location A string included in the error text and returned in the userInfo dict.
/// This should give a clue as to what operation was being performed.
/// :param: target A string included in the error text and returned in the userInfo dict.
/// This should give a clue as to which function returned this error
/// (i.e. the function in 3rd party code that returned the unexpected error.)
class func unknownErrorWithLocation(location: String, target: String = "") -> NSError {
var errorMessage = "Unknown error at location \(location)"
if target != "" {
errorMessage = "\(errorMessage) calling \(target)"
}
let userInfo = [
NSLocalizedDescriptionKey : errorMessage,
kLocation : location,
kTarget : target]
return NSError(errorCode:.UnknownError, userInfo:userInfo)
}
/// Class function to create an error to return when a method call failed but didn't say why.
///
/// :param: target The object we called a method on.
/// :param: selector Selector for the method we called on TARGET.
/// :param: caller The method or function which called the method that went wrong.
/// I.e. where in my code it is.
class func unknownErrorWithTarget(target: AnyObject
, method: String
, caller: String) -> NSError {
let callee = "\(target).(\(method))"
let errorText = "Unknown error calling \(callee) from caller \(caller)"
let userInfo = [
NSLocalizedDescriptionKey : errorText,
kCaller : caller,
kTarget : target,
kSelector : method]
return NSError(errorCode: .UnknownError, userInfo: userInfo)
}
}
|
mit
|
90f652554df76672ed874846675d9c7e
| 40.75 | 98 | 0.61911 | 4.905492 | false | false | false | false |
itssofluffy/NanoMessage
|
Tests/NanoMessageTests/PublishSubscribeProtocolFamilyTests.swift
|
1
|
11336
|
/*
PublishSubscibeProtocolFamilyTests.swift
Copyright (c) 2016, 2017 Stephen Whittle All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
import XCTest
import Foundation
import NanoMessage
class PublishSubscribeProtocolFamilyTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testPublishSubscribeTests(connectAddress: String, bindAddress: String = "") {
guard let connectURL = URL(string: connectAddress) else {
XCTAssert(false, "connectURL is invalid")
return
}
guard let bindURL = URL(string: (bindAddress.isEmpty) ? connectAddress : bindAddress) else {
XCTAssert(false, "bindURL is invalid")
return
}
var completed = false
do {
let node0 = try PublisherSocket()
let node1 = try SubscriberSocket()
try node0.setSendTimeout(seconds: 0.5)
try node1.setReceiveTimeout(seconds: 0.5)
let node0EndPointId: Int = try node0.createEndPoint(url: connectURL, type: .Connect)
XCTAssertGreaterThanOrEqual(node0EndPointId, 0, "node0.createEndPoint('\(connectURL)', .Connect) < 0")
let node1EndPointId: Int = try node1.createEndPoint(url: bindURL, type: .Bind)
XCTAssertGreaterThanOrEqual(node1EndPointId, 0, "node1.createEndPoint('\(bindURL)', .Bind) < 0")
pauseForBind()
// standard publisher -> subscriber where the topic known.
print("subscribe to an expected topic...")
var topic = try Topic(value: "shakespeare")
var done = try node1.subscribeTo(topic: topic)
XCTAssertEqual(done, true, "node1.subscribeTo(topic: \(topic))")
XCTAssertEqual(node1.isTopicSubscribed(topic), true, "node1.isTopicSubscribed()")
XCTAssertEqual(node1.removeTopicFromMessage, true, "node1.removeTopicFromMessage")
var message = Message(topic: topic, message: payload.data)
var node0Sent = try node0.sendMessage(message)
XCTAssertEqual(node0Sent.bytes, topic.count + 1 + payload.count, "node0.bytesSent != topic.count + 1 + payload.count")
var node1Received = try node1.receiveMessage()
XCTAssertEqual(node1Received.bytes, node1Received.topic!.count + 1 + node1Received.message.count, "node1.bytes != node1received.topic.count + 1 + node1Received.message.count")
XCTAssertEqual(node1Received.message.count, payload.count, "node1Received.message.count != payload.count")
XCTAssertEqual(node1Received.message, payload, "node1.message != payload")
XCTAssertEqual(node1Received.topic, topic, "node1Received.topic != topic")
// standard publisher -> subscriber where the topic is unknown.
print("subscribe to an unknown topic...")
try node1.unsubscribeFrom(topic: topic)
try node1.subscribeTo(topic: Topic(value: "xxxx"))
XCTAssertEqual(node1.subscribedTopics.count, 1, "node1.subscribedTopics.count != 0")
message = try Message(topic: Topic(value: "yyyy"), message: payload.data)
node0Sent = try node0.sendMessage(message)
XCTAssertEqual(node0Sent.bytes, node0Sent.topic!.count + 1 + payload.count, "node0.bytesSent != node0Sent.topic.count + 1 + payload.count")
try node1.setReceiveTimeout(seconds: -1)
do {
node1Received = try node1.receiveMessage(timeout: TimeInterval(seconds: 0.5))
XCTAssert(false, "received a message on node1")
} catch NanoMessageError.ReceiveTimedOut {
XCTAssert(true, "\(NanoMessageError.ReceiveTimedOut))") // we have timedout
}
try node1.setReceiveTimeout(seconds: 0.5)
try node1.unsubscribeFromAllTopics()
print("subscribe to all topics...")
done = try node1.subscribeToAllTopics()
XCTAssertEqual(done, true, "node1.subscribeToAllTopics()")
let planets = [ "mercury", "venus", "mars", "earth", "mars", "jupiter", "saturn", "uranus", "neptune" ]
topic = try Topic(value: "planet")
for planet in planets {
message = Message(topic: topic, message: planet)
let sent = try node0.sendMessage(message)
XCTAssertEqual(sent.bytes, sent.topic!.count + 1 + planet.utf8.count, "sent.bytes != sent.topic.count + 1 + planet.utf8.count")
let _ = try node1.receiveMessage()
}
let dwarfPlanets = [ "Eris", "Pluto", "Makemake", "Or", "Haumea", "Quaoar", "Senda", "Orcus", "2002 MS", "Ceres", "Salacia" ]
topic = try Topic(value: "dwarfPlanet")
for dwarfPlanet in dwarfPlanets {
message = Message(topic: topic, message: dwarfPlanet)
let sent = try node0.sendMessage(message)
XCTAssertEqual(sent.bytes, sent.topic!.count + 1 + dwarfPlanet.utf8.count, "sent.bytes != sent.topic.count + 1 + dwarfPlanet.utf8.count")
let _ = try node1.receiveMessage()
}
XCTAssertEqual(node0.sentTopics.count, 4, "node0.sentTopics.count != 3")
XCTAssertEqual(node0.sentTopics[topic]!, UInt64(dwarfPlanets.count), "node0.sentTopics[\"\(topic)\"] != \(dwarfPlanets.count)")
XCTAssertEqual(node1.subscribedTopics.count, 0, "node1.subscribedTopics.count != 0")
XCTAssertEqual(node1.receivedTopics.count, 1 + 2, "node1.receivedTopics.count != 3")
try XCTAssertEqual(UInt64(planets.count), node1.receivedTopics[Topic(value: "planet")]!, "planets.count != node1.receivedTopics[\"planet\"]")
try XCTAssertEqual(UInt64(dwarfPlanets.count), node1.receivedTopics[Topic(value: "dwarfPlanet")]!, "planets.count != node1.receivedTopics[\"dwarfPlanet\"]")
print("unsubscribe from all topics and subscribe to only one topic...")
try node1.unsubscribeFromAllTopics()
try node1.subscribeTo(topic: Topic(value: "dwarfPlanet"))
for planet in planets {
message = try Message(topic: Topic(value: "planet"), message: planet)
let sent = try node0.sendMessage(message)
XCTAssertEqual(sent.bytes, sent.topic!.count + 1 + planet.utf8.count, "sent.bytes != sent.topic.count + 1 + planet.utf8.count")
}
do {
let _ = try node1.receiveMessage()
XCTAssert(false, "received a message on node1")
} catch NanoMessageError.ReceiveTimedOut {
XCTAssert(true, "\(NanoMessageError.ReceiveTimedOut)")
}
topic = try Topic(value: "dwarfPlanet")
for dwarfPlanet in dwarfPlanets {
message = Message(topic: topic, message: dwarfPlanet)
let sent = try node0.sendMessage(message)
XCTAssertEqual(sent.bytes, sent.topic!.count + 1 + dwarfPlanet.utf8.count, "sent.bytes != node0.sendTopic.count + 1 + dwarfPlanet.utf8.count")
}
var received = try node1.receiveMessage()
XCTAssertEqual(received.topic, topic, "received.topic != topic")
XCTAssertEqual(received.message.string, dwarfPlanets[0], "received.message.string != \"\(dwarfPlanets[0])\"")
try node1.unsubscribeFromAllTopics()
print("ignore topic seperator...")
node0.ignoreTopicSeperator = true
try node1.subscribeTo(topic: Topic(value: "AAA"))
try node1.subscribeTo(topic: Topic(value: "BBB"))
try node1.subscribeTo(topic: Topic(value: "CCCC"))
try node1.subscribeTo(topic: Topic(value: "DDD"))
do {
let _ = try node1.flipIgnoreTopicSeperator()
} catch NanoMessageError.InvalidTopic {
XCTAssert(true, "\(NanoMessageError.InvalidTopic))") // have we unequal length topics
}
try node1.unsubscribeFrom(topic: Topic(value: "CCCC"))
try node1.subscribeTo(topic: Topic(value: "CCC"))
let _ = try node1.flipIgnoreTopicSeperator()
XCTAssertEqual(node1.ignoreTopicSeperator, true, "node1.ignoreTopicSeperator")
message = try Message(topic: Topic(value: "AAA"), message: payload.data)
let sent = try node0.sendMessage(message)
received = try node1.receiveMessage()
XCTAssertEqual(received.topic!.count, sent.topic!.count, "received.topic.count != sent.topic.count")
XCTAssertEqual(received.topic, sent.topic, "received.topic != sent.topic")
XCTAssertEqual(received.message, payload, "received.topic != payload")
completed = true
} catch let error as NanoMessageError {
XCTAssert(false, "\(error)")
} catch {
XCTAssert(false, "an unexpected error '\(error)' has occured in the library libNanoMessage.")
}
XCTAssert(completed, "test not completed")
}
func testTCPPublishSubscribe() {
testPublishSubscribeTests(connectAddress: "tcp://localhost:5400", bindAddress: "tcp://*:5400")
}
func testInProcessPublishSubscribe() {
testPublishSubscribeTests(connectAddress: "inproc:///tmp/pubsub.inproc")
}
func testInterProcessPublishSubscribe() {
testPublishSubscribeTests(connectAddress: "ipc:///tmp/pubsub.ipc")
}
func testWebSocketPublishSubscribe() {
testPublishSubscribeTests(connectAddress: "ws://localhost:5405", bindAddress: "ws://*:5405")
}
#if os(Linux)
static let allTests = [
("testTCPPublishSubscribe", testTCPPublishSubscribe),
("testInProcessPublishSubscribe", testInProcessPublishSubscribe),
("testInterProcessPublishSubscribe", testInterProcessPublishSubscribe),
("testWebSocketPublishSubscribe", testWebSocketPublishSubscribe)
]
#endif
}
|
mit
|
ac6ca0c9db11559fb536a00a40d1efa8
| 44.344 | 187 | 0.644407 | 4.400621 | false | true | false | false |
njdehoog/Spelt
|
Sources/Spelt/SiteConfiguration.swift
|
1
|
659
|
public struct SiteConfiguration {
public enum Path: String {
case config = "_config.yml"
case destinationConfig = "_destinations.yml"
case source = ""
case posts = "_posts"
case sass = "_sass"
case layouts = "_layouts"
case includes = "_includes"
case assets = "assets"
case build = "_build"
// returns absolute path
func relativeToPath(_ path: String) -> String {
return path.stringByAppendingPathComponent(rawValue)
}
}
static var defaultPaths: [Path] {
return [.posts, .sass, .layouts, .includes, .assets]
}
}
|
mit
|
b03fdb724ad37b5689b1060293311f65
| 28.954545 | 64 | 0.561457 | 4.673759 | false | true | false | false |
xiaomudegithub/iosstar
|
iOSStar/Library/EmojiKeyboard/HHEmojiManage.swift
|
4
|
1117
|
//
// HHEmojiManage.swift
// HHEmojiKeyboard
//
// Created by xoxo on 16/6/6.
// Copyright © 2016年 caohuihui. All rights reserved.
//
import Foundation
class HHEmojiManage:NSObject {
class func getEmojiAll() -> NSDictionary{
if let path = Bundle.main.path(forResource: "EmojisList", ofType: "plist"){
if let dic = NSDictionary(contentsOfFile: path as String){
return dic
}
}
return NSDictionary()
}
class func getYEmoji() -> NSArray{
if let bundlePath = Bundle.main.path(forResource: "NIMKitEmoticon", ofType: "bundle"){
if let path = Bundle.init(path: bundlePath)?.path(forResource: "emoji", ofType: "plist", inDirectory: "Emoji"){
if let arr = NSArray.init(contentsOfFile: path){
if let dic = arr[0] as? NSDictionary{
if let emojiArray = dic["data"] as? NSArray{
return emojiArray
}
}
}
}
}
return NSArray()
}
}
|
gpl-3.0
|
5cee206b716a6896a9876f24ff58f078
| 26.85 | 123 | 0.527828 | 4.403162 | false | false | false | false |
lukejmann/FBLA2017
|
FBLA2017/ChatsTableViewController.swift
|
1
|
10365
|
//
// ChatsTableViewController.swift
// FBLA2017
//
// Created by Luke Mann on 4/20/17.
// Copyright © 2017 Luke Mann. All rights reserved.
//
protocol TableHasLoadedDelegate {
func hasLoaded()
}
protocol ClearCellDelegate {
func clear()
func unClear()
}
import UIKit
import NVActivityIndicatorView
import ChameleonFramework
import DZNEmptyDataSet
//Outlets cause an error, need to define delegate/datasource
class ChatsTableViewController: UITableViewController, TableHasLoadedDelegate {
var itemKeys=[String]()
var directChatKeys=[String]()
var itemCells = currentUser.itemChats
var directCells = currentUser.directChats
var loadedItemCells=[ChatsTableViewCell?](repeating: nil, count:currentUser.itemChats.count)
var loadedDirectCells=[ChatsTableViewCell?](repeating: nil, count:currentUser.directChats.count)
var cellsToLoad = currentUser.itemChats.count + currentUser.directChats.count
var cellsLoaded = 0
var cellsToClear=[ClearCellDelegate]()
var activityIndicator: NVActivityIndicatorView?
var readyToLoad = true
var loading = true
var refresher = UIRefreshControl()
override func viewDidAppear(_ animated: Bool) {
activityIndicator = ActivityIndicatorLoader.startActivityIndicator(view: self.view)
refreshData()
}
var loadCells = false
func hasLoaded() {
// self.tableView.reloadData()
// self.viewWillAppear(true)
// viewDidLoad()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView?.emptyDataSetSource = self
tableView?.emptyDataSetDelegate = self
tableView?.tableFooterView = UIView()
currentUser.hasLoadedDelegate = self
refresher.addTarget(self, action:#selector(refreshData), for: .valueChanged)
self.tableView.addSubview(refresher)
self.tableView.separatorStyle = .none
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
if (itemCells.count < 1 && directCells.count < 1) {
return 0
}
if !(itemCells.count < 1 || directCells.count < 1) {
return 2
}
return 1
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.backgroundView?.backgroundColor = UIColor.flatNavyBlue
header.backgroundColor = UIColor.flatNavyBlue
header.textLabel?.textColor = UIColor.white
header.textLabel?.font = Fonts.bold.get(size: 17)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if getSectionType(section: section) == .item {
return itemCells.count
}
return directCells.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let type = getSectionType(section: indexPath.section)
if type == .item {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell", for: indexPath) as! ChatsTableViewCell
print(indexPath.row)
let cell2 = itemCells[indexPath.row]
cell.hasLoaded = cell2.hasLoaded
cell.mainImageView?.image = cell2.img
cell.dateLabel.text = cell2.date
cell.nameLabel.text = cell2.name
cell.delegate = cell2
cell2.item = cell.item
loadedItemCells[indexPath.row]=cell2
if !loadCells {
if cell.img == nil && cell.mainImageView.image == nil && cell.hasLoaded == false {
cell.tableViewDelegate = self
cell2.tableViewDelegate = self
} else {
// cellLoaded()
}
}
cellsToClear.append(cell)
return cell2
}
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell", for: indexPath) as! ChatsTableViewCell
let cell2 = directCells[indexPath.row]
cell.hasLoaded = cell2.hasLoaded
cell.mainImageView?.image = cell2.img
cell.dateLabel.text = cell2.date
cell.nameLabel.text = cell2.name
cell.delegate = cell2
cell2.item = cell.item
loadedDirectCells[indexPath.row]=cell2
if !loadCells {
if cell.img == nil && cell.hasLoaded == false {
cell.tableViewDelegate = self
cell2.tableViewDelegate = self
} else {
// cellLoaded()
}
}
cellsToClear.append(cell)
return cell2
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if getSectionType(section: section) == .user {
return "Users"
}
return "Items"
}
func getSectionType(section: Int) -> SectionType {
if section == 0 {
if itemCells.count < 1 {
return .user
}
if directCells.count < 1 {
return .item
}
return .item
}
return .user
}
}
enum SectionType {
case user
case item
}
//MARK - TableView to Item View
extension ChatsTableViewController:ItemDelegate {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if readyToLoad {
if getSectionType(section: indexPath.section) == .user {
let cell = loadedDirectCells[indexPath.row]
let user = cell?.user
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "OtherUserProfile") as! OtherUserProfileViewController
viewController.loadOtherChat = true
viewController.loginInUser = currentUser
viewController.otherUser = user
present(viewController, animated: true, completion: nil)
} else {
let cell = loadedItemCells[indexPath.row]
let item = Item()
item.delegate = self
item.load(keyString: (cell?.itemPath)!)
readyToLoad = false
activityIndicator = ActivityIndicatorLoader.startActivityIndicator(view: self.view)
cell?.item = item
}
}
}
func doneLoading(item: Item) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let middle = storyboard.instantiateViewController(withIdentifier: "pulley") as! FirstContainerViewController
middle.nextItemDelegate = nil
middle.dismissDelegate = nil
middle.item = item
middle.openWithChat = true
activityIndicator?.stopAnimating()
self.present(middle, animated: true, completion: nil)
readyToLoad = true
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
}
//MARK: - Refresh control
extension ChatsTableViewController:ChatsTableViewLoadedDelgate, ChatsTableCanReloadDelegate {
func cellLoaded() {
cellsLoaded += 1
if cellsLoaded >= cellsToLoad {
doneLoading()
}
}
func doneLoading() {
activityIndicator?.stopAnimating()
loadCells = true
}
func refreshData() {
activityIndicator?.startAnimating()
loading = true
if readyToLoad {
readyToLoad = false
currentUser.chatTableCanReloadDelegate = self
currentUser.resetLoadedCell()
}
}
func refreshChats() {
loading = false
loadCells = true
self.itemCells.removeAll()
self.directCells.removeAll()
loadedItemCells.removeAll()
loadedDirectCells.removeAll()
for cell in cellsToClear {
cell.clear()
}
cellsToLoad = 0
cellsLoaded = 0
tableView.reloadData()
itemCells = currentUser.itemChats
directCells = currentUser.directChats
loadedItemCells=[ChatsTableViewCell?](repeating: nil, count:currentUser.itemChats.count)
loadedDirectCells=[ChatsTableViewCell?](repeating: nil, count:currentUser.directChats.count)
cellsToLoad = currentUser.itemChats.count + currentUser.directChats.count
cellsLoaded = cellsToLoad
cellsToClear.removeAll()
self.tableView.reloadData()
readyToLoad = true
self.activityIndicator?.stopAnimating()
refresher.endRefreshing()
self.viewWillAppear(true)
}
}
//MARK - Empty table view
extension ChatsTableViewController:DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
if !loading {
return NSAttributedString(string: "Huh", attributes: [NSFontAttributeName: Fonts.bold.get(size: 17) as Any])
} else {
return NSAttributedString(string: "", attributes: [NSFontAttributeName: Fonts.bold.get(size: 17) as Any])
}
}
func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
if !loading {
return NSAttributedString(string: "It doesn't look like there are any chats here, either contribute to chats on items or start a chat with another user.", attributes: [NSFontAttributeName: Fonts.regular.get(size: 17) as Any])
} else {
return NSAttributedString(string: "", attributes: [NSFontAttributeName: Fonts.bold.get(size: 17) as Any])
}
}
func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControlState) -> NSAttributedString! {
if !loading {
return NSAttributedString(string: "Press Here To Refresh", attributes: [NSFontAttributeName: Fonts.bold.get(size: 25) as Any])
} else {
return NSAttributedString(string: "", attributes: [NSFontAttributeName: Fonts.bold.get(size: 17) as Any])
}
}
func emptyDataSet(_ scrollView: UIScrollView!, didTap button: UIButton!) {
refreshData()
}
}
|
mit
|
0b9ed57c02b177fdc80ecb47508914ee
| 32.006369 | 237 | 0.637881 | 5.009183 | false | false | false | false |
xeecos/motionmaker
|
GIFMaker/VideoManager.swift
|
1
|
19650
|
//
// VideoManager.swift
// GIFMaker
//
// Created by indream on 15/9/23.
// Copyright © 2015年 indream. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
class VideoManager: NSObject,AVCaptureFileOutputRecordingDelegate,AVCaptureVideoDataOutputSampleBufferDelegate {
static var _instance:VideoManager!
static func sharedManager()->VideoManager{
if(_instance==nil){
_instance = VideoManager()
}
return _instance
}
var videoWidth:Int32 = 1280
var videoHeight:Int32 = 720
var videoView:UIView?
var captureSession:AVCaptureSession?// = AVCaptureSession()
var previewLayer : AVCaptureVideoPreviewLayer?
var videoOutput:AVCaptureMovieFileOutput?
var imageOutput:AVCaptureStillImageOutput?
var videoSampleOutput:AVCaptureVideoDataOutput?
var timer:Timer?
var outputSampleFileURL:URL?
var isRecording:Bool = false
// If we find a device we'll store it here for later use
var captureDevice : AVCaptureDevice?
var currentISO:Float = 0
var currentSpeed:Float = 0
var currentFocus:Float = 0
var startISO:Float = 0
var endISO:Float = 0
var startFocus:Float = 0
var endFocus:Float = 0
var startSpeed:Float = 0
var endSpeed:Float = 0
var startTime:Double = 0.0
var totalTime:Int32 = 0
var currentTime:Float = 0
var interval:Float = 0.0
var prevTime:Float = 0.0
var isVideo:Bool = true
var videoWriter:AVAssetWriter?
var writerInput:AVAssetWriterInput?
var writeAdapter:AVAssetWriterInputPixelBufferAdaptor?
func initSession(){
let devices = AVCaptureDevice.devices()
// Loop through all the capture devices on this phone
for device in devices! {
// Make sure this particular device supports video
if ((device as AnyObject).hasMediaType(AVMediaTypeVideo)) {
// Finally check the position and confirm we've got the back camera
if((device as AnyObject).position == AVCaptureDevicePosition.back) {
captureDevice = device as? AVCaptureDevice
if captureDevice != nil {
beginSession()
}
}
}
}
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { (granted:Bool) -> Void in
}
createAlbum()
self.timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(VideoManager.timerHandle), userInfo: nil, repeats: true)
}
var recordBarButton:UIBarButtonItem?
func timerHandle(){
if(isRecording){
currentTime = Float(Date().timeIntervalSince1970 - startTime)
recordBarButton?.title = "\(Int32(Float(totalTime)-currentTime))"
let per:Float = currentTime/Float(totalTime)
currentFocus = startFocus + (endFocus-startFocus)*per
currentISO = startISO + (endISO - startISO)*per
currentSpeed = startSpeed + (endSpeed - startSpeed)*per
configureDevice(sid,cid:cid)
if(currentTime>=Float(totalTime)){
nextCamera()
}
}else{
}
}
var cameraID:Int16 = 0
var sid:Int16 = 0
var cid:Int16 = 0
func nextCamera(){
let camera:CameraModel? = DataManager.sharedManager().camera(0, cid: cameraID)!
startTime = Date().timeIntervalSince1970
totalTime = (camera?.time)!
startFocus = (camera?.focus)!
startISO = Float((camera?.iso)!)
startSpeed = Float((camera?.speed)!)
interval = (camera?.interval)!
sid = 0
cid = cameraID
if(cameraID+1<DataManager.sharedManager().countOfCamera(0)){
let nextCamera:CameraModel? = DataManager.sharedManager().camera(0, cid: cameraID+1)!
if((nextCamera)==nil){
stopRecord()
}else{
endFocus = (nextCamera?.focus)!
endISO = Float((nextCamera?.iso)!)
endSpeed = Float((nextCamera?.speed)!)
}
}else{
isRecording = false
let time: TimeInterval = 2.0
let delay = DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delay) {
self.stopRecord()
}
}
cameraID += 1
}
func configureDevice(_ sid:Int16,cid:Int16) {
if let device = captureDevice {
do {
try device.lockForConfiguration()
}catch let error as NSError {
print(error)
}
let cam:CameraModel = DataManager.sharedManager().camera(sid,cid:cid)!
let setting:SettingModel = DataManager.sharedManager().setting(sid)!
if(setting.resolution==0){
captureSession!.sessionPreset = AVCaptureSessionPreset1280x720
videoWidth = 1280
videoHeight = 720
}else if(setting.resolution==1){
captureSession!.sessionPreset = AVCaptureSessionPreset1920x1080
videoWidth = 1920
videoHeight = 1080
}else{
if #available(iOS 9.0, *) {
captureSession!.sessionPreset = AVCaptureSessionPreset3840x2160
videoWidth = 3840
videoHeight = 2160
} else {
// Fallback on earlier versions
}
}
isVideo = setting.mode==0
device.focusMode = AVCaptureFocusMode.autoFocus
if(currentFocus<0){
currentFocus = 0
}else if(currentFocus>8000){
currentFocus = 8000
}
if(currentISO<100){
currentISO = 100
}else if(currentISO>1600){
currentISO = 1600
}
if(currentSpeed<2){
currentSpeed = 2
}else if(currentSpeed>8000){
currentSpeed = 8000
}
if(!isRecording){
if(cam.iso<100){
cam.iso = 100
}
currentSpeed = Float(cam.speed)
currentFocus = cam.focus
currentISO = Float(cam.iso)
}
// print(currentISO,currentSpeed,currentFocus)
device.setFocusModeLockedWithLensPosition(currentFocus/8000.0, completionHandler: { (timestamp:CMTime) -> Void in
})
// let conf = device.activeFormat
// print(conf.minExposureDuration,conf.maxExposureDuration)
let duration:CMTime = CMTimeMake(1, Int32(max(2,currentSpeed)))
let minISO = device.activeFormat.minISO
let maxISO = device.activeFormat.maxISO
device.setExposureModeCustomWithDuration(duration, iso: (Float(currentISO-100)/1600)*(maxISO-minISO)+minISO, completionHandler: { (timestamp:CMTime) -> Void in
})
device.unlockForConfiguration()
}
}
func beginSession() {
captureSession = AVCaptureSession()
configureDevice(0,cid:0)
do {
let device = try AVCaptureDeviceInput(device: self.captureDevice) as AVCaptureDeviceInput
captureSession!.addInput(device)
}catch let error as NSError {
print(error)
}
let audioDevice:AVCaptureDevice? = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
do{
let audioInput:AVCaptureDeviceInput? = try AVCaptureDeviceInput(device: audioDevice!);
captureSession!.addInput(audioInput)
}catch let err as NSError{
print(err)
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
//CGRect(x: 0, y: 0, width: 640, height: 1136)
//self.view.layer.frame
captureSession!.startRunning()
}
func configVideoView(_ videoView:UIView){
if((previewLayer)==nil){
}else{
videoView.layer.addSublayer(previewLayer!)
previewLayer?.frame = videoView.frame
previewLayer!.connection.videoOrientation = AVCaptureVideoOrientation.landscapeRight
}
}
func startRecord(){
if((videoOutput)==nil){
}else{
captureSession!.removeOutput(videoOutput)
}
if((videoSampleOutput)==nil){
}else{
captureSession!.removeOutput(videoSampleOutput)
}
if(isVideo){
if((videoOutput) == nil){
self.videoOutput = AVCaptureMovieFileOutput()
}
if (captureSession!.canAddOutput(videoOutput)) {
print("can add output")
captureSession!.addOutput(videoOutput)
}
let paths:NSArray = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true) as NSArray
let documentsDirectoryPath:NSString! = paths.object(at: 0) as! NSString
let outputpathofmovie:String! = documentsDirectoryPath.appending("/\(Date().timeIntervalSince1970)") + ".MOV";
let outputURL:URL! = URL(fileURLWithPath: outputpathofmovie);
print(outputURL.path)
var videoConnection:AVCaptureConnection?;
for connection in videoOutput!.connections
{
for port in ((connection as AnyObject).inputPorts as NSArray)
{
if ( (port as AnyObject).mediaType==AVMediaTypeVideo)
{
videoConnection = connection as? AVCaptureConnection;
}
}
}
videoConnection?.videoOrientation = AVCaptureVideoOrientation.landscapeRight
videoOutput?.startRecording(toOutputFileURL: outputURL, recordingDelegate: self)
}else{
captureSession!.stopRunning()
let paths:NSArray = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true) as NSArray
let documentsDirectoryPath:NSString! = paths.object(at: 0) as! NSString
let outputpathofmovie:String! = documentsDirectoryPath.appending("/\(Date().timeIntervalSince1970)") + ".MOV";
self.outputSampleFileURL = URL(fileURLWithPath: outputpathofmovie);
do{
try videoWriter = AVAssetWriter(outputURL: outputSampleFileURL!, fileType: AVFileTypeMPEG4)
writerInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings:[ AVVideoCodecKey : AVVideoCodecH264,AVVideoWidthKey : String(videoWidth), AVVideoHeightKey: String(videoHeight)])
videoWriter!.add(writerInput!)
self.writeAdapter = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: writerInput!, sourcePixelBufferAttributes:[String(kCVPixelBufferPixelFormatTypeKey): String(kCVPixelFormatType_32ARGB), String(kCVPixelBufferWidthKey): String(videoWidth),String(kCVPixelBufferHeightKey): String(videoHeight)])
writerInput!.expectsMediaDataInRealTime = true;
videoWriter!.startWriting()
videoWriter!.startSession(atSourceTime: CMTimeMake(0, 24))
print("add writer")
}catch let err as NSError{
print(err)
}
self.videoSampleOutput = AVCaptureVideoDataOutput()
let recordingQueue = DispatchQueue(label: "q\(Date().timeIntervalSince1970)", attributes: [])
videoSampleOutput?.setSampleBufferDelegate(self, queue: recordingQueue)
videoSampleOutput?.alwaysDiscardsLateVideoFrames = true
videoSampleOutput?.videoSettings = videoSampleOutput?.recommendedVideoSettingsForAssetWriter(withOutputFileType: "public.mpeg-4")
// print(captureSession!.outputs,videoSampleOutput)
captureSession!.addOutput(videoSampleOutput)
captureSession!.commitConfiguration()
captureSession!.startRunning()
}
let time: TimeInterval = 1.0
let delay = DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
prevTime = 0
currentTime = 0
frameCount = 0
DispatchQueue.main.asyncAfter(deadline: delay) {
self.cameraID = 0
self.isRecording = true
self.nextCamera()
}
}
func stopRecord(){
isRecording = false
if(isVideo){
videoOutput?.stopRecording()
}else{
self.videoSampleOutput?.setSampleBufferDelegate(nil, queue: nil)
self.captureSession!.removeOutput(self.videoSampleOutput)
self.videoSampleOutput = nil
writerInput!.markAsFinished();
videoWriter!.endSession(atSourceTime: CMTimeMake(Int64(Float(frameCount - 1) * Float(fps) * Float(durationForEachImage)), Int32(fps)));
videoWriter!.finishWriting(completionHandler: { () -> Void in
print("finish recording")
self.videoWriter!.cancelWriting()
self.videoSampleOutput?.setSampleBufferDelegate(nil, queue: nil)
self.writeAdapter = nil
self.writerInput = nil
self.videoSampleOutput = nil
self.videoWriter = nil
self.isRecording = false
PHPhotoLibrary.shared().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: self.outputSampleFileURL!)
let assetPlaceholder = assetRequest!.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
let enumeration: NSArray = [assetPlaceholder!]
albumChangeRequest!.addAssets(enumeration)
}, completionHandler: { success, error in
self.recordBarButton?.title = "Record"
print("added frames to album")
let fileManager:FileManager? = FileManager.default
do{
try fileManager?.removeItem(at: self.outputSampleFileURL!)
}catch let err as NSError {
print(err)
}
})
});
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "STOP_RECORDING"), object: nil, userInfo: nil)
}
var assetCollection: PHAssetCollection!
var albumFound : Bool = false
var photosAsset: PHFetchResult<AnyObject>!
var assetThumbnailSize:CGSize!
var collection: PHAssetCollection!
var assetCollectionPlaceholder: PHObjectPlaceholder!
func createAlbum() {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", "Motion Maker")
let collection : PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let first_obj: AnyObject = collection.firstObject {
self.albumFound = true
assetCollection = collection.firstObject!
} else {
PHPhotoLibrary.shared().performChanges({
let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: "Motion Maker")
self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { success, error in
self.albumFound = (success ? true: false)
if (success) {
let collectionFetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [self.assetCollectionPlaceholder.localIdentifier], options: nil)
print(collectionFetchResult)
self.assetCollection = collectionFetchResult.firstObject!
}
})
}
}
var frameCount:Int16 = 0
let fps:Int16 = 24
let durationForEachImage:Float = 0.05
//0416
func captureImage(){
// let videoConnection = imageOutput?.connectionWithMediaType(AVMediaTypeVideo)
// imageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { (buff, error) -> Void in
// let imageData:NSData? = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buff)
// let frameTime:CMTime = CMTimeMake(Int64(self.frameCount * self.fps * self.durationForEachImage), Int32(self.fps));
//
// //self.appendPixelBufferForImageData(imageData!, pixelBufferAdaptor: self.writeAdapter!, presentationTime: frameTime)
//
// self.frameCount++;
//
// })
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
if(currentTime-prevTime>interval){
prevTime = currentTime
print("append frame")
let frameTime:CMTime = CMTimeMake(Int64(Float(self.frameCount) * Float(self.fps) * self.durationForEachImage), Int32(self.fps))
if(self.writerInput!.isReadyForMoreMediaData){
self.writeAdapter?.append(CMSampleBufferGetImageBuffer(sampleBuffer)!, withPresentationTime: frameTime)
self.frameCount += 1
}
}
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didDrop sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
print("drop")
}
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
print("capture output : finish recording to \(outputFileURL) \(error)")
PHPhotoLibrary.shared().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputFileURL)
let assetPlaceholder = assetRequest!.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
let enumeration: NSArray = [assetPlaceholder!]
albumChangeRequest!.addAssets(enumeration)
}, completionHandler: { success, error in
print("added video to album")
let fileManager:FileManager? = FileManager.default
do{
try fileManager?.removeItem(at: outputFileURL)
}catch let err as NSError {
print(err)
}
})
}
func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) {
print("capture output: started recording to \(fileURL)")
}
}
|
mit
|
90d335e0e0d2ca396e68c4075ae45577
| 42.27533 | 316 | 0.604672 | 5.55785 | false | false | false | false |
zjjzmw1/robot
|
robot/Pods/ObjectMapper/Sources/URLTransform.swift
|
70
|
2294
|
//
// URLTransform.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-27.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// 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
open class URLTransform: TransformType {
public typealias Object = URL
public typealias JSON = String
private let shouldEncodeURLString: Bool
/**
Initializes the URLTransform with an option to encode URL strings before converting them to an NSURL
- parameter shouldEncodeUrlString: when true (the default) the string is encoded before passing
to `NSURL(string:)`
- returns: an initialized transformer
*/
public init(shouldEncodeURLString: Bool = true) {
self.shouldEncodeURLString = shouldEncodeURLString
}
open func transformFromJSON(_ value: Any?) -> URL? {
guard let URLString = value as? String else { return nil }
if !shouldEncodeURLString {
return URL(string: URLString)
}
guard let escapedURLString = URLString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else {
return nil
}
return URL(string: escapedURLString)
}
open func transformToJSON(_ value: URL?) -> String? {
if let URL = value {
return URL.absoluteString
}
return nil
}
}
|
mit
|
7cc7ef3bfe05d119833210620e4a338c
| 34.292308 | 122 | 0.745859 | 4.216912 | false | false | false | false |
sanjaymhj/ChatOverLapView
|
HChatHeads/AppDelegate.swift
|
1
|
6104
|
//
// AppDelegate.swift
// HChatHeads
//
// Created by Sanjay Maharjan on 5/30/16.
// Copyright © 2016 Sanjay Maharjan. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.snjmhj.HChatHeads" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("HChatHeads", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
mit
|
12ace6aaebae1c30d22d7fbd12f1133b
| 53.981982 | 291 | 0.719974 | 5.840191 | false | false | false | false |
AllisonWangJiaoJiao/KnowledgeAccumulation
|
03-YFPageViewExtensionDemo(布局)/YFPageViewExtensionDemo/YFPageView/YFPageStyle.swift
|
2
|
811
|
//
// YFPageStyle.swift
// YFPageViewDemo
//
// Created by Allison on 2017/4/27.
// Copyright © 2017年 Allison. All rights reserved.
//
import UIKit
class YFPageStyle {
var titleViewHeight : CGFloat = 44
var normalColor : UIColor = UIColor(r: 0, g: 0, b: 0)
var selectColor : UIColor = UIColor(r: 255, g: 127, b: 0)
var fontSize : CGFloat = 15
var titleFont : UIFont = UIFont.systemFont(ofSize: 15.0)
//是否是滚动的title
var isScrollEnable : Bool = false
//间距
var itemMargin : CGFloat = 20
var isShowBottomLine : Bool = true
var bottomLineColor : UIColor = UIColor.orange
var bottomLineHeight : CGFloat = 2
//YFPageCollectionView
///title的高度
var titleHeight : CGFloat = 44
}
|
mit
|
2a5ab76696cadaa1964a5a8f7d998893
| 19.153846 | 61 | 0.618321 | 4.115183 | false | false | false | false |
rolson/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Features/Feature layer definition expression/DefinitionExpressionViewController.swift
|
1
|
2508
|
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class DefinitionExpressionViewController: UIViewController {
@IBOutlet private weak var mapView:AGSMapView!
private var map:AGSMap!
private var featureLayer:AGSFeatureLayer!
override func viewDidLoad() {
super.viewDidLoad()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["DefinitionExpressionViewController"]
//initialize map using topographic basemap
self.map = AGSMap(basemap: AGSBasemap.topographicBasemap())
//initial viewpoint
self.map.initialViewpoint = AGSViewpoint(center: AGSPoint(x: -13630484, y: 4545415, spatialReference: AGSSpatialReference.webMercator()), scale: 90000)
//assign map to the map view's map
self.mapView.map = self.map
//create feature table using a url to feature server's layer
let featureTable = AGSServiceFeatureTable(URL: NSURL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0")!)
//create feature layer using this feature table
self.featureLayer = AGSFeatureLayer(featureTable: featureTable)
//add the feature layer to the map
self.map.operationalLayers.addObject(self.featureLayer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func applyDefinitionExpression() {
//adding definition expression to show specific features only
self.featureLayer.definitionExpression = "req_Type = 'Tree Maintenance or Damage'"
}
@IBAction func resetDefinitionExpression() {
//reset definition expression
self.featureLayer.definitionExpression = ""
}
}
|
apache-2.0
|
aad921807584f6c17b8f292db379a1ca
| 38.809524 | 159 | 0.702153 | 4.823077 | false | false | false | false |
swghosh/infinnovation-stock-exchange-simulator-ios-app
|
Infinnovation Stock Exchange Simulator/UpdatesListAPICall.swift
|
1
|
1924
|
//
// UpdatesListAPICall.swift
// Infinnovation Stock Exchange Simulator
//
// Created by SwG Ghosh on 24/04/17.
// Copyright © 2017 infinnovation. All rights reserved.
//
import Foundation
class UpdatesListAPICall: APICall {
// the StockItem whose corresponding UpdateItem(s) list is to be fetched
var stock: StockItem
// initializer
init(urlString: String, apiKey: String, stock: StockItem) {
self.stock = stock
super.init(urlString: urlString, apiKey: apiKey)
// url escaping for white spaces
let name = stock.name.replacingOccurrences(of: " ", with: "%20")
self.url = URL(string: "\(urlString)?key=\(apiKey)&name=\(name)")
}
// an array of UpdateItem(s) that will be JSON serialised/casted from the JSON
var updates: [UpdateItem]?
func getUpdatesList() -> [UpdateItem] {
updates = [UpdateItem]()
do {
// JSON Serialization is attempted on the received data
let json = try JSONSerialization.jsonObject(with: jsonData!, options: JSONSerialization.ReadingOptions()) as? [String: Any]
// type casting
let list = json!["result"] as! [[String: Any]]
// the date, time when the data was fetched from the API is also stored as a String
time = json!["time"] as? String
// casting all data to be finally produce a complete UpdateItem array
for item in list {
let updateTime = item["time"] as! String
let updateCurrent = item["current"] as! Int
let update: UpdateItem = UpdateItem(time: updateTime, current: updateCurrent)
updates!.append(update)
}
}
catch {
print(error)
}
// the UpdateItem array is returned
return updates!
}
}
|
mit
|
7f62d55ac210edd8fc54e9e25e3df2c5
| 33.339286 | 135 | 0.586583 | 4.667476 | false | false | false | false |
fgengine/quickly
|
Quickly/StringFormatter/QCardNumberStringFormatter.swift
|
1
|
1470
|
//
// Quickly
//
open class QCardNumberStringFormatter : IQStringFormatter {
public init() {
}
public func format(_ unformat: String) -> String {
var format = String()
var unformatOffset = 0
while unformatOffset < unformat.count {
let unformatIndex = unformat.index(unformat.startIndex, offsetBy: unformatOffset)
let unformatCharacter = unformat[unformatIndex]
if unformatOffset != 0 && unformatOffset % 4 == 0 {
format.append(" ")
}
format.append(unformatCharacter)
unformatOffset += 1
}
return format
}
public func format(_ unformat: String, caret: inout Int) -> String {
let format = self.format(unformat)
caret = self.formatDifferenceCaret(
unformat: unformat,
format: format,
formatPrefix: 0,
formatSuffix: 0,
caret: caret
)
return format
}
public func unformat(_ format: String) -> String {
return format.replacingOccurrences(of: " ", with: "")
}
public func unformat(_ format: String, caret: inout Int) -> String {
let unformat = self.unformat(format)
caret = self.unformatDifferenceCaret(
unformat: unformat,
format: format,
formatPrefix: 0,
formatSuffix: 0,
caret: caret
)
return unformat
}
}
|
mit
|
1d85a23ba4155bf7ad816e5b16d01a63
| 26.735849 | 93 | 0.561224 | 4.537037 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
Steps4Impact/App/Assets.swift
|
1
|
4126
|
/**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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
enum Assets: String {
// UI
case gear = "GearIcon"
case disclosure = "BlueBackButton"
case close = "close"
case checkmark = "checkmark"
case chevronRight = "chevron_right"
case chevronLeft = "chevron_left"
// Login
case squareApple = "login-square-apple"
case squareFacebook = "login-square-facebook"
case squareGoogle = "login-square-google"
// Challenge
// case challengeJourney = "challenge-journey"
case inviteFriends = "invite-friends"
case inviteSupporters = "invite-supporters"
// Logos
case AKFLogo = "AKFLogo"
case logo = "logo"
// Navigation Bar
case backIcon = "back-icon"
// Badges
case badgeIcon = "badge_icon"
// Onboarding
case onboardingLoginPeople = "login-couple"
case onboardingCreateTeam = "create-team"
case onboardingJourney = "challenge-journey"
case onboardingDashboard = "dashboard"
// Leaderboard
case leaderboardEmpty = "leaderboard-empty"
// Journey
case journeyEmpty = "journey_map_test"
// case journeyDetailMock = "journeyDetailMock"
// Tab Bar
case tabbarDashboardSelected = "tabbar-dashboard-selected"
case tabbarDashboardUnselected = "tabbar-dashboard-unselected"
case tabbarChallengeSelected = "tabbar-challenge-selected"
case tabbarChallengeUnselected = "tabbar-challenge-unselected"
case tabbarLeaderboardSelected = "tabbar-leaderboard-selected"
case tabbarLeaderboardUnselected = "tabbar-leaderboard-unselected"
case tabbarNotificationsSelected = "tabbar-notifications-selected"
case tabbarNotificationsUnselected = "tabbar-notifications-unselected"
case circumflex = "circumflex"
case invertedCircumflex = "inverted-circumflex"
case uploadImageIcon = "uploadImageIcon"
case placeholder
var image: UIImage? {
switch self {
case .disclosure:
return UIImage(named: self.rawValue)?.withHorizontallyFlippedOrientation()
case .placeholder:
return UIImage(color: Style.Colors.FoundationGreen)
default:
return UIImage(named: self.rawValue)
}
}
}
enum BadgesAssets {
case dailyStreak(count: Int)
case personalProgress(miles: Int)
case steps(count: Int)
case teamProgress(progress: Int)
case finalMedal(level: String)
public var rawValue: String {
switch self {
case .dailyStreak(let count):
return "dailyStreak\(count)"
case .personalProgress(let miles):
return "\(miles)mi"
case .steps(let steps):
return "\(steps)steps"
case .teamProgress(let progress):
return "\(progress)progress"
case .finalMedal(let level):
return "\(level)"
}
}
var image: UIImage? {
return UIImage(named: self.rawValue)
}
}
|
bsd-3-clause
|
ec3378df41fd4bc77295fa2ea773f25d
| 30.976744 | 80 | 0.738909 | 4.261364 | false | false | false | false |
jtbandes/swift
|
test/expr/unary/keypath/keypath-objc.swift
|
7
|
4943
|
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library %s -verify
import ObjectiveC
import Foundation
// REQUIRES: objc_interop
@objc class A : NSObject {
@objc var propB: B = B()
@objc var propString: String = "" // expected-note {{did you mean 'propString'}}
@objc var propArray: [String] = []
@objc var propDict: [String: B] = [:]
@objc var propSet: Set<String> = []
@objc var propNSString: NSString?
@objc var propNSArray: NSArray?
@objc var propNSDict: NSDictionary?
@objc var propNSSet: NSSet?
@objc var propAnyObject: AnyObject?
@objc var ambiguous: String? // expected-note{{'ambiguous' declared here}}
@objc func someMethod() { }
@objc var `repeat`: String?
}
@objc class B : NSObject {
@objc var propA: A?
@objc var ambiguous: String? // expected-note{{'ambiguous' declared here}}
}
class C {
var nonObjC: String? // expected-note{{add '@objc' to expose this var to Objective-C}}{{3-3=@objc }}
}
extension NSArray {
@objc class Foo : NSObject {
@objc var propString: String = ""
}
}
extension Array {
typealias Foo = NSArray.Foo
}
func testKeyPath(a: A, b: B) {
// Property
let _: String = #keyPath(A.propB)
// Chained property
let _: String = #keyPath(A.propB.propA)
// Optional property
let _: String = #keyPath(A.propB.propA.propB)
// String property
let _: String = #keyPath(A.propString)
// Property of String property (which looks on NSString)
let _: String = #keyPath(A.propString.URLsInText)
// Array property (make sure we look at the array element).
let _: String = #keyPath(A.propArray)
let _: String = #keyPath(A.propArray.URLsInText)
// Dictionary property (make sure we look at the value type).
let _: String = #keyPath(A.propDict.anyKeyName)
let _: String = #keyPath(A.propDict.anyKeyName.propA)
// Set property (make sure we look at the set element).
let _: String = #keyPath(A.propSet)
let _: String = #keyPath(A.propSet.URLsInText)
// AnyObject property
let _: String = #keyPath(A.propAnyObject.URLsInText)
let _: String = #keyPath(A.propAnyObject.propA)
let _: String = #keyPath(A.propAnyObject.propB)
let _: String = #keyPath(A.propAnyObject.description)
// NSString property
let _: String = #keyPath(A.propNSString.URLsInText)
// NSArray property (AnyObject array element).
let _: String = #keyPath(A.propNSArray)
let _: String = #keyPath(A.propNSArray.URLsInText)
// NSDictionary property (AnyObject value type).
let _: String = #keyPath(A.propNSDict.anyKeyName)
let _: String = #keyPath(A.propNSDict.anyKeyName.propA)
// NSSet property (AnyObject set element).
let _: String = #keyPath(A.propNSSet)
let _: String = #keyPath(A.propNSSet.URLsInText)
// Property with keyword name.
let _: String = #keyPath(A.repeat)
// Nested type of a bridged type (rdar://problem/28061409).
typealias IntArray = [Int]
let _: String = #keyPath(IntArray.Foo.propString)
let dict: [String: Int] = [:]
let _: Int? = dict[#keyPath(A.propB)]
}
func testAsStaticString() {
let _: StaticString = #keyPath(A.propB)
}
func testSemanticErrors() {
let _: String = #keyPath(A.blarg) // expected-error{{type 'A' has no member 'blarg'}}
let _: String = #keyPath(blarg) // expected-error{{use of unresolved identifier 'blarg'}}
let _: String = #keyPath(AnyObject.ambiguous) // expected-error{{ambiguous reference to member 'ambiguous'}}
let _: String = #keyPath(C.nonObjC) // expected-error{{argument of '#keyPath' refers to non-'@objc' property 'nonObjC'}}
let _: String = #keyPath(A.propArray.UTF8View) // expected-error{{type 'String' has no member 'UTF8View'}}
let _: String = #keyPath(A.someMethod) // expected-error{{'#keyPath' cannot refer to instance method 'someMethod()'}}
let _: String = #keyPath(A) // expected-error{{empty '#keyPath' does not refer to a property}}
let _: String = #keyPath(A.propDict.anyKeyName.unknown) // expected-error{{type 'B' has no member 'unknown'}}
let _: String = #keyPath(A.propNSDict.anyKeyName.unknown) // expected-error{{type 'AnyObject' has no member 'unknown'}}
}
func testParseErrors() {
let _: String = #keyPath; // expected-error{{expected '(' following '#keyPath'}}
let _: String = #keyPath(123; // expected-error{{expected property or type name within '#keyPath(...)'}}
let _: String = #keyPath(a.123; // expected-error{{expected property or type name within '#keyPath(...)'}}
let _: String = #keyPath(A(b:c:d:).propSet); // expected-error{{an Objective-C key path cannot reference a declaration with a compound name}} expected-error{{unresolved identifier 'propSet'}}
let _: String = #keyPath(A.propString; // expected-error{{expected ')' to complete '#keyPath' expression}}
// expected-note@-1{{to match this opening '('}}
}
func testTypoCorrection() {
let _: String = #keyPath(A.proString) // expected-error {{type 'A' has no member 'proString'}}
}
|
apache-2.0
|
6dc88f4424d2c8b95e0d19ad218694ab
| 36.165414 | 193 | 0.680558 | 3.656065 | false | false | false | false |
slepcat/mint-lisp
|
mint-lisp/mint_CSG.swift
|
1
|
15246
|
//
// mint_CSG.swift
// MINT
//
// Created by NemuNeko on 2015/05/04.
// Copyright (c) 2015年 Taizo A. All rights reserved.
//
import Foundation
// # class PolygonTreeNode
// This class manages hierarchical splits of polygons
// At the top is a root node which doesn hold a polygon, only child PolygonTreeNodes
// Below that are zero or more 'top' nodes; each holds a polygon. The polygons can be in different planes
// splitByPlane() splits a node by a plane. If the plane intersects the polygon, two new child nodes
// are created holding the splitted polygon.
// getPolygons() retrieves the polygon from the tree. If for PolygonTreeNode the polygon is split but
// the two split parts (child nodes) are still intact, then the unsplit polygon is returned.
// This ensures that we can safely split a polygon into many fragments. If the fragments are untouched,
// getPolygons() will return the original unsplit polygon instead of the fragments.
// remove() removes a polygon from the tree. Once a polygon is removed, the parent polygons are invalidated
// since they are no longer intact.
// constructor creates the root node:
class PolygonTreeNode {
var parent : PolygonTreeNode? = nil
var children : [PolygonTreeNode] = []
var polygon : Polygon? = nil
var removed : Bool = false
// fill the tree with polygons. Should be called on the root node only; child nodes must
// always be a derivate (split) of the parent node.
func addPolygons(_ poly: [Polygon]) {
if !isRootNode() {
for p in poly {
addChild(p)
}
}
// new polygons can only be added to root node; children can only be splitted polygons
//MintErr.exc.raise()
}
// remove a node
// - the siblings become toplevel nodes
// - the parent is removed recursively
func remove() {
if removed == false {
removed = true
// remove ourselves from the parent's children list:
if let parentcsg = parent {
var i = 0
while i < parentcsg.children.count {
if parentcsg.children[i] === self {
parentcsg.children.remove(at: i)
i -= 1
}
i += 1
}
// invalidate the parent's polygon, and of all parents above it:
parentcsg.recursivelyInvalidatePolygon()
}
}
}
func isRootNode() -> Bool {
if parent == nil {
return true
} else {
return false
}
}
// invert all polygons in the tree. Call on the root node
func invert() {
if isRootNode() {// can only call this on the root node
invertSub()
} else {
print("Assertion failed", terminator: "\n")
}
}
func getPolygon() -> Polygon? {
if let poly = polygon {
return poly
} else { // doesn't have a polygon, which means that it has been broken down
print("Assertion failed", terminator: "\n")
return nil
}
}
func getPolygons() -> [Polygon] {
if let poly = polygon {
// the polygon hasn't been broken yet. We can ignore the children and return our polygon:
return [poly]
} else {
// our polygon has been split up and broken, so gather all subpolygons from the children:
var childpolygons = [Polygon]()
for child in children {
childpolygons += child.getPolygons()
}
return childpolygons
}
}
// split the node by a plane; add the resulting nodes to the frontnodes and backnodes array
// If the plane doesn't intersect the polygon, the 'this' object is added to one of the arrays
// If the plane does intersect the polygon, two new child nodes are created for the front and back fragments,
// and added to both arrays.
/* original
func splitByPlane(plane: Plane, inout cpfrontnodes: [PolygonTreeNode], inout cpbacknodes: [PolygonTreeNode], inout frontnodes: [PolygonTreeNode], inout backnodes: [PolygonTreeNode]) {
if children.count > 0 {
// if we have children, split the children
for child in children {
child.splitByPlane(plane, cpfrontnodes: &cpfrontnodes, cpbacknodes: &cpbacknodes, frontnodes: &frontnodes, backnodes: &backnodes)
}
} else {
// no children. Split the polygon:
if polygon != nil {
let bound = polygon!.boundingSphere()
var sphereradius = bound.radius + 1e-4
var planenormal = plane.normal
var spherecenter = bound.middle
var d = planenormal.dot(spherecenter) - plane.w
if d > sphereradius {
frontnodes.append(self)
} else if d < -sphereradius {
backnodes.append(self)
} else {
let splitresult = plane.splitPolygon(polygon!)
switch splitresult.type {
case .Coplanar_front:
// coplanar front:
cpfrontnodes.append(self)
case .Coplanar_back:
// coplanar back:
cpbacknodes.append(self)
case .Front:
// front:
frontnodes.append(self)
case .Back:
// back:
backnodes.append(self)
case .Spanning:
// spanning:
if let front = splitresult.front {
var frontnode = addChild(front)
frontnodes.append(frontnode)
}
if let back = splitresult.back {
var backnode = addChild(back)
backnodes.append(backnode)
}
default:
print("unexpected err")
break
}
}
}
}
}
*/
// Slightly modified. This ver of splitByPlane() does not have 'cpbacknodes' argument,
// because Swift cannot have 2 arguments of same reference.
func splitByPlane(_ plane: Plane, cpfrontnodes: inout [PolygonTreeNode], frontnodes: inout [PolygonTreeNode], backnodes: inout [PolygonTreeNode]) {
if children.count > 0 {
// if we have children, split the children
for child in children {
child.splitByPlane(plane, cpfrontnodes: &cpfrontnodes, frontnodes: &frontnodes, backnodes: &backnodes)
}
} else {
// no children. Split the polygon:
if polygon != nil {
let bound = polygon!.boundingSphere()
let sphereradius = bound.radius + 1e-4
let planenormal = plane.normal
let spherecenter = bound.middle
let d = planenormal.dot(spherecenter) - plane.w
if d > sphereradius {
frontnodes.append(self)
} else if d < -sphereradius {
backnodes.append(self)
} else {
let splitresult = plane.splitPolygon(polygon!)
switch splitresult.type {
case .Coplanar_front:
// coplanar front:
cpfrontnodes.append(self)
case .Coplanar_back:
// coplanar back:
backnodes.append(self)
case .Front:
// front:
frontnodes.append(self)
case .Back:
// back:
backnodes.append(self)
case .Spanning:
// spanning:
if let front = splitresult.front {
let frontnode = addChild(front)
frontnodes.append(frontnode)
}
if let back = splitresult.back {
let backnode = addChild(back)
backnodes.append(backnode)
}
default:
print("unexpected err", terminator: "\n")
break
}
}
}
}
}
// PRIVATE methods from here:
// add child to a node
// this should be called whenever the polygon is split
// a child should be created for every fragment of the split polygon
// returns the newly created child
fileprivate func addChild(_ poly: Polygon) -> PolygonTreeNode {
let newchild = PolygonTreeNode()
newchild.parent = self
newchild.polygon = poly
self.children.append(newchild)
return newchild
}
fileprivate func invertSub() {
if let poly = polygon {
polygon = poly.flipped()
}
for child in children {
child.invertSub()
}
}
fileprivate func recursivelyInvalidatePolygon() {
if polygon != nil {
polygon = nil
if let parentcsg = parent {
parentcsg.recursivelyInvalidatePolygon()
}
}
}
}
// # class MeshTree
// This is the root of a BSP tree
// We are using this separate class for the root of the tree, to hold the PolygonTreeNode root
// The actual tree is kept in this.rootnode
class MeshTree {
var polygonTree : PolygonTreeNode
var rootnode : Node
init(polygons : [Polygon]) {
polygonTree = PolygonTreeNode()
rootnode = Node(parent: nil)
if polygons.count > 0 {
addPolygons(polygons)
}
}
func invert() {
polygonTree.invert()
rootnode.invert()
}
// Remove all polygons in this BSP tree that are inside the other BSP tree
// `tree`.
func clipTo(_ tree: MeshTree, alsoRemovecoplanarFront: Bool) {
rootnode.clipTo(tree, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
}
func allPolygons() -> [Polygon] {
return polygonTree.getPolygons()
}
func addPolygons(_ polygons : [Polygon]) {
var polygontreenodes : [PolygonTreeNode] = []
for poly in polygons {
polygontreenodes += [polygonTree.addChild(poly)]
}
rootnode.addPolygonTreeNodes(polygontreenodes)
}
}
// # class Node
// Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
// by picking a polygon to split along.
// Polygons are not stored directly in the tree, but in PolygonTreeNodes, stored in
// this.polygontreenodes. Those PolygonTreeNodes are children of the owning
// CSG.Tree.polygonTree
// This is not a leafy BSP tree since there is
// no distinction between internal and leaf nodes.
class Node {
var plane : Plane? = nil
var front : Node? = nil
var back : Node? = nil
var polyTreeNodes : [PolygonTreeNode] = []
var parent : Node?
init(parent: Node?) {
self.parent = parent
}
// Convert solid space to empty space and empty space to solid space.
func invert() {
if let p = plane {
plane = p.flipped()
}
if let f = front {
f.invert()
}
if let b = back {
b.invert()
}
let temp = front
front = back
back = temp
}
// clip polygontreenodes to our plane
// calls remove() for all clipped PolygonTreeNodes
func clipPolygons(_ ptNodes: [PolygonTreeNode], alsoRemovecoplanarFront: Bool) {
if let p = plane {
var backnodes = [PolygonTreeNode]()
var frontnodes = [PolygonTreeNode]()
var coplanarfrontnodes = alsoRemovecoplanarFront ? backnodes : frontnodes
for node in ptNodes {
if !node.removed {
node.splitByPlane(p, cpfrontnodes: &coplanarfrontnodes, frontnodes: &frontnodes, backnodes: &backnodes)
}
}
if let f = front {
if frontnodes.count > 0 {
f.clipPolygons(frontnodes, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
}
}
if (back != nil) && (backnodes.count > 0) {
back!.clipPolygons(backnodes, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
} else {
// there's nothing behind this plane. Delete the nodes behind this plane:
for node in backnodes {
node.remove()
}
}
}
}
// Remove all polygons in this BSP tree that are inside the other BSP tree
// `tree`.
func clipTo(_ tree: MeshTree, alsoRemovecoplanarFront: Bool) {
if polyTreeNodes.count > 0 {
tree.rootnode.clipPolygons(polyTreeNodes, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
}
if let f = front {
f.clipTo(tree, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
}
if let b = back {
b.clipTo(tree, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
}
}
func addPolygonTreeNodes(_ polygontreenodes: [PolygonTreeNode]) {
if polygontreenodes.count > 0 {
if plane == nil {
let bestplane = polygontreenodes[0].getPolygon()?.plane
plane = bestplane;
}
var frontnodes : [PolygonTreeNode] = []
var backnodes : [PolygonTreeNode] = []
for node in polygontreenodes {
node.splitByPlane(plane!, cpfrontnodes: &self.polyTreeNodes, frontnodes: &frontnodes, backnodes: &backnodes)
}
if frontnodes.count > 0 {
if front == nil {
front = Node(parent: self)
}
if let f = front {
f.addPolygonTreeNodes(frontnodes)
}
}
if backnodes.count > 0 {
if back == nil {
back = Node(parent: self)
}
if let b = back {
b.addPolygonTreeNodes(backnodes)
}
}
}
}
func getParentPlaneNormals(_ normals: inout [Vector], maxdepth: Int) {
if maxdepth > 0 {
if let p = parent {
normals.append(p.plane!.normal)
p.getParentPlaneNormals(&normals, maxdepth: maxdepth - 1);
}
}
}
}
|
apache-2.0
|
4e5fa1f3b60025ad5468d99ab8437aaa
| 34.784038 | 187 | 0.524797 | 4.973573 | false | false | false | false |
quintonwall/SObjectKit
|
SObjectKit/Classes/Product.swift
|
2
|
1684
|
//
// Product.swift
// Pods
// Represents the Product2 sobject
//
// Created by QUINTON WALL on 12/7/16.
//
//
import Foundation
import SwiftyJSON
public final class Product : SObject {
public var Description : String?
public var Family : String?
public var IsActive : Bool?
public var IsDeleted : Bool?
public var LastReferencedDate : Date?
public var LastViewedDate : Date?
public var Name : String?
public var ProductCode : String?
override public class func populateToCollection(_ records : NSArray) -> [SObject] {
var allrecords : [Product] = []
let j = JSON(records)
for (_, subJson) in j {
allrecords.append(Product(json: subJson))
}
return allrecords
}
override public class func soqlGetAllFields(_ id: String?) -> String {
return configSOQLStatement(id, soqlbase: "select CreatedById, CreatedDate, Description, Family, Id, IsActive, IsDeleted, LastModifiedById, LastModifiedDate, LastReferencedDate, LastViewedDate, Name, ProductCode, SystemModstamp from Product2")
}
public init(json: JSON) {
super.init(objectType: SObjectType.Product2, json: json)
Name = json["Name"].stringValue
ProductCode = json["ProductCode"].stringValue
LastViewedDate = json["LastViewedDate"].date
LastReferencedDate = json["LastReferencedDate"].date
IsDeleted = json["IsDeleted"].boolValue
IsActive = json["IsActive"].boolValue
Family = json["Family"].stringValue
Description = json["Description"].stringValue
}
}
|
mit
|
45378f209e3952d9e6dbbeb6829c260c
| 28.54386 | 258 | 0.637173 | 4.466844 | false | false | false | false |
ygorshenin/omim
|
iphone/Maps/Classes/Components/Modal/AlertPresentationController.swift
|
1
|
653
|
final class AlertPresentationController: DimmedModalPresentationController {
override var frameOfPresentedViewInContainerView: CGRect {
let f = super.frameOfPresentedViewInContainerView
let s = presentedViewController.view.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
let r = CGRect(x: 0, y: 0, width: s.width, height: s.height)
return r.offsetBy(dx: (f.width - r.width) / 2, dy: (f.height - r.height) / 2)
}
override func presentationTransitionWillBegin() {
super.presentationTransitionWillBegin()
presentedViewController.view.layer.cornerRadius = 12
presentedViewController.view.clipsToBounds = true
}
}
|
apache-2.0
|
3dd7ddd7274f01853aead772a53b29ca
| 45.642857 | 95 | 0.770291 | 4.909774 | false | false | false | false |
gregomni/swift
|
test/Sema/const_pass_as_arguments.swift
|
9
|
3381
|
// RUN: %target-typecheck-verify-swift
public func takeIntConst(_ a: _const Int) {}
public func takeStringConst(_ a: _const String) {}
public func takeDoubleConst(_ a: _const Double) {}
public func takeArrayConst(_ a: _const [String]) {}
public func takeDictConst(_ a: _const [Int: String]) {}
func main(_ i: Int, _ d: Double, _ s: String, arr: [String], dict: [Int: String]) {
takeIntConst(2)
takeDoubleConst(3.3)
takeStringConst("")
takeArrayConst([""])
takeDictConst([1: "", 2: "text"])
takeIntConst(i) // expected-error {{expect a compile-time constant literal}}
takeDoubleConst(d) // expected-error {{expect a compile-time constant literal}}
takeStringConst("\(d)") // expected-error {{expect a compile-time constant literal}}
takeStringConst(s) // expected-error {{expect a compile-time constant literal}}
takeArrayConst(arr) // expected-error {{expect a compile-time constant literal}}
takeArrayConst([s]) // expected-error {{expect a compile-time constant literal}}
takeArrayConst(["", s]) // expected-error {{expect a compile-time constant literal}}
takeDictConst([1: "", 2: s]) // expected-error {{expect a compile-time constant literal}}
takeDictConst([1: "", i: "text"]) // expected-error {{expect a compile-time constant literal}}
}
public struct Utils {
public func takeIntConst(_ a: _const Int) {}
public func takeStringConst(_ a: _const String) {}
public func takeDoubleConst(_ a: _const Double) {}
}
func main_member(_ u: Utils, _ i: Int, _ d: Double, _ s: String) {
u.takeIntConst(2)
u.takeDoubleConst(3.3)
u.takeStringConst("")
u.takeIntConst(i) // expected-error {{expect a compile-time constant literal}}
u.takeDoubleConst(d) // expected-error {{expect a compile-time constant literal}}
u.takeStringConst("\(d)") // expected-error {{expect a compile-time constant literal}}
u.takeStringConst(s) // expected-error {{expect a compile-time constant literal}}
}
protocol ConstFan {
static _const var v: String { get } // expected-note {{protocol requires property 'v' with type 'String'; do you want to add a stub?}}
}
class ConstFanClass1: ConstFan { // expected-error {{type 'ConstFanClass1' does not conform to protocol 'ConstFan'}}
static let v: String = "" // expected-note {{candidate operates as non-const, not const as required}}
}
class ConstFanClassCorrect: ConstFan {
static _const let v: String = ""
}
class ConstFanClassWrong1: ConstFan {
static _const let v: String // expected-error {{_const let should be initialized with a compile-time literal}}
// expected-error@-1 {{'static let' declaration requires an initializer expression or an explicitly stated getter}}
// expected-note@-2 {{add an initializer to silence this error}}
}
class ConstFanClassWrong2: ConstFan {
static _const let v: String = "\(v)" // expected-error {{_const let should be initialized with a compile-time literal}}
}
class ConstFanClassWrong3: ConstFan {
static _const var v: String = "" // expected-error {{let is required for a _const variable declaration}}
}
class ConstFanClassWrong4: ConstFan {
static func giveMeString() -> String { return "" }
static _const let v: String = giveMeString() // expected-error {{_const let should be initialized with a compile-time literal}}
}
_const let globalConst = 3
class ConstFanClassWrong5 {
func foo() -> Int {
_const let localConst = 3
return globalConst + localConst
}
}
|
apache-2.0
|
f3dbf406114a5637ca074e1f83f0a146
| 40.231707 | 136 | 0.714286 | 3.540314 | false | false | false | false |
seaburg/PHDiff
|
Example/Example/DemoColor.swift
|
2
|
703
|
//
// DemoColor.swift
// Example
//
// Created by Andre Alves on 10/13/16.
// Copyright © 2016 Andre Alves. All rights reserved.
//
import UIKit
import PHDiff
struct DemoColor {
let name: String
let r: Float
let g: Float
let b: Float
func toUIColor() -> UIColor {
return UIColor(red: CGFloat(r)/255,
green: CGFloat(g)/255,
blue: CGFloat(b)/255,
alpha: 1.0)
}
}
extension DemoColor: Diffable {
var diffIdentifier: String {
return name
}
}
func ==(lhs: DemoColor, rhs: DemoColor) -> Bool {
return lhs.name == rhs.name && lhs.r == rhs.r && lhs.b == rhs.b && lhs.g == rhs.g
}
|
mit
|
8f4ce6b4ef021caf44757d2677577d14
| 19.647059 | 85 | 0.549858 | 3.581633 | false | false | false | false |
SwiftKit/Lipstick
|
LipstickTests/UIOffset+InitTest.swift
|
1
|
688
|
//
// UIOffset+InitTest.swift
// Lipstick
//
// Created by Filip Dolnik on 18.10.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Quick
import Nimble
import Lipstick
class UIOffsetInitTest: QuickSpec {
override func spec() {
describe("UIOffset init") {
it("creates UIOffset") {
expect(UIOffset(horizontal: 0, vertical: 0)) == UIOffset()
expect(UIOffset(horizontal: 1, vertical: 1)) == UIOffset(1)
expect(UIOffset(horizontal: 1, vertical: 0)) == UIOffset(horizontal: 1)
expect(UIOffset(horizontal: 0, vertical: 1)) == UIOffset(vertical: 1)
}
}
}
}
|
mit
|
0ef68ca1f843353cc28982b43d7f5d2e
| 26.48 | 87 | 0.58952 | 4.089286 | false | true | false | false |
orkenstein/ZLSwipeableViewSwift
|
ZLSwipeableViewSwiftDemo/Pods/Cartography/Cartography/ViewUtils.swift
|
31
|
927
|
//
// ViewUtils.swift
// Cartography
//
// Created by Garth Snyder on 11/23/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import AppKit
#endif
internal func closestCommonAncestor(a: View, b: View) -> View? {
let (aSuper, bSuper) = (a.superview, b.superview)
if a === b { return a }
if a === bSuper { return a }
if b === aSuper { return b }
if aSuper === bSuper { return aSuper }
var ancestorsOfA = Set(ancestors(a))
for ancestor in ancestors(b) {
if ancestorsOfA.contains(ancestor) {
return ancestor
}
}
return .None
}
private func ancestors(v: View) -> SequenceOf<View> {
return SequenceOf<View> { () -> GeneratorOf<View> in
var view: View? = v
return GeneratorOf {
let current = view
view = view?.superview
return current
}
}
}
|
mit
|
77f39d76ae4b3466530cb6085e046f6f
| 19.130435 | 64 | 0.583153 | 3.645669 | false | false | false | false |
ntwf/TheTaleClient
|
TheTale/Stores/PlayerInformation/AccountInformation/AccountInformation.swift
|
1
|
957
|
//
// AccountInfo.swift
// the-tale
//
// Created by Mikhail Vospennikov on 28/06/2017.
// Copyright © 2017 Mikhail Vospennikov. All rights reserved.
//
import Foundation
final class AccountInformation: NSObject {
var accountID: Int
var isOwn: Bool
var isOld: Bool
var hero: JSON
var inPvPQueue: Bool
var lastVisit: Int
required init?(jsonObject: JSON) {
guard let accountID = jsonObject["id"] as? Int,
let isOwn = jsonObject["is_own"] as? Bool,
let isOld = jsonObject["is_old"] as? Bool,
let inPvPQueue = jsonObject["in_pvp_queue"] as? Bool,
let lastVisit = jsonObject["last_visit"] as? Int,
let hero = jsonObject["hero"] as? JSON else {
return nil
}
self.accountID = accountID
self.isOld = isOld
self.isOwn = isOwn
self.hero = hero
self.inPvPQueue = inPvPQueue
self.lastVisit = lastVisit
}
}
|
mit
|
f434e47a45cfd70a1c4db34733b40aba
| 24.157895 | 64 | 0.609833 | 3.676923 | false | false | false | false |
AlesTsurko/Simple-MIDI
|
MIDIIn.swift
|
1
|
6840
|
//
// MIDIIn.swift
//
// Created by Ales Tsurko on 22.08.16.
// Copyright © 2016 Aliaksandr Tsurko. All rights reserved.
//
extension AUValue {
func mapLinearRangeToLinear(inMin: AUValue, inMax: AUValue, outMin: AUValue, outMax: AUValue) -> AUValue {
return (self - inMin) / (inMax - inMin) * (outMax - outMin) + outMin
}
}
open class MIDIMap: NSObject {
open var noteOnOffCallback: ((_ note: UInt8, _ velocity: UInt8) -> Void)?
open var sustainPedalCallback: ((_ value: UInt8) -> Void)?
open var pitchBendCallback: ((_ value: UInt8) -> Void)?
open var modulationWheelCallback: ((_ value: UInt8) -> Void)?
open var notificationCallback: ((_ message: MIDINotification) -> Void)?
open var ccMapping: [UInt8: AUParameter]?
required public init(noteOnOffCallback: ((UInt8, UInt8) -> Void)?, sustainPedalCallback: ((UInt8) -> Void)?, pitchBendCallback: ((UInt8) -> Void)?, modulationWheelCallback: ((UInt8) -> Void)?, notificationCallback: ((MIDINotification) -> Void)?, ccMapping: [UInt8: AUParameter]?) {
super.init()
self.noteOnOffCallback = noteOnOffCallback
self.sustainPedalCallback = sustainPedalCallback
self.pitchBendCallback = pitchBendCallback
self.modulationWheelCallback = modulationWheelCallback
self.notificationCallback = notificationCallback
self.ccMapping = ccMapping
}
}
open class MIDIDevice: NSObject {
open var name: String!
open var uniqueID: Int32!
open var isConnected: Bool {
didSet {
var object: MIDIObjectRef = 0
var type: MIDIObjectType = MIDIObjectType.destination
let err = MIDIObjectFindByUniqueID(self.uniqueID, &object, &type)
if self.isConnected && err != kMIDIObjectNotFound {
MIDIPortConnectSource(self.midiIn.port, object, nil)
print("\(self.name!) is connected")
} else {
MIDIPortDisconnectSource(self.midiIn.port, object)
print("\(self.name!) is disconnected")
}
}
}
open var midiIn: MIDIIn!
required public init(midiIn: MIDIIn, name: String, id: Int32, isConnected: Bool) {
self.midiIn = midiIn
self.name = name
self.uniqueID = id
self.isConnected = isConnected
}
}
private var inputDescription: MIDIMap!
open class MIDIIn: NSObject {
open let client: MIDIClientRef
open let port: MIDIPortRef
open let midiMap: MIDIMap
open var availableDevices: [MIDIDevice] = []
open let MIDINotifyCallback: MIDINotifyProc = {message, refCon in
var inDesc = refCon?.assumingMemoryBound(to: MIDIMap.self).pointee
if let callback = inDesc?.notificationCallback {
callback(message.pointee)
}
}
open let MIDIReadCallback: MIDIReadProc = {pktlist, refCon, connRefCon in
var inDesc = refCon?.assumingMemoryBound(to: MIDIMap.self).pointee
var packet = pktlist.pointee.packet
for _ in 1...pktlist.pointee.numPackets {
let midiStatus = packet.data.0
let midiCommand = midiStatus>>4
// NoteOff, NoteOn
if midiCommand == 0x08 || midiCommand == 0x09 {
let note = packet.data.1&0x7f
let velocity = midiCommand == 0x08 ? 0 : packet.data.2&0x7f
if let callback = inDesc?.noteOnOffCallback {
callback(note, velocity)
}
}
// Pitch bend
if midiCommand == 0x0E {
if let callback = inDesc?.pitchBendCallback {
let value = packet.data.2&0x7f
callback(value)
}
}
// CC change
if midiCommand == 0x0B {
let number = packet.data.1&0x7f
let value = packet.data.2&0x7f
if number == 1 {
// if CC is the modulation wheel
if let callback = inDesc?.modulationWheelCallback {
callback(value)
}
} else if number == 64 {
// if CC is a sustain pedal
if let callback = inDesc?.sustainPedalCallback {
callback(value)
}
} else {
if let ccMap = inDesc?.ccMapping {
if let parameter = ccMap[number] {
parameter.value = AUValue(value).mapLinearRangeToLinear(inMin: 0, inMax: 127, outMin: parameter.minValue, outMax: parameter.maxValue)
}
}
}
// print("CCNum \(number) with value \(value)")
}
// copy into new var to prevent bug, that appeared when using a
// packet's reference in place
var packCopy = packet
packet = MIDIPacketNext(&packCopy).pointee
}
}
required public init(clientName: String, portName: String, midiMap: MIDIMap) {
inputDescription = midiMap
self.midiMap = midiMap
// Create client, port and connect
var clientRef = MIDIPortRef()
MIDIClientCreate(clientName as CFString, MIDINotifyCallback, &inputDescription, &clientRef)
var portRef = MIDIPortRef()
MIDIInputPortCreate(clientRef, portName as CFString, MIDIReadCallback, &inputDescription, &portRef)
self.port = portRef
self.client = clientRef
super.init()
self.updateAvailableDevices()
// allow network MIDI
let session = MIDINetworkSession.default()
session.isEnabled = true
session.connectionPolicy = MIDINetworkConnectionPolicy.anyone
}
open func updateAvailableDevices() {
// fill available inputs
let sourceCount = MIDIGetNumberOfSources()
self.availableDevices = []
for i in 0..<sourceCount {
let src = MIDIGetSource(i)
var endpointName: Unmanaged<CFString>?
MIDIObjectGetStringProperty(src, kMIDIPropertyName, &endpointName)
let name = endpointName!.takeRetainedValue() as String
var id: Int32 = 0
MIDIObjectGetIntegerProperty(src, kMIDIPropertyUniqueID, &id)
let device = MIDIDevice(midiIn: self, name: name, id: id, isConnected: false)
self.availableDevices.append(device)
}
}
}
|
mit
|
83f0329e76c1894b4dede602336ad4c1
| 34.994737 | 285 | 0.560901 | 4.671448 | false | false | false | false |
ryanipete/AmericanChronicle
|
AmericanChronicle/Code/Modules/USStatePicker/View/USStateCell.swift
|
1
|
645
|
import UIKit
final class USStateCell: UICollectionViewCell {
let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
selectedBackgroundView = UIView()
selectedBackgroundView?.backgroundColor = AMCColor.brightBlue
label.textAlignment = .center
label.font = AMCFont.largeRegular
label.frame = bounds
label.highlightedTextColor = .white
contentView.addSubview(label)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
3e9569e33b59477fe36a695aa9fa1cbd
| 28.318182 | 69 | 0.663566 | 5 | false | false | false | false |
Jauzee/showroom
|
Showroom/Views/CircleView/CircleView.swift
|
2
|
1509
|
import UIKit
class CircleView: UIView {
// MARK: Inits
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
layer.shouldRasterize = true
layer.shadowOpacity = 1
layer.shadowColor = UIColor.white.cgColor
layer.shadowOffset = CGSize(width: -40, height: 30);
layer.shadowRadius = 20
}
// enableBlurWithAngle
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: Methods
extension CircleView {
class func build(on view: UIView, position: CGPoint) -> CircleView {
let width = position.x
let height = UIScreen.main.bounds.size.height - position.y
let diagonal = sqrt(width * width + height * height) * 2
let circleView = CircleView(frame: CGRect(x: 0, y: 0, width: diagonal, height: diagonal))
circleView.layer.cornerRadius = diagonal / 2
circleView.center = position
// view.addSubview(circleView)
// view.sendSubview(toBack: circleView)
view.layer.mask = circleView.layer
return circleView
}
}
// MARK: Animations
extension CircleView {
func show(completion: @escaping () -> Void = {}) {
alpha = 0
animate(duration: 0.1, [.alpha(to: 1)])
animate(duration: 0.4, [.viewScale(from: 0, to: 1)], timing: .easyInEasyOut, completion: completion)
}
func hide(completion: @escaping () -> Void) {
animate(duration: 0.4, [.viewScale(from: 1, to: 0)], timing: .easyInEasyOut, completion: completion)
}
}
|
gpl-3.0
|
98d5b6a5e52d6ec6187f7ae5c9b555a2
| 26.944444 | 104 | 0.666004 | 3.84949 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io
|
InfiniteScroll/InfiniteScrollTests/Model Tests/PixlrImageUnitTests.swift
|
1
|
3712
|
//
// PixlrImageUnitTests.swift
// InfiniteScrollTests
//
// Created by Anirudh Das on 7/7/18.
// Copyright © 2018 Aniruddha Das. All rights reserved.
//
import XCTest
import SwiftyJSON
@testable import InfiniteScroll
// MARK: - Tests Init, Parsing and Equatable for PixlrImage
class PixlrImageUnitTests: XCTestCase {
func testParsingLogicOfPixlrImageSuccess() {
let bundle = Bundle(for: type(of: self))
if let path = bundle.path(forResource: "ValidJSONData", ofType: "json"), let data = try? Data.init(contentsOf: URL.init(fileURLWithPath: path)) {
let json = JSON(data: data)
guard json != JSON.null, let hits = json["hits"].array, !hits.isEmpty else {
return
}
for hit in hits {
XCTAssertNotNil(PixlrImage(json: hit, pageNumber: 1), "Successful Parsing")
}
}
}
func testParsingLogicOfPixlrImageFailure() {
let bundle = Bundle(for: type(of: self))
if let path = bundle.path(forResource: "InValidJSONData", ofType: "json"), let data = try? Data.init(contentsOf: URL.init(fileURLWithPath: path)) {
let json = JSON(data: data)
guard json != JSON.null, let hits = json["hits"].array, !hits.isEmpty else {
return
}
for hit in hits {
XCTAssertNil(PixlrImage(json: hit, pageNumber: 1), "Successful Parsing")
}
}
}
func testInitPixlrImageWithValidParam() {
let dict: [String: Any] = ["id": 1234, "webformatURL": "https://pixabay.com/get/ea30b0082af4073ed1584d05fb1d4f92eb73ebd01fac104496f0c87ea0efb5be_640.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/07/04/22/55/fantasy-3517206_150.jpg"]
let json = JSON(parseJSON: dict.toJSONString())
let image = PixlrImage(json: json, pageNumber: 1)
XCTAssertNotNil(image, "Initialization Success")
XCTAssertEqual(image?.id, dict["id"] as? Int)
}
func testInitPixlrImageWithInValidParam() {
let dict: [String: Any] = ["id": 1234, "webURL": "https://pixabay.com/get/ea30b0082af4073ed1584d05fb1d4f92eb73ebd01fac104496f0c87ea0efb5be_640.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/07/04/22/55/fantasy-3517206_150.jpg"]
let json = JSON(parseJSON: dict.toJSONString())
let image = PixlrImage(json: json, pageNumber: 1)
XCTAssertNil(image, "Initialization Failure")
}
func testEquatableReturnsTrue() {
let dict: [String: Any] = ["id": 1234, "webformatURL": "https://pixabay.com/get/ea30b0082af4073ed1584d05fb1d4f92eb73ebd01fac104496f0c87ea0efb5be_640.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/07/04/22/55/fantasy-3517206_150.jpg"]
let json = JSON(parseJSON: dict.toJSONString())
let image1 = PixlrImage(json: json, pageNumber: 1)
let image2 = PixlrImage(json: json, pageNumber: 1)
XCTAssertEqual(image1, image2)
}
func testEquatableReturnsFalse() {
let dict: [String: Any] = ["id": 1234, "webformatURL": "https://pixabay.com/get/ea30b0082af4073ed1584d05fb1d4f92eb73ebd01fac104496f0c87ea0efb5be_640.jpg",
"previewURL": "https://cdn.pixabay.com/photo/2018/07/04/22/55/fantasy-3517206_150.jpg"]
let json = JSON(parseJSON: dict.toJSONString())
let image1 = PixlrImage(json: json, pageNumber: 1)
let image2 = PixlrImage(json: json, pageNumber: 2)
XCTAssertNotEqual(image1, image2)
}
}
|
apache-2.0
|
de2f02b358bfca83f1c5f5d74f8b02a4
| 43.178571 | 162 | 0.61951 | 3.578592 | false | true | false | false |
grachro/swift-layout
|
swift-layout/sampleViewControllers/BlurEffectViewController.swift
|
1
|
3898
|
//
// BlurEffectViewController.swift
// swift-layout
//
// Created by grachro on 2014/09/15.
// Copyright (c) 2014年 grachro. All rights reserved.
//
import UIKit
class BlurEffectViewController: UIViewController {
//磨りガラス効果
let extraLight = Layout.createExtraLightBlurEffect()
let light = Layout.createLightBlurEffect()
let dark = Layout.createDarkBlurEffect()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
//背景
let text1 = Layout.createCharWrappingLabel("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
Layout.addSubView(text1, superview: self.view)
.font(UIFont.systemFont(ofSize: 20))
.width(120)
.top(20).fromSuperviewTop()
.horizontalCenterInSuperview()
let text2 = Layout.createCharWrappingLabel("ABCDEFG")
Layout.addSubView(text2, superview: self.view)
.font(UIFont.boldSystemFont(ofSize: 40))
.textColor(UIColor.red)
.width(120)
.top(20).fromBottom(text1)
.horizontalCenterInSuperview()
//磨りガラス配置
Layout.addSubView(extraLight, superview: self.view)
.coverSuperView()
Layout.addSubView(light, superview: self.view)
.coverSuperView()
.hide()
Layout.addSubView(dark, superview: self.view)
.coverSuperView()
.hide()
//磨りガラス変更ボタン
let extraLightBtn = Layout.createSystemTypeBtn("ExtraLight")
Layout.addSubView(extraLightBtn, superview: self.view)
.bottom(20).fromSuperviewBottom()
.left(10).fromSuperviewLeft()
.touchUpInside({self.toggle(0)})
let lightBtn = Layout.createSystemTypeBtn("Light")
Layout.addSubView(lightBtn, superview: self.view)
.bottom(20).fromSuperviewBottom()
.left(10).fromRight(extraLightBtn)
.touchUpInside({self.toggle(1)})
let darkBtn = Layout.createSystemTypeBtn("Dark")
Layout.addSubView(darkBtn, superview: self.view)
.bottom(20).fromSuperviewBottom()
.left(10).fromRight(lightBtn)
.touchUpInside({self.toggle(2)})
let nothigBtn = Layout.createSystemTypeBtn("nothing")
Layout.addSubView(nothigBtn, superview: self.view)
.bottom(20).fromSuperviewBottom()
.left(10).fromRight(darkBtn)
.touchUpInside({self.toggle(3)})
//戻るボタン
let btn = Layout.createSystemTypeBtn("return")
Layout.addSubView(btn, superview: self.view)
.bottomIsSameSuperview()
.rightIsSameSuperview()
.touchUpInside({self.dismiss(animated: true, completion:nil)})
}
func toggle(_ id:Int) {
switch id {
case 0:
Layout.more(self.extraLight).show();
Layout.more(self.light).hide();
Layout.more(self.dark).hide()
case 1:
Layout.more(self.extraLight).hide();
Layout.more(self.light).show();
Layout.more(self.dark).hide()
case 2:
Layout.more(self.extraLight).hide();
Layout.more(self.light).hide();
Layout.more(self.dark).show()
default :
Layout.more(self.extraLight).hide();
Layout.more(self.light).hide();
Layout.more(self.dark).hide()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
36cf4d99eb6f2bc23a7ea6c7a8a9e040
| 28.72093 | 80 | 0.564945 | 4.505288 | false | false | false | false |
e78l/swift-corelibs-foundation
|
Foundation/URLSession/BodySource.swift
|
1
|
10433
|
// Foundation/URLSession/BodySource.swift - URLSession & libcurl
//
// 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
//
// -----------------------------------------------------------------------------
///
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
import CoreFoundation
import CFURLSessionInterface
import Dispatch
/// Turn `Data` into `DispatchData`
internal func createDispatchData(_ data: Data) -> DispatchData {
//TODO: Avoid copying data
return data.withUnsafeBytes { DispatchData(bytes: $0) }
}
/// Copy data from `DispatchData` into memory pointed to by an `UnsafeMutableBufferPointer`.
internal func copyDispatchData<T>(_ data: DispatchData, infoBuffer buffer: UnsafeMutableBufferPointer<T>) {
precondition(data.count <= (buffer.count * MemoryLayout<T>.size))
_ = data.copyBytes(to: buffer)
}
/// Split `DispatchData` into `(head, tail)` pair.
internal func splitData(dispatchData data: DispatchData, atPosition position: Int) -> (DispatchData,DispatchData) {
return (data.subdata(in: 0..<position), data.subdata(in: position..<data.count))
}
/// A (non-blocking) source for body data.
internal protocol _BodySource: class {
/// Get the next chunck of data.
///
/// - Returns: `.data` until the source is exhausted, at which point it will
/// return `.done`. Since this is non-blocking, it will return `.retryLater`
/// if no data is available at this point, but will be available later.
func getNextChunk(withLength length: Int) -> _BodySourceDataChunk
}
internal enum _BodySourceDataChunk {
case data(DispatchData)
/// The source is depleted.
case done
/// Retry later to get more data.
case retryLater
case error
}
internal final class _BodyStreamSource {
let inputStream: InputStream
init(inputStream: InputStream) {
self.inputStream = inputStream
}
}
extension _BodyStreamSource : _BodySource {
func getNextChunk(withLength length: Int) -> _BodySourceDataChunk {
guard inputStream.hasBytesAvailable else {
return .done
}
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: length, alignment: MemoryLayout<UInt8>.alignment)
guard let pointer = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
buffer.deallocate()
return .error
}
let readBytes = self.inputStream.read(pointer, maxLength: length)
if readBytes > 0 {
let dispatchData = DispatchData(bytesNoCopy: UnsafeRawBufferPointer(buffer), deallocator: .custom(nil, { buffer.deallocate() }))
return .data(dispatchData.subdata(in: 0 ..< readBytes))
}
else if readBytes == 0 {
buffer.deallocate()
return .done
}
else {
buffer.deallocate()
return .error
}
}
}
/// A body data source backed by `DispatchData`.
internal final class _BodyDataSource {
var data: DispatchData!
init(data: DispatchData) {
self.data = data
}
}
extension _BodyDataSource : _BodySource {
enum _Error : Error {
case unableToRewindData
}
func getNextChunk(withLength length: Int) -> _BodySourceDataChunk {
let remaining = data.count
if remaining == 0 {
return .done
} else if remaining <= length {
let r: DispatchData! = data
data = DispatchData.empty
return .data(r)
} else {
let (chunk, remainder) = splitData(dispatchData: data, atPosition: length)
data = remainder
return .data(chunk)
}
}
}
/// A HTTP body data source backed by a file.
///
/// This allows non-blocking streaming of file data to the remote server.
///
/// The source reads data using a `DispatchIO` channel, and hence reading
/// file data is non-blocking. It has a local buffer that it fills as calls
/// to `getNextChunk(withLength:)` drain it.
///
/// - Note: Calls to `getNextChunk(withLength:)` and callbacks from libdispatch
/// should all happen on the same (serial) queue, and hence this code doesn't
/// have to be thread safe.
internal final class _BodyFileSource {
fileprivate let fileURL: URL
fileprivate let channel: DispatchIO
fileprivate let workQueue: DispatchQueue
fileprivate let dataAvailableHandler: () -> Void
fileprivate var hasActiveReadHandler = false
fileprivate var availableChunk: _Chunk = .empty
/// Create a new data source backed by a file.
///
/// - Parameter fileURL: the file to read from
/// - Parameter workQueue: the queue that it's safe to call
/// `getNextChunk(withLength:)` on, and that the `dataAvailableHandler`
/// will be called on.
/// - Parameter dataAvailableHandler: Will be called when data becomes
/// available. Reading data is done in a non-blocking way, such that
/// no data may be available even if there's more data in the file.
/// if `getNextChunk(withLength:)` returns `.retryLater`, this handler
/// will be called once data becomes available.
init(fileURL: URL, workQueue: DispatchQueue, dataAvailableHandler: @escaping () -> Void) {
guard fileURL.isFileURL else { fatalError("The body data URL must be a file URL.") }
self.fileURL = fileURL
self.workQueue = workQueue
self.dataAvailableHandler = dataAvailableHandler
guard let channel = fileURL.withUnsafeFileSystemRepresentation({
// DispatchIO (dispatch_io_create_with_path) makes a copy of the path
DispatchIO(type: .stream, path: $0!,
oflag: O_RDONLY, mode: 0, queue: workQueue,
cleanupHandler: {_ in })
}) else {
fatalError("Can't create DispatchIO channel")
}
self.channel = channel
self.channel.setLimit(highWater: CFURLSessionMaxWriteSize)
}
fileprivate enum _Chunk {
/// Nothing has been read, yet
case empty
/// An error has occurred while reading
case errorDetected(Int)
/// Data has been read
case data(DispatchData)
/// All data has been read from the file (EOF).
case done(DispatchData?)
}
}
extension _BodyFileSource {
fileprivate var desiredBufferLength: Int { return 3 * CFURLSessionMaxWriteSize }
/// Enqueue a dispatch I/O read to fill the buffer.
///
/// - Note: This is a no-op if the buffer is full, or if a read operation
/// is already enqueued.
fileprivate func readNextChunk() {
// libcurl likes to use a buffer of size CFURLSessionMaxWriteSize, we'll
// try to keep 3 x of that around in the `chunk` buffer.
guard availableByteCount < desiredBufferLength else { return }
guard !hasActiveReadHandler else { return } // We're already reading
hasActiveReadHandler = true
let lengthToRead = desiredBufferLength - availableByteCount
channel.read(offset: 0, length: lengthToRead, queue: workQueue) { (done: Bool, data: DispatchData?, errno: Int32) in
let wasEmpty = self.availableByteCount == 0
self.hasActiveReadHandler = !done
switch (done, data, errno) {
case (true, _, errno) where errno != 0:
self.availableChunk = .errorDetected(Int(errno))
case (true, let d?, 0) where d.isEmpty:
self.append(data: d, endOfFile: true)
case (true, let d?, 0):
self.append(data: d, endOfFile: false)
case (false, let d?, 0):
self.append(data: d, endOfFile: false)
default:
fatalError("Invalid arguments to read(3) callback.")
}
if wasEmpty && (0 < self.availableByteCount) {
self.dataAvailableHandler()
}
}
}
fileprivate func append(data: DispatchData, endOfFile: Bool) {
switch availableChunk {
case .empty:
availableChunk = endOfFile ? .done(data) : .data(data)
case .errorDetected:
break
case .data(var oldData):
oldData.append(data)
availableChunk = endOfFile ? .done(oldData) : .data(oldData)
case .done:
fatalError("Trying to append data, but end-of-file was already detected.")
}
}
fileprivate var availableByteCount: Int {
switch availableChunk {
case .empty: return 0
case .errorDetected: return 0
case .data(let d): return d.count
case .done(let d?): return d.count
case .done(nil): return 0
}
}
}
extension _BodyFileSource : _BodySource {
func getNextChunk(withLength length: Int) -> _BodySourceDataChunk {
switch availableChunk {
case .empty:
readNextChunk()
return .retryLater
case .errorDetected:
return .error
case .data(let data):
let l = min(length, data.count)
let (head, tail) = splitData(dispatchData: data, atPosition: l)
availableChunk = tail.isEmpty ? .empty : .data(tail)
readNextChunk()
if head.isEmpty {
return .retryLater
} else {
return .data(head)
}
case .done(let data?):
let l = min(length, data.count)
let (head, tail) = splitData(dispatchData: data, atPosition: l)
availableChunk = tail.isEmpty ? .done(nil) : .done(tail)
if head.isEmpty {
return .done
} else {
return .data(head)
}
case .done(nil):
return .done
}
}
}
|
apache-2.0
|
a4c85266bf385b03bce370523a32df57
| 35.351916 | 140 | 0.610467 | 4.61433 | false | false | false | false |
storehouse/Advance
|
Samples/SampleApp-iOS/Sources/DemoViewController.swift
|
1
|
3112
|
import UIKit
class DemoViewController: UIViewController {
var note: String {
get { return noteLabel.text ?? "" }
set {
noteLabel.text = newValue
view.setNeedsLayout()
}
}
override var title: String? {
didSet {
titleLabel.text = title
view.setNeedsLayout()
}
}
let contentView = UIView()
fileprivate let titleLabel = UILabel()
fileprivate let noteLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
contentView.alpha = 0.4
contentView.layer.allowsGroupOpacity = false
contentView.isUserInteractionEnabled = false
contentView.frame = view.bounds
view.addSubview(contentView)
titleLabel.font = UIFont.systemFont(ofSize: 32.0, weight: UIFont.Weight.medium)
titleLabel.textColor = UIColor.darkGray
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 0
view.addSubview(titleLabel)
noteLabel.font = UIFont.systemFont(ofSize: 16.0, weight: UIFont.Weight.thin)
noteLabel.textColor = UIColor.darkGray
noteLabel.textAlignment = .center
noteLabel.numberOfLines = 0
noteLabel.alpha = 0.0
view.addSubview(noteLabel)
}
final var fullScreen = false {
didSet {
guard fullScreen != oldValue else { return }
UIView.animate(withDuration: 0.4, animations: {
if self.fullScreen {
self.didEnterFullScreen()
} else {
self.didLeaveFullScreen()
}
})
}
}
func didEnterFullScreen() {
noteLabel.alpha = 1.0
contentView.alpha = 1.0
contentView.isUserInteractionEnabled = true
titleLabel.alpha = 0.0
}
func didLeaveFullScreen() {
noteLabel.alpha = 0.0
contentView.alpha = 0.5
contentView.isUserInteractionEnabled = false
titleLabel.alpha = 1.0
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
contentView.frame = view.bounds
let labelHeight = noteLabel.sizeThatFits(CGSize(width: view.bounds.width-64.0, height: CGFloat.greatestFiniteMagnitude)).height
var labelFrame = CGRect.zero
labelFrame.origin.x = 32.0
labelFrame.origin.y = 64.0
labelFrame.size.width = view.bounds.width - 64.0
labelFrame.size.height = labelHeight
noteLabel.frame = labelFrame
let titleHeight = titleLabel.sizeThatFits(CGSize(width: view.bounds.width-64.0, height: CGFloat.greatestFiniteMagnitude)).height
var titleFrame = CGRect.zero
titleFrame.origin.x = 32.0
titleFrame.origin.y = 64.0
titleFrame.size.width = view.bounds.width - 64.0
titleFrame.size.height = titleHeight
titleLabel.frame = titleFrame
}
}
|
bsd-2-clause
|
becef691e5b2732ec1e9c79102fa41bf
| 30.12 | 136 | 0.595758 | 5.011272 | false | false | false | false |
exoplatform/exo-ios
|
Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift
|
1
|
5935
|
//
// ImageDataProvider.swift
// Kingfisher
//
// Created by onevcat on 2018/11/13.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Represents a data provider to provide image data to Kingfisher when setting with
/// `Source.provider` source. Compared to `Source.network` member, it gives a chance
/// to load some image data in your own way, as long as you can provide the data
/// representation for the image.
public protocol ImageDataProvider {
/// The key used in cache.
var cacheKey: String { get }
/// Provides the data which represents image. Kingfisher uses the data you pass in the
/// handler to process images and caches it for later use.
///
/// - Parameter handler: The handler you should call when you prepared your data.
/// If the data is loaded successfully, call the handler with
/// a `.success` with the data associated. Otherwise, call it
/// with a `.failure` and pass the error.
///
/// - Note:
/// If the `handler` is called with a `.failure` with error, a `dataProviderError` of
/// `ImageSettingErrorReason` will be finally thrown out to you as the `KingfisherError`
/// from the framework.
func data(handler: @escaping (Result<Data, Error>) -> Void)
/// The content URL represents this provider, if exists.
var contentURL: URL? { get }
}
public extension ImageDataProvider {
var contentURL: URL? { return nil }
func convertToSource() -> Source {
.provider(self)
}
}
/// Represents an image data provider for loading from a local file URL on disk.
/// Uses this type for adding a disk image to Kingfisher. Compared to loading it
/// directly, you can get benefit of using Kingfisher's extension methods, as well
/// as applying `ImageProcessor`s and storing the image to `ImageCache` of Kingfisher.
public struct LocalFileImageDataProvider: ImageDataProvider {
// MARK: Public Properties
/// The file URL from which the image be loaded.
public let fileURL: URL
// MARK: Initializers
/// Creates an image data provider by supplying the target local file URL.
///
/// - Parameters:
/// - fileURL: The file URL from which the image be loaded.
/// - cacheKey: The key is used for caching the image data. By default,
/// the `absoluteString` of `fileURL` is used.
public init(fileURL: URL, cacheKey: String? = nil) {
self.fileURL = fileURL
self.cacheKey = cacheKey ?? fileURL.absoluteString
}
// MARK: Protocol Conforming
/// The key used in cache.
public var cacheKey: String
public func data(handler: (Result<Data, Error>) -> Void) {
handler(Result(catching: { try Data(contentsOf: fileURL) }))
}
/// The URL of the local file on the disk.
public var contentURL: URL? {
return fileURL
}
}
/// Represents an image data provider for loading image from a given Base64 encoded string.
public struct Base64ImageDataProvider: ImageDataProvider {
// MARK: Public Properties
/// The encoded Base64 string for the image.
public let base64String: String
// MARK: Initializers
/// Creates an image data provider by supplying the Base64 encoded string.
///
/// - Parameters:
/// - base64String: The Base64 encoded string for an image.
/// - cacheKey: The key is used for caching the image data. You need a different key for any different image.
public init(base64String: String, cacheKey: String) {
self.base64String = base64String
self.cacheKey = cacheKey
}
// MARK: Protocol Conforming
/// The key used in cache.
public var cacheKey: String
public func data(handler: (Result<Data, Error>) -> Void) {
let data = Data(base64Encoded: base64String)!
handler(.success(data))
}
}
/// Represents an image data provider for a raw data object.
public struct RawImageDataProvider: ImageDataProvider {
// MARK: Public Properties
/// The raw data object to provide to Kingfisher image loader.
public let data: Data
// MARK: Initializers
/// Creates an image data provider by the given raw `data` value and a `cacheKey` be used in Kingfisher cache.
///
/// - Parameters:
/// - data: The raw data reprensents an image.
/// - cacheKey: The key is used for caching the image data. You need a different key for any different image.
public init(data: Data, cacheKey: String) {
self.data = data
self.cacheKey = cacheKey
}
// MARK: Protocol Conforming
/// The key used in cache.
public var cacheKey: String
public func data(handler: @escaping (Result<Data, Error>) -> Void) {
handler(.success(data))
}
}
|
lgpl-3.0
|
fda8ab997c92b1a22fffde2dfccd2a62
| 36.09375 | 115 | 0.676832 | 4.492808 | false | false | false | false |
onekiloparsec/KPCTabsControl
|
KPCTabsControl/Constants.swift
|
2
|
2314
|
//
// Constants.swift
// KPCTabsControl
//
// Created by Cédric Foellmi on 15/07/16.
// Licensed under the MIT License (see LICENSE file)
//
import Foundation
/// The name of the notification upon the selection of a new tab.
public let TabsControlSelectionDidChangeNotification = "TabsControlSelectionDidChangeNotification"
/**
The position of a tab button inside the control. Used in the Style.
- first: The most left-hand tab button.
- middle: Any middle tab button between first and last.
- last: The most right-hand tab button
*/
public enum TabPosition {
case first
case middle
case last
/**
Convenience function to get TabPosition from a given index compared to a given total count.
- parameter idx: The index for which one wants the position
- parameter totalCount: The total count of tabs
- returns: The tab position
*/
static func fromIndex(_ idx: Int, totalCount: Int) -> TabPosition {
switch idx {
case 0: return .first
case totalCount-1: return .last
default: return .middle
}
}
}
/**
The tab width modes.
- Full: The tab widths will be equally distributed accross the tabs control width.
- Flexible: The tab widths will be adjusted between min and max, depending on the tabs control width.
*/
public enum TabWidth {
case full
case flexible(min: CGFloat, max: CGFloat)
}
/**
The tab selection state.
- Normal: The tab is not selected.
- Selected: The tab is selected.
- Unselectable: The tab is not selectable.
*/
public enum TabSelectionState {
case normal
case selected
case unselectable
}
/**
* Border mask option set, used in tab buttons and the tabs control itself.
*/
public struct BorderMask: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static func all() -> BorderMask {
return BorderMask.top.union(BorderMask.left).union(BorderMask.right).union(BorderMask.bottom)
}
public static let top = BorderMask(rawValue: 1 << 0)
public static let left = BorderMask(rawValue: 1 << 1)
public static let right = BorderMask(rawValue: 1 << 2)
public static let bottom = BorderMask(rawValue: 1 << 3)
}
|
mit
|
579f94895ffef2a01d277956439cbc8f
| 25.895349 | 102 | 0.674016 | 4.307263 | false | false | false | false |
banxi1988/Staff
|
Pods/BXForm/Pod/Classes/Cells/SwitchCell.swift
|
1
|
1385
|
//
// SwitchCell.swift
// Pods
//
// Created by Haizhen Lee on 15/12/24.
//
//
import UIKit
import PinAutoLayout
import BXModel
// -SwitchCell:tc
// toggle[x,r15]:sw
public class SwitchCell : StaticTableViewCell,BXBindable{
public let toggleSwitch = UISwitch(frame:CGRectZero)
public convenience init() {
self.init(style: .Default, reuseIdentifier: "SwitchCellCell")
}
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
public func bind(item:Bool){
toggleSwitch.on = item
contentView.bringSubviewToFront(toggleSwitch)
}
public override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
var allOutlets :[UIView]{
return [toggleSwitch]
}
var allUISwitchOutlets :[UISwitch]{
return [toggleSwitch]
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func commonInit(){
staticHeight = 44
for childView in allOutlets{
contentView.addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
}
func installConstaints(){
toggleSwitch.pinCenterY()
toggleSwitch.pinTrailing(15)
}
func setupAttrs(){
backgroundColor = .whiteColor()
}
}
|
mit
|
5a1b68e596d00f2d20de3ab48621ec91
| 19.367647 | 79 | 0.688809 | 4.526144 | false | false | false | false |
josve05a/wikipedia-ios
|
Wikipedia/Code/DiffListContextViewModel.swift
|
2
|
11022
|
import Foundation
final class DiffListContextItemViewModel {
private let text: String
private let semanticContentAttribute: UISemanticContentAttribute
var theme: Theme {
didSet {
self.textAttributedString = DiffListContextItemViewModel.calculateAttributedString(with: text, semanticContentAttribute: semanticContentAttribute, theme: theme, contextFont: contextFont)
}
}
var contextFont: UIFont {
didSet {
self.textAttributedString = DiffListContextItemViewModel.calculateAttributedString(with: text, semanticContentAttribute: semanticContentAttribute, theme: theme, contextFont: contextFont)
}
}
private(set) var textAttributedString: NSAttributedString
init(text: String, semanticContentAttribute: UISemanticContentAttribute, theme: Theme, contextFont: UIFont) {
self.text = text
self.semanticContentAttribute = semanticContentAttribute
self.theme = theme
self.contextFont = contextFont
self.textAttributedString = DiffListContextItemViewModel.calculateAttributedString(with: text, semanticContentAttribute: semanticContentAttribute, theme: theme, contextFont: contextFont)
}
private static func calculateAttributedString(with text: String, semanticContentAttribute: UISemanticContentAttribute, theme: Theme, contextFont: UIFont) -> NSAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
let lineSpacing: CGFloat = 4
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineHeightMultiple = contextFont.lineHeightMultipleToMatch(lineSpacing: lineSpacing)
switch semanticContentAttribute {
case .forceRightToLeft:
paragraphStyle.alignment = .right
default:
paragraphStyle.alignment = .left
}
let attributes = [NSAttributedString.Key.font: contextFont,
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.foregroundColor: theme.colors.primaryText]
return NSAttributedString(string: text, attributes: attributes)
}
}
extension DiffListContextItemViewModel: Equatable {
static func == (lhs: DiffListContextItemViewModel, rhs: DiffListContextItemViewModel) -> Bool {
return lhs.text == rhs.text
}
}
final class DiffListContextViewModel: DiffListGroupViewModel {
let heading: String
var isExpanded: Bool
let items: [DiffListContextItemViewModel?]
var theme: Theme {
didSet {
for item in items {
item?.theme = theme
}
}
}
var expandButtonTitle: String {
return isExpanded ? WMFLocalizedString("diff-context-lines-expanded-button-title", value:"Hide", comment:"Expand button title in diff compare context section when section is in expanded state.") : WMFLocalizedString("diff-context-lines-collapsed-button-title", value:"Show", comment:"Expand button title in diff compare context section when section is in collapsed state.")
}
private(set) var contextFont: UIFont {
didSet {
for item in items {
item?.contextFont = contextFont
}
}
}
private(set) var headingFont: UIFont
private var _width: CGFloat
var width: CGFloat {
get {
return _width
}
set {
_width = newValue
expandedHeight = DiffListContextViewModel.calculateExpandedHeight(items: items, heading: heading, availableWidth: availableWidth, innerPadding: innerPadding, contextItemPadding: DiffListContextViewModel.contextItemTextPadding, contextFont: contextFont, headingFont: headingFont, emptyContextLineHeight: emptyContextLineHeight)
height = DiffListContextViewModel.calculateCollapsedHeight(items: items, heading: heading, availableWidth: availableWidth, innerPadding: innerPadding, contextItemPadding: DiffListContextViewModel.contextItemTextPadding, contextFont: contextFont, headingFont: headingFont)
}
}
var traitCollection: UITraitCollection {
didSet {
innerPadding = DiffListContextViewModel.calculateInnerPadding(traitCollection: traitCollection)
contextFont = UIFont.wmf_font(contextDynamicTextStyle, compatibleWithTraitCollection: traitCollection)
headingFont = UIFont.wmf_font(.boldFootnote, compatibleWithTraitCollection: traitCollection)
}
}
private let contextDynamicTextStyle = DynamicTextStyle.subheadline
private(set) var height: CGFloat = 0
private(set) var expandedHeight: CGFloat = 0
private(set) var innerPadding: NSDirectionalEdgeInsets
static let contextItemTextPadding = NSDirectionalEdgeInsets(top: 3, leading: 8, bottom: 8, trailing: 8)
static let contextItemStackSpacing: CGFloat = 5
static let containerStackSpacing: CGFloat = 15
private var availableWidth: CGFloat {
return width - innerPadding.leading - innerPadding.trailing - DiffListContextViewModel.contextItemTextPadding.leading - DiffListContextViewModel.contextItemTextPadding.trailing
}
var emptyContextLineHeight: CGFloat {
return contextFont.pointSize * 1.8
}
init(diffItems: [TransformDiffItem], isExpanded: Bool, theme: Theme, width: CGFloat, traitCollection: UITraitCollection, semanticContentAttribute: UISemanticContentAttribute) {
self.isExpanded = isExpanded
self.theme = theme
self._width = width
self.traitCollection = traitCollection
if let firstItemLineNumber = diffItems.first?.lineNumber,
let lastItemLineNumber = diffItems.last?.lineNumber {
if diffItems.count == 1 {
self.heading = String.localizedStringWithFormat(CommonStrings.diffSingleLineFormat, firstItemLineNumber)
} else {
self.heading = String.localizedStringWithFormat(CommonStrings.diffMultiLineFormat, firstItemLineNumber, lastItemLineNumber)
}
} else {
self.heading = "" //tonitodo: optional would be better
}
let contextFont = UIFont.wmf_font(contextDynamicTextStyle, compatibleWithTraitCollection: traitCollection)
self.items = diffItems.map({ (item) -> DiffListContextItemViewModel? in
if item.text.isEmpty {
return nil
}
return DiffListContextItemViewModel(text: item.text, semanticContentAttribute: semanticContentAttribute, theme: theme, contextFont: contextFont)
})
self.contextFont = contextFont
self.headingFont = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection)
innerPadding = DiffListContextViewModel.calculateInnerPadding(traitCollection: traitCollection)
expandedHeight = DiffListContextViewModel.calculateExpandedHeight(items: items, heading: heading, availableWidth: availableWidth, innerPadding: innerPadding, contextItemPadding: DiffListContextViewModel.contextItemTextPadding, contextFont: contextFont, headingFont: headingFont, emptyContextLineHeight: emptyContextLineHeight)
height = DiffListContextViewModel.calculateCollapsedHeight(items: items, heading: heading, availableWidth: availableWidth, innerPadding: innerPadding, contextItemPadding: DiffListContextViewModel.contextItemTextPadding, contextFont: contextFont, headingFont: headingFont)
}
private static func calculateInnerPadding(traitCollection: UITraitCollection) -> NSDirectionalEdgeInsets {
switch (traitCollection.horizontalSizeClass, traitCollection.verticalSizeClass) {
case (.regular, .regular):
return NSDirectionalEdgeInsets(top: 0, leading: 50, bottom: 0, trailing: 50)
default:
return NSDirectionalEdgeInsets(top: 0, leading: 15, bottom: 0, trailing: 15)
}
}
private static func calculateExpandedHeight(items: [DiffListContextItemViewModel?], heading: String, availableWidth: CGFloat, innerPadding: NSDirectionalEdgeInsets, contextItemPadding: NSDirectionalEdgeInsets, contextFont: UIFont, headingFont: UIFont, emptyContextLineHeight: CGFloat) -> CGFloat {
var height: CGFloat = 0
height = calculateCollapsedHeight(items: items, heading: heading, availableWidth: availableWidth, innerPadding: innerPadding, contextItemPadding: contextItemPadding, contextFont: contextFont, headingFont: headingFont)
for (index, item) in items.enumerated() {
height += contextItemPadding.top
let itemTextHeight: CGFloat
if let item = item {
itemTextHeight = ceil(item.textAttributedString.boundingRect(with: CGSize(width: availableWidth, height: CGFloat.infinity), options: [.usesLineFragmentOrigin], context: nil).height)
} else {
itemTextHeight = emptyContextLineHeight
}
height += itemTextHeight
height += contextItemPadding.bottom
if index < (items.count - 1) {
height += DiffListContextViewModel.contextItemStackSpacing
}
}
height += DiffListContextViewModel.containerStackSpacing
return height
}
private static func calculateCollapsedHeight(items: [DiffListContextItemViewModel?], heading: String, availableWidth: CGFloat, innerPadding: NSDirectionalEdgeInsets, contextItemPadding: NSDirectionalEdgeInsets, contextFont: UIFont, headingFont: UIFont) -> CGFloat {
var height: CGFloat = 0
//add heading height
height += innerPadding.top
let attributedString = NSAttributedString(string: heading, attributes: [NSAttributedString.Key.font: headingFont])
height += ceil(attributedString.boundingRect(with: CGSize(width: availableWidth, height: CGFloat.infinity), options: [.usesLineFragmentOrigin], context: nil).height)
height += innerPadding.bottom
return height
}
func updateSize(width: CGFloat, traitCollection: UITraitCollection) {
_width = width
self.traitCollection = traitCollection
expandedHeight = DiffListContextViewModel.calculateExpandedHeight(items: items, heading: heading, availableWidth: availableWidth, innerPadding: innerPadding, contextItemPadding: DiffListContextViewModel.contextItemTextPadding, contextFont: contextFont, headingFont: headingFont, emptyContextLineHeight: emptyContextLineHeight)
height = DiffListContextViewModel.calculateCollapsedHeight(items: items, heading: heading, availableWidth: availableWidth, innerPadding: innerPadding, contextItemPadding: DiffListContextViewModel.contextItemTextPadding, contextFont: contextFont, headingFont: headingFont)
}
}
|
mit
|
5467168be1f279efcaa3db6a516119df
| 50.746479 | 381 | 0.710125 | 5.687307 | false | false | false | false |
maheenkhalid/MKGradients
|
Pod/Classes/MKGradients.swift
|
1
|
777
|
//
// MKGradients.swift
// Pods
//
// Created by Maheen Khalid on 4/1/16.
//
//
import UIKit
class MKGradients {
class func addGradientLayerAlongXAxis(view: UIView, colors:[CGColor]) {
let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = colors
gradient.startPoint = CGPointMake(0, 0.5)
gradient.endPoint = CGPointMake(1.0, 0.5)
view.layer.insertSublayer(gradient, atIndex: 0)
}
class func addGradientLayerAlongYAxis(view: UIView, colors:[CGColor]) {
let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = colors
view.layer.insertSublayer(gradient, atIndex: 0)
}
}
|
mit
|
b7f15608af0896a65001220c71f67d43
| 22.545455 | 75 | 0.603604 | 4.316667 | false | false | false | false |
iOSCowboy/realm-cocoa
|
RealmSwift-swift2.0/Object.swift
|
1
|
9873
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// 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 Realm
import Realm.Private
/**
In Realm you define your model classes by subclassing `Object` and adding properties to be persisted.
You then instantiate and use your custom subclasses instead of using the Object class directly.
```swift
class Dog: Object {
dynamic var name: String = ""
dynamic var adopted: Bool = false
let siblings = List<Dog>
}
```
### Supported property types
- `String`
- `Int`
- `Float`
- `Double`
- `Bool`
- `NSDate`
- `NSData`
- `Object` subclasses for to-one relationships
- `List<T: Object>` for to-many relationships
### Querying
You can gets `Results` of an Object subclass via tha `objects(_:)` free function or
the `objects(_:)` instance method on `Realm`.
### Relationships
See our [Cocoa guide](http://realm.io/docs/cocoa) for more details.
*/
public class Object: RLMObjectBase {
// MARK: Initializers
/**
Initialize a standalone (unpersisted) Object.
Call `add(_:)` on a `Realm` to add standalone objects to a realm.
- see: Realm().add(_:)
*/
public required override init() {
super.init()
}
/**
Initialize a standalone (unpersisted) `Object` with values from an `Array<AnyObject>` or `Dictionary<String, AnyObject>`.
Call `add(_:)` on a `Realm` to add standalone objects to a realm.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON object such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
*/
public init(value: AnyObject) {
super.init(value: value, schema: RLMSchema.sharedSchema())
}
// MARK: Properties
/// The `Realm` this object belongs to, or `nil` if the object
/// does not belong to a realm (the object is standalone).
public var realm: Realm? {
if let rlmReam = RLMObjectBaseRealm(self) {
return Realm(rlmReam)
}
return nil
}
/// The `ObjectSchema` which lists the persisted properties for this object.
public var objectSchema: ObjectSchema {
return ObjectSchema(RLMObjectBaseObjectSchema(self))
}
/// Indicates if an object can no longer be accessed.
public override var invalidated: Bool { return super.invalidated }
/// Returns a human-readable description of this object.
public override var description: String { return super.description }
#if os(OSX)
/// Helper to return the class name for an Object subclass.
public final override var className: String { return "" }
#else
/// Helper to return the class name for an Object subclass.
public final var className: String { return "" }
#endif
// MARK: Object Customization
/**
Override to designate a property as the primary key for an `Object` subclass. Only properties of
type String and Int can be designated as the primary key. Primary key
properties enforce uniqueness for each value whenever the property is set which incurs some overhead.
Indexes are created automatically for primary key properties.
- returns: Name of the property designated as the primary key, or `nil` if the model has no primary key.
*/
public class func primaryKey() -> String? { return nil }
/**
Override to return an array of property names to ignore. These properties will not be persisted
and are treated as transient.
- returns: `Array` of property names to ignore.
*/
public class func ignoredProperties() -> [String] { return [] }
/**
Return an array of property names for properties which should be indexed. Only supported
for string and int properties.
- returns: `Array` of property names to index.
*/
public class func indexedProperties() -> [String] { return [] }
// MARK: Inverse Relationships
/**
Get an `Array` of objects of type `className` which have this object as the given property value. This can
be used to get the inverse relationship value for `Object` and `List` properties.
- parameter className: The type of object on which the relationship to query is defined.
- parameter property: The name of the property which defines the relationship.
- returns: An `Array` of objects of type `className` which have this object as their value for the `propertyName` property.
*/
public func linkingObjects<T: Object>(type: T.Type, forProperty propertyName: String) -> [T] {
// FIXME: use T.className()
return RLMObjectBaseLinkingObjectsOfClass(self, (T.self as Object.Type).className(), propertyName) as! [T]
}
// MARK: Key-Value Coding & Subscripting
/// Returns or sets the value of the property with the given name.
public subscript(key: String) -> AnyObject? {
get {
if realm == nil {
return self.valueForKey(key)
}
let property = RLMValidatedGetProperty(self, key)
if property.type == .Array {
return self.listForProperty(property)
}
return RLMDynamicGet(self, property)
}
set(value) {
if realm == nil {
self.setValue(value, forKey: key)
}
else {
RLMDynamicValidatedSet(self, key, value)
}
}
}
// MARK: Equatable
/// Returns whether both objects are equal.
/// Objects are considered equal when they are both from the same Realm
/// and point to the same underlying object in the database.
public override func isEqual(object: AnyObject?) -> Bool {
return RLMObjectBaseAreEqual(self as RLMObjectBase?, object as? RLMObjectBase);
}
// MARK: Private functions
// FIXME: None of these functions should be exposed in the public interface.
/**
WARNING: This is an internal initializer not intended for public use.
:nodoc:
*/
public override init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
/**
WARNING: This is an internal initializer not intended for public use.
:nodoc:
*/
public override init(value: AnyObject, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
// Helper for getting the list object for a property
internal func listForProperty(prop: RLMProperty) -> RLMListBase {
return object_getIvar(self, prop.swiftListIvar) as! RLMListBase
}
}
/// Object interface which allows untyped getters and setters for Objects.
public final class DynamicObject : Object {
private var listProperties = [String: List<DynamicObject>]()
// Override to create List<DynamicObject> on access
internal override func listForProperty(prop: RLMProperty) -> RLMListBase {
if let list = listProperties[prop.name] {
return list
}
let list = List<DynamicObject>()
listProperties[prop.name] = list
return list
}
/// :nodoc:
public override func valueForUndefinedKey(key: String) -> AnyObject? {
return self[key]
}
/// :nodoc:
public override func setValue(value: AnyObject?, forUndefinedKey key: String) {
self[key] = value
}
@objc private class func shouldPersistToRealm() -> Bool {
return false;
}
}
/// :nodoc:
/// Internal class. Do not use directly.
public class ObjectUtil: NSObject {
@objc private class func ignoredPropertiesForClass(type: AnyClass) -> NSArray? {
if let type = type as? Object.Type {
return type.ignoredProperties() as NSArray?
}
return nil
}
@objc private class func indexedPropertiesForClass(type: AnyClass) -> NSArray? {
if let type = type as? Object.Type {
return type.indexedProperties() as NSArray?
}
return nil
}
// Get the names of all properties in the object which are of type List<>.
@objc private class func getGenericListPropertyNames(object: AnyObject) -> NSArray {
return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) in
return prop.value.dynamicType is RLMListBase.Type
}.flatMap { (prop: Mirror.Child) in
return prop.label
}
}
@objc private class func initializeListProperty(object: RLMObjectBase, property: RLMProperty, array: RLMArray) {
(object as! Object).listForProperty(property)._rlmArray = array
}
@objc private class func getOptionalPropertyNames(object: AnyObject) -> NSArray {
return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) in
return Mirror(reflecting: prop.value).displayStyle == .Optional
}.flatMap { (prop: Mirror.Child) in
return prop.label
}
}
@objc private class func requiredPropertiesForClass(_: AnyClass) -> NSArray? {
return nil
}
}
|
apache-2.0
|
8d50af610d7ffd24a047258ac75c7058
| 33.044828 | 127 | 0.651372 | 4.717152 | false | false | false | false |
willer88/Rappi-Catalog
|
RappiCatalog/Pods/RealmSwift/RealmSwift/RealmCollectionType.swift
|
1
|
36061
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// 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 Realm
/**
Encapsulates iteration state and interface for iteration over a
`RealmCollectionType`.
*/
public final class RLMGenerator<T: Object>: GeneratorType {
private let generatorBase: NSFastGenerator
internal init(collection: RLMCollection) {
generatorBase = NSFastGenerator(collection)
}
/// Advance to the next element and return it, or `nil` if no next element exists.
public func next() -> T? { // swiftlint:disable:this valid_docs
let accessor = generatorBase.next() as! T?
if let accessor = accessor {
RLMInitializeSwiftAccessorGenerics(accessor)
}
return accessor
}
}
/**
RealmCollectionChange is passed to the notification blocks for Realm
collections, and reports the current state of the collection and what changes
were made to the collection since the last time the notification was called.
The arrays of indices in the .Update case follow UITableView's batching
conventions, and can be passed as-is to a table view's batch update functions
after converting to index paths in the appropriate section. For example, for a
simple one-section table view, you can do the following:
self.notificationToken = results.addNotificationBlock { changes
switch changes {
case .Initial:
// Results are now populated and can be accessed without blocking the UI
self.tableView.reloadData()
break
case .Update(_, let deletions, let insertions, let modifications):
// Query results have changed, so apply them to the TableView
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
self.tableView.endUpdates()
break
case .Error(let err):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(err)")
break
}
}
*/
public enum RealmCollectionChange<T> {
/// The initial run of the query has completed (if applicable), and the
/// collection can now be used without performing any blocking work.
case Initial(T)
/// A write transaction has been committed which either changed which objects
/// are in the collection and/or modified one or more of the objects in the
/// collection.
///
/// All three of the change arrays are always sorted in ascending order.
///
/// - parameter deletions: The indices in the previous version of the collection
/// which were removed from this one.
/// - parameter insertions: The indices in the new collection which were added in
/// this version.
/// - parameter modifications: The indices of the objects in the new collection which
/// were modified in this version.
case Update(T, deletions: [Int], insertions: [Int], modifications: [Int])
/// If an error occurs, notification blocks are called one time with a
/// .Error result and an NSError with details. Currently the only thing
/// that can fail is opening the Realm on a background worker thread to
/// calculate the change set.
case Error(NSError)
static func fromObjc(value: T, change: RLMCollectionChange?, error: NSError?) -> RealmCollectionChange {
if let error = error {
return .Error(error)
}
if let change = change {
return .Update(value,
deletions: change.deletions as! [Int],
insertions: change.insertions as! [Int],
modifications: change.modifications as! [Int])
}
return .Initial(value)
}
}
/**
A homogenous collection of `Object`s which can be retrieved, filtered, sorted,
and operated upon.
*/
public protocol RealmCollectionType: CollectionType, CustomStringConvertible {
/// Element type contained in this collection.
associatedtype Element: Object
// MARK: Properties
/// The Realm the objects in this collection belong to, or `nil` if the
/// collection's owning object does not belong to a realm (the collection is
/// standalone).
var realm: Realm? { get }
/// Indicates if the collection can no longer be accessed.
///
/// The collection can no longer be accessed if `invalidate` is called on the containing `Realm`.
var invalidated: Bool { get }
/// Returns the number of objects in this collection.
var count: Int { get }
/// Returns a human-readable description of the objects contained in this collection.
var description: String { get }
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the collection.
- parameter object: The object whose index is being queried.
- returns: The index of the given object, or `nil` if the object is not in the collection.
*/
func indexOf(object: Element) -> Int?
/**
Returns the index of the first object matching the given predicate,
or `nil` no objects match.
- parameter predicate: The `NSPredicate` used to filter the objects.
- returns: The index of the first matching object, or `nil` if no objects match.
*/
func indexOf(predicate: NSPredicate) -> Int?
/**
Returns the index of the first object matching the given predicate,
or `nil` if no objects match.
- parameter predicateFormat: The predicate format string, optionally followed by a variable number
of arguments.
- returns: The index of the first matching object, or `nil` if no objects match.
*/
func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int?
// MARK: Filtering
/**
Returns `Results` containing collection elements that match the given predicate.
- parameter predicateFormat: The predicate format string which can accept variable arguments.
- returns: `Results` containing collection elements that match the given predicate.
*/
func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element>
/**
Returns `Results` containing collection elements that match the given predicate.
- parameter predicate: The predicate to filter the objects.
- returns: `Results` containing collection elements that match the given predicate.
*/
func filter(predicate: NSPredicate) -> Results<Element>
// MARK: Sorting
/**
Returns `Results` containing collection elements sorted by the given property.
- parameter property: The property name to sort by.
- parameter ascending: The direction to sort by.
- returns: `Results` containing collection elements sorted by the given property.
*/
func sorted(property: String, ascending: Bool) -> Results<Element>
/**
Returns `Results` with elements sorted by the given sort descriptors.
- parameter sortDescriptors: `SortDescriptor`s to sort by.
- returns: `Results` with elements sorted by the given sort descriptors.
*/
func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element>
// MARK: Aggregate Operations
/**
Returns the minimum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on.
- returns: The minimum value for the property amongst objects in the collection, or `nil` if the
collection is empty.
*/
func min<U: MinMaxType>(property: String) -> U?
/**
Returns the maximum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on.
- returns: The maximum value for the property amongst objects in the collection, or `nil` if the
collection is empty.
*/
func max<U: MinMaxType>(property: String) -> U?
/**
Returns the sum of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
- returns: The sum of the given property over all objects in the collection.
*/
func sum<U: AddableType>(property: String) -> U
/**
Returns the average of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate average on.
- returns: The average of the given property over all objects in the collection, or `nil` if the
collection is empty.
*/
func average<U: AddableType>(property: String) -> U?
// MARK: Key-Value Coding
/**
Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects.
- parameter key: The name of the property.
- returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects.
*/
func valueForKey(key: String) -> AnyObject?
/**
Returns an Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the
collection's objects.
- parameter keyPath: The key path to the property.
- returns: Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the
collection's objects.
*/
func valueForKeyPath(keyPath: String) -> AnyObject?
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key.
- warning: This method can only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property.
*/
func setValue(value: AnyObject?, forKey key: String)
// MARK: Notifications
/**
Register a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then
called again after each write transaction which changes either any of the
objects in the collection, or which objects are in the collection.
At the time when the block is called, the collection object will be fully
evaluated and up-to-date, and as long as you do not perform a write
transaction on the same thread or explicitly call realm.refresh(),
accessing it will never perform blocking work.
Notifications are delivered via the standard run loop, and so can't be
delivered while the run loop is blocked by other activity. When
notifications can't be delivered instantly, multiple notifications may be
coalesced into a single notification. This can include the notification
with the initial collection. For example, the following code performs a write
transaction immediately after adding the notification block, so there is no
opportunity for the initial notification to be delivered first. As a
result, the initial notification will reflect the state of the Realm after
the write transaction.
let results = realm.objects(Dog)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.addNotificationBlock { (changes: RealmCollectionChange) in
switch changes {
case .Initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .Update:
// Will not be hit in this example
break
case .Error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
You must retain the returned token for as long as you want updates to continue
to be sent to the block. To stop receiving updates, call stop() on the token.
- warning: This method cannot be called during a write transaction, or when
the source realm is read-only.
- parameter block: The block to be called with the evaluated collection and change information.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
func addNotificationBlock(block: (RealmCollectionChange<Self>) -> Void) -> NotificationToken
/// :nodoc:
func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken
}
private class _AnyRealmCollectionBase<T: Object> {
typealias Wrapper = AnyRealmCollection<Element>
typealias Element = T
var realm: Realm? { fatalError() }
var invalidated: Bool { fatalError() }
var count: Int { fatalError() }
var description: String { fatalError() }
func indexOf(object: Element) -> Int? { fatalError() }
func indexOf(predicate: NSPredicate) -> Int? { fatalError() }
func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() }
func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> { fatalError() }
func filter(predicate: NSPredicate) -> Results<Element> { fatalError() }
func sorted(property: String, ascending: Bool) -> Results<Element> { fatalError() }
func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> {
fatalError()
}
func min<U: MinMaxType>(property: String) -> U? { fatalError() }
func max<U: MinMaxType>(property: String) -> U? { fatalError() }
func sum<U: AddableType>(property: String) -> U { fatalError() }
func average<U: AddableType>(property: String) -> U? { fatalError() }
subscript(index: Int) -> Element { fatalError() }
func generate() -> RLMGenerator<T> { fatalError() }
var startIndex: Int { fatalError() }
var endIndex: Int { fatalError() }
func valueForKey(key: String) -> AnyObject? { fatalError() }
func valueForKeyPath(keyPath: String) -> AnyObject? { fatalError() }
func setValue(value: AnyObject?, forKey key: String) { fatalError() }
func _addNotificationBlock(block: (RealmCollectionChange<Wrapper>) -> Void)
-> NotificationToken { fatalError() }
}
private final class _AnyRealmCollection<C: RealmCollectionType>: _AnyRealmCollectionBase<C.Element> {
let base: C
init(base: C) {
self.base = base
}
// MARK: Properties
/// The Realm the objects in this collection belong to, or `nil` if the
/// collection's owning object does not belong to a realm (the collection is
/// standalone).
override var realm: Realm? { return base.realm }
/// Indicates if the collection can no longer be accessed.
///
/// The collection can no longer be accessed if `invalidate` is called on the containing `Realm`.
override var invalidated: Bool { return base.invalidated }
/// Returns the number of objects in this collection.
override var count: Int { return base.count }
/// Returns a human-readable description of the objects contained in this collection.
override var description: String { return base.description }
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the collection.
- parameter object: The object whose index is being queried.
- returns: The index of the given object, or `nil` if the object is not in the collection.
*/
override func indexOf(object: C.Element) -> Int? { return base.indexOf(object) }
/**
Returns the index of the first object matching the given predicate,
or `nil` no objects match.
- parameter predicate: The `NSPredicate` used to filter the objects.
- returns: The index of the first matching object, or `nil` if no objects match.
*/
override func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) }
/**
Returns the index of the first object matching the given predicate,
or `nil` if no objects match.
- parameter predicateFormat: The predicate format string, optionally followed by a variable number
of arguments.
- returns: The index of the first matching object, or `nil` if no objects match.
*/
override func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? {
return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args))
}
// MARK: Filtering
/**
Returns `Results` containing collection elements that match the given predicate.
- parameter predicateFormat: The predicate format string which can accept variable arguments.
- returns: `Results` containing collection elements that match the given predicate.
*/
override func filter(predicateFormat: String, _ args: AnyObject...) -> Results<C.Element> {
return base.filter(NSPredicate(format: predicateFormat, argumentArray: args))
}
/**
Returns `Results` containing collection elements that match the given predicate.
- parameter predicate: The predicate to filter the objects.
- returns: `Results` containing collection elements that match the given predicate.
*/
override func filter(predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) }
// MARK: Sorting
/**
Returns `Results` containing collection elements sorted by the given property.
- parameter property: The property name to sort by.
- parameter ascending: The direction to sort by.
- returns: `Results` containing collection elements sorted by the given property.
*/
override func sorted(property: String, ascending: Bool) -> Results<C.Element> {
return base.sorted(property, ascending: ascending)
}
/**
Returns `Results` with elements sorted by the given sort descriptors.
- parameter sortDescriptors: `SortDescriptor`s to sort by.
- returns: `Results` with elements sorted by the given sort descriptors.
*/
override func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>
(sortDescriptors: S) -> Results<C.Element> {
return base.sorted(sortDescriptors)
}
// MARK: Aggregate Operations
/**
Returns the minimum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on.
- returns: The minimum value for the property amongst objects in the collection, or `nil` if the
collection is empty.
*/
override func min<U: MinMaxType>(property: String) -> U? { return base.min(property) }
/**
Returns the maximum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on.
- returns: The maximum value for the property amongst objects in the collection, or `nil` if the
collection is empty.
*/
override func max<U: MinMaxType>(property: String) -> U? { return base.max(property) }
/**
Returns the sum of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
- returns: The sum of the given property over all objects in the collection.
*/
override func sum<U: AddableType>(property: String) -> U { return base.sum(property) }
/**
Returns the average of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate average on.
- returns: The average of the given property over all objects in the collection, or `nil` if the
collection is empty.
*/
override func average<U: AddableType>(property: String) -> U? { return base.average(property) }
// MARK: Sequence Support
/**
Returns the object at the given `index`.
- parameter index: The index.
- returns: The object at the given `index`.
*/
override subscript(index: Int) -> C.Element {
// FIXME: it should be possible to avoid this force-casting
return unsafeBitCast(base[index as! C.Index], C.Element.self)
}
/// Returns a `GeneratorOf<Element>` that yields successive elements in the collection.
override func generate() -> RLMGenerator<Element> {
// FIXME: it should be possible to avoid this force-casting
return base.generate() as! RLMGenerator<Element>
}
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
override var startIndex: Int {
// FIXME: it should be possible to avoid this force-casting
return base.startIndex as! Int
}
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
override var endIndex: Int {
// FIXME: it should be possible to avoid this force-casting
return base.endIndex as! Int
}
// MARK: Key-Value Coding
/**
Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects.
- parameter key: The name of the property.
- returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects.
*/
override func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) }
/**
Returns an Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the
collection's objects.
- parameter keyPath: The key path to the property.
- returns: Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the
collection's objects.
*/
override func valueForKeyPath(keyPath: String) -> AnyObject? { return base.valueForKeyPath(keyPath) }
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key.
- warning: This method can only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property.
*/
override func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) }
// MARK: Notifications
/// :nodoc:
override func _addNotificationBlock(block: (RealmCollectionChange<Wrapper>) -> Void)
-> NotificationToken { return base._addNotificationBlock(block) }
}
/**
A type-erased `RealmCollectionType`.
Forwards operations to an arbitrary underlying collection having the same
Element type, hiding the specifics of the underlying `RealmCollectionType`.
*/
public final class AnyRealmCollection<T: Object>: RealmCollectionType {
/// Element type contained in this collection.
public typealias Element = T
private let base: _AnyRealmCollectionBase<T>
/// Creates an AnyRealmCollection wrapping `base`.
public init<C: RealmCollectionType where C.Element == T>(_ base: C) {
self.base = _AnyRealmCollection(base: base)
}
// MARK: Properties
/// The Realm the objects in this collection belong to, or `nil` if the
/// collection's owning object does not belong to a realm (the collection is
/// standalone).
public var realm: Realm? { return base.realm }
/// Indicates if the collection can no longer be accessed.
///
/// The collection can no longer be accessed if `invalidate` is called on the containing `Realm`.
public var invalidated: Bool { return base.invalidated }
/// Returns the number of objects in this collection.
public var count: Int { return base.count }
/// Returns a human-readable description of the objects contained in this collection.
public var description: String { return base.description }
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the collection.
- parameter object: The object whose index is being queried.
- returns: The index of the given object, or `nil` if the object is not in the collection.
*/
public func indexOf(object: Element) -> Int? { return base.indexOf(object) }
/**
Returns the index of the first object matching the given predicate,
or `nil` no objects match.
- parameter predicate: The `NSPredicate` used to filter the objects.
- returns: The index of the first matching object, or `nil` if no objects match.
*/
public func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) }
/**
Returns the index of the first object matching the given predicate,
or `nil` if no objects match.
- parameter predicateFormat: The predicate format string, optionally followed by a variable number
of arguments.
- returns: The index of the first matching object, or `nil` if no objects match.
*/
public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? {
return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args))
}
// MARK: Filtering
/**
Returns `Results` containing collection elements that match the given predicate.
- parameter predicateFormat: The predicate format string which can accept variable arguments.
- returns: `Results` containing collection elements that match the given predicate.
*/
public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> {
return base.filter(NSPredicate(format: predicateFormat, argumentArray: args))
}
/**
Returns `Results` containing collection elements that match the given predicate.
- parameter predicate: The predicate to filter the objects.
- returns: `Results` containing collection elements that match the given predicate.
*/
public func filter(predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) }
// MARK: Sorting
/**
Returns `Results` containing collection elements sorted by the given property.
- parameter property: The property name to sort by.
- parameter ascending: The direction to sort by.
- returns: `Results` containing collection elements sorted by the given property.
*/
public func sorted(property: String, ascending: Bool) -> Results<Element> {
return base.sorted(property, ascending: ascending)
}
/**
Returns `Results` with elements sorted by the given sort descriptors.
- parameter sortDescriptors: `SortDescriptor`s to sort by.
- returns: `Results` with elements sorted by the given sort descriptors.
*/
public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>
(sortDescriptors: S) -> Results<Element> {
return base.sorted(sortDescriptors)
}
// MARK: Aggregate Operations
/**
Returns the minimum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on.
- returns: The minimum value for the property amongst objects in the collection, or `nil` if the
collection is empty.
*/
public func min<U: MinMaxType>(property: String) -> U? { return base.min(property) }
/**
Returns the maximum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on.
- returns: The maximum value for the property amongst objects in the collection, or `nil` if the
collection is empty.
*/
public func max<U: MinMaxType>(property: String) -> U? { return base.max(property) }
/**
Returns the sum of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
- returns: The sum of the given property over all objects in the collection.
*/
public func sum<U: AddableType>(property: String) -> U { return base.sum(property) }
/**
Returns the average of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate average on.
- returns: The average of the given property over all objects in the collection, or `nil` if the
collection is empty.
*/
public func average<U: AddableType>(property: String) -> U? { return base.average(property) }
// MARK: Sequence Support
/**
Returns the object at the given `index`.
- parameter index: The index.
- returns: The object at the given `index`.
*/
public subscript(index: Int) -> T { return base[index] }
/// Returns a `GeneratorOf<T>` that yields successive elements in the collection.
public func generate() -> RLMGenerator<T> { return base.generate() }
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return base.startIndex }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return base.endIndex }
// MARK: Key-Value Coding
/**
Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects.
- parameter key: The name of the property.
- returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects.
*/
public func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) }
/**
Returns an Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the
collection's objects.
- parameter keyPath: The key path to the property.
- returns: Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the
collection's objects.
*/
public func valueForKeyPath(keyPath: String) -> AnyObject? { return base.valueForKeyPath(keyPath) }
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key.
- warning: This method can only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property.
*/
public func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) }
// MARK: Notifications
/**
Register a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then
called again after each write transaction which changes either any of the
objects in the collection, or which objects are in the collection.
At the time when the block is called, the collection object will be fully
evaluated and up-to-date, and as long as you do not perform a write
transaction on the same thread or explicitly call realm.refresh(),
accessing it will never perform blocking work.
Notifications are delivered via the standard run loop, and so can't be
delivered while the run loop is blocked by other activity. When
notifications can't be delivered instantly, multiple notifications may be
coalesced into a single notification. This can include the notification
with the initial collection. For example, the following code performs a write
transaction immediately after adding the notification block, so there is no
opportunity for the initial notification to be delivered first. As a
result, the initial notification will reflect the state of the Realm after
the write transaction.
let results = realm.objects(Dog)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.addNotificationBlock { (changes: RealmCollectionChange) in
switch changes {
case .Initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .Update:
// Will not be hit in this example
break
case .Error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
You must retain the returned token for as long as you want updates to continue
to be sent to the block. To stop receiving updates, call stop() on the token.
- warning: This method cannot be called during a write transaction, or when
the source realm is read-only.
- parameter block: The block to be called with the evaluated collection and change information.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection>) -> ())
-> NotificationToken { return base._addNotificationBlock(block) }
/// :nodoc:
public func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection>) -> ())
-> NotificationToken { return base._addNotificationBlock(block) }
}
|
mit
|
d3221703c3d7b4546493550058fcf6db
| 38.111714 | 120 | 0.678184 | 4.902257 | false | false | false | false |
nanthi1990/SwiftCharts
|
SwiftCharts/Layers/ChartPointsScatterLayer.swift
|
7
|
5476
|
//
// ChartPointsScatterLayer.swift
// Examples
//
// Created by ischuetz on 17/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class ChartPointsScatterLayer<T: ChartPoint>: ChartPointsLayer<T> {
let itemSize: CGSize
let itemFillColor: UIColor
required init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
self.itemSize = itemSize
self.itemFillColor = itemFillColor
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay)
}
override func chartViewDrawing(#context: CGContextRef, chart: Chart) {
for chartPointModel in self.chartPointsModels {
self.drawChartPointModel(context: context, chartPointModel: chartPointModel)
}
}
func drawChartPointModel(#context: CGContextRef, chartPointModel: ChartPointLayerModel<T>) {
fatalError("override")
}
}
public class ChartPointsScatterTrianglesLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override func drawChartPointModel(#context: CGContextRef, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, chartPointModel.screenLoc.x, chartPointModel.screenLoc.y - h / 2)
CGPathAddLineToPoint(path, nil, chartPointModel.screenLoc.x + w / 2, chartPointModel.screenLoc.y + h / 2)
CGPathAddLineToPoint(path, nil, chartPointModel.screenLoc.x - w / 2, chartPointModel.screenLoc.y + h / 2)
CGPathCloseSubpath(path)
CGContextSetFillColorWithColor(context, self.itemFillColor.CGColor)
CGContextAddPath(context, path)
CGContextFillPath(context)
}
}
public class ChartPointsScatterSquaresLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override func drawChartPointModel(#context: CGContextRef, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
CGContextSetFillColorWithColor(context, self.itemFillColor.CGColor)
CGContextFillRect(context, CGRectMake(chartPointModel.screenLoc.x - w / 2, chartPointModel.screenLoc.y - h / 2, w, h))
}
}
public class ChartPointsScatterCirclesLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override func drawChartPointModel(#context: CGContextRef, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
CGContextSetFillColorWithColor(context, self.itemFillColor.CGColor)
CGContextFillEllipseInRect(context, CGRectMake(chartPointModel.screenLoc.x - w / 2, chartPointModel.screenLoc.y - h / 2, w, h))
}
}
public class ChartPointsScatterCrossesLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
private let strokeWidth: CGFloat
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor, strokeWidth: CGFloat = 2) {
self.strokeWidth = strokeWidth
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override func drawChartPointModel(#context: CGContextRef, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
func drawLine(p1X: CGFloat, p1Y: CGFloat, p2X: CGFloat, p2Y: CGFloat) {
CGContextSetStrokeColorWithColor(context, self.itemFillColor.CGColor)
CGContextSetLineWidth(context, self.strokeWidth)
CGContextMoveToPoint(context, p1X, p1Y)
CGContextAddLineToPoint(context, p2X, p2Y)
CGContextStrokePath(context)
}
drawLine(chartPointModel.screenLoc.x - w / 2, chartPointModel.screenLoc.y - h / 2, chartPointModel.screenLoc.x + w / 2, chartPointModel.screenLoc.y + h / 2)
drawLine(chartPointModel.screenLoc.x + w / 2, chartPointModel.screenLoc.y - h / 2, chartPointModel.screenLoc.x - w / 2, chartPointModel.screenLoc.y + h / 2)
}
}
|
apache-2.0
|
3d06d3bd8ceccf1c90bb33622d9e20b4
| 49.238532 | 203 | 0.717129 | 4.656463 | false | false | false | false |
inaka/EventSource
|
EventSourceTests/EventSourceTests.swift
|
1
|
6459
|
//
// EventSourceTests.swift
// EventSourceTests
//
// Created by Andres on 22/08/2019.
// Copyright © 2019 Andres. All rights reserved.
//
import XCTest
@testable import EventSource
class EventSourceTests: XCTestCase {
var eventSource: EventSource!
let url = URL(string: "https://localhost")!
override func setUp() {
eventSource = EventSource(url: url, headers: ["header": "value"])
}
func testCreation() {
XCTAssertEqual(url, eventSource.url)
XCTAssertEqual(eventSource.headers, ["header": "value"])
XCTAssertEqual(eventSource.readyState, EventSourceState.closed)
}
func testDisconnect() {
XCTAssertEqual(eventSource.readyState, EventSourceState.closed)
}
func testSessionConfiguration() {
let configuration = eventSource.sessionConfiguration(lastEventId: "event-id")
XCTAssertEqual(configuration.timeoutIntervalForRequest, TimeInterval(INT_MAX))
XCTAssertEqual(configuration.timeoutIntervalForResource, TimeInterval(INT_MAX))
XCTAssertEqual(configuration.httpAdditionalHeaders as? [String: String], [
"Last-Event-Id": "event-id", "Accept": "text/event-stream", "Cache-Control": "no-cache", "header": "value"]
)
}
func testAddEventListener() {
eventSource.addEventListener("event-name") { _, _, _ in }
XCTAssertEqual(eventSource.events(), ["event-name"])
}
func testRemoveEventListener() {
eventSource.addEventListener("event-name") { _, _, _ in }
eventSource.removeEventListener("event-name")
XCTAssertEqual(eventSource.events(), [])
}
func testRetryTime() {
eventSource.connect()
eventSource.readyStateOpen()
let aSession = URLSession(configuration: URLSessionConfiguration.default)
let aSessionDataTask = URLSessionDataTask()
let event = """
id: event-id-1
data: event-data-first
retry: 1000
id: event
"""
let data = event.data(using: .utf8)!
eventSource.urlSession(aSession, dataTask: aSessionDataTask, didReceive: data)
XCTAssertEqual(eventSource.retryTime, 1000)
}
func testOnOpen() {
let expectation = XCTestExpectation(description: "onOpen gets called")
eventSource.onOpen {
XCTAssertEqual(self.eventSource.readyState, EventSourceState.open)
expectation.fulfill()
}
let aSession = URLSession(configuration: URLSessionConfiguration.default)
let aSessionDataTask = URLSessionDataTask()
let urlResponse = URLResponse(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil)
eventSource.urlSession(aSession, dataTask: aSessionDataTask, didReceive: urlResponse) { _ in }
wait(for: [expectation], timeout: 2.0)
}
func testOnCompleteRetryTrue() {
let expectation = XCTestExpectation(description: "onComplete gets called")
eventSource.onComplete { statusCode, retry, _ in
XCTAssertEqual(statusCode, 200)
XCTAssertEqual(retry, false)
expectation.fulfill()
}
let aSession = URLSession(configuration: URLSessionConfiguration.default)
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: [:])
let dataTask = URLSessionDataTaskMock(response: response)
eventSource.urlSession(aSession, task: dataTask, didCompleteWithError: nil)
wait(for: [expectation], timeout: 2.0)
}
func testOnCompleteRetryFalse() {
let expectation = XCTestExpectation(description: "onComplete gets called")
eventSource.onComplete { statusCode, retry, _ in
XCTAssertEqual(statusCode, 250)
XCTAssertEqual(retry, true)
expectation.fulfill()
}
let aSession = URLSession(configuration: URLSessionConfiguration.default)
let response = HTTPURLResponse(url: url, statusCode: 250, httpVersion: nil, headerFields: [:])
let dataTask = URLSessionDataTaskMock(response: response)
eventSource.urlSession(aSession, task: dataTask, didCompleteWithError: nil)
wait(for: [expectation], timeout: 2.0)
}
func testOnCompleteError() {
let expectation = XCTestExpectation(description: "onComplete gets called")
eventSource.onComplete { statusCode, retry, error in
XCTAssertNotNil(error)
XCTAssertNil(retry)
XCTAssertNil(statusCode)
expectation.fulfill()
}
let aSession = URLSession(configuration: URLSessionConfiguration.default)
let dataTask = URLSessionDataTaskMock(response: nil)
let error = NSError(domain: "", code: -1, userInfo: [:])
eventSource.urlSession(aSession, task: dataTask, didCompleteWithError: error)
wait(for: [expectation], timeout: 2.0)
}
func testSmallEventStream() {
eventSource.connect()
eventSource.readyStateOpen()
var eventsIds: [String] = []
var eventNames: [String] = []
var eventDatas: [String] = []
let exp = self.expectation(description: "onMessage gets called")
eventSource.onMessage { eventId, eventName, eventData in
eventsIds.append(eventId ?? "")
eventNames.append(eventName ?? "")
eventDatas.append(eventData ?? "")
if(eventsIds.count == 3) {
exp.fulfill()
}
}
let eventsString = """
id: event-id-1
data: event-data-first
id: event-id-2
data: event-data-second
id: event-id-3
data: event-data-third
"""
let aSession = URLSession(configuration: URLSessionConfiguration.default)
let aSessionDataTask = URLSessionDataTask()
let data = eventsString.data(using: .utf8)!
eventSource.urlSession(aSession, dataTask: aSessionDataTask, didReceive: data)
waitForExpectations(timeout: 2) { _ in
XCTAssertEqual(eventsIds, ["event-id-1", "event-id-2", "event-id-3"])
XCTAssertEqual(eventNames, ["message", "message", "message"])
XCTAssertEqual(eventsIds, ["event-id-1", "event-id-2", "event-id-3"])
}
}
func testDisconnet() {
eventSource.readyStateOpen()
eventSource.disconnect()
XCTAssertEqual(eventSource.readyState, .closed)
}
}
|
apache-2.0
|
fa30f47f8c9074f10cafdf0eb5eada3b
| 34.097826 | 119 | 0.646795 | 4.888721 | false | true | false | false |
br1sk/brisk-ios
|
Brisk iOS/Dupe/DupeViewController.swift
|
1
|
1512
|
import UIKit
import InterfaceBacked
protocol DupeViewDelegate: class {
func controllerDidCancel(_ controller: DupeViewController)
func controller(_ controller: DupeViewController, didSubmit number: String)
}
final class DupeViewController: UIViewController, StoryboardBacked, StatusDisplay {
// MARK: - Properties
@IBOutlet private weak var numberField: UITextField!
@IBOutlet private weak var hintLabel: UILabel!
var number: String = ""
weak var delegate: DupeViewDelegate?
// MARK: - UIViewController Methods
override func viewWillAppear(_ animated: Bool) {
if let content = UIPasteboard.general.string, content.isOpenRadar && number.isEmpty {
numberField.text = content.extractRadarNumber()
hintLabel.text = "Found \(content) on your clipboard"
} else {
hintLabel.text = "You can also post rdar:// or https://openradar.appspot.com/ links"
}
if number.isNotEmpty && number.isOpenRadar {
numberField.text = number
}
}
// MARK: - User Actions
@IBAction func submitTapped() {
// TODO: Show error if invalid
guard let text = numberField.text, text.isOpenRadar else { return }
let number = text.extractRadarNumber() ?? ""
delegate?.controller(self, didSubmit: number)
}
@IBAction func cancelTapped() {
delegate?.controllerDidCancel(self)
}
}
// MARK: - UITextFieldDelegate Methods
extension DupeViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
mit
|
99de36c89ed249278eabe6ec306dff89
| 24.627119 | 87 | 0.744048 | 4.01061 | false | false | false | false |
programersun/HiChongSwift
|
HiChongSwift/PetFinalFilterViewController.swift
|
1
|
6358
|
//
// PetFinalFilterViewController.swift
// HiChongSwift
//
// Created by eagle on 14/12/24.
// Copyright (c) 2014年 多思科技. All rights reserved.
//
import UIKit
class PetFinalFilterViewController: UITableViewController {
weak var delegate: PetCateFilterDelegate?
weak var root: UIViewController?
var parentID: String?
private var subTypeInfo: LCYPetSubTypeBase?
private var groupedTypeInfo: [String: [LCYPetSubTypeChildStyle]] = [String: [LCYPetSubTypeChildStyle]]()
private var keyList: [String]?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
if let uid = parentID{
let parameter = ["f_id": uid]
LCYNetworking.sharedInstance.POST(LCYApi.PetSubType, parameters: parameter, success: { [weak self] (object) -> Void in
self?.subTypeInfo = LCYPetSubTypeBase.modelObjectWithDictionary(object as [NSObject : AnyObject])
self?.groupInfo()
self?.tableView.reloadData()
return
}, failure: { [weak self](error) -> Void in
self?.alert("您的网络状态不给力哟")
return
})
} else {
alert("内部错误,请退回重试")
}
tableView.backgroundColor = UIColor.LCYThemeColor()
tableView.tintColor = UIColor.LCYThemeDarkText()
navigationItem.title = "品种"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Actions
func groupInfo() {
if let resultList = subTypeInfo?.childStyle as? [LCYPetSubTypeChildStyle] {
for child in resultList {
let key = child.spell
var startArray: [LCYPetSubTypeChildStyle]?
if groupedTypeInfo[key] != nil {
startArray = groupedTypeInfo[key]
} else {
startArray = [LCYPetSubTypeChildStyle]()
}
startArray?.append(child)
groupedTypeInfo[key] = startArray
}
}
keyList = (groupedTypeInfo as NSDictionary).allKeys.sorted({ (a: AnyObject, b: AnyObject) -> Bool in
return (a as! String) < (b as! String)
}) as? [String]
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
if let keys = keyList {
return keys.count
} else {
return 0
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let groupedData = groupedTypeInfo[keyList![section]] {
return groupedData.count
} else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(PetCateFilterCell.identifier(), forIndexPath: indexPath) as! PetCateFilterCell
if let groupedData = groupedTypeInfo[keyList![indexPath.section]] {
let childInfo = groupedData[indexPath.row]
cell.icyImageView?.setImageWithURL(NSURL(string: childInfo.headImg.toAbsolutePath()), placeholderImage: UIImage(named: "placeholderLogo"))
cell.icyTextLabel?.text = childInfo.name
}
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let keys = keyList {
return keys[section]
} else {
return nil
}
}
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! {
if let keys = keyList {
return keys
} else {
return nil
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 25.0
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let groupedData = groupedTypeInfo[keyList![indexPath.section]] {
let childInfo = groupedData[indexPath.row]
if let myRoot = root {
if myRoot.isKindOfClass(WikiViewController.classForCoder()) {
// 如果是百科,则直接跳转
let wikiStoryBoard = UIStoryboard(name: "Wiki", bundle: nil)
let wikiVC = wikiStoryBoard.instantiateViewControllerWithIdentifier("catedWiki") as! WikiesViewController
wikiVC.childCate = childInfo
navigationController?.pushViewController(wikiVC, animated: true)
return
} else {
// 一般情况,返回处理
delegate?.didSelectCategory(childInfo)
navigationController?.popToViewController(myRoot, animated: true)
return
}
}
delegate?.didSelectCategory(childInfo)
if let uroot = root {
navigationController?.popToViewController(uroot, animated: true)
} else {
navigationController?.popToRootViewControllerAnimated(true)
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
protocol PetCateFilterDelegate: class {
func didSelectCategory(childCategory: LCYPetSubTypeChildStyle)
}
|
apache-2.0
|
372091550745a078fe77d9b5109ac606
| 35.208092 | 150 | 0.605843 | 5.286076 | false | false | false | false |
radex/swift-compiler-crashes
|
crashes-fuzzing/22608-swift-declcontext-lookupqualified.swift
|
11
|
2446
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var a)
typealias B : d<f {
func a
}
struct B {
func e()
struct B : (c> {
protocol A : b : b
}
func a))] as BooleanType, U>
struct S<T where H : C {
let end = b<Int>], b { {
}
println(c]
struct B : a {
{
typealias b { func a)
let d
let a {
protocol c : A {
}
println(Any) -> {
protocol a {
}
{
}
}
protocol b : a {
class A.h ==
protocol c {
let : ())
struct b<T where B {
struct B : e(Any)
}
class a {
struct b: A : C {
class d
}
}
}
enum a))
}
}
}
class c : A {
{
func a)!)] as BooleanType, b { func b(Any)
struct B : A
}
struct B
typealias B {
func a<b
protocol A {
protocol A {
class B : a {
func a
typealias b { func g: d
typealias b<H
let d<T where g: B<T where H : a {
var a
}
struct S
var d {
}
}
}
{
typealias d
protocol c {
func d: e: T {
}
struct S<T where Optional<S : b {
}
let a {
}
}
protocol c {
}
}
return
struct S<T where g.a("A?
let start = e(#object1, AnyObject, AnyObject
typealias d
func f{
protocol A {
{
extension NSSet {
struct b<T {
struct c {
func c(a))
func a
let a {
{
typealias B = "
}
}
let a {
class C(#object1, Any) -> {
}
class A {
}
protocol A {
typealias b { func c]() {
}
}
func b: AnyObject
}
}
struct S
typealias b : ()
enum S<1 {
protocol A : e: AnyObject
{
protocol b { {
struct A? {
struct c {
class A : B
let end = "], U) -> {
{
}
}
let d: A? {
enum a: d) {
{
class c : A {
typealias b
}
class d
case C(A, AnyObject, AnyObject, b { func a)
{
}
let start = [self.h === [self.init(c
var d {
let a = c, AnyObject, U>], b { func a("
struct c : B<S : a = [T where g: b> (1])
}
}
class c {
}
}
protocol b : a {
struct b
let : A, U>
va d
class b
let start = "A) -> === " "]))
}
struct A : e()
println()
}
let a {
extension NSSet {
enum a {
import DummyModule
extension NSSet {
println(v: b {
func f{
}
}
func b(Any) {
enum a<H
struct b: AnyObject, U, b { func d
{
}
}
class A {
struct Q<U) -> T
let
}
}
class A {
class A : (a: a {
}
struct B {
protocol b {
typealias d<U>
struct S<S : a {
enum S<T where g.a: ()
let : e: a {
struct S<T where h: AnyObject, b { func b() {
var d === ")
protocol A : a {
protocol c {
func c(A
{
}
let : AnyObject) -> {
<T where Optional<T where g: A<T where g.init()
func b<H
}
struct c : AnyObject
}
}
struct S<T : a
class B : T where B = "
protocol A : b<U) {
class A {
protocol A {
struct Q<S : C {
}
protocol
|
mit
|
3f365ef3a3230c171d2e243a51422355
| 10.931707 | 87 | 0.590352 | 2.455823 | false | false | false | false |
Darren-chenchen/yiyiTuYa
|
testDemoSwift/Share/CLCoustomButton.swift
|
1
|
857
|
//
// CLCoustomButton.swift
// haihang_swift
//
// Created by darren on 16/8/16.
// Copyright © 2016年 shanku. All rights reserved.
//
import UIKit
class CLCoustomButton: UIButton {
var imageF = CGRect()
var titleF = CGRect()
func initTitleFrameAndImageFrame(_ buttomFrame:CGRect, imageFrame:CGRect, titleFrame:CGRect) {
imageF = imageFrame
self.frame = buttomFrame
titleF = titleFrame
self.titleLabel!.textAlignment = NSTextAlignment.center
self.titleLabel!.font = UIFont.systemFont(ofSize: 15)
self.setTitleColor(UIColor.black, for: UIControlState())
}
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
return imageF
}
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
return titleF
}
}
|
apache-2.0
|
37ca07977d85b42e99f2150b2704e05e
| 25.6875 | 98 | 0.665105 | 4.313131 | false | false | false | false |
vicentesuarez/TransitionManager
|
TransitionManager/TransitionManager/InteractiveTransitioning.swift
|
1
|
4514
|
//
// InteractiveTransitioning.swift
// TransitionManager
//
// Created by Vicente Suarez on 11/9/16.
// Copyright © 2016 Vicente Suarez. All rights reserved.
//
import UIKit
class InteractiveTransitioning: UIPercentDrivenInteractiveTransition {
// MARK: - Constants -
private let minimumProgress: CGFloat = 0.0
private let thresholdProgress: CGFloat = 0.5
private let completeThreshold: CGFloat = 0.9
private let maximumProgress: CGFloat = 1.0
// MARK: - Cues -
private(set) var interactionInProgress = false
private var shouldCompleteTransition = false
// MARK: - Properties -
private let source: UIViewController
private var destination: UIViewController?
private var presentationType: PresentationType
private var direction: PresentationDirection
private var translationWidth: CGFloat?
// MARK: - Intialization -
init(source: UIViewController, presentationType: PresentationType, direction: PresentationDirection = .left) {
self.source = source
self.presentationType = presentationType
self.direction = direction
super.init()
let presentHandler = #selector(handlePresentationGesture(gestureRecognizer:))
let gestureRecongnizer = UIScreenEdgePanGestureRecognizer(target: self, action: presentHandler)
gestureRecongnizer.edges = direction == .left ? .left : .right
source.view.addGestureRecognizer(gestureRecongnizer)
}
// MARK: - Setters -
func setDestination<T: UIViewController>(_ destination: T) where T: TransitionDestination {
self.destination = destination
translationWidth = destination.translationWidth
let dismissHandler = #selector(handleDismissGesture(gestureRecognizer:))
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: dismissHandler)
destination.view.addGestureRecognizer(gestureRecognizer)
}
// MARK: - Gesture handling -
func handlePresentationGesture(gestureRecognizer: UIScreenEdgePanGestureRecognizer) {
guard let translationView = gestureRecognizer.view else { return }
let translation = gestureRecognizer.translation(in: translationView)
var progress = translation.x * direction.rawValue / (translationWidth ?? translationView.bounds.width)
progress = CGFloat(fmin(fmax(progress, minimumProgress), maximumProgress))
switch gestureRecognizer.state {
case .began:
interactionInProgress = true
switch presentationType {
case .segue(let presentIdentifier, _):
source.performSegue(withIdentifier: presentIdentifier, sender: self)
case .presenting:
guard let destination = destination else { return }
source.present(destination, animated: true, completion: nil)
}
case .changed:
shouldCompleteTransition = progress > thresholdProgress
update(progress)
default:
interactionInProgress = false
shouldCompleteTransition ? finish() : cancel()
}
}
func handleDismissGesture(gestureRecognizer: UIPanGestureRecognizer) {
guard let translationView = gestureRecognizer.view,
let destination = destination else { return }
let translation = gestureRecognizer.translation(in: translationView)
let translationWidth = self.translationWidth ?? translationView.bounds.width
var progress = -translation.x * direction.rawValue / translationWidth
progress = CGFloat(fmin(fmax(progress, minimumProgress), maximumProgress))
switch gestureRecognizer.state {
case .began:
interactionInProgress = true
switch presentationType {
case .segue(_, let dismissIdentifier):
destination.performSegue(withIdentifier: dismissIdentifier, sender: self)
case .presenting:
destination.dismiss(animated: true, completion: nil)
}
case .changed:
if progress >= completeThreshold {
finish()
} else {
shouldCompleteTransition = progress > thresholdProgress
update(progress)
}
default:
interactionInProgress = false
shouldCompleteTransition ? finish() : cancel()
}
}
}
|
mit
|
aa9e712071aa4b41fcbc9ef28ce25689
| 37.905172 | 114 | 0.658985 | 5.876302 | false | false | false | false |
dtartaglia/Apex
|
Apex/BlockCommand.swift
|
1
|
625
|
//
// BlockCommand.swift
// Apex
//
// Created by Daniel Tartaglia on 12/18/17.
// Copyright © 2017 Daniel Tartaglia. All rights reserved.
//
public final
class BlockCommand: Command, Equatable, CustomStringConvertible {
public let description: String
public
init(description: String, work: @escaping (Dispatcher) -> Void) {
self.description = description
self.work = work
}
public
func execute(dispatcher: Dispatcher) {
work(dispatcher)
}
public
static func ==(lhs: BlockCommand, rhs: BlockCommand) -> Bool {
return lhs.description == rhs.description
}
private let work: (Dispatcher) -> Void
}
|
mit
|
1d41c3e03ed9d07d5e6992419c146521
| 19.129032 | 66 | 0.713141 | 3.586207 | false | false | false | false |
dnseitz/YAPI
|
YAPI/YAPITests/NetworkMockObjects.swift
|
1
|
1000
|
//
// NetworkMockObjects.swift
// Chowroulette
//
// Created by Daniel Seitz on 7/29/16.
// Copyright © 2016 Daniel Seitz. All rights reserved.
//
import Foundation
@testable import YAPI
class MockURLSession: URLSessionProtocol {
var nextData: Data?
var nextError: NSError?
var nextDataTask = MockURLSessionDataTask()
fileprivate(set) var lastURL: URL?
func dataTask(with url: URL, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol {
self.lastURL = url
completionHandler(self.nextData, nil, self.nextError)
return self.nextDataTask
}
func dataTask(with request: URLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol {
self.lastURL = request.url
completionHandler(self.nextData, nil, self.nextError)
return self.nextDataTask
}
}
class MockURLSessionDataTask: URLSessionDataTaskProtocol {
fileprivate(set) var resumeWasCalled = false
func resume() {
resumeWasCalled = true
}
}
|
mit
|
d29d36f6f3075077f6c650a5aa3531af
| 26 | 118 | 0.745746 | 4.400881 | false | false | false | false |
zmarvin/EnjoyMusic
|
Pods/Macaw/Source/model/geom2d/PathBuilder.swift
|
1
|
5237
|
import Foundation
open class PathBuilder {
open let segment: PathSegment
open let rest: PathBuilder?
public init(segment: PathSegment, rest: PathBuilder? = nil) {
self.segment = segment
self.rest = rest
}
// GENERATED NOT
open func moveTo(x: Double, y: Double) -> PathBuilder {
return M(x, y)
}
// GENERATED NOT
open func lineTo(x: Double, y: Double) -> PathBuilder {
return L(x, y)
}
// GENERATED NOT
open func cubicTo(x1: Double, y1: Double, x2: Double, y2: Double, x: Double, y: Double) -> PathBuilder {
return C(x1, y1, x2, y2, x, y)
}
// GENERATED NOT
open func quadraticTo(x1: Double, y1: Double, x: Double, y: Double) -> PathBuilder {
return Q(x1, y1, x, y)
}
// GENERATED NOT
open func arcTo(rx: Double, ry: Double, angle: Double, largeArc: Bool, sweep: Bool, x: Double, y: Double) -> PathBuilder {
return A(rx, ry, angle, largeArc, sweep, x, y)
}
// GENERATED NOT
open func close() -> PathBuilder {
return Z()
}
// GENERATED NOT
open func m(_ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .m, data: [x, y]), rest: self)
}
// GENERATED NOT
open func M(_ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .M, data: [x, y]), rest: self)
}
// GENERATED NOT
open func l(_ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .l, data: [x, y]), rest: self)
}
// GENERATED NOT
open func L(_ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .L, data: [x, y]), rest: self)
}
// GENERATED NOT
open func h(_ x: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .h, data: [x]), rest: self)
}
// GENERATED NOT
open func H(_ x: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .H, data: [x]), rest: self)
}
// GENERATED NOT
open func v(_ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .v, data: [y]), rest: self)
}
// GENERATED NOT
open func V(_ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .V, data: [y]), rest: self)
}
// GENERATED NOT
open func c(_ x1: Double, _ y1: Double, _ x2: Double, _ y2: Double, _ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .c, data: [x1, y1, x2, y2, x, y]), rest: self)
}
// GENERATED NOT
open func C(_ x1: Double, _ y1: Double, _ x2: Double, _ y2: Double, _ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .C, data: [x1, y1, x2, y2, x, y]), rest: self)
}
// GENERATED NOT
open func s(_ x2: Double, _ y2: Double, _ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .s, data: [x2, y2, x, y]), rest: self)
}
// GENERATED NOT
open func S(_ x2: Double, _ y2: Double, _ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .S, data: [x2, y2, x, y]), rest: self)
}
// GENERATED NOT
open func q(_ x1: Double, _ y1: Double, _ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .q, data: [x1, y1, x, y]), rest: self)
}
// GENERATED NOT
open func Q(_ x1: Double, _ y1: Double, _ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .Q, data: [x1, y1, x, y]), rest: self)
}
// GENERATED NOT
open func t(_ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .t, data: [x, y]), rest: self)
}
// GENERATED NOT
open func T(_ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .T, data: [x, y]), rest: self)
}
// GENERATED NOT
open func a(_ rx: Double, _ ry: Double, _ angle: Double, _ largeArc: Bool, _ sweep: Bool, _ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .a, data: [rx, ry, angle, boolsToNum(largeArc, sweep: sweep), x, y]), rest: self)
}
// GENERATED NOT
open func A(_ rx: Double, _ ry: Double, _ angle: Double, _ largeArc: Bool, _ sweep: Bool, _ x: Double, _ y: Double) -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .A, data: [rx, ry, angle, boolsToNum(largeArc, sweep: sweep), x, y]), rest: self)
}
// GENERATED NOT
open func Z() -> PathBuilder {
return PathBuilder(segment: PathSegment(type: .z), rest: self)
}
// GENERATED NOT
open func build() -> Path {
var segments : [PathSegment] = []
var builder : PathBuilder? = self
while(builder != nil) {
segments.append(builder!.segment)
builder = builder!.rest
}
return Path(segments: segments.reversed())
}
// GENERATED NOT
fileprivate func boolsToNum(_ largeArc: Bool, sweep: Bool) -> Double {
return (largeArc ? 1 : 0) + (sweep ? 1 : 0) * 2;
}
}
|
mit
|
cea7469430ac161efbb165c44f46568f
| 33.006494 | 136 | 0.586977 | 3.318758 | false | false | false | false |
icecrystal23/ios-charts
|
ChartsDemo-iOS/Swift/Demos/HorizontalBarChartViewController.swift
|
2
|
3799
|
//
// HorizontalBarChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class HorizontalBarChartViewController: DemoBaseViewController {
@IBOutlet var chartView: HorizontalBarChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderY: UISlider!
@IBOutlet var sliderTextX: UITextField!
@IBOutlet var sliderTextY: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Horizontal Bar Char"
self.options = [.toggleValues,
.toggleIcons,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData,
.toggleBarBorders]
self.setup(barLineChartView: chartView)
chartView.delegate = self
chartView.drawBarShadowEnabled = false
chartView.drawValueAboveBarEnabled = true
chartView.maxVisibleCount = 60
let xAxis = chartView.xAxis
xAxis.labelPosition = .bottom
xAxis.labelFont = .systemFont(ofSize: 10)
xAxis.drawAxisLineEnabled = true
xAxis.granularity = 10
let leftAxis = chartView.leftAxis
leftAxis.labelFont = .systemFont(ofSize: 10)
leftAxis.drawAxisLineEnabled = true
leftAxis.drawGridLinesEnabled = true
leftAxis.axisMinimum = 0
let rightAxis = chartView.rightAxis
rightAxis.enabled = true
rightAxis.labelFont = .systemFont(ofSize: 10)
rightAxis.drawAxisLineEnabled = true
rightAxis.axisMinimum = 0
let l = chartView.legend
l.horizontalAlignment = .left
l.verticalAlignment = .bottom
l.orientation = .horizontal
l.drawInside = false
l.form = .square
l.formSize = 8
l.font = UIFont(name: "HelveticaNeue-Light", size: 11)!
l.xEntrySpace = 4
// chartView.legend = l
chartView.fitBars = true
sliderX.value = 12
sliderY.value = 50
slidersValueChanged(nil)
chartView.animate(yAxisDuration: 2.5)
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setDataCount(Int(sliderX.value) + 1, range: UInt32(sliderY.value))
}
func setDataCount(_ count: Int, range: UInt32) {
let barWidth = 9.0
let spaceForBar = 10.0
let yVals = (0..<count).map { (i) -> BarChartDataEntry in
let mult = range + 1
let val = Double(arc4random_uniform(mult))
return BarChartDataEntry(x: Double(i)*spaceForBar, y: val, icon: #imageLiteral(resourceName: "icon"))
}
let set1 = BarChartDataSet(values: yVals, label: "DataSet")
set1.drawIconsEnabled = false
let data = BarChartData(dataSet: set1)
data.setValueFont(UIFont(name:"HelveticaNeue-Light", size:10)!)
data.barWidth = barWidth
chartView.data = data
}
override func optionTapped(_ option: Option) {
super.handleOption(option, forChartView: chartView)
}
// MARK: - Actions
@IBAction func slidersValueChanged(_ sender: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
sliderTextY.text = "\(Int(sliderY.value))"
self.updateChartData()
}
}
|
apache-2.0
|
65e1471427d727ecab20db1ef60065ad
| 29.629032 | 113 | 0.582412 | 5.091153 | false | false | false | false |
appprova/appprova-ui-components-ios
|
AppProvaUIComponents/UIViewController+HUD.swift
|
1
|
3231
|
//
// UIViewController+HUD.swift
// AppProvaUIComponents
//
// Created by Guilherme Castro on 10/11/16.
// Copyright © 2016 AppProva. All rights reserved.
//
import Foundation
import UIKit
import MBProgressHUD
private var blurImageView: UIImageView?
private var _hud: MBProgressHUD?
public extension UIViewController {
public var hud:MBProgressHUD? {
get {
return _hud
}
set {
if (newValue == nil) {
self.dismissBlurBackground()
}
_hud?.hide(animated: true)
_hud = newValue
}
}
public func showToast(localizedString: String) {
self.showToast(text: NSLocalizedString(localizedString, comment: ""))
}
public func showToast(text: String) {
self.dismissHud()
hud = MBProgressHUD.showAdded(to: self.view, animated: true)
let gestureRecognizer = UITapGestureRecognizer()
gestureRecognizer.addTarget(self, action: #selector(dismissHud))
hud?.addGestureRecognizer(gestureRecognizer)
hud?.mode = .text
hud?.detailsLabel.text = text
hud?.offset = CGPoint(x: 0.0, y: MBProgressMaxOffset)
hud?.hide(animated: true, afterDelay: 3.5)
}
// MARK: Loading
public func showBlur(targetView: UIView) {
let blurImage = self.getBlurScreenShot()
let blurScreenShotImageView = UIImageView(image: blurImage)
blurImageView = blurScreenShotImageView
targetView.addSubview(blurScreenShotImageView)
}
public func showLoading() {
guard let keyWindow = UIApplication.shared.keyWindow else {
NSLog("The Application key window was not defined. The Background Blur of The Loading view will not be show.")
return
}
self.showBlur(targetView: keyWindow)
hud = MBProgressHUD.showAdded(to: keyWindow, animated: true)
}
public func dismissHud() {
hud = nil
}
private func dismissBlurBackground(_ bool:Bool = false) {
let blurTime = 0.4
UIView.animate(withDuration: blurTime, animations: { () -> Void in
blurImageView?.alpha = 0.0
}, completion: { _ in
blurImageView?.removeFromSuperview()
blurImageView = nil
})
}
private func getBlurScreenShot() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, true, 1)
self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: false)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//let tintColor = UIColor(white: 1.0, alpha: 0.3) // light
let tintColor = UIColor(white: 0.11, alpha: 0.73)
//self applyBlurWithRadius:30 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil
//return screenshot.applyExtraLightEffect()
//UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73];
return screenshot == nil ? UIImage() :
screenshot!.applyBlurWithRadius(5, tintColor: tintColor, saturationDeltaFactor: 1.8, maskImage: nil)
}
}
|
mit
|
5181c8dbcc1819d483e4e9e051993a18
| 31.3 | 122 | 0.627864 | 4.842579 | false | false | false | false |
thulefog/ScrollableAdaptiveImageViewer
|
ScrollableAdaptiveImageViewer/AppDelegate.swift
|
1
|
3345
|
//
// AppDelegate.swift
// ScrollableAdaptiveImageViewer
//
// Originally created by John Matthew Weston in April 2015 with edits since.
// Images Copyright © 2015 John Matthew Weston.
// Source Code - Copyright © 2015 John Matthew Weston but published as open source under MIT License.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let viewController = ScrollableImageViewController()
//read JSON data s
if let file = NSBundle(forClass:AppDelegate.self).pathForResource("SimpleStore", ofType: "json") {
let data = NSData(contentsOfFile: file)!
let json = JSON(data:data)
//traverse the data set and log to sanity check
for (index, subJson): (String, JSON) in json["SimpleStore"] {
let instance = subJson["Instance"].string;
let description = subJson["Description"].string;
log( "index \(index) Instance \(instance) | Description \(description)" )
//TODO: assert to enforce expected index of 0
viewController.assetName = instance
}
}
window!.rootViewController = UINavigationController(rootViewController: viewController)
window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
66355606161c1f4f08a406e148bf21de
| 46.084507 | 285 | 0.69997 | 5.685374 | false | false | false | false |
Rauleinstein/iSWAD
|
iSWAD/iSWAD/CoursesMasterViewController.swift
|
1
|
2858
|
//
// CoursesMasterViewController.swift
// iSWAD
//
// Created by Raul Alvarez on 13/06/2016.
// Copyright © 2016 Raul Alvarez. All rights reserved.
//
import UIKit
import SWXMLHash
class CoursesMasterViewController: UITableViewController {
var coursesList:[Course] = []
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Asignaturas"
self.tableView.dataSource = self;
if self.coursesList.isEmpty {
getCourses()
}
}
class Course: AnyObject {
var name: String = ""
var code: Int = 0
}
//MARK: Table View Data Source and Delegate
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return coursesList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = coursesList[indexPath.row].name
return cell
}
// MARK: - Segues
/*!
Segue for navigate to the details of the course
*/
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
self.splitViewController?.toggleMasterView()
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = coursesList[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! CoursesDetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
/*!
Function that loads all the courses for the logged student
*/
func getCourses() -> Void {
print("Start get Courses")
let client = SyedAbsarClient()
let defaults = NSUserDefaults.standardUserDefaults()
let requestCourses = GetCourses()
print(defaults.stringForKey(Constants.wsKey))
requestCourses.cpWsKey = defaults.stringForKey(Constants.wsKey)
client.opGetCourses(requestCourses){ (error, response2: XMLIndexer?) in
print(response2)
print(response2!["getCoursesOutput"]["numCourses"].element?.text)
let coursesArray = response2!["getCoursesOutput"]["coursesArray"].children
print(coursesArray)
for item in coursesArray{
let course = Course()
course.name = (item["courseFullName"].element?.text)!
course.code = Int((item["courseCode"].element?.text)!)!
self.coursesList.append(course)
}
// We have to send the reloadData to the UIThread otherwise won't be instant
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
print(self.coursesList)
}
}
}
|
apache-2.0
|
a09f3e85adeb6e9300eca291346bc957
| 30.755556 | 131 | 0.739937 | 4.046742 | false | false | false | false |
DevaLee/LYCSwiftDemo
|
LYCSwiftDemo/Classes/Component/Protocol/LYCEmitterProtocol.swift
|
1
|
1726
|
//
// LYCEmitterProtocol.swift
// LYCSwiftDemo
//
// Created by 李玉臣 on 2017/6/11.
// Copyright © 2017年 zsc. All rights reserved.
//
import Foundation
import UIKit
protocol LYCEmitterProtocol {
}
// 协议,结构体,里面不可以定义类方法即class方法 可以定义静态方法 static
// where Self 对协议添加约束 Self : Self关键字只能用在类里, 作为函数返回值类型, 表示当前类
extension LYCEmitterProtocol where Self : UIViewController{
// 对象方法
func addEmitter(point : CGPoint ){
let emitterLayer = CAEmitterLayer()
//位置
emitterLayer.emitterPosition = point;
// 添加三维效果
emitterLayer.preservesDepth = true;
//
var cells = [CAEmitterCell]()
for i in 0 ..< 10 {
let emitterCell = CAEmitterCell()
// 一秒有3个
emitterCell.birthRate = 2
// 粒子的内容
emitterCell.contents = UIImage(named: "good\(i)_30x30")?.cgImage
emitterCell.lifetime = 5
// 上下波动数为2
emitterCell.lifetimeRange = 3
emitterCell.emissionLongitude = CGFloat(-.pi * 0.5)
emitterCell.emissionRange = .pi * 0.1
emitterCell.velocity = 150
emitterCell.velocityRange = 100
cells.append(emitterCell)
}
emitterLayer.emitterCells = cells
view.layer.addSublayer(emitterLayer)
}
func stopEmitter(){
view.layer.sublayers!.filter( { $0.isKind(of: CAEmitterLayer.self) } ).first?.removeFromSuperlayer()
}
}
|
mit
|
138d96be48d3b8ea207f6bca9150cc46
| 26.105263 | 108 | 0.573463 | 4.426934 | false | false | false | false |
Darkhorse-Fraternity/EasyIOS-Swift
|
Pod/Classes/Easy/Core/EZAction.swift
|
1
|
8924
|
//
// Action.swift
// medical
//
// Created by zhuchao on 15/4/25.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import UIKit
import Alamofire
import Haneke
import Bond
public var HOST_URL = "" //服务端域名:端口
public var CODE_KEY = "" //错误码key,暂不支持路径 如 code
public var RIGHT_CODE = 0 //正确校验码
public var MSG_KEY = "" //消息提示msg,暂不支持路径 如 msg
private var networkReachabilityHandle: UInt8 = 2;
public class EZAction: NSObject {
//使用缓存策略 仅首次读取缓存
public class func SEND_IQ_CACHE (req:EZRequest) {
req.useCache = true
req.dataFromCache = req.isFirstRequest
self.Send(req)
}
//使用缓存策略 优先从缓存读取
public class func SEND_CACHE (req:EZRequest) {
req.useCache = true
req.dataFromCache = true
self.Send(req)
}
//不使用缓存策略
public class func SEND (req:EZRequest) {
req.useCache = false
req.dataFromCache = false
self.Send(req)
}
public class func Send (req :EZRequest){
var url = ""
var requestParams = Dictionary<String,AnyObject>()
if !isEmpty(req.staticPath) {
url = req.staticPath
}else{
if isEmpty(req.scheme) {
req.scheme = "http"
}
if isEmpty(req.host) {
req.host = HOST_URL
}
url = req.scheme + "://" + req.host + req.path
if isEmpty(req.appendPathInfo) {
requestParams = req.requestParams
}else{
url = url + req.appendPathInfo
}
}
req.state.value = .Sending
req.op = req.manager
.request(req.method, url, parameters: requestParams, encoding: req.parameterEncoding)
.validate(statusCode: 200..<300)
.validate(contentType: req.acceptableContentTypes)
.responseString { (_, _, string, _) in
req.responseString = string
}.responseJSON { (_, _, json, error) in
if json == nil{
req.error = error
self.failed(req)
}else{
req.output = json as! Dictionary<String, AnyObject>
self.checkCode(req)
}
}
req.url = req.op?.request.URL
self.getCacheJson(req)
}
public class func Upload (req :EZRequest){
req.state.value = .Sending
req.op = req.manager
.upload(.POST, req.uploadUrl, data: req.uploadData!)
.validate(statusCode: 200..<300)
.validate(contentType: req.acceptableContentTypes)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
req.totalBytesWritten = Double(totalBytesWritten)
req.totalBytesExpectedToWrite = Double(totalBytesExpectedToWrite)
req.progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
}
.responseString { (_, _, string, _) in
req.responseString = string!
}.responseJSON { (_, _, json, error) in
if error != nil{
req.error = error
self.failed(req)
}else{
req.output = json as! Dictionary<String, AnyObject>
self.checkCode(req)
}
}
req.url = req.op?.request.URL
}
public class func Download (req :EZRequest){
req.state.value = .Sending
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
req.op = req.manager
.download(.GET, req.downloadUrl, destination: { (temporaryURL, response) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,
inDomains: .UserDomainMask)[0]
as? NSURL {
return directoryURL.URLByAppendingPathComponent(req.targetPath + response.suggestedFilename!)
}
return temporaryURL
})
.validate(statusCode: 200..<300)
.progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
req.totalBytesRead = Double(totalBytesRead)
req.totalBytesExpectedToRead = Double(totalBytesExpectedToRead)
req.progress = Double(totalBytesRead) / Double(totalBytesExpectedToRead)
}
.response { (request, response, _, error) in
if error != nil{
req.error = error
self.failed(req)
}else{
req.responseString = "\(response)"
req.state.value = .Success
}
}
req.url = req.op?.request.URL
}
private class func cacheJson (req: EZRequest) {
if req.useCache {
let cache = Shared.JSONCache
cache.set(value: .Dictionary(req.output), key: req.cacheKey, formatName: HanekeGlobals.Cache.OriginalFormatName){ JSON in
EZPrintln("Cache Success for key: \(req.cacheKey)")
}
}
}
private class func getCacheJson (req: EZRequest) {
let cache = Shared.JSONCache
cache.fetch(key: req.cacheKey).onSuccess { JSON in
req.output = JSON.dictionary
if req.dataFromCache && !isEmpty(req.output) {
let delayTime = dispatch_time(DISPATCH_TIME_NOW,
Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.loadFromCache(req)
}
}
}
}
private class func loadFromCache (req: EZRequest){
if req.needCheckCode && req.state.value != .Success {
req.codeKey = req.output[CODE_KEY] as? Int
if req.codeKey == RIGHT_CODE {
req.message = req.output[MSG_KEY] as? String
req.state.value = .SuccessFromCache
EZPrintln("Fetch Success from Cache by key: \(req.cacheKey)")
}else{
req.message = req.output[MSG_KEY] as? String
req.state.value = .ErrorFromCache
EZPrintln(req.message)
}
}
}
private class func checkCode (req: EZRequest) {
if req.needCheckCode {
req.codeKey = req.output[CODE_KEY] as? Int
if req.codeKey == RIGHT_CODE {
self.success(req)
self.cacheJson(req)
}else{
self.error(req)
}
}else{
req.state.value = .Success
self.cacheJson(req)
}
}
private class func success (req: EZRequest) {
req.isFirstRequest = false
req.message = req.output[MSG_KEY] as? String
if isEmpty(req.output) {
req.state.value = .Error
}else{
req.state.value = .Success
}
}
private class func failed (req: EZRequest) {
req.message = req.error?.userInfo?["NSLocalizedDescription"] as? String
req.state.value = .Failed
EZPrintln(req.message)
}
private class func error (req: EZRequest) {
req.message = req.output[MSG_KEY] as? String
req.state.value = .Error
EZPrintln(req.message)
}
/* Usage
EZAction.networkReachability *->> Bond<NetworkStatus>{ status in
switch (status) {
case .NotReachable:
EZPrintln("NotReachable")
case .ReachableViaWiFi:
EZPrintln("ReachableViaWiFi")
case .ReachableViaWWAN:
EZPrintln("ReachableViaWWAN")
default:
EZPrintln("default")
}
}
*/
public class var networkReachability: InternalDynamic<NetworkStatus> {
if let d: AnyObject = objc_getAssociatedObject(self, &networkReachabilityHandle) {
return (d as? InternalDynamic<NetworkStatus>)!
} else {
let reachability = Reachability.reachabilityForInternetConnection()
let d = InternalDynamic<NetworkStatus>(reachability.currentReachabilityStatus)
reachability.whenReachable = { reachability in
d.value = reachability.currentReachabilityStatus
}
reachability.whenUnreachable = { reachability in
d.value = reachability.currentReachabilityStatus
}
reachability.startNotifier()
objc_setAssociatedObject(self, &networkReachabilityHandle, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
}
|
mit
|
ace032fcca27d17374ddb558b3c71621
| 33.880952 | 133 | 0.554608 | 4.730893 | false | false | false | false |
superk589/CGSSGuide
|
DereGuide/Controller/RefreshableTableViewController.swift
|
2
|
13766
|
//
// RefreshableTableViewController.swift
// DereGuide
//
// Created by zzk on 16/7/25.
// Copyright © 2016 zzk. All rights reserved.
//
import UIKit
import MJRefresh
protocol Refreshable {
var refresher: MJRefreshHeader { get set }
func check(_ types: CGSSUpdateDataTypes)
func checkUpdate()
}
extension Refreshable where Self: UIViewController {
func check(_ types: CGSSUpdateDataTypes) {
let updater = CGSSUpdater.default
let vm = CGSSVersionManager.default
let dao = CGSSDAO.shared
let hm = CGSSUpdatingHUDManager.shared
let gr = CGSSGameResource.shared
defer {
refresher.endRefreshing()
}
if updater.isWorking || gr.isProcessing { return }
hm.show()
hm.cancelAction = {
updater.cancelCurrentSession()
}
hm.setup(NSLocalizedString("检查更新中", comment: "更新框"), animated: true, cancelable: true)
func doUpdating(types: CGSSUpdateDataTypes) {
DispatchQueue.main.async {
hm.show()
hm.cancelAction = {
updater.cancelCurrentSession()
}
hm.setup(NSLocalizedString("检查更新中", comment: "更新框"), animated: true, cancelable: true)
}
updater.checkUpdate(dataTypes: types, complete: { [weak self] (items, errors) in
if !errors.isEmpty && items.count == 0 {
if errors.contains(where: { (error) -> Bool in
return (error as NSError).code == NSURLErrorCancelled
}) {
// do nothing
} else {
hm.hide(animated: false)
var errorStr = ""
if let error = errors.first as? CGSSUpdaterError {
errorStr.append(error.localizedDescription)
} else if let error = errors.first {
errorStr.append(error.localizedDescription)
}
let alert = UIAlertController.init(title: NSLocalizedString("检查更新失败", comment: "更新框")
, message: errorStr, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: NSLocalizedString("确定", comment: "弹出框按钮"), style: .default, handler: nil))
self?.tabBarController?.present(alert, animated: true, completion: nil)
}
} else {
if items.count == 0 {
hm.setup(NSLocalizedString("数据是最新版本", comment: "更新框"), animated: false, cancelable: false)
hm.hide(animated: true)
} else {
hm.show()
hm.setup(current: 0, total: items.count, animated: true, cancelable: true)
updater.updateItems(items, progress: { processed, total in
hm.setup(current: processed, total: total, animated: true, cancelable: true)
}) { success, total in
hm.show()
hm.setup(NSLocalizedString("正在完成更新", comment: "更新框"), animated: true, cancelable: false)
DispatchQueue.global(qos: .userInitiated).async {
gr.processDownloadedData(types: CGSSUpdateDataTypes(items.map { $0.dataType }), completion: {
let alert = UIAlertController.init(title: NSLocalizedString("更新完成", comment: "弹出框标题"), message: "\(NSLocalizedString("成功", comment: "通用")) \(success), \(NSLocalizedString("失败", comment: "通用")) \(total - success)", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: NSLocalizedString("确定", comment: "弹出框按钮"), style: .default, handler: nil))
UIViewController.root?.present(alert, animated: true, completion: nil)
hm.hide(animated: false)
})
}
}
}
}
})
}
func confirmToUpdate(reason: String?, newVersion: Version, cancelable: Bool) {
DispatchQueue.main.async { [weak self] in
hm.hide(animated: false)
let alert = UIAlertController(title: NSLocalizedString("数据需要更新", comment: "弹出框标题"), message: reason, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("确定", comment: "弹出框按钮"), style: .default, handler: { (alertAction) in
vm.dataVersion = newVersion
doUpdating(types: types)
}))
if cancelable {
alert.addAction(UIAlertAction(title: NSLocalizedString("取消", comment: "弹出框按钮"), style: .cancel, handler: nil))
}
self?.tabBarController?.present(alert, animated: true, completion: nil)
}
}
if types.contains(.card) {
updater.checkRemoteDataVersion(callback: { payload, error in
// firstly, we check remote data version
if let payload = payload, let version = Version(string: payload.version) {
if let udid = payload.udid, let userID = payload.userID, let viewerID = payload.viewerID {
APIClient.shared.udid = udid
APIClient.shared.userID = userID
APIClient.shared.viewerID = viewerID
}
// if remote data version's major is greater than local version, remove all data then re-download.
if vm.dataVersion.major < version.major {
dao.removeAllData()
let reason: String?
if vm.dataVersion == Version(1, 0, 0) || payload.localizedReason == nil {
reason = NSLocalizedString("数据主版本过低,请点击确定开始更新", comment: "")
} else {
reason = payload.localizedReason
}
confirmToUpdate(reason: reason, newVersion: version, cancelable: false)
// else if remote data version's minor is greater than local version, recommend user to update all data
} else if vm.dataVersion.minor < version.minor {
let reason: String?
if vm.dataVersion == Version(1, 0, 0) || payload.localizedReason == nil {
reason = NSLocalizedString("数据存在新版本,推荐进行更新,请点击确定开始更新", comment: "")
} else {
reason = payload.localizedReason
}
confirmToUpdate(reason: reason, newVersion: version, cancelable: true)
// else if remote data version's patch is greater than local version, remove the items only in patch items array, then re-download them.
} else if vm.dataVersion.patch < version.patch {
for item in payload.items {
switch item.type {
case .card:
dao.cardDict.removeObject(forKey: item.id)
case .chara:
if let id = Int(item.id) {
let cards = dao.findCardsByCharId(id)
dao.cardDict.removeObjects(forKeys: cards.map { String($0.id) })
}
default:
break
}
}
vm.dataVersion = version
doUpdating(types: types)
// finally, only check patch items to make sure they are all updated to the newest version
} else {
for item in payload.items {
switch item.type {
case .card:
if let id = Int(item.id), let card = dao.findCardById(id), card.dataVersion < version {
dao.cardDict.removeObject(forKey: item.id)
}
case .chara:
if let id = Int(item.id) {
let cards = dao.findCardsByCharId(id)
dao.cardDict.removeObjects(forKeys: cards.compactMap {
if $0.dataVersion < version {
return String($0.id)
} else {
return nil
}
})
}
default:
break
}
}
vm.dataVersion = version
doUpdating(types: types)
}
// if we can't get remote data version(eg. network error), check the local minimum supported version
} else {
// if local minimum supported version's major is greater than local version, remove all data and re-download
if vm.dataVersion.major < vm.minimumSupportedDataVersion.major {
dao.removeAllData()
let reason = NSLocalizedString("数据主版本过低,请点击确定开始更新", comment: "")
confirmToUpdate(reason: reason, newVersion: vm.minimumSupportedDataVersion, cancelable: false)
// else if local minimum supported version's minor is greater than local version. recommand user to update
} else if vm.dataVersion.minor < vm.minimumSupportedDataVersion.minor {
let reason = NSLocalizedString("数据存在新版本,推荐进行更新,请点击确定开始更新", comment: "")
confirmToUpdate(reason: reason, newVersion: vm.minimumSupportedDataVersion, cancelable: true)
// finally, do normal updating, local minimum supported version has no patch information.
} else {
// if user cancelled, do nothing
if let error = error as NSError?, error.code == NSURLErrorCancelled {
} else {
doUpdating(types: types)
}
}
}
})
} else {
doUpdating(types: types)
}
}
}
class RefreshableTableViewController: BaseTableViewController, Refreshable {
var refresher: MJRefreshHeader = CGSSRefreshHeader()
override func viewDidLoad() {
super.viewDidLoad()
tableView.mj_header = refresher
refresher.refreshingBlock = { [weak self] in self?.checkUpdate() }
}
func checkUpdate() {
}
}
class RefreshableCollectionViewController: BaseViewController, Refreshable {
var refresher: MJRefreshHeader = CGSSRefreshHeader()
var layout: UICollectionViewFlowLayout!
var collectionView: UICollectionView!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
layout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
collectionView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
collectionView.mj_header = refresher
refresher.refreshingBlock = { [weak self] in self?.checkUpdate() }
}
func checkUpdate() {
}
}
extension RefreshableCollectionViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 0
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
|
mit
|
d6c8e6c4397252672765c6d76f21b098
| 45.370242 | 273 | 0.504291 | 5.836672 | false | false | false | false |
SusanDoggie/Doggie
|
Sources/DoggieGPU/CoreImage/ConvolveKernel.swift
|
1
|
4924
|
//
// ConvolveKernel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if canImport(CoreImage) && canImport(MetalPerformanceShaders)
extension CIImage {
private class ConvolveKernel: CIImageProcessorKernel {
override class var synchronizeInputs: Bool {
return false
}
override class func roi(forInput input: Int32, arguments: [String: Any]?, outputRect: CGRect) -> CGRect {
guard let orderX = arguments?["orderX"] as? Int else { return outputRect }
guard let orderY = arguments?["orderY"] as? Int else { return outputRect }
let inset_x = -(orderX + 1) / 2
let inset_y = -(orderY + 1) / 2
return outputRect.insetBy(dx: CGFloat(inset_x), dy: CGFloat(inset_y))
}
override class func process(with inputs: [CIImageProcessorInput]?, arguments: [String: Any]?, output: CIImageProcessorOutput) throws {
guard let commandBuffer = output.metalCommandBuffer else { return }
guard let input = inputs?.first else { return }
guard let source = input.metalTexture else { return }
guard let destination = output.metalTexture else { return }
guard let orderX = arguments?["orderX"] as? Int, orderX > 0 else { return }
guard let orderY = arguments?["orderY"] as? Int, orderY > 0 else { return }
guard let matrix = arguments?["matrix"] as? [Double], orderX * orderY == matrix.count else { return }
guard let bias = arguments?["bias"] as? Double else { return }
let kernel = MPSImageConvolution(device: commandBuffer.device, kernelWidth: orderX, kernelHeight: orderY, weights: matrix.map { Float($0) })
kernel.offset.x = Int(output.region.minX - input.region.minX)
kernel.offset.y = Int(output.region.minY - input.region.minY)
kernel.bias = Float(bias)
kernel.encode(commandBuffer: commandBuffer, sourceTexture: source, destinationTexture: destination)
}
}
public func convolve(_ matrix: [Double], _ bias: Double, _ orderX: Int, _ orderY: Int) -> CIImage {
if extent.isEmpty { return .empty() }
guard orderX > 0 && orderY > 0 && orderX * orderY == matrix.count else { return self }
if orderX > 1 && orderY > 1, let (horizontal, vertical) = separate_convolution_filter(matrix, orderX, orderY) {
return self.convolve(horizontal, 0, orderX, 1).convolve(vertical, bias, 1, orderY)
}
let matrix = Array(matrix.chunks(ofCount: orderX).lazy.map { $0.reversed() }.joined())
let _orderX = orderX | 1
let _orderY = orderY | 1
guard _orderX <= 9 && _orderY <= 9 else { return self }
let append_x = _orderX - orderX
let append_y = _orderY - orderY
var _matrix = Array(matrix.chunks(ofCount: orderX).joined(separator: repeatElement(0, count: append_x)))
_matrix.append(contentsOf: repeatElement(0, count: append_x + _orderX * append_y))
let inset_x = -(_orderX + 1) / 2
let inset_y = -(_orderY + 1) / 2
let extent = self.extent.insetBy(dx: CGFloat(inset_x), dy: CGFloat(inset_y))
let _extent = extent.isInfinite ? extent : extent.insetBy(dx: .random(in: -1..<0), dy: .random(in: -1..<0))
var rendered = try? ConvolveKernel.apply(withExtent: _extent, inputs: [self], arguments: ["matrix": _matrix, "bias": bias, "orderX": _orderX, "orderY": _orderY])
if !extent.isInfinite {
rendered = rendered?.cropped(to: extent)
}
return rendered ?? .empty()
}
}
#endif
|
mit
|
f175992ffc1f05ecdcb014b861a5f486
| 47.27451 | 169 | 0.627945 | 4.334507 | false | false | false | false |
duycao2506/SASCoffeeIOS
|
Pods/String+Extensions/Sources/StringHTML.swift
|
3
|
12692
|
// adapted from https://gist.github.com/mwaterfall/25b4a6a06dc3309d9555
import Foundation
public extension String {
fileprivate struct HTMLEntities {
static let characterEntities : [String: Character] = [
// XML predefined entities:
""" : "\"",
"&" : "&",
"'" : "'",
"<" : "<",
">" : ">",
// HTML character entity references:
" " : "\u{00A0}",
"¡" : "\u{00A1}",
"¢" : "\u{00A2}",
"£" : "\u{00A3}",
"¤" : "\u{00A4}",
"¥" : "\u{00A5}",
"¦" : "\u{00A6}",
"§" : "\u{00A7}",
"¨" : "\u{00A8}",
"©" : "\u{00A9}",
"ª" : "\u{00AA}",
"«" : "\u{00AB}",
"¬" : "\u{00AC}",
"­" : "\u{00AD}",
"®" : "\u{00AE}",
"¯" : "\u{00AF}",
"°" : "\u{00B0}",
"±" : "\u{00B1}",
"²" : "\u{00B2}",
"³" : "\u{00B3}",
"´" : "\u{00B4}",
"µ" : "\u{00B5}",
"¶" : "\u{00B6}",
"·" : "\u{00B7}",
"¸" : "\u{00B8}",
"¹" : "\u{00B9}",
"º" : "\u{00BA}",
"»" : "\u{00BB}",
"¼" : "\u{00BC}",
"½" : "\u{00BD}",
"¾" : "\u{00BE}",
"¿" : "\u{00BF}",
"À" : "\u{00C0}",
"Á" : "\u{00C1}",
"Â" : "\u{00C2}",
"Ã" : "\u{00C3}",
"Ä" : "\u{00C4}",
"Å" : "\u{00C5}",
"Æ" : "\u{00C6}",
"Ç" : "\u{00C7}",
"È" : "\u{00C8}",
"É" : "\u{00C9}",
"Ê" : "\u{00CA}",
"Ë" : "\u{00CB}",
"Ì" : "\u{00CC}",
"Í" : "\u{00CD}",
"Î" : "\u{00CE}",
"Ï" : "\u{00CF}",
"Ð" : "\u{00D0}",
"Ñ" : "\u{00D1}",
"Ò" : "\u{00D2}",
"Ó" : "\u{00D3}",
"Ô" : "\u{00D4}",
"Õ" : "\u{00D5}",
"Ö" : "\u{00D6}",
"×" : "\u{00D7}",
"Ø" : "\u{00D8}",
"Ù" : "\u{00D9}",
"Ú" : "\u{00DA}",
"Û" : "\u{00DB}",
"Ü" : "\u{00DC}",
"Ý" : "\u{00DD}",
"Þ" : "\u{00DE}",
"ß" : "\u{00DF}",
"à" : "\u{00E0}",
"á" : "\u{00E1}",
"â" : "\u{00E2}",
"ã" : "\u{00E3}",
"ä" : "\u{00E4}",
"å" : "\u{00E5}",
"æ" : "\u{00E6}",
"ç" : "\u{00E7}",
"è" : "\u{00E8}",
"é" : "\u{00E9}",
"ê" : "\u{00EA}",
"ë" : "\u{00EB}",
"ì" : "\u{00EC}",
"í" : "\u{00ED}",
"î" : "\u{00EE}",
"ï" : "\u{00EF}",
"ð" : "\u{00F0}",
"ñ" : "\u{00F1}",
"ò" : "\u{00F2}",
"ó" : "\u{00F3}",
"ô" : "\u{00F4}",
"õ" : "\u{00F5}",
"ö" : "\u{00F6}",
"÷" : "\u{00F7}",
"ø" : "\u{00F8}",
"ù" : "\u{00F9}",
"ú" : "\u{00FA}",
"û" : "\u{00FB}",
"ü" : "\u{00FC}",
"ý" : "\u{00FD}",
"þ" : "\u{00FE}",
"ÿ" : "\u{00FF}",
"Œ" : "\u{0152}",
"œ" : "\u{0153}",
"Š" : "\u{0160}",
"š" : "\u{0161}",
"Ÿ" : "\u{0178}",
"ƒ" : "\u{0192}",
"ˆ" : "\u{02C6}",
"˜" : "\u{02DC}",
"Α" : "\u{0391}",
"Β" : "\u{0392}",
"Γ" : "\u{0393}",
"Δ" : "\u{0394}",
"Ε" : "\u{0395}",
"Ζ" : "\u{0396}",
"Η" : "\u{0397}",
"Θ" : "\u{0398}",
"Ι" : "\u{0399}",
"Κ" : "\u{039A}",
"Λ" : "\u{039B}",
"Μ" : "\u{039C}",
"Ν" : "\u{039D}",
"Ξ" : "\u{039E}",
"Ο" : "\u{039F}",
"Π" : "\u{03A0}",
"Ρ" : "\u{03A1}",
"Σ" : "\u{03A3}",
"Τ" : "\u{03A4}",
"Υ" : "\u{03A5}",
"Φ" : "\u{03A6}",
"Χ" : "\u{03A7}",
"Ψ" : "\u{03A8}",
"Ω" : "\u{03A9}",
"α" : "\u{03B1}",
"β" : "\u{03B2}",
"γ" : "\u{03B3}",
"δ" : "\u{03B4}",
"ε" : "\u{03B5}",
"ζ" : "\u{03B6}",
"η" : "\u{03B7}",
"θ" : "\u{03B8}",
"ι" : "\u{03B9}",
"κ" : "\u{03BA}",
"λ" : "\u{03BB}",
"μ" : "\u{03BC}",
"ν" : "\u{03BD}",
"ξ" : "\u{03BE}",
"ο" : "\u{03BF}",
"π" : "\u{03C0}",
"ρ" : "\u{03C1}",
"ς" : "\u{03C2}",
"σ" : "\u{03C3}",
"τ" : "\u{03C4}",
"υ" : "\u{03C5}",
"φ" : "\u{03C6}",
"χ" : "\u{03C7}",
"ψ" : "\u{03C8}",
"ω" : "\u{03C9}",
"ϑ" : "\u{03D1}",
"ϒ" : "\u{03D2}",
"ϖ" : "\u{03D6}",
" " : "\u{2002}",
" " : "\u{2003}",
" " : "\u{2009}",
"‌" : "\u{200C}",
"‍" : "\u{200D}",
"‎" : "\u{200E}",
"‏" : "\u{200F}",
"–" : "\u{2013}",
"—" : "\u{2014}",
"‘" : "\u{2018}",
"’" : "\u{2019}",
"‚" : "\u{201A}",
"“" : "\u{201C}",
"”" : "\u{201D}",
"„" : "\u{201E}",
"†" : "\u{2020}",
"‡" : "\u{2021}",
"•" : "\u{2022}",
"…" : "\u{2026}",
"‰" : "\u{2030}",
"′" : "\u{2032}",
"″" : "\u{2033}",
"‹" : "\u{2039}",
"›" : "\u{203A}",
"‾" : "\u{203E}",
"⁄" : "\u{2044}",
"€" : "\u{20AC}",
"ℑ" : "\u{2111}",
"℘" : "\u{2118}",
"ℜ" : "\u{211C}",
"™" : "\u{2122}",
"ℵ" : "\u{2135}",
"←" : "\u{2190}",
"↑" : "\u{2191}",
"→" : "\u{2192}",
"↓" : "\u{2193}",
"↔" : "\u{2194}",
"↵" : "\u{21B5}",
"⇐" : "\u{21D0}",
"⇑" : "\u{21D1}",
"⇒" : "\u{21D2}",
"⇓" : "\u{21D3}",
"⇔" : "\u{21D4}",
"∀" : "\u{2200}",
"∂" : "\u{2202}",
"∃" : "\u{2203}",
"∅" : "\u{2205}",
"∇" : "\u{2207}",
"∈" : "\u{2208}",
"∉" : "\u{2209}",
"∋" : "\u{220B}",
"∏" : "\u{220F}",
"∑" : "\u{2211}",
"−" : "\u{2212}",
"∗" : "\u{2217}",
"√" : "\u{221A}",
"∝" : "\u{221D}",
"∞" : "\u{221E}",
"∠" : "\u{2220}",
"∧" : "\u{2227}",
"∨" : "\u{2228}",
"∩" : "\u{2229}",
"∪" : "\u{222A}",
"∫" : "\u{222B}",
"∴" : "\u{2234}",
"∼" : "\u{223C}",
"≅" : "\u{2245}",
"≈" : "\u{2248}",
"≠" : "\u{2260}",
"≡" : "\u{2261}",
"≤" : "\u{2264}",
"≥" : "\u{2265}",
"⊂" : "\u{2282}",
"⊃" : "\u{2283}",
"⊄" : "\u{2284}",
"⊆" : "\u{2286}",
"⊇" : "\u{2287}",
"⊕" : "\u{2295}",
"⊗" : "\u{2297}",
"⊥" : "\u{22A5}",
"⋅" : "\u{22C5}",
"⌈" : "\u{2308}",
"⌉" : "\u{2309}",
"⌊" : "\u{230A}",
"⌋" : "\u{230B}",
"⟨" : "\u{2329}",
"⟩" : "\u{232A}",
"◊" : "\u{25CA}",
"♠" : "\u{2660}",
"♣" : "\u{2663}",
"♥" : "\u{2665}",
"♦" : "\u{2666}",
]
}
// Convert the number in the string to the corresponding
// Unicode character, e.g.
// decodeNumeric("64", 10) --> "@"
// decodeNumeric("20ac", 16) --> "€"
fileprivate func decodeNumeric(_ string : String, base : Int32) -> Character? {
let code = UInt32(strtoul(string, nil, base))
return Character(UnicodeScalar(code)!)
}
// Decode the HTML character entity to the corresponding
// Unicode character, return `nil` for invalid input.
// decode("@") --> "@"
// decode("€") --> "€"
// decode("<") --> "<"
// decode("&foo;") --> nil
fileprivate func decode(_ entity : String) -> Character? {
if entity.hasPrefix("&#x") || entity.hasPrefix("&#X"){
return decodeNumeric(entity.substring(from: entity.index(entity.startIndex, offsetBy: 3)), base: 16)
} else if entity.hasPrefix("&#") {
return decodeNumeric(entity.substring(from: entity.index(entity.startIndex, offsetBy: 2)), base: 10)
} else {
return HTMLEntities.characterEntities[entity]
}
}
/// Returns a new string made by replacing in the `String`
/// all HTML character entity references with the corresponding
/// character.
func decodeHTML() -> String {
var result = ""
var position = startIndex
// Find the next '&' and copy the characters preceding it to `result`:
while let ampRange = self.range(of: "&", range: position ..< endIndex) {
result.append(self[position ..< ampRange.lowerBound])
position = ampRange.lowerBound
// Find the next ';' and copy everything from '&' to ';' into `entity`
if let semiRange = self.range(of: ";", range: position ..< endIndex) {
let entity = self[position ..< semiRange.upperBound]
position = semiRange.upperBound
if let decoded = decode(entity) {
// Replace by decoded character:
result.append(decoded)
} else {
// Invalid entity, copy verbatim:
result.append(entity)
}
} else {
// No matching ';'.
break
}
}
// Copy remaining characters to `result`:
result.append(self[position ..< endIndex])
return result
}
}
|
gpl-3.0
|
95f098f002ee208d4d9b5d70e0c2d81d
| 37.682927 | 112 | 0.312027 | 3.31886 | false | false | false | false |
MYLILUYANG/xinlangweibo
|
xinlangweibo/xinlangweibo/Class/Home/LYPresentationManager.swift
|
1
|
4130
|
//
// LYPresentationManager.swift
// xinlangweibo
//
// Created by liluyang on 2017/3/5.
// Copyright © 2017年 liluyang. All rights reserved.
//
import UIKit
class LYPresentationManager: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning
{
//定义标记 记录当前是否是展现或者消失
var isPrsent = false;
var presentViewFrame:CGRect = CGRect.zero;
//MARK: - UIViewControllerTransitioningDelegate
//该方法用户返回一个负责转场动画的对象
public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?
{
let presentViewController = LYPresentationController(presentedViewController: presented, presenting: presenting)
presentViewController.presentViewFrame = presentViewFrame;
return presentViewController
}
//返回一个负责转场动画如何出现的对象
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: LYPresentationManagerDidPresented), object: self)
isPrsent = true;
return self;
}
//返回一个转场动画如何消失的对象
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
NotificationCenter.default.post(name: NSNotification.Name(LYPresentationManagerDidDismiss), object: self)
isPrsent = false;
return self;
}
//MARK: - UIPresentationController
//告诉系统展现和小时的动画时长
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval
{
return 12;
}
//专门用于管理modal如何展现和消失的,无论展现还是消失都会调用该方法,
//只要实现这个方法系统就不会有默认动画
//默认的modal 自下到上移动 就消失了----所有的动画操作都都需要我们自己实现,包括需要展现的视图也需要我们自己添加到容器视图上
/*
transitionContext 所有动画需要的东西都保存在上下文中,可以通过transitionContext 获取我们想要的东西
*/
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning)
{
if isPrsent
{
willPresentedController(using: transitionContext)
}else
{
willDismissdController(using: transitionContext);
}
}
//执行展现动画
private func willPresentedController(using transitionContext: UIViewControllerContextTransitioning){
//获取需要弹出的视图
guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else {
return;
}
// 将需要弹出的视图添加到contentview 上
transitionContext.containerView.addSubview(toView)
//执行动画
toView.transform = CGAffineTransform(scaleX: 1.0, y: 0)
toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
UIView.animate(withDuration: 0.5, animations: {
toView.transform = .identity
}) { (_) in
//自定义转场,在执行动画完毕后一定要告诉系统动画执行完毕
transitionContext.completeTransition(true)
}
}
//执行消失动画
private func willDismissdController(using transitionContext: UIViewControllerContextTransitioning){
//获取应该消失的view
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from);
//执行消失的动画
UIView.animate(withDuration: 0.5, animations: {
fromView?.transform = CGAffineTransform.init(scaleX: 1.0, y: 0.0000000001)
}, completion: { (true) in
transitionContext.completeTransition(true)
})
}
}
|
gpl-3.0
|
91f0e91b05c10289248553ce9fe37ba2
| 36.648936 | 175 | 0.706414 | 4.963534 | false | false | false | false |
kandelvijaya/XcodeFormatter
|
XcodeFormatterExtension/SourceEditorCommand.swift
|
1
|
5878
|
//
// SourceEditorCommand.swift
// Linter
//
// Created by Vijaya Prakash Kandel on 9/11/16.
// Copyright © 2016 Vijaya Prakash Kandel. All rights reserved.
//
import Foundation
import XcodeKit
class SourceEditorCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void {
switch invocation.commandIdentifier {
case CommandIdentifier.finilizeClass.rawValue:
markClassFinalUnlessOpenSpecified(invocation: invocation)
case CommandIdentifier.correctInterSpace.rawValue:
ensureProperSpacing(invocation: invocation)
case CommandIdentifier.correctEmptyLine.rawValue:
ensureProperEmptyLines(invocation: invocation)
case CommandIdentifier.correctComment.rawValue:
ensureProperFileComment(invocation: invocation)
case CommandIdentifier.swiftlyLintAll.rawValue:
ensureProperSpacing(invocation: invocation)
ensureProperEmptyLines(invocation: invocation)
ensureProperFileComment(invocation: invocation)
default:
break
}
completionHandler(nil)
}
//MARK:- Private Methods
fileprivate func forEachLine(invocation: XCSourceEditorCommandInvocation, check: (String) -> String?) {
let originalLines = invocation.buffer.lines
var changed: [Int: String] = [:]
for (counter, lineContent) in originalLines.enumerated() {
let lineString = String(describing: lineContent)
if let modified = check(lineString) {
changed[counter] = modified
}
}
//mdofiy the lines array
changed.forEach{ invocation.buffer.lines[$0] = $1 }
}
}
extension SourceEditorCommand {
/// Makes class declaration final
/// Note: This doesnot check for 2 things
/// 1. Inheritance tree. This could be added sometime later.
/// 2. Inner classes are also finilized
///
/// - parameter invocation: Text Buffer
func markClassFinalUnlessOpenSpecified(invocation: XCSourceEditorCommandInvocation) {
forEachLine(invocation: invocation) { lineString in
var string = lineString
let contains = ["class ", " class "]
let doesnotContain = ["final ", "open ", ".class"]
//If the line has " class " or "class "
//And it doesnot have "final ", "open " or ".class" then it sounds like a class declaration
guard string.contains(contains[0]) || string.contains(contains[1]) else { return nil }
//Check if line contains keyword inside a quote
guard !string.contains("\"") else { return nil }
//TODO: classes inside should not be finilized
guard doesnotContain.map(string.contains).filter({ $0 == true }).count == 0 else { return nil}
let range = string.range(of: "class")
let startIndex = range?.lowerBound
string.insert(contentsOf: "final ", at: startIndex!)
return string
}
}
}
extension SourceEditorCommand {
/// Checks for the proper spacing in mostly 4 places
/// 1. Trailing ) { in function declaration
/// 2. Type information i.e. let x: String
/// 3. Dictionary type info i.e [String: Int] or ["a": "apple"]
/// 4. Space after a comma i.e ["a": "apple", "b": "ball"] or sum(1, 2)
///
/// - parameter invocation: Text Buffer
func ensureProperSpacing(invocation: XCSourceEditorCommandInvocation) {
let spaceLinter = LintSpace()
forEachLine(invocation: invocation) { strings in
let allCorrected = [strings]
.map { spaceLinter.correctColonSpace(line: $0) }
.map { spaceLinter.correctCommaSeparation(line: $0) }
.map { spaceLinter.correctTernaryOperator(line: $0) }
.map { spaceLinter.correctFunctionReturnArrow(line: $0) }
.map { spaceLinter.correctTrailingCurlyBracket(line: $0) }
.first
return allCorrected
}
}
}
extension SourceEditorCommand {
//NOTE: App seems to crash when mutating the complete buffer directly.
func ensureProperFileComment(invocation: XCSourceEditorCommandInvocation) {
let newFileCommentLines = LintFileComment().extractNewCommentLines(from: invocation.buffer.completeBuffer)
guard !newFileCommentLines.isEmpty else { return }
//There usually are 7 lines of default Xcode comment template.
(0..<7).forEach{ _ in invocation.buffer.lines.removeObject(at: 0) }
for value in newFileCommentLines.reversed() {
invocation.buffer.lines.insert(value, at: 0)
}
}
}
extension SourceEditorCommand {
//1. Ensure empty lines at opening and ending of code blocks for Types
// Protocol | enum | struct | class
//2. Ensure 1 empty line at the EOF
//3. Ensure 1 empty line between functions
//4. Ensure 1 empty line before and after
//
// NOTE: Mutation was preferred over to immutability assignment
// due to the fact that app crashed randomly when doing so
//
// invocation.buffer.lines.removeAll()
// correctedLines.forEach {
// invocation.buffer.lines.add($0)
// }
//
//
func ensureProperEmptyLines(invocation: XCSourceEditorCommandInvocation) {
LintLine().ensureProperEmptyLines(in: invocation.buffer.lines)
}
}
extension String: Collection {}
|
mit
|
32c2d41e888d8583f7c98e592711ea69
| 35.503106 | 124 | 0.61511 | 4.922111 | false | false | false | false |
zhangzichen/Pontus
|
Pontus/UIKit+Pontus/UILabel+Pontus.swift
|
1
|
864
|
import Foundation
import UIKit
public extension UILabel {
public func numberOfLines(_ numberOfLines : Int) -> Self {
self.numberOfLines = numberOfLines
return self
}
}
extension UILabel : HasText {
public var h_text : String {
get {
return text ?? ""
}
set {
text = newValue
}
}
public var h_textColor : UIColor {
get {
return textColor
}
set {
textColor = newValue
}
}
public var h_font : UIFont {
get {
return font
}
set {
font = newValue
}
}
public var h_textAlignment : NSTextAlignment {
get {
return textAlignment
}
set {
textAlignment = newValue
}
}
}
|
mit
|
1deddc9e8723b507cab1261865d0810b
| 15.615385 | 62 | 0.461806 | 5.300613 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.