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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jverkoey/FigmaKit | Sources/FigmaKit/BlendMode.swift | 1 | 926 | /// A Figma blend mode.
///
/// "Enum describing how layer blends with layers below."
/// https://www.figma.com/developers/api#blendmode-type
public enum BlendMode: String, Codable {
// MARK: Normal blends
case normal = "NORMAL"
/// Only applicable to objects with children.
case passThrough = "PASS_THROUGH"
// MARK: Darken
case darken = "DARKEN"
case multiply = "MULTIPLY"
case linearBurn = "LINEAR_BURN"
case colorBurn = "COLOR_BURN"
// MARK: Lighten
case lighten = "LIGHTEN"
case screen = "SCREEN"
case linearDoge = "LINEAR_DOGE"
case colorDoge = "COLOR_DODGE"
// MARK: Contrast
case overlay = "OVERLAY"
case softLight = "SOFT_LIGHT"
case hardLight = "HARD_LIGHT"
// MARK: Inversion
case difference = "DIFFERENCE"
case exclusion = "EXCLUSION"
// MARK: Component
case hue = "HUE"
case saturation = "SATURATION"
case color = "COLOR"
case luminosity = "LUMINOSITY"
}
| apache-2.0 | 86db218712093dc98616b303a069d370 | 23.368421 | 57 | 0.677106 | 3.442379 | false | false | false | false |
relayrides/objective-c-sdk | Pods/Mixpanel-swift/Mixpanel/ObjectFilter.swift | 1 | 6279 | //
// ObjectFilter.swift
// Mixpanel
//
// Created by Yarden Eitan on 8/24/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
import UIKit
class ObjectFilter: CustomStringConvertible {
var name: String? = nil
var predicate: NSPredicate? = nil
var index: Int? = nil
var unique: Bool
var nameOnly: Bool
init() {
self.unique = false
self.nameOnly = false
}
var description: String {
return "name: \(name), index: \(index), predicate: \(predicate)]"
}
func apply(on views: [AnyObject]) -> [AnyObject] {
var result = [AnyObject]()
let currentClass: AnyClass? = NSClassFromString(name!)
if currentClass != nil || name == "*" {
for view in views {
var children = getChildren(of: view, searchClass: currentClass)
if let index = index, index < children.count {
if view.isKind(of: UIView.self) {
children = [children[index]]
} else {
children = []
}
}
result += children
}
}
if !nameOnly {
if unique && result.count != 1 {
return []
}
if let predicate = predicate {
return result.filter { predicate.evaluate(with: $0) }
}
}
return result
}
/*
Apply this filter to the views. For any view that
matches this filter's class / predicate pattern, return
its parents.
*/
func applyReverse(on views: [AnyObject]) -> [AnyObject] {
var result = [AnyObject]()
for view in views {
if doesApply(on: view) {
result += getParents(of: view)
}
}
return result
}
/*
Returns whether the given view would pass this filter.
*/
func doesApply(on view: AnyObject) -> Bool {
let typeValidation = name == "*" || (name != nil && NSClassFromString(name!) != nil && view.isKind(of: NSClassFromString(name!)!))
let predicateValidation = predicate == nil || predicate!.evaluate(with: view)
let indexValidation = index == nil || isSibling(view, at: index!)
let uniqueValidation = !unique || isSibling(view, of: 1)
return typeValidation && (nameOnly || (predicateValidation && indexValidation && uniqueValidation))
}
/*
Returns whether any of the given views would pass this filter
*/
func doesApply(on views: [AnyObject]) -> Bool {
for view in views {
if doesApply(on: view) {
return true
}
}
return false
}
/*
Returns true if the given view is at the index given by number in
its parent's subviews. The view's parent must be of type UIView
*/
func isSibling(_ view: AnyObject, at index: Int) -> Bool {
return isSibling(view, at: index, of: nil)
}
func isSibling(_ view: AnyObject, of count: Int) -> Bool {
return isSibling(view, at: nil, of: count)
}
func isSibling(_ view: AnyObject, at index: Int?, of count: Int?) -> Bool {
guard let name = name else {
return false
}
let parents = self.getParents(of: view)
for parent in parents {
if let parent = parent as? UIView {
let siblings = getChildren(of: parent, searchClass: NSClassFromString(name))
if index == nil || (index! < siblings.count && siblings[index!] === view) && (count == nil || siblings.count == count!) {
return true
}
}
}
return false
}
func getParents(of object: AnyObject) -> [AnyObject] {
var result = [AnyObject]()
if let object = object as? UIView {
if let superview = object.superview {
result.append(superview)
}
if let nextResponder = object.next, nextResponder != object.superview {
result.append(nextResponder)
}
} else if let object = object as? UIViewController {
if let parentViewController = object.parent {
result.append(parentViewController)
}
if let presentingViewController = object.presentingViewController {
result.append(presentingViewController)
}
if let keyWindow = UIApplication.shared.keyWindow, keyWindow.rootViewController == object {
result.append(keyWindow)
}
}
return result
}
func getChildren(of object: AnyObject, searchClass: AnyClass?) -> [AnyObject] {
var children = [AnyObject]()
if let window = object as? UIWindow,
let rootVC = window.rootViewController,
let sClass = searchClass,
rootVC.isKind(of: sClass) {
children.append(rootVC)
} else if let view = object as? UIView {
for subview in view.subviews {
if searchClass == nil || subview.isKind(of: searchClass!) {
children.append(subview)
}
}
} else if let viewController = object as? UIViewController {
for child in viewController.childViewControllers {
if searchClass == nil || child.isKind(of: searchClass!) {
children.append(child)
}
}
if let presentedVC = viewController.presentedViewController,
(searchClass == nil || presentedVC.isKind(of: searchClass!)) {
children.append(presentedVC)
}
if viewController.isViewLoaded && (searchClass == nil || viewController.view.isKind(of: searchClass!)) {
children.append(viewController.view)
}
}
// Reorder the cells in a table view so that they are arranged by y position
if let sClass = searchClass, sClass.isSubclass(of: UITableViewCell.self) {
children.sort {
return $0.frame.origin.y < $1.frame.origin.y
}
}
return children
}
}
| apache-2.0 | adc1b5cfcf6e39be15c37d006f23649f | 31.360825 | 138 | 0.545715 | 4.851623 | false | false | false | false |
dreymonde/SwiftyNURE | Sources/SwiftyNURE/Providers/TeachersProvider.swift | 1 | 1757 | //
// TeachersProvider.swift
// NUREAPI
//
// Created by Oleg Dreyman on 20.02.16.
// Copyright © 2016 Oleg Dreyman. All rights reserved.
//
import Foundation
import EezehRequests
public protocol TeachersProviderType: Receivable {
associatedtype ATeacher = TeacherType
var completion: ([ATeacher] -> Void) { get }
var error: (ErrorType -> Void)? { get set }
func execute() -> Void
}
public struct TeachersProvider {
public class Remote: TeachersProviderType {
public let completion: ([Teacher.Extended] -> Void)
public var error: (ErrorType -> Void)?
private let filter: String?
public init(matching filter: String?, _ completion: ([Teacher.Extended] -> Void)) {
self.filter = filter
self.completion = completion
}
public convenience init(completion: ([Teacher.Extended] -> Void)) {
self.init(matching: nil, completion)
}
public func execute() {
let request = JSONRequest(.GET, url: NURE.apiTeachersJson) { jsonResponse in
let json = jsonResponse.data
if let teachers = TeachersCISTParser.parse(fromJSON: json) {
self.completion(teachers.filter({ $0.isConforming(toString: self.filter) }))
return
}
self.error?(RequestError.JsonParseNull)
}
request.error = pushError
request.execute()
}
}
}
extension Teacher.Extended {
func isConforming(toString filter: String?) -> Bool {
return fullName.containsOptionalString(filter) || shortName.containsOptionalString(filter) || department.isConforming(filter) || faculty.isConforming(filter)
}
}
| mit | 83eec3c3e40b8da2a1427ca4d1bc26be | 27.322581 | 165 | 0.619021 | 4.479592 | false | false | false | false |
hooman/swift | test/DebugInfo/returnlocation.swift | 3 | 6748 | // RUN: %target-swift-frontend -g -emit-ir %s -o %t.ll
// REQUIRES: objc_interop
import Foundation
// This file contains linetable testcases for all permutations
// of simple/complex/empty return expressions,
// cleanups/no cleanups, single / multiple return locations.
// RUN: %FileCheck %s --check-prefix=CHECK_NONE < %t.ll
// CHECK_NONE: define{{( protected)?}} {{.*}}void {{.*}}none
public func none(_ a: inout Int64) {
// CHECK_NONE: call void @llvm.dbg{{.*}}, !dbg
// CHECK_NONE: store i64{{.*}}, !dbg ![[NONE_INIT:.*]]
a -= 2
// CHECK_NONE: ret {{.*}}, !dbg ![[NONE_RET:.*]]
// CHECK_NONE: ![[NONE_INIT]] = !DILocation(line: [[@LINE-2]], column:
// CHECK_NONE: ![[NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_EMPTY < %t.ll
// CHECK_EMPTY: define {{.*}}empty
public func empty(_ a: inout Int64) {
if a > 24 {
// CHECK-DAG_EMPTY: br {{.*}}, !dbg ![[EMPTY_RET1:.*]]
// CHECK-DAG_EMPTY_RET1: ![[EMPTY_RET1]] = !DILocation(line: [[@LINE+1]], column: 6,
return
}
a -= 2
// CHECK-DAG_EMPTY: br {{.*}}, !dbg ![[EMPTY_RET2:.*]]
// CHECK-DAG_EMPTY_RET2: ![[EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 3,
return
// CHECK-DAG_EMPTY: ret {{.*}}, !dbg ![[EMPTY_RET:.*]]
// CHECK-DAG_EMPTY: ![[EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_EMPTY_NONE < %t.ll
// CHECK_EMPTY_NONE: define {{.*}}empty_none
public func empty_none(_ a: inout Int64) {
if a > 24 {
return
}
a -= 2
// CHECK_EMPTY_NONE: ret {{.*}}, !dbg ![[EMPTY_NONE_RET:.*]]
// CHECK_EMPTY_NONE: ![[EMPTY_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_SIMPLE_RET < %t.ll
// CHECK_SIMPLE_RET: define {{.*}}simple
public func simple(_ a: Int64) -> Int64 {
if a > 24 {
return 0
}
return 1
// CHECK_SIMPLE_RET: ret i{{.*}}, !dbg ![[SIMPLE_RET:.*]]
// CHECK_SIMPLE_RET: ![[SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_COMPLEX_RET < %t.ll
// CHECK_COMPLEX_RET: define {{.*}}complex
public func complex(_ a: Int64) -> Int64 {
if a > 24 {
return a*a
}
return a/2
// CHECK_COMPLEX_RET: ret i{{.*}}, !dbg ![[COMPLEX_RET:.*]]
// CHECK_COMPLEX_RET: ![[COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_COMPLEX_SIMPLE < %t.ll
// CHECK_COMPLEX_SIMPLE: define {{.*}}complex_simple
public func complex_simple(_ a: Int64) -> Int64 {
if a > 24 {
return a*a
}
return 2
// CHECK_COMPLEX_SIMPLE: ret i{{.*}}, !dbg ![[COMPLEX_SIMPLE_RET:.*]]
// CHECK_COMPLEX_SIMPLE: ![[COMPLEX_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_SIMPLE_COMPLEX < %t.ll
// CHECK_SIMPLE_COMPLEX: define {{.*}}simple_complex
public func simple_complex(_ a: Int64) -> Int64 {
if a > 24 {
return a*a
}
return 2
// CHECK_SIMPLE_COMPLEX: ret {{.*}}, !dbg ![[SIMPLE_COMPLEX_RET:.*]]
// CHECK_SIMPLE_COMPLEX: ![[SIMPLE_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// ---------------------------------------------------------------------
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_NONE < %t.ll
// CHECK_CLEANUP_NONE: define {{.*}}cleanup_none
public func cleanup_none(_ a: inout NSString) {
a = "empty"
// CHECK_CLEANUP_NONE: ret void, !dbg ![[CLEANUP_NONE_RET:.*]]
// CHECK_CLEANUP_NONE: ![[CLEANUP_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_EMPTY < %t.ll
// CHECK_CLEANUP_EMPTY: define {{.*}}cleanup_empty
public func cleanup_empty(_ a: inout NSString) {
if a.length > 24 {
return
}
a = "empty"
return
// CHECK_CLEANUP_EMPTY: ret void, !dbg ![[CLEANUP_EMPTY_RET:.*]]
// CHECK_CLEANUP_EMPTY: ![[CLEANUP_EMPTY_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_EMPTY_NONE < %t.ll
// CHECK_CLEANUP_EMPTY_NONE: define {{.*}}cleanup_empty_none
public func cleanup_empty_none(_ a: inout NSString) {
if a.length > 24 {
return
}
a = "empty"
// CHECK_CLEANUP_EMPTY_NONE: ret {{.*}}, !dbg ![[CLEANUP_EMPTY_NONE_RET:.*]]
// CHECK_CLEANUP_EMPTY_NONE: ![[CLEANUP_EMPTY_NONE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_SIMPLE_RET < %t.ll
// CHECK_CLEANUP_SIMPLE_RET: define {{.*}}cleanup_simple
public func cleanup_simple(_ a: NSString) -> Int64 {
if a.length > 24 {
return 0
}
return 1
// CHECK_CLEANUP_SIMPLE_RET: ret {{.*}}, !dbg ![[CLEANUP_SIMPLE_RET:.*]]
// CHECK_CLEANUP_SIMPLE_RET: ![[CLEANUP_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_COMPLEX < %t.ll
// CHECK_CLEANUP_COMPLEX: define {{.*}}cleanup_complex
public func cleanup_complex(_ a: NSString) -> Int64 {
if a.length > 24 {
return Int64(a.length*a.length)
}
return Int64(a.length/2)
// CHECK_CLEANUP_COMPLEX: ret i{{.*}}, !dbg ![[CLEANUP_COMPLEX_RET:.*]]
// CHECK_CLEANUP_COMPLEX: ![[CLEANUP_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_COMPLEX_SIMPLE < %t.ll
// CHECK_CLEANUP_COMPLEX_SIMPLE: define {{.*}}cleanup_complex_simple
public func cleanup_complex_simple(_ a: NSString) -> Int64 {
if a.length > 24 {
return Int64(a.length*a.length)
}
return 2
// CHECK_CLEANUP_COMPLEX_SIMPLE: ret i{{.*}}, !dbg ![[CLEANUP_COMPLEX_SIMPLE_RET:.*]]
// CHECK_CLEANUP_COMPLEX_SIMPLE: ![[CLEANUP_COMPLEX_SIMPLE_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// RUN: %FileCheck %s --check-prefix=CHECK_CLEANUP_SIMPLE_COMPLEX < %t.ll
// CHECK_CLEANUP_SIMPLE_COMPLEX: define {{.*}}cleanup_simple_complex
public func cleanup_simple_complex(_ a: NSString) -> Int64 {
if a.length > 24 {
return Int64(a.length*a.length)
}
return 2
// CHECK_CLEANUP_SIMPLE_COMPLEX: ret i{{.*}}, !dbg ![[CLEANUP_SIMPLE_COMPLEX_RET:.*]]
// CHECK_CLEANUP_SIMPLE_COMPLEX: ![[CLEANUP_SIMPLE_COMPLEX_RET]] = !DILocation(line: [[@LINE+1]], column: 1,
}
// ---------------------------------------------------------------------
// RUN: %FileCheck %s --check-prefix=CHECK_INIT < %t.ll
// CHECK_INIT: define {{.*}}$s4main6Class1CACSgycfc
public class Class1 {
public required init?() {
print("hello")
// CHECK_INIT: call {{.*}}@"$ss5print_9separator10terminatoryypd_S2StF"{{.*}}, !dbg [[printLoc:![0-9]+]]
// FIXME: Why doesn't ret have the correct line number?
// CHECK_INIT: ret i{{32|64}} 0, !dbg [[printLoc]]
// CHECK_INIT: [[printLoc]] = !DILocation(line: [[@LINE-4]]
return nil
}
}
| apache-2.0 | ae4d525bc649011bb5c4265593e174e7 | 34.145833 | 110 | 0.601215 | 3.153271 | false | false | false | false |
lorentey/swift | test/Generics/associated_type_where_clause.swift | 18 | 5844 | // RUN: %target-typecheck-verify-swift -swift-version 4
func needsSameType<T>(_: T.Type, _: T.Type) {}
protocol Foo {}
func needsFoo<T: Foo>(_: T.Type) {}
protocol Foo2 {}
func needsFoo2<T: Foo2>(_: T.Type) {}
extension Int: Foo, Foo2 {}
extension Float: Foo {}
protocol Conforms {
associatedtype T where T: Foo
}
func needsConforms<X: Conforms>(_: X.Type) {
needsFoo(X.T.self)
}
struct ConcreteConforms: Conforms { typealias T = Int }
struct ConcreteConforms2: Conforms { typealias T = Int }
struct ConcreteConformsNonFoo2: Conforms { typealias T = Float }
protocol NestedConforms {
associatedtype U where U: Conforms, U.T: Foo2 // expected-note{{protocol requires nested type 'U'; do you want to add it?}}
func foo(_: U)
}
extension NestedConforms { func foo(_: U) {} }
func needsNestedConforms<X: NestedConforms>(_: X.Type) {
needsConforms(X.U.self)
needsFoo(X.U.T.self)
needsFoo2(X.U.T.self)
}
struct ConcreteNestedConforms: NestedConforms {
typealias U = ConcreteConforms
}
struct ConcreteNestedConformsInfer: NestedConforms {
func foo(_: ConcreteConforms) {}
}
struct BadConcreteNestedConforms: NestedConforms {
// expected-error@-1 {{type 'ConcreteConformsNonFoo2.T' (aka 'Float') does not conform to protocol 'Foo2'}}
typealias U = ConcreteConformsNonFoo2
}
struct BadConcreteNestedConformsInfer: NestedConforms {
// expected-error@-1 {{type 'BadConcreteNestedConformsInfer' does not conform to protocol 'NestedConforms'}}
func foo(_: ConcreteConformsNonFoo2) {}
}
protocol NestedConformsDefault {
associatedtype U = ConcreteConforms where U: Conforms, U.T: Foo2
}
struct ConcreteNestedConformsDefaultDefaulted: NestedConformsDefault {}
struct ConcreteNestedConformsDefault: NestedConformsDefault {
typealias U = ConcreteConforms2
}
func needsNestedConformsDefault<X: NestedConformsDefault>(_: X.Type) {
needsConforms(X.U.self)
needsFoo(X.U.T.self)
needsFoo2(X.U.T.self)
}
protocol NestedSameType {
associatedtype U: Conforms where U.T == Int // expected-note{{protocol requires nested type 'U'; do you want to add it?}}
func foo(_: U)
}
extension NestedSameType { func foo(_: U) {} }
func needsNestedSameType<X: NestedSameType>(_: X.Type) {
needsConforms(X.U.self)
needsSameType(X.U.T.self, Int.self)
}
struct BadConcreteNestedSameType: NestedSameType {
// expected-error@-1 {{'NestedSameType' requires the types 'ConcreteConformsNonFoo2.T' (aka 'Float') and 'Int' be equivalent}}
// expected-note@-2 {{requirement specified as 'Self.U.T' == 'Int' [with Self = BadConcreteNestedSameType]}}
typealias U = ConcreteConformsNonFoo2
}
struct BadConcreteNestedSameTypeInfer: NestedSameType {
// expected-error@-1 {{type 'BadConcreteNestedSameTypeInfer' does not conform to protocol 'NestedSameType'}}
func foo(_: ConcreteConformsNonFoo2) {}
}
protocol NestedSameTypeDefault {
associatedtype U: Conforms = ConcreteConforms where U.T == Int
func foo(_: U)
}
extension NestedSameTypeDefault { func foo(_: U) {} }
func needsNestedSameTypeDefault<X: NestedSameTypeDefault>(_: X.Type) {
needsConforms(X.U.self)
needsSameType(X.U.T.self, Int.self)
}
struct ConcreteNestedSameTypeDefaultDefaulted: NestedSameTypeDefault {}
struct ConcreteNestedSameTypeDefault: NestedSameTypeDefault {
typealias U = ConcreteConforms2
}
struct ConcreteNestedSameTypeDefaultInfer: NestedSameTypeDefault {
func foo(_: ConcreteConforms2) {}
}
protocol Inherits: NestedConforms {
associatedtype X: Conforms where X.T == U.T
func bar(_: X)
}
extension Inherits { func bar(_: X) {} }
func needsInherits<X: Inherits>(_: X.Type) {
needsConforms(X.U.self)
needsConforms(X.X.self)
needsSameType(X.U.T.self, X.X.T.self)
}
struct ConcreteInherits: Inherits {
typealias U = ConcreteConforms
typealias X = ConcreteConforms
}
struct ConcreteInheritsDiffer: Inherits {
typealias U = ConcreteConforms
typealias X = ConcreteConforms2
}
/*
FIXME: the sametype requirement gets dropped from the requirement signature
(enumerateRequirements doesn't yield it), so this doesn't error as it should.
struct BadConcreteInherits: Inherits {
typealias U = ConcreteConforms
typealias X = ConcreteConformsNonFoo2
}
*/
struct X { }
protocol P {
associatedtype P1 where P1 == X
// expected-note@-1{{same-type constraint 'Self.P1' == 'X' written here}}
associatedtype P2 where P2 == P1, P2 == X
// expected-warning@-1{{redundant same-type constraint 'Self.P2' == 'X'}}
}
// Lookup of same-named associated types aren't ambiguous in this context.
protocol P1 {
associatedtype A
}
protocol P2: P1 {
associatedtype A
associatedtype B where A == B
}
protocol P3: P1 {
associatedtype A
}
protocol P4 {
associatedtype A
}
protocol P5: P3, P4 {
associatedtype B where B == A?
}
// Associated type inference should account for where clauses.
protocol P6 {
associatedtype A
}
struct X1 { }
struct X2 { }
struct Y1 : P6 {
typealias A = X1
}
struct Y2 : P6 {
typealias A = X2
}
protocol P7 {
associatedtype B: P6 // expected-note{{ambiguous inference of associated type 'B': 'Y1' vs. 'Y2'}}
associatedtype C: P6 where B.A == C.A
func getB() -> B
func getC() -> C
}
struct Z1 : P7 {
func getB() -> Y1 { return Y1() }
func getB() -> Y2 { return Y2() }
func getC() -> Y1 { return Y1() }
}
func testZ1(z1: Z1) {
let _: Z1.C = Y1()
}
struct Z2 : P7 { // expected-error{{type 'Z2' does not conform to protocol 'P7'}}
func getB() -> Y1 { return Y1() } // expected-note{{matching requirement 'getB()' to this declaration inferred associated type to 'Y1'}}
func getB() -> Y2 { return Y2() } // expected-note{{matching requirement 'getB()' to this declaration inferred associated type to 'Y2'}}
func getC() -> Y1 { return Y1() }
func getC() -> Y2 { return Y2() }
}
| apache-2.0 | a70350b2ee4b8b94ba2aea3ec88196fb | 27.788177 | 138 | 0.709446 | 3.539673 | false | false | false | false |
kelby/TreeTableVIewWithSwift | TreeTableVIewWithSwift/TreeTableView.swift | 1 | 4632 | //
// TreeTableView.swift
// TreeTableVIewWithSwift
//
// Created by Robert Zhang on 15/10/24.
// Copyright © 2015年 robertzhang. All rights reserved.
//
import UIKit
protocol TreeTableViewCellDelegate: NSObjectProtocol {
func cellClick() //参数还没加,TreeNode表示节点
}
class TreeTableView: UITableView, UITableViewDataSource,UITableViewDelegate{
var mAllNodes: [TreeNode]? //所有的node
var mNodes: [TreeNode]? //可见的node
// var treeTableViewCellDelegate: TreeTableViewCellDelegate?
let NODE_CELL_ID: String = "nodecell"
init(frame: CGRect, withData data: [TreeNode]) {
super.init(frame: frame, style: UITableViewStyle.Plain)
self.delegate = self
self.dataSource = self
mAllNodes = data
mNodes = TreeNodeHelper.sharedInstance.filterVisibleNode(mAllNodes!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// =================================================================================
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 通过nib自定义tableviewcell
let nib = UINib(nibName: "TreeNodeTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: NODE_CELL_ID)
let cell = tableView.dequeueReusableCellWithIdentifier(NODE_CELL_ID) as! TreeNodeTableViewCell
let node: TreeNode = mNodes![indexPath.row]
//cell缩进
cell.background.bounds.origin.x = -20.0 * CGFloat(node.getLevel())
//代码修改nodeIMG---UIImageView的显示模式.
if node.type == TreeNode.NODE_TYPE_G {
cell.nodeIMG.contentMode = UIViewContentMode.Center
cell.nodeIMG.image = UIImage(named: node.icon!)
} else {
cell.nodeIMG.image = nil
}
cell.nodeName.text = node.name
cell.nodeDesc.text = node.desc
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (mNodes?.count)!
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 55.0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let parentNode = mNodes![indexPath.row]
let startPosition = indexPath.row+1
var endPosition = startPosition
if !parentNode.isLeaf() {// 点击的节点为非叶子节点
expandOrCollapse(&endPosition, node: parentNode)
mNodes = TreeNodeHelper.sharedInstance.filterVisibleNode(mAllNodes!) //更新可见节点
//修正indexpath
var indexPathArray :[NSIndexPath] = []
var tempIndexPath: NSIndexPath?
for (var i = startPosition; i < endPosition ; i++) {
tempIndexPath = NSIndexPath(forRow: i, inSection: 0)
indexPathArray.append(tempIndexPath!)
}
// 插入和删除节点的动画
if parentNode.isExpand {
self.insertRowsAtIndexPaths(indexPathArray, withRowAnimation: UITableViewRowAnimation.None)
} else {
self.deleteRowsAtIndexPaths(indexPathArray, withRowAnimation: UITableViewRowAnimation.None)
}
//更新被选组节点
self.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}
}
// ========================================================================================
//展开或者关闭某个节点
func expandOrCollapse(inout count: Int, node: TreeNode) {
if node.isExpand { //如果当前节点是开着的,需要关闭节点下的所有子节点
closedChildNode(&count,node: node)
} else { //如果节点是关着的,打开当前节点即可
count += node.children.count
node.setExpand(true)
}
}
//关闭某个节点和该节点的所有子节点
func closedChildNode(inout count:Int, node: TreeNode) {
if node.isLeaf() {
return
}
if node.isExpand {
node.isExpand = false
for item in node.children { //关闭子节点
count++ // 计算子节点数加一
closedChildNode(&count, node: item)
}
}
}
}
| mit | d7b83b0a4149bd3c481bb4609193641f | 32.076336 | 109 | 0.587584 | 4.852184 | false | false | false | false |
piwik/piwik-sdk-ios | MatomoTracker/MatomoUserDefaults.swift | 1 | 4934 | import Foundation
/// MatomoUserDefaults is a wrapper for the UserDefaults with properties
/// mapping onto values stored in the UserDefaults.
/// All getter and setter are sideeffect free and automatically syncronize
/// after writing.
internal struct MatomoUserDefaults {
let userDefaults: UserDefaults
init(suiteName: String?) {
userDefaults = UserDefaults(suiteName: suiteName)!
}
var totalNumberOfVisits: Int {
get {
return userDefaults.integer(forKey: MatomoUserDefaults.Key.totalNumberOfVisits)
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.totalNumberOfVisits)
userDefaults.synchronize()
}
}
var firstVisit: Date? {
get {
return userDefaults.object(forKey: MatomoUserDefaults.Key.firstVistsTimestamp) as? Date
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.firstVistsTimestamp)
userDefaults.synchronize()
}
}
var previousVisit: Date? {
get {
return userDefaults.object(forKey: MatomoUserDefaults.Key.previousVistsTimestamp) as? Date
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.previousVistsTimestamp)
userDefaults.synchronize()
}
}
var currentVisit: Date? {
get {
return userDefaults.object(forKey: MatomoUserDefaults.Key.currentVisitTimestamp) as? Date
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.currentVisitTimestamp)
userDefaults.synchronize()
}
}
var optOut: Bool {
get {
return userDefaults.bool(forKey: MatomoUserDefaults.Key.optOut)
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.optOut)
userDefaults.synchronize()
}
}
var clientId: String? {
get {
return userDefaults.string(forKey: MatomoUserDefaults.Key.clientID)
}
set {
userDefaults.setValue(newValue, forKey: MatomoUserDefaults.Key.clientID)
userDefaults.synchronize()
}
}
var forcedVisitorId: String? {
get {
return userDefaults.string(forKey: MatomoUserDefaults.Key.forcedVisitorID)
}
set {
userDefaults.setValue(newValue, forKey: MatomoUserDefaults.Key.forcedVisitorID)
userDefaults.synchronize()
}
}
var visitorUserId: String? {
get {
return userDefaults.string(forKey: MatomoUserDefaults.Key.visitorUserID);
}
set {
userDefaults.setValue(newValue, forKey: MatomoUserDefaults.Key.visitorUserID);
userDefaults.synchronize()
}
}
var lastOrder: Date? {
get {
return userDefaults.object(forKey: MatomoUserDefaults.Key.lastOrder) as? Date
}
set {
userDefaults.set(newValue, forKey: MatomoUserDefaults.Key.lastOrder)
}
}
}
extension MatomoUserDefaults {
public mutating func copy(from userDefaults: UserDefaults) {
totalNumberOfVisits = userDefaults.integer(forKey: MatomoUserDefaults.Key.totalNumberOfVisits)
firstVisit = userDefaults.object(forKey: MatomoUserDefaults.Key.firstVistsTimestamp) as? Date
previousVisit = userDefaults.object(forKey: MatomoUserDefaults.Key.previousVistsTimestamp) as? Date
currentVisit = userDefaults.object(forKey: MatomoUserDefaults.Key.currentVisitTimestamp) as? Date
optOut = userDefaults.bool(forKey: MatomoUserDefaults.Key.optOut)
clientId = userDefaults.string(forKey: MatomoUserDefaults.Key.clientID)
forcedVisitorId = userDefaults.string(forKey: MatomoUserDefaults.Key.forcedVisitorID)
visitorUserId = userDefaults.string(forKey: MatomoUserDefaults.Key.visitorUserID)
lastOrder = userDefaults.object(forKey: MatomoUserDefaults.Key.lastOrder) as? Date
}
}
extension MatomoUserDefaults {
internal struct Key {
static let totalNumberOfVisits = "PiwikTotalNumberOfVistsKey"
static let currentVisitTimestamp = "PiwikCurrentVisitTimestampKey"
static let previousVistsTimestamp = "PiwikPreviousVistsTimestampKey"
static let firstVistsTimestamp = "PiwikFirstVistsTimestampKey"
// Note: To be compatible with previous versions, the clientID key retains its old value,
// even though it is now a misnomer since adding visitorUserID makes it a bit confusing.
static let clientID = "PiwikVisitorIDKey"
static let forcedVisitorID = "PiwikForcedVisitorIDKey"
static let visitorUserID = "PiwikVisitorUserIDKey"
static let optOut = "PiwikOptOutKey"
static let lastOrder = "PiwikLastOrderDateKey"
}
}
| mit | 394829387a5ff5917dd52df7a3b49688 | 36.097744 | 107 | 0.66437 | 4.953815 | false | false | false | false |
xpush/lib-xpush-ios | XpushFramework/Event.swift | 1 | 762 | //
// Event.swift
// XpushFramework
//
// Created by notdol on 10/25/15.
// Copyright © 2015 stalk. All rights reserved.
//
import Foundation
public typealias CB = (JSON) -> Void
public class Event {
var handlers = [String:[CB]]();
public func on(key: String, handler: CB) {
var hs = handlers[key];
if hs == nil {
handlers[key] = [handler];
}else{
hs!.append(handler);
}
//hs.append(handler);
//handlers.append(handler)
}
public func emit(key: String, param:JSON) {
let hs = handlers[key];
if hs != nil{
for handler in hs! {
print(param);
handler(param)
}
}
}
}
| mit | c82ebb9e00c170ca216e3bc6a740d937 | 19.026316 | 48 | 0.492773 | 3.862944 | false | false | false | false |
benlangmuir/swift | test/SILGen/foreign_errors.swift | 2 | 19697 |
// RUN: %empty-directory(%t)
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk-nosource -I %t) -module-name foreign_errors -parse-as-library %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import errors
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors5test0yyKF : $@convention(thin) () -> @error any Error
func test0() throws {
// Create a strong temporary holding nil before we perform any further parts of function emission.
// CHECK: [[ERR_TEMP0:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: inject_enum_addr [[ERR_TEMP0]] : $*Optional<NSError>, #Optional.none!enumelt
// CHECK: [[SELF:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $@objc_metatype ErrorProne.Type, #ErrorProne.fail!foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
// Create an unmanaged temporary, copy into it, and make a AutoreleasingUnsafeMutablePointer.
// CHECK: [[ERR_TEMP1:%.*]] = alloc_stack $@sil_unmanaged Optional<NSError>
// CHECK: [[T0:%.*]] = load_borrow [[ERR_TEMP0]]
// CHECK: [[T1:%.*]] = ref_to_unmanaged [[T0]]
// CHECK: store [[T1]] to [trivial] [[ERR_TEMP1]]
// CHECK: address_to_pointer [stack_protection] [[ERR_TEMP1]]
// Call the method.
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]({{.*}}, [[SELF]])
// Writeback to the first temporary.
// CHECK: [[T0:%.*]] = load [trivial] [[ERR_TEMP1]]
// CHECK: [[T1:%.*]] = unmanaged_to_ref [[T0]]
// CHECK: [[T1_COPY:%.*]] = copy_value [[T1]]
// CHECK: assign [[T1_COPY]] to [[ERR_TEMP0]]
// Pull out the boolean value and compare it to zero.
// CHECK: [[BOOL_OR_INT:%.*]] = struct_extract [[RESULT]]
// CHECK: [[RAW_VALUE:%.*]] = struct_extract [[BOOL_OR_INT]]
// On some platforms RAW_VALUE will be compared against 0; on others it's
// already an i1 (bool) and those instructions will be skipped. Just do a
// looser check.
// CHECK: cond_br {{%.+}}, [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
try ErrorProne.fail()
// Normal path: fall out and return.
// CHECK: [[NORMAL_BB]]:
// CHECK: return
// Error path: fall out and rethrow.
// CHECK: [[ERROR_BB]]:
// CHECK: [[T0:%.*]] = load [take] [[ERR_TEMP0]]
// CHECK: [[T1:%.*]] = function_ref @$s10Foundation22_convertNSErrorToErrorys0E0_pSo0C0CSgF : $@convention(thin) (@guaranteed Optional<NSError>) -> @owned any Error
// CHECK: [[T2:%.*]] = apply [[T1]]([[T0]])
// CHECK: "willThrow"([[T2]] : $any Error)
// CHECK: throw [[T2]] : $any Error
}
extension NSObject {
@objc func abort() throws {
throw NSError(domain: "", code: 1, userInfo: [:])
}
// CHECK-LABEL: sil private [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE5abortyyKFTo : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
// CHECK: [[T0:%.*]] = function_ref @$sSo8NSObjectC14foreign_errorsE5abortyyKF : $@convention(method) (@guaranteed NSObject) -> @error any Error
// CHECK: try_apply [[T0]](
// CHECK: bb1(
// CHECK: [[BITS:%.*]] = integer_literal $Builtin.Int{{[18]}}, {{1|-1}}
// CHECK: [[VALUE:%.*]] = struct ${{Bool|UInt8}} ([[BITS]] : $Builtin.Int{{[18]}})
// CHECK: [[BOOL:%.*]] = struct $ObjCBool ([[VALUE]] : ${{Bool|UInt8}})
// CHECK: br bb6([[BOOL]] : $ObjCBool)
// CHECK: bb2([[ERR:%.*]] : @owned $any Error):
// CHECK: switch_enum %0 : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt: bb3, case #Optional.none!enumelt: bb4
// CHECK: bb3([[UNWRAPPED_OUT:%.+]] : $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
// CHECK: [[T0:%.*]] = function_ref @$s10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF : $@convention(thin) (@guaranteed any Error) -> @owned NSError
// CHECK: [[T1:%.*]] = apply [[T0]]([[ERR]])
// CHECK: [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt, [[T1]] : $NSError
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: store [[OBJCERR]] to [init] [[TEMP]]
// CHECK: [[SETTER:%.*]] = function_ref @$sSA7pointeexvs :
// CHECK: apply [[SETTER]]<Optional<NSError>>([[TEMP]], [[UNWRAPPED_OUT]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br bb5
// CHECK: bb4:
// CHECK: destroy_value [[ERR]] : $any Error
// CHECK: br bb5
// CHECK: bb5:
// CHECK: [[BITS:%.*]] = integer_literal $Builtin.Int{{[18]}}, 0
// CHECK: [[VALUE:%.*]] = struct ${{Bool|UInt8}} ([[BITS]] : $Builtin.Int{{[18]}})
// CHECK: [[BOOL:%.*]] = struct $ObjCBool ([[VALUE]] : ${{Bool|UInt8}})
// CHECK: br bb6([[BOOL]] : $ObjCBool)
// CHECK: bb6([[BOOL:%.*]] : $ObjCBool):
// CHECK: return [[BOOL]] : $ObjCBool
@objc func badDescription() throws -> String {
throw NSError(domain: "", code: 1, userInfo: [:])
}
// CHECK-LABEL: sil private [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE14badDescriptionSSyKFTo : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> @autoreleased Optional<NSString> {
// CHECK: bb0([[UNOWNED_ARG0:%.*]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[UNOWNED_ARG1:%.*]] : @unowned $NSObject):
// CHECK: [[ARG1:%.*]] = copy_value [[UNOWNED_ARG1]]
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[T0:%.*]] = function_ref @$sSo8NSObjectC14foreign_errorsE14badDescriptionSSyKF : $@convention(method) (@guaranteed NSObject) -> (@owned String, @error any Error)
// CHECK: try_apply [[T0]]([[BORROWED_ARG1]]) : $@convention(method) (@guaranteed NSObject) -> (@owned String, @error any Error), normal [[NORMAL_BB:bb[0-9][0-9]*]], error [[ERROR_BB:bb[0-9][0-9]*]]
//
// CHECK: [[NORMAL_BB]]([[RESULT:%.*]] : @owned $String):
// CHECK: [[T0:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]]
// CHECK: [[T1:%.*]] = apply [[T0]]([[BORROWED_RESULT]])
// CHECK: end_borrow [[BORROWED_RESULT]]
// CHECK: [[T2:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[T1]] : $NSString
// CHECK: destroy_value [[RESULT]]
// CHECK: br bb6([[T2]] : $Optional<NSString>)
//
// CHECK: [[ERROR_BB]]([[ERR:%.*]] : @owned $any Error):
// CHECK: switch_enum [[UNOWNED_ARG0]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9][0-9]*]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9][0-9]*]]
//
// CHECK: [[SOME_BB]]([[UNWRAPPED_OUT:%.+]] : $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
// CHECK: [[T0:%.*]] = function_ref @$s10Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF : $@convention(thin) (@guaranteed any Error) -> @owned NSError
// CHECK: [[T1:%.*]] = apply [[T0]]([[ERR]])
// CHECK: [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt, [[T1]] : $NSError
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: store [[OBJCERR]] to [init] [[TEMP]]
// CHECK: [[SETTER:%.*]] = function_ref @$sSA7pointeexvs :
// CHECK: apply [[SETTER]]<Optional<NSError>>([[TEMP]], [[UNWRAPPED_OUT]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br bb5
//
// CHECK: [[NONE_BB]]:
// CHECK: destroy_value [[ERR]] : $any Error
// CHECK: br bb5
//
// CHECK: bb5:
// CHECK: [[T0:%.*]] = enum $Optional<NSString>, #Optional.none!enumelt
// CHECK: br bb6([[T0]] : $Optional<NSString>)
//
// CHECK: bb6([[T0:%.*]] : @owned $Optional<NSString>):
// CHECK: end_borrow [[BORROWED_ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: return [[T0]] : $Optional<NSString>
// CHECK-LABEL: sil private [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE7takeIntyySiKFTo : $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
// CHECK: bb0([[I:%[0-9]+]] : $Int, [[ERROR:%[0-9]+]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[SELF:%[0-9]+]] : @unowned $NSObject)
@objc func takeInt(_ i: Int) throws { }
// CHECK-LABEL: sil private [thunk] [ossa] @$sSo8NSObjectC14foreign_errorsE10takeDouble_3int7closureySd_S3iXEtKFTo : $@convention(objc_method) (Double, Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @convention(block) @noescape (Int) -> Int, NSObject) -> ObjCBool
// CHECK: bb0([[D:%[0-9]+]] : $Double, [[INT:%[0-9]+]] : $Int, [[ERROR:%[0-9]+]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[CLOSURE:%[0-9]+]] : @unowned $@convention(block) @noescape (Int) -> Int, [[SELF:%[0-9]+]] : @unowned $NSObject):
@objc func takeDouble(_ d: Double, int: Int, closure: (Int) -> Int) throws {
throw NSError(domain: "", code: 1, userInfo: [:])
}
}
let fn = ErrorProne.fail
// CHECK-LABEL: sil private [ossa] @$s14foreign_errors2fnyyKcvpfiyyKcSo10ErrorProneCmcfu_ : $@convention(thin) (@thick ErrorProne.Type) -> @owned @callee_guaranteed () -> @error any Error {
// CHECK: [[T0:%.*]] = function_ref @$s14foreign_errors2fnyyKcvpfiyyKcSo10ErrorProneCmcfu_yyKcfu0_ : $@convention(thin) (@thick ErrorProne.Type) -> @error any Error
// CHECK-NEXT: [[T1:%.*]] = partial_apply [callee_guaranteed] [[T0]](%0)
// CHECK-NEXT: return [[T1]]
// CHECK-LABEL: sil private [ossa] @$s14foreign_errors2fnyyKcvpfiyyKcSo10ErrorProneCmcfu_yyKcfu0_ : $@convention(thin) (@thick ErrorProne.Type) -> @error any Error {
// CHECK: [[TEMP:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[SELF:%.*]] = thick_to_objc_metatype %0 : $@thick ErrorProne.Type to $@objc_metatype ErrorProne.Type
// CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $@objc_metatype ErrorProne.Type, #ErrorProne.fail!foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]({{%.*}}, [[SELF]])
// CHECK: cond_br
// CHECK: return
// CHECK: [[T0:%.*]] = load [take] [[TEMP]]
// CHECK: [[T1:%.*]] = apply {{%.*}}([[T0]])
// CHECK: "willThrow"([[T1]] : $any Error)
// CHECK: throw [[T1]]
func testArgs() throws {
try ErrorProne.consume(nil)
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors8testArgsyyKF : $@convention(thin) () -> @error any Error
// CHECK: debug_value undef : $any Error, var, name "$error", argno 1
// CHECK: objc_method {{.*}} : $@objc_metatype ErrorProne.Type, #ErrorProne.consume!foreign : (ErrorProne.Type) -> (Any?) throws -> (), $@convention(objc_method) (Optional<AnyObject>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
func testBridgedResult() throws {
let array = try ErrorProne.collection(withCount: 0)
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors17testBridgedResultyyKF : $@convention(thin) () -> @error any Error {
// CHECK: debug_value undef : $any Error, var, name "$error", argno 1
// CHECK: objc_method {{.*}} : $@objc_metatype ErrorProne.Type, #ErrorProne.collection!foreign : (ErrorProne.Type) -> (Int) throws -> [Any], $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> @autoreleased Optional<NSArray>
// CHECK: } // end sil function '$s14foreign_errors17testBridgedResultyyKF'
// rdar://20861374
// Clear out the self box before delegating.
class VeryErrorProne : ErrorProne {
init(withTwo two: AnyObject?) throws {
try super.init(one: two)
}
}
// SEMANTIC SIL TODO: _TFC14foreign_errors14VeryErrorPronec has a lot more going
// on than is being tested here, we should consider adding FileCheck tests for
// it.
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors14VeryErrorProneC7withTwoACyXlSg_tKcfc :
// CHECK: bb0([[ARG1:%.*]] : @owned $Optional<AnyObject>, [[ARG2:%.*]] : @owned $VeryErrorProne):
// CHECK: [[BOX:%.*]] = alloc_box ${ var VeryErrorProne }
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]]
// CHECK: [[LIFETIME:%.*]] = begin_borrow [lexical] [[MARKED_BOX]]
// CHECK: [[PB:%.*]] = project_box [[LIFETIME]]
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [lexical] [[ARG1]]
// CHECK: store [[ARG2]] to [init] [[PB]]
// CHECK: [[T0:%.*]] = load [take] [[PB]]
// CHECK-NEXT: [[T1:%.*]] = upcast [[T0]] : $VeryErrorProne to $ErrorProne
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]]
// CHECK-NOT: [[BOX]]{{^[0-9]}}
// CHECK-NOT: [[PB]]{{^[0-9]}}
// CHECK: [[BORROWED_T1:%.*]] = begin_borrow [[T1]]
// CHECK-NEXT: [[DOWNCAST_BORROWED_T1:%.*]] = unchecked_ref_cast [[BORROWED_T1]] : $ErrorProne to $VeryErrorProne
// CHECK-NEXT: [[T2:%.*]] = objc_super_method [[DOWNCAST_BORROWED_T1]] : $VeryErrorProne, #ErrorProne.init!initializer.foreign : (ErrorProne.Type) -> (Any?) throws -> ErrorProne, $@convention(objc_method) (Optional<AnyObject>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @owned ErrorProne) -> @owned Optional<ErrorProne>
// CHECK: end_borrow [[BORROWED_T1]]
// CHECK: apply [[T2]]([[ARG1_COPY]], {{%.*}}, [[T1]])
// CHECK: } // end sil function '$s14foreign_errors14VeryErrorProneC7withTwoACyXlSg_tKcfc'
// rdar://21051021
// CHECK: sil hidden [ossa] @$s14foreign_errors12testProtocolyySo010ErrorProneD0_pKF : $@convention(thin) (@guaranteed any ErrorProneProtocol) -> @error any Error
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $any ErrorProneProtocol):
func testProtocol(_ p: ErrorProneProtocol) throws {
// CHECK: [[T0:%.*]] = open_existential_ref [[ARG0]] : $any ErrorProneProtocol to $[[OPENED:@opened\(.*, any ErrorProneProtocol\) Self]]
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $[[OPENED]], #ErrorProneProtocol.obliterate!foreign : {{.*}}
// CHECK: apply [[T1]]<[[OPENED]]>({{%.*}}, [[T0]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : ErrorProneProtocol> (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, τ_0_0) -> ObjCBool
try p.obliterate()
// CHECK: [[T0:%.*]] = open_existential_ref [[ARG0]] : $any ErrorProneProtocol to $[[OPENED:@opened\(.*, any ErrorProneProtocol\) Self]]
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $[[OPENED]], #ErrorProneProtocol.invigorate!foreign : {{.*}}
// CHECK: apply [[T1]]<[[OPENED]]>({{%.*}}, {{%.*}}, [[T0]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : ErrorProneProtocol> (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, Optional<@convention(block) () -> ()>, τ_0_0) -> ObjCBool
try p.invigorate(callback: {})
}
// rdar://21144509 - Ensure that overrides of replace-with-() imports are possible.
class ExtremelyErrorProne : ErrorProne {
override func conflict3(_ obj: Any, error: ()) throws {}
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors19ExtremelyErrorProneC9conflict3_5erroryyp_yttKF
// CHECK-LABEL: sil private [thunk] [ossa] @$s14foreign_errors19ExtremelyErrorProneC9conflict3_5erroryyp_yttKFTo : $@convention(objc_method) (AnyObject, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, ExtremelyErrorProne) -> ObjCBool
// These conventions are usable because of swift_error. rdar://21715350
func testNonNilError() throws -> Float {
return try ErrorProne.bounce()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors15testNonNilErrorSfyKF :
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.bounce!foreign : (ErrorProne.Type) -> () throws -> Float, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Float
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: assign {{%.*}} to [[OPTERR]]
// CHECK: [[T0:%.*]] = load [take] [[OPTERR]]
// CHECK: switch_enum [[T0]] : $Optional<NSError>, case #Optional.some!enumelt: [[ERROR_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NORMAL_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResult() throws -> CInt {
return try ErrorProne.ounce()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors19testPreservedResults5Int32VyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.ounce!foreign : (ErrorProne.Type) -> () throws -> Int32, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int32
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int32"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResultBridged() throws -> Int {
return try ErrorProne.ounceWord()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors26testPreservedResultBridgedSiyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.ounceWord!foreign : (ErrorProne.Type) -> () throws -> Int, $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int{{.*}}"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResultInverted() throws {
try ErrorProne.once()
}
// CHECK-LABEL: sil hidden [ossa] @$s14foreign_errors27testPreservedResultInvertedyyKF
// CHECK: [[OPTERR:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[T0:%.*]] = metatype $@objc_metatype ErrorProne.Type
// CHECK: [[T1:%.*]] = objc_method [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.once!foreign : (ErrorProne.Type) -> () throws -> (), $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int32
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int32"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[ERROR_BB:bb[0-9]+]], [[NORMAL_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return {{%.+}} : $()
// CHECK: [[ERROR_BB]]
// Make sure that we do not crash when emitting the error value here.
//
// TODO: Add some additional filecheck tests.
extension NSURL {
func resourceValue<T>(forKey key: String) -> T? {
var prop: AnyObject? = nil
_ = try? self.getResourceValue(&prop, forKey: key)
return prop as? T
}
}
| apache-2.0 | 423b12ead1e7eeb8e5668179468052fa | 61.313291 | 340 | 0.643492 | 3.435875 | false | true | false | false |
Henawey/TheArabianCenter | TheArabianCenter/HomeInteractor.swift | 1 | 4877 | //
// HomeInteractor.swift
// TheArabianCenter
//
// Created by Ahmed Henawey on 2/18/17.
// Copyright (c) 2017 Ahmed Henawey. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
import RxSwift
import CoreLocation
protocol HomeInteractorInput
{
func validateCameraAvaliabilty()
func startLocationManager()
func changeLanguage(request: Language.Request)
func handleCameraResult(request:Home.Offer.Image.Request)
var image: UIImage {get set}
var userLocation: CLLocation? {get set}
}
protocol HomeInteractorOutput
{
func presentImageProccessed(response: Home.Offer.Image.Response)
func presentImageError(error: Home.Offer.Image.Error)
func presentLocationError(error: Location.Error)
func presentCameraAvaliable()
func presentCameraNotAvaliable()
}
class HomeInteractor: HomeInteractorInput
{
var output: HomeInteractorOutput!
var worker: HomeWorker!
/// Used for passing data from Home to Share View Controller
var _image: UIImage!
var image: UIImage{
set{
_image = newValue
}
get{
return _image
}
}
/// User for saving user location until needed
var _userLocation: CLLocation?
var userLocation: CLLocation?{
set{
_userLocation = newValue
}
get{
return _userLocation
}
}
fileprivate let disposeBag = DisposeBag()
// MARK: - Business logic
/// Check if camera avaliable for this device (Usally work for real devices and doesn't work for Simulator)
func validateCameraAvaliabilty(){
if UIImagePickerController.isSourceTypeAvailable(.camera){
self.output.presentCameraAvaliable()
}else{
self.output.presentCameraNotAvaliable()
}
}
/// Notify the interaction for need to subscribe for any location change to be ready if location required
func startLocationManager() {
let locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
/// Subscribe for delegate obserable method for any chnage for authorization.
locationManager.rx.didChangeAuthorizationStatus.subscribe(onNext: { (status) in
switch status{
case .authorizedWhenInUse:
locationManager.startUpdatingLocation()
default:
self.output.presentLocationError(error: Location.Error.locationAuthorizaionRequired)
}
}).addDisposableTo(disposeBag)
/// Subscribe for any location change to update user location to be ready with latest user location
locationManager.rx.didUpdateLocations.subscribe(onNext: { (locations) in
guard let location: CLLocation = locations.first else{
return
}
self.userLocation = location
}).addDisposableTo(disposeBag)
}
/// Handle UIImagePickerController response for camera result
///
/// - Parameter request: Wrapper for Event that have camera response
func handleCameraResult(request: Home.Offer.Image.Request) {
let event = request.event
switch event {
case let .next(result):
let response = Home.Offer.Image.Response(result: result)
self.output.presentImageProccessed(response: response)
case let .error(error):
self.output.presentImageError(error: Home.Offer.Image.Error.failure(error: error))
default: break
}
}
/// Request to change the Locaization for the application basically
/// 1. override "AppleLanguages"
/// 2. Update "semanticContentAttribute" for UIView
/// 3. Notify any observer that listen for "localizationChanged"
///
/// - Parameter request: Request for required language and the "semanticContentAttribute"
func changeLanguage(request: Language.Request) {
var selectedLanguage:Language!
if request.language == nil{
selectedLanguage = .English
}else{
selectedLanguage = request.language
}
Bundle.setLanguage(selectedLanguage.rawValue)
UserDefaults.standard.set([selectedLanguage.rawValue], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()
UIView.appearance().semanticContentAttribute = selectedLanguage.semanticContentAttribute
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "localizationChanged"), object: nil)
}
}
| mit | 37fcfd63986f1c286be0dc7e10f8e0df | 30.063694 | 112 | 0.650195 | 5.249731 | false | false | false | false |
noppoMan/Suv | Sources/Suv/Stream/Handle.swift | 1 | 3210 | //
// Handle.swift
// SwiftyLibuv
//
// Created by Yuki Takei on 6/12/16.
//
//
import CLibUv
internal func close_handle<T>(_ req: UnsafeMutablePointer<T>){
if uv_is_closing(req.cast(to: UnsafeMutablePointer<uv_handle_t>.self)) == 1 {
return
}
uv_close(req.cast(to: UnsafeMutablePointer<uv_handle_t>.self)) {
if let handle = $0 {
dealloc(handle)
}
}
}
public class Handle {
private var onCloseHandlers = [() -> ()]()
internal var handlePtr: UnsafeMutablePointer<uv_handle_t>
public init(_ handlePtr: UnsafeMutablePointer<uv_handle_t>){
self.handlePtr = handlePtr
}
/**
Returns true if the stream handle is active, 0 otherwise. What “active”means depends on the type of handle:
* A uv_async_t handle is always active and cannot be deactivated, except by closing it with uv_close().
* A uv_pipe_t, uv_tcp_t, uv_udp_t, etc. handle - basically any handle that deals with i/o - is active when it is doing something that involves i/o, like reading, writing, connecting, accepting new connections, etc.
* A uv_check_t, uv_idle_t, uv_timer_t, etc. handle is active when it has been started with a call to uv_check_start(), uv_idle_start(), etc.
Rule of thumb: if a handle of type uv_foo_t has a uv_foo_start() function, then it’s active from the moment that function is called. Likewise, uv_foo_stop() deactivates the handle again.
- returns: bool
*/
public func isActive() -> Bool {
if(uv_is_active(handlePtr) == 1) {
return true
}
return false
}
/**
Returns true if the stream handle is closing or closed, 0 otherwise.
- returns: bool
*/
public func isClosing() -> Bool {
if(uv_is_closing(handlePtr) == 1) {
return true
}
return false
}
public func onClose(_ onClose: @escaping () -> ()){
self.onCloseHandlers.append(onClose)
}
/**
close stream handle
*/
public func close(){
if isClosing() { return }
close_handle(handlePtr)
for handler in onCloseHandlers {
handler()
}
}
/**
Reference the internal handle. References are idempotent, that is, if a handle is already referenced calling this function again will have no effect
*/
public func ref(){
uv_ref(handlePtr)
}
/**
Un-reference the internal handle. References are idempotent, that is, if a handle is not referenced calling this function again will have no effect
*/
public func unref(){
uv_unref(handlePtr)
}
/**
Returne true if handle_type is TCP
*/
public var typeIsTcp: Bool {
return handlePtr.pointee.type == UV_TCP
}
/**
Returne true if handle_type is UDP
*/
public var typeIsUdp: Bool {
return handlePtr.pointee.type == UV_UDP
}
/**
Returne true if handle_type is UV_NAMED_PIPE
*/
public var typeIsNamedPipe: Bool {
return handlePtr.pointee.type == UV_NAMED_PIPE
}
}
| mit | dca007292b5e540f2ce49a6a3136a92d | 26.86087 | 219 | 0.595818 | 4.086735 | false | false | false | false |
gspd-mobi/rage-ios | Sources/Rage/Rage+Codable.swift | 1 | 5500 | import Foundation
extension Encodable {
public func encode(encoder: JSONEncoder = JSONEncoder()) throws -> Data {
return try encoder.encode(self)
}
public func toJSONString(encoder: JSONEncoder = JSONEncoder()) throws -> String? {
return try String(data: self.encode(encoder: encoder), encoding: .utf8)
}
public func makeTypedObject(encoder: JSONEncoder = JSONEncoder()) throws -> TypedObject? {
guard let json = try toJSONString(encoder: encoder) else {
return nil
}
guard let data = json.utf8Data() else {
return nil
}
return TypedObject(data, mimeType: ContentType.json.stringValue())
}
}
extension Array where Element: Encodable {
public func encode(encoder: JSONEncoder = JSONEncoder()) throws -> Data {
return try encoder.encode(self)
}
public func toJSONString(encoder: JSONEncoder = JSONEncoder()) throws -> String? {
return try String(data: self.encode(encoder: encoder), encoding: .utf8)
}
public func makeTypedObject(encoder: JSONEncoder = JSONEncoder()) throws -> TypedObject? {
guard let json = try toJSONString(encoder: encoder) else {
return nil
}
guard let data = json.utf8Data() else {
return nil
}
return TypedObject(data, mimeType: ContentType.json.stringValue())
}
}
extension BodyRageRequest {
public func bodyJson<T: Codable>(_ value: T, encoder: JSONEncoder = JSONEncoder()) -> BodyRageRequest {
if !httpMethod.hasBody() {
preconditionFailure("Can't add body to request with such HttpMethod")
}
guard let json = try? value.toJSONString(encoder: encoder) else {
return self
}
_ = contentType(.json)
return bodyString(json)
}
public func bodyJson<T: Codable>(_ value: [T], encoder: JSONEncoder = JSONEncoder()) -> BodyRageRequest {
if !httpMethod.hasBody() {
preconditionFailure("Can't add body to request with such HttpMethod")
}
guard let json = try? value.toJSONString(encoder: encoder) else {
return self
}
_ = contentType(.json)
return bodyString(json)
}
}
extension RageRequest {
public func stub<T: Codable>(_ value: T,
mode: StubMode = .immediate,
encoder: JSONEncoder = JSONEncoder()) -> RageRequest {
guard let json = try? value.toJSONString(encoder: encoder) else {
return self
}
return self.stub(json, mode: mode)
}
public func stub<T: Codable>(_ value: [T],
mode: StubMode = .immediate,
encoder: JSONEncoder = JSONEncoder()) -> RageRequest {
guard let json = try? value.toJSONString(encoder: encoder) else {
return self
}
return self.stub(json, mode: mode)
}
open func executeObject<T: Codable>(decoder: JSONDecoder = JSONDecoder()) -> Result<T, RageError> {
let result = self.execute()
switch result {
case .success(let response):
let parsedObject: T? = response.data?.parseJson(decoder: decoder)
if let resultObject = parsedObject {
return .success(resultObject)
} else {
return .failure(RageError(type: .configuration))
}
case .failure(let error):
return .failure(error)
}
}
open func executeArray<T: Codable>(decoder: JSONDecoder = JSONDecoder()) -> Result<[T], RageError> {
let result = self.execute()
switch result {
case .success(let response):
let parsedObject: [T]? = response.data?.parseJsonArray(decoder: decoder)
if let resultObject = parsedObject {
return .success(resultObject)
} else {
return .failure(RageError(type: .configuration))
}
case .failure(let error):
return .failure(error)
}
}
open func enqueueObject<T: Codable>(decoder: JSONDecoder = JSONDecoder(),
_ completion: @escaping (Result<T, RageError>) -> Void) {
DispatchQueue.global(qos: .background).async(execute: {
let result: Result<T, RageError> = self.executeObject(decoder: decoder)
DispatchQueue.main.async(execute: {
completion(result)
})
})
}
open func enqueueArray<T: Codable>(decoder: JSONDecoder = JSONDecoder(),
_ completion: @escaping (Result<[T], RageError>) -> Void) {
DispatchQueue.global(qos: .background).async(execute: {
let result: Result<[T], RageError> = self.executeArray(decoder: decoder)
DispatchQueue.main.async(execute: {
completion(result)
})
})
}
}
extension Data {
public func parseJson<T: Codable>(decoder: JSONDecoder = JSONDecoder()) -> T? {
guard let value = try? decoder.decode(T.self, from: self) else {
return nil
}
return value
}
public func parseJsonArray<T: Codable>(decoder: JSONDecoder = JSONDecoder()) -> [T]? {
guard let value = try? decoder.decode([T].self, from: self) else {
return nil
}
return value
}
}
| mit | f3c809072bf3e434fdf1d67827fc2f1a | 31.544379 | 109 | 0.575091 | 4.782609 | false | false | false | false |
JGiola/swift-corelibs-foundation | TestFoundation/TestNSCalendar.swift | 1 | 49936 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
class TestNSCalendar: XCTestCase {
func test_initWithCalendarIdentifier() {
var calMaybe = NSCalendar(calendarIdentifier: NSCalendar.Identifier("Not a calendar"))
XCTAssertNil(calMaybe)
calMaybe = NSCalendar(calendarIdentifier: .chinese)
guard let cal = calMaybe else {
XCTFail(); return
}
XCTAssertEqual(cal.calendarIdentifier, NSCalendar.Identifier.chinese)
}
func test_calendarWithIdentifier() {
var calMaybe = NSCalendar(identifier: NSCalendar.Identifier("Not a calendar"))
XCTAssertNil(calMaybe)
calMaybe = NSCalendar(identifier: .chinese)
guard let cal = calMaybe else {
XCTFail(); return
}
XCTAssertEqual(cal.calendarIdentifier, NSCalendar.Identifier.chinese)
}
func test_calendarOptions() {
let allOptions: [NSCalendar.Options] = [.matchStrictly, .searchBackwards, .matchPreviousTimePreservingSmallerUnits, .matchNextTimePreservingSmallerUnits, .matchNextTime, .matchFirst, .matchLast]
for (i, option) in allOptions.enumerated() {
var otherOptions: NSCalendar.Options.RawValue = 0
for (j, otherOption) in allOptions.enumerated() {
if (i != j) {
otherOptions |= otherOption.rawValue
}
}
XCTAssertEqual(0, (option.rawValue & otherOptions), "Options should be exclusive")
}
}
func test_isEqualWithDifferentWaysToCreateCalendar() throws {
let date = Date(timeIntervalSinceReferenceDate: 497973600) // 2016-10-12 07:00:00 +0000;
let gregorianCalendar = try NSCalendar(identifier: .gregorian).unwrapped()
let gregorianCalendar2 = try gregorianCalendar.components(.calendar, from: date).calendar.unwrapped() as NSCalendar
XCTAssertEqual(gregorianCalendar, gregorianCalendar2)
let timeZone = try TimeZone(identifier: "Antarctica/Vostok").unwrapped()
gregorianCalendar.timeZone = timeZone
let gregorianCalendar3 = try gregorianCalendar.components(.calendar, from: date).calendar.unwrapped() as NSCalendar
XCTAssertEqual(gregorianCalendar, gregorianCalendar3)
}
func test_isEqual() throws {
let testCal1 = try NSCalendar(identifier: .gregorian).unwrapped()
let testCal2 = try NSCalendar(identifier: .gregorian).unwrapped()
XCTAssertEqual(testCal1, testCal2)
testCal2.timeZone = try TimeZone(identifier: "Antarctica/Vostok").unwrapped()
testCal2.locale = Locale(identifier: "ru_RU")
testCal2.firstWeekday += 1
testCal2.minimumDaysInFirstWeek += 1
XCTAssertNotEqual(testCal1, testCal2)
let testCal3 = try NSCalendar(calendarIdentifier: .chinese).unwrapped()
XCTAssertNotEqual(testCal1, testCal3)
}
func test_isEqualCurrentCalendar() {
let testCal1 = NSCalendar.current as NSCalendar
let testCal2 = NSCalendar.current as NSCalendar
XCTAssertEqual(testCal1, testCal2)
XCTAssert(testCal1 !== testCal2)
XCTAssertNotEqual(testCal1.firstWeekday, 4)
testCal1.firstWeekday = 4
XCTAssertNotEqual(testCal1, testCal2)
}
func test_isEqualAutoUpdatingCurrentCalendar() {
let testCal1 = NSCalendar.autoupdatingCurrent as NSCalendar
let testCal2 = NSCalendar.autoupdatingCurrent as NSCalendar
XCTAssertEqual(testCal1, testCal2)
XCTAssert(testCal1 !== testCal2)
XCTAssertNotEqual(testCal1.firstWeekday, 4)
testCal1.firstWeekday = 4
XCTAssertNotEqual(testCal1, testCal2)
}
func test_copy() throws {
let cal = try NSCalendar(identifier: .gregorian).unwrapped()
let calCopy = try (cal.copy() as? NSCalendar).unwrapped()
XCTAssertEqual(cal, calCopy)
XCTAssert(cal !== calCopy)
}
func test_copyCurrentCalendar() throws {
let cal = NSCalendar.current as NSCalendar
let calCopy = try (cal.copy() as? NSCalendar).unwrapped()
XCTAssertEqual(cal, calCopy)
XCTAssert(cal !== calCopy)
}
// MARK: API Method Tests
let timeIntervalsNext50Months: [TimeInterval] = [
349776000, // 2012-02-01 08:00:00 +0000
352281600, // 2012-03-01 08:00:00 +0000
354956400, // 2012-04-01 07:00:00 +0000
357548400, // 2012-05-01 07:00:00 +0000
360226800, // 2012-06-01 07:00:00 +0000
362818800, // 2012-07-01 07:00:00 +0000
365497200, // 2012-08-01 07:00:00 +0000
368175600, // 2012-09-01 07:00:00 +0000
370767600, // 2012-10-01 07:00:00 +0000
373446000, // 2012-11-01 07:00:00 +0000
376041600, // 2012-12-01 08:00:00 +0000
378720000, // 2013-01-01 08:00:00 +0000
381398400, // 2013-02-01 08:00:00 +0000
383817600, // 2013-03-01 08:00:00 +0000
386492400, // 2013-04-01 07:00:00 +0000
389084400, // 2013-05-01 07:00:00 +0000
391762800, // 2013-06-01 07:00:00 +0000
394354800, // 2013-07-01 07:00:00 +0000
397033200, // 2013-08-01 07:00:00 +0000
399711600, // 2013-09-01 07:00:00 +0000
402303600, // 2013-10-01 07:00:00 +0000
404982000, // 2013-11-01 07:00:00 +0000
407577600, // 2013-12-01 08:00:00 +0000
410256000, // 2014-01-01 08:00:00 +0000
412934400, // 2014-02-01 08:00:00 +0000
415353600, // 2014-03-01 08:00:00 +0000
418028400, // 2014-04-01 07:00:00 +0000
420620400, // 2014-05-01 07:00:00 +0000
423298800, // 2014-06-01 07:00:00 +0000
425890800, // 2014-07-01 07:00:00 +0000
428569200, // 2014-08-01 07:00:00 +0000
431247600, // 2014-09-01 07:00:00 +0000
433839600, // 2014-10-01 07:00:00 +0000
436518000, // 2014-11-01 07:00:00 +0000
439113600, // 2014-12-01 08:00:00 +0000
441792000, // 2015-01-01 08:00:00 +0000
444470400, // 2015-02-01 08:00:00 +0000
446889600, // 2015-03-01 08:00:00 +0000
449564400, // 2015-04-01 07:00:00 +0000
452156400, // 2015-05-01 07:00:00 +0000
454834800, // 2015-06-01 07:00:00 +0000
457426800, // 2015-07-01 07:00:00 +0000
460105200, // 2015-08-01 07:00:00 +0000
462783600, // 2015-09-01 07:00:00 +0000
465375600, // 2015-10-01 07:00:00 +0000
468054000, // 2015-11-01 07:00:00 +0000
470649600, // 2015-12-01 08:00:00 +0000
473328000, // 2016-01-01 08:00:00 +0000
476006400, // 2016-02-01 08:00:00 +0000
478512000, // 2016-03-01 08:00:00 +0000
];
func test_next50MonthsFromDate() throws {
let calendar = try NSCalendar(identifier: .gregorian).unwrapped()
calendar.timeZone = try TimeZone(identifier: "America/Los_Angeles").unwrapped()
let startDate = Date(timeIntervalSinceReferenceDate: 347113850) // 2012-01-01 12:30:50 +0000
let expectedDates = timeIntervalsNext50Months.map { Date(timeIntervalSinceReferenceDate: $0) }
var count = 0
var resultDates: [Date] = []
let components = NSDateComponents()
components.day = 1
calendar.enumerateDates(startingAfter: startDate, matching: components as DateComponents, options: .matchNextTime) { (date, exactMatch, stop) in
count += 1
if count > expectedDates.count {
stop.pointee = true
return
}
guard let date = date else {
XCTFail()
stop.pointee = true
return
}
resultDates.append(date)
}
XCTAssertEqual(expectedDates, resultDates)
}
let iterableCalendarUnits: [NSCalendar.Unit] = [
.era,
.year,
.month,
.day,
.hour,
.minute,
.second,
.weekday,
.weekdayOrdinal,
.quarter,
.weekOfMonth,
.weekOfYear,
.yearForWeekOfYear,
.nanosecond,
.calendar,
.timeZone,
]
let allCalendarUnits: NSCalendar.Unit = [
.era,
.year,
.month,
.day,
.hour,
.minute,
.second,
.weekday,
.weekdayOrdinal,
.quarter,
.weekOfMonth,
.weekOfYear,
.yearForWeekOfYear,
.nanosecond,
.calendar,
.timeZone,
]
func yieldUnits(in components: NSDateComponents) -> [NSCalendar.Unit] {
return iterableCalendarUnits.filter({ (unit) -> Bool in
switch unit {
case .calendar:
return components.calendar != nil
case .timeZone:
return components.timeZone != nil
default:
return components.value(forComponent: unit) != NSDateComponentUndefined
}
})
}
func units(in components: NSDateComponents) -> NSCalendar.Unit {
return yieldUnits(in: components).reduce([], { (current, toAdd) in
var new = current
new.insert(toAdd)
return new
})
}
func performTest_dateByAdding(with calendar: NSCalendar, components: NSDateComponents, toAdd secondComponents: NSDateComponents, options: NSCalendar.Options, expected: NSDateComponents, addSingleUnit: Bool) throws {
let date = try calendar.date(from: components as DateComponents).unwrapped()
var returnedDate: Date
if addSingleUnit {
let unit = units(in: secondComponents)
let valueToAdd = secondComponents.value(forComponent: unit)
returnedDate = try calendar.date(byAdding: unit, value: valueToAdd, to: date, options: options).unwrapped()
} else {
returnedDate = try calendar.date(byAdding: secondComponents as DateComponents, to: date, options: options).unwrapped()
}
let expectedUnitFlags = units(in: expected)
// If the NSDateComponents is being added to with a time zone, we want the result to be in the same time zone.
let originalTimeZone = calendar.timeZone
let calculationTimeZone = components.timeZone
if let calculationTimeZone = calculationTimeZone {
calendar.timeZone = calculationTimeZone
}
let returnedComponents = calendar.components(expectedUnitFlags, from: returnedDate) as NSDateComponents
XCTAssertEqual(expected, returnedComponents, "\(calendar.calendarIdentifier) \(components) \(secondComponents) Expected \(expected), but received \(returnedComponents)")
if calculationTimeZone != nil {
calendar.timeZone = originalTimeZone
}
}
func performTest_componentsFromDateToDate(with calendar: NSCalendar, from fromComponents: NSDateComponents, to toComponents: NSDateComponents, expected: NSDateComponents, options: NSCalendar.Options) throws {
let fromDate = try calendar.date(from: fromComponents as DateComponents).unwrapped()
let toDate = try calendar.date(from: toComponents as DateComponents).unwrapped()
let expectedUnitFlags = units(in: expected)
let returned = calendar.components(expectedUnitFlags, from: fromDate, to: toDate, options: options) as NSDateComponents
XCTAssertEqual(expected, returned, "Expected \(expected), but received \(returned) - from date: \(fromDate) to date: \(toDate)")
}
func performTest_componentsFromDCToDC(with calendar: NSCalendar, from fromComponents: NSDateComponents, to toComponents: NSDateComponents, expected: NSDateComponents, options: NSCalendar.Options) throws {
let expectedUnitFlags = units(in: expected)
let returned = calendar.components(expectedUnitFlags, from: fromComponents as DateComponents, to: toComponents as DateComponents, options: options) as NSDateComponents
XCTAssertEqual(expected, returned, "Expected \(expected), but received \(returned) - from components: \(fromComponents) to components: \(toComponents)")
}
func performTest_getComponentsInOtherCalendar(from fromCalendar: NSCalendar, to toCalendar: NSCalendar, from fromComponents: NSDateComponents, expected: NSDateComponents) throws {
let originalTZ = fromCalendar.timeZone
fromCalendar.timeZone = toCalendar.timeZone
let fromDate = try fromCalendar.date(from: fromComponents as DateComponents).unwrapped()
fromCalendar.timeZone = originalTZ
let expectedUnitFlags = units(in: expected)
let returned = toCalendar.components(expectedUnitFlags, from: fromDate) as NSDateComponents
XCTAssertEqual(expected, returned, "Expected \(expected), but received \(returned) - from calendar: \(fromCalendar) to calendar: \(toCalendar) from components: \(fromComponents)")
}
func test_dateByAddingUnit_withWrapOption() throws {
let locale = Locale(identifier: "ar_EG")
let calendar = try NSCalendar(identifier: .gregorian).unwrapped()
let timeZone = try TimeZone(abbreviation: "GMT").unwrapped()
calendar.locale = locale
calendar.timeZone = timeZone
let date = try self.date(fromFixture: "2013-09-20 23:20:28 +0000")
let newDate = try calendar.date(byAdding: .hour, value: 12, to: date, options: .wrapComponents).unwrapped()
XCTAssertEqual(newDate, try self.date(fromFixture: "2013-09-20 11:20:28 +0000"))
}
func date(fromFixture string: String) throws -> Date {
let formatter = DateFormatter()
let calendar = Calendar(identifier: .gregorian)
formatter.calendar = calendar
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.locale = Locale(identifier: "en_US")
return try formatter.date(from: string).unwrapped()
}
func enumerateTestDates(using block: (NSCalendar, Date, NSDateComponents) throws -> Void) throws {
func yield(to block: (NSCalendar, Date, NSDateComponents) throws -> Void, _ element: (calendarIdentifier: NSCalendar.Identifier, localeIdentifier: String, timeZoneName: String, dateString: String)) throws {
let calendar = try NSCalendar(calendarIdentifier: element.calendarIdentifier).unwrapped()
let currentCalendar = NSCalendar.current as NSCalendar
let autoCalendar = NSCalendar.autoupdatingCurrent as NSCalendar
for aCalendar in [calendar, currentCalendar, autoCalendar] {
if aCalendar.calendarIdentifier != element.calendarIdentifier {
continue
}
let locale = NSLocale(localeIdentifier: element.localeIdentifier) as Locale
let timeZone = try TimeZone(identifier: element.timeZoneName).unwrapped()
calendar.locale = locale
calendar.timeZone = timeZone
let date = try self.date(fromFixture: element.dateString)
let components = calendar.components(self.allCalendarUnits, from: date) as NSDateComponents
try block(calendar, date, components)
}
}
try yield(to: block, (.gregorian, "en_US", "America/Edmonton", "1906-09-01 00:33:52 -0700"))
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-09-23 20:11:39 -0800"))
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2016-02-29 06:30:33 -0900"))
try yield(to: block, (.hebrew, "he_IL", "Israel", "2018-12-24 05:40:43 +0200"))
try yield(to: block, (.hebrew, "he_IL", "Israel", "2019-03-22 09:23:26 +0200"))
try yield(to: block, (.buddhist, "es_MX", "America/Cancun", "2022-10-26 23:05:34 -0500"))
try yield(to: block, (.buddhist, "es_MX", "America/Cancun", "2014-10-22 07:13:00 -0500"))
try yield(to: block, (.japanese, "ja_JP", "Asia/Tokyo", "2013-08-23 06:09:01 +0900"))
try yield(to: block, (.japanese, "ja_JP", "Asia/Tokyo", "2014-11-23 05:34:30 +0900"))
try yield(to: block, (.persian, "ps_AF", "Asia/Kabul", "2013-07-18 20:55:06 +0430"))
try yield(to: block, (.persian, "ps_AF", "Asia/Kabul", "2015-09-21 23:21:45 +0430"))
try yield(to: block, (.coptic, "ar_EG", "Africa/Cairo", "2013-12-22 19:49:15 +0200"))
try yield(to: block, (.coptic, "ar_EG", "Africa/Cairo", "2015-03-14 17:36:20 +0200"))
try yield(to: block, (.ethiopicAmeteMihret, "am_ET", "Africa/Addis_Ababa", "2014-01-31 10:10:33 +0300"))
try yield(to: block, (.ethiopicAmeteMihret, "am_ET", "Africa/Addis_Ababa", "2013-07-19 13:05:16 +0300"))
try yield(to: block, (.ethiopicAmeteAlem, "am_ET", "Africa/Addis_Ababa", "2015-02-28 16:34:34 +0300"))
try yield(to: block, (.ethiopicAmeteAlem, "am_ET", "Africa/Addis_Ababa", "2017-07-19 15:25:59 +0300"))
try yield(to: block, (.islamic, "ar_SA", "Asia/Riyadh", "2015-06-04 19:28:36 +0300"))
try yield(to: block, (.islamic, "ar_SA", "Asia/Riyadh", "2015-05-21 21:47:39 +0300"))
try yield(to: block, (.islamicCivil, "ar_SA", "Asia/Riyadh", "2002-05-05 22:44:18 +0300"))
try yield(to: block, (.islamicCivil, "ar_SA", "Asia/Riyadh", "2015-11-20 02:21:09 +0300"))
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2019-04-12 01:12:10 +0800"))
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2015-04-02 07:13:22 +0800"))
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2014-10-16 06:12:10 +0800"))
}
func test_getEra_year_month_day_fromDate() throws {
try enumerateTestDates() { (calendar, date, components) in
var era = 0, year = 0, month = 0, day = 0
calendar.getEra(&era, year: &year, month: &month, day: &day, from: date)
XCTAssertEqual(era, components.era)
XCTAssertEqual(year, components.year)
XCTAssertEqual(month, components.month)
XCTAssertEqual(day, components.day)
}
}
func test_getEra_yearForWeekOfYear_weekOfYear_weekday_fromDate() throws {
try enumerateTestDates() { (calendar, date, components) in
var era = 0, yearForWeekOfYear = 0, weekOfYear = 0, weekday = 0
calendar.getEra(&era, yearForWeekOfYear: &yearForWeekOfYear, weekOfYear: &weekOfYear, weekday: &weekday, from: date)
XCTAssertEqual(era, components.era)
XCTAssertEqual(yearForWeekOfYear, components.yearForWeekOfYear)
XCTAssertEqual(weekOfYear, components.weekOfYear)
XCTAssertEqual(weekday, components.weekday)
}
}
func test_getHour_minute_second_nanoseconds_fromDate() throws {
try enumerateTestDates() { (calendar, date, components) in
var hour = 0, minute = 0, second = 0, nanosecond = 0
calendar.getHour(&hour, minute: &minute, second: &second, nanosecond: &nanosecond, from: date)
XCTAssertEqual(hour, components.hour)
XCTAssertEqual(minute, components.minute)
XCTAssertEqual(second, components.second)
XCTAssertEqual(nanosecond, components.nanosecond)
}
}
func test_component_fromDate() throws {
try enumerateTestDates() { (calendar, date, components) in
for unit in iterableCalendarUnits {
if unit == .calendar || unit == .timeZone {
continue
}
let value = calendar.component(unit, from: date)
let expectedValue = components.value(forComponent: unit)
XCTAssertEqual(expectedValue, value)
}
}
}
func test_dateWithYear_month_day_hour_minute_second_nanosecond() throws {
try enumerateTestDates() { (calendar, date, components) in
let returnedDate = try calendar.date(era: components.era, year: components.year, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second, nanosecond: components.nanosecond).unwrapped()
let interval = date.timeIntervalSince(returnedDate)
XCTAssertEqual(fabs(interval), 0, accuracy: 0.0000001)
}
}
func test_dateWithYearForWeekOfYear_weekOfYear_weekday_hour_minute_second_nanosecond() throws {
try enumerateTestDates() { (calendar, date, components) in
// Era is defined to be in the current era, so the below can only work for dates that are in the current era.
if components.era != calendar.components(.era, from: Date()).era {
return
}
if (calendar.calendarIdentifier == .chinese) {
// chinese calendar does not work for yearForWeekOfYear
return;
}
let returnedDate = try calendar.date(era: components.era, yearForWeekOfYear: components.yearForWeekOfYear, weekOfYear: components.weekOfYear, weekday: components.weekday, hour: components.hour, minute: components.minute, second: components.second, nanosecond: components.nanosecond).unwrapped()
let interval = date.timeIntervalSince(returnedDate)
XCTAssertEqual(fabs(interval), 0, accuracy: 0.0000001)
}
}
func enumerateTestDatesWithStartOfDay(using block: (NSCalendar, Date, Date) throws -> Void) throws {
func yield(to block: (NSCalendar, Date, Date) throws -> Void, _ element: (calendarIdentifier: NSCalendar.Identifier, localeIdentifier: String, timeZoneName: String, dateString: String, startOfDayDateString: String)) throws {
let calendar = try NSCalendar(calendarIdentifier: element.calendarIdentifier).unwrapped()
let currentCalendar = NSCalendar.current as NSCalendar
let autoCalendar = NSCalendar.autoupdatingCurrent as NSCalendar
for aCalendar in [calendar, currentCalendar, autoCalendar] {
if aCalendar.calendarIdentifier != element.calendarIdentifier {
continue
}
let locale = NSLocale(localeIdentifier: element.localeIdentifier) as Locale
let timeZone = try TimeZone(identifier: element.timeZoneName).unwrapped()
calendar.locale = locale
calendar.timeZone = timeZone
let date = try self.date(fromFixture: element.dateString)
let startOfDay = try self.date(fromFixture: element.startOfDayDateString)
try block(calendar, date, startOfDay)
}
}
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2013-03-26 10:04:16 -0700", "2013-03-26 00:00:00 -0700"))
try yield(to: block, (.gregorian, "pt_BR", "Brazil/East", "2013-10-20 13:10:20 -0200", "2013-10-20 01:00:00 -0200")) // DST jump forward at midnight
try yield(to: block, (.gregorian, "pt_BR", "Brazil/East", "2014-02-15 23:59:59 -0300", "2014-02-15 00:00:00 -0200")) // DST jump backward
}
func test_startOfDayForDate() throws {
try enumerateTestDatesWithStartOfDay() { (calendar, date, startOfDay) in
let resultDate = calendar.startOfDay(for: date)
XCTAssertEqual(startOfDay, resultDate)
}
}
func test_componentsInTimeZone_fromDate() throws {
try enumerateTestDates() { (calendar, date, components) in
let calendarWithoutTimeZone = try NSCalendar(identifier: calendar.calendarIdentifier).unwrapped()
calendarWithoutTimeZone.locale = calendar.locale
let timeZone = calendar.timeZone
let returned = calendarWithoutTimeZone.components(in: timeZone, from: date) as NSDateComponents
XCTAssertEqual(components, returned)
}
}
func enumerateTestDateComparisons(using block: (NSCalendar, Date, Date, NSCalendar.Unit, ComparisonResult) throws -> Void) throws {
func yield(to block: (NSCalendar, Date, Date, NSCalendar.Unit, ComparisonResult) throws -> Void, _ element: (calendarIdentifier: NSCalendar.Identifier, localeIdentifier: String, timeZoneName: String, firstDateString: String, secondDateString: String, granularity: NSCalendar.Unit, expectedResult: ComparisonResult)) throws {
let calendar = try NSCalendar(calendarIdentifier: element.calendarIdentifier).unwrapped()
let currentCalendar = NSCalendar.current as NSCalendar
let autoCalendar = NSCalendar.autoupdatingCurrent as NSCalendar
for aCalendar in [calendar, currentCalendar, autoCalendar] {
if aCalendar.calendarIdentifier != element.calendarIdentifier {
continue
}
let locale = NSLocale(localeIdentifier: element.localeIdentifier) as Locale
let timeZone = try TimeZone(identifier: element.timeZoneName).unwrapped()
calendar.locale = locale
calendar.timeZone = timeZone
let firstDate = try self.date(fromFixture: element.firstDateString)
let secondDate = try self.date(fromFixture: element.secondDateString)
try block(calendar, firstDate, secondDate, element.granularity, element.expectedResult)
}
}
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-09-23 20:11:39 -0800", "2014-09-23 20:11:39 -0800", .year, .orderedSame))
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-09-23 20:11:39 -0800", "2014-09-23 20:11:39 -0800", .month, .orderedSame))
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-09-23 20:11:39 -0800", "2014-09-23 20:11:39 -0800", .day, .orderedSame))
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-09-23 20:11:39 -0800", "2014-09-23 20:11:39 -0800", .hour, .orderedSame))
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-09-23 20:11:39 -0800", "2014-09-23 20:11:39 -0800", .minute, .orderedSame))
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-09-23 20:11:39 -0800", "2014-09-23 20:11:39 -0800", .second, .orderedSame))
// DST fall back
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-11-02 01:30:00 -0700", "2014-11-02 01:30:00 -0800", .day, .orderedSame))
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-11-02 01:30:00 -0700", "2014-11-02 01:30:00 -0800", .hour, .orderedAscending))
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-11-02 01:30:00 -0700", "2014-11-02 01:30:00 -0800", .minute, .orderedAscending))
try yield(to: block, (.gregorian, "en_US", "America/Los_Angeles", "2014-11-02 01:30:00 -0700", "2014-11-02 01:30:00 -0800", .second, .orderedAscending))
// Chinese leap month. First date is not a leap month, 2nd is. Same day.
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2014-10-07 21:12:10 +0000", "2014-11-06 21:12:10 +0000", .era, .orderedSame))
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2014-10-07 21:12:10 +0000", "2014-11-06 21:12:10 +0000", .year, .orderedSame))
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2014-10-07 21:12:10 +0000", "2014-11-06 21:12:10 +0000", .month, .orderedAscending))
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2014-10-07 21:12:10 +0000", "2014-11-06 21:12:10 +0000", .day, .orderedAscending))
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2014-10-07 21:12:10 +0000", "2014-11-06 21:12:10 +0000", .hour, .orderedAscending))
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2014-10-07 21:12:10 +0000", "2014-11-06 21:12:10 +0000", .minute, .orderedAscending))
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2014-10-07 21:12:10 +0000", "2014-11-06 21:12:10 +0000", .second, .orderedAscending))
// Different eras. era: 235, year: 23, month: 1, day: 22 vs era: 234, year: 23, month: 1, day: 22
try yield(to: block, (.japanese, "ja_JP", "Asia/Tokyo", "2011-01-23 06:12:10 +0900", "1948-01-23 06:12:10 +0900", .era, .orderedDescending))
try yield(to: block, (.japanese, "ja_JP", "Asia/Tokyo", "2011-01-23 06:12:10 +0900", "1948-01-23 06:12:10 +0900", .year, .orderedDescending))
try yield(to: block, (.japanese, "ja_JP", "Asia/Tokyo", "2011-01-23 06:12:10 +0900", "1948-01-23 06:12:10 +0900", .month, .orderedDescending))
try yield(to: block, (.japanese, "ja_JP", "Asia/Tokyo", "2011-01-23 06:12:10 +0900", "1948-01-23 06:12:10 +0900", .day, .orderedDescending))
try yield(to: block, (.japanese, "ja_JP", "Asia/Tokyo", "2011-01-23 06:12:10 +0900", "1948-01-23 06:12:10 +0900", .hour, .orderedDescending))
try yield(to: block, (.japanese, "ja_JP", "Asia/Tokyo", "2011-01-23 06:12:10 +0900", "1948-01-23 06:12:10 +0900", .minute, .orderedDescending))
try yield(to: block, (.japanese, "ja_JP", "Asia/Tokyo", "2011-01-23 06:12:10 +0900", "1948-01-23 06:12:10 +0900", .second, .orderedDescending))
// Same week and week of year, different non-week year.
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-30 02:34:56 +0000", "2013-01-04 02:34:56 +0000", .yearForWeekOfYear, .orderedSame))
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-30 02:34:56 +0000", "2013-01-04 02:34:56 +0000", .weekOfYear, .orderedSame))
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-30 02:34:56 +0000", "2013-01-04 02:34:56 +0000", .weekOfMonth, .orderedAscending))
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-30 02:34:56 +0000", "2013-01-04 02:34:56 +0000", .weekday, .orderedAscending))
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-30 02:34:56 +0000", "2013-01-04 02:34:56 +0000", .weekdayOrdinal, .orderedAscending))
// Same non-week year, different week of year
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-30 02:34:56 +0000", "2012-12-29 02:34:56 +0000", .yearForWeekOfYear, .orderedDescending))
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-30 02:34:56 +0000", "2012-12-29 02:34:56 +0000", .weekOfYear, .orderedDescending))
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-30 02:34:56 +0000", "2012-12-29 02:34:56 +0000", .weekOfMonth, .orderedDescending))
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-30 02:34:56 +0000", "2012-12-29 02:34:56 +0000", .weekday, .orderedDescending))
// Same week, different weekday ordinal
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-14 02:34:56 +0000", "2012-12-15 02:34:56 +0000", .weekOfYear, .orderedSame))
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-14 02:34:56 +0000", "2012-12-15 02:34:56 +0000", .weekOfMonth, .orderedSame))
try yield(to: block, (.buddhist, "zh-Hans_HK", "Asia/Hong_Kong", "2012-12-14 02:34:56 +0000", "2012-12-15 02:34:56 +0000", .weekdayOrdinal, .orderedAscending))
}
func test_compareDate_toDate_toUnitGranularity() throws {
try enumerateTestDateComparisons { (calendar, firstDate, secondDate, granularity, result) in
let returned = calendar.compare(firstDate, to: secondDate, toUnitGranularity: granularity)
XCTAssertEqual(returned, result, "Comparison result should match; expected \(result), got \(returned), when comparing \(firstDate) (\(firstDate.timeIntervalSinceReferenceDate) to \(secondDate) (\(secondDate.timeIntervalSinceReferenceDate) with granularity \(granularity)")
}
}
func test_isDate_equalToDate_toUnitGranularity() throws {
try enumerateTestDateComparisons { (calendar, firstDate, secondDate, granularity, result) in
let expected = result == .orderedSame
let returned = calendar.isDate(firstDate, equalTo: secondDate, toUnitGranularity: granularity)
XCTAssertEqual(returned, expected)
}
}
let availableCalendarIdentifiers: [NSCalendar.Identifier] = [
.gregorian,
.buddhist,
.chinese,
.coptic,
.ethiopicAmeteMihret,
.ethiopicAmeteAlem,
.hebrew,
.ISO8601,
.indian,
.islamic,
.islamicCivil,
.japanese,
.persian,
.republicOfChina,
.islamicTabular,
.islamicUmmAlQura,
]
func test_isDateInToday() throws {
var datesTested: [Date] = []
for identifier in availableCalendarIdentifiers {
let calendar = try NSCalendar(identifier: identifier).unwrapped()
var foundDate = false
var dateInToday = Date()
for _ in 0..<10 {
datesTested.append(dateInToday)
if calendar.isDateInToday(dateInToday) {
foundDate = true
break
}
dateInToday += 1
}
XCTAssertTrue(foundDate, "Unable to match any of these dates: \(datesTested)")
// Makes sure it doesn't work for other dates:
XCTAssertFalse(calendar.isDateInToday(Date.distantPast), "Shouldn't match the distant past")
XCTAssertFalse(calendar.isDateInToday(Date.distantFuture), "Shouldn't match the distant future")
}
}
func test_isDateInYesterday() throws {
var datesTested: [Date] = []
for identifier in availableCalendarIdentifiers {
let calendar = try NSCalendar(identifier: identifier).unwrapped()
var foundDate = false
var dateInToday = Date()
for _ in 0..<10 {
let delta = NSDateComponents()
delta.day = -1
let dateInYesterday = try calendar.date(byAdding: delta as DateComponents, to: dateInToday).unwrapped()
datesTested.append(dateInYesterday)
if calendar.isDateInYesterday(dateInYesterday) {
foundDate = true
break
}
dateInToday += 1
}
XCTAssertTrue(foundDate, "Unable to match any of these dates: \(datesTested)")
// Makes sure it doesn't work for other dates:
XCTAssertFalse(calendar.isDateInYesterday(Date.distantPast), "Shouldn't match the distant past")
XCTAssertFalse(calendar.isDateInYesterday(Date.distantFuture), "Shouldn't match the distant future")
}
}
func test_isDateInTomorrow() throws {
var datesTested: [Date] = []
for identifier in availableCalendarIdentifiers {
let calendar = try NSCalendar(identifier: identifier).unwrapped()
var foundDate = false
var dateInToday = Date()
for _ in 0..<10 {
let delta = NSDateComponents()
delta.day = 1
let dateInTomorrow = try calendar.date(byAdding: delta as DateComponents, to: dateInToday).unwrapped()
datesTested.append(dateInTomorrow)
if calendar.isDateInTomorrow(dateInTomorrow) {
foundDate = true
break
}
dateInToday += 1
}
XCTAssertTrue(foundDate, "Unable to match any of these dates: \(datesTested)")
// Makes sure it doesn't work for other dates:
XCTAssertFalse(calendar.isDateInTomorrow(Date.distantPast), "Shouldn't match the distant past")
XCTAssertFalse(calendar.isDateInTomorrow(Date.distantFuture), "Shouldn't match the distant future")
}
}
func enumerateTestWeekends(using block: (NSCalendar, DateInterval) throws -> Void) throws {
func yield(to block: (NSCalendar, DateInterval) throws -> Void, _ element: (calendarIdentifier: NSCalendar.Identifier, localeIdentifier: String, timeZoneName: String, firstDateString: String, secondDateString: String)) throws {
let calendar = try NSCalendar(calendarIdentifier: element.calendarIdentifier).unwrapped()
let locale = NSLocale(localeIdentifier: element.localeIdentifier) as Locale
let timeZone = try TimeZone(identifier: element.timeZoneName).unwrapped()
calendar.locale = locale
calendar.timeZone = timeZone
let firstDate = try self.date(fromFixture: element.firstDateString)
let secondDate = try self.date(fromFixture: element.secondDateString)
try block(calendar, DateInterval(start: firstDate, end: secondDate))
}
try yield(to: block, (.gregorian, "en_US", "America/Edmonton", "1906-09-01 00:33:52 -0700", "1906-09-03 00:00:00 -0700")) // suprise weekend 1
try yield(to: block, (.gregorian, "en_US", "Asia/Damascus", "2006-04-01 01:00:00 +0300", "2006-04-03 00:00:00 +0300")) // suprise weekend 2
try yield(to: block, (.gregorian, "en_US", "Asia/Tehran", "2014-03-22 01:00:00 +0430", "2014-03-24 00:00:00 +0430")) // suprise weekend 3
try yield(to: block, (.gregorian, "en_US", "Africa/Algiers", "1971-04-24 00:00:00 +0000", "1971-04-26 00:00:00 +0100")) // suprise weekday 1
try yield(to: block, (.gregorian, "en_US", "America/Toronto", "1919-03-29 00:00:00 -0500", "1919-03-31 00:30:00 -0400")) // suprise weekday 2
try yield(to: block, (.gregorian, "en_US", "Europe/Madrid", "1978-04-01 00:00:00 +0100", "1978-04-03 00:00:00 +0200")) // suprise weekday 3
try yield(to: block, (.hebrew, "he_IL", "Israel", "2018-03-23 00:00:00 +0200", "2018-03-25 00:00:00 +0300")) // weekend with DST jump
try yield(to: block, (.japanese, "ja_JP", "Asia/Tokyo", "2015-08-22 00:00:00 +0900", "2015-08-24 00:00:00 +0900")) // japanese
try yield(to: block, (.persian, "ps_AF", "Asia/Kabul", "2015-03-19 00:00:00 +0430", "2015-03-21 00:00:00 +0430")) // persian
try yield(to: block, (.coptic, "ar_EG", "Africa/Cairo", "2015-12-18 00:00:00 +0200", "2015-12-20 00:00:00 +0200")) // coptic
try yield(to: block, (.ethiopicAmeteMihret, "am_ET", "Africa/Addis_Ababa", "2015-07-25 00:00:00 +0300", "2015-07-27 00:00:00 +0300")) // ethiopic
try yield(to: block, (.ethiopicAmeteAlem, "am_ET", "Africa/Addis_Ababa", "2015-07-25 00:00:00 +0300", "2015-07-27 00:00:00 +0300")) // ethiopic-amete-alem
try yield(to: block, (.islamic, "ar_SA", "Asia/Riyadh", "2015-05-29 00:00:00 +0300", "2015-05-31 00:00:00 +0300")) // islamic
try yield(to: block, (.islamicCivil, "ar_SA", "Asia/Riyadh", "2015-05-29 00:00:00 +0300", "2015-05-31 00:00:00 +0300")) // islamic-civil
try yield(to: block, (.chinese, "zh_CN", "Asia/Hong_Kong", "2015-01-03 00:00:00 +0800", "2015-01-05 00:00:00 +0800")) // chinese
}
func test_isDateInWeekend() throws {
try enumerateTestWeekends() { (calendar, interval) in
XCTAssertTrue(calendar.isDateInWeekend(interval.start), "Start date should be in weekend")
XCTAssertFalse(calendar.isDateInWeekend(interval.end), "End date should not be in weekend")
XCTAssertFalse(calendar.isDateInWeekend(interval.start - 1), "Just before start date should not be in weekend")
XCTAssertTrue(calendar.isDateInWeekend(interval.end - 1), "Just before end date should be in weekend")
}
}
func test_rangeOfWeekendStartDate_interval_containingDate() throws {
try enumerateTestWeekends() { (calendar, interval) in
let startDateResult = calendar.range(ofWeekendContaining: interval.start)
XCTAssertEqual(startDateResult, interval)
let endDateResult = calendar.range(ofWeekendContaining: interval.end)
XCTAssertNil(endDateResult)
let oneSecondBeforeStartResult = calendar.range(ofWeekendContaining: interval.start - 1)
XCTAssertNil(oneSecondBeforeStartResult)
let oneSecondBeforeEndResult = calendar.range(ofWeekendContaining: interval.end - 1)
XCTAssertEqual(oneSecondBeforeEndResult, interval)
}
}
func test_enumerateDatesStartingAfterDate_chineseEra_matchYearOne() throws {
let calendar = try NSCalendar(calendarIdentifier: .chinese).unwrapped()
let locale = Locale(identifier: "zh_CN")
let timeZone = try TimeZone(identifier: "Asia/Chongqing").unwrapped()
calendar.locale = locale
calendar.timeZone = timeZone
let startDate = try date(fromFixture: "2013-06-19 15:59:59 +0000")
let matchingComponents = NSDateComponents()
matchingComponents.year = 1
let expectedDate = try date(fromFixture: "1984-02-01 16:00:00 +0000")
var atLeastOnce = false
calendar.enumerateDates(startingAfter: startDate, matching: matchingComponents as DateComponents, options: [.matchStrictly, .searchBackwards]) { (date, exactMatch, stop) in
atLeastOnce = true
if let date = date {
XCTAssertEqual(expectedDate, date)
XCTAssertTrue(exactMatch)
stop.pointee = true
}
}
XCTAssertTrue(atLeastOnce)
}
struct TimeIntervalQuintuple {
var value: (TimeInterval, TimeInterval, TimeInterval, TimeInterval, TimeInterval) = (0, 0, 0, 0, 0)
subscript(_ index: Int) -> TimeInterval {
switch index {
case 0:
return value.0
case 1:
return value.1
case 2:
return value.2
case 3:
return value.3
case 4:
return value.4
default:
fatalError()
}
}
let count = 5
init(_ a: TimeInterval, _ b: TimeInterval, _ c: TimeInterval, _ d: TimeInterval, _ e: TimeInterval) {
value = (a, b, c, d, e)
}
}
func test_enumerateDatesStartingAfterDate_ensureStrictlyIncreasingResults_minuteSecondClearing() throws {
// When we match a specific hour in date enumeration, we clear out lower units (minute and second). This can cause us to accidentally match the components backwards, when we otherwise wouldn't have (e.g. 2018-02-14 00:00:01 -> 2018-02-14 00:00:00).
// This leads us to propose a potential match twice in certain circumstances (when the highest set date component is hour and we're looking for hour 0).
//
// We want to ensure this never happens, and that all matches are strictly increasing or decreasing in time.
let calendar = try NSCalendar(identifier: .gregorian).unwrapped()
calendar.timeZone = try TimeZone(identifier: "America/Los_Angeles").unwrapped()
let reference = try date(fromFixture: "2018-02-13 12:00:00 -0800")
let expectations: [(minute: Int, second: Int, results: TimeIntervalQuintuple)] = [
(NSDateComponentUndefined, NSDateComponentUndefined, TimeIntervalQuintuple(540288000, 540374400, 540460800, 540547200, 540633600)),
(0 , NSDateComponentUndefined, TimeIntervalQuintuple(540288000, 540374400, 540460800, 540547200, 540633600)),
(NSDateComponentUndefined, 0 , TimeIntervalQuintuple(540288000, 540374400, 540460800, 540547200, 540633600)),
(0 , 0 , TimeIntervalQuintuple(540288000, 540374400, 540460800, 540547200, 540633600)),
]
for expectation in expectations {
let matchComponents = NSDateComponents()
matchComponents.hour = 0
matchComponents.minute = expectation.minute
matchComponents.second = expectation.second
var j = 0
calendar.enumerateDates(startingAfter: reference, matching: matchComponents as DateComponents, options: .matchNextTime) { (match, exactMatch, stop) in
let expected = Date(timeIntervalSinceReferenceDate: TimeInterval(expectation.results[j]))
XCTAssertTrue(exactMatch)
XCTAssertEqual(match, expected)
j += 1
guard j < expectation.results.count else {
stop.pointee = true
return
}
}
}
}
static var allTests: [(String, (TestNSCalendar) -> () throws -> Void)] {
return [
("test_initWithCalendarIdentifier", test_initWithCalendarIdentifier),
("test_calendarWithIdentifier", test_calendarWithIdentifier),
("test_calendarOptions", test_calendarOptions),
("test_isEqualWithDifferentWaysToCreateCalendar", test_isEqualWithDifferentWaysToCreateCalendar),
("test_isEqual", test_isEqual),
("test_isEqualCurrentCalendar", test_isEqualCurrentCalendar),
("test_isEqualAutoUpdatingCurrentCalendar", test_isEqualAutoUpdatingCurrentCalendar),
("test_copy", test_copy),
("test_copyCurrentCalendar", test_copyCurrentCalendar),
("test_next50MonthsFromDate", test_next50MonthsFromDate),
("test_dateByAddingUnit_withWrapOption", test_dateByAddingUnit_withWrapOption),
("test_getEra_year_month_day_fromDate", test_getEra_year_month_day_fromDate),
("test_getEra_yearForWeekOfYear_weekOfYear_weekday_fromDate", test_getEra_yearForWeekOfYear_weekOfYear_weekday_fromDate),
("test_getHour_minute_second_nanoseconds_fromDate", test_getHour_minute_second_nanoseconds_fromDate),
("test_component_fromDate", test_component_fromDate),
("test_dateWithYear_month_day_hour_minute_second_nanosecond", test_dateWithYear_month_day_hour_minute_second_nanosecond),
("test_dateWithYearForWeekOfYear_weekOfYear_weekday_hour_minute_second_nanosecond", test_dateWithYearForWeekOfYear_weekOfYear_weekday_hour_minute_second_nanosecond),
("test_startOfDayForDate", test_startOfDayForDate),
("test_componentsInTimeZone_fromDate", test_componentsInTimeZone_fromDate),
("test_compareDate_toDate_toUnitGranularity", test_compareDate_toDate_toUnitGranularity),
("test_isDate_equalToDate_toUnitGranularity", test_isDate_equalToDate_toUnitGranularity),
("test_isDateInToday", test_isDateInToday),
("test_isDateInYesterday", test_isDateInYesterday),
("test_isDateInTomorrow", test_isDateInTomorrow),
("test_isDateInWeekend", test_isDateInWeekend),
("test_rangeOfWeekendStartDate_interval_containingDate", test_rangeOfWeekendStartDate_interval_containingDate),
("test_enumerateDatesStartingAfterDate_chineseEra_matchYearOne", test_enumerateDatesStartingAfterDate_chineseEra_matchYearOne),
("test_enumerateDatesStartingAfterDate_ensureStrictlyIncreasingResults_minuteSecondClearing", test_enumerateDatesStartingAfterDate_ensureStrictlyIncreasingResults_minuteSecondClearing),
]
}
}
| apache-2.0 | 3cf689fa9fefdb985b7df8b965b07779 | 55.044893 | 332 | 0.608038 | 4.202306 | false | true | false | false |
caicai0/ios_demo | load/Carthage/Checkouts/SwiftSoup/Example/Pods/SwiftSoup/Sources/HtmlTreeBuilderState.swift | 1 | 75192 | //
// HtmlTreeBuilderState.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 24/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
protocol HtmlTreeBuilderStateProtocol {
func process(_ t: Token, _ tb: HtmlTreeBuilder)throws->Bool
}
enum HtmlTreeBuilderState: String, HtmlTreeBuilderStateProtocol {
case Initial
case BeforeHtml
case BeforeHead
case InHead
case InHeadNoscript
case AfterHead
case InBody
case Text
case InTable
case InTableText
case InCaption
case InColumnGroup
case InTableBody
case InRow
case InCell
case InSelect
case InSelectInTable
case AfterBody
case InFrameset
case AfterFrameset
case AfterAfterBody
case AfterAfterFrameset
case ForeignContent
private static let nullString: String = "\u{0000}"
public func equals(_ s: HtmlTreeBuilderState) -> Bool {
return self.hashValue == s.hashValue
}
func process(_ t: Token, _ tb: HtmlTreeBuilder)throws->Bool {
switch self {
case .Initial:
if (HtmlTreeBuilderState.isWhitespace(t)) {
return true // ignore whitespace
} else if (t.isComment()) {
try tb.insert(t.asComment())
} else if (t.isDoctype()) {
// todo: parse error check on expected doctypes
// todo: quirk state check on doctype ids
let d: Token.Doctype = t.asDoctype()
let doctype: DocumentType = DocumentType(
tb.settings.normalizeTag(d.getName()), d.getPubSysKey(), d.getPublicIdentifier(), d.getSystemIdentifier(), tb.getBaseUri())
//tb.settings.normalizeTag(d.getName()), d.getPublicIdentifier(), d.getSystemIdentifier(), tb.getBaseUri())
try tb.getDocument().appendChild(doctype)
if (d.isForceQuirks()) {
tb.getDocument().quirksMode(Document.QuirksMode.quirks)
}
tb.transition(.BeforeHtml)
} else {
// todo: check not iframe srcdoc
tb.transition(.BeforeHtml)
return try tb.process(t) // re-process token
}
return true
case .BeforeHtml:
func anythingElse(_ t: Token, _ tb: HtmlTreeBuilder)throws->Bool {
try tb.insertStartTag("html")
tb.transition(.BeforeHead)
return try tb.process(t)
}
if (t.isDoctype()) {
tb.error(self)
return false
} else if (t.isComment()) {
try tb.insert(t.asComment())
} else if (HtmlTreeBuilderState.isWhitespace(t)) {
return true // ignore whitespace
} else if (t.isStartTag() && (t.asStartTag().normalName()?.equals("html"))!) {
try tb.insert(t.asStartTag())
tb.transition(.BeforeHead)
} else if (t.isEndTag() && (StringUtil.inString(t.asEndTag().normalName()!, haystack: "head", "body", "html", "br"))) {
return try anythingElse(t, tb)
} else if (t.isEndTag()) {
tb.error(self)
return false
} else {
return try anythingElse(t, tb)
}
return true
case .BeforeHead:
if (HtmlTreeBuilderState.isWhitespace(t)) {
return true
} else if (t.isComment()) {
try tb.insert(t.asComment())
} else if (t.isDoctype()) {
tb.error(self)
return false
} else if (t.isStartTag() && (t.asStartTag().normalName()?.equals("html"))!) {
return try HtmlTreeBuilderState.InBody.process(t, tb) // does not transition
} else if (t.isStartTag() && (t.asStartTag().normalName()?.equals("head"))!) {
let head: Element = try tb.insert(t.asStartTag())
tb.setHeadElement(head)
tb.transition(.InHead)
} else if (t.isEndTag() && (StringUtil.inString(t.asEndTag().normalName()!, haystack: "head", "body", "html", "br"))) {
try tb.processStartTag("head")
return try tb.process(t)
} else if (t.isEndTag()) {
tb.error(self)
return false
} else {
try tb.processStartTag("head")
return try tb.process(t)
}
return true
case .InHead:
func anythingElse(_ t: Token, _ tb: TreeBuilder)throws->Bool {
try tb.processEndTag("head")
return try tb.process(t)
}
if (HtmlTreeBuilderState.isWhitespace(t)) {
try tb.insert(t.asCharacter())
return true
}
switch (t.type) {
case .Comment:
try tb.insert(t.asComment())
break
case .Doctype:
tb.error(self)
return false
case .StartTag:
let start: Token.StartTag = t.asStartTag()
var name: String = start.normalName()!
if (name.equals("html")) {
return try HtmlTreeBuilderState.InBody.process(t, tb)
} else if (StringUtil.inString(name, haystack: "base", "basefont", "bgsound", "command", "link")) {
let el: Element = try tb.insertEmpty(start)
// jsoup special: update base the frist time it is seen
if (name.equals("base") && el.hasAttr("href")) {
try tb.maybeSetBaseUri(el)
}
} else if (name.equals("meta")) {
let meta: Element = try tb.insertEmpty(start)
// todo: charset switches
} else if (name.equals("title")) {
try HtmlTreeBuilderState.handleRcData(start, tb)
} else if (StringUtil.inString(name, haystack:"noframes", "style")) {
try HtmlTreeBuilderState.handleRawtext(start, tb)
} else if (name.equals("noscript")) {
// else if noscript && scripting flag = true: rawtext (jsoup doesn't run script, to handle as noscript)
try tb.insert(start)
tb.transition(.InHeadNoscript)
} else if (name.equals("script")) {
// skips some script rules as won't execute them
tb.tokeniser.transition(TokeniserState.ScriptData)
tb.markInsertionMode()
tb.transition(.Text)
try tb.insert(start)
} else if (name.equals("head")) {
tb.error(self)
return false
} else {
return try anythingElse(t, tb)
}
break
case .EndTag:
let end: Token.EndTag = t.asEndTag()
let name = end.normalName()
if (name?.equals("head"))! {
tb.pop()
tb.transition(.AfterHead)
} else if (name != nil && StringUtil.inString(name!, haystack:"body", "html", "br")) {
return try anythingElse(t, tb)
} else {
tb.error(self)
return false
}
break
default:
return try anythingElse(t, tb)
}
return true
case .InHeadNoscript:
func anythingElse(_ t: Token, _ tb: HtmlTreeBuilder)throws->Bool {
tb.error(self)
try tb.insert(Token.Char().data(t.toString()))
return true
}
if (t.isDoctype()) {
tb.error(self)
} else if (t.isStartTag() && (t.asStartTag().normalName()?.equals("html"))!) {
return try tb.process(t, .InBody)
} else if (t.isEndTag() && (t.asEndTag().normalName()?.equals("noscript"))!) {
tb.pop()
tb.transition(.InHead)
} else if (HtmlTreeBuilderState.isWhitespace(t) || t.isComment() || (t.isStartTag() && StringUtil.inString(t.asStartTag().normalName()!,
haystack: "basefont", "bgsound", "link", "meta", "noframes", "style"))) {
return try tb.process(t, .InHead)
} else if (t.isEndTag() && (t.asEndTag().normalName()?.equals("br"))!) {
return try anythingElse(t, tb)
} else if ((t.isStartTag() && StringUtil.inString(t.asStartTag().normalName()!, haystack: "head", "noscript")) || t.isEndTag()) {
tb.error(self)
return false
} else {
return try anythingElse(t, tb)
}
return true
case .AfterHead:
@discardableResult
func anythingElse(_ t: Token, _ tb: HtmlTreeBuilder)throws->Bool {
try tb.processStartTag("body")
tb.framesetOk(true)
return try tb.process(t)
}
if (HtmlTreeBuilderState.isWhitespace(t)) {
try tb.insert(t.asCharacter())
} else if (t.isComment()) {
try tb.insert(t.asComment())
} else if (t.isDoctype()) {
tb.error(self)
} else if (t.isStartTag()) {
let startTag: Token.StartTag = t.asStartTag()
let name: String = startTag.normalName()!
if (name.equals("html")) {
return try tb.process(t, .InBody)
} else if (name.equals("body")) {
try tb.insert(startTag)
tb.framesetOk(false)
tb.transition(.InBody)
} else if (name.equals("frameset")) {
try tb.insert(startTag)
tb.transition(.InFrameset)
} else if (StringUtil.inString(name, haystack: "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "title")) {
tb.error(self)
let head: Element = tb.getHeadElement()!
tb.push(head)
try tb.process(t, .InHead)
tb.removeFromStack(head)
} else if (name.equals("head")) {
tb.error(self)
return false
} else {
try anythingElse(t, tb)
}
} else if (t.isEndTag()) {
if (StringUtil.inString(t.asEndTag().normalName()!, haystack: "body", "html")) {
try anythingElse(t, tb)
} else {
tb.error(self)
return false
}
} else {
try anythingElse(t, tb)
}
return true
case .InBody:
func anyOtherEndTag(_ t: Token, _ tb: HtmlTreeBuilder) -> Bool {
let name: String? = t.asEndTag().normalName()
let stack: Array<Element> = tb.getStack()
for pos in (0..<stack.count).reversed() {
let node: Element = stack[pos]
if (name != nil && node.nodeName().equals(name!)) {
tb.generateImpliedEndTags(name)
if (!name!.equals((tb.currentElement()?.nodeName())!)) {
tb.error(self)
}
tb.popStackToClose(name!)
break
} else {
if (tb.isSpecial(node)) {
tb.error(self)
return false
}
}
}
return true
}
switch (t.type) {
case Token.TokenType.Char:
let c: Token.Char = t.asCharacter()
if (c.getData() != nil && c.getData()!.equals(HtmlTreeBuilderState.nullString)) {
// todo confirm that check
tb.error(self)
return false
} else if (tb.framesetOk() && HtmlTreeBuilderState.isWhitespace(c)) { // don't check if whitespace if frames already closed
try tb.reconstructFormattingElements()
try tb.insert(c)
} else {
try tb.reconstructFormattingElements()
try tb.insert(c)
tb.framesetOk(false)
}
break
case Token.TokenType.Comment:
try tb.insert(t.asComment())
break
case Token.TokenType.Doctype:
tb.error(self)
return false
case Token.TokenType.StartTag:
let startTag: Token.StartTag = t.asStartTag()
if let name: String = startTag.normalName() {
if (name.equals("a")) {
if (tb.getActiveFormattingElement("a") != nil) {
tb.error(self)
try tb.processEndTag("a")
// still on stack?
let remainingA: Element? = tb.getFromStack("a")
if (remainingA != nil) {
tb.removeFromActiveFormattingElements(remainingA)
tb.removeFromStack(remainingA!)
}
}
try tb.reconstructFormattingElements()
let a = try tb.insert(startTag)
tb.pushActiveFormattingElements(a)
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyStartEmptyFormatters)) {
try tb.reconstructFormattingElements()
try tb.insertEmpty(startTag)
tb.framesetOk(false)
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyStartPClosers)) {
if (try tb.inButtonScope("p")) {
try tb.processEndTag("p")
}
try tb.insert(startTag)
} else if (name.equals("span")) {
// same as final else, but short circuits lots of checks
try tb.reconstructFormattingElements()
try tb.insert(startTag)
} else if (name.equals("li")) {
tb.framesetOk(false)
let stack: Array<Element> = tb.getStack()
for i in (0..<stack.count).reversed() {
let el: Element = stack[i]
if (el.nodeName().equals("li")) {
try tb.processEndTag("li")
break
}
if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), haystack: Constants.InBodyStartLiBreakers)) {
break
}
}
if (try tb.inButtonScope("p")) {
try tb.processEndTag("p")
}
try tb.insert(startTag)
} else if (name.equals("html")) {
tb.error(self)
// merge attributes onto real html
let html: Element = tb.getStack()[0]
for attribute in startTag.getAttributes().iterator() {
if (!html.hasAttr(attribute.getKey())) {
html.getAttributes()?.put(attribute: attribute)
}
}
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyStartToHead)) {
return try tb.process(t, .InHead)
} else if (name.equals("body")) {
tb.error(self)
let stack: Array<Element> = tb.getStack()
if (stack.count == 1 || (stack.count > 2 && !stack[1].nodeName().equals("body"))) {
// only in fragment case
return false // ignore
} else {
tb.framesetOk(false)
let body: Element = stack[1]
for attribute: Attribute in startTag.getAttributes().iterator() {
if (!body.hasAttr(attribute.getKey())) {
body.getAttributes()?.put(attribute: attribute)
}
}
}
} else if (name.equals("frameset")) {
tb.error(self)
var stack: Array<Element> = tb.getStack()
if (stack.count == 1 || (stack.count > 2 && !stack[1].nodeName().equals("body"))) {
// only in fragment case
return false // ignore
} else if (!tb.framesetOk()) {
return false // ignore frameset
} else {
let second: Element = stack[1]
if (second.parent() != nil) {
try second.remove()
}
// pop up to html element
while (stack.count > 1) {
stack.remove(at: stack.count-1)
}
try tb.insert(startTag)
tb.transition(.InFrameset)
}
} else if (StringUtil.inSorted(name, haystack: Constants.Headings)) {
if (try tb.inButtonScope("p")) {
try tb.processEndTag("p")
}
if (tb.currentElement() != nil && StringUtil.inSorted(tb.currentElement()!.nodeName(), haystack: Constants.Headings)) {
tb.error(self)
tb.pop()
}
try tb.insert(startTag)
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyStartPreListing)) {
if (try tb.inButtonScope("p")) {
try tb.processEndTag("p")
}
try tb.insert(startTag)
// todo: ignore LF if next token
tb.framesetOk(false)
} else if (name.equals("form")) {
if (tb.getFormElement() != nil) {
tb.error(self)
return false
}
if (try tb.inButtonScope("p")) {
try tb.processEndTag("p")
}
try tb.insertForm(startTag, true)
} else if (StringUtil.inSorted(name, haystack: Constants.DdDt)) {
tb.framesetOk(false)
let stack: Array<Element> = tb.getStack()
for i in (1..<stack.count).reversed() {
let el: Element = stack[i]
if (StringUtil.inSorted(el.nodeName(), haystack: Constants.DdDt)) {
try tb.processEndTag(el.nodeName())
break
}
if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), haystack: Constants.InBodyStartLiBreakers)) {
break
}
}
if (try tb.inButtonScope("p")) {
try tb.processEndTag("p")
}
try tb.insert(startTag)
} else if (name.equals("plaintext")) {
if (try tb.inButtonScope("p")) {
try tb.processEndTag("p")
}
try tb.insert(startTag)
tb.tokeniser.transition(TokeniserState.PLAINTEXT) // once in, never gets out
} else if (name.equals("button")) {
if (try tb.inButtonScope("button")) {
// close and reprocess
tb.error(self)
try tb.processEndTag("button")
try tb.process(startTag)
} else {
try tb.reconstructFormattingElements()
try tb.insert(startTag)
tb.framesetOk(false)
}
} else if (StringUtil.inSorted(name, haystack: Constants.Formatters)) {
try tb.reconstructFormattingElements()
let el: Element = try tb.insert(startTag)
tb.pushActiveFormattingElements(el)
} else if (name.equals("nobr")) {
try tb.reconstructFormattingElements()
if (try tb.inScope("nobr")) {
tb.error(self)
try tb.processEndTag("nobr")
try tb.reconstructFormattingElements()
}
let el: Element = try tb.insert(startTag)
tb.pushActiveFormattingElements(el)
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyStartApplets)) {
try tb.reconstructFormattingElements()
try tb.insert(startTag)
tb.insertMarkerToFormattingElements()
tb.framesetOk(false)
} else if (name.equals("table")) {
if (try tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) {
try tb.processEndTag("p")
}
try tb.insert(startTag)
tb.framesetOk(false)
tb.transition(.InTable)
} else if (name.equals("input")) {
try tb.reconstructFormattingElements()
let el: Element = try tb.insertEmpty(startTag)
if (try !el.attr("type").equalsIgnoreCase(string: "hidden")) {
tb.framesetOk(false)
}
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyStartMedia)) {
try tb.insertEmpty(startTag)
} else if (name.equals("hr")) {
if (try tb.inButtonScope("p")) {
try tb.processEndTag("p")
}
try tb.insertEmpty(startTag)
tb.framesetOk(false)
} else if (name.equals("image")) {
if (tb.getFromStack("svg") == nil) {
return try tb.process(startTag.name("img")) // change <image> to <img>, unless in svg
} else {
try tb.insert(startTag)
}
} else if (name.equals("isindex")) {
// how much do we care about the early 90s?
tb.error(self)
if (tb.getFormElement() != nil) {
return false
}
tb.tokeniser.acknowledgeSelfClosingFlag()
try tb.processStartTag("form")
if (startTag._attributes.hasKey(key: "action")) {
if let form: Element = tb.getFormElement() {
try form.attr("action", startTag._attributes.get(key: "action"))
}
}
try tb.processStartTag("hr")
try tb.processStartTag("label")
// hope you like english.
let prompt: String = startTag._attributes.hasKey(key: "prompt") ?
startTag._attributes.get(key: "prompt") :
"self is a searchable index. Enter search keywords: "
try tb.process(Token.Char().data(prompt))
// input
let inputAttribs: Attributes = Attributes()
for attr: Attribute in startTag._attributes.iterator() {
if (!StringUtil.inSorted(attr.getKey(), haystack: Constants.InBodyStartInputAttribs)) {
inputAttribs.put(attribute: attr)
}
}
try inputAttribs.put("name", "isindex")
try tb.processStartTag("input", inputAttribs)
try tb.processEndTag("label")
try tb.processStartTag("hr")
try tb.processEndTag("form")
} else if (name.equals("textarea")) {
try tb.insert(startTag)
// todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
tb.tokeniser.transition(TokeniserState.Rcdata)
tb.markInsertionMode()
tb.framesetOk(false)
tb.transition(.Text)
} else if (name.equals("xmp")) {
if (try tb.inButtonScope("p")) {
try tb.processEndTag("p")
}
try tb.reconstructFormattingElements()
tb.framesetOk(false)
try HtmlTreeBuilderState.handleRawtext(startTag, tb)
} else if (name.equals("iframe")) {
tb.framesetOk(false)
try HtmlTreeBuilderState.handleRawtext(startTag, tb)
} else if (name.equals("noembed")) {
// also handle noscript if script enabled
try HtmlTreeBuilderState.handleRawtext(startTag, tb)
} else if (name.equals("select")) {
try tb.reconstructFormattingElements()
try tb.insert(startTag)
tb.framesetOk(false)
let state: HtmlTreeBuilderState = tb.state()
if (state.equals(.InTable) || state.equals(.InCaption) || state.equals(.InTableBody) || state.equals(.InRow) || state.equals(.InCell)) {
tb.transition(.InSelectInTable)
} else {
tb.transition(.InSelect)
}
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyStartOptions)) {
if (tb.currentElement() != nil && tb.currentElement()!.nodeName().equals("option")) {
try tb.processEndTag("option")
}
try tb.reconstructFormattingElements()
try tb.insert(startTag)
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyStartRuby)) {
if (try tb.inScope("ruby")) {
tb.generateImpliedEndTags()
if (tb.currentElement() != nil && !tb.currentElement()!.nodeName().equals("ruby")) {
tb.error(self)
tb.popStackToBefore("ruby") // i.e. close up to but not include name
}
try tb.insert(startTag)
}
} else if (name.equals("math")) {
try tb.reconstructFormattingElements()
// todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml)
try tb.insert(startTag)
tb.tokeniser.acknowledgeSelfClosingFlag()
} else if (name.equals("svg")) {
try tb.reconstructFormattingElements()
// todo: handle A start tag whose tag name is "svg" (xlink, svg)
try tb.insert(startTag)
tb.tokeniser.acknowledgeSelfClosingFlag()
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyStartDrop)) {
tb.error(self)
return false
} else {
try tb.reconstructFormattingElements()
try tb.insert(startTag)
}
} else {
try tb.reconstructFormattingElements()
try tb.insert(startTag)
}
break
case .EndTag:
let endTag: Token.EndTag = t.asEndTag()
if let name = endTag.normalName() {
if (StringUtil.inSorted(name, haystack: Constants.InBodyEndAdoptionFormatters)) {
// Adoption Agency Algorithm.
for i in 0..<8 {
let formatEl: Element? = tb.getActiveFormattingElement(name)
if (formatEl == nil) {
return anyOtherEndTag(t, tb)
} else if (!tb.onStack(formatEl!)) {
tb.error(self)
tb.removeFromActiveFormattingElements(formatEl!)
return true
} else if (try !tb.inScope(formatEl!.nodeName())) {
tb.error(self)
return false
} else if (tb.currentElement() != formatEl!) {
tb.error(self)
}
var furthestBlock: Element? = nil
var commonAncestor: Element? = nil
var seenFormattingElement: Bool = false
let stack: Array<Element> = tb.getStack()
// the spec doesn't limit to < 64, but in degenerate cases (9000+ stack depth) self prevents
// run-aways
var stackSize = stack.count
if(stackSize > 64) {stackSize = 64}
for si in 0..<stackSize {
let el: Element = stack[si]
if (el == formatEl) {
commonAncestor = stack[si - 1]
seenFormattingElement = true
} else if (seenFormattingElement && tb.isSpecial(el)) {
furthestBlock = el
break
}
}
if (furthestBlock == nil) {
tb.popStackToClose(formatEl!.nodeName())
tb.removeFromActiveFormattingElements(formatEl)
return true
}
// todo: Let a bookmark note the position of the formatting element in the list of active formatting elements relative to the elements on either side of it in the list.
// does that mean: int pos of format el in list?
var node: Element? = furthestBlock
var lastNode: Element? = furthestBlock
for j in 0..<3 {
if (node != nil && tb.onStack(node!)) {
node = tb.aboveOnStack(node!)
}
// note no bookmark check
if (node != nil && !tb.isInActiveFormattingElements(node!)) {
tb.removeFromStack(node!)
continue
} else if (node == formatEl) {
break
}
let replacement: Element = try Element(Tag.valueOf(node!.nodeName(), ParseSettings.preserveCase), tb.getBaseUri())
// case will follow the original node (so honours ParseSettings)
try tb.replaceActiveFormattingElement(node!, replacement)
try tb.replaceOnStack(node!, replacement)
node = replacement
if (lastNode == furthestBlock) {
// todo: move the aforementioned bookmark to be immediately after the node in the list of active formatting elements.
// not getting how self bookmark both straddles the element above, but is inbetween here...
}
if (lastNode!.parent() != nil) {
try lastNode?.remove()
}
try node!.appendChild(lastNode!)
lastNode = node
}
if (StringUtil.inSorted(commonAncestor!.nodeName(), haystack: Constants.InBodyEndTableFosters)) {
if (lastNode!.parent() != nil) {
try lastNode!.remove()
}
try tb.insertInFosterParent(lastNode!)
} else {
if (lastNode!.parent() != nil) {
try lastNode!.remove()
}
try commonAncestor!.appendChild(lastNode!)
}
let adopter: Element = Element(formatEl!.tag(), tb.getBaseUri())
adopter.getAttributes()?.addAll(incoming: formatEl!.getAttributes())
var childNodes: [Node] = furthestBlock!.getChildNodes()
for childNode: Node in childNodes {
try adopter.appendChild(childNode) // append will reparent. thus the clone to avoid concurrent mod.
}
try furthestBlock?.appendChild(adopter)
tb.removeFromActiveFormattingElements(formatEl)
// todo: insert the element into the list of active formatting elements at the position of the aforementioned bookmark.
tb.removeFromStack(formatEl!)
try tb.insertOnStackAfter(furthestBlock!, adopter)
}
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyEndClosers)) {
if (try !tb.inScope(name)) {
// nothing to close
tb.error(self)
return false
} else {
tb.generateImpliedEndTags()
if (!tb.currentElement()!.nodeName().equals(name)) {
tb.error(self)
}
tb.popStackToClose(name)
}
} else if (name.equals("span")) {
// same as final fall through, but saves short circuit
return anyOtherEndTag(t, tb)
} else if (name.equals("li")) {
if (try !tb.inListItemScope(name)) {
tb.error(self)
return false
} else {
tb.generateImpliedEndTags(name)
if (tb.currentElement() != nil && !tb.currentElement()!.nodeName().equals(name)) {
tb.error(self)
}
tb.popStackToClose(name)
}
} else if (name.equals("body")) {
if (try !tb.inScope("body")) {
tb.error(self)
return false
} else {
// todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, tr, body, html
tb.transition(.AfterBody)
}
} else if (name.equals("html")) {
let notIgnored: Bool = try tb.processEndTag("body")
if (notIgnored) {
return try tb.process(endTag)
}
} else if (name.equals("form")) {
let currentForm: Element? = tb.getFormElement()
tb.setFormElement(nil)
if (try currentForm == nil || !tb.inScope(name)) {
tb.error(self)
return false
} else {
tb.generateImpliedEndTags()
if (tb.currentElement() != nil && !tb.currentElement()!.nodeName().equals(name)) {
tb.error(self)
}
// remove currentForm from stack. will shift anything under up.
tb.removeFromStack(currentForm!)
}
} else if (name.equals("p")) {
if (try !tb.inButtonScope(name)) {
tb.error(self)
try tb.processStartTag(name) // if no p to close, creates an empty <p></p>
return try tb.process(endTag)
} else {
tb.generateImpliedEndTags(name)
if (tb.currentElement() != nil && !tb.currentElement()!.nodeName().equals(name)) {
tb.error(self)
}
tb.popStackToClose(name)
}
} else if (StringUtil.inSorted(name, haystack: Constants.DdDt)) {
if (try !tb.inScope(name)) {
tb.error(self)
return false
} else {
tb.generateImpliedEndTags(name)
if (tb.currentElement() != nil && !tb.currentElement()!.nodeName().equals(name)) {
tb.error(self)
}
tb.popStackToClose(name)
}
} else if (StringUtil.inSorted(name, haystack: Constants.Headings)) {
if (try !tb.inScope(Constants.Headings)) {
tb.error(self)
return false
} else {
tb.generateImpliedEndTags(name)
if (tb.currentElement() != nil && !tb.currentElement()!.nodeName().equals(name)) {
tb.error(self)
}
tb.popStackToClose(Constants.Headings)
}
} else if (name.equals("sarcasm")) {
// *sigh*
return anyOtherEndTag(t, tb)
} else if (StringUtil.inSorted(name, haystack: Constants.InBodyStartApplets)) {
if (try !tb.inScope("name")) {
if (try !tb.inScope(name)) {
tb.error(self)
return false
}
tb.generateImpliedEndTags()
if (tb.currentElement() != nil && !tb.currentElement()!.nodeName().equals(name)) {
tb.error(self)
}
tb.popStackToClose(name)
tb.clearFormattingElementsToLastMarker()
}
} else if (name.equals("br")) {
tb.error(self)
try tb.processStartTag("br")
return false
} else {
return anyOtherEndTag(t, tb)
}
} else {
return anyOtherEndTag(t, tb)
}
break
case .EOF:
// todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html
// stop parsing
break
}
return true
case .Text:
if (t.isCharacter()) {
try tb.insert(t.asCharacter())
} else if (t.isEOF()) {
tb.error(self)
// if current node is script: already started
tb.pop()
tb.transition(tb.originalState())
return try tb.process(t)
} else if (t.isEndTag()) {
// if: An end tag whose tag name is "script" -- scripting nesting level, if evaluating scripts
tb.pop()
tb.transition(tb.originalState())
}
return true
case .InTable:
func anythingElse(_ t: Token, _ tb: HtmlTreeBuilder)throws->Bool {
tb.error(self)
var processed: Bool
if (tb.currentElement() != nil && StringUtil.inString(tb.currentElement()!.nodeName(), haystack: "table", "tbody", "tfoot", "thead", "tr")) {
tb.setFosterInserts(true)
processed = try tb.process(t, .InBody)
tb.setFosterInserts(false)
} else {
processed = try tb.process(t, .InBody)
}
return processed
}
if (t.isCharacter()) {
tb.newPendingTableCharacters()
tb.markInsertionMode()
tb.transition(.InTableText)
return try tb.process(t)
} else if (t.isComment()) {
try tb.insert(t.asComment())
return true
} else if (t.isDoctype()) {
tb.error(self)
return false
} else if (t.isStartTag()) {
let startTag: Token.StartTag = t.asStartTag()
if let name: String = startTag.normalName() {
if (name.equals("caption")) {
tb.clearStackToTableContext()
tb.insertMarkerToFormattingElements()
try tb.insert(startTag)
tb.transition(.InCaption)
} else if (name.equals("colgroup")) {
tb.clearStackToTableContext()
try tb.insert(startTag)
tb.transition(.InColumnGroup)
} else if (name.equals("col")) {
try tb.processStartTag("colgroup")
return try tb.process(t)
} else if (StringUtil.inString(name, haystack: "tbody", "tfoot", "thead")) {
tb.clearStackToTableContext()
try tb.insert(startTag)
tb.transition(.InTableBody)
} else if (StringUtil.inString(name, haystack: "td", "th", "tr")) {
try tb.processStartTag("tbody")
return try tb.process(t)
} else if (name.equals("table")) {
tb.error(self)
let processed: Bool = try tb.processEndTag("table")
if (processed) // only ignored if in fragment
{return try tb.process(t)}
} else if (StringUtil.inString(name, haystack: "style", "script")) {
return try tb.process(t, .InHead)
} else if (name.equals("input")) {
if (!startTag._attributes.get(key: "type").equalsIgnoreCase(string: "hidden")) {
return try anythingElse(t, tb)
} else {
try tb.insertEmpty(startTag)
}
} else if (name.equals("form")) {
tb.error(self)
if (tb.getFormElement() != nil) {
return false
} else {
try tb.insertForm(startTag, false)
}
} else {
return try anythingElse(t, tb)
}
}
return true // todo: check if should return processed http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#parsing-main-intable
} else if (t.isEndTag()) {
let endTag: Token.EndTag = t.asEndTag()
if let name: String = endTag.normalName() {
if (name.equals("table")) {
if (try !tb.inTableScope(name)) {
tb.error(self)
return false
} else {
tb.popStackToClose("table")
}
tb.resetInsertionMode()
} else if (StringUtil.inString(name,
haystack: "body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr")) {
tb.error(self)
return false
} else {
return try anythingElse(t, tb)
}
} else {
return try anythingElse(t, tb)
}
return true // todo: as above todo
} else if (t.isEOF()) {
if (tb.currentElement() != nil && tb.currentElement()!.nodeName().equals("html")) {
tb.error(self)
}
return true // stops parsing
}
return try anythingElse(t, tb)
case .InTableText:
switch (t.type) {
case .Char:
let c: Token.Char = t.asCharacter()
if (c.getData() != nil && c.getData()!.equals(HtmlTreeBuilderState.nullString)) {
tb.error(self)
return false
} else {
var a = tb.getPendingTableCharacters()
a.append(c.getData()!)
tb.setPendingTableCharacters(a)
}
break
default:
// todo - don't really like the way these table character data lists are built
if (tb.getPendingTableCharacters().count > 0) {
for character: String in tb.getPendingTableCharacters() {
if (!HtmlTreeBuilderState.isWhitespace(character)) {
// InTable anything else section:
tb.error(self)
if (tb.currentElement() != nil && StringUtil.inString(tb.currentElement()!.nodeName(), haystack: "table", "tbody", "tfoot", "thead", "tr")) {
tb.setFosterInserts(true)
try tb.process(Token.Char().data(character), .InBody)
tb.setFosterInserts(false)
} else {
try tb.process(Token.Char().data(character), .InBody)
}
} else {
try tb.insert(Token.Char().data(character))
}
}
tb.newPendingTableCharacters()
}
tb.transition(tb.originalState())
return try tb.process(t)
}
return true
case .InCaption:
if (t.isEndTag() && t.asEndTag().normalName()!.equals("caption")) {
let endTag: Token.EndTag = t.asEndTag()
let name: String? = endTag.normalName()
if (try name != nil && !tb.inTableScope(name!)) {
tb.error(self)
return false
} else {
tb.generateImpliedEndTags()
if (!tb.currentElement()!.nodeName().equals("caption")) {
tb.error(self)
}
tb.popStackToClose("caption")
tb.clearFormattingElementsToLastMarker()
tb.transition(.InTable)
}
} else if ((
t.isStartTag() && StringUtil.inString(t.asStartTag().normalName()!,
haystack: "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr") ||
t.isEndTag() && t.asEndTag().normalName()!.equals("table"))
) {
tb.error(self)
let processed: Bool = try tb.processEndTag("caption")
if (processed) {
return try tb.process(t)
}
} else if (t.isEndTag() && StringUtil.inString(t.asEndTag().normalName()!,
haystack: "body", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr")) {
tb.error(self)
return false
} else {
return try tb.process(t, .InBody)
}
return true
case .InColumnGroup:
func anythingElse(_ t: Token, _ tb: TreeBuilder)throws->Bool {
let processed: Bool = try tb.processEndTag("colgroup")
if (processed) { // only ignored in frag case
return try tb.process(t)
}
return true
}
if (HtmlTreeBuilderState.isWhitespace(t)) {
try tb.insert(t.asCharacter())
return true
}
switch (t.type) {
case .Comment:
try tb.insert(t.asComment())
break
case .Doctype:
tb.error(self)
break
case .StartTag:
let startTag: Token.StartTag = t.asStartTag()
let name: String? = startTag.normalName()
if ("html".equals(name)) {
return try tb.process(t, .InBody)
} else if ("col".equals(name)) {
try tb.insertEmpty(startTag)
} else {
return try anythingElse(t, tb)
}
break
case .EndTag:
let endTag: Token.EndTag = t.asEndTag()
let name = endTag.normalName()
if ("colgroup".equals(name)) {
if ("html".equals(tb.currentElement()?.nodeName())) { // frag case
tb.error(self)
return false
} else {
tb.pop()
tb.transition(.InTable)
}
} else {
return try anythingElse(t, tb)
}
break
case .EOF:
if ("html".equals(tb.currentElement()?.nodeName())) {
return true // stop parsing; frag case
} else {
return try anythingElse(t, tb)
}
default:
return try anythingElse(t, tb)
}
return true
case .InTableBody:
@discardableResult
func exitTableBody(_ t: Token, _ tb: HtmlTreeBuilder)throws->Bool {
if (try !(tb.inTableScope("tbody") || tb.inTableScope("thead") || tb.inScope("tfoot"))) {
// frag case
tb.error(self)
return false
}
tb.clearStackToTableBodyContext()
try tb.processEndTag(tb.currentElement()!.nodeName()) // tbody, tfoot, thead
return try tb.process(t)
}
func anythingElse(_ t: Token, _ tb: HtmlTreeBuilder)throws->Bool {
return try tb.process(t, .InTable)
}
switch (t.type) {
case .StartTag:
let startTag: Token.StartTag = t.asStartTag()
let name: String? = startTag.normalName()
if ("tr".equals(name)) {
tb.clearStackToTableBodyContext()
try tb.insert(startTag)
tb.transition(.InRow)
} else if (StringUtil.inString(name, haystack: "th", "td")) {
tb.error(self)
try tb.processStartTag("tr")
return try tb.process(startTag)
} else if (StringUtil.inString(name, haystack: "caption", "col", "colgroup", "tbody", "tfoot", "thead")) {
return try exitTableBody(t, tb)
} else {
return try anythingElse(t, tb)
}
break
case .EndTag:
let endTag: Token.EndTag = t.asEndTag()
let name = endTag.normalName()
if (StringUtil.inString(name, haystack: "tbody", "tfoot", "thead")) {
if (try !tb.inTableScope(name!)) {
tb.error(self)
return false
} else {
tb.clearStackToTableBodyContext()
tb.pop()
tb.transition(.InTable)
}
} else if ("table".equals(name)) {
return try exitTableBody(t, tb)
} else if (StringUtil.inString(name, haystack: "body", "caption", "col", "colgroup", "html", "td", "th", "tr")) {
tb.error(self)
return false
} else {
return try anythingElse(t, tb)
}
break
default:
return try anythingElse(t, tb)
}
return true
case .InRow:
func anythingElse(_ t: Token, _ tb: HtmlTreeBuilder)throws->Bool {
return try tb.process(t, .InTable)
}
func handleMissingTr(_ t: Token, _ tb: TreeBuilder)throws->Bool {
let processed: Bool = try tb.processEndTag("tr")
if (processed) {
return try tb.process(t)
} else {
return false
}
}
if (t.isStartTag()) {
let startTag: Token.StartTag = t.asStartTag()
let name: String? = startTag.normalName()
if (StringUtil.inString(name, haystack: "th", "td")) {
tb.clearStackToTableRowContext()
try tb.insert(startTag)
tb.transition(.InCell)
tb.insertMarkerToFormattingElements()
} else if (StringUtil.inString(name, haystack: "caption", "col", "colgroup", "tbody", "tfoot", "thead", "tr")) {
return try handleMissingTr(t, tb)
} else {
return try anythingElse(t, tb)
}
} else if (t.isEndTag()) {
let endTag: Token.EndTag = t.asEndTag()
let name: String? = endTag.normalName()
if ("tr".equals(name)) {
if (try !tb.inTableScope(name!)) {
tb.error(self) // frag
return false
}
tb.clearStackToTableRowContext()
tb.pop() // tr
tb.transition(.InTableBody)
} else if ("table".equals(name)) {
return try handleMissingTr(t, tb)
} else if (StringUtil.inString(name, haystack: "tbody", "tfoot", "thead")) {
if (try !tb.inTableScope(name!)) {
tb.error(self)
return false
}
try tb.processEndTag("tr")
return try tb.process(t)
} else if (StringUtil.inString(name, haystack: "body", "caption", "col", "colgroup", "html", "td", "th")) {
tb.error(self)
return false
} else {
return try anythingElse(t, tb)
}
} else {
return try anythingElse(t, tb)
}
return true
case .InCell:
func anythingElse(_ t: Token, _ tb: HtmlTreeBuilder)throws->Bool {
return try tb.process(t, .InBody)
}
func closeCell(_ tb: HtmlTreeBuilder)throws {
if (try tb.inTableScope("td")) {
try tb.processEndTag("td")
} else {
try tb.processEndTag("th") // only here if th or td in scope
}
}
if (t.isEndTag()) {
let endTag: Token.EndTag = t.asEndTag()
let name: String? = endTag.normalName()
if (StringUtil.inString(name, haystack: "td", "th")) {
if (try !tb.inTableScope(name!)) {
tb.error(self)
tb.transition(.InRow) // might not be in scope if empty: <td /> and processing fake end tag
return false
}
tb.generateImpliedEndTags()
if (!name!.equals(tb.currentElement()?.nodeName())) {
tb.error(self)
}
tb.popStackToClose(name!)
tb.clearFormattingElementsToLastMarker()
tb.transition(.InRow)
} else if (StringUtil.inString(name, haystack: "body", "caption", "col", "colgroup", "html")) {
tb.error(self)
return false
} else if (StringUtil.inString(name, haystack: "table", "tbody", "tfoot", "thead", "tr")) {
if (try !tb.inTableScope(name!)) {
tb.error(self)
return false
}
try closeCell(tb)
return try tb.process(t)
} else {
return try anythingElse(t, tb)
}
} else if (t.isStartTag() &&
StringUtil.inString(t.asStartTag().normalName(),
haystack: "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr")) {
if (try !(tb.inTableScope("td") || tb.inTableScope("th"))) {
tb.error(self)
return false
}
try closeCell(tb)
return try tb.process(t)
} else {
return try anythingElse(t, tb)
}
return true
case .InSelect:
func anythingElse(_ t: Token, _ tb: HtmlTreeBuilder) -> Bool {
tb.error(self)
return false
}
switch (t.type) {
case .Char:
let c: Token.Char = t.asCharacter()
if (HtmlTreeBuilderState.nullString.equals(c.getData())) {
tb.error(self)
return false
} else {
try tb.insert(c)
}
break
case .Comment:
try tb.insert(t.asComment())
break
case .Doctype:
tb.error(self)
return false
case .StartTag:
let start: Token.StartTag = t.asStartTag()
let name: String? = start.normalName()
if ("html".equals(name)) {
return try tb.process(start, .InBody)
} else if ("option".equals(name)) {
try tb.processEndTag("option")
try tb.insert(start)
} else if ("optgroup".equals(name)) {
if ("option".equals(tb.currentElement()?.nodeName())) {
try tb.processEndTag("option")
} else if ("optgroup".equals(tb.currentElement()?.nodeName())) {
try tb.processEndTag("optgroup")
}
try tb.insert(start)
} else if ("select".equals(name)) {
tb.error(self)
return try tb.processEndTag("select")
} else if (StringUtil.inString(name, haystack: "input", "keygen", "textarea")) {
tb.error(self)
if (try !tb.inSelectScope("select")) {
return false // frag
}
try tb.processEndTag("select")
return try tb.process(start)
} else if ("script".equals(name)) {
return try tb.process(t, .InHead)
} else {
return anythingElse(t, tb)
}
break
case .EndTag:
let end: Token.EndTag = t.asEndTag()
let name = end.normalName()
if ("optgroup".equals(name)) {
if ("option".equals(tb.currentElement()?.nodeName()) && tb.currentElement() != nil && tb.aboveOnStack(tb.currentElement()!) != nil && "optgroup".equals(tb.aboveOnStack(tb.currentElement()!)?.nodeName())) {
try tb.processEndTag("option")
}
if ("optgroup".equals(tb.currentElement()?.nodeName())) {
tb.pop()
} else {
tb.error(self)
}
} else if ("option".equals(name)) {
if ("option".equals(tb.currentElement()?.nodeName())) {
tb.pop()
} else {
tb.error(self)
}
} else if ("select".equals(name)) {
if (try !tb.inSelectScope(name!)) {
tb.error(self)
return false
} else {
tb.popStackToClose(name!)
tb.resetInsertionMode()
}
} else {
return anythingElse(t, tb)
}
break
case .EOF:
if (!"html".equals(tb.currentElement()?.nodeName())) {
tb.error(self)
}
break
// default:
// return anythingElse(t, tb)
}
return true
case .InSelectInTable:
if (t.isStartTag() && StringUtil.inString(t.asStartTag().normalName(), haystack: "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th")) {
tb.error(self)
try tb.processEndTag("select")
return try tb.process(t)
} else if (t.isEndTag() && StringUtil.inString(t.asEndTag().normalName(), haystack: "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th")) {
tb.error(self)
if (try t.asEndTag().normalName() != nil && tb.inTableScope(t.asEndTag().normalName()!)) {
try tb.processEndTag("select")
return try (tb.process(t))
} else {
return false
}
} else {
return try tb.process(t, .InSelect)
}
case .AfterBody:
if (HtmlTreeBuilderState.isWhitespace(t)) {
return try tb.process(t, .InBody)
} else if (t.isComment()) {
try tb.insert(t.asComment()) // into html node
} else if (t.isDoctype()) {
tb.error(self)
return false
} else if (t.isStartTag() && "html".equals(t.asStartTag().normalName())) {
return try tb.process(t, .InBody)
} else if (t.isEndTag() && "html".equals(t.asEndTag().normalName())) {
if (tb.isFragmentParsing()) {
tb.error(self)
return false
} else {
tb.transition(.AfterAfterBody)
}
} else if (t.isEOF()) {
// chillax! we're done
} else {
tb.error(self)
tb.transition(.InBody)
return try tb.process(t)
}
return true
case .InFrameset:
if (HtmlTreeBuilderState.isWhitespace(t)) {
try tb.insert(t.asCharacter())
} else if (t.isComment()) {
try tb.insert(t.asComment())
} else if (t.isDoctype()) {
tb.error(self)
return false
} else if (t.isStartTag()) {
let start: Token.StartTag = t.asStartTag()
let name: String? = start.normalName()
if ("html".equals(name)) {
return try tb.process(start, .InBody)
} else if ("frameset".equals(name)) {
try tb.insert(start)
} else if ("frame".equals(name)) {
try tb.insertEmpty(start)
} else if ("noframes".equals(name)) {
return try tb.process(start, .InHead)
} else {
tb.error(self)
return false
}
} else if (t.isEndTag() && "frameset".equals(t.asEndTag().normalName())) {
if ("html".equals(tb.currentElement()?.nodeName())) { // frag
tb.error(self)
return false
} else {
tb.pop()
if (!tb.isFragmentParsing() && !"frameset".equals(tb.currentElement()?.nodeName())) {
tb.transition(.AfterFrameset)
}
}
} else if (t.isEOF()) {
if (!"html".equals(tb.currentElement()?.nodeName())) {
tb.error(self)
return true
}
} else {
tb.error(self)
return false
}
return true
case .AfterFrameset:
if (HtmlTreeBuilderState.isWhitespace(t)) {
try tb.insert(t.asCharacter())
} else if (t.isComment()) {
try tb.insert(t.asComment())
} else if (t.isDoctype()) {
tb.error(self)
return false
} else if (t.isStartTag() && "html".equals(t.asStartTag().normalName())) {
return try tb.process(t, .InBody)
} else if (t.isEndTag() && "html".equals(t.asEndTag().normalName())) {
tb.transition(.AfterAfterFrameset)
} else if (t.isStartTag() && "noframes".equals(t.asStartTag().normalName())) {
return try tb.process(t, .InHead)
} else if (t.isEOF()) {
// cool your heels, we're complete
} else {
tb.error(self)
return false
}
return true
case .AfterAfterBody:
if (t.isComment()) {
try tb.insert(t.asComment())
} else if (t.isDoctype() || HtmlTreeBuilderState.isWhitespace(t) || (t.isStartTag() && "html".equals(t.asStartTag().normalName()))) {
return try tb.process(t, .InBody)
} else if (t.isEOF()) {
// nice work chuck
} else {
tb.error(self)
tb.transition(.InBody)
return try tb.process(t)
}
return true
case .AfterAfterFrameset:
if (t.isComment()) {
try tb.insert(t.asComment())
} else if (t.isDoctype() || HtmlTreeBuilderState.isWhitespace(t) || (t.isStartTag() && "html".equals(t.asStartTag().normalName()))) {
return try tb.process(t, .InBody)
} else if (t.isEOF()) {
// nice work chuck
} else if (t.isStartTag() && "noframes".equals(t.asStartTag().normalName())) {
return try tb.process(t, .InHead)
} else {
tb.error(self)
return false
}
return true
case .ForeignContent:
return true
// todo: implement. Also how do we get here?
}
}
private static func isWhitespace(_ t: Token) -> Bool {
if (t.isCharacter()) {
let data: String? = t.asCharacter().getData()
return isWhitespace(data)
}
return false
}
private static func isWhitespace(_ data: String?) -> Bool {
// todo: self checks more than spec - "\t", "\n", "\f", "\r", " "
if let data = data {
for c in data.characters {
if (!StringUtil.isWhitespace(c)) {
return false}
}
}
return true
}
private static func handleRcData(_ startTag: Token.StartTag, _ tb: HtmlTreeBuilder)throws {
try tb.insert(startTag)
tb.tokeniser.transition(TokeniserState.Rcdata)
tb.markInsertionMode()
tb.transition(.Text)
}
private static func handleRawtext(_ startTag: Token.StartTag, _ tb: HtmlTreeBuilder)throws {
try tb.insert(startTag)
tb.tokeniser.transition(TokeniserState.Rawtext)
tb.markInsertionMode()
tb.transition(.Text)
}
// lists of tags to search through. A little harder to read here, but causes less GC than dynamic varargs.
// was contributing around 10% of parse GC load.
fileprivate final class Constants {
fileprivate static let InBodyStartToHead: [String] = ["base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title"]
fileprivate static let InBodyStartPClosers: [String] = ["address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl",
"fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol",
"p", "section", "summary", "ul"]
fileprivate static let Headings: [String] = ["h1", "h2", "h3", "h4", "h5", "h6"]
fileprivate static let InBodyStartPreListing: [String] = ["pre", "listing"]
fileprivate static let InBodyStartLiBreakers: [String] = ["address", "div", "p"]
fileprivate static let DdDt: [String] = ["dd", "dt"]
fileprivate static let Formatters: [String] = ["b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u"]
fileprivate static let InBodyStartApplets: [String] = ["applet", "marquee", "object"]
fileprivate static let InBodyStartEmptyFormatters: [String] = ["area", "br", "embed", "img", "keygen", "wbr"]
fileprivate static let InBodyStartMedia: [String] = ["param", "source", "track"]
fileprivate static let InBodyStartInputAttribs: [String] = ["name", "action", "prompt"]
fileprivate static let InBodyStartOptions: [String] = ["optgroup", "option"]
fileprivate static let InBodyStartRuby: [String] = ["rp", "rt"]
fileprivate static let InBodyStartDrop: [String] = ["caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr"]
fileprivate static let InBodyEndClosers: [String] = ["address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div",
"dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu",
"nav", "ol", "pre", "section", "summary", "ul"]
fileprivate static let InBodyEndAdoptionFormatters: [String] = ["a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u"]
fileprivate static let InBodyEndTableFosters: [String] = ["table", "tbody", "tfoot", "thead", "tr"]
}
}
| mit | f345fbe207542c67450fa864d2b3c2be | 47.54164 | 232 | 0.432618 | 5.150068 | false | false | false | false |
UIKit0/VPNOn | VPNOnWatchKitExtension/InterfaceController.swift | 22 | 2565 | //
// InterfaceController.swift
// VPN On WatchKit Extension
//
// Created by Lex Tang on 3/30/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import WatchKit
import Foundation
import VPNOnKit
let kVPNOnSelectedIDInToday = "kVPNOnSelectedIDInToday"
class InterfaceController: VPNInterfaceController {
@IBOutlet weak var tableView: WKInterfaceTable!
override func willActivate() {
super.willActivate()
loadVPNs()
}
func loadVPNs() {
if vpns.count > 0 {
self.tableView.setNumberOfRows(vpns.count, withRowType: "VPNRow")
for i in 0...vpns.count-1 {
if let row = self.tableView.rowControllerAtIndex(i) as! VPNRowWithSwitch? {
let vpn = vpns[i]
if let countryCode = vpn.countryCode {
row.flag.setImageNamed(countryCode)
}
row.latency = LTPingQueue.sharedQueue.latencyForHostname(vpn.server)
let connected = Bool(VPNManager.sharedManager.status == .Connected && vpn.ID == selectedID)
let backgroundColor = connected ? UIColor(red:0, green:0.6, blue:1, alpha:1) : UIColor(white: 1.0, alpha: 0.2)
row.group.setBackgroundColor(backgroundColor)
row.VPNSwitch.setOn(connected)
}
}
} else {
self.tableView.setNumberOfRows(1, withRowType: "HintRow")
}
}
func didTurnOnVPN(notifiction: NSNotification) {
if let userInfo = notifiction.userInfo as! [String: Int]? {
if let index = userInfo[kVPNIndexKey] {
let vpn = vpns[index]
selectedID = vpn.ID
connectVPN(vpn)
}
}
}
func didTurnOffVPN(notification: NSNotification) {
VPNManager.sharedManager.disconnect()
loadVPNs()
}
// MARK: - Notification
func pingDidUpdate(notification: NSNotification) {
loadVPNs()
}
func coreDataDidSave(notification: NSNotification) {
VPNDataManager.sharedManager.managedObjectContext?.mergeChangesFromContextDidSaveNotification(notification)
loadVPNs()
}
func VPNStatusDidChange(notification: NSNotification?) {
loadVPNs()
if VPNManager.sharedManager.status == .Disconnected {
LTPingQueue.sharedQueue.restartPing()
}
}
}
| mit | 6547bf2e8fa892995189f4a8f5e0f389 | 29.903614 | 130 | 0.577778 | 4.812383 | false | false | false | false |
themonki/onebusaway-iphone | Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/BinaryEncodingVisitor.swift | 1 | 13466 | // Sources/SwiftProtobuf/BinaryEncodingVisitor.swift - Binary encoding support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Core support for protobuf binary encoding. Note that this is built
/// on the general traversal machinery.
///
// -----------------------------------------------------------------------------
import Foundation
/// Visitor that encodes a message graph in the protobuf binary wire format.
internal struct BinaryEncodingVisitor: Visitor {
var encoder: BinaryEncoder
/// Creates a new visitor that writes the binary-coded message into the memory
/// at the given pointer.
///
/// - Precondition: `pointer` must point to an allocated block of memory that
/// is large enough to hold the entire encoded message. For performance
/// reasons, the encoder does not make any attempts to verify this.
init(forWritingInto pointer: UnsafeMutablePointer<UInt8>) {
encoder = BinaryEncoder(forWritingInto: pointer)
}
init(encoder: BinaryEncoder) {
self.encoder = encoder
}
mutating func visitUnknown(bytes: Data) throws {
encoder.appendUnknown(data: bytes)
}
mutating func visitSingularFloatField(value: Float, fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .fixed32)
encoder.putFloatValue(value: value)
}
mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .fixed64)
encoder.putDoubleValue(value: value)
}
mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws {
try visitSingularUInt64Field(value: UInt64(bitPattern: value), fieldNumber: fieldNumber)
}
mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .varint)
encoder.putVarInt(value: value)
}
mutating func visitSingularSInt32Field(value: Int32, fieldNumber: Int) throws {
try visitSingularSInt64Field(value: Int64(value), fieldNumber: fieldNumber)
}
mutating func visitSingularSInt64Field(value: Int64, fieldNumber: Int) throws {
try visitSingularUInt64Field(value: ZigZag.encoded(value), fieldNumber: fieldNumber)
}
mutating func visitSingularFixed32Field(value: UInt32, fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .fixed32)
encoder.putFixedUInt32(value: value)
}
mutating func visitSingularFixed64Field(value: UInt64, fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .fixed64)
encoder.putFixedUInt64(value: value)
}
mutating func visitSingularSFixed32Field(value: Int32, fieldNumber: Int) throws {
try visitSingularFixed32Field(value: UInt32(bitPattern: value), fieldNumber: fieldNumber)
}
mutating func visitSingularSFixed64Field(value: Int64, fieldNumber: Int) throws {
try visitSingularFixed64Field(value: UInt64(bitPattern: value), fieldNumber: fieldNumber)
}
mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws {
try visitSingularUInt64Field(value: value ? 1 : 0, fieldNumber: fieldNumber)
}
mutating func visitSingularStringField(value: String, fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
encoder.putStringValue(value: value)
}
mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
encoder.putBytesValue(value: value)
}
mutating func visitSingularEnumField<E: Enum>(value: E,
fieldNumber: Int) throws {
try visitSingularUInt64Field(value: UInt64(bitPattern: Int64(value.rawValue)),
fieldNumber: fieldNumber)
}
mutating func visitSingularMessageField<M: Message>(value: M,
fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
let length = try value.serializedDataSize()
encoder.putVarInt(value: length)
try value.traverse(visitor: &self)
}
mutating func visitSingularGroupField<G: Message>(value: G, fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .startGroup)
try value.traverse(visitor: &self)
encoder.startField(fieldNumber: fieldNumber, wireFormat: .endGroup)
}
// Repeated fields are handled by the default implementations in Visitor.swift
// Packed Fields
mutating func visitPackedFloatField(value: [Float], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
encoder.putVarInt(value: value.count * MemoryLayout<Float>.size)
for v in value {
encoder.putFloatValue(value: v)
}
}
mutating func visitPackedDoubleField(value: [Double], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
encoder.putVarInt(value: value.count * MemoryLayout<Double>.size)
for v in value {
encoder.putDoubleValue(value: v)
}
}
mutating func visitPackedInt32Field(value: [Int32], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
var packedSize = 0
for v in value {
packedSize += Varint.encodedSize(of: v)
}
encoder.putVarInt(value: packedSize)
for v in value {
encoder.putVarInt(value: Int64(v))
}
}
mutating func visitPackedInt64Field(value: [Int64], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
var packedSize = 0
for v in value {
packedSize += Varint.encodedSize(of: v)
}
encoder.putVarInt(value: packedSize)
for v in value {
encoder.putVarInt(value: v)
}
}
mutating func visitPackedSInt32Field(value: [Int32], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
var packedSize = 0
for v in value {
packedSize += Varint.encodedSize(of: ZigZag.encoded(v))
}
encoder.putVarInt(value: packedSize)
for v in value {
encoder.putZigZagVarInt(value: Int64(v))
}
}
mutating func visitPackedSInt64Field(value: [Int64], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
var packedSize = 0
for v in value {
packedSize += Varint.encodedSize(of: ZigZag.encoded(v))
}
encoder.putVarInt(value: packedSize)
for v in value {
encoder.putZigZagVarInt(value: v)
}
}
mutating func visitPackedUInt32Field(value: [UInt32], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
var packedSize = 0
for v in value {
packedSize += Varint.encodedSize(of: v)
}
encoder.putVarInt(value: packedSize)
for v in value {
encoder.putVarInt(value: UInt64(v))
}
}
mutating func visitPackedUInt64Field(value: [UInt64], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
var packedSize = 0
for v in value {
packedSize += Varint.encodedSize(of: v)
}
encoder.putVarInt(value: packedSize)
for v in value {
encoder.putVarInt(value: v)
}
}
mutating func visitPackedFixed32Field(value: [UInt32], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
encoder.putVarInt(value: value.count * MemoryLayout<UInt32>.size)
for v in value {
encoder.putFixedUInt32(value: v)
}
}
mutating func visitPackedFixed64Field(value: [UInt64], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
encoder.putVarInt(value: value.count * MemoryLayout<UInt64>.size)
for v in value {
encoder.putFixedUInt64(value: v)
}
}
mutating func visitPackedSFixed32Field(value: [Int32], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
encoder.putVarInt(value: value.count * MemoryLayout<Int32>.size)
for v in value {
encoder.putFixedUInt32(value: UInt32(bitPattern: v))
}
}
mutating func visitPackedSFixed64Field(value: [Int64], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
encoder.putVarInt(value: value.count * MemoryLayout<Int64>.size)
for v in value {
encoder.putFixedUInt64(value: UInt64(bitPattern: v))
}
}
mutating func visitPackedBoolField(value: [Bool], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
encoder.putVarInt(value: value.count)
for v in value {
encoder.putVarInt(value: v ? 1 : 0)
}
}
mutating func visitPackedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
var packedSize = 0
for v in value {
packedSize += Varint.encodedSize(of: Int32(truncatingIfNeeded: v.rawValue))
}
encoder.putVarInt(value: packedSize)
for v in value {
encoder.putVarInt(value: v.rawValue)
}
}
mutating func visitMapField<KeyType, ValueType: MapValueType>(
fieldType: _ProtobufMap<KeyType, ValueType>.Type,
value: _ProtobufMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws {
for (k,v) in value {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
var sizer = BinaryEncodingSizeVisitor()
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer)
try ValueType.visitSingular(value: v, fieldNumber: 2, with: &sizer)
let entrySize = sizer.serializedSize
encoder.putVarInt(value: entrySize)
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &self)
try ValueType.visitSingular(value: v, fieldNumber: 2, with: &self)
}
}
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type,
value: _ProtobufEnumMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws where ValueType.RawValue == Int {
for (k,v) in value {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
var sizer = BinaryEncodingSizeVisitor()
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer)
try sizer.visitSingularEnumField(value: v, fieldNumber: 2)
let entrySize = sizer.serializedSize
encoder.putVarInt(value: entrySize)
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &self)
try visitSingularEnumField(value: v, fieldNumber: 2)
}
}
mutating func visitMapField<KeyType, ValueType>(
fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type,
value: _ProtobufMessageMap<KeyType, ValueType>.BaseType,
fieldNumber: Int
) throws {
for (k,v) in value {
encoder.startField(fieldNumber: fieldNumber, wireFormat: .lengthDelimited)
var sizer = BinaryEncodingSizeVisitor()
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer)
try sizer.visitSingularMessageField(value: v, fieldNumber: 2)
let entrySize = sizer.serializedSize
encoder.putVarInt(value: entrySize)
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &self)
try visitSingularMessageField(value: v, fieldNumber: 2)
}
}
mutating func visitExtensionFieldsAsMessageSet(
fields: ExtensionFieldValueSet,
start: Int,
end: Int
) throws {
var subVisitor = BinaryEncodingMessageSetVisitor(encoder: encoder)
try fields.traverse(visitor: &subVisitor, start: start, end: end)
encoder = subVisitor.encoder
}
}
extension BinaryEncodingVisitor {
// Helper Visitor to when writing out the extensions as MessageSets.
internal struct BinaryEncodingMessageSetVisitor: SelectiveVisitor {
var encoder: BinaryEncoder
init(encoder: BinaryEncoder) {
self.encoder = encoder
}
mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws {
encoder.putVarInt(value: Int64(WireFormat.MessageSet.Tags.itemStart.rawValue))
encoder.putVarInt(value: Int64(WireFormat.MessageSet.Tags.typeId.rawValue))
encoder.putVarInt(value: fieldNumber)
encoder.putVarInt(value: Int64(WireFormat.MessageSet.Tags.message.rawValue))
// Use a normal BinaryEncodingVisitor so any message fields end up in the
// normal wire format (instead of MessageSet format).
let length = try value.serializedDataSize()
encoder.putVarInt(value: length)
// Create the sub encoder after writing the length.
var subVisitor = BinaryEncodingVisitor(encoder: encoder)
try value.traverse(visitor: &subVisitor)
encoder = subVisitor.encoder
encoder.putVarInt(value: Int64(WireFormat.MessageSet.Tags.itemEnd.rawValue))
}
// SelectiveVisitor handles the rest.
}
}
| apache-2.0 | 9f2e950643a465cd53cc3834d40700ae | 36.405556 | 93 | 0.710902 | 4.460417 | false | false | false | false |
devcastid/iOS-Tutorials | Davcast-iOS/Davcast-iOS/AppDelegate.swift | 1 | 6270 | //
// AppDelegate.swift
// Davcast-iOS
//
// Created by Innovecto iOS Dev on 2/20/16.
// Copyright © 2016 Devcast. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let viewController = ViewController()
window!.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:.
// 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 "Devcast.Davcast_iOS" 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("Davcast_iOS", 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 | fa57b656d9e117f81cdde05410cbb263 | 51.680672 | 291 | 0.713032 | 5.908577 | false | false | false | false |
ahoppen/swift | test/Constraints/diagnostics_swift4.swift | 21 | 1769 | // RUN: %target-typecheck-verify-swift -swift-version 4
// SR-2505: "Call arguments did not match up" assertion
func sr_2505(_ a: Any) {} // expected-note {{}}
sr_2505() // expected-error {{missing argument for parameter #1 in call}}
sr_2505(a: 1) // expected-error {{extraneous argument label 'a:' in call}}
sr_2505(1, 2) // expected-error {{extra argument in call}}
sr_2505(a: 1, 2) // expected-error {{extra argument in call}}
struct C_2505 {
init(_ arg: Any) {
}
}
protocol P_2505 {
}
extension C_2505 {
init<T>(from: [T]) where T: P_2505 {
}
}
class C2_2505: P_2505 {
}
let c_2505 = C_2505(arg: [C2_2505()]) // expected-error {{extraneous argument label 'arg:' in call}}
// rdar://problem/31898542 - Swift 4: 'type of expression is ambiguous without more context' errors, without a fixit
enum R31898542<T> {
case success(T) // expected-note {{'success' declared here}}
case failure
}
func foo() -> R31898542<()> {
return .success() // expected-error {{missing argument for parameter #1 in call}} {{19-19=<#()#>}}
}
// rdar://problem/31973368 - Cannot convert value of type '(K, V) -> ()' to expected argument type '((key: _, value: _)) -> Void'
// SE-0110: We reverted to allowing this for the time being, but this
// test is valuable in case we end up disallowing it again in the
// future.
class R<K: Hashable, V> {
func forEach(_ body: (K, V) -> ()) {
let dict: [K:V] = [:]
dict.forEach(body)
}
}
// Make sure that solver doesn't try to form solutions with available overloads when better generic choices are present.
infix operator +=+ : AdditionPrecedence
func +=+(_ lhs: Int, _ rhs: Int) -> Bool { return lhs == rhs }
func +=+<T: BinaryInteger>(_ lhs: T, _ rhs: Int) -> Bool { return lhs == rhs }
| apache-2.0 | 699693278eff4eb4e456e85ca37c2194 | 30.589286 | 129 | 0.63991 | 3.251838 | false | false | false | false |
JmoVxia/CLPlayer | CLTableViewController/View/Cell/CLTableViewCell.swift | 1 | 1975 | //
// CLTableViewCell.swift
// CLPlayer
//
// Created by Chen JmoVxia on 2021/12/14.
//
import UIKit
// MARK: - JmoVxia---类-属性
class CLTableViewCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
initUI()
makeConstraints()
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var iconImageView: UIImageView = {
let view = UIImageView()
view.image = UIImage(named: "placeholder")
return view
}()
private lazy var playImageView: UIImageView = {
let view = UIImageView()
view.image = UIImage(named: "play")
return view
}()
}
// MARK: - JmoVxia---布局
private extension CLTableViewCell {
func initUI() {
selectionStyle = .none
backgroundColor = UIColor.orange.withAlphaComponent(0.5)
contentView.addSubview(iconImageView)
iconImageView.addSubview(playImageView)
}
func makeConstraints() {
iconImageView.snp.makeConstraints { make in
make.top.left.right.equalToSuperview()
make.bottom.equalTo(-10)
}
playImageView.snp.makeConstraints { make in
make.center.equalToSuperview()
}
}
}
// MARK: - JmoVxia---CKDCellProtocol
extension CLTableViewCell: CLCellProtocol {
func setItem(_ item: CLCellItemProtocol) {
guard let _ = item as? CLTableViewItem else { return }
}
}
// MARK: - JmoVxia---数据
private extension CLTableViewCell {
func initData() {}
}
// MARK: - JmoVxia---override
extension CLTableViewCell {}
// MARK: - JmoVxia---objc
@objc private extension CLTableViewCell {}
// MARK: - JmoVxia---私有方法
private extension CLTableViewCell {}
// MARK: - JmoVxia---公共方法
extension CLTableViewCell {}
| mit | 9df3584d4dc612874ce02ef36abe44fb | 21.616279 | 79 | 0.644216 | 4.147122 | false | false | false | false |
J3D1-WARR10R/WikiRaces | WikiRaces/Shared/Menu View Controllers/Connect View Controllers/GKHostViewController/SwiftUI/HostContentView.swift | 2 | 4345 | //
// HostContentView.swift
// WikiRaces
//
// Created by Andrew Finke on 6/25/20.
// Copyright © 2020 Andrew Finke. All rights reserved.
//
import SwiftUI
import WKRKit
import WKRUIKit
import GameKit
struct HostContentView: View {
// MARK: - Types -
enum Modal {
case activity, settings
}
// MARK: - Properties -
@ObservedObject var model: HostContentViewModel
@Environment(\.colorScheme) var colorScheme: ColorScheme
let cancelAction: () -> Void
let startMatch: () -> Void
let presentModal: (Modal) -> Void
// MARK: - Body -
var body: some View {
VStack {
HStack {
Button(action: cancelAction, label: {
Image(systemName: "chevron.left")
.font(.system(size: 22))
})
.opacity(model.state == .raceStarting ? 0.2 : 1)
Spacer()
if model.state == .raceStarting {
ActivityIndicatorView()
} else {
Button(action: startMatch, label: {
Image(systemName: "play.fill")
.font(.system(size: 22))
})
}
}
.foregroundColor(.wkrTextColor(for: colorScheme))
.padding()
.padding(.horizontal)
.frame(height: 60)
.allowsHitTesting(model.state != .raceStarting)
Spacer()
if Defaults.isFastlaneSnapshotInstance {
WKRUIPlayerImageView(
player: WKRPlayerProfile(name: "A", playerID: "A"),
size: 100,
effectSize: 5)
.padding(.bottom, 20)
} else {
WKRUIPlayerImageView(
player: WKRPlayerProfile(player: GKLocalPlayer.local),
size: 100,
effectSize: 5)
.padding(.bottom, 20)
}
if !WKRUIPlayerImageManager.shared.isLocalPlayerImageFromGameCenter && !Defaults.isFastlaneSnapshotInstance {
HStack {
Spacer()
Text("Set a custom racer photo\nin the Game Center settings")
.font(.system(size: 12, weight: .regular))
.multilineTextAlignment(.center)
.offset(y: -5)
Spacer()
}
}
VStack {
HostSectionView(
header: "RACE CODE",
title: (model.raceCode?.uppercased() ?? "-") + " ", // ' ' prevents trimming??
imageName: "square.and.arrow.up",
disabled: model.raceCode == nil) {
self.presentModal(.activity)
}
.padding(.vertical, 16)
HostSectionView(
header: "TYPE",
title: model.settings.isCustom ? "CUSTOM" : "STANDARD",
imageName: "gear",
disabled: false) {
self.presentModal(.settings)
}
}.frame(width: 220)
Color.clear.frame(height: 50)
Spacer()
HStack {
Color.clear.frame(width: 1)
ForEach(model.connectedPlayers) { player in
WKRUIPlayerImageView(player: player, size: 44, effectSize: 3)
.padding(.all, 2)
}
.transition(.opacity)
.scaleEffect(model.connectedPlayers.count < 6 ? 1 : 1.5 - 0.1 * CGFloat(model.connectedPlayers.count), anchor: .center)
Color.clear.frame(width: 1)
}
.frame(maxHeight: 60)
VStack {
Text(model.status)
.font(.system(size: 14, weight: .medium))
.foregroundColor(.secondary)
.transition(.opacity)
.id(model.status)
ActivityIndicatorView().offset(x: 0, y: -5)
.opacity((model.state == .raceStarting || model.state == .soloRace) ? 0 : 1)
}
.padding(.bottom, 20)
}
.animation(.spring())
}
}
| mit | ae13a91609f685fede25633c5aba3b48 | 32.415385 | 135 | 0.464088 | 5.033604 | false | false | false | false |
tomasharkema/R.swift | Sources/RswiftCore/RswiftCore.swift | 1 | 7424 | //
// RswiftCore.swift
// R.swift
//
// Created by Tom Lokhorst on 2017-04-22.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
import XcodeEdit
public typealias RswiftGenerator = Generator
public enum Generator: String, CaseIterable {
case image
case string
case color
case file
case font
case nib
case segue
case storyboard
case reuseIdentifier
case entitlements
case info
case id
}
public struct RswiftCore {
private let callInformation: CallInformation
public init(_ callInformation: CallInformation) {
self.callInformation = callInformation
}
public func run() throws {
do {
let xcodeproj = try Xcodeproj(url: callInformation.xcodeprojURL)
let ignoreFile = (try? IgnoreFile(ignoreFileURL: callInformation.rswiftIgnoreURL)) ?? IgnoreFile()
let buildConfigurations = try xcodeproj.buildConfigurations(forTarget: callInformation.targetName)
let resourceURLs = try xcodeproj.resourcePaths(forTarget: callInformation.targetName)
.map { path in path.url(with: callInformation.urlForSourceTreeFolder) }
.compactMap { $0 }
.filter { !ignoreFile.matches(url: $0) }
let resources = Resources(resourceURLs: resourceURLs, fileManager: FileManager.default)
let infoPlistWhitelist = ["UIApplicationShortcutItems", "UIApplicationSceneManifest", "NSUserActivityTypes", "NSExtension"]
var structGenerators: [StructGenerator] = []
if callInformation.generators.contains(.image) {
structGenerators.append(ImageStructGenerator(assetFolders: resources.assetFolders, images: resources.images))
}
if callInformation.generators.contains(.color) {
structGenerators.append(ColorStructGenerator(assetFolders: resources.assetFolders))
}
if callInformation.generators.contains(.font) {
structGenerators.append(FontStructGenerator(fonts: resources.fonts))
}
if callInformation.generators.contains(.segue) {
structGenerators.append(SegueStructGenerator(storyboards: resources.storyboards))
}
if callInformation.generators.contains(.storyboard) {
structGenerators.append(StoryboardStructGenerator(storyboards: resources.storyboards))
}
if callInformation.generators.contains(.nib) {
structGenerators.append(NibStructGenerator(nibs: resources.nibs))
}
if callInformation.generators.contains(.reuseIdentifier) {
structGenerators.append(ReuseIdentifierStructGenerator(reusables: resources.reusables))
}
if callInformation.generators.contains(.file) {
structGenerators.append(ResourceFileStructGenerator(resourceFiles: resources.resourceFiles))
}
if callInformation.generators.contains(.string) {
structGenerators.append(StringsStructGenerator(localizableStrings: resources.localizableStrings, developmentLanguage: xcodeproj.developmentLanguage))
}
if callInformation.generators.contains(.id) {
structGenerators.append(AccessibilityIdentifierStructGenerator(nibs: resources.nibs, storyboards: resources.storyboards))
}
if callInformation.generators.contains(.info) {
let infoPlists = buildConfigurations.compactMap { config in
return loadPropertyList(name: config.name, url: callInformation.infoPlistFile, callInformation: callInformation)
}
structGenerators.append(PropertyListGenerator(name: "info", plists: infoPlists, toplevelKeysWhitelist: infoPlistWhitelist))
}
if callInformation.generators.contains(.entitlements) {
let entitlements = buildConfigurations.compactMap { config -> PropertyList? in
guard let codeSignEntitlement = callInformation.codeSignEntitlements else { return nil }
return loadPropertyList(name: config.name, url: codeSignEntitlement, callInformation: callInformation)
}
structGenerators.append(PropertyListGenerator(name: "entitlements", plists: entitlements, toplevelKeysWhitelist: nil))
}
// Generate regular R file
let fileContents = generateRegularFileContents(resources: resources, generators: structGenerators)
writeIfChanged(contents: fileContents, toURL: callInformation.outputURL)
// Generate UITest R file
if let uiTestOutputURL = callInformation.uiTestOutputURL {
let uiTestFileContents = generateUITestFileContents(resources: resources, generators: [
AccessibilityIdentifierStructGenerator(nibs: resources.nibs, storyboards: resources.storyboards)
])
writeIfChanged(contents: uiTestFileContents, toURL: uiTestOutputURL)
}
} catch let error as ResourceParsingError {
switch error {
case let .parsingFailed(description):
fail(description)
case let .unsupportedExtension(givenExtension, supportedExtensions):
let joinedSupportedExtensions = supportedExtensions.joined(separator: ", ")
fail("File extension '\(String(describing: givenExtension))' is not one of the supported extensions: \(joinedSupportedExtensions)")
}
exit(EXIT_FAILURE)
}
}
private func generateRegularFileContents(resources: Resources, generators: [StructGenerator]) -> String {
let aggregatedResult = AggregatedStructGenerator(subgenerators: generators)
.generatedStructs(at: callInformation.accessLevel, prefix: "")
let (externalStructWithoutProperties, internalStruct) = ValidatedStructGenerator(validationSubject: aggregatedResult)
.generatedStructs(at: callInformation.accessLevel, prefix: "")
let externalStruct = externalStructWithoutProperties.addingInternalProperties(forBundleIdentifier: callInformation.bundleIdentifier)
let codeConvertibles: [SwiftCodeConverible?] = [
HeaderPrinter(),
ImportPrinter(
modules: callInformation.imports,
extractFrom: [externalStruct, internalStruct],
exclude: [Module.custom(name: callInformation.productModuleName)]
),
externalStruct,
internalStruct
]
return codeConvertibles
.compactMap { $0?.swiftCode }
.joined(separator: "\n\n")
+ "\n" // Newline at end of file
}
private func generateUITestFileContents(resources: Resources, generators: [StructGenerator]) -> String {
let (externalStruct, _) = AggregatedStructGenerator(subgenerators: generators)
.generatedStructs(at: callInformation.accessLevel, prefix: "")
let codeConvertibles: [SwiftCodeConverible?] = [
HeaderPrinter(),
externalStruct
]
return codeConvertibles
.compactMap { $0?.swiftCode }
.joined(separator: "\n\n")
+ "\n" // Newline at end of file
}
}
private func loadPropertyList(name: String, url: URL, callInformation: CallInformation) -> PropertyList? {
do {
return try PropertyList(buildConfigurationName: name, url: url)
} catch let ResourceParsingError.parsingFailed(humanReadableError) {
warn(humanReadableError)
return nil
}
catch {
return nil
}
}
private func writeIfChanged(contents: String, toURL outputURL: URL) {
let currentFileContents = try? String(contentsOf: outputURL, encoding: .utf8)
guard currentFileContents != contents else { return }
do {
try contents.write(to: outputURL, atomically: true, encoding: .utf8)
} catch {
fail(error.localizedDescription)
}
}
| mit | 4e7fda150b98f1b151a272db7ac3f8d8 | 38.489362 | 157 | 0.729122 | 4.765083 | false | false | false | false |
nolili/BluetoothExampleTV | BluetoothExampleTV/ViewController.swift | 1 | 838 | //
// ViewController.swift
// BluetoothExampleTV
//
// Created by Noritaka Kamiya on 2015/10/30.
// Copyright © 2015年 Noritaka Kamiya. All rights reserved.
//
import UIKit
import CoreBluetooth
class ViewController: UIViewController {
let bluetoothManager = BluetoothManager()
@IBOutlet var label:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
bluetoothManager.heartRateUpdateHandler = { bpm in
self.label?.text = "❤️" + String(bpm)
let current = self.label.transform
UIView.animateWithDuration(0.1, animations: {
self.label.transform = CGAffineTransformScale(current, 1.1, 1.1)
}, completion: { completed in
self.label.transform = current
})
}
}
}
| mit | eac34bc70ee500e795eb7e788cac6949 | 24.96875 | 80 | 0.606498 | 4.59116 | false | false | false | false |
huonw/swift | test/ClangImporter/objc_ir.swift | 2 | 17047 |
// RUN: %empty-directory(%t)
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -module-name objc_ir -I %S/Inputs/custom-modules -emit-ir -g -o - -primary-file %s | %FileCheck %s
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
// CHECK: %TSo1BC = type
import ObjectiveC
import Foundation
import objc_ext
import TestProtocols
import ObjCIRExtras
// CHECK: @"\01L_selector_data(method:withFloat:)" = private global [18 x i8] c"method:withFloat:\00"
// CHECK: @"\01L_selector_data(method:withDouble:)" = private global [19 x i8] c"method:withDouble:\00"
// CHECK: @"\01L_selector_data(method:separateExtMethod:)" = private global [26 x i8] c"method:separateExtMethod:\00", section "__TEXT,__objc_methname,cstring_literals"
// Instance method invocation
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir15instanceMethodsyySo1BCF"(%TSo1BC*
func instanceMethods(_ b: B) {
// CHECK: load i8*, i8** @"\01L_selector(method:withFloat:)"
// CHECK: call i32 bitcast (void ()* @objc_msgSend to i32
var i = b.method(1, with: 2.5 as Float)
// CHECK: load i8*, i8** @"\01L_selector(method:withDouble:)"
// CHECK: call i32 bitcast (void ()* @objc_msgSend to i32
i = i + b.method(1, with: 2.5 as Double)
}
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir16extensionMethods1bySo1BC_tF"
func extensionMethods(b b: B) {
// CHECK: load i8*, i8** @"\01L_selector(method:separateExtMethod:)", align 8
// CHECK: [[T0:%.*]] = call i8* bitcast (void ()* @objc_msgSend to i8*
// CHECK-NEXT: [[T1:%.*]] = {{.*}}call i8* @objc_retainAutoreleasedReturnValue(i8* [[T0]])
// CHECK-NOT: [[T0]]
// CHECK: [[T1]]
b.method(1, separateExtMethod:1.5)
}
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir19initCallToAllocInit1iys5Int32V_tF"
func initCallToAllocInit(i i: CInt) {
// CHECK: call {{.*}} @"$SSo1BC3intABSgs5Int32V_tcfC"
B(int: i)
}
// CHECK-LABEL: linkonce_odr hidden {{.*}} @"$SSo1BC3intABSgs5Int32V_tcfC"
// CHECK: call [[OPAQUE:%.*]]* @objc_allocWithZone
// Indexed subscripting
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir19indexedSubscripting1b3idx1aySo1BC_SiSo1ACtF"
func indexedSubscripting(b b: B, idx: Int, a: A) {
// CHECK: load i8*, i8** @"\01L_selector(setObject:atIndexedSubscript:)", align 8
b[idx] = a
// CHECK: load i8*, i8** @"\01L_selector(objectAtIndexedSubscript:)"
var a2 = b[idx] as! A
}
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir17keyedSubscripting1b3idx1aySo1BC_So1ACAItF"
func keyedSubscripting(b b: B, idx: A, a: A) {
// CHECK: load i8*, i8** @"\01L_selector(setObject:forKeyedSubscript:)"
b[a] = a
// CHECK: load i8*, i8** @"\01L_selector(objectForKeyedSubscript:)"
var a2 = b[a] as! A
}
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir14propertyAccess1bySo1BC_tF"
func propertyAccess(b b: B) {
// CHECK: load i8*, i8** @"\01L_selector(counter)"
// CHECK: load i8*, i8** @"\01L_selector(setCounter:)"
b.counter = b.counter + 1
// CHECK: load %objc_class*, %objc_class** @"\01l_OBJC_CLASS_REF_$_B"
// CHECK: load i8*, i8** @"\01L_selector(sharedCounter)"
// CHECK: load i8*, i8** @"\01L_selector(setSharedCounter:)"
B.sharedCounter = B.sharedCounter + 1
}
// CHECK-LABEL: define hidden swiftcc %TSo1BC* @"$S7objc_ir8downcast1aSo1BCSo1AC_tF"(
func downcast(a a: A) -> B {
// CHECK: [[CLASS:%.*]] = load %objc_class*, %objc_class** @"\01l_OBJC_CLASS_REF_$_B"
// CHECK: [[T0:%.*]] = call %objc_class* @swift_getInitializedObjCClass(%objc_class* [[CLASS]])
// CHECK: [[T1:%.*]] = bitcast %objc_class* [[T0]] to i8*
// CHECK: call i8* @swift_dynamicCastObjCClassUnconditional(i8* [[A:%.*]], i8* [[T1]]) [[NOUNWIND:#[0-9]+]]
return a as! B
}
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir19almostSubscriptable3as11aySo06AlmostD0C_So1ACtF"
func almostSubscriptable(as1 as1: AlmostSubscriptable, a: A) {
as1.objectForKeyedSubscript(a)
}
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir13protocolTypes1a1bySo7NSMinceC_So9NSRuncing_ptF"(%TSo7NSMinceC*, %objc_object*) {{.*}} {
func protocolTypes(a a: NSMince, b: NSRuncing) {
// - (void)eatWith:(id <NSRuncing>)runcer;
a.eat(with: b)
// CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(eatWith:)", align 8
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE:%.*]]*, i8*, i8*)*)([[OPAQUE:%.*]]* {{%.*}}, i8* [[SEL]], i8* {{%.*}})
}
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir6getset1pySo8FooProto_p_tF"(%objc_object*) {{.*}} {
func getset(p p: FooProto) {
// CHECK: load i8*, i8** @"\01L_selector(bar)"
// CHECK: load i8*, i8** @"\01L_selector(setBar:)"
let prop = p.bar
p.bar = prop
}
// CHECK-LABEL: define hidden swiftcc %swift.type* @"$S7objc_ir16protocolMetatype1pSo8FooProto_pXpSoAD_p_tF"(%objc_object*) {{.*}} {
func protocolMetatype(p: FooProto) -> FooProto.Type {
// CHECK: = call %swift.type* @swift_getObjectType(%objc_object* %0)
// CHECK-NOT: {{retain|release}}
// CHECK: [[RAW_RESULT:%.+]] = call i8* @processFooType(i8* {{%.+}})
// CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class*
// CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]])
// CHECK-NOT: call void @swift_unknownRelease(%objc_object* %0)
// CHECK: ret %swift.type* [[SWIFT_RESULT]]
let type = processFooType(type(of: p))
return type
} // CHECK: }
class Impl: FooProto, AnotherProto {
@objc var bar: Int32 = 0
}
// CHECK-LABEL: define hidden swiftcc %swift.type* @"$S7objc_ir27protocolCompositionMetatype1pSo12AnotherProto_So03FooG0pXpAA4ImplC_tF"(%T7objc_ir4ImplC*) {{.*}} {
func protocolCompositionMetatype(p: Impl) -> (FooProto & AnotherProto).Type {
// CHECK: = getelementptr inbounds %T7objc_ir4ImplC, %T7objc_ir4ImplC* %0, i32 0, i32 0, i32 0
// CHECK-NOT: {{retain|release}}
// CHECK: [[RAW_RESULT:%.+]] = call i8* @processComboType(i8* {{%.+}})
// CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class*
// CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]])
// CHECK-NOT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%T7objc_ir4ImplC*)*)(%T7objc_ir4ImplC* %0)
// CHECK: ret %swift.type* [[SWIFT_RESULT]]
let type = processComboType(type(of: p))
return type
} // CHECK: }
// CHECK-LABEL: define hidden swiftcc %swift.type* @"$S7objc_ir28protocolCompositionMetatype21pSo12AnotherProto_So03FooG0pXpAA4ImplC_tF"(%T7objc_ir4ImplC*) {{.*}} {
func protocolCompositionMetatype2(p: Impl) -> (FooProto & AnotherProto).Type {
// CHECK: = getelementptr inbounds %T7objc_ir4ImplC, %T7objc_ir4ImplC* %0, i32 0, i32 0, i32 0
// CHECK-NOT: {{retain|release}}
// CHECK: [[RAW_RESULT:%.+]] = call i8* @processComboType2(i8* {{%.+}})
// CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class*
// CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]])
// CHECK-NOT: @swift_release
// CHECK: ret %swift.type* [[SWIFT_RESULT]]
let type = processComboType2(type(of: p))
return type
} // CHECK: }
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir17pointerPropertiesyySo14PointerWrapperCF"(%TSo14PointerWrapperC*) {{.*}} {
func pointerProperties(_ obj: PointerWrapper) {
// CHECK: load i8*, i8** @"\01L_selector(setVoidPtr:)"
// CHECK: load i8*, i8** @"\01L_selector(setIntPtr:)"
// CHECK: load i8*, i8** @"\01L_selector(setIdPtr:)"
obj.voidPtr = nil as UnsafeMutableRawPointer?
obj.intPtr = nil as UnsafeMutablePointer?
obj.idPtr = nil as AutoreleasingUnsafeMutablePointer?
}
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir16strangeSelectorsyySo13SwiftNameTestCF"(%TSo13SwiftNameTestC*) {{.*}} {
func strangeSelectors(_ obj: SwiftNameTest) {
// CHECK: load i8*, i8** @"\01L_selector(:b:)"
obj.empty(a: 0, b: 0)
}
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir20customFactoryMethodsyyF"() {{.*}} {
func customFactoryMethods() {
// CHECK: call swiftcc %TSo13SwiftNameTestC* @"$SSo13SwiftNameTestC10dummyParamAByt_tcfCTO"
// CHECK: call swiftcc %TSo13SwiftNameTestC* @"$SSo13SwiftNameTestC2ccABypSg_tcfCTO"
// CHECK: call swiftcc %TSo13SwiftNameTestC* @"$SSo13SwiftNameTestC5emptyABs5Int32V_tcfCTO"
_ = SwiftNameTest(dummyParam: ())
_ = SwiftNameTest(cc: nil)
_ = SwiftNameTest(empty: 0)
// CHECK: load i8*, i8** @"\01L_selector(testZ)"
// CHECK: load i8*, i8** @"\01L_selector(testY:)"
// CHECK: load i8*, i8** @"\01L_selector(testX:xx:)"
// CHECK: load i8*, i8** @"\01L_selector(::)"
_ = SwiftNameTest.zz()
_ = SwiftNameTest.yy(aa: nil)
_ = SwiftNameTest.xx(nil, bb: nil)
_ = SwiftNameTest.empty(1, 2)
do {
// CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC5errorAByt_tKcfCTO"
// CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC2aa5errorABypSg_yttKcfCTO"
// CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC2aa5error5blockABypSg_ytyyctKcfCTO"
// CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC5error5blockAByt_yyctKcfCTO"
// CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC2aaABypSg_tKcfCTO"
// CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC2aa5blockABypSg_yyctKcfCTO"
// CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC5blockAByyc_tKcfCTO"
_ = try SwiftNameTestError(error: ())
_ = try SwiftNameTestError(aa: nil, error: ())
_ = try SwiftNameTestError(aa: nil, error: (), block: {})
_ = try SwiftNameTestError(error: (), block: {})
_ = try SwiftNameTestError(aa: nil)
_ = try SwiftNameTestError(aa: nil, block: {})
_ = try SwiftNameTestError(block: {})
// CHECK: load i8*, i8** @"\01L_selector(testW:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testW2:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testV:)"
// CHECK: load i8*, i8** @"\01L_selector(testV2:)"
_ = try SwiftNameTestError.ww(nil)
_ = try SwiftNameTestError.w2(nil, error: ())
_ = try SwiftNameTestError.vv()
_ = try SwiftNameTestError.v2(error: ())
} catch _ {
}
}
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo13SwiftNameTestC* @"$SSo13SwiftNameTestC10dummyParamAByt_tcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(b)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo13SwiftNameTestC* @"$SSo13SwiftNameTestC2ccABypSg_tcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(c:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC5errorAByt_tKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err1:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC2aa5errorABypSg_yttKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err2:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC2aa5error5blockABypSg_ytyyctKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err3:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC5error5blockAByt_yyctKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err4:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC2aaABypSg_tKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err5:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC2aa5blockABypSg_yyctKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err6:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$SSo18SwiftNameTestErrorC5blockAByyc_tKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err7:callback:)"
// CHECK: }
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir29customFactoryMethodsInheritedyyF"() {{.*}} {
func customFactoryMethodsInherited() {
// CHECK: call swiftcc %TSo16SwiftNameTestSubC* @"$SSo16SwiftNameTestSubC10dummyParamAByt_tcfCTO"
// CHECK: call swiftcc %TSo16SwiftNameTestSubC* @"$SSo16SwiftNameTestSubC2ccABypSg_tcfCTO"
_ = SwiftNameTestSub(dummyParam: ())
_ = SwiftNameTestSub(cc: nil)
// CHECK: load i8*, i8** @"\01L_selector(testZ)"
// CHECK: load i8*, i8** @"\01L_selector(testY:)"
// CHECK: load i8*, i8** @"\01L_selector(testX:xx:)"
_ = SwiftNameTestSub.zz()
_ = SwiftNameTestSub.yy(aa: nil)
_ = SwiftNameTestSub.xx(nil, bb: nil)
do {
// CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC5errorAByt_tKcfCTO"
// CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC2aa5errorABypSg_yttKcfCTO"
// CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC2aa5error5blockABypSg_ytyyctKcfCTO"
// CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC5error5blockAByt_yyctKcfCTO"
// CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC2aaABypSg_tKcfCTO"
// CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC2aa5blockABypSg_yyctKcfCTO"
// CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC5blockAByyc_tKcfCTO"
_ = try SwiftNameTestErrorSub(error: ())
_ = try SwiftNameTestErrorSub(aa: nil, error: ())
_ = try SwiftNameTestErrorSub(aa: nil, error: (), block: {})
_ = try SwiftNameTestErrorSub(error: (), block: {})
_ = try SwiftNameTestErrorSub(aa: nil)
_ = try SwiftNameTestErrorSub(aa: nil, block: {})
_ = try SwiftNameTestErrorSub(block: {})
// CHECK: load i8*, i8** @"\01L_selector(testW:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testW2:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testV:)"
// CHECK: load i8*, i8** @"\01L_selector(testV2:)"
_ = try SwiftNameTestErrorSub.ww(nil)
_ = try SwiftNameTestErrorSub.w2(nil, error: ())
_ = try SwiftNameTestErrorSub.vv()
_ = try SwiftNameTestErrorSub.v2(error: ())
} catch _ {
}
}
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo16SwiftNameTestSubC* @"$SSo16SwiftNameTestSubC10dummyParamAByt_tcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(b)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo16SwiftNameTestSubC* @"$SSo16SwiftNameTestSubC2ccABypSg_tcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(c:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC5errorAByt_tKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err1:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC2aa5errorABypSg_yttKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err2:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC2aa5error5blockABypSg_ytyyctKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err3:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC5error5blockAByt_yyctKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err4:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC2aaABypSg_tKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err5:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC2aa5blockABypSg_yyctKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err6:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$SSo21SwiftNameTestErrorSubC5blockAByyc_tKcfCTO"
// CHECK: load i8*, i8** @"\01L_selector(err7:callback:)"
// CHECK: }
// CHECK-LABEL: define hidden swiftcc void @"$S7objc_ir30testCompatibilityAliasMangling3objySo13SwiftNameTestC_tF"
func testCompatibilityAliasMangling(obj: SwiftNameAlias) {
// CHECK: call void @llvm.dbg.declare(metadata %TSo13SwiftNameTestC** {{%.+}}, metadata ![[SWIFT_NAME_ALIAS_VAR:[0-9]+]], metadata !DIExpression())
}
// CHECK: linkonce_odr hidden {{.*}} @"$SSo1BC3intABSgs5Int32V_tcfcTO"
// CHECK: load i8*, i8** @"\01L_selector(initWithInt:)"
// CHECK: call [[OPAQUE:%.*]]* bitcast (void ()* @objc_msgSend
// CHECK: attributes [[NOUNWIND]] = { nounwind }
// CHECK: ![[SWIFT_NAME_ALIAS_VAR]] = !DILocalVariable(name: "obj", arg: 1, scope: !{{[0-9]+}}, file: !{{[0-9]+}}, line: {{[0-9]+}}, type: ![[SWIFT_NAME_ALIAS_TYPE:[0-9]+]])
// CHECK: ![[SWIFT_NAME_ALIAS_TYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$SSo14SwiftNameAliasaD", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, baseType: !{{[0-9]+}})
| apache-2.0 | e56f8347962db4f5c71e677981410c5f | 47.845272 | 175 | 0.69238 | 3.389066 | false | true | false | false |
Paladinfeng/leetcode | leetcode/Best Time to Buy and Sell Stock/main.swift | 1 | 1203 | //
// main.swift
// Best Time to Buy and Sell Stock
//
// Created by xuezhaofeng on 27/02/2018.
// Copyright © 2018 paladinfeng. All rights reserved.
//
import Foundation
class Solution {
func maxProfit(_ prices: [Int]) -> Int {
// if let min = prices.min(), let minIndex = prices.index(of: min) {
// if minIndex != prices.count {
// var minProfit = 0
// for i in minIndex+1..<prices.count {
// if minProfit < prices[i] - min {
// minProfit = prices[i] - min
// }
// }
// return minProfit
// }
// }
var maxProfit = 0
for i in 0..<prices.count {
// print(prices[i])
if i != prices.count - 1 {
if prices[i] < prices[i + 1] {
for j in i+1..<prices.count {
let temp = prices[j] - prices[i]
if maxProfit < temp { maxProfit = temp }
}
}
}
}
return maxProfit
}
}
let result = Solution().maxProfit([7, 1, 5, 3, 6, 4])
print(result)
| mit | 4cc0985a1226cce7f50e8745e9fb54b6 | 26.318182 | 75 | 0.43178 | 3.928105 | false | false | false | false |
chris-wood/reveiller | reveiller/Pods/SwiftCharts/SwiftCharts/Layers/ChartPointsViewsLayer.swift | 5 | 4011 | //
// ChartPointsViewsLayer.swift
// SwiftCharts
//
// Created by ischuetz on 27/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public class ChartPointsViewsLayer<T: ChartPoint, U: UIView>: ChartPointsLayer<T> {
public typealias ChartPointViewGenerator = (chartPointModel: ChartPointLayerModel<T>, layer: ChartPointsViewsLayer<T, U>, chart: Chart) -> U?
public typealias ViewWithChartPoint = (view: U, chartPointModel: ChartPointLayerModel<T>)
private(set) var viewsWithChartPoints: [ViewWithChartPoint] = []
private let delayBetweenItems: Float = 0
let viewGenerator: ChartPointViewGenerator
private var conflictSolver: ChartViewsConflictSolver<T, U>?
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints:[T], viewGenerator: ChartPointViewGenerator, conflictSolver: ChartViewsConflictSolver<T, U>? = nil, displayDelay: Float = 0, delayBetweenItems: Float = 0) {
self.viewGenerator = viewGenerator
self.conflictSolver = conflictSolver
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay)
}
override func display(chart chart: Chart) {
super.display(chart: chart)
self.viewsWithChartPoints = self.generateChartPointViews(chartPointModels: self.chartPointsModels, chart: chart)
if self.delayBetweenItems == 0 {
for v in self.viewsWithChartPoints {chart.addSubview(v.view)}
} else {
func next(index: Int, delay: dispatch_time_t) {
if index < self.viewsWithChartPoints.count {
dispatch_after(delay, dispatch_get_main_queue()) {() -> Void in
let view = self.viewsWithChartPoints[index].view
chart.addSubview(view)
next(index + 1, delay: ChartUtils.toDispatchTime(self.delayBetweenItems))
}
}
}
next(0, delay: 0)
}
}
private func generateChartPointViews(chartPointModels chartPointModels: [ChartPointLayerModel<T>], chart: Chart) -> [ViewWithChartPoint] {
let viewsWithChartPoints = self.chartPointsModels.reduce(Array<ViewWithChartPoint>()) {viewsWithChartPoints, model in
if let view = self.viewGenerator(chartPointModel: model, layer: self, chart: chart) {
return viewsWithChartPoints + [(view: view, chartPointModel: model)]
} else {
return viewsWithChartPoints
}
}
self.conflictSolver?.solveConflicts(views: viewsWithChartPoints)
return viewsWithChartPoints
}
override public func chartPointsForScreenLoc(screenLoc: CGPoint) -> [T] {
return self.filterChartPoints{self.inXBounds(screenLoc.x, view: $0.view) && self.inYBounds(screenLoc.y, view: $0.view)}
}
override public func chartPointsForScreenLocX(x: CGFloat) -> [T] {
return self.filterChartPoints{self.inXBounds(x, view: $0.view)}
}
override public func chartPointsForScreenLocY(y: CGFloat) -> [T] {
return self.filterChartPoints{self.inYBounds(y, view: $0.view)}
}
private func filterChartPoints(filter: (ViewWithChartPoint) -> Bool) -> [T] {
return self.viewsWithChartPoints.reduce([]) {arr, viewWithChartPoint in
if filter(viewWithChartPoint) {
return arr + [viewWithChartPoint.chartPointModel.chartPoint]
} else {
return arr
}
}
}
private func inXBounds(x: CGFloat, view: UIView) -> Bool {
return (x > view.frame.origin.x) && (x < (view.frame.origin.x + view.frame.width))
}
private func inYBounds(y: CGFloat, view: UIView) -> Bool {
return (y > view.frame.origin.y) && (y < (view.frame.origin.y + view.frame.height))
}
}
| mit | 79346a7716f71ab058348f335d6c70b4 | 40.78125 | 250 | 0.640489 | 4.527088 | false | false | false | false |
ayalcinkaya/DashedSlider | Pod/Classes/DashedSlider.swift | 2 | 6984 | //
// DashedSlider.swift
//
//
// Created by Ahmet Yalcinkaya on 1/31/16.
// Copyright © 2016 ayalcinkaya
//
import UIKit
import CoreGraphics
public class DashedSlider: UISlider {
let DEFAULT_MARKER_COUNT:Int = 25
let DEFAULT_MARK_WIDTH:CGFloat = 4.0
let DEFAULT_TOP_MARGIN:CGFloat = 3.0
public var selectedBarColor:UIColor! {
didSet {
self.setNeedsLayout()
}
}
public var unselectedBarColor:UIColor! {
didSet {
self.setNeedsLayout()
}
}
public var markColor:UIColor! {
didSet {
self.setNeedsLayout()
}
}
public var handlerColor:UIColor? {
didSet {
self.setNeedsLayout()
}
}
// number of markers to draw
// 1 to 100
public var markerCount:Int! {
didSet {
self.setNeedsLayout()
}
}
public var markWidth:CGFloat! {
didSet {
self.setNeedsLayout()
}
}
public var topMargin:CGFloat! {
didSet {
self.setNeedsLayout()
}
}
public var handlerWidth:CGFloat? {
didSet {
self.setNeedsLayout()
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
func configure(){
if selectedBarColor == nil {
selectedBarColor = UIColor.redColor()
}
if unselectedBarColor == nil {
unselectedBarColor = UIColor.lightGrayColor()
}
if markColor == nil {
markColor = UIColor.whiteColor()
}
if markWidth == nil {
markWidth = DEFAULT_MARK_WIDTH
}
if topMargin == nil {
topMargin = DEFAULT_TOP_MARGIN
}
if markerCount == nil {
markerCount = DEFAULT_MARKER_COUNT
}
}
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
// Create an innerRect to paint the lines
let innerRect:CGRect = CGRectInset(rect, 1.0, 1.0)
UIGraphicsBeginImageContextWithOptions(innerRect.size, false, 0)
let context:CGContextRef = UIGraphicsGetCurrentContext()!
// Selected side
CGContextSetFillColorWithColor(context, self.selectedBarColor.CGColor);
CGContextFillRect(context, CGRectMake(0, topMargin, innerRect.size.width, innerRect.size.height - topMargin*2.0))
let selectedSide:UIImage = UIGraphicsGetImageFromCurrentImageContext().resizableImageWithCapInsets(UIEdgeInsetsZero)
// Unselected side
CGContextSetFillColorWithColor(context, self.unselectedBarColor.CGColor);
CGContextFillRect(context, CGRectMake(0, topMargin, innerRect.size.width, innerRect.size.height - (topMargin * 2.0)))
let unselectedSide:UIImage = UIGraphicsGetImageFromCurrentImageContext().resizableImageWithCapInsets(UIEdgeInsetsZero)
// Set markers on selected side
selectedSide.drawAtPoint(CGPoint(x: 0, y: 0))
// marker can not be less than 1
if markerCount <= 0 {
markerCount = DEFAULT_MARKER_COUNT
}
let spaceBetweenMarkers:CGFloat = 100.0 / CGFloat(markerCount)
for var i:CGFloat = 0; i < 100 ; i = i + spaceBetweenMarkers {
CGContextSetLineWidth(context, self.markWidth);
let position:CGFloat = i * innerRect.size.width / 100.0
CGContextMoveToPoint(context, position, 0);
CGContextAddLineToPoint(context, position, CGRectGetHeight(innerRect));
CGContextSetStrokeColorWithColor(context, self.markColor.CGColor)
CGContextStrokePath(context);
}
let selectedStripSide:UIImage = UIGraphicsGetImageFromCurrentImageContext().resizableImageWithCapInsets(UIEdgeInsetsZero)
// Set markers on unselected side
unselectedSide.drawAtPoint(CGPoint(x: 0, y: 0))
for var i:CGFloat = 0; i < 100 ; i = i + spaceBetweenMarkers {
CGContextSetLineWidth(context, self.markWidth);
let position:CGFloat = i * innerRect.size.width / 100.0
CGContextMoveToPoint(context, position, 0);
CGContextAddLineToPoint(context, position, CGRectGetHeight(innerRect));
CGContextSetStrokeColorWithColor(context, self.markColor.CGColor);
CGContextStrokePath(context);
}
let unselectedStripSide:UIImage = UIGraphicsGetImageFromCurrentImageContext().resizableImageWithCapInsets(UIEdgeInsetsZero)
UIGraphicsEndImageContext();
self.setMinimumTrackImage(selectedStripSide, forState: UIControlState.Normal)
self.setMaximumTrackImage(unselectedStripSide, forState: UIControlState.Normal)
if let trackImageColor = handlerColor,
let trackImageWidth = handlerWidth {
let trackImage:UIImage = UIImage.imageWithColor(trackImageColor, cornerRadius: 0.0).imageWithMinimumSize(CGSize(width: trackImageWidth, height: CGRectGetHeight(innerRect)))
self.setThumbImage(trackImage, forState: UIControlState.Normal)
self.setThumbImage(trackImage, forState: UIControlState.Highlighted)
self.setThumbImage(trackImage, forState: UIControlState.Selected)
}
}
}
extension UIImage {
static func imageWithColor(color:UIColor,cornerRadius:CGFloat) -> UIImage {
let minEdgeSize:CGFloat = cornerRadius * 2 + 1 // edge size from corner radius
let rect:CGRect = CGRectMake(0, 0, minEdgeSize, minEdgeSize);
let roundedRect:UIBezierPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
roundedRect.lineWidth = 0;
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
roundedRect.fill()
roundedRect.stroke()
roundedRect.addClip()
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image.resizableImageWithCapInsets(UIEdgeInsets(top: cornerRadius, left: cornerRadius, bottom: cornerRadius, right: cornerRadius))
}
func imageWithMinimumSize(size:CGSize) -> UIImage {
let rect:CGRect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), false, 0.0)
self.drawInRect(rect)
let resized:UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resized.resizableImageWithCapInsets(UIEdgeInsets(top: size.height/2, left: size.width/2, bottom: size.height/2, right: size.width/2))
}
} | mit | cf618f3d2951a1c95dc117164c9dcfd1 | 33.574257 | 184 | 0.634827 | 5.286147 | false | false | false | false |
CocoaHeads-Shanghai/MeetupPresentations | 2016_03_31 Meeting #15 Begin a New Start/Presentation && Demo/5 Swift Tips in 5 Minutes.playground/Pages/Easier Configuration.xcplaygroundpage/Contents.swift | 1 | 715 | //: [Previous](@previous)
import UIKit
import XCPlayground
/// - SeeAlso: [Reader Submissions - New Year's 2016](http://nshipster.com/new-years-2016/)
@warn_unused_result
public func Init<Type>(value : Type, @noescape block: (object: Type) -> Void) -> Type {
block(object: value)
return value
}
//: Good
let textLabel = Init(UILabel()) {
$0.font = UIFont.boldSystemFontOfSize(13.0)
$0.text = "Hello, World"
$0.textAlignment = .Center
}
//: Not that good
let anotherLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFontOfSize(13.0)
label.text = "Hello, World"
label.textAlignment = .Center
return label
}()
textLabel
anotherLabel
//: [Next](@next)
| mit | 0cdefaf48fcbadd8ab9187da454aaaa1 | 21.34375 | 91 | 0.664336 | 3.504902 | false | false | false | false |
sebastiangoetz/slr-toolkit | ios-client/SLR Toolkit/Logic/Taxonomy Parser/TaxonomyParser.swift | 1 | 2922 | import Foundation
/// Parser for SLR Toolkit taxonomies.
enum TaxonomyParser {
static func parse(_ taxonomy: String) -> [TaxonomyParserNode]? {
guard taxonomy.filter({ $0 == "{" }).count == taxonomy.filter({ $0 == "}" }).count else { return nil }
var nodes = [TaxonomyParserNode]()
var parent: TaxonomyParserNode?
var string = ""
var lastControlChar = ""
for char in taxonomy {
if char == "{" {
let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmedString.isEmpty {
return nil
} else {
let newNode = TaxonomyParserNode(name: trimmedString, parent: parent)
if let parent = parent {
parent.children.append(newNode)
} else {
nodes.append(newNode)
}
parent = newNode
string = ""
}
lastControlChar = "{"
} else if char == "}" {
let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmedString.isEmpty {
if lastControlChar == "{" || lastControlChar == "," {
return nil
} else if lastControlChar == "}" {
parent = parent?.parent
}
} else {
if let parent = parent {
parent.children.append(TaxonomyParserNode(name: trimmedString, parent: parent))
} else {
return nil
}
string = ""
}
lastControlChar = "}"
} else if char == "," {
let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmedString.isEmpty {
if lastControlChar == "{" || lastControlChar == "," {
return nil
} else if lastControlChar == "}" {
parent = parent?.parent
}
} else {
if let parent = parent {
parent.children.append(TaxonomyParserNode(name: trimmedString, parent: parent))
} else {
nodes.append(TaxonomyParserNode(name: trimmedString))
}
string = ""
}
lastControlChar = ","
} else {
string += String(char)
}
}
let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmedString.isEmpty {
nodes.append(TaxonomyParserNode(name: trimmedString))
}
return nodes
}
}
| epl-1.0 | 58b4d3a3cb90b3c6a3ded15feaeff3f1 | 37.96 | 110 | 0.452772 | 5.91498 | false | false | false | false |
cubixlabs/GIST-Framework | GISTFramework/Classes/GISTSocial/Protocols/Mappable+ToDictionary.swift | 1 | 1111 | //
// Mappable+ToDictionary.swift
// FoodParcel
//
// Created by Shoaib Abdul on 14/10/2016.
// Copyright © 2016 Cubixlabs. All rights reserved.
//
import Foundation
import ObjectMapper
public protocol ReverseMappable {
func toDictionary () -> NSDictionary;
}
public extension ReverseMappable {
func reverseMap (_ obj:Any?) -> Any? {
guard (obj != nil) else {
return nil;
}
if let mappableObj:ReverseMappable = obj as? ReverseMappable {
return mappableObj.toDictionary();
}
if let arrMappableObj:[Any] = obj as? [Any] {
return self.reverseMapArray(arrMappableObj);
}
return obj;
} //F.E.
func reverseMapArray(_ arrMappableObj:[Any]) -> NSArray {
let rtnArr:NSMutableArray = NSMutableArray();
for obj in arrMappableObj {
if let mappable = obj as? ReverseMappable {
let dict = mappable.toDictionary()
rtnArr.add(dict);
}
}
return rtnArr;
}
}
| agpl-3.0 | 348014048c4979127168d1c25d51d9d1 | 23.130435 | 70 | 0.557658 | 4.586777 | false | false | false | false |
buguanhu/THLiveSmart | THLiveSmart/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Bag.swift | 8 | 2629 | //
// Bag.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-07-10.
// Copyright (c) 2014 GitHub. All rights reserved.
//
/// A uniquely identifying token for removing a value that was inserted into a
/// Bag.
public final class RemovalToken {
private var identifier: UInt?
private init(identifier: UInt) {
self.identifier = identifier
}
}
/// An unordered, non-unique collection of values of type `Element`.
public struct Bag<Element> {
private var elements: [BagElement<Element>] = []
private var currentIdentifier: UInt = 0
public init() {
}
/// Insert the given value into `self`, and return a token that can
/// later be passed to `removeValueForToken()`.
///
/// - parameters:
/// - value: A value that will be inserted.
public mutating func insert(value: Element) -> RemovalToken {
let (nextIdentifier, overflow) = UInt.addWithOverflow(currentIdentifier, 1)
if overflow {
reindex()
}
let token = RemovalToken(identifier: currentIdentifier)
let element = BagElement(value: value, identifier: currentIdentifier, token: token)
elements.append(element)
currentIdentifier = nextIdentifier
return token
}
/// Remove a value, given the token returned from `insert()`.
///
/// - note: If the value has already been removed, nothing happens.
///
/// - parameters:
/// - token: A token returned from a call to `insert()`.
public mutating func removeValueForToken(token: RemovalToken) {
if let identifier = token.identifier {
// Removal is more likely for recent objects than old ones.
for i in elements.indices.reverse() {
if elements[i].identifier == identifier {
elements.removeAtIndex(i)
token.identifier = nil
break
}
}
}
}
/// In the event of an identifier overflow (highly, highly unlikely), reset
/// all current identifiers to reclaim a contiguous set of available
/// identifiers for the future.
private mutating func reindex() {
for i in elements.indices {
currentIdentifier = UInt(i)
elements[i].identifier = currentIdentifier
elements[i].token.identifier = currentIdentifier
}
}
}
extension Bag: CollectionType {
public typealias Index = Array<Element>.Index
public var startIndex: Index {
return elements.startIndex
}
public var endIndex: Index {
return elements.endIndex
}
public subscript(index: Index) -> Element {
return elements[index].value
}
}
private struct BagElement<Value> {
let value: Value
var identifier: UInt
let token: RemovalToken
}
extension BagElement: CustomStringConvertible {
var description: String {
return "BagElement(\(value))"
}
}
| apache-2.0 | 3b3890600ee150820ea3e9ad4aa0f95d | 24.038095 | 85 | 0.708254 | 3.750357 | false | false | false | false |
apple/swift-nio-http2 | Sources/NIOHTTP2/HTTP2Settings.swift | 1 | 3708 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
/// A collection of HTTP/2 settings.
///
/// This is a typealias because we may change this into a custom structure at some stage.
public typealias HTTP2Settings = [HTTP2Setting]
/// A HTTP/2 settings parameter that allows representing both known and unknown HTTP/2
/// settings parameters.
public struct HTTP2SettingsParameter: Sendable {
internal let networkRepresentation: UInt16
/// Create a ``HTTP2SettingsParameter`` that is not known to NIO.
///
/// If this is a known parameter, use one of the static values.
public init(extensionSetting: Int) {
self.networkRepresentation = UInt16(extensionSetting)
}
/// Initialize a ``HTTP2SettingsParameter`` from nghttp2's representation.
internal init(fromNetwork value: Int32) {
self.networkRepresentation = UInt16(value)
}
/// Initialize a ``HTTP2SettingsParameter`` from a network `UInt16`.
internal init(fromPayload value: UInt16) {
self.networkRepresentation = value
}
/// A helper to initialize the static parameters.
private init(_ value: UInt16) {
self.networkRepresentation = value
}
/// Corresponds to `SETTINGS_HEADER_TABLE_SIZE`
public static let headerTableSize = HTTP2SettingsParameter(1)
/// Corresponds to `SETTINGS_ENABLE_PUSH`.
public static let enablePush = HTTP2SettingsParameter(2)
/// Corresponds to `SETTINGS_MAX_CONCURRENT_STREAMS`
public static let maxConcurrentStreams = HTTP2SettingsParameter(3)
/// Corresponds to `SETTINGS_INITIAL_WINDOW_SIZE`
public static let initialWindowSize = HTTP2SettingsParameter(4)
/// Corresponds to `SETTINGS_MAX_FRAME_SIZE`
public static let maxFrameSize = HTTP2SettingsParameter(5)
/// Corresponds to `SETTINGS_MAX_HEADER_LIST_SIZE`
public static let maxHeaderListSize = HTTP2SettingsParameter(6)
/// Corresponds to `SETTINGS_ENABLE_CONNECT_PROTOCOL` from RFC 8441.
public static let enableConnectProtocol = HTTP2SettingsParameter(8)
}
extension HTTP2SettingsParameter: Equatable { }
extension HTTP2SettingsParameter: Hashable { }
/// A single setting for HTTP/2, a combination of a ``HTTP2SettingsParameter`` and its value.
public struct HTTP2Setting: Sendable {
/// The settings parameter for this setting.
public var parameter: HTTP2SettingsParameter
/// The value of the settings parameter. This must be a 32-bit number.
public var value: Int {
get {
return Int(self._value)
}
set {
self._value = UInt32(newValue)
}
}
/// The value of the setting. Swift doesn't like using explicitly-sized integers in general,
/// so we use this as an internal implementation detail and expose it via a computed Int
/// property.
internal var _value: UInt32
/// Create a new ``HTTP2Setting``.
public init(parameter: HTTP2SettingsParameter, value: Int) {
self.parameter = parameter
self._value = UInt32(value)
}
}
extension HTTP2Setting: Equatable {
public static func ==(lhs: HTTP2Setting, rhs: HTTP2Setting) -> Bool {
return lhs.parameter == rhs.parameter && lhs._value == rhs._value
}
}
| apache-2.0 | 6f760035a80b05a161618869b89ad34a | 33.981132 | 96 | 0.672869 | 4.483676 | false | false | false | false |
codestergit/swift | test/SILGen/partial_apply_generic.swift | 3 | 2464 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
protocol Foo {
static func staticFunc()
func instanceFunc()
}
// CHECK-LABEL: sil hidden @_T021partial_apply_generic14getStaticFunc1{{[_0-9a-zA-Z]*}}F
func getStaticFunc1<T: Foo>(t: T.Type) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK-NEXT: apply [[REF]]<T>(%0)
return t.staticFunc
// CHECK-NEXT: return
}
// CHECK-LABEL: sil shared [thunk] @_T021partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK: [[REF:%.*]] = witness_method $Self, #Foo.staticFunc!1
// CHECK-NEXT: partial_apply [[REF]]<Self>(%0)
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @_T021partial_apply_generic14getStaticFunc2{{[_0-9a-zA-Z]*}}F
func getStaticFunc2<T: Foo>(t: T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK: apply [[REF]]<T>
return T.staticFunc
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T021partial_apply_generic16getInstanceFunc1{{[_0-9a-zA-Z]*}}F
func getInstanceFunc1<T: Foo>(t: T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization]
// CHECK-NEXT: apply [[REF]]<T>
return t.instanceFunc
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: return
}
// CHECK-LABEL: sil shared [thunk] @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK: [[REF:%.*]] = witness_method $Self, #Foo.instanceFunc!1
// CHECK-NEXT: partial_apply [[REF]]<Self>(%0)
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @_T021partial_apply_generic16getInstanceFunc2{{[_0-9a-zA-Z]*}}F
func getInstanceFunc2<T: Foo>(t: T) -> (T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: partial_apply [[REF]]<T>(
return T.instanceFunc
// CHECK-NEXT: destroy_addr %0 : $*
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T021partial_apply_generic16getInstanceFunc3{{[_0-9a-zA-Z]*}}F
func getInstanceFunc3<T: Foo>(t: T.Type) -> (T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: partial_apply [[REF]]<T>(
return t.instanceFunc
// CHECK-NEXT: return
}
| apache-2.0 | a42683a26f82318a6450f637900f8a09 | 38.111111 | 101 | 0.655438 | 2.933333 | false | false | false | false |
tjw/swift | test/SILGen/lying_about_optional_return.swift | 2 | 1727 | // RUN: %target-swift-frontend -import-objc-header %S/Inputs/c_function_pointer_in_c_struct.h -emit-silgen -enable-sil-ownership %s | %FileCheck %s
// CHECK-LABEL: sil hidden @$S27lying_about_optional_return0C37ChainingForeignFunctionTypeProperties{{[_0-9a-zA-Z]*}}F
func optionalChainingForeignFunctionTypeProperties(a: SomeCallbacks?) {
// CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $()
let _: ()? = voidReturning()
// CHECK: unchecked_trivial_bit_cast {{%.*}} : $UnsafeMutableRawPointer to $Optional<UnsafeMutableRawPointer>
let _: UnsafeMutableRawPointer? = voidPointerReturning()
// CHECK: unchecked_trivial_bit_cast {{%.*}} : $UnsafeMutablePointer<Int8> to $Optional<UnsafeMutablePointer<Int8>>
let _: UnsafeMutablePointer<Int8>? = pointerReturning()
// CHECK: unchecked_trivial_bit_cast {{%.*}} : $UnsafePointer<Int8> to $Optional<UnsafePointer<Int8>>
let _: UnsafePointer<Int8>? = constPointerReturning()
// CHECK: unchecked_trivial_bit_cast {{%.*}} : $OpaquePointer to $Optional<OpaquePointer>
let _: OpaquePointer? = opaquePointerReturning()
// CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $()
a?.voidReturning()
// CHECK: unchecked_trivial_bit_cast {{%.*}} : $UnsafeMutableRawPointer to $Optional<UnsafeMutableRawPointer>
a?.voidPointerReturning()
// CHECK: unchecked_trivial_bit_cast {{%.*}} : $UnsafeMutablePointer<Int8> to $Optional<UnsafeMutablePointer<Int8>>
a?.pointerReturning()
// CHECK: unchecked_trivial_bit_cast {{%.*}} : $UnsafePointer<Int8> to $Optional<UnsafePointer<Int8>>
a?.constPointerReturning()
// CHECK: unchecked_trivial_bit_cast {{%.*}} : $OpaquePointer to $Optional<OpaquePointer>
a?.opaquePointerReturning()
}
| apache-2.0 | 67f6cb0ad1084102653e68a3fa9c13ee | 62.962963 | 147 | 0.714534 | 4.161446 | false | false | false | false |
shhuangtwn/ProjectLynla | Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisLabel.swift | 1 | 951 | //
// ChartAxisLabel.swift
// swift_charts
//
// Created by ischuetz on 01/03/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/// A model of an axis label
public class ChartAxisLabel {
public let text: String
let settings: ChartLabelSettings
var hidden: Bool = false
/// The size of the bounding rectangle for the axis label, taking into account the font and rotation it will be drawn with
lazy var textSize: CGSize = {
let size = ChartUtils.textSize(self.text, font: self.settings.font)
if self.settings.rotation == 0 {
return size
} else {
return ChartUtils.boundingRectAfterRotatingRect(CGRectMake(0, 0, size.width, size.height), radians: self.settings.rotation * CGFloat(M_PI) / 180.0).size
}
}()
public init(text: String, settings: ChartLabelSettings) {
self.text = text
self.settings = settings
}
}
| mit | ea96791a6f61bbbe6f760709f38329b8 | 27.818182 | 164 | 0.656151 | 4.189427 | false | false | false | false |
ajaybeniwal/SwiftTransportApp | TransitFare/TransitFare/LoginViewController.swift | 1 | 7961 | //
// LoginViewController.swift
// TransitFare
//
// Created by ajaybeniwal203 on 7/2/16.
// Copyright © 2016 ajaybeniwal203. All rights reserved.
//
import UIKit
import SnapKit
import MBProgressHUD
import Material
import Alamofire
import Parse
class LoginViewController: UIViewController {
let kUserName = "me.fin.username"
var backgroundImageView : UIImageView?
var userNameTextField:UITextField?
var passwordTextField:UITextField?
var loginButton:RaisedButton?
var frostedView :UIView?
var registerButton :RaisedButton?
var forgotPassword :UILabel?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blackColor()
self.backgroundImageView = UIImageView(image: UIImage(named: "background-logo.jpg"))
self.backgroundImageView!.frame = self.view.frame
self.backgroundImageView!.contentMode = .ScaleToFill
self.view.addSubview(self.backgroundImageView!)
frostedView = UIView()
frostedView!.frame = self.view.frame
self.view.addSubview(frostedView!)
self.userNameTextField = UITextField()
self.userNameTextField!.textColor = UIColor.blackColor()
self.userNameTextField!.backgroundColor = UIColor(white: 1, alpha: 0.6);
self.userNameTextField!.layer.borderWidth = 0.5
self.userNameTextField!.keyboardType = .ASCIICapable
self.userNameTextField!.layer.borderColor = UIColor(white: 1, alpha: 0.8).CGColor;
self.userNameTextField!.placeholder = "UserName"
self.userNameTextField!.clearButtonMode = .Always
self.userNameTextField!.frame = CGRectMake(0, 100, self.view.frame.width,60)
let userNameIconImageView = UIImageView(image: UIImage(named: "username")!.imageWithRenderingMode(.AlwaysTemplate));
userNameIconImageView.frame = CGRectMake(30, 10, 24, 24)
userNameIconImageView.contentMode = .ScaleAspectFit
userNameIconImageView.tintColor = MaterialColor.grey.base
self.userNameTextField!.leftView = userNameIconImageView
self.userNameTextField!.leftViewMode = .Always
frostedView!.addSubview(self.userNameTextField!)
self.userNameTextField!.snp_makeConstraints{ (make) -> Void in
make.centerX.equalTo(self.frostedView!)
make.top.equalTo(self.frostedView!).offset(150)
make.trailing.equalTo(self.frostedView!)
make.leading.equalTo(self.frostedView!)
make.height.equalTo(50)
}
self.passwordTextField = UITextField()
self.passwordTextField!.textColor = UIColor.blackColor()
self.passwordTextField!.backgroundColor = UIColor(white: 1, alpha: 0.6);
self.passwordTextField!.layer.borderWidth = 0.5
self.passwordTextField!.keyboardType = .ASCIICapable
self.passwordTextField!.secureTextEntry = true
self.passwordTextField!.layer.borderColor = UIColor(white: 1, alpha: 0.8).CGColor;
self.passwordTextField!.placeholder = "Password"
self.passwordTextField!.clearButtonMode = .Always
self.passwordTextField!.frame = CGRectMake(0, 160, self.view.frame.width,60)
let passwordIconImageView = UIImageView(image: UIImage(named: "password")!.imageWithRenderingMode(.AlwaysTemplate));
passwordIconImageView.frame = CGRectMake(30, 10, 24, 24)
passwordIconImageView.contentMode = .ScaleAspectFit
passwordIconImageView.tintColor = MaterialColor.grey.base
self.passwordTextField!.leftView = passwordIconImageView
self.passwordTextField!.leftViewMode = .Always
frostedView!.addSubview(self.passwordTextField!)
self.passwordTextField!.snp_makeConstraints{ (make) -> Void in
make.top.equalTo(self.userNameTextField!.snp_bottom).offset(0)
make.centerX.equalTo(self.frostedView!)
make.leading.equalTo(self.frostedView!)
make.height.equalTo(50)
}
self.loginButton = RaisedButton()
self.loginButton!.setTitle("Login", forState: .Normal)
self.loginButton!.backgroundColor = MaterialColor.pink.base
self.loginButton!.alpha = 0.8
frostedView!.addSubview(self.loginButton!)
self.loginButton?.addTarget(self, action: #selector(self.loginClick(_:)), forControlEvents: .TouchUpInside)
self.loginButton!.snp_makeConstraints{ (make) -> Void in
make.top.equalTo(self.passwordTextField!.snp_bottom).offset(20)
make.centerX.equalTo(self.frostedView!)
make.width.equalTo(250)
make.height.equalTo(50)
}
self.registerButton = RaisedButton()
self.registerButton!.setTitle("Register", forState: .Normal)
self.registerButton!.backgroundColor = MaterialColor.blue.base
self.registerButton!.alpha = 0.8
frostedView!.addSubview(self.registerButton!)
self.registerButton?.addTarget(self, action: #selector(self.registerClick(_:)), forControlEvents: .TouchUpInside)
self.registerButton!.snp_makeConstraints{ (make) -> Void in
make.top.equalTo(self.loginButton!.snp_bottom).offset(20)
make.centerX.equalTo(self.frostedView!)
make.width.equalTo(250)
make.height.equalTo(50)
}
self.forgotPassword = UILabel()
self.forgotPassword!.text = "Forgot your password?"
self.forgotPassword?.textColor = MaterialColor.white
self.forgotPassword?.userInteractionEnabled = true;
frostedView!.addSubview(self.forgotPassword!)
self.forgotPassword!.snp_makeConstraints{ (make) -> Void in
make.top.equalTo(self.registerButton!.snp_bottom).offset(20)
make.centerX.equalTo(self.frostedView!)
}
// Do any additional setup after loading the view.
}
override func viewDidDisappear(animated: Bool) {
self.view.endEditing(true);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loginClick(sender:UIButton){
let progressHUD = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
PFUser.logInWithUsernameInBackground(self.userNameTextField!.text!, password: self.passwordTextField!.text!){
(user: PFUser?, error: NSError?) -> Void in
progressHUD.hide(true)
if user != nil {
let installation = PFInstallation.currentInstallation()
installation["user"] = PFUser.currentUser()
installation.saveInBackground()
installation.addUniqueObject("Giants", forKey: "channels")
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootViewController = storyboard.instantiateViewControllerWithIdentifier("HomeStory") as! UITabBarController
appDelegate.window?.rootViewController = rootViewController
} else {
self.showAlert("Error", message: "Wrong username or password")
}
}
}
func registerClick(sender:UIButton){
self.showViewController(RegisterViewController(), sender: self)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 170d027dd67deb1438a8021347b870e8 | 42.027027 | 127 | 0.662186 | 5.182292 | false | false | false | false |
chordsNcode/jsonperf | JsonPerfTests/GlossPerfTests.swift | 1 | 737 | //
// GlossPerfTests.swift
// JsonPerf
//
// Created by Matt Dias on 10/9/16.
//
import XCTest
import Gloss
@testable import JsonPerf
class GlossPerfTests: XCTestCase {
func testGlossPerformance() {
self.measure {
do {
guard let json = try JSONSerialization.jsonObject(with: self.data!, options: .mutableLeaves) as? [String: Any],
let items = json["items"] as? [[String: Any]] else {
XCTFail("bad JSON")
return
}
let result = items.map { Repo(json: $0) }
XCTAssertTrue(result.count == 30)
} catch {
XCTFail("bad json")
}
}
}
}
| mit | 42bc170fb1d07366fd0b258f209f88f6 | 21.333333 | 127 | 0.502035 | 4.360947 | false | true | false | false |
15221758864/TestKitchen_1606 | TestKitchen/TestKitchen/classes/common/CBRedPacketCell.swift | 1 | 3769 | //
// CBRedPacketCell.swift
// TestKitchen
//
// Created by Ronie on 16/8/18.
// Copyright © 2016年 Ronie. All rights reserved.
//
import UIKit
class CBRedPacketCell: UITableViewCell {
@IBOutlet weak var scrollView: UIScrollView!
//显示数据
var model: CBRecommendWidgetListModel? {
didSet{
showData()
}
}
//显示图片和文字
func showData() {
//删除之前的子视图
for sub in scrollView.subviews {
sub.removeFromSuperview()
}
//1.容器视图
let container = UIView.createView()
scrollView.addSubview(container)
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
//约束
container.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.scrollView)
make.height.equalTo((self?.scrollView.snp_height)!)
}
var lastView: UIView? = nil
let cnt = model?.widget_data?.count
if cnt > 0 {
for i in 0..<cnt! {
let imageModel = model?.widget_data![i]
if imageModel?.type == "image" {
let imageView = UIImageView.createImageView(nil)
let url = NSURL(string: (imageModel?.content)!)
imageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "g2.jpg"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
container.addSubview(imageView)
//约束
imageView.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(container)
make.width.equalTo(180)
if i == 0{
make.left.equalTo(0)
}else{
make.left.equalTo((lastView?.snp_right)!)
}
})
//添加点击事件
imageView.userInteractionEnabled = true
imageView.tag = 400+i
//手势
let g = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
imageView.addGestureRecognizer(g)
lastView = imageView
}
}
//修改容器的大小
container.snp_makeConstraints(closure: { (make) in
make.right.equalTo((lastView?.snp_right)!)
})
}
}
func tapAction(g: UIGestureRecognizer) {
let index = (g.view?.tag)! - 400
print(index)
}
//创建cell的方法
class func createRedPacketCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withListModel listModel: CBRecommendWidgetListModel) -> CBRedPacketCell{
let cellID = "CBRedPacketCellID"
var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? CBRedPacketCell
if cell == nil{
cell = NSBundle.mainBundle().loadNibNamed("CBRedPacketCell", owner: nil, options: nil).last as? CBRedPacketCell
}
cell?.model = listModel
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
//红包入口分组里面的一个控件
class packetButton: UIControl{
}
| mit | 4a97c6db1b4dae522074ca97720c1fb0 | 27.936508 | 170 | 0.530993 | 5.261183 | false | false | false | false |
tomabuct/TAStackView | TAStackView/StackSpacerView.swift | 1 | 1699 | //
// StackSpacerView.swift
// TAStackView
//
// Created by Tom Abraham on 9/25/14.
// Copyright (c) 2014 Tom Abraham. All rights reserved.
//
import UIKit
class StackSpacerView : UIView {
let huggingConstraint : NSLayoutConstraint!
let spacingConstraint : NSLayoutConstraint!
required init(coder aDecoder: NSCoder) {
fatalError("NSCoder not supported")
}
override convenience init() {
self.init(frame: CGRectNull)
}
override init(frame: CGRect) {
super.init(frame: frame)
// always invisible
hidden = true
// always used in manual Auto Layout context
setTranslatesAutoresizingMaskIntoConstraints(false)
}
// MARK: Configuration
var orientation : TAUserInterfaceLayoutOrientation = .Horizontal {
didSet { setNeedsUpdateConstraints() }
};
var spacing : Float = DefaultSpacing {
didSet { setNeedsUpdateConstraints() }
}
var spacingPriority : UILayoutPriority = LayoutPriorityDefaultLow {
didSet { setNeedsUpdateConstraints() }
}
// MARK: Layout
override func updateConstraints() {
removeConstraints(constraints())
let char = orientation.toCharacter()
let metrics = [ "spacing": spacing, "sP": spacingPriority ]._bridgeToObjectiveC()
let views = [ "self": self ]._bridgeToObjectiveC()
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("\(char):[self(>=spacing)]",
options: NSLayoutFormatOptions(0), metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("\(char):[self(spacing@sP)]",
options: NSLayoutFormatOptions(0), metrics: metrics, views: views))
super.updateConstraints()
}
} | mit | 630f7213fe9ebe0f8211608a3d77a1c5 | 25.984127 | 95 | 0.699823 | 4.924638 | false | false | false | false |
csmulhern/uranus | Uranus/Uranus/ComponentsView.swift | 1 | 11061 | import Foundation
import Mars
internal protocol ViewDelegate: class {
func viewDidInvalidateLayout(_ view: View)
}
public class View: Component {
internal weak var delegate: ViewDelegate?
public var children: [Specification] {
didSet(oldValue) {
for child in oldValue {
child.model.parent = nil
}
for child in self.children {
child.model.parent = self
}
}
}
public var horizontalAlignment: HorizontalAlignment {
didSet {
self.invalidateLayout()
}
}
public var automaticMarginsApplyToEdges: Bool {
didSet {
self.invalidateLayout()
}
}
public init(children: [Component] = [], horizontalAlignment: HorizontalAlignment = .left, automaticMarginsApplyToEdges: Bool = true) {
self.children = View.createSpecifications(with: children)
self.horizontalAlignment = horizontalAlignment
self.automaticMarginsApplyToEdges = automaticMarginsApplyToEdges
super.init()
for child in self.children {
child.model.parent = self
}
}
public func children(_ children: [Component]) -> Self {
self.children = View.createSpecifications(with: children)
return self
}
public func horizontalAlignment(_ horizontalAlignment: HorizontalAlignment) -> Self {
self.horizontalAlignment = horizontalAlignment
return self
}
public func automaticMarginsApplyToEdges(_ automaticMarginsApplyToEdges: Bool) -> Self {
self.automaticMarginsApplyToEdges = automaticMarginsApplyToEdges
return self
}
public override func invalidateLayout() {
super.invalidateLayout()
if self.parent == nil {
self.delegate?.viewDidInvalidateLayout(self)
}
}
public override func intoSpecification() -> Specification {
return Specification(model: self, viewClass: ComponentsView.self)
}
public func visibleChildren() -> [Specification] {
return self.children.filter({(child) in
return !child.model.isHidden
})
}
private static func createSpecifications(with components: [Component]) -> [Specification] {
return components.map({(component) in
return component.intoSpecification()
})
}
}
public protocol ComponentsViewDelegate: class {
func componentsViewDidInvalidateLayout(_ componentsView: ComponentsView)
}
public class ComponentsView: UIView {
private static let animationDuration: TimeInterval = 0.33
public override static var layerClass: AnyClass {
return CATransformLayer.self
}
private var views: [UIView] = []
private var root: View? {
didSet(oldValue) {
oldValue?.delegate = nil
self.root?.delegate = self
}
}
internal var requiresViewConfiguration = false
public weak var delegate: ComponentsViewDelegate?
public required override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func layoutSubviews() {
super.layoutSubviews()
if let root = self.root {
let frames = FlexLayout.viewFrames(for: root, constrainedToSize: self.bounds.size)
let layoutDirection = self.userInterfaceLayoutDirection()
for (view, frame) in self.views.zip(frames) {
view.frame = self.layoutDirectionAdjustedLayout(for: frame, layoutDirection: layoutDirection)
}
}
}
public override func sizeThatFits(_ size: CGSize) -> CGSize {
let layoutSize = self.root.map({(view) in
ComponentsView.size(for: view, constrainedToSize: size)
})
return layoutSize ?? CGSize.zero
}
public func configure(with rootView: View, animated: Bool) {
if animated {
self.animatedConfiguration(with: rootView)
}
else {
self.nonanimatedConfiguration(with: rootView)
}
}
private func nonanimatedConfiguration(with rootView: View) {
self.root = rootView
if self.viewNeedsToBeReset(for: rootView.children) {
for view in self.views {
view.removeFromSuperview()
}
self.views.removeAll(keepingCapacity: true)
for specification in rootView.children {
let view = specification.internalViewCreationBlock()
self.addSubview(view)
self.views.append(view)
}
}
self.performViewConfiguration()
}
private func animatedConfiguration(with rootView: View) {
let oldComponents = self.root?.children ?? []
let newComponents = rootView.children
self.root = rootView
let oldIndexToNewIndex = self.createMatchingComponentIndexLookupTable(source: oldComponents, destination: newComponents)
var removedViews: [UIView] = []
var reusedViews: [Int: UIView] = [:]
var newViews: [Int: UIView] = [:]
for (index, view) in self.views.enumerated() {
if let newIndex = oldIndexToNewIndex[index] {
reusedViews[newIndex] = view
}
else {
removedViews.append(view)
}
}
self.views.removeAll(keepingCapacity: true)
for (index, component) in newComponents.enumerated() {
if let view = reusedViews[index] {
self.views.append(view)
}
else {
let view = component.internalViewCreationBlock()
self.addSubview(view)
self.views.append(view)
newViews[index] = view
}
}
let layoutDirection = self.userInterfaceLayoutDirection()
let frames = FlexLayout.viewFrames(for: rootView, constrainedToSize: self.bounds.size)
self.performViewConfiguration()
for (index, view) in newViews {
view.frame = self.layoutDirectionAdjustedLayout(for: frames[index], layoutDirection: layoutDirection)
view.alpha = 0.0
}
UIView.animate(withDuration: ComponentsView.animationDuration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [], animations: {
for (index, view) in reusedViews {
let component = newComponents[index]
component.internalConfigurationBlock(view)
view.frame = self.layoutDirectionAdjustedLayout(for: frames[index], layoutDirection: layoutDirection)
}
for (index, view) in newViews {
let component = newComponents[index]
view.alpha = component.model.alpha
}
for view in removedViews {
view.alpha = 0.0
}
}, completion: {(_) in
for view in removedViews {
view.removeFromSuperview()
}
})
}
// MARK: Layout
private func userInterfaceLayoutDirection() -> UIUserInterfaceLayoutDirection {
let layoutDirection: UIUserInterfaceLayoutDirection
if #available(iOS 9, *) {
layoutDirection = UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute)
}
else {
layoutDirection = UIApplication.shared.userInterfaceLayoutDirection
}
return layoutDirection
}
private func layoutDirectionAdjustedLayout(for frame: CGRect, layoutDirection: UIUserInterfaceLayoutDirection) -> CGRect {
return (layoutDirection == UIUserInterfaceLayoutDirection.rightToLeft) ? self.rightToLeftAdjustedFrame(for: frame) : frame
}
private func rightToLeftAdjustedFrame(for frame: CGRect) -> CGRect {
return CGRect(x: self.frame.size.width - frame.origin.x - frame.size.width, y: frame.origin.y, width: frame.size.width, height: frame.size.height)
}
// MARK: Animation
private func createMatchingComponentIndexLookupTable(source: [Specification], destination: [Specification]) -> [Int: Int] {
var specificationIndex = SpecificationIndex(specifications: source)
var destinationToSourceIndexMap: [Int: Int] = [:]
for (destinationIndex, specification) in destination.enumerated() {
if let sourceIndex = specificationIndex.popAddressIndex(for: specification) {
destinationToSourceIndexMap[destinationIndex] = sourceIndex
}
}
for (destinationIndex, specification) in destination.enumerated() {
if destinationToSourceIndexMap[destinationIndex] != nil {
continue
}
if let sourceIndex = specificationIndex.popIdentifierIndex(for: specification) {
destinationToSourceIndexMap[destinationIndex] = sourceIndex
}
}
var sourceToDestinationIndexMap: [Int: Int] = [:]
for (key, value) in destinationToSourceIndexMap {
sourceToDestinationIndexMap[value] = key
}
return sourceToDestinationIndexMap
}
// MARK: Helpers
private func viewNeedsToBeReset(for specifications: [Specification]) -> Bool {
return specifications.count != self.views.count || specifications.zip(self.views).any({(pair) -> Bool in
let (specification, view) = pair
return specification.viewClass !== type(of: view)
})
}
internal func performViewConfiguration() {
guard let children = self.root?.children else {
return
}
for (view, specification) in self.views.zip(children) {
view.alpha = specification.model.alpha
view.isHidden = specification.model.isHidden
if specification.model.isHidden {
continue
}
specification.internalConfigurationBlock(view)
}
self.delegate?.componentsViewDidInvalidateLayout(self)
}
}
extension ComponentsView: Composable {
public func configure(with component: View) {
self.configure(with: component, animated: false)
}
public func setHighlighted(_ highlighted: Bool, animated: Bool) {
}
public func setSelected(_ selected: Bool, animated: Bool) {
}
public func prepareForReuse() {
}
public static func size(for component: View, constrainedToSize: CGSize) -> CGSize {
return FlexLayout.size(for: component, constrainedToSize: constrainedToSize)
}
}
extension ComponentsView: ViewDelegate {
func viewDidInvalidateLayout(_ view: View) {
if !self.requiresViewConfiguration {
self.requiresViewConfiguration = true
DispatchQueue.main.async(execute: {
self.requiresViewConfiguration = false
self.performViewConfiguration()
})
}
}
}
| unlicense | 7c55f7e82f92bb7e71f27cd8eea61426 | 31.06087 | 166 | 0.627611 | 5.195397 | false | false | false | false |
zyuanming/HSStockChart | HSStockChartDemo/HSStockChartDemo/HSStockChart/theme/HSKLineTheme.swift | 1 | 528 | //
// HSKLineTheme.swift
// HSStockChartDemo
//
// Created by Hanson on 2017/1/20.
// Copyright © 2017年 hanson. All rights reserved.
//
import UIKit
class HSKLineTheme: HSBasicTheme {
var borderWidth: CGFloat = 1
var xAxisHeitht: CGFloat = 20
var candleWidth: CGFloat = 5
var candleGap: CGFloat = 2
var candleMinHeight: CGFloat = 0.5
var candleMaxWidth: CGFloat = 30
var candleMinWidth: CGFloat = 2
var viewMinYGap: CGFloat = 15
var volumeMaxGap: CGFloat = 10
}
| mit | 80b5d0daa1246db6a0b0b0d01183b9f5 | 19.192308 | 50 | 0.659048 | 3.59589 | false | false | false | false |
oNguyenVanHung/TODO-App | TO-DO-APP/SettingsViewController.swift | 1 | 1425 | //
// SettingsViewController.swift
// TO-DO-APP
//
// Created by tran.xuan.diep on 8/1/17.
// Copyright © 2017 framgia. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var alertView: UIView!
@IBOutlet weak var profileView: UIView!
@IBOutlet weak var activeProfileTab: UIImageView!
@IBOutlet weak var activeAlertTab: UIImageView!
@IBAction func onButtonProfileClicked(_ sender: Any) {
if self.profileView.isHidden != false {
self.profileView.isHidden = false
self.activeProfileTab.isHidden = false
self.activeAlertTab.isHidden = true
self.alertView.isHidden = true
}
}
@IBAction func onButtonAlertClicked(_ sender: Any) {
if self.alertView.isHidden != false {
self.profileView.isHidden = true
self.activeProfileTab.isHidden = true
self.activeAlertTab.isHidden = false
self.alertView.isHidden = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.profileView.isHidden = false
self.activeProfileTab.isHidden = false
self.activeAlertTab.isHidden = true
self.alertView.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 76cc529f590bd2ce8110d79962ef3429 | 28.666667 | 58 | 0.650983 | 4.668852 | false | false | false | false |
edwardvalentini/AsyncMessagesViewController | AsyncMessagesViewController/Classes/Views/MessageTextBubbleNode.swift | 1 | 1726 | //
// MessageTextBubbleNode.swift
// AsyncMessagesViewController
//
// Created by Huy Nguyen on 13/02/15.
// Copyright (c) 2015 Huy Nguyen. All rights reserved.
//
import Foundation
import AsyncDisplayKit
private class MessageTextNode: ASTextNode {
override init() {
super.init()
placeholderColor = UIColor.gray
isLayerBacked = true
}
override func calculateSizeThatFits(_ constrainedSize: CGSize) -> CGSize {
let size = super.calculateSizeThatFits(constrainedSize)
return CGSize(width: max(size.width, 15), height: size.height)
}
}
public class MessageTextBubbleNode: ASDisplayNode {
private let isOutgoing: Bool
private let bubbleImageNode: ASImageNode
private let textNode: ASTextNode
public init(text: NSAttributedString, isOutgoing: Bool, bubbleImage: UIImage) {
self.isOutgoing = isOutgoing
bubbleImageNode = ASImageNode()
bubbleImageNode.image = bubbleImage
textNode = MessageTextNode()
textNode.attributedText = text
super.init()
addSubnode(bubbleImageNode)
addSubnode(textNode)
}
override public func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let textNodeVerticalOffset = CGFloat(6)
return ASBackgroundLayoutSpec(
child: ASInsetLayoutSpec(
insets: UIEdgeInsetsMake(
12,
12 + (isOutgoing ? 0 : textNodeVerticalOffset),
12,
12 + (isOutgoing ? textNodeVerticalOffset : 0)),
child: textNode),
background: bubbleImageNode)
}
}
| mit | 51d63ca360d6f1e7c51617945cf8bce8 | 26.396825 | 93 | 0.627462 | 5.246201 | false | false | false | false |
Hukuma23/CS193p | Assignment_4/Smashtag L9/Smashtag/TweetTableViewController.swift | 1 | 4458 | //
// TweetTableViewController.swift
// Smashtag
//
// Created by CS193p Instructor.
// Copyright © 2016 Stanford University. All rights reserved.
//
import UIKit
import Twitter
class TweetTableViewController: UITableViewController, UITextFieldDelegate
{
// MARK: Model
var tweets = [Array<Twitter.Tweet>]() {
didSet {
tableView.reloadData()
}
}
var searchText: String? {
didSet {
tweets.removeAll()
lastTwitterRequest = nil
searchForTweets()
title = searchText
}
}
// MARK: Fetching Tweets
private var twitterRequest: Twitter.Request? {
if lastTwitterRequest == nil {
if let query = searchText , !query.isEmpty {
return Twitter.Request(search: query + " -filter:retweets", count: 100)
}
}
return lastTwitterRequest?.requestForNewer
}
private var lastTwitterRequest: Twitter.Request?
private func searchForTweets()
{
if let request = twitterRequest {
lastTwitterRequest = request
request.fetchTweets { [weak weakSelf = self] newTweets in
DispatchQueue.main.async {
if request == weakSelf?.lastTwitterRequest {
if !newTweets.isEmpty {
weakSelf?.tweets.insert(newTweets, at: 0)
}
}
weakSelf?.refreshControl?.endRefreshing()
}
}
} else {
self.refreshControl?.endRefreshing()
}
}
@IBAction func refresh(_ sender: UIRefreshControl) {
searchForTweets()
}
// MARK: UITableViewDataSource
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "\(tweets.count - section)"
}
override func numberOfSections(in tableView: UITableView) -> Int {
return tweets.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.TweetCellIdentifier, for: indexPath)
let tweet = tweets[indexPath.section][indexPath.row]
if let tweetCell = cell as? TweetTableViewCell {
tweetCell.tweet = tweet
}
return cell
}
// MARK: Constants
private struct Storyboard {
static let TweetCellIdentifier = "Tweet"
static let ShowDetail = "Show Detail"
}
// MARK: Outlets
@IBOutlet weak var searchTextField: UITextField! {
didSet {
searchTextField.delegate = self
searchTextField.text = searchText
}
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
searchText = textField.text
return true
}
// MARK: View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var destinationVC = segue.destination
if let navCon = destinationVC as? UINavigationController {
destinationVC = navCon.visibleViewController ?? destinationVC
}
if let vc = destinationVC as? TweetInfoTableViewController, segue.identifier == Storyboard.ShowDetail {
if let sender = sender as? TweetTableViewCell {
print("Sender is tweetTableViewCell = \(sender.tweet?.text)")
//vc.navigationItem.title = sender.tweet?.user.name
vc.tweet = sender.tweet
}
}
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
| apache-2.0 | cf6d9e6654f59902b9f66e5ee4632b29 | 28.912752 | 112 | 0.594795 | 5.714103 | false | false | false | false |
NikitaAsabin/pdpDecember | DayPhoto/CoreData/Photo.swift | 1 | 1423 |
import UIKit
class Photo {
class func allPhotos() -> [Photo] {
var photos = [Photo]()
if let URL = NSBundle.mainBundle().URLForResource("Photos", withExtension: "plist") {
if let photosFromPlist = NSArray(contentsOfURL: URL) {
for dictionary in photosFromPlist {
let photo = Photo(dictionary: dictionary as! NSDictionary)
photos.append(photo)
}
}
}
return photos
}
var caption: String
var comment: String
var image: UIImage
init(caption: String, comment: String, image: UIImage) {
self.caption = caption
self.comment = comment
self.image = image
}
convenience init(dictionary: NSDictionary) {
let caption = dictionary["Caption"] as? String
let comment = dictionary["Comment"] as? String
let photo = dictionary["Photo"] as? String
let image = UIImage(named: photo!)?.decompressedImage
self.init(caption: caption!, comment: comment!, image: image!)
}
func heightForComment(font: UIFont, width: CGFloat) -> CGFloat {
let rect = NSString(string: comment).boundingRectWithSize(CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(rect.height)
}
}
| mit | 028a91bb479ac76c5c492553afedcfed | 32.880952 | 203 | 0.605762 | 4.940972 | false | false | false | false |
Altece/Reggie | Source/PrefixedIterator.swift | 1 | 1832 | import Foundation
/// An iterator which will return values from a given sequence before returning its
/// given interator's values.
struct PrefixedIterator<Element>: IteratorProtocol {
private var buffer: AnyIterator<Element>
private var iterator: AnyIterator<Element>
/// Create a new prefixed iterator.
/// - parameter elements: A sequence of values which should be returned before consuming the
/// given iterator's values.
/// - parameter iterator: An iterator whose values will be emitted after the buffer's elements
/// have been iterated over.
init<Elements: Sequence, Iterator: IteratorProtocol>(emitting elements: Elements,
before iterator: Iterator)
where Element == Elements.Iterator.Element, Element == Iterator.Element {
self.buffer = AnyIterator(elements.makeIterator())
self.iterator = AnyIterator(iterator)
}
mutating func next() -> Element? {
return buffer.next() ?? iterator.next()
}
}
extension AnyIterator {
/// Create an iterator which will emit values from the given sequence of elements before
/// emitting values from the given iterator.
/// - parameter elements: A buffer of values to emit before emitting
/// the wrapped iterator's values.
/// - parameter iterator: An iterator to wrap, whose values will be returned after iterating
/// over the values in the given buffer.
init<Elements: Sequence, Iterator: IteratorProtocol>(emitting elements: Elements,
before iterator: Iterator)
where Element == Elements.Iterator.Element, Element == Iterator.Element {
self = AnyIterator(PrefixedIterator(emitting: elements, before: iterator))
}
}
| mit | 6bb7fb1e58be1eb1fb82fa8c3d2c71e7 | 47.210526 | 96 | 0.662118 | 5.372434 | false | false | false | false |
mshhmzh/firefox-ios | Client/Frontend/Browser/BackForwardListAnimator.swift | 2 | 4064 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class BackForwardListAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var presenting: Bool = false
let animationDuration = 0.4
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let screens = (from: transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, to: transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!)
guard let backForwardViewController = !self.presenting ? screens.from as? BackForwardListViewController : screens.to as? BackForwardListViewController else {
return
}
var bottomViewController = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController
if let navController = bottomViewController as? UINavigationController {
bottomViewController = navController.viewControllers.last ?? bottomViewController
}
if let browserViewController = bottomViewController as? BrowserViewController {
animateWithBackForward(backForwardViewController, browserViewController: browserViewController, transitionContext: transitionContext)
}
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return animationDuration
}
}
extension BackForwardListAnimator: UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
return self
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
}
extension BackForwardListAnimator {
private func animateWithBackForward(backForward: BackForwardListViewController, browserViewController bvc: BrowserViewController, transitionContext: UIViewControllerContextTransitioning) {
guard let containerView = transitionContext.containerView() else {
return
}
if presenting {
backForward.view.frame = bvc.view.frame
backForward.view.alpha = 0;
containerView.addSubview(backForward.view)
backForward.view.snp_updateConstraints { make in
make.edges.equalTo(containerView)
}
backForward.view.layoutIfNeeded()
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options: [], animations: { () -> Void in
backForward.view.alpha = 1;
backForward.tableView.snp_updateConstraints { make in
make.height.equalTo(backForward.tableHeight)
}
backForward.view.layoutIfNeeded()
}, completion: { (completed) -> Void in
transitionContext.completeTransition(completed)
})
} else {
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 1.2, initialSpringVelocity: 0.0, options: [], animations: { () -> Void in
backForward.view.alpha = 0;
backForward.tableView.snp_updateConstraints { make in
make.height.equalTo(0)
}
backForward.view.layoutIfNeeded()
}, completion: { (completed) -> Void in
backForward.view.removeFromSuperview()
transitionContext.completeTransition(completed)
})
}
}
}
| mpl-2.0 | 070f659267d280099aa71709c16c3b8b | 46.811765 | 217 | 0.682087 | 6.673235 | false | false | false | false |
pointfreeco/swift-web | Tests/UrlFormEncodingTests/UrlFormDecoderTests.swift | 1 | 5216 | import Prelude
import SnapshotTesting
import UrlFormEncoding
import XCTest
final class UrlFormDecoderTests: XCTestCase {
let decoder = UrlFormDecoder()
override func setUp() {
super.setUp()
// record = true
}
func testOptionality() throws {
struct Foo: Decodable {
let x: Int?
}
XCTAssertNil(try decoder.decode(Foo.self, from: Data()).x)
XCTAssertNil(try decoder.decode(Foo.self, from: Data("foo=bar".utf8)).x)
XCTAssertEqual(1, try decoder.decode(Foo.self, from: Data("x=1".utf8)).x)
}
func testPlusses() throws {
struct Foo: Decodable {
let x: String
}
XCTAssertEqual("hello world", try decoder.decode(Foo.self, from: Data("x=hello+world".utf8)).x)
}
func testDefaultStrategyAccumulatePairs() throws {
struct Foo: Decodable {
let x: Int
let ys: [Int]
}
assertSnapshot(matching: try decoder.decode(Foo.self, from: Data("x=1&ys=1".utf8)), as: .dump)
assertSnapshot(matching: try decoder.decode(Foo.self, from: Data("x=1&ys=1&ys=2".utf8)), as: .dump)
// FIXME: Make work!
// XCTAssertNil(try decoder.decode(Foo?.self, from: Data("ys=1&ys=2".utf8)))
// XCTAssertNil(try decoder.decode(Foo?.self, from: Data()))
}
func testBrackets() throws {
struct Bar: Decodable {
let baz: Int
}
struct Foo: Decodable {
let helloWorld: String
let port: Int
let bar: Bar?
let bars: [Bar]
let barses: [[Bar]]
private enum CodingKeys: String, CodingKey {
case helloWorld = "hello world"
case port
case bar
case bars
case barses
}
}
let data = Data(
"""
hello%20world=a%20greeting%20for%20you&\
port=8080&\
bars[][baz]=1&\
bars[][baz]=2&\
bar=&\
barses[][][baz]=3&\
barses[][][baz]=4&\
k&&
""".utf8
)
decoder.parsingStrategy = .brackets
assertSnapshot(matching: try decoder.decode(Foo.self, from: data), as: .dump)
}
func testBracketsWithIndices() throws {
struct Bar: Decodable {
let baz: Int
}
struct Foo: Decodable {
let helloWorld: String
let port: Int
let bar: Bar?
let bars: [Bar]
private enum CodingKeys: String, CodingKey {
case helloWorld = "hello world"
case port
case bar
case bars
}
}
let data = Data(
"""
hello%20world=a%20greeting%20for%20you&port=8080&bars[1][baz]=2&bars[0][baz]=1&bar=&k&
""".utf8
)
decoder.parsingStrategy = .bracketsWithIndices
assertSnapshot(matching: try decoder.decode(Foo.self, from: data), as: .dump)
}
func testDataDecodingWithBase64() throws {
struct MyData: Decodable {
let data: Data
}
decoder.dataDecodingStrategy = .base64
XCTAssertEqual(
"OOPs",
String(decoding: try decoder.decode(MyData.self, from: Data("data=T09Qcw==".utf8)).data, as: UTF8.self)
)
}
func testDateDecodingWithSecondsSince1970() throws {
struct MyDate: Decodable {
let date: Date
}
decoder.dateDecodingStrategy = .secondsSince1970
let interval = Int(Date(timeIntervalSinceReferenceDate: 0).timeIntervalSince1970)
assertSnapshot(matching: try decoder.decode(MyDate.self, from: Data("date=\(interval)".utf8)), as: .dump)
}
func testDateDecodingWithMillisecondsSince1970() throws {
struct MyDate: Decodable {
let date: Date
}
decoder.dateDecodingStrategy = .millisecondsSince1970
let interval = "\(Int(Date(timeIntervalSinceReferenceDate: 0).timeIntervalSince1970))000"
assertSnapshot(matching: try decoder.decode(MyDate.self, from: Data("date=\(interval)".utf8)), as: .dump)
}
func testDateDecodingWithIso8601() throws {
struct MyDate: Decodable {
let date: Date
}
decoder.dateDecodingStrategy = .iso8601
assertSnapshot(
matching: try decoder.decode(MyDate.self, from: Data("date=2001-01-01T00:00:00.000-00:00".utf8)),
as: .dump
)
assertSnapshot(
matching: try decoder.decode(MyDate.self, from: Data("date=2001-01-01T00:00:00-00:00".utf8)),
as: .dump
)
}
func testBools() {
struct MyBool: Decodable {
let bool: Bool
}
XCTAssertTrue(try decoder.decode(MyBool.self, from: Data("bool=true".utf8)).bool)
XCTAssertTrue(try decoder.decode(MyBool.self, from: Data("bool=TRUE".utf8)).bool)
XCTAssertTrue(try decoder.decode(MyBool.self, from: Data("bool=1".utf8)).bool)
XCTAssertFalse(try decoder.decode(MyBool.self, from: Data("bool=false".utf8)).bool)
XCTAssertFalse(try decoder.decode(MyBool.self, from: Data("bool=FALSE".utf8)).bool)
XCTAssertFalse(try decoder.decode(MyBool.self, from: Data("bool=0".utf8)).bool)
}
// func testDateDecodingWithFormatted() throws {
// struct MyDate: Decodable {
// let date: Date
// }
//
// let formatter = DateFormatter()
// formatter.locale = Locale(identifier: "en_US")
// formatter.setLocalizedDateFormatFromTemplate("MMMMdyyyy")
//
// decoder.dateDecodingStrategy = .formatted(formatter)
// assertSnapshot(matching: try decoder.decode(MyDate.self, from: Data("date=December%2031,%202017".utf8)))
// }
}
| mit | c3d4a5615aa9ecfb66d54ae175e61306 | 26.452632 | 110 | 0.645514 | 3.696669 | false | true | false | false |
loudnate/Loop | WatchApp Extension/Extensions/ButtonGroup.swift | 1 | 1691 | //
// ButtonGroup.swift
// WatchApp Extension
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import WatchKit
class ButtonGroup {
private let button: WKInterfaceButton
private let image: WKInterfaceImage
private let background: WKInterfaceGroup
private let onBackgroundColor: UIColor
private let offBackgroundColor: UIColor
enum State {
case on
case off
case disabled
}
var state: State = .off {
didSet {
let imageTintColor: UIColor
let backgroundColor: UIColor
switch state {
case .on:
imageTintColor = offBackgroundColor
backgroundColor = onBackgroundColor
case .off:
imageTintColor = onBackgroundColor
backgroundColor = offBackgroundColor
case .disabled:
imageTintColor = .disabledButtonColor
backgroundColor = .darkDisabledButtonColor
}
button.setEnabled(state != .disabled)
image.setTintColor(imageTintColor)
background.setBackgroundColor(backgroundColor)
}
}
init(button: WKInterfaceButton, image: WKInterfaceImage, background: WKInterfaceGroup, onBackgroundColor: UIColor, offBackgroundColor: UIColor) {
self.button = button
self.image = image
self.background = background
self.onBackgroundColor = onBackgroundColor
self.offBackgroundColor = offBackgroundColor
}
func turnOff() {
switch state {
case .on:
state = .off
case .off, .disabled:
break
}
}
}
| apache-2.0 | 005c13ade24a56c8936a94cf737f94a4 | 26.258065 | 149 | 0.609467 | 5.767918 | false | false | false | false |
vinitam/iOS8Samples | HelloWorld/HelloWorld/XMLParsingViewController.swift | 1 | 3295 | //
// XMLParsingViewController.swift
// iOS8SampleCode
//
// Copyright (c) 2014 Vinita. All rights reserved.
//
import UIKit
class XMLParsingViewController: UIViewController,NSXMLParserDelegate {
var parser : NSXMLParser!
var elementName: NSString!
var feedsArray :NSMutableArray = []
@IBOutlet var tableView : UITableView
var titleName = NSMutableString()
var link = NSMutableString()
var element = NSMutableString()
override func viewDidLoad() {
var url : NSURL = NSURL.URLWithString("http://images.apple.com/main/rss/hotnews/hotnews.rss")
self.parser = NSXMLParser(contentsOfURL: url)
self.parser.delegate = self
self.parser.parse()
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "tableCell")
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: NSDictionary!)
{
self.elementName = elementName;
if self.elementName == "item"
{
self.titleName = NSMutableString()
self.link = NSMutableString()
self.element = NSMutableString()
}
}
func parser(parser: NSXMLParser!, foundCharacters string: String!)
{
if self.elementName == "title"
{
titleName.appendString(string)
}
else if self.elementName == "link"
{
link.appendString(string)
}
}
func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!)
{
if elementName == "item"
{
var itemDictionary = Dictionary<String, String >()
itemDictionary["title"] = self.titleName
itemDictionary["link"] = self.link
self.feedsArray.addObject(itemDictionary)
}
}
func parserDidEndDocument(parser: NSXMLParser!)
{
self.tableView.reloadData()
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
return self.feedsArray.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
var cell = tableView.dequeueReusableCellWithIdentifier("tableCell")
as UITableViewCell
var dictionary : NSMutableDictionary = self.feedsArray[indexPath.row] as NSMutableDictionary
cell.textLabel.text = dictionary.objectForKey("title") as NSString
return cell
}
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | 01df0e93211db3161fdce4b15c3bc717 | 28.684685 | 169 | 0.643703 | 5.349026 | false | false | false | false |
when50/TabBarView | TabBarPageView/PageView.swift | 1 | 2591 | //
// PageView.swift
// TabBarPageView
//
// Created by chc on 2017/6/9.
// Copyright © 2017年 chc. All rights reserved.
//
import UIKit
public class PageView: UIView, UIScrollViewDelegate {
var tabBar: TabBarView!
lazy var scrollView: UIScrollView = {
let view = UIScrollView(frame: .zero)
view.alwaysBounceVertical = false
view.alwaysBounceHorizontal = true
view.isPagingEnabled = true
view.delegate = self
return view
}()
var tabItems: [(String, UIView)]!
var currentPageNumber = 0
public init(frame: CGRect, tabItems: [(String, UIView)]) {
super.init(frame: frame)
self.tabItems = tabItems
var tabBarItems: [(String, ((Int) -> Void))] = []
for item in tabItems {
scrollView.addSubview(item.1)
let tabBarItem = (item.0, { [weak self] (index: Int) -> Void in
guard let frame = self?.scrollView.frame else { return }
self?.currentPageNumber = index
self?.scrollView.scrollRectToVisible(frame.offsetBy(dx: CGFloat(index) * frame.size.width, dy: 0), animated: false)
})
tabBarItems.append(tabBarItem)
}
tabBar = TabBarView(items: tabBarItems)
addSubview(tabBar)
addSubview(scrollView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func layoutSubviews() {
super.layoutSubviews()
let tabBarHeight: CGFloat = 55
var frame = tabBar.frame
frame.size.width = bounds.size.width
frame.size.height = tabBarHeight
tabBar.frame = frame
scrollView.frame = bounds.offsetBy(dx: 0, dy: tabBarHeight)
scrollView.contentSize = CGSize(width: CGFloat(tabItems.count) * bounds.size.width, height: scrollView.frame.size.height)
let views = scrollView.subviews
for i in 0..<views.count {
let frame = scrollView.bounds.offsetBy(dx: CGFloat(i) * scrollView.bounds.size.width, dy: 0)
views[i].frame = frame
}
}
// MARK: UIScrollViewDelegate
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageWidth = scrollView.frame.size.width
let pageNumber = Int(floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1)
if pageNumber != currentPageNumber {
currentPageNumber = pageNumber
tabBar.setCurrentTabIndex(newIndex: pageNumber)
}
}
}
| mit | d3d615b1492724516de3567b4f413ff9 | 33.972973 | 131 | 0.617465 | 4.629696 | false | false | false | false |
aronse/Hero | Sources/Transition/HeroTransition.swift | 1 | 7199 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[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 UIKit
/**
### The singleton class/object for controlling interactive transitions.
```swift
Hero.shared
```
#### Use the following methods for controlling the interactive transition:
```swift
func update(progress:Double)
func end()
func cancel()
func apply(modifiers:[HeroModifier], to view:UIView)
```
*/
public class Hero: NSObject {
/// Shared singleton object for controlling the transition
public static var shared = HeroTransition()
}
open class HeroTransition: NSObject {
public var defaultAnimation: HeroDefaultAnimationType = .auto
public var containerColor: UIColor = .black
public var isUserInteractionEnabled = false
public var viewOrderingStrategy: HeroViewOrderingStrategy = .auto
public internal(set) var state: HeroTransitionState = .possible {
didSet {
if state != .notified, state != .starting {
beginCallback?(state == .animating)
beginCallback = nil
}
}
}
public var isTransitioning: Bool { return state != .possible }
public internal(set) var isPresenting: Bool = true
@available(*, deprecated, message: "Use isTransitioning instead")
public var transitioning: Bool {
return isTransitioning
}
@available(*, deprecated, message: "Use isPresenting instead")
public var presenting: Bool {
return isPresenting
}
/// container we created to hold all animating views, will be a subview of the
/// transitionContainer when transitioning
public internal(set) var container: UIView!
/// this is the container supplied by UIKit
internal var transitionContainer: UIView?
internal var completionCallback: ((Bool) -> Void)?
internal var beginCallback: ((Bool) -> Void)?
internal var processors: [HeroPreprocessor] = []
internal var animators: [HeroAnimator] = []
internal var plugins: [HeroPlugin] = []
internal var animatingFromViews: [UIView] = []
internal var animatingToViews: [UIView] = []
internal static var enabledPlugins: [HeroPlugin.Type] = []
/// destination view controller
public internal(set) var toViewController: UIViewController?
/// source view controller
public internal(set) var fromViewController: UIViewController?
/// context object holding transition informations
public internal(set) var context: HeroContext!
/// whether or not we are handling transition interactively
public var interactive: Bool {
return !progressRunner.isRunning
}
internal var progressUpdateObservers: [HeroProgressUpdateObserver]?
/// max duration needed by the animators
public internal(set) var totalDuration: TimeInterval = 0.0
/// progress of the current transition. 0 if no transition is happening
public internal(set) var progress: Double = 0 {
didSet {
if state == .animating {
if let progressUpdateObservers = progressUpdateObservers {
for observer in progressUpdateObservers {
observer.heroDidUpdateProgress(progress: progress)
}
}
let timePassed = progress * totalDuration
if interactive {
for animator in animators {
animator.seekTo(timePassed: timePassed)
}
} else {
for plugin in plugins where plugin.requirePerFrameCallback {
plugin.seekTo(timePassed: timePassed)
}
}
transitionContext?.updateInteractiveTransition(CGFloat(progress))
}
}
}
lazy var progressRunner: HeroProgressRunner = {
let runner = HeroProgressRunner()
runner.delegate = self
return runner
}()
/// a UIViewControllerContextTransitioning object provided by UIKit,
/// might be nil when transitioning. This happens when calling heroReplaceViewController
internal weak var transitionContext: UIViewControllerContextTransitioning?
internal var fullScreenSnapshot: UIView?
// By default, Hero will always appear to be interactive to UIKit. This forces it to appear non-interactive.
// Used when doing a hero_replaceViewController within a UINavigationController, to fix a bug with
// UINavigationController.setViewControllers not able to handle interactive transition
internal var forceNotInteractive = false
internal var forceFinishing: Bool?
internal var inNavigationController = false
internal var inTabBarController = false
internal var inContainerController: Bool {
return inNavigationController || inTabBarController
}
internal var toOverFullScreen: Bool {
return !inContainerController && (toViewController?.modalPresentationStyle == .overFullScreen || toViewController?.modalPresentationStyle == .overCurrentContext)
}
internal var fromOverFullScreen: Bool {
return !inContainerController && (fromViewController?.modalPresentationStyle == .overFullScreen || fromViewController?.modalPresentationStyle == .overCurrentContext)
}
internal var toView: UIView? { return toViewController?.view }
internal var fromView: UIView? { return fromViewController?.view }
public override init() { super.init() }
func complete(after: TimeInterval, finishing: Bool) {
guard [HeroTransitionState.animating, .starting, .notified].contains(state) else { return }
if after <= 1.0 / 120 {
complete(finished: finishing)
return
}
let totalTime: TimeInterval
if finishing {
totalTime = after / max((1 - progress), 0.01)
} else {
totalTime = after / max(progress, 0.01)
}
progressRunner.start(timePassed: progress * totalTime, totalTime: totalTime, reverse: !finishing)
}
// MARK: Observe Progress
/**
Receive callbacks on each animation frame.
Observers will be cleaned when transition completes
- Parameters:
- observer: the observer
*/
func observeForProgressUpdate(observer: HeroProgressUpdateObserver) {
if progressUpdateObservers == nil {
progressUpdateObservers = []
}
progressUpdateObservers!.append(observer)
}
}
extension HeroTransition: HeroProgressRunnerDelegate {
func updateProgress(progress: Double) {
self.progress = progress
}
}
| mit | 9ede1b15a9334bfcf6495d5932e9d7d2 | 34.117073 | 169 | 0.728712 | 5.034266 | false | false | false | false |
SimonFairbairn/SwiftyMarkdown | Playground/SwiftyMarkdown.playground/Pages/Groups.xcplaygroundpage/Contents.swift | 1 | 7475 | //: [Previous](@previous)
import Foundation
extension String {
func repeating( _ max : Int ) -> String {
var output = self
for _ in 1..<max {
output += self
}
return output
}
}
enum TagState {
case none
case open
case intermediate
case closed
}
struct TagString {
var state : TagState = .none
var preOpenString = ""
var openTagString = ""
var intermediateString = ""
var intermediateTagString = ""
var metadataString = ""
var closedTagString = ""
var postClosedString = ""
let rule : Rule
init( with rule : Rule ) {
self.rule = rule
}
mutating func append( _ string : String? ) {
guard let existentString = string else {
return
}
switch self.state {
case .none:
self.preOpenString += existentString
case .open:
self.intermediateString += existentString
case .intermediate:
self.metadataString += existentString
case .closed:
self.postClosedString += existentString
}
}
mutating func append( contentsOf tokenGroup: [TokenGroup] ) {
print(tokenGroup)
for token in tokenGroup {
switch token.state {
case .none:
self.append(token.string)
case .open:
if self.state != .none {
self.preOpenString += token.string
} else {
self.openTagString += token.string
}
case .intermediate:
if self.state != .open {
self.intermediateString += token.string
} else {
self.intermediateTagString += token.string
}
case .closed:
if self.rule.intermediateTag != nil && self.state != .intermediate {
self.metadataString += token.string
} else {
self.closedTagString += token.string
}
}
self.state = token.state
}
}
mutating func tokens() -> [Token] {
print(self)
var tokens : [Token] = []
if !self.preOpenString.isEmpty {
tokens.append(Token(type: .string, inputString: self.preOpenString))
}
if !self.openTagString.isEmpty {
tokens.append(Token(type: .openTag, inputString: self.openTagString))
}
if !self.intermediateString.isEmpty {
var token = Token(type: .string, inputString: self.intermediateString)
token.metadataString = self.metadataString
tokens.append(token)
}
if !self.intermediateTagString.isEmpty {
tokens.append(Token(type: .intermediateTag, inputString: self.intermediateTagString))
}
if !self.metadataString.isEmpty {
tokens.append(Token(type: .metadata, inputString: self.metadataString))
}
if !self.closedTagString.isEmpty {
tokens.append(Token(type: .closeTag, inputString: self.closedTagString))
}
self.preOpenString = ""
self.openTagString = ""
self.intermediateString = ""
self.intermediateTagString = ""
self.metadataString = ""
self.closedTagString = ""
self.postClosedString = ""
self.state = .none
return tokens
}
}
struct TokenGroup {
enum TokenGroupType {
case string
case tag
case escape
}
let string : String
let isEscaped : Bool
let type : TokenGroupType
var state : TagState = .none
}
func getTokenGroups( for string : inout String, with rule : Rule, shouldEmpty : Bool = false ) -> [TokenGroup] {
if string.isEmpty {
return []
}
let maxCount = rule.openTag.count * rule.maxTags
var groups : [TokenGroup] = []
let maxTag = rule.openTag.repeating(rule.maxTags)
if maxTag.contains(string) {
if string.count == maxCount || shouldEmpty {
var token = TokenGroup(string: string, isEscaped: false, type: .tag)
token.state = .open
groups.append(token)
string.removeAll()
}
} else if string == rule.intermediateTag {
var token = TokenGroup(string: string, isEscaped: false, type: .tag)
token.state = .intermediate
groups.append(token)
string.removeAll()
} else if string == rule.closingTag {
var token = TokenGroup(string: string, isEscaped: false, type: .tag)
token.state = .closed
groups.append(token)
string.removeAll()
}
if shouldEmpty && !string.isEmpty {
let token = TokenGroup(string: string, isEscaped: false, type: .tag)
groups.append(token)
string.removeAll()
}
return groups
}
func scan( _ string : String, with rule : Rule) -> [Token] {
let scanner = Scanner(string: string)
scanner.charactersToBeSkipped = nil
var tokens : [Token] = []
var set = CharacterSet(charactersIn: "\(rule.openTag)\(rule.intermediateTag ?? "")\(rule.closingTag ?? "")")
if let existentEscape = rule.escapeCharacter {
set.insert(charactersIn: String(existentEscape))
}
var openTag = rule.openTag.repeating(rule.maxTags)
var tagString = TagString(with: rule)
var openTagFound : TagState = .none
var regularCharacters = ""
var tagGroupCount = 0
while !scanner.isAtEnd {
tagGroupCount += 1
if #available(iOS 13.0, OSX 10.15, watchOS 6.0, tvOS 13.0, *) {
if let start = scanner.scanUpToCharacters(from: set) {
tagString.append(start)
}
} else {
var string : NSString?
scanner.scanUpToCharacters(from: set, into: &string)
if let existentString = string as String? {
tagString.append(existentString)
}
}
// The end of the string
let maybeFoundChars = scanner.scanCharacters(from: set )
guard let foundTag = maybeFoundChars else {
continue
}
if foundTag == rule.openTag && foundTag.count < rule.minTags {
tagString.append(foundTag)
continue
}
//:--
print(foundTag)
var tokenGroups : [TokenGroup] = []
var escapeCharacter : Character? = nil
var cumulatedString = ""
for char in foundTag {
if let existentEscapeCharacter = escapeCharacter {
// If any of the tags feature the current character
let escape = String(existentEscapeCharacter)
let nextTagCharacter = String(char)
if rule.openTag.contains(nextTagCharacter) || rule.intermediateTag?.contains(nextTagCharacter) ?? false || rule.closingTag?.contains(nextTagCharacter) ?? false {
tokenGroups.append(TokenGroup(string: nextTagCharacter, isEscaped: true, type: .tag))
escapeCharacter = nil
} else if nextTagCharacter == escape {
// Doesn't apply to this rule
tokenGroups.append(TokenGroup(string: nextTagCharacter, isEscaped: false, type: .escape))
}
continue
}
if let existentEscape = rule.escapeCharacter {
if char == existentEscape {
tokenGroups.append(contentsOf: getTokenGroups(for: &cumulatedString, with: rule, shouldEmpty: true))
escapeCharacter = char
continue
}
}
cumulatedString.append(char)
tokenGroups.append(contentsOf: getTokenGroups(for: &cumulatedString, with: rule))
}
if let remainingEscape = escapeCharacter {
tokenGroups.append(TokenGroup(string: String(remainingEscape), isEscaped: false, type: .escape))
}
tokenGroups.append(contentsOf: getTokenGroups(for: &cumulatedString, with: rule, shouldEmpty: true))
tagString.append(contentsOf: tokenGroups)
if tagString.state == .closed {
tokens.append(contentsOf: tagString.tokens())
}
}
tokens.append(contentsOf: tagString.tokens())
return tokens
}
//: [Next](@next)
var string = "[]([[\\[Some Link]\\]](\\(\\(\\url) [Regular link](url)"
//string = "Text before [Regular link](url) Text after"
var output = "[]([[Some Link]] Regular link"
var tokens = scan(string, with: LinkRule())
print( tokens.filter( { $0.type == .string }).map({ $0.outputString }).joined())
//print( tokens )
//string = "**\\*\\Bold\\*\\***"
//output = "*\\Bold**"
//tokens = scan(string, with: AsteriskRule())
//print( tokens )
| mit | fcbdb31faeb914d52762f9105722838a | 25.22807 | 166 | 0.674649 | 3.432048 | false | false | false | false |
cjbeauchamp/tvOSDashboard | Charts/Classes/Charts/PieChartView.swift | 1 | 16102 | //
// PieChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
/// View that represents a pie chart. Draws cake like slices.
public class PieChartView: PieRadarChartViewBase
{
/// rect object that represents the bounds of the piechart, needed for drawing the circle
private var _circleBox = CGRect()
private var _drawXLabelsEnabled = true
/// array that holds the width of each pie-slice in degrees
private var _drawAngles = [CGFloat]()
/// array that holds the absolute angle in degrees of each slice
private var _absoluteAngles = [CGFloat]()
/// if true, the hole inside the chart will be drawn
private var _drawHoleEnabled = true
private var _holeColor: NSUIColor? = NSUIColor.whiteColor()
/// if true, the hole will see-through to the inner tips of the slices
private var _drawSlicesUnderHoleEnabled = false
/// if true, the values inside the piechart are drawn as percent values
private var _usePercentValuesEnabled = false
/// variable for the text that is drawn in the center of the pie-chart
private var _centerAttributedText: NSAttributedString?
/// indicates the size of the hole in the center of the piechart
///
/// **default**: `0.5`
private var _holeRadiusPercent = CGFloat(0.5)
private var _transparentCircleColor: NSUIColor? = NSUIColor(white: 1.0, alpha: 105.0/255.0)
/// the radius of the transparent circle next to the chart-hole in the center
private var _transparentCircleRadiusPercent = CGFloat(0.55)
/// if enabled, centertext is drawn
private var _drawCenterTextEnabled = true
private var _centerTextRadiusPercent: CGFloat = 1.0
/// maximum angle for this pie
private var _maxAngle: CGFloat = 360.0
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
internal override func initialize()
{
super.initialize()
renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect)
if _data === nil
{
return
}
let optionalContext = NSUIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
renderer!.drawData(context: context)
if (valuesToHighlight())
{
renderer!.drawHighlighted(context: context, indices: _indicesToHighlight)
}
renderer!.drawExtras(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
internal override func calculateOffsets()
{
super.calculateOffsets()
// prevent nullpointer when no data set
if _data === nil
{
return
}
let radius = diameter / 2.0
let c = self.centerOffsets
let shift = (data as? PieChartData)?.dataSet?.selectionShift ?? 0.0
// create the circle box that will contain the pie-chart (the bounds of the pie-chart)
_circleBox.origin.x = (c.x - radius) + shift
_circleBox.origin.y = (c.y - radius) + shift
_circleBox.size.width = diameter - shift * 2.0
_circleBox.size.height = diameter - shift * 2.0
}
internal override func calcMinMax()
{
super.calcMinMax()
calcAngles()
}
public override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
let center = self.centerCircleBox
var r = self.radius
var off = r / 10.0 * 3.6
if self.isDrawHoleEnabled
{
off = (r - (r * self.holeRadiusPercent)) / 2.0
}
r -= off // offset to keep things inside the chart
let rotationAngle = self.rotationAngle
let i = e.xIndex
// offset needed to center the drawn text in the slice
let offset = drawAngles[i] / 2.0
// calculate the text position
let x: CGFloat = (r * cos(((rotationAngle + absoluteAngles[i] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.x)
let y: CGFloat = (r * sin(((rotationAngle + absoluteAngles[i] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.y)
return CGPoint(x: x, y: y)
}
/// calculates the needed angles for the chart slices
private func calcAngles()
{
_drawAngles = [CGFloat]()
_absoluteAngles = [CGFloat]()
guard let data = _data else { return }
_drawAngles.reserveCapacity(data.yValCount)
_absoluteAngles.reserveCapacity(data.yValCount)
let yValueSum = (_data as! PieChartData).yValueSum
var dataSets = data.dataSets
var cnt = 0
for (var i = 0; i < data.dataSetCount; i++)
{
let set = dataSets[i]
let entryCount = set.entryCount
for (var j = 0; j < entryCount; j++)
{
guard let e = set.entryForIndex(j) else { continue }
_drawAngles.append(calcAngle(abs(e.value), yValueSum: yValueSum))
if (cnt == 0)
{
_absoluteAngles.append(_drawAngles[cnt])
}
else
{
_absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt])
}
cnt++
}
}
}
/// checks if the given index in the given DataSet is set for highlighting or not
public func needsHighlight(xIndex xIndex: Int, dataSetIndex: Int) -> Bool
{
// no highlight
if (!valuesToHighlight() || dataSetIndex < 0)
{
return false
}
for (var i = 0; i < _indicesToHighlight.count; i++)
{
// check if the xvalue for the given dataset needs highlight
if (_indicesToHighlight[i].xIndex == xIndex
&& _indicesToHighlight[i].dataSetIndex == dataSetIndex)
{
return true
}
}
return false
}
/// calculates the needed angle for a given value
private func calcAngle(value: Double) -> CGFloat
{
return calcAngle(value, yValueSum: (_data as! PieChartData).yValueSum)
}
/// calculates the needed angle for a given value
private func calcAngle(value: Double, yValueSum: Double) -> CGFloat
{
return CGFloat(value) / CGFloat(yValueSum) * _maxAngle
}
public override func indexForAngle(angle: CGFloat) -> Int
{
// take the current angle of the chart into consideration
let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle)
for (var i = 0; i < _absoluteAngles.count; i++)
{
if (_absoluteAngles[i] > a)
{
return i
}
}
return -1; // return -1 if no index found
}
/// - returns: the index of the DataSet this x-index belongs to.
public func dataSetIndexForIndex(xIndex: Int) -> Int
{
var dataSets = _data?.dataSets ?? []
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].entryForXIndex(xIndex) !== nil)
{
return i
}
}
return -1
}
/// - returns: an integer array of all the different angles the chart slices
/// have the angles in the returned array determine how much space (of 360°)
/// each slice takes
public var drawAngles: [CGFloat]
{
return _drawAngles
}
/// - returns: the absolute angles of the different chart slices (where the
/// slices end)
public var absoluteAngles: [CGFloat]
{
return _absoluteAngles
}
/// The color for the hole that is drawn in the center of the PieChart (if enabled).
///
/// *Note: Use holeTransparent with holeColor = nil to make the hole transparent.*
public var holeColor: NSUIColor?
{
get
{
return _holeColor
}
set
{
_holeColor = newValue
setNeedsDisplay()
}
}
/// if true, the hole will see-through to the inner tips of the slices
///
/// **default**: `false`
public var drawSlicesUnderHoleEnabled: Bool
{
get
{
return _drawSlicesUnderHoleEnabled
}
set
{
_drawSlicesUnderHoleEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: `true` if the inner tips of the slices are visible behind the hole, `false` if not.
public var isDrawSlicesUnderHoleEnabled: Bool
{
return drawSlicesUnderHoleEnabled
}
/// true if the hole in the center of the pie-chart is set to be visible, false if not
public var drawHoleEnabled: Bool
{
get
{
return _drawHoleEnabled
}
set
{
_drawHoleEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if the hole in the center of the pie-chart is set to be visible, false if not
public var isDrawHoleEnabled: Bool
{
get
{
return drawHoleEnabled
}
}
/// the text that is displayed in the center of the pie-chart
public var centerText: String?
{
get
{
return self.centerAttributedText?.string
}
set
{
var attrString: NSMutableAttributedString?
if newValue == nil
{
attrString = nil
}
else
{
let paragraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail
paragraphStyle.alignment = .Center
attrString = NSMutableAttributedString(string: newValue!)
attrString?.setAttributes([
NSForegroundColorAttributeName: NSUIColor.blackColor(),
NSFontAttributeName: NSUIFont.systemFontOfSize(12.0),
NSParagraphStyleAttributeName: paragraphStyle
], range: NSMakeRange(0, attrString!.length))
}
self.centerAttributedText = attrString
}
}
/// the text that is displayed in the center of the pie-chart
public var centerAttributedText: NSAttributedString?
{
get
{
return _centerAttributedText
}
set
{
_centerAttributedText = newValue
setNeedsDisplay()
}
}
/// true if drawing the center text is enabled
public var drawCenterTextEnabled: Bool
{
get
{
return _drawCenterTextEnabled
}
set
{
_drawCenterTextEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing the center text is enabled
public var isDrawCenterTextEnabled: Bool
{
get
{
return drawCenterTextEnabled
}
}
internal override var requiredLegendOffset: CGFloat
{
return _legend.font.pointSize * 2.0
}
internal override var requiredBaseOffset: CGFloat
{
return 0.0
}
public override var radius: CGFloat
{
return _circleBox.width / 2.0
}
/// - returns: the circlebox, the boundingbox of the pie-chart slices
public var circleBox: CGRect
{
return _circleBox
}
/// - returns: the center of the circlebox
public var centerCircleBox: CGPoint
{
return CGPoint(x: _circleBox.midX, y: _circleBox.midY)
}
/// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.5 (50%) (half the pie)
public var holeRadiusPercent: CGFloat
{
get
{
return _holeRadiusPercent
}
set
{
_holeRadiusPercent = newValue
setNeedsDisplay()
}
}
/// The color that the transparent-circle should have.
///
/// **default**: `nil`
public var transparentCircleColor: NSUIColor?
{
get
{
return _transparentCircleColor
}
set
{
_transparentCircleColor = newValue
setNeedsDisplay()
}
}
/// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.55 (55%) -> means 5% larger than the center-hole by default
public var transparentCircleRadiusPercent: CGFloat
{
get
{
return _transparentCircleRadiusPercent
}
set
{
_transparentCircleRadiusPercent = newValue
setNeedsDisplay()
}
}
/// set this to true to draw the x-value text into the pie slices
public var drawSliceTextEnabled: Bool
{
get
{
return _drawXLabelsEnabled
}
set
{
_drawXLabelsEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing x-values is enabled, false if not
public var isDrawSliceTextEnabled: Bool
{
get
{
return drawSliceTextEnabled
}
}
/// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent.
public var usePercentValuesEnabled: Bool
{
get
{
return _usePercentValuesEnabled
}
set
{
_usePercentValuesEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing x-values is enabled, false if not
public var isUsePercentValuesEnabled: Bool
{
get
{
return usePercentValuesEnabled
}
}
/// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole
public var centerTextRadiusPercent: CGFloat
{
get
{
return _centerTextRadiusPercent
}
set
{
_centerTextRadiusPercent = newValue
setNeedsDisplay()
}
}
/// The max angle that is used for calculating the pie-circle.
/// 360 means it's a full pie-chart, 180 results in a half-pie-chart.
/// **default**: 360.0
public var maxAngle: CGFloat
{
get
{
return _maxAngle
}
set
{
_maxAngle = newValue
if _maxAngle > 360.0
{
_maxAngle = 360.0
}
if _maxAngle < 90.0
{
_maxAngle = 90.0
}
}
}
} | apache-2.0 | 72d80bde2b19ca5e6b47102dfa94c7fc | 26.666667 | 189 | 0.557108 | 5.183838 | false | false | false | false |
jdbateman/OnTheMap | OnTheMap/WebSearchViewController.swift | 1 | 2425 | //
// WebSearchViewController.swift
// OnTheMap
//
// Created by john bateman on 9/1/15.
// Copyright (c) 2015 John Bateman. All rights reserved.
//
// This file implements a UIViewController containing a search bar and a UIWebView.
//
// Acknowledgement: http://stackoverflow.com/questions/26436050/how-do-i-connect-the-search-bar-with-the-uiwebview-in-xcode-6-using-swift
import UIKit
import WebKit
class WebSearchViewController: UIViewController, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var bottomView: UIView!
var initialURL:String? = nil
var webViewDelegate:UIWebViewDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
// setup search bar delegate to this view controller
self.searchBar.delegate = self
// adjust background and trancparency of bottom view
bottomView.backgroundColor = UIColor(white: 1, alpha: 0.85)
// if an initial URL has been set, initialize the search hbar text with it
if let url = initialURL {
searchBar.text = url
}
// if the web view delegate property was set then assign it to the child webView's delegate
if let delegate = webViewDelegate {
webView.delegate = delegate
}
// force the webView to display the searchBar text
searchBarSearchButtonClicked(searchBar)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onGoButtonTap(sender: AnyObject) {
searchBarSearchButtonClicked(searchBar)
}
@IBAction func onSaveButton(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: UISearchBarDelegate functions
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
// hide keyboard
searchBar.resignFirstResponder()
// Load web page in UIWebView from search bar text.
if let text = searchBar.text {
var url = NSURL(string: text)
var urlReq = NSURLRequest(URL:url!)
self.webView!.loadRequest(urlReq)
}
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | aca52e1464d2529d322abf586529d94f | 30.493506 | 138 | 0.65567 | 5.06263 | false | false | false | false |
jozsef-vesza/Swift-practice | Learning/Learning/Gallery view/GalleryViewModel.swift | 1 | 2958 | //
// GalleryViewModel.swift
// Learning
//
// Created by Jozsef Vesza on 04/06/14.
// Copyright (c) 2014 Jozsef Vesza. All rights reserved.
//
import UIKit
let imageNotification = "imagesDownloaded"
class GalleryViewModel: NSObject, NSURLSessionDataDelegate {
let mealImageUrl = "http://verdant-upgrade-554.appspot.com/soservices/mealimageservice"
weak var viewController: GalleryViewController?
var model: Meal[]
init(viewController: UIViewController, model:Meal[]) {
self.viewController = viewController as? GalleryViewController
self.model = model
super.init()
self.viewController!.viewModel = self
self.downloadImages()
}
func downloadImages() {
for (index, meal) in enumerate(self.model) {
let actualImageUrlString = mealImageUrl + "?identifier=\(meal.identifier)"
let request = NSURLRequest(URL: NSURL(string: actualImageUrlString))
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithRequest(request)
NSNotificationCenter.defaultCenter().postNotificationName(startAnimNotification, object: nil, userInfo: ["meal" : meal.name])
task.resume()
}
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
completionHandler(NSURLSessionResponseDisposition.Allow)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
let correctMeal = self.loadMealByIdentifier("\(dataTask.originalRequest)");
if correctMeal.meal {
var imageData = correctMeal.meal!.imageData.mutableCopy() as NSMutableData
imageData.appendData(data)
correctMeal.meal!.imageData = imageData as NSData
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
let correctMeal = self.loadMealByIdentifier("\(task.originalRequest)")
if correctMeal.index {
NSNotificationCenter.defaultCenter().postNotificationName(imageNotification, object: self, userInfo: ["index" : correctMeal.index!])
NSNotificationCenter.defaultCenter().postNotificationName(stopAnimNotification, object: nil, userInfo: ["meal" : correctMeal.meal!.name])
}
}
func loadMealByIdentifier(identifier: String) -> (meal: Meal?, index: Int?) {
for (index, meal) in enumerate(self.model) {
if identifier.bridgeToObjectiveC().containsString("\(meal.identifier)") {
return (meal, index)
}
}
return (nil, nil)
}
}
| mit | fb403e00f83b1456c4878147f44beb11 | 41.257143 | 188 | 0.678161 | 5.244681 | false | true | false | false |
leonereveel/Moya | Source/Moya+Defaults.swift | 1 | 1035 | import Alamofire
/// These functions are default mappings to `MoyaProvider`'s properties: endpoints, requests, manager, etc.
public extension MoyaProvider {
public final class func DefaultEndpointMapping(target: Target) -> Endpoint<Target> {
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
}
public final class func DefaultRequestMapping(endpoint: Endpoint<Target>, closure: RequestResultClosure) {
return closure(.Success(endpoint.urlRequest))
}
public final class func DefaultAlamofireManager() -> Manager {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
let manager = Manager(configuration: configuration)
manager.startRequestsImmediately = false
return manager
}
}
| mit | 08648518e17d4608f5668e7a4b921345 | 46.045455 | 154 | 0.753623 | 5.75 | false | true | false | false |
jwfriese/FrequentFlyer | FrequentFlyer/Authentication/TeamsViewController.swift | 1 | 8745 | import UIKit
import RxSwift
import RxCocoa
class TeamsViewController: UIViewController {
@IBOutlet weak var teamsTableView: UITableView?
var teamListService = TeamListService()
var authMethodsService = AuthMethodsService()
var unauthenticatedTokenService = UnauthenticatedTokenService()
var concourseURLString: String?
var selectedTeamName: String!
let disposeBag = DisposeBag()
class var storyboardIdentifier: String { get { return "Teams" } }
class var showLoginSegueId: String { get { return "ShowLogin" } }
class var setTeamPipelinesAsRootPageSegueId: String { get { return "SetTeamPipelinesAsRootPage" } }
class var showGitHubAuthSegueId: String { get { return "ShowGitHubAuth" } }
override func viewDidLoad() {
super.viewDidLoad()
guard let concourseURLString = concourseURLString else { return }
guard let teamsTableView = teamsTableView else { return }
title = "Teams"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
teamListService.getTeams(forConcourseWithURL: concourseURLString)
.catchError({ _ in
self.handleTeamListServiceError()
return Observable.empty()
})
.do(onNext: { teams in
if teams.count == 0 {
self.handleNoTeams()
}
})
.bind(to: teamsTableView.rx.items(
cellIdentifier: TeamTableViewCell.cellReuseIdentifier,
cellType: TeamTableViewCell.self)) { (row, teamName, cell) in
cell.teamLabel?.text = teamName
}
.disposed(by: self.disposeBag)
teamsTableView.rx.modelSelected(String.self)
.flatMap { teamName in
self.doAuthMethodsCall(forTeamName: teamName, concourseURLString: concourseURLString)
}
.subscribe(onNext: { authMethods in
self.routeToCorrectAuthenticationPage(authMethods, concourseURLString: concourseURLString)
},
onError: { _ in
let errorMessage = "Encountered error when trying to fetch Concourse auth methods. Please check your Concourse configuration and try again later."
self.presentErrorAlert(withTitle: "Error", message: errorMessage)
})
.disposed(by: self.disposeBag)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == TeamsViewController.showLoginSegueId {
guard let loginViewController = segue.destination as? LoginViewController else { return }
guard let concourseURLString = concourseURLString else { return }
guard let authMethods = sender as? [AuthMethod] else { return }
loginViewController.authMethods = authMethods
loginViewController.concourseURLString = concourseURLString
loginViewController.teamName = selectedTeamName
} else if segue.identifier == TeamsViewController.setTeamPipelinesAsRootPageSegueId {
guard let target = sender as? Target else { return }
guard let pipelinesViewController = segue.destination as? PipelinesViewController else {
return
}
pipelinesViewController.target = target
let pipelinesService = PipelinesService()
pipelinesService.httpClient = HTTPClient()
pipelinesService.pipelineDataDeserializer = PipelineDataDeserializer()
pipelinesViewController.pipelinesService = pipelinesService
} else if segue.identifier == TeamsViewController.showGitHubAuthSegueId {
guard let gitHubAuthMethod = sender as? AuthMethod else { return }
guard let gitHubAuthViewController = segue.destination as? GitHubAuthViewController else { return }
guard let concourseURLString = concourseURLString else { return }
gitHubAuthViewController.concourseURLString = concourseURLString
gitHubAuthViewController.teamName = selectedTeamName
gitHubAuthViewController.gitHubAuthURLString = gitHubAuthMethod.url
}
}
private func handleNoTeams() {
let alert = UIAlertController(
title: "No Teams",
message: "Could not find any teams for this Concourse instance.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
private func handleTeamListServiceError() {
let alert = UIAlertController(
title: "Error",
message: "Could not connect to a Concourse at the given URL.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
private func routeToCorrectAuthenticationPage(_ authMethods: [AuthMethod], concourseURLString: String) {
guard authMethods.count > 0 else {
self.attemptUnauthenticatedLogin(forTeamName: self.selectedTeamName, concourseURLString: concourseURLString)
return
}
if authMethods.count == 1 && authMethods.first!.type == .uaa {
let errorMessage = "The app does not support UAA yet."
self.presentErrorAlert(withTitle: "Unsupported Auth Method", message: errorMessage)
return
}
var segueIdentifier: String!
var sender: Any!
if self.isGitHubAuthTheOnlySupportedAuthType(inAuthMethodCollection: authMethods) {
segueIdentifier = TeamsViewController.showGitHubAuthSegueId
sender = authMethods.first!
} else {
segueIdentifier = TeamsViewController.showLoginSegueId
sender = authMethods
}
DispatchQueue.main.async {
self.performSegue(withIdentifier: segueIdentifier, sender: sender)
}
}
private func isGitHubAuthTheOnlySupportedAuthType(inAuthMethodCollection authMethods: [AuthMethod]) -> Bool {
let authMethodsWithoutUAA = authMethods.filter { authMethod in
return authMethod.type != .uaa
}
return authMethodsWithoutUAA.count == 1 && authMethodsWithoutUAA.first!.type == .gitHub
}
private func doAuthMethodsCall(forTeamName teamName: String, concourseURLString: String) -> Observable<[AuthMethod]> {
selectedTeamName = teamName
return authMethodsService.getMethods(forTeamName: teamName, concourseURL: concourseURLString)
}
private func presentErrorAlert(withTitle title: String, message: String) {
let alert = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
private func attemptUnauthenticatedLogin(forTeamName teamName: String, concourseURLString: String) {
unauthenticatedTokenService.getUnauthenticatedToken(forTeamName: teamName, concourseURL: concourseURLString)
.subscribe(
onNext: { token in
let newTarget = Target(name: "target",
api: concourseURLString,
teamName: teamName,
token: token)
DispatchQueue.main.async {
self.performSegue(withIdentifier: TeamsViewController.setTeamPipelinesAsRootPageSegueId, sender: newTarget)
}
},
onError: { error in
let alert = UIAlertController(title: "Error",
message: "Failed to fetch authentication methods and failed to fetch a token without credentials.",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
},
onCompleted: nil,
onDisposed: nil
)
.disposed(by: disposeBag)
}
}
| apache-2.0 | 56b6a590a68b3b7e724fd882ffcbe968 | 43.390863 | 170 | 0.624814 | 5.51735 | false | false | false | false |
bravelocation/yeltzland-ios | yeltzland/Data Managers/TeamImageManager.swift | 1 | 1611 | //
// TeamImageManager.swift
// yeltzland
//
// Created by John Pollard on 12/06/2018.
// Copyright © 2018 John Pollard. All rights reserved.
//
import Foundation
import UIKit
import SDWebImage
public class TeamImageManager {
fileprivate static let sharedInstance = TeamImageManager()
class var shared: TeamImageManager {
get {
return sharedInstance
}
}
public func teamImageUrl(teamName: String) -> URL? {
let imageUrl = String(format: "https://bravelocation.com/teamlogos/%@.png", self.makeTeamFileName(teamName))
return URL(string: imageUrl)
}
public func loadTeamImage(teamName: String, completion: @escaping (UIImage?) -> Void) {
SDWebImageManager.shared.loadImage(with: self.teamImageUrl(teamName: teamName),
options: .continueInBackground,
progress: nil) { image, _, _, _, _, _ in
completion(image)
}
}
func makeTeamFileName(_ teamName: String) -> String {
let teamFileName = teamName.replacingOccurrences(of: " ", with: "_").lowercased()
// Do we have a bracket in the name
let bracketPos = teamFileName.firstIndex(of: "(")
if bracketPos == nil {
return teamFileName
} else {
let beforeBracket = teamFileName.split(separator: "(", maxSplits: 1, omittingEmptySubsequences: true)[0]
return beforeBracket.trimmingCharacters(in: CharacterSet(charactersIn: " _"))
}
}
}
| mit | 96e3a3d40d4fe5fdd5ef5cdbc72fe123 | 34 | 116 | 0.59441 | 4.849398 | false | false | false | false |
piotr-tobolski/SwiftyInvocation | Example/Tests/SwiftyInvocationTests.swift | 1 | 3411 | import UIKit
import XCTest
import SwiftyInvocation
class SwiftyInvocationTests: XCTestCase {
func testGetImplementationWithoutParametersReturning3() {
let array: NSArray = ["1", "2", "3"]
let selector = #selector(getter: NSArray.count)
typealias Type = @convention(c) (AnyObject, Selector) -> UnsafeRawPointer
let implementation = try! swift_getImplementation(object: array, selector: selector, type: Type.self)
let returnValue = implementation(array, selector)
let returnValueAsInt = unsafeBitCast(returnValue, to: Int.self)
XCTAssertEqual(returnValueAsInt, 3)
}
func testGetImplementationWithoutParametersReturning0() {
let array: NSArray = []
let selector = #selector(getter: NSArray.count)
typealias Type = @convention(c) (AnyObject, Selector) -> UnsafeRawPointer
let implementation = try! swift_getImplementation(object: array, selector: selector, type: Type.self)
let returnValue = implementation(array, selector)
let returnValueAsInt = unsafeBitCast(returnValue, to: Int.self)
XCTAssertEqual(returnValueAsInt, 0)
}
func testGetImplementationWithIntParameterReturningObject() {
let array: NSArray = ["1", "2", "3"]
let selector = #selector(NSArray.object(at:))
typealias Type = @convention(c) (AnyObject, Selector, Int) -> Unmanaged<NSString>
let implementation = try! swift_getImplementation(object: array, selector: selector, type: Type.self)
let returnValue = implementation(array, selector, 1)
let returnValueAsString = returnValue.takeUnretainedValue()
XCTAssertEqual(returnValueAsString, "2")
}
func testGetImplementationWithObjectParameterReturningVoid() {
let array: NSMutableArray = ["1", "2", "3"]
let selector = #selector(NSMutableArray.add(_:))
typealias Type = @convention(c) (AnyObject, Selector, AnyObject) -> Void
let implementation = try! swift_getImplementation(object: array, selector: selector, type: Type.self)
implementation(array, selector, "4" as AnyObject)
XCTAssertEqual(array, ["1", "2", "3", "4"])
}
func testGetImplementationWithObjectAndIntParameterReturningVoid() {
let array: NSMutableArray = ["1", "2", "3"]
let selector = #selector(NSMutableArray.insert(_:at:) as (NSMutableArray) -> (Any, Int) -> Void)
typealias Type = @convention(c) (AnyObject, Selector, AnyObject, Int) -> Void
let implementation = try! swift_getImplementation(object: array, selector: selector, type: Type.self)
implementation(array, selector, "0" as AnyObject, 0)
XCTAssertEqual(array, ["0", "1", "2", "3"])
}
func testSIInvocation() {
let array: NSArray = ["1", "2", "3"]
let selector = #selector(NSArray.object(at:))
let methodSignature = NSArray.si_instanceMethodSignature(for: selector)
let invocation = SIInvocation(methodSignature: methodSignature)
invocation.target = array
invocation.selector = selector
var argument = 1
invocation.setArgument(&argument, at: 2)
invocation.retainArguments()
invocation.invoke()
var returnValue: Unmanaged<NSString>?
invocation.getReturnValue(&returnValue)
XCTAssertEqual(returnValue?.takeUnretainedValue(), "2")
}
}
| mit | 6b80c978140ed16ea319fd89e5102a82 | 37.761364 | 109 | 0.673116 | 4.724377 | false | true | false | false |
suncry/MLHybrid | Source/Content/Model/Hybrid_naviButtonModel.swift | 1 | 761 | //
// Hybrid_naviButtonModel.swift
// Hybrid_Medlinker
//
// Created by caiyang on 16/5/13.
// Copyright © 2016年 caiyang. All rights reserved.
//
import UIKit
class Hybrid_naviButtonModel: NSObject {
var tagname: String = ""
var value: String = ""
var icon: String = ""
var callback: String = ""
class func convert(_ dic: [String: AnyObject]) -> Hybrid_naviButtonModel {
let naviButtonModel = Hybrid_naviButtonModel()
naviButtonModel.tagname = dic["tagname"] as? String ?? ""
naviButtonModel.value = dic["value"] as? String ?? ""
naviButtonModel.icon = dic["icon"] as? String ?? ""
naviButtonModel.callback = dic["callback"] as? String ?? ""
return naviButtonModel
}
}
| mit | ebb58193d04a54fb522b94600dd88409 | 27.074074 | 78 | 0.62533 | 3.752475 | false | false | false | false |
dreamsxin/swift | validation-test/compiler_crashers_2_fixed/0020-rdar21598514.swift | 3 | 5695 | // RUN: not %target-swift-frontend %s -parse
protocol Resettable : AnyObject {
func reset()
}
internal var _allResettables: [Resettable] = []
public class TypeIndexed<Value> : Resettable {
public init(_ value: Value) {
self.defaultValue = value
_allResettables.append(self)
}
public subscript(t: Any.Type) -> Value {
get {
return byType[ObjectIdentifier(t)] ?? defaultValue
}
set {
byType[ObjectIdentifier(t)] = newValue
}
}
public func reset() { byType = [:] }
internal var byType: [ObjectIdentifier:Value] = [:]
internal var defaultValue: Value
}
public protocol Wrapper {
typealias Base
init(_: Base)
var base: Base {get set}
}
public protocol LoggingType : Wrapper {
typealias Log : AnyObject
}
extension LoggingType {
public var log: Log.Type {
return Log.self
}
public var selfType: Any.Type {
return self.dynamicType
}
}
public class IteratorLog {
public static func dispatchTester<G : IteratorProtocol>(
g: G
) -> LoggingIterator<LoggingIterator<G>> {
return LoggingIterator(LoggingIterator(g))
}
public static var next = TypeIndexed(0)
}
public struct LoggingIterator<Base : IteratorProtocol>
: IteratorProtocol, LoggingType {
typealias Log = IteratorLog
public init(_ base: Base) {
self.base = base
}
public mutating func next() -> Base.Element? {
++Log.next[selfType]
return base.next()
}
public var base: Base
}
public class SequenceLog {
public class func dispatchTester<S: Sequence>(
s: S
) -> LoggingSequence<LoggingSequence<S>> {
return LoggingSequence(LoggingSequence(s))
}
public static var iterator = TypeIndexed(0)
public static var underestimatedCount = TypeIndexed(0)
public static var map = TypeIndexed(0)
public static var filter = TypeIndexed(0)
public static var _customContainsEquatableElement = TypeIndexed(0)
public static var _preprocessingPass = TypeIndexed(0)
public static var _copyToNativeArrayBuffer = TypeIndexed(0)
public static var _copyContents = TypeIndexed(0)
}
public protocol LoggingSequenceType : Sequence, LoggingType {
typealias Base : Sequence
}
extension LoggingSequenceType {
public init(_ base: Base) {
self.base = base
}
public func makeIterator() -> LoggingIterator<Base.Iterator> {
++SequenceLog.iterator[selfType]
return LoggingIterator(base.makeIterator())
}
public func underestimatedCount() -> Int {
++SequenceLog.underestimatedCount[selfType]
return base.underestimatedCount()
}
public func map<T>(
@noescape transform: (Base.Iterator.Element) -> T
) -> [T] {
++SequenceLog.map[selfType]
return base.map(transform)
}
public func filter(
@noescape includeElement: (Base.Iterator.Element) -> Bool
) -> [Base.Iterator.Element] {
++SequenceLog.filter[selfType]
return base.filter(includeElement)
}
public func _customContainsEquatableElement(
element: Base.Iterator.Element
) -> Bool? {
++SequenceLog._customContainsEquatableElement[selfType]
return base._customContainsEquatableElement(element)
}
/// If `self` is multi-pass (i.e., a `Collection`), invoke
/// `preprocess` on `self` and return its result. Otherwise, return
/// `nil`.
public func _preprocessingPass<R>(
@noescape _ preprocess: (Self) -> R
) -> R? {
++SequenceLog._preprocessingPass[selfType]
return base._preprocessingPass { _ in preprocess(self) }
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Iterator.Element> {
++SequenceLog._copyToNativeArrayBuffer[selfType]
return base._copyToNativeArrayBuffer()
}
/// Copy a Sequence into an array.
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Base.Iterator.Element>
) {
++SequenceLog._copyContents[selfType]
return base._copyContents(initializing: ptr)
}
}
public struct LoggingSequence<Base_: Sequence> : LoggingSequenceType {
typealias Log = SequenceLog
typealias Base = Base_
public init(_ base: Base_) {
self.base = base
}
public var base: Base_
}
public class CollectionLog : SequenceLog {
public class func dispatchTester<C: Collection>(
c: C
) -> LoggingCollection<LoggingCollection<C>> {
return LoggingCollection(LoggingCollection(c))
}
static var subscriptIndex = TypeIndexed(0)
static var subscriptRange = TypeIndexed(0)
static var isEmpty = TypeIndexed(0)
static var count = TypeIndexed(0)
static var _customIndexOfEquatableElement = TypeIndexed(0)
static var first = TypeIndexed(0)
}
public protocol LoggingCollectionType : Collection, LoggingSequenceType {
typealias Base : Collection
}
extension LoggingCollectionType {
subscript(position: Base.Index) -> Base.Iterator.Element {
++CollectionLog.subscriptIndex[selfType]
return base[position]
}
subscript(_prext_bounds: Range<Base.Index>) -> Base._prext_SubSequence {
++CollectionLog.subscriptRange[selfType]
return base[_prext_bounds]
}
var isEmpty: Bool {
++CollectionLog.isEmpty[selfType]
return base.isEmpty
}
var count: Base.Index.Distance {
++CollectionLog.count[selfType]
return base.count
}
func _customIndexOfEquatableElement(element: Iterator.Element) -> Base.Index?? {
++CollectionLog._customIndexOfEquatableElement[selfType]
return base._customIndexOfEquatableElement(element)
}
var first: Iterator.Element? {
++CollectionLog.first[selfType]
return base.first
}
}
struct LoggingCollection<Base_: Collection> : LoggingCollectionType {}
| apache-2.0 | 5cfbbfbc32e728e33055d79248dc9000 | 24.886364 | 82 | 0.70518 | 4.320941 | false | false | false | false |
nickfrey/knightsapp | Newman Knights/CalendarSearchViewController.swift | 1 | 5625 | //
// CalendarSearchViewController.swift
// Newman Knights
//
// Created by Nick Frey on 12/24/15.
// Copyright © 2015 Nick Frey. All rights reserved.
//
import UIKit
class CalendarSearchViewController: UITableViewController, UISearchBarDelegate {
fileprivate weak var searchBar: UISearchBar?
fileprivate var searchResults: Array<Event>?
fileprivate var currentCancelHandler: (() -> Void)?
fileprivate let noneCellIdentifier = "NoneCell"
fileprivate let resultCellIdentifier = "ResultCell"
override func loadView() {
super.loadView()
self.tableView.rowHeight = 55
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.noneCellIdentifier)
self.tableView.register(CalendarDayViewController.EventCell.self, forCellReuseIdentifier: self.resultCellIdentifier)
if #available(iOS 11.0, *) {
self.title = NSLocalizedString("Search Events", comment: "Title for calendar search")
let searchController = UISearchController(searchResultsController: nil)
searchController.obscuresBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
self.navigationItem.searchController = searchController
self.navigationItem.hidesSearchBarWhenScrolling = false
let searchBar = searchController.searchBar
searchBar.delegate = self
searchBar.tintColor = .white
self.searchBar = searchBar
} else {
let searchBar = UISearchBar()
searchBar.delegate = self
searchBar.placeholder = NSLocalizedString("Search", comment: "Search bar placeholder")
searchBar.showsCancelButton = true
searchBar.backgroundImage = UIImage()
searchBar.tintColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
self.searchBar = searchBar
let barWrapperView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width - 15, height: 44))
barWrapperView.addSubview(searchBar)
searchBar.sizeToFit()
self.navigationItem.titleView = barWrapperView
}
UIBarButtonItem.swift_appearanceWhenContained(in: [UISearchBar.self]).tintColor = .white
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if #available(iOS 11.0, *) {
DispatchQueue.main.async {
self.searchBar?.becomeFirstResponder()
}
} else {
self.searchBar?.becomeFirstResponder()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@objc func fetchResults() {
guard let searchText = self.searchBar?.text, searchText.count > 2
else { return }
if let cancelHandler = self.currentCancelHandler {
cancelHandler()
}
self.currentCancelHandler = EventCalendar.fetchEvents(searchText) { (events, error) -> Void in
DispatchQueue.main.async(execute: {
if error == nil {
self.searchResults = events
self.tableView.reloadData()
}
})
}
}
// MARK: UISearchBarDelegate
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.dismiss(animated: true, completion: nil)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(fetchResults), object: nil)
self.perform(#selector(fetchResults), with: nil, afterDelay: 0.3)
}
// MARK: UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let searchResults = self.searchResults, searchResults.count > 0 {
return searchResults.count
}
if let searchText = self.searchBar?.text {
return (searchText.count > 0 ? 1 : 0)
} else {
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let searchResults = self.searchResults, searchResults.count > 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: self.resultCellIdentifier, for: indexPath) as! CalendarDayViewController.EventCell
cell.event = searchResults[indexPath.row]
cell.dateFormat = "MMMM d, yyyy h:mm a"
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: self.noneCellIdentifier, for: indexPath)
cell.backgroundColor = .clear
cell.selectionStyle = .none
cell.textLabel?.textColor = UIColor(white: 0, alpha: 0.4)
cell.textLabel?.textAlignment = .center
cell.textLabel?.text = "No events."
return cell
}
}
// MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let searchResults = self.searchResults, indexPath.row < searchResults.count
else { return }
let viewController = CalendarEventViewController(event: searchResults[indexPath.row])
self.navigationController?.pushViewController(viewController, animated: true)
}
}
| mit | 6a302f702a82c7c2209028ff07fa656b | 39.171429 | 151 | 0.635846 | 5.607178 | false | false | false | false |
micazeve/MAGearRefreshControl | Classes/MAAnimatedMultiGearView.swift | 1 | 4184 | //
// MAAnimatedMultiGearView.swift
// MAGearRefreshControl-Demo
//
// Created by Michaël Azevedo on 20/02/2017.
// Copyright © 2017 micazeve. All rights reserved.
//
import UIKit
//MARK: - MAAnimatedMultiGearView Class
/// This class is used to draw and animate multiple gears
public class MAAnimatedMultiGearView: MAMultiGearView {
//MARK: Instance properties
/// Enum representing the animation style
internal enum MAGearRefreshAnimationStyle: UInt8 {
case singleGear // Only the main gear is rotating when the data is refreshing
case keepGears // All the gear are still visible during the refresh and disappear only when its finished
}
/// Animation style of the refresh control
internal var style = MAGearRefreshAnimationStyle.keepGears
/// Array of rotational angle for the refresh
fileprivate var arrayOfRotationAngle:[CGFloat] = [180]
/// Workaround for the issue with the CGAffineTransformRotate (when angle > Double.pi its rotate clockwise beacause it's shorter)
fileprivate var divisionFactor: CGFloat = 1
/// Variable used to rotate or no the gear
var stopRotation = true
/// Boolean used to know if the view is already animated
var isRotating = false
//MARK: Various methods
/// Override of the `addLinkedGear` method in order to update the array of rotational angle when a gear is added
override public func addLinkedGear(_ gearLinked: Int, nbTeeth:UInt, color:UIColor, angleInDegree:Double, gearStyle:MASingleGearView.MAGearStyle = .Normal, nbBranches:UInt = 5) -> Bool {
if !super.addLinkedGear(gearLinked, nbTeeth: nbTeeth, color: color, angleInDegree: angleInDegree, gearStyle: gearStyle, nbBranches: nbBranches) {
return false
}
let ratio = CGFloat(arrayViews[gearLinked].gear.nbTeeth) / CGFloat(arrayViews[arrayViews.count - 1].gear.nbTeeth)
let newAngle = -1 * arrayOfRotationAngle[gearLinked] * ratio
/*
NSLog("addLinkedGear \(gearLinked) , \(nbTeeth) , \(angleInDegree)")
NSLog(" angleOtherGear : \(arrayOfRotationAngle[gearLinked])")
NSLog(" ratio : \(ratio)")
NSLog(" newAngle : \(newAngle)")
*/
arrayOfRotationAngle.append(newAngle)
let angleScaled = 1+floor(abs(newAngle)/180)
if angleScaled > divisionFactor {
divisionFactor = angleScaled
}
return true
}
/// Method called to rotate the main gear by 360 degree
internal func rotate() {
if !stopRotation && !isRotating {
isRotating = true
let duration = TimeInterval(1/divisionFactor)
/*
NSLog("rotation 0 \(self.arrayOfRotationAngle[0] / 180 * CGFloat(Double.pi) / self.divisionFactor)" )
NSLog(" -> duration : \(duration)")
*/
UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: { () -> Void in
switch self.style {
case .singleGear:
self.arrayViews[0].transform = self.arrayViews[0].transform.rotated(by: self.arrayOfRotationAngle[0] / 180 * CGFloat(Double.pi))
case .keepGears:
for i in 0..<self.arrayViews.count {
let view = self.arrayViews[i]
view.transform = view.transform.rotated(by: self.arrayOfRotationAngle[i] / 180 * CGFloat(Double.pi) / self.divisionFactor)
}
}
}, completion: { (finished) -> Void in
// NSLog(" -> completion \(finished)")
self.isRotating = false
self.rotate()
})
}
}
/// Public method to start rotating
public func startRotating() {
stopRotation = false
rotate()
}
/// Public method to start rotating
public func stopRotating() {
stopRotation = true
}
}
| mit | 95540ed664fc9d1fe37207c2611300a7 | 35.365217 | 189 | 0.599474 | 4.741497 | false | false | false | false |
BGDigital/mcwa | mcwa/mcwa/LoginViewController.swift | 1 | 5462 | //
// LoginViewController.swift
// mcwa
//
// Created by 陈强 on 15/10/21.
// Copyright © 2015年 XingfuQiu. All rights reserved.
//
import Foundation
import UIKit
class LoginViewController: UIViewController,UMSocialUIDelegate {
@IBOutlet weak var loginBtn: UIButton!
var Delegate: LoginDelegate?
var manager = AFHTTPRequestOperationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "登录"
self.view.layer.contents = UIImage(named: "login_bg")!.CGImage
// Do any additional setup after loading the view.
if(!WXApi.isWXAppInstalled()){
self.loginBtn.hidden = true
self.navigationItem.title = ""
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginGuest(sender: UIButton) {
let dict = ["act":"tempLogin"]
manager.GET(URL_MC,
parameters: dict,
success: {
(operation, responseObject) -> Void in
print(responseObject)
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
MCUtils.AnalysisUserInfo(json["dataObject"])
self.navigationController?.popViewControllerAnimated(true)
MCUtils.showCustomHUD(self, aMsg: "登录成功", aType: .Success)
self.Delegate?.loginSuccessfull!()
}else{
MCUtils.showCustomHUD(self, aMsg: "登录失败", aType: .Error)
}
}) { (operation, error) -> Void in
print(error)
}
}
@IBAction func loginAction(sender: UIButton) {
let snsPlatform:UMSocialSnsPlatform = UMSocialSnsPlatformManager.getSocialPlatformWithName(UMShareToWechatSession)
snsPlatform.loginClickHandler(self,UMSocialControllerService.defaultControllerService(),true,{(response:UMSocialResponseEntity!) ->Void in
if(response.responseCode == UMSResponseCodeSuccess){
UMSocialDataService.defaultDataService().requestSnsInformation(UMShareToWechatSession, completion: {(res:UMSocialResponseEntity!) ->Void in
var data = res.data
let openId:String = data["openid"] as! String!
let nickName:String = data["screen_name"] as! String!
let headImg:String = data["profile_image_url"] as! String!
let accessToken:String = data["access_token"] as! String!
let genderInt:Int = data["gender"] as! Int
let gender:String = genderInt==1 ? "男":"女"
let params = [
"accessToken": accessToken,
"openId": openId,
"nickName": nickName,
"gender": gender,
"headImg": headImg,
]
self.manager.POST(qqlogin_url,
parameters: params,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
if (responseObject != nil) {
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
MCUtils.AnalysisUserInfo(json["dataObject"])
self.navigationController?.popViewControllerAnimated(true)
MCUtils.showCustomHUD(self, aMsg: "登录成功", aType: .Success)
self.Delegate?.loginSuccessfull!()
}else{
MCUtils.showCustomHUD(self, aMsg: "登录失败,请重试", aType: .Error)
}
} else {
MCUtils.showCustomHUD(self, aMsg: "登录失败,请重试", aType: .Error)
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
MCUtils.showCustomHUD(self, aMsg: "登录失败,请重试", aType: .Error)
})
})
}
})
}
class func showLoginViewPage(fromNavigation:UINavigationController?, delegate: LoginDelegate?){
let loginView = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("loginViewController") as! LoginViewController
loginView.Delegate = delegate
if (fromNavigation != nil) {
fromNavigation?.pushViewController(loginView, animated: true)
} else {
fromNavigation?.presentViewController(loginView, animated: true, completion: nil)
}
}
override func viewWillAppear(animated: Bool) {
MobClick.beginLogPageView("LoginViewController")
}
override func viewWillDisappear(animated: Bool) {
MobClick.endLogPageView("LoginViewController")
}
} | mit | cf89e702d86341b143b5a2d5a15d35e2 | 41.046875 | 155 | 0.524066 | 5.593555 | false | false | false | false |
XLsn0w/XLsn0wKit_swift | XLsn0wKit/XLsn0wSwiftMacro/XLsn0wSwiftMacro.swift | 1 | 4530 | /*********************************************************************************************
* __ __ _ _________ _ _ _ _________ __ _ __ *
* \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / *
* \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / *
* \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / *
* /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / *
* / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / *
* /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ *
* *
*********************************************************************************************/
import UIKit
import SwiftyJSON
import Kingfisher
//import SnapKit
let NavBarHeigh = 44.0
let NavBarBottom = 64.0
let TabBarHeight = 49.0
let kScreenWidth = Int(UIScreen.main.bounds.width)
let kScreenHeight = Int(UIScreen.main.bounds.height)
let IS_SCREEN_4_INCH = UIScreen.main.currentMode!.size .equalTo(CGSize(width: 640, height: 1136))
let IS_SCREEN_47_INCH = UIScreen.main.currentMode!.size .equalTo(CGSize(width: 750, height: 1334))
let IS_SCREEN_55_INCH = UIScreen.main.currentMode!.size .equalTo(CGSize(width: 1242, height: 2208))
func iOS8()->Bool{
return((UIDevice.current.systemVersion as NSString).floatValue >= 8.0)
}
func iOS10()->Bool{
return((UIDevice.current.systemVersion as NSString).floatValue >= 10.0)
}
func getScreenWidth() -> CGFloat{
return UIScreen.main.bounds.size.width
}
func getScreenHeight() -> CGFloat{
return UIScreen.main.bounds.size.height
}
func getMaxYOfView(_ view: UIView) -> CGFloat{
return view.frame.origin.y + view.frame.size.height
}
func get_PI() -> CGFloat {
return CGFloat(Double.pi)
}
let colorStart = UIColor(red:0.1 , green: 0.2, blue: 0.5, alpha: 1.0)
let colorEnd = UIColor(red:0.21 , green: 0.32, blue: 0.15, alpha: 1.0)
func getColor_RGB_Float(r:Float,g:Float,b:Float) -> UIColor {
let color = UIColor(red: CGFloat(r), green: CGFloat(g), blue: CGFloat(b), alpha: 1.0)
return color
}
func getColor_RGB(r:Float,g:Float,b:Float) -> UIColor {
return UIColor(red: CGFloat(r/255.0), green: CGFloat(g/255.0), blue: CGFloat(b/255.0), alpha: 1.0)
}
// MARK: - 大小类
let CLSCREE_BOUNDS = UIScreen.main.bounds
let CLSCREE_WIDYH = UIScreen.main.bounds.width
let CLSCREE_HEIGHT = UIScreen.main.bounds.height
let CLSCREE_SCALE = UIScreen.main.scale
/// 根据不同机型尺寸的宽度
///
/// - Parameter width: 宽度
/// - Returns: 对应机型尺寸的宽度
func KScaleWidth(width : CGFloat) -> CGFloat {
return (CLSCREE_WIDYH / 375.0) * width
}
/// 根据不同机型尺寸的高度
///
/// - Parameter height: 高度
/// - Returns: 对应机型的高度
func KScaleHeight(height : CGFloat) -> CGFloat {
return (CLSCREE_HEIGHT / 667.0) * height
}
// MARK: - 判断机型
let isIphoneX = UIScreen.main.bounds.width / UIScreen.main.bounds.height < 375.0 / 667.0
/// 与导航栏对下方对齐
let CLTopLayoutGuide = UIApplication.shared.statusBarFrame.size.height + UINavigationController().navigationBar.frame.height
/// 与导航栏上方对齐
let CLBottomLayoutGuide : CGFloat = {
if isIphoneX {
return 83
}else {
return UITabBarController().tabBar.frame.size.height
}
}()
/*********************************************************************************************
* __ __ _ _________ _ _ _ _________ __ _ __ *
* \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / *
* \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / *
* \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / *
* /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / *
* / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / *
* /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ *
* *
*********************************************************************************************/
| mit | df34aa3179c2321a3688c2ec380c2566 | 37.920354 | 124 | 0.399727 | 3.301802 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Controllers/Chat/MessagesListViewController.swift | 1 | 14200 | //
// MessagesListViewController.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 10/4/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
import RealmSwift
// swiftlint:disable file_length
extension RoomMessagesResource {
func fetchMessagesFromRealm() -> [Message]? {
var messages = [Message]()
raw?["messages"].arrayValue.forEach { json in
Realm.executeOnMainThread({ realm in
let message = Message.getOrCreate(realm: realm, values: json, updates: nil)
message.map(json, realm: realm)
messages.append(message)
})
}
return messages
}
}
extension RoomMentionsResource {
func fetchMessagesFromRealm() -> [Message]? {
var messages = [Message]()
raw?["mentions"].arrayValue.forEach { json in
Realm.executeOnMainThread({ realm in
let message = Message.getOrCreate(realm: realm, values: json, updates: nil)
message.map(json, realm: realm)
messages.append(message)
})
}
return messages
}
}
extension SearchMessagesResource {
func fetchMessagesFromRealm() -> [Message]? {
var messages = [Message]()
raw?["messages"].arrayValue.forEach { json in
Realm.executeOnMainThread({ realm in
let message = Message.getOrCreate(realm: realm, values: json, updates: nil)
message.map(json, realm: realm)
messages.append(message)
})
}
return messages
}
}
class MessagesListViewData {
typealias CellData = (message: Message?, date: Date?)
var subscription: Subscription?
let pageSize = 20
var currentPage = 0
var showing: Int = 0
var total: Int = 0
var title: String = localized("chat.messages.list.title")
var isLoadingSearchResults: Bool = false
var isSearchingMessages: Bool = false
var isListingMentions: Bool = false
var isShowingAllMessages: Bool {
return showing >= total
}
var cellsPages: [[CellData]] = []
var cells: FlattenCollection<[[CellData]]> {
return cellsPages.joined()
}
func cell(at index: Int) -> CellData {
return cells[cells.index(cells.startIndex, offsetBy: index)]
}
var query: String?
private var isLoadingMoreMessages = false
private var hasMoreMessages = true
func searchMessages(withText text: String, completion: (() -> Void)? = nil) {
guard let subscription = subscription else {
return
}
API.current()?.fetch(SearchMessagesRequest(roomId: subscription.rid, searchText: text)) { [weak self] response in
self?.isLoadingSearchResults = false
switch response {
case .resource(let resource):
self?.handleMessages(
fetchingWith: resource.fetchMessagesFromRealm,
showing: nil,
total: nil,
completion: completion
)
default:
break
}
}
}
func loadMoreMessages(completion: (() -> Void)? = nil) {
guard !isLoadingMoreMessages && hasMoreMessages else { return }
if isListingMentions {
loadMentions(completion: completion)
} else {
loadMessages(completion: completion)
}
}
private func loadMessages(completion: (() -> Void)? = nil) {
guard let subscription = subscription else { return }
isLoadingMoreMessages = true
let options: APIRequestOptionSet = [.paginated(count: pageSize, offset: currentPage*pageSize)]
let request = RoomMessagesRequest(roomId: subscription.rid, type: subscription.type, query: query)
API.current()?.fetch(request, options: options) { [weak self] response in
switch response {
case .resource(let resource):
self?.hasMoreMessages = resource.count ?? 0 > 0
self?.handleMessages(
fetchingWith: resource.fetchMessagesFromRealm,
showing: resource.count,
total: resource.total,
completion: completion
)
case .error:
Alert.defaultError.present()
}
}
}
private func loadMentions(completion: (() -> Void)? = nil) {
guard let subscription = subscription else { return }
isLoadingMoreMessages = true
let options: APIRequestOptionSet = [.paginated(count: pageSize, offset: currentPage*pageSize)]
let request = RoomMentionsRequest(roomId: subscription.rid)
API.current()?.fetch(request, options: options) { [weak self] response in
switch response {
case .resource(let resource):
self?.hasMoreMessages = resource.count ?? 0 > 0
self?.handleMessages(
fetchingWith: resource.fetchMessagesFromRealm,
showing: resource.count,
total: resource.total,
completion: completion
)
case .error:
Alert.defaultError.present()
}
}
}
private func handleMessages(fetchingWith messagesFetcher: @escaping () -> [Message]?, showing: Int?, total: Int?, completion: (() -> Void)? = nil) {
DispatchQueue.main.async {
self.showing += showing ?? 0
self.total = total ?? 0
if let messages = messagesFetcher() {
guard var lastMessage = messages.first else {
if self.isSearchingMessages {
self.cellsPages = []
}
self.isLoadingMoreMessages = false
completion?()
return
}
var cellsPage = [CellData(message: nil, date: lastMessage.createdAt ?? Date(timeIntervalSince1970: 0))]
messages.forEach { message in
if lastMessage.createdAt?.day != message.createdAt?.day ||
lastMessage.createdAt?.month != message.createdAt?.month ||
lastMessage.createdAt?.year != message.createdAt?.year {
cellsPage.append(CellData(message: nil, date: message.createdAt ?? Date(timeIntervalSince1970: 0)))
}
cellsPage.append(CellData(message: message, date: nil))
lastMessage = message
}
if self.isSearchingMessages {
self.cellsPages = [cellsPage]
} else {
self.cellsPages.append(cellsPage)
}
}
if !self.isSearchingMessages { self.currentPage += 1 }
self.isLoadingMoreMessages = false
completion?()
}
}
}
class MessagesListViewController: BaseViewController {
lazy var refreshControl = UIRefreshControl()
lazy var searchBar = UISearchBar()
var searchTimer: Timer?
var data = MessagesListViewData()
@IBOutlet weak var collectionView: UICollectionView!
@objc func refreshControlDidPull(_ sender: UIRefreshControl) {
let data = MessagesListViewData()
data.subscription = self.data.subscription
data.query = self.data.query
data.isListingMentions = self.data.isListingMentions
data.loadMoreMessages {
self.data = data
self.collectionView.reloadData()
self.collectionView.refreshControl?.endRefreshing()
self.updateIsEmptyMessage()
}
}
func updateIsEmptyMessage() {
guard let label = collectionView.backgroundView as? UILabel else { return }
if data.cells.count == 0 {
if data.isSearchingMessages &&
(searchBar.text == nil || searchBar.text == "") ||
data.isLoadingSearchResults {
label.text = ""
return
}
label.text = localized("chat.messages.list.empty")
} else {
label.text = ""
}
}
func loadMoreMessages() {
data.loadMoreMessages {
self.collectionView.reloadData()
self.collectionView.refreshControl?.endRefreshing()
self.updateIsEmptyMessage()
}
}
func searchMessages(withText text: String) {
data.searchMessages(withText: text) {
if self.searchBar.text == nil || self.searchBar.text == "" {
self.data.cellsPages = []
}
self.collectionView.reloadData()
self.updateIsEmptyMessage()
}
}
}
// MARK: ViewController
extension MessagesListViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: collectionView.frame)
label.textAlignment = .center
label.textColor = .gray
collectionView.backgroundView = label
registerCells()
if data.isSearchingMessages {
let gesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
gesture.cancelsTouchesInView = false
collectionView.addGestureRecognizer(gesture)
setupSearchBar()
} else {
title = data.title
refreshControl.addTarget(self, action: #selector(refreshControlDidPull), for: .valueChanged)
collectionView.refreshControl = refreshControl
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !data.isSearchingMessages {
loadMoreMessages()
} else {
searchBar.becomeFirstResponder()
}
guard let refreshControl = collectionView.refreshControl, !data.isSearchingMessages else { return }
collectionView.contentOffset = CGPoint(x: 0, y: -refreshControl.frame.size.height)
collectionView.refreshControl?.beginRefreshing()
}
func registerCells() {
collectionView.register(UINib(
nibName: "ChatMessageCell",
bundle: Bundle.main
), forCellWithReuseIdentifier: ChatMessageCell.identifier)
collectionView.register(UINib(
nibName: "ChatLoaderCell",
bundle: Bundle.main
), forCellWithReuseIdentifier: ChatLoaderCell.identifier)
collectionView.register(UINib(
nibName: "ChatMessageDaySeparator",
bundle: Bundle.main
), forCellWithReuseIdentifier: ChatMessageDaySeparator.identifier)
}
func setupSearchBar() {
searchBar.placeholder = localized("chat.messages.list.search.placeholder")
searchBar.delegate = self
let cancelButton = UIBarButtonItem(title: localized("global.cancel"), style: .plain, target: self, action: #selector(close))
navigationItem.rightBarButtonItem = cancelButton
navigationItem.titleView = searchBar
searchBar.applyTheme()
}
@objc func close() {
hideKeyboard()
presentingViewController?.dismiss(animated: true, completion: nil)
}
@objc func hideKeyboard() {
guard data.isSearchingMessages else {
return
}
searchBar.resignFirstResponder()
}
}
// MARK: CollectionView
extension MessagesListViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return !data.isLoadingSearchResults ? data.cells.count + (data.isShowingAllMessages ? 0 : 1) : 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard indexPath.row < data.cells.count else {
return collectionView.dequeueReusableCell(withReuseIdentifier: ChatLoaderCell.identifier, for: indexPath)
}
if data.isSearchingMessages && data.isLoadingSearchResults {
return collectionView.dequeueReusableCell(withReuseIdentifier: ChatLoaderCell.identifier, for: indexPath)
}
let cellData = data.cell(at: indexPath.row)
if let message = cellData.message,
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ChatMessageCell.identifier, for: indexPath) as? ChatMessageCell {
cell.message = message
return cell
}
if let date = cellData.date,
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ChatMessageDaySeparator.identifier, for: indexPath) as? ChatMessageDaySeparator {
cell.labelTitle.text = RCDateFormatter.date(date)
return cell
}
return UICollectionViewCell()
}
}
extension MessagesListViewController: UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
hideKeyboard()
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.row == data.cells.count - data.pageSize/3 && !data.isSearchingMessages {
loadMoreMessages()
}
}
}
extension MessagesListViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let fullWidth = collectionView.bounds.size.width
guard indexPath.row < data.cells.count else { return CGSize(width: fullWidth, height: 50) }
let cellData = data.cell(at: indexPath.row)
if let message = cellData.message {
return CGSize(width: fullWidth, height: ChatMessageCell.cellMediaHeightFor(message: message, width: fullWidth, sequential: false))
}
if cellData.date != nil {
return CGSize(width: fullWidth, height: ChatMessageDaySeparator.minimumHeight)
}
return CGSize(width: fullWidth, height: 50)
}
}
| mit | b583db15ad1bdb534a05546ad23d6c1d | 33.716381 | 160 | 0.610747 | 5.368242 | false | false | false | false |
mzyy94/TesSoMe | TesSoMe/UserViewController.swift | 1 | 15322 | //
// UserViewController.swift
// TesSoMe
//
// Created by Yuki Mizuno on 2014/10/02.
// Copyright (c) 2014年 Yuki Mizuno. All rights reserved.
//
import UIKit
class UserViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let apiManager = TessoApiManager()
let ud = NSUserDefaults()
var username = ""
var labels: [NSDictionary] = []
var messages: [TesSoMeData] = []
var segmentedControl: HMSegmentedControl! = nil
@IBOutlet weak var userIcon: UIImageView!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var levelLabel: UILabel!
@IBOutlet weak var segmentedControlArea: UIView!
@IBOutlet weak var informationTableView: UITableView!
@IBOutlet weak var profileTextView: UITextView!
@IBOutlet weak var profileView: UIView!
@IBAction func WebIconBtnPressed() {
let webKitViewController = WebKitViewController()
webKitViewController.url = NSURL(string: "https://tesso.pw/mem/\(username)/")
self.navigationController?.pushViewController(webKitViewController, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
if username == "" {
username = appDelegate.usernameOfTesSoMe!
}
if username == appDelegate.usernameOfTesSoMe {
let settingUserdataBtn = UIBarButtonItem(image: UIImage(named: "setting_icon"), style: .Plain, target: self, action: Selector("settingUserdata"))
self.navigationItem.rightBarButtonItem = settingUserdataBtn
} else {
let addLabelBtn = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: Selector("addLabelToUser"))
self.navigationItem.rightBarButtonItem = addLabelBtn
}
let nib = UINib(nibName: "TimelineMessageCell", bundle: nil)
self.informationTableView.registerNib(nib, forCellReuseIdentifier: "MessageCell")
self.informationTableView.estimatedRowHeight = 90.5
self.informationTableView.rowHeight = UITableViewAutomaticDimension
self.informationTableView.delegate = self
self.informationTableView.dataSource = self
self.profileTextView.delegate = self
let profile = NSLocalizedString("Profile", comment: "Profile at segmented control")
let label = NSLocalizedString("Label", comment: "Label at segmented control")
let post = NSLocalizedString("Recently Post", comment: "Recently Post at segmented control")
let items = [profile, label, post]
segmentedControl = HMSegmentedControl(sectionTitles: items)
segmentedControl.frame = CGRectMake(0, 0, self.view.frame.width, 32)
segmentedControl.selectionIndicatorHeight = 4.0
segmentedControl.backgroundColor = UIColor.whiteColor()
segmentedControl.textColor = UIColor.lightGrayColor()
segmentedControl.selectedTextColor = UIColor.globalTintColor()
segmentedControl.selectionIndicatorColor = UIColor.globalTintColor()
segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleBox
segmentedControl.selectedSegmentIndex = 0
segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown
segmentedControl.shouldAnimateUserSelection = true
segmentedControl.setTranslatesAutoresizingMaskIntoConstraints(false)
segmentedControl.addTarget(self, action: Selector("segmentedControlValueChanged:"), forControlEvents: .ValueChanged)
self.segmentedControlArea.addSubview(segmentedControl)
for constraintAttribute: NSLayoutAttribute in [.Bottom, .Top, .Right, .Left] {
self.view.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: constraintAttribute, relatedBy: .Equal, toItem: self.segmentedControlArea, attribute: constraintAttribute, multiplier: 1.0, constant: 0))
}
self.userIcon.layer.borderColor = UIColor(white: 0.0, alpha: 0.3).CGColor
self.userIcon.layer.borderWidth = 1.0
self.userIcon.layer.cornerRadius = 4.0
self.userIcon.clipsToBounds = true
self.usernameLabel.text = "@\(username)"
self.navigationItem.title = "@\(username)"
self.userIcon.sd_setImageWithURL(NSURL(string: "https://tesso.pw/img/icons/\(username).png"))
apiManager.getProfile(username: username, withTitle: true, withTimeline: true, onSuccess:
{ data in
let userdata = (data["data"] as [NSDictionary]).first!
let userInfo = userdata["data"] as String!
let id = userdata["id"] as String!
let nickname = userdata["nickname"] as String!
let level = userdata["lv"] as String!
self.labels = userdata["label"] as [NSDictionary]!
let timeline = TesSoMeData.tlFromResponce(data) as [NSDictionary]
for post in timeline {
self.messages.append(TesSoMeData(data: post, isTopicIdVisible: true))
}
self.nicknameLabel.text = nickname
self.levelLabel.text = "Lv. \(level)"
self.profileTextView.attributedText = TesSoMeData.convertAttributedProfile(userInfo, size: CGFloat(self.ud.floatForKey("fontSize")))
}
, onFailure:
{ err in
let notification = MPGNotification(title: NSLocalizedString("Can not get user infomation", comment: "Can not get user information"), subtitle: err.localizedDescription, backgroundColor: UIColor(red: 1.0, green: 0.3, blue: 0.3, alpha: 1.0), iconImage: UIImage(named: "warning_icon"))
notification.duration = 5.0
notification.animationType = .Drop
notification.setButtonConfiguration(.ZeroButtons, withButtonTitles: nil)
notification.swipeToDismissEnabled = false
notification.show()
self.navigationController?.popViewControllerAnimated(true)
})
}
var addLabelAction: UIAlertAction! = nil
func addLabelToUser() {
let alertController = UIAlertController(title: NSLocalizedString("Add Label", comment: "Add Label on AlertView"), message: NSLocalizedString("Please type new label (max. 256 characters).", comment: "Please type new label (max. 256 characters)."), preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel on AlertView"), style: .Cancel) {
action in
NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields?.first)
}
alertController.addAction(cancelAction)
self.addLabelAction = UIAlertAction(title: NSLocalizedString("Add", comment: "Add on AlertView"), style: .Default) {
action in
let textField = alertController.textFields?.first as UITextField
let newLabel = textField.text
self.apiManager.addTitle(username: self.username, title: newLabel, onSuccess:
{ data in
self.apiManager.getProfile(username: self.username, withTitle: true, withTimeline: true, onSuccess:
{ data in
let userdata = (data["data"] as [NSDictionary]).first!
let userInfo = userdata["data"] as String!
let nickname = userdata["nickname"] as String!
let level = userdata["lv"] as String!
self.labels = userdata["label"] as [NSDictionary]!
self.nicknameLabel.text = nickname
self.levelLabel.text = "Lv. \(level)"
self.profileTextView.attributedText = TesSoMeData.convertAttributedProfile(userInfo, size: CGFloat(self.ud.floatForKey("fontSize")))
self.informationTableView.reloadData()
}
, onFailure: nil)
}, onFailure:
{ err in
let notification = MPGNotification(title: NSLocalizedString("Can not add new label", comment: "Can not add new label"), subtitle: err.localizedDescription, backgroundColor: UIColor(red: 1.0, green: 0.3, blue: 0.3, alpha: 1.0), iconImage: UIImage(named: "warning_icon"))
notification.duration = 5.0
notification.animationType = .Drop
notification.setButtonConfiguration(.ZeroButtons, withButtonTitles: nil)
notification.swipeToDismissEnabled = false
notification.show()
})
NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields?.first)
}
alertController.addAction(self.addLabelAction)
alertController.addTextFieldWithConfigurationHandler(
{ textField in
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleTextFieldTextDidChangeNotification:"), name: UITextFieldTextDidChangeNotification, object: textField)
}
)
self.presentViewController(alertController, animated: true, completion: nil)
}
func settingUserdata() {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let addLabel = UIAlertAction(title: NSLocalizedString("Add Label", comment: "Add Label on AlertView"), style: .Default)
{ action in
self.addLabelToUser()
}
alertController.addAction(addLabel)
let changeNickname = UIAlertAction(title: NSLocalizedString("Change Nickname", comment: "Change Nickname on AlertView"), style: .Default)
{ action in
self.changeNickname()
}
// MEMO: NO API AVAILABLE
//alertController.addAction(changeNickname)
let editProfile = UIAlertAction(title: NSLocalizedString("Edit Profile", comment: "Edit Profile on AlertView"), style: .Default)
{ action in
self.editProfile()
}
// MEMO: NO API AVAILABLE
//alertController.addAction(editProfile)
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel on AlertView"), style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func changeNickname() {
let alertController = UIAlertController(title: NSLocalizedString("Change Nickname", comment: "Change Nickname on AlertView"), message: NSLocalizedString("Please type new nickname.", comment: "Please type new nickname."), preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel on AlertView"), style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let changeNicknameAction = UIAlertAction(title: NSLocalizedString("Change", comment: "Change on AlertView"), style: .Default) {
action in
let textField = alertController.textFields?.first as UITextField
let newNickname = textField.text
self.apiManager.updateProfile(nickname: newNickname, onSuccess:
{ data in
self.nicknameLabel.text = newNickname
}, onFailure:
{ err in
let notification = MPGNotification(title: NSLocalizedString("Can not change nickname", comment: "Can not change nickname"), subtitle: err.localizedDescription, backgroundColor: UIColor(red: 1.0, green: 0.3, blue: 0.3, alpha: 1.0), iconImage: UIImage(named: "warning_icon"))
notification.duration = 5.0
notification.animationType = .Drop
notification.setButtonConfiguration(.ZeroButtons, withButtonTitles: nil)
notification.swipeToDismissEnabled = false
notification.show()
})
}
alertController.addAction(changeNicknameAction)
alertController.addTextFieldWithConfigurationHandler(
{ textField in
textField.placeholder = NSLocalizedString("New Nickname", comment: "New Nickname on AlertView")
}
)
self.presentViewController(alertController, animated: true, completion: nil)
}
func editProfile() {
let alertController = UIAlertController(title: NSLocalizedString("Edit Profile", comment: "Edit Profile on AlertView"), message: NSLocalizedString("Please type new profile.", comment: "Please type new profile."), preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel on AlertView"), style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let editProfileAction = UIAlertAction(title: NSLocalizedString("OK", comment: "OK on AlertView"), style: .Default) {
action in
let textField = alertController.textFields?.first as UITextField
let newProfile = textField.text
self.apiManager.updateProfile(profile: newProfile, onSuccess:
{ data in
self.profileTextView.text = newProfile
}, onFailure:
{ err in
let notification = MPGNotification(title: NSLocalizedString("Can not edit profile", comment: "Can not edit profile"), subtitle: err.localizedDescription, backgroundColor: UIColor(red: 1.0, green: 0.3, blue: 0.3, alpha: 1.0), iconImage: UIImage(named: "warning_icon"))
notification.duration = 5.0
notification.animationType = .Drop
notification.setButtonConfiguration(.ZeroButtons, withButtonTitles: nil)
notification.swipeToDismissEnabled = false
notification.show()
})
}
alertController.addAction(editProfileAction)
alertController.addTextFieldWithConfigurationHandler(nil)
self.presentViewController(alertController, animated: true, completion: nil)
}
func handleTextFieldTextDidChangeNotification(notification: NSNotification) {
let textField = notification.object as UITextField
let newLabel = textField.text
if newLabel != nil && textField.text.utf16Count < 256 {
addLabelAction.enabled = true
} else {
addLabelAction.enabled = false
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch segmentedControl.selectedSegmentIndex {
case 1:
var cell = tableView.dequeueReusableCellWithIdentifier("LabelCell", forIndexPath: indexPath) as LabelCell
let data = labels[indexPath.row]
cell.labeledUsername = data["username"] as String!
cell.userIconBtn.sd_setBackgroundImageWithURL(NSURL(string: "https://tesso.pw/img/icons/\(cell.labeledUsername).png"), forState: .Normal)
let converter = HTMLEntityConverter()
cell.labelLabel.text = HTMLEntityConverter.unescape(data["data"] as String!)
return cell
case 2:
var cell = tableView.dequeueReusableCellWithIdentifier("MessageCell", forIndexPath: indexPath) as TimelineMessageCell
let data = messages[indexPath.row]
// Configure the cell...
data.setDataToCell(&cell, withFontSize: CGFloat(ud.floatForKey("fontSize")), withBadge: true, withImagePreview: ud.boolForKey("imagePreview"), withReplyIcon: ud.boolForKey("replyIcon"))
cell.updateTimestamp(relative: false)
return cell
default:
return UITableViewCell()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch self.segmentedControl.selectedSegmentIndex {
case 0:
self.profileView.hidden = false
return 0
case 1:
self.profileView.hidden = true
return labels.count
case 2:
self.profileView.hidden = true
return messages.count
default:
return 0
}
}
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
let webKitViewController = WebKitViewController()
webKitViewController.url = URL
self.navigationController?.pushViewController(webKitViewController, animated: true)
return false
}
func segmentedControlValueChanged(sender: HMSegmentedControl) {
self.informationTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 34ac4da5c41affd6308c55c676cdaff0 | 41.087912 | 286 | 0.745235 | 4.459971 | false | false | false | false |
Slowhand0309/OralWar | OralWar/Game/GameScene.swift | 1 | 3596 | //
// GameScene.swift
// OralWar
//
// Created by MrSmall on 2015/08/26.
// Copyright (c) 2015年 MrSmall. All rights reserved.
//
import SpriteKit
let STAGELIST: String = "stagelist"
class GameScene: SKScene {
var uiView: UILayerView!
var oralPieceMap: OralPieceMap!
var user: User!
override init(size: CGSize) {
super.init(size: size)
}
// set user info
func setUser(_ user: User) {
self.user = user
}
// set ui layer
func setUiLayerView(_ view: UILayerView) {
uiView = view
self.view!.addSubview(uiView)
}
// set up piece map
func setUp() -> Bool {
// load UserDefaults
guard let user = UserDefaultsUtil.getUserInfo() else {
return false
}
let stage = user.getStage()
print("stage \(stage)")
// read stagelist.json
let util: JsonUtil = JsonUtil()
let data = util.parseJson(STAGELIST, type: JSON_FORMAT.file)
guard let stageData: NSArray = data as? NSArray else {
return false
}
var uri = ""
for elm in stageData {
print(elm)
guard let stageInfo: Stage = ConvertUtil.toStage(elm as? NSDictionary) else {
continue
}
if stage == stageInfo.getId() {
uri = stageInfo.getUri()
}
}
if uri == "" {
// uri empty
return false
}
print(uri)
// get stage data
guard let stageMapData = util.parseJson(uri) else {
return false
}
// convert oralpiecemap
oralPieceMap = ConvertUtil.toOralPieceMap(stageMapData as! NSDictionary)
// TODO set info data to ui view
return true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMove(to view: SKView) {
// show background for debug
let backtooth = SKSpriteNode(imageNamed: "backtooth01.png")
backtooth.size = self.size
backtooth.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
self.addChild(backtooth)
print("w : \(self.size.width), y : \(self.size.height)")
// TODO for debug
let ary = TextureUtil.loadDivImage("chip_pumpkin1.png", col: 3, row: 4)
let node: SKSpriteNode = SKSpriteNode(texture: ary[0])
node.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
node.name = "pumpkin"
//let action: SKAction = SKAction.animateWithTextures(ary, timePerFrame: 0.2)
//let forever: SKAction = SKAction.repeatActionForever(action)
//node.runAction(forever)
self.addChild(node)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
/* Called when a touch begins */
if let touch = touches.first as UITouch! {
let location = touch.location(in: self.view)
let newlocation = CGPoint(x: location.x, y: self.size.height - location.y)
// TODO for debug
print(location)
let node = self.childNode(withName: "pumpkin")
let action = SKAction.move(to: newlocation, duration: 1.0)
node?.run(action)
}
}
override func update(_ currentTime: TimeInterval) {
/* Called before each frame is rendered */
}
}
| mit | c874fb14621a9c1d5bee905257167984 | 28.95 | 97 | 0.560657 | 4.258294 | false | false | false | false |
ufogxl/MySQLTest | Sources/getAllExam.swift | 1 | 2528 | //
// File.swift
// GoodStudent
//
// Created by ufogxl on 2016/12/12.
//
//
import Foundation
import PerfectLib
import PerfectHTTP
import MySQL
import ObjectMapper
fileprivate let container = ResponseContainer()
fileprivate let errorContent = ErrorContent()
fileprivate var user_info = NSDictionary()
func getAllExam(_ request:HTTPRequest,response:HTTPResponse){
let params = request.params()
phaseParams(params: params)
if !paramsValid(){
errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue
container.data = errorContent
container.result = false
container.message = "参数错误"
response.appendBody(string: container.toJSONString(prettyPrint: true)!)
response.completed()
return
}
if let exams = makeAllExams(){
container.data = exams
container.result = true
container.message = "获取成功!"
}else{
errorContent.code = ErrCode.SERVER_ERROR.hashValue
container.data = errorContent
container.result = false
container.message = "获取失败,稍后再试!"
}
response.appendBody(string: container.toJSONString(prettyPrint: true)!)
response.completed()
}
fileprivate func phaseParams(params: [(String,String)]){
let info = NSMutableDictionary()
for pair in params{
info.setObject(pair.1, forKey: NSString(string:pair.0))
}
user_info = info as NSDictionary
}
fileprivate func makeAllExams() -> AllExams?{
let exams = AllExams()
var examInfo = [Exam]()
let mysql = MySQL()
let connected = mysql.connect(host: db_host, user: db_user, password: db_password, db: database,port:db_port)
guard connected else {
print(mysql.errorMessage())
return nil
}
defer {
mysql.close()
}
let statement = "SELECT c_name,exam_time,exam_place FROM stujoincou WHERE s_num=\(Int(user_info["username"] as! String)!) and exam_time>=\(getWhichExam()) order by exam_time"
let querySuccess = mysql.query(statement: statement)
guard querySuccess else{
return nil
}
let results = mysql.storeResults()!
while let row = results.next(){
let exam = Exam()
exam.name = row[0]!
exam.time = getExamTime(Int(row[1]!)!)
exam.place = row[2]!
examInfo.append(exam)
}
exams.exams = examInfo
return exams
}
fileprivate func paramsValid() -> Bool{
return true
}
| apache-2.0 | 8d05d9130398b012861257b8bb81dd2f | 24.191919 | 178 | 0.636728 | 4.14975 | false | false | false | false |
qxuewei/XWSwiftWB | XWSwiftWB/XWSwiftWB/Classes/Tools/XWEmojiTool/Model/EmotionText.swift | 1 | 2108 | //
// EmotionText.swift
// XWSwiftWB
//
// Created by 邱学伟 on 2016/12/8.
// Copyright © 2016年 邱学伟. All rights reserved.
//
import UIKit
class EmotionText {
//Swift 单例对象
static let sharedInstance : EmotionText = EmotionText()
// MARK:- 表情属性
private lazy var manager : EmoticonManager = EmoticonManager()
//MARK: - 替换带有表情的文本
func replaceEmotionText(text : String?, font : UIFont) -> NSAttributedString? {
guard let text = text else {
XWLog("想替换表情的文本nil")
return nil
}
let pattern = "\\[.*?\\]"
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
XWLog("正则表达式写错了")
return nil
}
let results : [NSTextCheckingResult] = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count))
let attrM = NSMutableAttributedString(string: text)
if results.count == 0 {
return attrM
}
for i in (0...(results.count-1)).reversed(){
let result = results[i]
let chs = (text as NSString).substring(with: result.range)
if let emotionPath = findPngPath(chs) {
let imageAttachment : NSTextAttachment = NSTextAttachment()
imageAttachment.image = UIImage(contentsOfFile: emotionPath)
imageAttachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
let imageAttributedStr : NSAttributedString = NSAttributedString(attachment: imageAttachment)
attrM.replaceCharacters(in: result.range, with: imageAttributedStr)
}
}
return attrM
}
private func findPngPath(_ chs : String) -> String?{
for package in manager.packages {
for emotion in package.emojis {
if emotion.chs == chs {
return emotion.pngPath
}
}
}
return nil
}
}
| apache-2.0 | 72f756be71cb64a42fb17744d85a607f | 33.355932 | 143 | 0.579181 | 4.617312 | false | false | false | false |
KrishMunot/swift | test/Constraints/closures.swift | 2 | 6342 | // RUN: %target-parse-verify-swift
func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {}
var intArray : [Int]
myMap(intArray, { String($0) })
myMap(intArray, { x -> String in String(x) } )
// Closures with too few parameters.
func foo(_ x: (Int, Int) -> Int) {}
foo({$0}) // expected-error{{cannot convert value of type '(Int, Int)' to closure result type 'Int'}}
struct X {}
func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {}
func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {}
var strings : [String]
mySort(strings, { x, y in x < y })
// Closures with inout arguments.
func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U {
var t2 = t
return f(&t2)
}
struct X2 {
func g() -> Float { return 0 }
}
f0(X2(), {$0.g()})
// Autoclosure
func f1(@autoclosure f: () -> Int) { }
func f2() -> Int { }
f1(f: f2) // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}}
f1(f: 5)
// Ternary in closure
var evenOrOdd : Int -> String = {$0 % 2 == 0 ? "even" : "odd"}
// <rdar://problem/15367882>
func foo() {
not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}}
}
// <rdar://problem/15536725>
struct X3<T> {
init(_: (T) -> ()) {}
}
func testX3(_ x: Int) {
var x = x
_ = X3({ x = $0 })
_ = x
}
// <rdar://problem/13811882>
func test13811882() {
var _ : (Int) -> (Int, Int) = {($0, $0)}
var x = 1
var _ : (Int) -> (Int, Int) = {($0, x)}
x = 2
}
// <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement
func r21544303() {
var inSubcall = true
{ // expected-error {{expected 'do' keyword to designate a block of statements}} {{3-3=do }}
}
inSubcall = false
// This is a problem, but isn't clear what was intended.
var somethingElse = true { // expected-error {{cannot call value of non-function type 'Bool'}}
}
inSubcall = false
var v2 : Bool = false
v2 = true
{ // expected-error {{expected 'do' keyword to designate a block of statements}}
}
}
// <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure
func r22162441(_ lines: [String]) {
_ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
_ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
}
func testMap() {
let a = 42
[1,a].map { $0 + 1.0 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (Double, Double), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
}
// <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier
[].reduce { $0 + $1 } // expected-error {{missing argument for parameter #1 in call}}
// <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments
var _: () -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }}
var _: (Int) -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}}
var _: (Int) -> Int = { 0 }
// expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }}
var _: (Int, Int) -> Int = {0}
// expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
var _: (Int,Int) -> Int = {$0+$1+$2}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {$0+$1}
var _: () -> Int = {a in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}}
var _: (Int) -> Int = {a,b in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}}
var _: (Int) -> Int = {a,b,c in 0}
var _: (Int, Int) -> Int = {a in 0}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {a, b in a+b}
// <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument
func r15998821() {
func take_closure(_ x : (inout Int) -> ()) { }
func test1() {
take_closure { (a : inout Int) in
a = 42
}
}
func test2() {
take_closure { a in
a = 42
}
}
func withPtr(_ body: (inout Int) -> Int) {}
func f() { withPtr { p in return p } }
let g = { x in x = 3 }
take_closure(g)
}
// <rdar://problem/22602657> better diagnostics for closures w/o "in" clause
var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
// Crash when re-typechecking bodies of non-single expression closures
struct CC {}
// expected-note @+1 {{in call to function 'callCC'}}
func callCC<U>(_ f: CC -> U) -> () {}
func typeCheckMultiStmtClosureCrash() {
callCC { // expected-error {{generic parameter 'U' could not be inferred}}
_ = $0
return 1
}
}
// SR-832 - both these should be ok
func someFunc(_ foo: (String -> String)?, bar: String -> String) {
let _: String -> String = foo != nil ? foo! : bar
let _: String -> String = foo ?? bar
}
// SR-1069 - Error diagnostic refers to wrong argument
class SR1069_W<T> {
func append<Key: AnyObject where Key: Hashable>(value: T, forKey key: Key) {}
}
class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() }
struct S<T> {
let cs: [SR1069_C<T>] = []
func subscribe<Object: AnyObject where Object: Hashable>(object: Object?, method: (Object, T) -> ()) {
let wrappedMethod = { (object: AnyObject, value: T) in }
// expected-error @+1 {{cannot convert value of type '(AnyObject, T) -> ()' to expected argument type '(AnyObject, _) -> ()'}}
cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) }
}
}
| apache-2.0 | e2c10338bcbd0e034db854ed1e4ccb6e | 30.869347 | 195 | 0.61684 | 3.193353 | false | false | false | false |
alexth/CDVDictionary | Dictionary/Dictionary/ViewControllers/DictionaryViewController.swift | 1 | 5371 | //
// DictionaryViewController.swift
// Dictionary
//
// Created by Alex Golub on 12/17/15.
// Copyright © 2015 Alex Golub. All rights reserved.
//
import UIKit
final class DictionaryViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var dictionaryTableView: UITableView!
@IBOutlet weak var dictionaryTableViewBottomConstraint: NSLayoutConstraint!
private struct Constants {
static let dictionaryTableViewHeaderFooterHeight = CGFloat(0.01)
static let animationDuration = TimeInterval(0.3)
}
var dictionaryName: String!
private var sourceArray = [String]()
private var displayArray = [String]()
private var displayDictionary = [String: String]()
private let attributedStringUtils = AttributedStringUtils()
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if let dictionaryName = dictionaryName {
setupData(plistName: dictionaryName)
}
setupTableView()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(keyboardWillHide(notification:)),
name: .UIKeyboardWillHide,
object: nil)
notificationCenter.addObserver(self,
selector: #selector(keyboardWillShow(notification:)),
name: .UIKeyboardWillShow,
object: nil)
}
// MARK: - Utils
private func setupTableView() {
dictionaryTableView.rowHeight = UITableViewAutomaticDimension
dictionaryTableView.estimatedRowHeight = 50.0
}
private func setupData(plistName: String) {
guard let data = PlistReaderUtils().read(plistName) else {
return
}
sourceArray = data.sourceArray
displayDictionary = data.displayDictionary
displayArray.append(contentsOf: sourceArray)
dictionaryTableView.reloadData()
}
private func setupAttributedString(cell: DictionaryCell, fullString: String) {
guard let text = searchBar.text,
text.count >= 0 else { return }
cell.wordLabel.attributedText = attributedStringUtils.createAttributedString(fullString: fullString, subString: text)
}
private func setupColorView(indexPathRow: Int) -> UIColor {
if indexPathRow % 2 == 0 {
return .base
}
let baseCellColor = UIColor.baseCell.withAlphaComponent(0.3)
return baseCellColor
}
@objc private func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: Constants.animationDuration) {
self.dictionaryTableViewBottomConstraint.constant = 0
}
}
@objc private func keyboardWillShow(notification: NSNotification) {
guard let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
UIView.animate(withDuration: Constants.animationDuration) {
self.dictionaryTableViewBottomConstraint.constant = keyboardSize.height
}
}
}
extension DictionaryViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "dictionaryCell", for: indexPath) as? DictionaryCell else {
fatalError("ERROR! Unable to dequeue DictionaryCell")
}
let word = displayArray[indexPath.row]
cell.wordLabel?.text = word
cell.translationLabel?.text = displayDictionary[word]
setupAttributedString(cell: cell, fullString: word)
cell.colorView.backgroundColor = setupColorView(indexPathRow: indexPath.row)
return cell
}
}
extension DictionaryViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return Constants.dictionaryTableViewHeaderFooterHeight
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return Constants.dictionaryTableViewHeaderFooterHeight
}
}
extension DictionaryViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
displayArray.removeAll()
if searchText.isEmpty {
displayArray.append(contentsOf: sourceArray)
} else {
for word in sourceArray {
if word.range(of: searchText, options: .caseInsensitive) != nil {
displayArray.append(word)
}
}
}
dictionaryTableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}
| mit | b454df633388a186d7c2dcb20cb0db2c | 32.987342 | 130 | 0.660521 | 5.786638 | false | false | false | false |
khizkhiz/swift | test/IDE/complete_expr_postfix_begin.swift | 5 | 20579 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_1 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_2 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_3 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_4 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_5 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_6 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IGNORED_1 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IGNORED_2 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IGNORED_3 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_1 > %t.param.txt
// RUN: FileCheck %s -check-prefix=COMMON < %t.param.txt
// RUN: FileCheck %s -check-prefix=FIND_FUNC_PARAM_1 < %t.param.txt
// RUN: FileCheck %s -check-prefix=NO_SELF < %t.param.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_2 > %t.param.txt
// RUN: FileCheck %s -check-prefix=COMMON < %t.param.txt
// RUN: FileCheck %s -check-prefix=FIND_FUNC_PARAM_2 < %t.param.txt
// RUN: FileCheck %s -check-prefix=NO_SELF < %t.param.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_3 | FileCheck %s -check-prefix=FIND_FUNC_PARAM_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_4 | FileCheck %s -check-prefix=FIND_FUNC_PARAM_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_5 | FileCheck %s -check-prefix=FIND_FUNC_PARAM_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_6 | FileCheck %s -check-prefix=FIND_FUNC_PARAM_6
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_7 | FileCheck %s -check-prefix=FIND_FUNC_PARAM_7
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_SELECTOR_1 > %t.param.txt
// RUN: FileCheck %s -check-prefix=COMMON < %t.param.txt
// RUN: FileCheck %s -check-prefix=FIND_FUNC_PARAM_SELECTOR_1 < %t.param.txt
// RUN: FileCheck %s -check-prefix=NO_SELF < %t.param.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_1 | FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_2 | FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_3 | FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_4 | FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_5 | FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_SELECTOR_1 | FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_SELECTOR_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_DESTRUCTOR_PARAM_1 > %t.param.txt
// RUN: FileCheck %s -check-prefix=FIND_DESTRUCTOR_PARAM_1 < %t.param.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_DESTRUCTOR_PARAM_2 > %t.param.txt
// RUN: FileCheck %s -check-prefix=FIND_DESTRUCTOR_PARAM_2 < %t.param.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NO_PLACEHOLDER_NAMES_1 | FileCheck %s -check-prefix=NO_PLACEHOLDER_NAMES_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_1 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_2 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_3 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_5 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_6 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_7 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_8 | FileCheck %s -check-prefix=COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_1 | FileCheck %s -check-prefix=MY_ALIAS
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_2 | FileCheck %s -check-prefix=MY_ALIAS
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_1 | FileCheck %s -check-prefix=IN_FOR_EACH_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_2 | FileCheck %s -check-prefix=IN_FOR_EACH_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_3 | FileCheck %s -check-prefix=IN_FOR_EACH_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_4 | FileCheck %s -check-prefix=IN_FOR_EACH_3
//
// Test code completion at the beginning of expr-postfix.
//
//===--- Helper types that are used in this test
struct FooStruct {
}
var fooObject : FooStruct
func fooFunc() -> FooStruct {
return fooObject
}
enum FooEnum {
}
class FooClass {
}
protocol FooProtocol {
}
typealias FooTypealias = Int
// COMMON: Begin completions
// Function parameter
// COMMON-DAG: Decl[LocalVar]/Local: fooParam[#FooStruct#]{{; name=.+$}}
// Global completions
// COMMON-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// COMMON-DAG: Decl[Enum]/CurrModule: FooEnum[#FooEnum#]{{; name=.+$}}
// COMMON-DAG: Decl[Class]/CurrModule: FooClass[#FooClass#]{{; name=.+$}}
// COMMON-DAG: Decl[Protocol]/CurrModule: FooProtocol[#FooProtocol#]{{; name=.+$}}
// COMMON-DAG: Decl[TypeAlias]/CurrModule: FooTypealias[#Int#]{{; name=.+$}}
// COMMON-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// COMMON-DAG: Keyword[try]/None: try{{; name=.+$}}
// COMMON-DAG: Literal[Boolean]/None: true[#Bool#]{{; name=.+$}}
// COMMON-DAG: Literal[Boolean]/None: false[#Bool#]{{; name=.+$}}
// COMMON-DAG: Literal[Nil]/None: nil{{; name=.+$}}
// COMMON-DAG: Decl[Struct]/OtherModule[Swift]: Int8[#Int8#]{{; name=.+$}}
// COMMON-DAG: Decl[Struct]/OtherModule[Swift]: Int16[#Int16#]{{; name=.+$}}
// COMMON-DAG: Decl[Struct]/OtherModule[Swift]: Int32[#Int32#]{{; name=.+$}}
// COMMON-DAG: Decl[Struct]/OtherModule[Swift]: Int64[#Int64#]{{; name=.+$}}
// COMMON-DAG: Decl[Struct]/OtherModule[Swift]: Bool[#Bool#]{{; name=.+$}}
// COMMON-DAG: Keyword[#function]/None: #function[#String#]{{; name=.+$}}
// COMMON-DAG: Keyword[#file]/None: #file[#String#]{{; name=.+$}}
// COMMON-DAG: Keyword[#line]/None: #line[#Int#]{{; name=.+$}}
// COMMON-DAG: Keyword[#column]/None: #column[#Int#]{{; name=.+$}}
// COMMON: End completions
// NO_SELF-NOT: Self
// NO_SELF-NOT: self
//===--- Test that we can code complete at the beginning of expr-postfix.
func testExprPostfixBegin1(fooParam: FooStruct) {
#^EXPR_POSTFIX_BEGIN_1^#
}
func testExprPostfixBegin2(fooParam: FooStruct) {
1 + #^EXPR_POSTFIX_BEGIN_2^#
}
func testExprPostfixBegin3(fooParam: FooStruct) {
fooFunc()
1 + #^EXPR_POSTFIX_BEGIN_3^#
}
func testExprPostfixBegin4(fooParam: FooStruct) {
"\(#^EXPR_POSTFIX_BEGIN_4^#)"
}
func testExprPostfixBegin3(fooParam: FooStruct) {
1+#^EXPR_POSTFIX_BEGIN_5^#
}
func testExprPostfixBegin3(fooParam: FooStruct) {
for i in 1...#^EXPR_POSTFIX_BEGIN_6^#
}
//===--- Test that we sometimes ignore the expr-postfix.
// In these cases, displaying '.instance*' completion results is technically
// valid, but would be extremely surprising.
func testExprPostfixBeginIgnored1(fooParam: FooStruct) {
fooFunc()
#^EXPR_POSTFIX_BEGIN_IGNORED_1^#
}
func testExprPostfixBeginIgnored2(fooParam: FooStruct) {
123456789
#^EXPR_POSTFIX_BEGIN_IGNORED_2^#
}
func testExprPostfixBeginIgnored3(fooParam: FooStruct) {
123456789 +
fooFunc()
#^EXPR_POSTFIX_BEGIN_IGNORED_3^#
}
//===--- Test that we include function parameters in completion results.
func testFindFuncParam1(fooParam: FooStruct, a: Int, b: Float, c: inout Double)(d: inout Double) {
#^FIND_FUNC_PARAM_1^#
// FIND_FUNC_PARAM_1: Begin completions
// FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}}
// FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: c[#inout Double#]{{; name=.+$}}
// FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: d[#inout Double#]{{; name=.+$}}
// FIND_FUNC_PARAM_1: End completions
}
func testFindFuncParam2<Foo : FooProtocol>(fooParam: FooStruct, foo: Foo) {
#^FIND_FUNC_PARAM_2^#
// FIND_FUNC_PARAM_2: Begin completions
// FIND_FUNC_PARAM_2-DAG: Decl[GenericTypeParam]/Local: Foo[#Foo#]{{; name=.+$}}
// FIND_FUNC_PARAM_2-DAG: Decl[LocalVar]/Local: foo[#Foo#]{{; name=.+$}}
// FIND_FUNC_PARAM_2: End completions
}
struct TestFindFuncParam3_4 {
func testFindFuncParam3(a: Int, b: Float)(c: Double) {
#^FIND_FUNC_PARAM_3^#
// FIND_FUNC_PARAM_3: Begin completions
// FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam3_4#]{{; name=.+$}}
// FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}}
// FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: c[#Double#]{{; name=.+$}}
// FIND_FUNC_PARAM_3: End completions
}
func testFindFuncParam4<U>(a: Int, b: U) {
#^FIND_FUNC_PARAM_4^#
// FIND_FUNC_PARAM_4: Begin completions
// FIND_FUNC_PARAM_4-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}}
// FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam3_4#]{{; name=.+$}}
// FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: b[#U#]{{; name=.+$}}
// FIND_FUNC_PARAM_4: End completions
}
}
struct TestFindFuncParam5_6<T> {
func testFindFuncParam5(a: Int, b: T) {
#^FIND_FUNC_PARAM_5^#
// FIND_FUNC_PARAM_5: Begin completions
// FIND_FUNC_PARAM_5-DAG: Decl[GenericTypeParam]/CurrNominal: T[#T#]{{; name=.+$}}
// FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam5_6<T>#]{{; name=.+$}}
// FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}}
// FIND_FUNC_PARAM_5: End completions
}
func testFindFuncParam6<U>(a: Int, b: T, c: U) {
#^FIND_FUNC_PARAM_6^#
// FIND_FUNC_PARAM_6: Begin completions
// FIND_FUNC_PARAM_6-DAG: Decl[GenericTypeParam]/CurrNominal: T[#T#]{{; name=.+$}}
// FIND_FUNC_PARAM_6-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}}
// FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam5_6<T>#]{{; name=.+$}}
// FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}}
// FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: c[#U#]{{; name=.+$}}
// FIND_FUNC_PARAM_6: End completions
}
}
class TestFindFuncParam7 {
func testFindFuncParam7(a: Int, b: Float)(c: Double) {
#^FIND_FUNC_PARAM_7^#
// FIND_FUNC_PARAM_7: Begin completions
// FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam7#]{{; name=.+$}}
// FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}}
// FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: c[#Double#]{{; name=.+$}}
// FIND_FUNC_PARAM_7: End completions
}
}
func testFindFuncParamSelector1(a: Int, b x: Float, foo fooParam: FooStruct, bar barParam: inout FooStruct) {
#^FIND_FUNC_PARAM_SELECTOR_1^#
// FIND_FUNC_PARAM_SELECTOR_1: Begin completions
// FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: x[#Float#]{{; name=.+$}}
// FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: barParam[#inout FooStruct#]{{; name=.+$}}
// FIND_FUNC_PARAM_SELECTOR_1: End completions
}
//===--- Test that we include constructor parameters in completion results.
class TestFindConstructorParam1 {
init(a: Int, b: Float) {
#^FIND_CONSTRUCTOR_PARAM_1^#
// FIND_CONSTRUCTOR_PARAM_1: Begin completions
// FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam1#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_1: End completions
}
}
struct TestFindConstructorParam2 {
init(a: Int, b: Float) {
#^FIND_CONSTRUCTOR_PARAM_2^#
// FIND_CONSTRUCTOR_PARAM_2: Begin completions
// FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam2#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_2: End completions
}
}
class TestFindConstructorParam3 {
init<U>(a: Int, b: U) {
#^FIND_CONSTRUCTOR_PARAM_3^#
// FIND_CONSTRUCTOR_PARAM_3: Begin completions
// FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam3#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: b[#U#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_3: End completions
}
}
class TestFindConstructorParam4<T> {
init(a: Int, b: T) {
#^FIND_CONSTRUCTOR_PARAM_4^#
// FIND_CONSTRUCTOR_PARAM_4: Begin completions
// FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[GenericTypeParam]/CurrNominal: T[#T#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam4<T>#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_4: End completions
}
}
class TestFindConstructorParam5<T> {
init<U>(a: Int, b: T, c: U) {
#^FIND_CONSTRUCTOR_PARAM_5^#
// FIND_CONSTRUCTOR_PARAM_5: Begin completions
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[GenericTypeParam]/CurrNominal: T[#T#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam5<T>#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: c[#U#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5: End completions
}
}
class TestFindConstructorParamSelector1 {
init(a x: Int, b y: Float) {
#^FIND_CONSTRUCTOR_PARAM_SELECTOR_1^#
// FIND_CONSTRUCTOR_PARAM_SELECTOR_1: Begin completions
// FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParamSelector1#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: y[#Float#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_SELECTOR_1: End completions
}
}
//===--- Test that we include destructor's 'self' in completion results.
class TestFindDestructorParam1 {
deinit {
#^FIND_DESTRUCTOR_PARAM_1^#
// FIND_DESTRUCTOR_PARAM_1: Begin completions
// FIND_DESTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: self[#TestFindDestructorParam1#]{{; name=.+$}}
// FIND_DESTRUCTOR_PARAM_1: End completions
}
}
class TestFindDestructorParam2<T> {
deinit {
#^FIND_DESTRUCTOR_PARAM_2^#
// FIND_DESTRUCTOR_PARAM_2: Begin completions
// FIND_DESTRUCTOR_PARAM_2-DAG: Decl[GenericTypeParam]/CurrNominal: T[#T#]{{; name=.+$}}
// FIND_DESTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: self[#TestFindDestructorParam2<T>#]{{; name=.+$}}
// FIND_DESTRUCTOR_PARAM_2: End completions
}
}
struct TestPlaceholdersInNames {
var <#placeholder_in_name1#>: FooStruct
func test() {
var <#placeholder_in_name2#>: FooStruct
#^NO_PLACEHOLDER_NAMES_1^#
}
// NO_PLACEHOLDER_NAMES_1-NOT: placeholder_in_name
}
//===--- Test that we don't crash in constructors and destructors in contexts
//===--- where they are not allowed.
init() {
var fooParam = FooStruct()
#^IN_INVALID_1^#
}
init { // Missing parameters
var fooParam = FooStruct()
#^IN_INVALID_2^#
}
deinit {
var fooParam = FooStruct()
#^IN_INVALID_3^#
}
func testInInvalid5() {
var fooParam = FooStruct()
init() {
#^IN_INVALID_5^#
}
}
func testInInvalid6() {
deinit {
var fooParam = FooStruct()
#^IN_INVALID_6^#
}
}
struct TestInInvalid7 {
deinit {
var fooParam = FooStruct()
#^IN_INVALID_7^#
}
}
func foo() -> Undeclared {
var fooParam = FooStruct()
#^IN_INVALID_8^#
}
func testGenericTypealias1() {
typealias MyAlias<T> = (T, T)
let x: MyAlias<Int> = (1, 2)
var y: (Int, Int)
y = #^GENERIC_TYPEALIAS_1^#
}
// FIXME: should we use the alias name in the annotation?
// MY_ALIAS: Decl[TypeAlias]/Local: MyAlias[#(T, T)#];
// MY_ALIAS: Decl[LocalVar]/Local/TypeRelation[Identical]: x[#(Int, Int)#];
// MY_ALIAS: Decl[LocalVar]/Local/TypeRelation[Identical]: y[#(Int, Int)#];
func testGenericTypealias2() {
typealias MyAlias<T> = (T, T)
let x: (Int, Int) = (1, 2)
var y: MyAlias<Int>
y = #^GENERIC_TYPEALIAS_2^#
}
func testInForEach1(arg: Int) {
let local = 2
for index in #^IN_FOR_EACH_1^# {
let inBody = 3
}
let after = 4
// IN_FOR_EACH_1-NOT: Decl[LocalVar]
// IN_FOR_EACH_1: Decl[LocalVar]/Local: local[#Int#];
// FIXME: shouldn't show 'after' here.
// IN_FOR_EACH_1: Decl[LocalVar]/Local: after[#Int#];
// IN_FOR_EACH_1: Decl[LocalVar]/Local: arg[#Int#];
// IN_FOR_EACH_1-NOT: Decl[LocalVar]
}
func testInForEach2(arg: Int) {
let local = 2
for index in 1 ... #^IN_FOR_EACH_2^# {
let inBody = 3
}
let after = 4
}
func testInForEach3(arg: Int) {
let local = 2
for index: Int in 1 ... 2 where #^IN_FOR_EACH_3^# {
let inBody = 3
}
let after = 4
// IN_FOR_EACH_3-NOT: Decl[LocalVar]
// IN_FOR_EACH_3: Decl[LocalVar]/Local: index[#Int#];
// IN_FOR_EACH_3-NOT: Decl[LocalVar]
// IN_FOR_EACH_3: Decl[LocalVar]/Local: local[#Int#];
// FIXME: shouldn't show 'after' here.
// IN_FOR_EACH_3: Decl[LocalVar]/Local: after[#Int#];
// IN_FOR_EACH_3: Decl[LocalVar]/Local: arg[#Int#];
// IN_FOR_EACH_3-NOT: Decl[LocalVar]
}
func testInForEach4(arg: Int) {
let local = 2
for index in 1 ... 2 {
#^IN_FOR_EACH_4^#
}
let after = 4
}
| apache-2.0 | bbd4feadc06e306ce985c361be34cf35 | 44.030635 | 187 | 0.678847 | 3.166974 | false | true | false | false |
MarvinNazari/ICSPullToRefresh.Swift | ICSPullToRefresh/NVActivityIndicatorView.swift | 1 | 7406 | //
// NVActivityIndicatorView.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/21/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
public enum NVActivityIndicatorType {
case Blank
case BallPulse
case BallGridPulse
case BallClipRotate
case SquareSpin
case BallClipRotatePulse
case BallClipRotateMultiple
case BallPulseRise
case BallRotate
case CubeTransition
case BallZigZag
case BallZigZagDeflect
case BallTrianglePath
case BallScale
case LineScale
case LineScaleParty
case BallScaleMultiple
case BallPulseSync
case BallBeat
case LineScalePulseOut
case LineScalePulseOutRapid
case BallScaleRipple
case BallScaleRippleMultiple
case BallSpinFadeLoader
case LineSpinFadeLoader
case TriangleSkewSpin
case Pacman
case BallGridBeat
case SemiCircleSpin
}
public class NVActivityIndicatorView: UIView {
private let DEFAULT_TYPE: NVActivityIndicatorType = .Pacman
private let DEFAULT_COLOR = UIColor.whiteColor()
private let DEFAULT_SIZE: CGSize = CGSize(width: 40, height: 40)
private var type: NVActivityIndicatorType
private var color: UIColor
private var size: CGSize
var animating: Bool = false
var hidesWhenStopped: Bool = true
/**
Create a activity indicator view with default type, color and size
This is used by storyboard to initiate the view
- Default type is pacman\n
- Default color is white\n
- Default size is 40
- parameter decoder:
- returns: The activity indicator view
*/
required public init?(coder aDecoder: NSCoder) {
self.type = DEFAULT_TYPE
self.color = DEFAULT_COLOR
self.size = DEFAULT_SIZE
super.init(coder: aDecoder);
}
/**
Create a activity indicator view with specified type, color, size and size
- parameter frame: view's frame
- parameter type: animation type, value of NVActivityIndicatorType enum
- parameter color: color of activity indicator view
- parameter size: actual size of animation in view
- returns: The activity indicator view
*/
public init(frame: CGRect, type: NVActivityIndicatorType, color: UIColor?, size: CGSize?) {
self.type = type
self.color = DEFAULT_COLOR
self.size = DEFAULT_SIZE
super.init(frame: frame)
if let _color = color {
self.color = _color
}
if let _size = size {
self.size = _size
}
}
/**
Create a activity indicator view with specified type, color and default size
- Default size is 40
- parameter frame: view's frame
- parameter value: animation type, value of NVActivityIndicatorType enum
- parameter color: color of activity indicator view
- returns: The activity indicator view
*/
convenience public init(frame: CGRect, type: NVActivityIndicatorType, color: UIColor?) {
self.init(frame: frame, type: type, color: color, size: nil)
}
/**
Create a activity indicator view with specified type and default color, size
- Default color is white
- Default size is 40
- parameter view: view's frame
- parameter value: animation type, value of NVActivityIndicatorType enum
- returns: The activity indicator view
*/
convenience public init(frame: CGRect, type: NVActivityIndicatorType) {
self.init(frame: frame, type: type, color: nil)
}
/**
Start animation
*/
public func startAnimation() {
if (self.layer.sublayers == nil) {
setUpAnimation()
}
if hidesWhenStopped && hidden {
hidden = false
}
self.layer.speed = 1
self.animating = true
}
/**
Stop animation
*/
public func stopAnimation() {
self.layer.speed = 0
self.animating = false
if hidesWhenStopped && !hidden {
hidden = true
}
}
// MARK: Privates
private func setUpAnimation() {
let animation: protocol<NVActivityIndicatorAnimationDelegate> = animationOfType(self.type)
self.layer.sublayers = nil
animation.setUpAnimationInLayer(self.layer, size: self.size, color: self.color)
}
private func animationOfType(type: NVActivityIndicatorType) -> protocol<NVActivityIndicatorAnimationDelegate> {
switch type {
case .Blank:
return NVActivityIndicatorAnimationBlank()
case .BallPulse:
return NVActivityIndicatorAnimationBallPulse()
case .BallGridPulse:
return NVActivityIndicatorAnimationBallGridPulse()
case .BallClipRotate:
return NVActivityIndicatorAnimationBallClipRotate()
case .SquareSpin:
return NVActivityIndicatorAnimationSquareSpin()
case .BallClipRotatePulse:
return NVActivityIndicatorAnimationBallClipRotatePulse()
case .BallClipRotateMultiple:
return NVActivityIndicatorAnimationBallClipRotateMultiple()
case .BallPulseRise:
return NVActivityIndicatorAnimationBallPulseRise()
case .BallRotate:
return NVActivityIndicatorAnimationBallRotate()
case .CubeTransition:
return NVActivityIndicatorAnimationCubeTransition()
case .BallZigZag:
return NVActivityIndicatorAnimationBallZigZag()
case .BallZigZagDeflect:
return NVActivityIndicatorAnimationBallZigZagDeflect()
case .BallTrianglePath:
return NVActivityIndicatorAnimationBallTrianglePath()
case .BallScale:
return NVActivityIndicatorAnimationBallScale()
case .LineScale:
return NVActivityIndicatorAnimationLineScale()
case .LineScaleParty:
return NVActivityIndicatorAnimationLineScaleParty()
case .BallScaleMultiple:
return NVActivityIndicatorAnimationBallScaleMultiple()
case .BallPulseSync:
return NVActivityIndicatorAnimationBallPulseSync()
case .BallBeat:
return NVActivityIndicatorAnimationBallBeat()
case .LineScalePulseOut:
return NVActivityIndicatorAnimationLineScalePulseOut()
case .LineScalePulseOutRapid:
return NVActivityIndicatorAnimationLineScalePulseOutRapid()
case .BallScaleRipple:
return NVActivityIndicatorAnimationBallScaleRipple()
case .BallScaleRippleMultiple:
return NVActivityIndicatorAnimationBallScaleRippleMultiple()
case .BallSpinFadeLoader:
return NVActivityIndicatorAnimationBallSpinFadeLoader()
case .LineSpinFadeLoader:
return NVActivityIndicatorAnimationLineSpinFadeLoader()
case .TriangleSkewSpin:
return NVActivityIndicatorAnimationTriangleSkewSpin()
case .Pacman:
return NVActivityIndicatorAnimationPacman()
case .BallGridBeat:
return NVActivityIndicatorAnimationBallGridBeat()
case .SemiCircleSpin:
return NVActivityIndicatorAnimationSemiCircleSpin()
}
}
}
| mit | 380965d9f683f9abaf96edc3fc9f4442 | 32.0625 | 115 | 0.658385 | 5.781421 | false | false | false | false |
devpunk/velvet_room | Source/View/Connecting/VConnecting.swift | 1 | 2778 | import UIKit
final class VConnecting:ViewMain
{
weak var viewStatus:View<ArchConnecting>?
private(set) weak var button:UIButton!
private weak var layoutCancelLeft:NSLayoutConstraint!
private let kCancelBottom:CGFloat = -80
private let kCancelHeight:CGFloat = 45
private let kCancelWidth:CGFloat = 140
required init(controller:UIViewController)
{
super.init(controller:controller)
guard
let controller:CConnecting = controller as? CConnecting
else
{
return
}
factoryViews(controller:controller)
updateStatus()
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
let width:CGFloat = bounds.width
let remainCancel:CGFloat = width - kCancelWidth
let cancelLeft:CGFloat = remainCancel / 2.0
layoutCancelLeft.constant = cancelLeft
super.layoutSubviews()
}
//MARK: selectors
@objc
private func selectorCancel(sender button:UIButton)
{
guard
let controller:CConnecting = self.controller as? CConnecting
else
{
return
}
controller.cancelConnection()
}
//MARK: private
private func factoryViews(controller:CConnecting)
{
let viewGradient:VGradient = VGradient.vertical(
colourTop:UIColor.colourGradientLight,
colourBottom:UIColor.colourGradientDark)
let button:UIButton = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(
UIColor(white:1, alpha:0.6),
for:UIControlState.normal)
button.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
button.titleLabel!.font = UIFont.regular(size:17)
button.addTarget(
self,
action:#selector(selectorCancel(sender:)),
for:UIControlEvents.touchUpInside)
self.button = button
addSubview(viewGradient)
addSubview(button)
NSLayoutConstraint.equals(
view:viewGradient,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:button,
toView:self,
constant:kCancelBottom)
NSLayoutConstraint.height(
view:button,
constant:kCancelHeight)
NSLayoutConstraint.width(
view:button,
constant:kCancelWidth)
layoutCancelLeft = NSLayoutConstraint.leftToLeft(
view:button,
toView:self)
}
}
| mit | 192efd146f0c5cd59338115e97179a5b | 25.457143 | 72 | 0.588193 | 5.332054 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | source/Core/Classes/EnhancedMultipleChoice/RSEnhancedMultipleChoiceCellWithNumericScaleAccessoryController.swift | 1 | 3509 | //
// RSEnhancedMultipleChoiceCellWithNumericScaleAccessoryController.swift
// ResearchSuiteExtensions
//
// Created by James Kizer on 4/26/18.
//
import UIKit
import ResearchKit
open class RSEnhancedMultipleChoiceCellWithNumericScaleAccessoryController: RSEnhancedMultipleChoiceBaseCellController {
override open class func supports(textChoice: RSTextChoiceWithAuxiliaryAnswer) -> Bool {
return (textChoice.auxiliaryItem?.answerFormat as? RSEnhancedScaleAnswerFormat) != nil
}
open override class func generate(textChoice: RSTextChoiceWithAuxiliaryAnswer, choiceSelection: RSEnahncedMultipleChoiceSelection?, onValidationFailed: ((String) -> ())?, onAuxiliaryItemResultChanged: (() -> ())?) -> RSEnhancedMultipleChoiceCellController? {
return self.init(
textChoice: textChoice,
choiceSelection: choiceSelection,
onValidationFailed: onValidationFailed,
onAuxiliaryItemResultChanged: onAuxiliaryItemResultChanged
)
}
var answerFormat: RSEnhancedScaleAnswerFormat {
return (self.auxiliaryItem?.answerFormat as? RSEnhancedScaleAnswerFormat)!
}
var accessoryView: RSSliderView?
open override func viewForAuxiliaryItem(item: ORKFormItem, cell: RSEnhancedMultipleChoiceCell) -> UIView? {
if let accessoryView = self.accessoryView {
return accessoryView
}
else {
guard let auxItem = self.auxiliaryItem,
let answerFormat = auxItem.answerFormat as? RSEnhancedScaleAnswerFormat,
let sliderView = RSSliderView.newView(minimumValue: answerFormat.minimum, maximumValue: answerFormat.maximum) else {
return nil
}
assert(auxItem == item)
sliderView.minValueLabel.text = answerFormat.minValueLabel
sliderView.maxValueLabel.text = answerFormat.maxValueLabel
sliderView.minValueDescriptionLabel.text = answerFormat.minimumValueDescription
sliderView.neutralValueDescriptionLabel.text = answerFormat.neutralValueDescription
sliderView.maxValueDescriptionLabel.text = answerFormat.maximumValueDescription
sliderView.textLabel.text = item.text
sliderView.onValueChanged = { value, touched in
if value >= answerFormat.minimum && value <= answerFormat.maximum {
sliderView.currentValueLabel.text = "\(value)"
let numericResult = ORKNumericQuestionResult(identifier: item.identifier)
numericResult.numericAnswer = NSNumber(value: value)
self.validatedResult = numericResult
}
else {
self.validatedResult = nil
}
}
if let result = self.validatedResult as? ORKNumericQuestionResult,
let numericAnswer = result.numericAnswer {
sliderView.setValue(value: numericAnswer.intValue, animated: false)
}
else {
sliderView.setValue(value: answerFormat.defaultValue, animated: false)
}
sliderView.setNeedsLayout()
self.accessoryView = sliderView
return sliderView
}
}
}
| apache-2.0 | f0db8b4f4dba15debd5c503765bb47e0 | 38.426966 | 262 | 0.626104 | 6.403285 | false | false | false | false |
dvor/Antidote | Antidote/ChatOutgoingCallCell.swift | 2 | 2588 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import SnapKit
private struct Constants {
static let RightOffset = -20.0
static let ImageViewToLabelOffset = -5.0
static let ImageViewYOffset = -1.0
static let VerticalOffset = 8.0
}
class ChatOutgoingCallCell: ChatMovableDateCell {
fileprivate var callImageView: UIImageView!
fileprivate var label: UILabel!
override func setupWithTheme(_ theme: Theme, model: BaseCellModel) {
super.setupWithTheme(theme, model: model)
guard let outgoingModel = model as? ChatOutgoingCallCellModel else {
assert(false, "Wrong model \(model) passed to cell \(self)")
return
}
label.textColor = theme.colorForType(.ChatListCellMessage)
callImageView.tintColor = theme.colorForType(.LinkText)
if outgoingModel.answered {
label.text = String(localized: "chat_call_message") + String(timeInterval: outgoingModel.callDuration)
}
else {
label.text = String(localized: "chat_unanwered_call")
}
}
override func createViews() {
super.createViews()
let image = UIImage.templateNamed("start-call-small")
callImageView = UIImageView(image: image)
movableContentView.addSubview(callImageView)
label = UILabel()
label.font = UIFont.antidoteFontWithSize(16.0, weight: .light)
movableContentView.addSubview(label)
}
override func installConstraints() {
super.installConstraints()
callImageView.snp.makeConstraints {
$0.centerY.equalTo(label).offset(Constants.ImageViewYOffset)
$0.trailing.equalTo(label.snp.leading).offset(Constants.ImageViewToLabelOffset)
}
label.snp.makeConstraints {
$0.top.equalTo(contentView).offset(Constants.VerticalOffset)
$0.bottom.equalTo(contentView).offset(-Constants.VerticalOffset)
$0.trailing.equalTo(movableContentView).offset(Constants.RightOffset)
}
}
}
// Accessibility
extension ChatOutgoingCallCell {
override var accessibilityLabel: String? {
get {
return label.text
}
set {}
}
}
// ChatEditable
extension ChatOutgoingCallCell {
override func shouldShowMenu() -> Bool {
return true
}
override func menuTargetRect() -> CGRect {
return label.frame
}
}
| mit | 7b16d43af388d98d8e1b9789f2c76405 | 29.093023 | 114 | 0.662674 | 4.516579 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 02--Fourth-Dimensionally/Human/Human.playground/Contents.swift | 1 | 10144 | //: # 02 -- Human -- Pedro Trujillo
//: 1. *Create a Playground named Human.*
///OK
//: 2. *Make a class named BodyPart.*
class BodyPart
{
let Name: String
let id:Int
init( Name: String, id:Int)
{
self.Name = Name
self.id = id
}
func getName()->String
{return Name}
func getId()->Int
{return id}
}
//: 3. *Create 20 classes that are subclasses of BodyPart.*
//: - **1. Class Brain**
class Brain: BodyPart
{
var isSleeping:Bool
var isThinking:Bool
var emotionsDic:Dictionary<String, Double>
init()
{
self.isSleeping = false
self.isThinking = true
self.emotionsDic = [String:Double]()
super.init( Name: "Brain", id: 1)
}
func setThinkingState()
{
self.isThinking = !isThinking
}
func setSleeping()
{
self.isSleeping = !isSleeping
}
func setEmotion(emotion:String, value:Double)
{
self.emotionsDic[emotion]=value
}
}
//: - **2. Class Heart**
class Heart: BodyPart
{
var heartbeat:Double
var ventriclesDic:Dictionary<String, Bool>
var atriumsDic:Dictionary<String, Bool>
init(heartbeat:Double)
{
self.heartbeat = heartbeat
self.ventriclesDic = [String: Bool]()
self.atriumsDic = [String: Bool]()
super.init( Name: "Heart", id: 2)
}
func setVentricles(ventricle:String, status:Bool)
{
self.atriumsDic[ventricle]=status
}
func setHeartbeat(heartbeat:Double)
{
self.heartbeat = heartbeat
}
func setAtriums(atrium:String, status:Bool)
{
self.atriumsDic[atrium]=status
}
}
//: - **3. Class Lungs**
class Lung: BodyPart
{
var inhale:Bool
var capacity:Double
var positionLeft:Bool
init(inhale:Bool, capacity:Double, positionLeft:Bool)
{
self.inhale = inhale
self.capacity = capacity
self.positionLeft = positionLeft
super.init( Name: "Lung", id: 3)
}
func getPosition()->String
{
if self.positionLeft
{return "Left"}
else
{return "right"}
}
func setInhale()
{
self.inhale = !self.inhale
}
func setCapacity(capacity:Double)
{
self.capacity = capacity
}
}
//: - **4. Class Stomach**
class Stomach: BodyPart
{
var empty:Bool
var capacity:Double
var digesting:Bool
init(empty:Bool, capacity:Double, digesting:Bool)
{
self.empty = empty
self.capacity = capacity
self.digesting = digesting
super.init( Name: "Stomach", id: 4)
}
func isEmpty()->Bool
{
return empty
}
func setDigesting()
{
self.digesting = !self.digesting
}
func setCapacity(capacity:Double)
{
self.capacity = capacity
}
}
//: - **5. Class Kidney**
class Kidney: BodyPart
{
var excretion:Double
var filtration:Double
var positionLeft:Bool
init(excretion:Double, filtration:Double, positionLeft:Bool)
{
self.excretion = excretion
self.filtration = filtration
self.positionLeft = positionLeft
super.init( Name: "Kidney", id: 5)
}
func getPosition()->String
{
if self.positionLeft
{return "Left"}
else
{return "right"}
}
func getExcretion()->Double
{
return self.excretion
}
func setFiltration(filtration:Double)
{
self.filtration = filtration
}
}
//: - **6. Class Muscle**
class Muscle: BodyPart
{
var contract:Bool
var strength:Double
var tired:Bool
init(contract:Bool, strength:Double, tired:Bool)
{
self.contract = contract
self.strength = strength
self.tired = tired
super.init( Name: "Muscle", id: 6)
}
func isContract()->Bool
{
return contract
}
func isTired()->Bool
{
return self.tired
}
func setStrength(strength:Double)
{
self.strength = strength
}
}
//: - **7. Class Bone**
class Bone: BodyPart
{
var kindOf:String
var length:Double
var articulate:Bool
init(kindOf:String, length:Double, articulate:Bool)
{
self.kindOf = kindOf
self.length = length
self.articulate = articulate
super.init( Name: "Bone", id: 7)
}
func setKindOf(kindOf:String)
{
self.kindOf = kindOf
}
func isArticulate()->Bool
{
return self.articulate
}
func setLength(length:Double)
{
self.length = length
}
}
//: - **8. Class Blood**
class Blood: BodyPart
{
var RH:String
var quantity:Double
var presure:Double
init(RH:String, quantity:Double, presure:Double)
{
self.RH = RH
self.quantity = quantity
self.presure = presure
super.init( Name: "Blood", id: 8)
}
func getRH()->String
{
return self.RH
}
func getPresure()->Double
{
return self.presure
}
func setQuantity(quantity:Double)
{
self.quantity = quantity
}
}
//: - **9. Class Skin**
class Skin: BodyPart
{
var color:String
var length:Double
var hydrated:Bool
init(color:String, length:Double, hydrated:Bool)
{
self.color = color
self.length = length
self.hydrated = hydrated
super.init( Name: "Skin", id: 9)
}
func setColor(color:String)
{
self.color = color
}
func isHydrated()->Bool
{
return self.hydrated
}
func setLength(length:Double)
{
self.length = length
}
}
//: - **10. Class ears**
class Ear: BodyPart
{
var listening:Bool
var hearingCapacity:Double
var positionLeft:Bool
init(listening:Bool, hearingCapacity:Double, positionLeft:Bool)
{
self.listening = listening
self.hearingCapacity = hearingCapacity
self.positionLeft = positionLeft
super.init( Name: "Ear", id: 10)
}
func getPosition()->String
{
if self.positionLeft
{return "Left"}
else
{return "right"}
}
func setListening()
{
self.listening = !self.listening
}
func sethearingCapacity(hearingCapacity:Double)
{
self.hearingCapacity = hearingCapacity
}
}
//: - **11. Class eye**
class Eye: BodyPart
{
var color:String
var visualCapacity:Double
var positionLeft:Bool
init(color:String, visualCapacity:Double, positionLeft:Bool)
{
self.color = color
self.visualCapacity = visualCapacity
self.positionLeft = positionLeft
super.init( Name: "Eye", id: 11)
}
func getPosition()->String
{
if self.positionLeft
{return "Left"}
else
{return "right"}
}
func setColor(color:String)
{
self.color = color
}
func setvisualCapacity(visualCapacity:Double)
{
self.visualCapacity = visualCapacity
}
}
//: - **12. Class Head**
class Head: BodyPart
{
var brain:Brain
var leftEye:Eye
var rightEye:Eye
init(eyeColor:String, visualCapacity:Double)
{
self.brain = Brain()
self.leftEye = Eye(color: eyeColor, visualCapacity: visualCapacity, positionLeft: true)
self.rightEye = Eye(color: eyeColor, visualCapacity: visualCapacity, positionLeft: false)
super.init( Name: "Head", id: 12)
}
func printEyesPosition()
{
print("Position left eye: \(self.leftEye.getPosition())")
print("Position right eye: \(self.rightEye.getPosition())")
}
func setColorEyes(col:String)
{
self.leftEye.setColor(col)
self.rightEye.setColor(col)
}
func setEyeVisualCapacity(visualCapacity:Double)
{
self.leftEye.visualCapacity = visualCapacity
self.leftEye.visualCapacity = visualCapacity
}
}
//: - **13. Class Intestine**
class Intestine: BodyPart
{
var full:Bool
var capacity:Double
var digesting:Bool
init(full:Bool, capacity:Double, digesting:Bool)
{
self.full = full
self.capacity = capacity
self.digesting = digesting
super.init( Name: "Intestine", id: 13)
}
func isFull()->Bool
{
return full
}
func setDigesting()
{
self.digesting = !self.digesting
}
func setCapacity(capacity:Double)
{
self.capacity = capacity
}
}
//: - **14. Class DegistiveSystem**
class DigestiveSystem: BodyPart
{
var stomach:Stomach
var largeIntestine:Intestine
var smallIntestine:Intestine
init(Capacity:Double, digesting: Bool)
{
self.stomach = Stomach(empty: true, capacity: Capacity, digesting: digesting)
largeIntestine = Intestine(full:true, capacity:Capacity*2, digesting:true)
smallIntestine = Intestine(full:false, capacity:3.0, digesting:true)
super.init( Name: "DegistiveSystem", id: 14)
}
}
//: - **15. Class Torso**
class Torso: BodyPart
{
var head:Head
var heart:Heart
var digestiveSystem:DigestiveSystem
init(color:String, visualCapacity:Double, positionLeft:Bool, Capacity:Double)
{
self.head = Head(eyeColor:"Blue", visualCapacity:22.0)
self.heart = Heart(heartbeat: 30)
self.digestiveSystem = DigestiveSystem(Capacity: Capacity, digesting: true)
super.init( Name: "Torso", id: 15)
}
func getBodyPartID()->(head:Int, heart:Int, stomach:Int, brain: Int)
{
return (head:self.head.getId(), heart:self.heart.getId(), stomach:self.digestiveSystem.stomach.getId(), brain: self.head.brain.getId())
}
}
| cc0-1.0 | 9a2d2ce197d67d7b53c1a240af905a8b | 18.47025 | 143 | 0.571076 | 3.864381 | false | false | false | false |
SmallElephant/FEDesignPattern | 9-CompositePattern/9-CompositePattern/ViewController.swift | 1 | 1589 | //
// ViewController.swift
// 9-CompositePattern
//
// Created by keso on 2017/6/4.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setUp()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setUp() {
// root/study/composite.Swift
// root/study.html
let rootDir:Directory = Directory(name: "root", parent: nil)
let file:File = File(name: "study.html", parent: rootDir)
let file2:File = File(name: "readme.txt", parent: rootDir)
let studyDir:Directory = Directory(name: "study", parent: rootDir)
let file3:File = File(name: "composite.swift", parent: studyDir)
let file4:File = File(name: "study.project", parent: studyDir)
rootDir.addEntry(entry: file)
rootDir.addEntry(entry: file2)
rootDir.addEntry(entry: studyDir)
studyDir.addEntry(entry: file3)
studyDir.addEntry(entry: file4)
rootDir.printnEntry()
print("FlyElephant---删除文件夹")
rootDir.deleteEntry(entry:studyDir)
rootDir.printnEntry()
print("FlyElephant---删除文件")
rootDir.deleteEntry(entry:file2)
rootDir.printnEntry()
}
}
| mit | 6afd8466a6947264198e8a560a3eeeef | 26.508772 | 80 | 0.609056 | 4.137203 | false | false | false | false |
coolbnjmn/CBPhotoPicker | CBPhotoPicker/CBImageView.swift | 1 | 3652 | //
// CBImageView.swift
// CBPhotoPicker
//
// Created by Benjamin Hendricks on 11/15/15.
// Copyright © 2015 coolbnjmn. All rights reserved.
//
import UIKit
extension CGRect {
func scale(scale: CGFloat) -> CGRect {
return CGRectMake(origin.x * scale, origin.y * scale, size.width * scale, size.height * scale)
}
}
public class CBImageView: UIScrollView {
var imageView: UIImageView?
var animator : UIDynamicAnimator?
public var overlayDelegate : CBOverlayViewDelegate?
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
self.imageView?.image = nil
self.imageView = nil
}
func setup() {
self.clipsToBounds = false
self.showsVerticalScrollIndicator = false
self.showsHorizontalScrollIndicator = false
self.alwaysBounceHorizontal = true
self.alwaysBounceVertical = true
self.bouncesZoom = true
self.maximumZoomScale = 10
self.decelerationRate = UIScrollViewDecelerationRateFast;
self.delegate = self
imageView = UIImageView(frame: self.frame)
if let imageView = imageView {
imageView.userInteractionEnabled = true
imageView.contentMode = .ScaleAspectFit
self.addSubview(imageView)
}
}
func loadNewImage(image: UIImage) {
// reset everything
zoomScale = minimumZoomScale
if let superviewFrame = superview?.frame {
contentSize = superviewFrame.size
}
self.imageView?.image = image
setupScrollView()
}
func setupScrollView() {
if let imageSize = imageView?.image?.size where imageSize.width > imageView?.frame.size.width || imageSize.height > imageView?.frame.size.height {
self.contentSize = imageSize
self.zoomScale = self.minimumZoomScale
}
if let image = imageView?.image {
let widthScaleFactor = self.bounds.width / image.size.width
let heightScaleFactor = self.bounds.height / image.size.height
var imageViewXOrigin: CGFloat = 0
let imageViewYOrigin: CGFloat = 0
var imageViewHeight : CGFloat
var imageViewWidth : CGFloat
if widthScaleFactor > heightScaleFactor {
imageViewWidth = image.size.width * widthScaleFactor
imageViewHeight = image.size.height * widthScaleFactor
} else {
imageViewWidth = image.size.width * heightScaleFactor
imageViewHeight = image.size.height * heightScaleFactor
imageViewXOrigin = -1 * (imageViewWidth - self.bounds.width) / CGFloat(2)
}
self.imageView?.frame = CGRectMake(imageViewXOrigin,
imageViewYOrigin,
imageViewWidth,
imageViewHeight);
}
}
public func capture() -> UIImage? {
return superview?.snapshot
}
}
extension CBImageView : UIScrollViewDelegate {
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.imageView
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
overlayDelegate?.hideOverlay()
}
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
overlayDelegate?.showOverlay()
}
}
| mit | 566a05c722bf7e59e900e5ccadcffeec | 30.205128 | 154 | 0.61983 | 5.416914 | false | false | false | false |
openHPI/xikolo-ios | iOS/ViewControllers/Dashboard/CourseDateOverviewViewController.swift | 1 | 6317 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Common
import CoreData
import UIKit
class CourseDateOverviewViewController: UIViewController {
@IBOutlet private weak var summaryContainer: UIView!
@IBOutlet private weak var todayCountLabel: UILabel!
@IBOutlet private weak var nextCountLabel: UILabel!
@IBOutlet private weak var allCountLabel: UILabel!
@IBOutlet private var summaryWidthConstraint: NSLayoutConstraint!
@IBOutlet private weak var nextUpView: UIView!
@IBOutlet private weak var nextUpContainer: UIView!
@IBOutlet private weak var nextUpImageView: UIImageView!
@IBOutlet private weak var relativeDateTimeLabel: UILabel!
@IBOutlet private weak var dateLabel: UILabel!
@IBOutlet private weak var courseLabel: UILabel!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private var nextUpWidthConstraint: NSLayoutConstraint!
@IBOutlet private weak var equalTitleWrapperHeightConstraint: NSLayoutConstraint!
private lazy var courseDateFormatter: DateFormatter = {
return DateFormatter.localizedFormatter(dateStyle: .long, timeStyle: .long)
}()
private lazy var relativeCourseDateFormatter: DateFormatter = {
let formatter = DateFormatter.localizedFormatter(dateStyle: .long, timeStyle: .long)
formatter.doesRelativeDateFormatting = true
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
self.updateWidthConstraints()
self.summaryContainer.layer.roundCorners(for: .default, masksToBounds: false)
self.nextUpContainer.layer.roundCorners(for: .default, masksToBounds: false)
self.summaryContainer.addDefaultPointerInteraction()
self.nextUpContainer.addDefaultPointerInteraction()
self.courseLabel.textColor = Brand.default.colors.secondary
self.nextUpView.isHidden = true
self.nextUpContainer.isHidden = true
self.equalTitleWrapperHeightConstraint.isActive = false
self.loadData()
let summaryGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showAllCourseDates))
self.summaryContainer.addGestureRecognizer(summaryGestureRecognizer)
let nextUpGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showCourseForNextCourseDate))
self.nextUpContainer.addGestureRecognizer(nextUpGestureRecognizer)
NotificationCenter.default.addObserver(self,
selector: #selector(coreDataChange(notification:)),
name: NSNotification.Name.NSManagedObjectContextObjectsDidChange,
object: CoreDataHelper.viewContext)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.updateWidthConstraints()
}
func loadData() {
self.todayCountLabel.text = self.formattedItemCount(for: CourseDateHelper.FetchRequest.courseDatesForNextDays(numberOfDays: 1))
self.nextCountLabel.text = self.formattedItemCount(for: CourseDateHelper.FetchRequest.courseDatesForNextDays(numberOfDays: 7))
self.allCountLabel.text = self.formattedItemCount(for: CourseDateHelper.FetchRequest.allCourseDates)
if let courseDate = CoreDataHelper.viewContext.fetchSingle(CourseDateHelper.FetchRequest.nextCourseDate).value {
self.courseLabel.text = courseDate.course?.title
self.titleLabel.text = courseDate.contextAwareTitle
self.nextUpView.isHidden = false
self.nextUpContainer.isHidden = false
self.equalTitleWrapperHeightConstraint.isActive = true
if #available(iOS 13, *) {
self.nextUpImageView.image = R.image.calendarLarge()
self.relativeDateTimeLabel.text = courseDate.relativeDateTime
self.dateLabel.text = courseDate.date.map(self.courseDateFormatter.string(from:))
} else {
self.nextUpImageView.image = R.image.calendar()
self.relativeDateTimeLabel.text = nil
self.dateLabel.text = courseDate.date.map(self.relativeCourseDateFormatter.string(from:))
}
} else {
self.nextUpView.isHidden = true
self.nextUpContainer.isHidden = true
self.equalTitleWrapperHeightConstraint.isActive = false
}
}
private func formattedItemCount(for fetchRequest: NSFetchRequest<CourseDate>) -> String {
if let count = try? CoreDataHelper.viewContext.count(for: fetchRequest) {
return String(count)
} else {
return "-"
}
}
private func updateWidthConstraints() {
let courseCellWidth = CourseCell.minimalWidthInOverviewList(for: self.traitCollection)
let availableWidth = self.view.bounds.width - self.view.layoutMargins.left - self.view.layoutMargins.right + 2 * CourseCell.cardInset
let itemsPerRow = max(1, floor(availableWidth / courseCellWidth))
let cellWidth = availableWidth / itemsPerRow
self.summaryWidthConstraint.constant = cellWidth - 2 * CourseCell.cardInset
self.nextUpWidthConstraint.constant = cellWidth - 2 * CourseCell.cardInset
}
@objc private func showAllCourseDates() {
self.performSegue(withIdentifier: R.segue.courseDateOverviewViewController.showCourseDates, sender: nil)
}
@objc private func showCourseForNextCourseDate() {
guard let course = CoreDataHelper.viewContext.fetchSingle(CourseDateHelper.FetchRequest.nextCourseDate).value?.course else { return }
self.appNavigator?.show(course: course)
}
@objc private func coreDataChange(notification: Notification) {
let courseDatesChanged = notification.includesChanges(for: CourseDate.self)
let courseRefreshed = notification.includesChanges(for: Course.self, key: .refreshed)
let enrollmentRefreshed = notification.includesChanges(for: Enrollment.self, key: .refreshed)
if courseDatesChanged || courseRefreshed || enrollmentRefreshed {
self.loadData()
}
}
}
| gpl-3.0 | ef95938e382c69b5b818f74f28c0b533 | 44.768116 | 141 | 0.71026 | 5.168576 | false | false | false | false |
Judy-u/Reflect | Reflect/Reflect/Dict2Model/Reflect+Parse.swift | 4 | 5019 | //
// Reflect+Parse.swift
// Reflect
//
// Created by 成林 on 15/8/23.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
extension Reflect{
class func parsePlist(name: String) -> Self?{
//加载plist
let path = NSBundle.mainBundle().pathForResource(name+".plist", ofType: nil)
if path == nil {return nil}
let dict = NSDictionary(contentsOfFile: path!)
if dict == nil {return nil}
return parse(dict: dict!)
}
class func parses(#arr: NSArray) -> [Reflect]{
var models: [Reflect] = []
for (index, dict) in enumerate(arr){
let model = self.parse(dict: dict as! NSDictionary)
models.append(model)
}
return models
}
class func parse(#dict: NSDictionary) -> Self{
let model = self()
let mappingDict = model.mappingDict()
let ignoreProperties = model.ignorePropertiesForParse()
model.properties { (name, type, value) -> Void in
assert(type.check(), "[Charlin Feng]: Property '\(name)' type can not be a '\(type.realType.rawValue)' Type,Please use 'NSNumber' instead!")
let dataDictHasKey = dict[name] != nil
let mappdictDictHasKey = mappingDict?[name] != nil
let needIgnore = ignoreProperties == nil ? false : contains(ignoreProperties!, name)
if (dataDictHasKey || mappdictDictHasKey) && !needIgnore {
var key = mappdictDictHasKey ? mappingDict![name]! : name
if !type.isArray { //不是数组
if type.disposition != MirrorDisposition.Class { // 基本属性:String,Int,Float,Double,Bool
model.setValue(dict[key], forKeyPath: name)
}else{
model.setValue((type.typeClass as! Reflect.Type).parse(dict: dict[key] as! NSDictionary), forKeyPath: name)
}
}else{
if let res = type.isAggregate(){
var arrAggregate = []
if res is Int.Type {arrAggregate = self.parseAggregateArray(dict[key] as! NSArray, temp: 0)}
if res is Float.Type {arrAggregate = self.parseAggregateArray(dict[key] as! NSArray, temp: 0.0)}
if res is Double.Type {arrAggregate = self.parseAggregateArray(dict[key] as! NSArray, temp: 0.0)}
if res is String.Type {arrAggregate = self.parseAggregateArray(dict[key] as! NSArray, temp: "")}
model.setValue(arrAggregate, forKeyPath: name)
}else{
let elementModelType = ReflectType.makeClass(type.typeName) as! Reflect.Type
//遍历
let dictKeyArr = dict[key] as! NSArray
var arrM: [Reflect] = []
for (key, value) in enumerate(dictKeyArr) {
let elementModel = elementModelType.parse(dict: value as! NSDictionary)
arrM.append(elementModel)
}
model.setValue(arrM, forKeyPath: name)
}
}
}
}
return model
}
class func parseAggregateArray<T>(arrDict: NSArray,temp: T) -> [T]{
var intArrM: [T] = []
for (key, value) in enumerate(arrDict) {
var element: T = temp
if value is String {
if temp is Int {element = (value as! String).toInt() as! T}
if temp is Float {element = (value as! String).floatValue as! T}
if temp is Double {element = (value as! String).doubleValue as! T}
element = value as! T
}else{
element = value as! T
}
intArrM.append(element)
}
return intArrM
}
/** 字段映射 */
func mappingDict() -> [String: String]? {
return nil
}
/** 字段忽略 */
func ignorePropertiesForParse() -> [String]? {
return nil
}
}
| mit | 475c14cc455fc22b6800fe5258232776 | 30.226415 | 152 | 0.436254 | 5.350216 | false | false | false | false |
22377832/ccyswift | GCDSort/GCDSort/ViewController.swift | 1 | 2793 | //
// ViewController.swift
// GCDSort
//
// Created by sks on 17/2/20.
// Copyright © 2017年 chen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
func fileLocation() -> String? {
let folders = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if folders.count == 0{
return nil
}
let documentsFolder = folders[0] as NSString
return documentsFolder.appendingPathComponent("list5.txt")
}
func hasFileAlreadyBeenCreated() -> Bool{
let fileManager = FileManager.default
if let theLocation = fileLocation() {
return fileManager.fileExists(atPath: theLocation)
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let concurrentQueue = DispatchQueue.global()
concurrentQueue.async {
[weak self] in
let numberOfValuesRequired = 1000
if self?.hasFileAlreadyBeenCreated() == false{
concurrentQueue.sync {
var arrayOfRandomNumbers = [Int]()
for _ in 0..<numberOfValuesRequired {
let randomNumber = Int(arc4random() % 1000)
arrayOfRandomNumbers.append(randomNumber)
}
let array = arrayOfRandomNumbers as NSArray
array.write(toFile: (self?.fileLocation())!, atomically: true)
}
}
var randomNumbers: NSMutableArray?
concurrentQueue.sync {
if (self?.hasFileAlreadyBeenCreated())!{
randomNumbers = NSMutableArray(contentsOfFile: (self?.fileLocation())!)
randomNumbers?.sort(comparator: { (obj1, obj2) -> ComparisonResult in
let number1 = obj1 as! NSNumber
let number2 = obj2 as! NSNumber
return number1.compare(number2)
})
}
}
DispatchQueue.main.async {
if let numbers = randomNumbers{
if numbers.count > 0{
print(numbers)
print(numbers.count)
} else {
print("The numbers array is empty")
}
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 4541ae8dd1a04a68633edeb337a8e993 | 31.823529 | 100 | 0.534767 | 5.58 | false | false | false | false |
hsiun/yoyo | ufile/ios/demo/ufile sdk demo/ufile sdk demo/DownloadViewController.swift | 1 | 5313 |
//
// DownloadViewController.swift
// ufile sdk demo
//
// Created by wu shauk on 12/14/15.
// Copyright © 2015 ucloud. All rights reserved.
//
import UIKit
class DownloadViewController: UIViewController {
var ufileSDK: UFileSDK?
@IBOutlet weak var progress: UIProgressView!
@IBOutlet weak var rangeText: UITextField!
@IBOutlet weak var downloadFileName: UITextField!
@IBAction func downloadFile(sender: AnyObject) {
progress.setProgress(0.0, animated: true)
let range = self.rangeText.text!
let fileName = self.downloadFileName.text!
var options = [String:String]()
if !range.isEmpty {
options[kUFileSDKOptionRange] = range
}
let auth = ufileSDK!.calcKey("GET", key: fileName, contentMd5: nil, contentType: nil);
ufileSDK?.ufileSDK!.getFile(fileName, authorization: auth, option: options as [NSObject : AnyObject], progress: { (p: NSProgress) -> Void in
dispatch_async(dispatch_get_main_queue()) {
self.progress.setProgress(Float(p.fractionCompleted), animated: true)
}
},
success: {(result: [NSObject : AnyObject], responseObj: AnyObject) -> Void in
let data = responseObj as! NSData
let alert = UIAlertController(title: "File Delete Done", message: fileName + " File Downloaded, file size: " + UInt(data.length).description, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
},
failure: { (err: NSError) -> Void in
var errMsg: String? = nil;
if err.domain == kUFileSDKAPIErrorDomain {
errMsg = err.userInfo["ErrMsg"] as? NSString as? String;
NSLog("%@", err.userInfo);
} else {
errMsg = err.description
}
let alert = UIAlertController(title: "Fail Shame", message: errMsg, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
})
}
@IBAction func downloadToFile(sender: AnyObject) {
progress.setProgress(0.0, animated: true)
let range = self.rangeText.text!
let fileName = self.downloadFileName.text!
var options = [String:String]()
if !range.isEmpty {
options[kUFileSDKOptionRange] = range
}
let dirUrl = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask);
let downloadFile = NSURL(fileURLWithPath: fileName, relativeToURL: dirUrl[0])
let auth = ufileSDK!.calcKey("GET", key: fileName, contentMd5: nil, contentType: nil);
ufileSDK!.ufileSDK!.getFile(fileName, toFile: downloadFile.path!, authorization: auth, option: options as [NSObject : AnyObject],
progress: { (p: NSProgress) -> Void in
p.pause()
let delta: Int64 = 10 * Int64(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, delta)
dispatch_after(time, dispatch_get_main_queue(), {
p.resume()
})
dispatch_async(dispatch_get_main_queue()) {
self.progress.setProgress(Float(p.fractionCompleted), animated: true)
}
},
success: {(result: [NSObject : AnyObject], responseObj: AnyObject) -> Void in
let data = (responseObj as! NSURL).absoluteString
let alert = UIAlertController(title: "File Delete Done", message: fileName + " File Downloaded to " + data, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
},
failure: { (err: NSError) -> Void in
var errMsg: String? = nil;
if err.domain == kUFileSDKAPIErrorDomain {
errMsg = err.userInfo["ErrMsg"] as? NSString as? String;
NSLog("%@", err.userInfo);
} else {
errMsg = err.description
}
let alert = UIAlertController(title: "Fail Shame", message: errMsg, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
})
}
}
| apache-2.0 | 68dd703eefcd891eb48a525841258883 | 47.290909 | 203 | 0.58302 | 5.001883 | false | false | false | false |
RxSwiftCommunity/RxSwiftExt | Source/RxSwift/retryWithBehavior.swift | 1 | 4906 | //
// retryWithBehavior.swift
// RxSwiftExt
//
// Created by Anton Efimenko on 17/07/16.
// Copyright © 2016 RxSwift Community. All rights reserved.
//
import Foundation
import RxSwift
/**
Specifies how observable sequence will be repeated in case of an error.
*/
public enum RepeatBehavior {
/**
Will be immediately repeated specified number of times.
- **maxCount:** Maximum number of times to repeat the sequence.
*/
case immediate (maxCount: UInt)
/**
Will be repeated after specified delay specified number of times.
- **maxCount:** Maximum number of times to repeat the sequence.
*/
case delayed (maxCount: UInt, time: Double)
/**
Will be repeated specified number of times.
Delay will be incremented by multiplier after each iteration (multiplier = 0.5 means 50% increment).
- **maxCount:** Maximum number of times to repeat the sequence.
*/
case exponentialDelayed (maxCount: UInt, initial: Double, multiplier: Double)
/**
Will be repeated specified number of times. Delay will be calculated by custom closure.
- **maxCount:** Maximum number of times to repeat the sequence.
*/
case customTimerDelayed (maxCount: UInt, delayCalculator: (UInt) -> DispatchTimeInterval)
}
public typealias RetryPredicate = (Error) -> Bool
extension RepeatBehavior {
/**
Extracts maxCount and calculates delay for current RepeatBehavior
- parameter currentAttempt: Number of current attempt
- returns: Tuple with maxCount and calculated delay for provided attempt
*/
func calculateConditions(_ currentRepetition: UInt) -> (maxCount: UInt, delay: DispatchTimeInterval) {
switch self {
case .immediate(let max):
// if Immediate, return 0.0 as delay
return (maxCount: max, delay: .never)
case .delayed(let max, let time):
// return specified delay
return (maxCount: max, delay: .milliseconds(Int(time * 1000)))
case .exponentialDelayed(let max, let initial, let multiplier):
// if it's first attempt, simply use initial delay, otherwise calculate delay
let delay = currentRepetition == 1 ? initial : initial * pow(1 + multiplier, Double(currentRepetition - 1))
return (maxCount: max, delay: .milliseconds(Int(delay * 1000)))
case .customTimerDelayed(let max, let delayCalculator):
// calculate delay using provided calculator
return (maxCount: max, delay: delayCalculator(currentRepetition))
}
}
}
extension ObservableType {
/**
Repeats the source observable sequence using given behavior in case of an error or until it successfully terminated
- parameter behavior: Behavior that will be used in case of an error
- parameter scheduler: Schedular that will be used for delaying subscription after error
- parameter shouldRetry: Custom optional closure for checking error (if returns true, repeat will be performed)
- returns: Observable sequence that will be automatically repeat if error occurred
*/
public func retry(_ behavior: RepeatBehavior, scheduler: SchedulerType = MainScheduler.instance, shouldRetry: RetryPredicate? = nil) -> Observable<Element> {
return retry(1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry)
}
/**
Repeats the source observable sequence using given behavior in case of an error or until it successfully terminated
- parameter currentAttempt: Number of current attempt
- parameter behavior: Behavior that will be used in case of an error
- parameter scheduler: Schedular that will be used for delaying subscription after error
- parameter shouldRetry: Custom optional closure for checking error (if returns true, repeat will be performed)
- returns: Observable sequence that will be automatically repeat if error occurred
*/
internal func retry(_ currentAttempt: UInt, behavior: RepeatBehavior, scheduler: SchedulerType = MainScheduler.instance, shouldRetry: RetryPredicate? = nil)
-> Observable<Element> {
guard currentAttempt > 0 else { return Observable.empty() }
// calculate conditions for bahavior
let conditions = behavior.calculateConditions(currentAttempt)
return `catch` { error -> Observable<Element> in
// return error if exceeds maximum amount of retries
guard conditions.maxCount > currentAttempt else { return Observable.error(error) }
if let shouldRetry = shouldRetry, !shouldRetry(error) {
// also return error if predicate says so
return Observable.error(error)
}
guard conditions.delay != .never else {
// if there is no delay, simply retry
return self.retry(currentAttempt + 1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry)
}
// otherwise retry after specified delay
return Observable<Void>.just(()).delaySubscription(conditions.delay, scheduler: scheduler).flatMapLatest {
self.retry(currentAttempt + 1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry)
}
}
}
}
| mit | 6c591953c787c18eef3d255cb9c1863d | 40.218487 | 158 | 0.741081 | 4.504132 | false | false | false | false |
to4iki/conference-app-2017-ios | conference-app-2017/data/extension/UIApplicationExtension.swift | 1 | 1300 | import UIKit
extension UIApplication {
var topViewController: UIViewController? {
guard var topViewController = UIApplication.shared.keyWindow?.rootViewController else { return nil }
while case .some = topViewController.presentedViewController {
topViewController = topViewController.presentedViewController!
}
return topViewController
}
func findViewController<T: UIViewController>(_ type: T.Type) -> T? {
func go(childViewControllers: [UIViewController]) -> T? {
if let viewController: T = childViewControllers.convert(to: T.self).first {
return viewController
} else {
if childViewControllers.nonEmpty {
let grandsonViewControllers = childViewControllers.flatMap({ $0.childViewControllers })
return go(childViewControllers: grandsonViewControllers)
} else {
return nil
}
}
}
guard let topViewController = topViewController else { return nil }
if let viewController = topViewController as? T {
return viewController
} else {
return go(childViewControllers: topViewController.childViewControllers)
}
}
}
| apache-2.0 | 5b486c84f83d230135f85e9d947e78c5 | 38.393939 | 108 | 0.624615 | 6.435644 | false | false | false | false |
BryanHoke/swift-corelibs-foundation | TestFoundation/TestNSAffineTransform.swift | 1 | 3118 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
class TestNSAffineTransform : XCTestCase {
private let accuracyThreshold = 0.001
var allTests : [(String, () -> ())] {
return [
("test_BasicConstruction", test_BasicConstruction),
("test_IdentityTransformation", test_IdentityTransformation)
]
}
func test_BasicConstruction() {
let identityTransform = NSAffineTransform()
let transformStruct = identityTransform.transformStruct
// The diagonal entries (1,1) and (2,2) of the identity matrix are ones. The other entries are zeros.
// TODO: These should use DBL_MAX but it's not available as part of Glibc on Linux
XCTAssertEqualWithAccuracy(Double(transformStruct.m11), Double(1), accuracy: accuracyThreshold)
XCTAssertEqualWithAccuracy(Double(transformStruct.m22), Double(1), accuracy: accuracyThreshold)
XCTAssertEqualWithAccuracy(Double(transformStruct.m12), Double(0), accuracy: accuracyThreshold)
XCTAssertEqualWithAccuracy(Double(transformStruct.m21), Double(0), accuracy: accuracyThreshold)
XCTAssertEqualWithAccuracy(Double(transformStruct.tX), Double(0), accuracy: accuracyThreshold)
XCTAssertEqualWithAccuracy(Double(transformStruct.tY), Double(0), accuracy: accuracyThreshold)
}
func test_IdentityTransformation() {
let identityTransform = NSAffineTransform()
func checkIdentityPointTransformation(point: NSPoint) {
let newPoint = identityTransform.transformPoint(point)
XCTAssertEqualWithAccuracy(Double(newPoint.x), Double(point.x), accuracy: accuracyThreshold)
XCTAssertEqualWithAccuracy(Double(newPoint.y), Double(point.y), accuracy: accuracyThreshold)
}
checkIdentityPointTransformation(NSPoint())
checkIdentityPointTransformation(NSMakePoint(CGFloat(24.5), CGFloat(10.0)))
checkIdentityPointTransformation(NSMakePoint(CGFloat(-7.5), CGFloat(2.0)))
func checkIdentitySizeTransformation(size: NSSize) {
let newSize = identityTransform.transformSize(size)
XCTAssertEqualWithAccuracy(Double(newSize.width), Double(size.width), accuracy: accuracyThreshold)
XCTAssertEqualWithAccuracy(Double(newSize.height), Double(size.height), accuracy: accuracyThreshold)
}
checkIdentitySizeTransformation(NSSize())
checkIdentitySizeTransformation(NSMakeSize(CGFloat(13.0), CGFloat(12.5)))
checkIdentitySizeTransformation(NSMakeSize(CGFloat(100.0), CGFloat(-100.0)))
}
}
| apache-2.0 | 26fb5baa0219db2a73e4aba02eb6f1d4 | 41.135135 | 112 | 0.720013 | 5.153719 | false | true | false | false |
dusek/firefox-ios | Client/Frontend/Browser/BrowserToolbar.swift | 1 | 6228 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
protocol BrowserToolbarDelegate {
func didBeginEditing()
func didClickBack()
func didClickForward()
func didClickAddTab()
func didLongPressBack()
func didLongPressForward()
}
class BrowserToolbar: UIView, UITextFieldDelegate {
var browserToolbarDelegate: BrowserToolbarDelegate?
private var forwardButton: UIButton!
private var backButton: UIButton!
private var toolbarTextButton: UIButton!
private var tabsButton: UIButton!
private var progressBar: UIProgressView!
private var longPressGestureBackButton: UILongPressGestureRecognizer!
private var longPressGestureForwardButton: UILongPressGestureRecognizer!
override init() {
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
viewDidInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
viewDidInit()
}
private func viewDidInit() {
self.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
backButton = UIButton()
backButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
backButton.setTitle("<", forState: UIControlState.Normal)
backButton.addTarget(self, action: "SELdidClickBack", forControlEvents: UIControlEvents.TouchUpInside)
longPressGestureBackButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressBack")
backButton.addGestureRecognizer(longPressGestureBackButton)
self.addSubview(backButton)
forwardButton = UIButton()
forwardButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
forwardButton.setTitle(">", forState: UIControlState.Normal)
forwardButton.addTarget(self, action: "SELdidClickForward", forControlEvents: UIControlEvents.TouchUpInside)
longPressGestureForwardButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressForward")
forwardButton.addGestureRecognizer(longPressGestureForwardButton)
self.addSubview(forwardButton)
toolbarTextButton = UIButton()
toolbarTextButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
toolbarTextButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
toolbarTextButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
toolbarTextButton.layer.backgroundColor = UIColor.whiteColor().CGColor
toolbarTextButton.layer.cornerRadius = 8
toolbarTextButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 14)
toolbarTextButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail
toolbarTextButton.addTarget(self, action: "SELdidClickToolbar", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(toolbarTextButton)
progressBar = UIProgressView()
self.progressBar.trackTintColor = self.backgroundColor
self.addSubview(progressBar)
tabsButton = UIButton()
tabsButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
tabsButton.titleLabel?.layer.borderColor = UIColor.blackColor().CGColor
tabsButton.titleLabel?.layer.cornerRadius = 4
tabsButton.titleLabel?.layer.borderWidth = 1
tabsButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 12)
tabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
tabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(24)
return
}
tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(tabsButton)
self.backButton.snp_remakeConstraints { make in
make.left.equalTo(self)
make.centerY.equalTo(self)
make.width.height.equalTo(44)
}
self.forwardButton.snp_remakeConstraints { make in
make.left.equalTo(self.backButton.snp_right)
make.centerY.equalTo(self)
make.width.height.equalTo(44)
}
self.toolbarTextButton.snp_remakeConstraints { make in
make.left.equalTo(self.forwardButton.snp_right)
make.centerY.equalTo(self)
}
self.tabsButton.snp_remakeConstraints { make in
make.left.equalTo(self.toolbarTextButton.snp_right)
make.centerY.equalTo(self)
make.width.height.equalTo(44)
make.right.equalTo(self).offset(-8)
}
self.progressBar.snp_remakeConstraints { make in
make.centerY.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
}
func updateURL(url: NSURL?) {
toolbarTextButton.setTitle(url?.absoluteString, forState: UIControlState.Normal)
}
func updateTabCount(count: Int) {
tabsButton.setTitle(count.description, forState: UIControlState.Normal)
}
func SELdidClickBack() {
browserToolbarDelegate?.didClickBack()
}
func SELdidLongPressBack() {
browserToolbarDelegate?.didLongPressBack()
}
func SELdidClickForward() {
browserToolbarDelegate?.didClickForward()
}
func SELdidLongPressForward() {
browserToolbarDelegate?.didLongPressForward()
}
func SELdidClickAddTab() {
browserToolbarDelegate?.didClickAddTab()
}
func SELdidClickToolbar() {
browserToolbarDelegate?.didBeginEditing()
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: true)
UIView.animateWithDuration(1.5, animations: {self.progressBar.alpha = 0.0},
completion: {_ in self.progressBar.setProgress(0.0, animated: false)})
} else {
self.progressBar.alpha = 1.0
self.progressBar.setProgress(progress, animated: true)
}
}
}
| mpl-2.0 | 916357a778c0c221a0cf7f2f7fe9bc12 | 37.208589 | 120 | 0.695087 | 5.251265 | false | false | false | false |
TonnyTao/Acornote | Acornote_iOS/Acornote/AppDelegate.swift | 1 | 10773 | //
// AppDelegate.swift
// Acornote
//
// Created by Tonny on 27/10/2016.
// Copyright © 2016 Tonny&Sunm. All rights reserved.
//
import UIKit
import CoreData
/* TODO:
order item;
restore iOS state;
Home swip page;
items re-order
youtube in webview
*/
/* Feature:
share from other app
player : play list
*/
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().barStyle = .black
UINavigationBar.appearance().barTintColor = .rgb(56, 59, 69)
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
UIReferenceLibraryViewController.dictionaryHasDefinition(forTerm: "")
#if DEBUG
// importDB()
// importFromPlist()
createDemoDataIfNecessory();
#endif
return true
}
func applicationWillResignActive(_ application: UIApplication) {
clearDefaults()
}
private func clearDefaults() {
let ud = UserDefaults(suiteName: "group.tonnysunm.acornote")
ud?.removeObject(forKey: "Items")
ud?.removeObject(forKey: "Item_Folder_Map")
ud?.synchronize()
}
func applicationDidEnterBackground(_ application: UIApplication) {
try? cdStore.operation { (context, save) throws -> Void in
let folders = try! context.request(Folder.self).fetch()
let folderArr = folders.reduce([], { (results, folder) -> [[String: Any]] in
var re = results
re.append(folder.dic as [String : Any])
return re
})
let items = try! context.request(Item.self).fetch()
let itemArr = items.reduce([], { (results, item) -> [[String: Any]] in
var re = results
re.append(item.dic)
return re
})
if let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
let dic = ["folders": folderArr, "items": itemArr]
let c = Calendar.current
let coms = c.dateComponents([.year, .month, .day], from: Date())
let file = (path as NSString).appendingPathComponent("db_\(coms.year!)_\(coms.month!)_\(coms.day!)")
let success = (dic as NSDictionary).write(toFile: file, atomically: true)
debugPrint("save file ", success)
//TODO remove old files
}
save()
}
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
importFromTodayWedget()
}
func importFromTodayWedget() {
let ud = UserDefaults(suiteName: "group.tonnysunm.acornote")!
if let arr = ud.object(forKey: "Items") as? [String], let map = ud.object(forKey: "Item_Folder_Map") as? [String: String] {
try? cdStore.operation { (context, save) throws -> Void in
//TODO in batch
arr.forEach({ text in
guard let fName = map[text] else {
return
}
let pre = NSPredicate(format: "title == %@", fName)
if let folder = Folder.findOne(context, predicate: pre) {
if let _ = Item.findOne(context, predicate: NSPredicate(format:"folder=%@ AND title == %@", folder, text)) {
//repeat
}else {
//copy des firstly, copy title later.
if let item = Item.findOne(context, predicate: NSPredicate(format: "folder == %@ AND title CONTAINS[cd] %@", folder, text)) {
if let des = item.des {
if !des.components(separatedBy: .newlines).contains(text) {
item.des = des + "\n" + text
}
}else {
item.des = item.title
item.title = text
}
}else {
let item: Item = try! context.create()
item.createdAt = NSDate()
item.title = text
item.folder = folder
folder.updatedAt = NSDate()
}
}
}
})
save()
self.clearDefaults()
}
}
try? cdStore.operation { (context, save) throws -> Void in
let folders = try! context.request(Folder.self).sorted(with: "updatedAt", ascending: false).fetch()
let items = folders.map({ (f) -> [String: String] in
let rgb = Folder.ColorConfig.color(withId: f.color)!.rgb
return [f.title!: "\(rgb.0),\(rgb.1),\(rgb.2)"]
})
ud.set(items, forKey: "All_Folder_Names")
ud.synchronize()
}
}
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
return true
}
#if DEBUG
func importDB() {
let url = Bundle.main.url(forResource: "db", withExtension: nil)!
let data = try! Data(contentsOf: url)
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let p = (path as NSString).appendingPathComponent("db")
try? data.write(to: URL(fileURLWithPath: p))
}
func importFromPlist() {
let texts:String = Bundle.main.path(forResource: "db", ofType: "")!
let dic = NSDictionary(contentsOfFile: texts)!
(dic["folders"] as! [[String: Any]]).forEach({ item in
let model: Folder = try! cdStore.saveContext.create()
model.title = item["title"] as? String
model.url = item["url"] as? String
model.audioUrl = item["audioUrl"] as? String
model.color = item["color"] as? Int16 ?? Folder.ColorConfig.defalut
model.playable = item["playable"] as? Bool ?? false
model.flipable = item["flipable"] as? Bool ?? false
model.tagable = item["tagable"] as? Bool ?? false
model.orderBy = item["orderBy"] as? Int16 ?? 0
model.quizlet = item["quizlet"] as? Bool ?? false
model.createdAt = item["createdAt"] as? NSDate ?? NSDate()
model.updatedAt = item["updatedAt"] as? NSDate ?? NSDate()
model.lastVisited = item["lastVisited"] as? String
})
(dic["items"] as! [[String: Any]]).forEach({ item in
let model: Item = try! cdStore.saveContext.create()
model.title = item["title"] as? String
model.url = item["url"] as? String
model.des = item["des"] as? String
model.imgPath = item["imgPath"] as? String
model.taged = item["taged"] as? Bool ?? false
model.fliped = item["fliped"] as? Bool ?? false
model.createdAt = item["createdAt"] as? NSDate ?? NSDate()
if let title = item["folder"] as? String,
let folder = try? cdStore.saveContext.request(Folder.self).filtered(with: NSPredicate(format: "title == %@", title)).fetch().first {
model.folder = folder
}
})
try? cdStore.operation { (context, save) throws -> Void in
save()
}
}
func createDemoDataIfNecessory() {
let projects = try! cdStore.saveContext.request(Folder.self).fetch()
if projects.count == 0 {
[("demo", "Everyday Essential Words")].forEach({ (file, name) in
let model: Folder = try! cdStore.saveContext.create()
model.createdAt = NSDate()
model.playable = true
model.flipable = true
model.title = name
model.color = Folder.ColorConfig.defalut
// model.url = "https://dict.eudic.net/webting/desktopplay/8b472527-01ec-11e6-a7a6-000c29ffef9b"
let texts:String = try! String(contentsOfFile: Bundle.main.path(forResource: file, ofType: "")!, encoding: .utf8)
let arr = texts.components(separatedBy: .newlines)
for i in 0..<arr.count/2 {
let item: Item = try! cdStore.saveContext.create()
item.title = arr[2*i].trimmingCharacters(in: .whitespacesAndNewlines)
let des = arr[2*i+1].trimmingCharacters(in: .whitespacesAndNewlines)
if des != "."{
item.des = des
}
item.createdAt = NSDate()
item.folder = model
model.updatedAt = NSDate()
}
})
let ctx = (cdStore.saveContext as! NSManagedObjectContext)
ctx.performAndWait({
try! ctx.save()
})
}
}
#endif
}
extension String {
// He is tall
// ["He", "He is", "He is tall", "is", "is tall", "tall"]
var components: [String] {
if self.isEmpty {
return []
}
let arr = self.components(separatedBy: .whitespaces)
var result = [String]()
for (index, _) in arr.enumerated() {
var items = [String]()
for i in index..<arr.count {
let item = arr[index...i].joined(separator: " ")
items.append(item.replacingOccurrences(of: ".", with: "").replacingOccurrences(of: ",", with: ""))
}
result.append(contentsOf: items)
}
return result
}
}
| apache-2.0 | 27db58ff71a3c496effc187ee3f0ce34 | 36.381944 | 153 | 0.504273 | 4.938532 | false | false | false | false |
LedgerHQ/u2f-ble-test-ios | u2f-ble-test-ios/Managers/BluetoothManager.swift | 1 | 5637 | //
// BluetoothManager.swift
// u2f-ble-test-ios
//
// Created by Nicolas Bigot on 13/05/2016.
// Copyright © 2016 Ledger. All rights reserved.
//
import Foundation
import CoreBluetooth
enum BluetoothManagerState: String {
case Scanning
case Connecting
case Connected
case Disconnecting
case Disconnected
}
final class BluetoothManager: NSObject {
var onStateChanged: ((BluetoothManager, BluetoothManagerState) -> Void)?
var onDebugMessage: ((BluetoothManager, String) -> Void)?
var onReceivedAPDU: ((BluetoothManager, NSData) -> Void)?
var deviceName: String? { return deviceManager?.deviceName }
private var centralManager: CBCentralManager?
private var deviceManager: DeviceManager?
private(set) var state = BluetoothManagerState.Disconnected {
didSet {
onStateChanged?(self, self.state)
onDebugMessage?(self, "New state: \(self.state.rawValue)")
}
}
func scanForDevice() {
guard centralManager == nil else { return }
// create central
centralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: NSNumber(bool: true)])
state = .Scanning
}
func stopSession() {
guard let centralManager = centralManager else { return }
// handle disconnection
if state == .Scanning {
centralManager.stopScan()
self.centralManager = nil
state = .Disconnected
}
else if state == .Connecting || state == .Connected, let device = deviceManager?.peripheral {
centralManager.cancelPeripheralConnection(device)
state = .Disconnecting
}
}
func exchangeAPDU(data: NSData) {
guard state == .Connected else { return }
// send data
onDebugMessage?(self, "Exchanging APDU = \(data)")
deviceManager?.exchangeAPDU(data)
}
private func handleDeviceManagerStateChanged(deviceManager: DeviceManager, state: DeviceManagerState) {
if state == .Bound {
onDebugMessage?(self, "Successfully connected device \(deviceManager.peripheral.identifier.UUIDString)")
self.state = .Connected
}
else if state == .Binding {
onDebugMessage?(self, "Binding to device \(deviceManager.peripheral.identifier.UUIDString)...")
}
else if state == .NotBound {
onDebugMessage?(self, "Something when wrong with device \(deviceManager.peripheral.identifier.UUIDString)")
stopSession()
}
}
private func handleDeviceManagerDebugMessage(deviceManager: DeviceManager, message: String) {
onDebugMessage?(self, message)
}
private func handleDeviceManagerReceivedAPDU(deviceManager: DeviceManager, data: NSData) {
onReceivedAPDU?(self, data)
}
private func resetState() {
deviceManager = nil
centralManager = nil
state = .Disconnected
}
}
extension BluetoothManager: CBCentralManagerDelegate {
func centralManagerDidUpdateState(central: CBCentralManager) {
if central.state == .PoweredOn && state == .Scanning {
// bluetooth stack is ready, start scanning
onDebugMessage?(self, "Bluetooth stack is ready, scanning devices...")
let serviceUUID = CBUUID(string: DeviceManager.deviceServiceUUID)
central.scanForPeripheralsWithServices([serviceUUID], options: nil)
}
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
guard state == .Scanning else { return }
guard let connectable = advertisementData[CBAdvertisementDataIsConnectable] as? NSNumber where connectable.boolValue == true else { return }
// a device has been found
onDebugMessage?(self, "Found connectable device \"\(peripheral.name)\", connecting \(peripheral.identifier.UUIDString)...")
deviceManager = DeviceManager(peripheral: peripheral)
deviceManager?.onStateChanged = handleDeviceManagerStateChanged
deviceManager?.onDebugMessage = handleDeviceManagerDebugMessage
deviceManager?.onAPDUReceived = handleDeviceManagerReceivedAPDU
central.stopScan()
central.connectPeripheral(peripheral, options: nil)
state = .Connecting
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
guard state == .Connecting, let deviceManager = deviceManager else { return }
// we're connected, bind to characteristics
deviceManager.bindForReadWrite()
}
func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
guard state == .Connecting, let _ = deviceManager else { return }
// failed to connect
onDebugMessage?(self, "Failed to connect device \(peripheral.identifier.UUIDString), error: \(error?.description)")
resetState()
}
func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
guard state == .Connecting || state == .Connected || state == .Disconnecting, let _ = deviceManager else { return }
// destroy central
onDebugMessage?(self, "Disconnected device \(peripheral.identifier.UUIDString), error: \(error?.description)")
resetState()
}
} | apache-2.0 | e6f357fa3a25039c36e1f143c2174b5c | 37.609589 | 157 | 0.664301 | 5.574679 | false | false | false | false |
longsirhero/DinDinShop | DinDinShopDemo/DinDinShopDemo/海外/Models/WCSeasActivityModel.swift | 1 | 1312 | //
// WCSeasActivityModel.swift
// DinDinShopDemo
//
// Created by longsirHERO on 2017/8/24.
// Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved.
//
import UIKit
class WCSeasActivityModel: NSObject {
var context:String?
var dataId:String?
var goods:NSArray?
var picPath:String?
var title:String?
var typeId:String?
class func initModelWithDictionary(dic:[String:Any]) -> WCSeasActivityModel {
let model:WCSeasActivityModel = WCSeasActivityModel.init()
model.context = dic["context"] as? String
model.dataId = dic["dataId"] as? String
model.picPath = dic["picPath"] as? String
model.title = dic["title"] as? String
model.typeId = dic["typeId"] as? String
let goods:NSMutableArray = NSMutableArray()
for dict in (dic["goods"] as? NSArray)! {
let model:WCSeasActivityDetailModel = WCSeasActivityDetailModel.initModelWithDictionary(dic: dict as! [String : Any])
goods.add(model)
}
model.goods = goods
return model
}
// 避免KVC找不到对应的key值报错 空实现系统以下方法
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| mit | 02592563473696baddf0a61271a9487c | 26.586957 | 129 | 0.631206 | 3.940994 | false | false | false | false |
Piwigo/Piwigo-Mobile | piwigoKit/Supporting Files/Data+AppTools.swift | 1 | 11615 | //
// Data+AppTools.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 06/02/2021.
// Copyright © 2021 Piwigo.org. All rights reserved.
//
import Foundation
import var CommonCrypto.CC_MD5_DIGEST_LENGTH
import func CommonCrypto.CC_MD5
import typealias CommonCrypto.CC_LONG
#if canImport(CryptoKit)
import CryptoKit // Requires iOS 13
#endif
extension Data {
// MARK: - MD5 Checksum
// Return the MD5 checksum of data
public func MD5checksum() -> String {
var md5Checksum = ""
// Determine MD5 checksum of video file to upload
if #available(iOS 13.0, *) {
#if canImport(CryptoKit) // Requires iOS 13
md5Checksum = self.MD5(data: self)
#endif
} else {
// Fallback on earlier versions
md5Checksum = self.oldMD5(data: self)
}
return md5Checksum
}
#if canImport(CryptoKit) // Requires iOS 13
@available(iOS 13.0, *)
private func MD5(data: Data?) -> String {
let digest = Insecure.MD5.hash(data: data ?? Data())
return digest.map { String(format: "%02hhx", $0) }.joined()
}
#endif
private func oldMD5(data: Data?) -> String {
let length = Int(CC_MD5_DIGEST_LENGTH)
let messageData = data ?? Data()
var digestData = Data(count: length)
_ = digestData.withUnsafeMutableBytes { digestBytes -> UInt8 in
messageData.withUnsafeBytes { messageBytes -> UInt8 in
if let messageBytesBaseAddress = messageBytes.baseAddress,
let digestBytesBlindMemory = digestBytes.bindMemory(to: UInt8.self).baseAddress {
let messageLength = CC_LONG(messageData.count)
CC_MD5(messageBytesBaseAddress, messageLength, digestBytesBlindMemory)
}
return 0
}
}
return digestData.map { String(format: "%02hhx", $0) }.joined()
}
// MARK: - MIME type and file extension sniffing
// Return contentType of image data
func contentType() -> String? {
var bytes: [UInt8] = Array(repeating: UInt8(0), count: 12)
(self as NSData).getBytes(&bytes, length: 12)
var jpg = jpgSignature()
if memcmp(bytes, &jpg, jpg.count) == 0 { return "image/jpeg" }
var heic = heicSignature()
if memcmp(bytes, &heic, heic.count) == 0 { return "image/heic" }
var png = pngSignature()
if memcmp(bytes, &png, png.count) == 0 { return "image/png" }
var gif87a = gif87aSignature()
var gif89a = gif89aSignature()
if memcmp(bytes, &gif87a, gif87a.count) == 0 ||
memcmp(bytes, &gif89a, gif89a.count) == 0 { return "image/gif" }
var bmp = bmpSignature()
if memcmp(bytes, &bmp, bmp.count) == 0 { return "image/x-ms-bmp" }
var psd = psdSignature()
if memcmp(bytes, &psd, psd.count) == 0 { return "image/vnd.adobe.photoshop" }
var iff = iffSignature()
if memcmp(bytes, &iff, iff.count) == 0 { return "image/iff" }
var webp = webpSignature()
if memcmp(bytes, &webp, webp.count) == 0 { return "image/webp" }
var win_ico = win_icoSignature()
var win_cur = win_curSignature()
if memcmp(bytes, &win_ico, win_ico.count) == 0 ||
memcmp(bytes, &win_cur, win_cur.count) == 0 { return "image/x-icon" }
var tif_ii = tif_iiSignature()
var tif_mm = tif_mmSignature()
if memcmp(bytes, &tif_ii, tif_ii.count) == 0 ||
memcmp(bytes, &tif_mm, tif_mm.count) == 0 { return "image/tiff" }
var jp2 = jp2Signature()
if memcmp(bytes, &jp2, jp2.count) == 0 { return "image/jp2" }
return nil
}
// Return file extension corresponding to image data
func fileExtension() -> String? {
var bytes: [UInt8] = Array(repeating: UInt8(0), count: 12)
(self as NSData).getBytes(&bytes, length: 12)
var jpg = jpgSignature()
if memcmp(bytes, &jpg, jpg.count) == 0 { return "jpg" }
var heic = heicSignature()
if memcmp(bytes, &heic, heic.count) == 0 { return "heic" }
var png = pngSignature()
if memcmp(bytes, &png, png.count) == 0 { return "png" }
var gif87a = gif87aSignature()
var gif89a = gif89aSignature()
if memcmp(bytes, &gif87a, gif87a.count) == 0 ||
memcmp(bytes, &gif89a, gif89a.count) == 0 { return "gif" }
var bmp = bmpSignature()
if memcmp(bytes, &bmp, bmp.count) == 0 { return "bmp" }
var psd = psdSignature()
if memcmp(bytes, &psd, psd.count) == 0 { return "psd" }
var iff = iffSignature()
if memcmp(bytes, &iff, iff.count) == 0 { return "iff" }
var webp = webpSignature()
if memcmp(bytes, &webp, webp.count) == 0 { return "webp" }
var win_ico = win_icoSignature()
if memcmp(bytes, &win_ico, win_ico.count) == 0 { return "ico" }
var win_cur = win_curSignature()
if memcmp(bytes, &win_cur, win_cur.count) == 0 { return "cur" }
var tif_ii = tif_iiSignature()
var tif_mm = tif_mmSignature()
if memcmp(bytes, &tif_ii, tif_ii.count) == 0 ||
memcmp(bytes, &tif_mm, tif_mm.count) == 0 { return "tif" }
var jp2 = jp2Signature()
if memcmp(bytes, &jp2, jp2.count) == 0 { return "jp2" }
return nil
}
// MARK: - Image Formats
// See https://en.wikipedia.org/wiki/List_of_file_signatures
// https://mimesniff.spec.whatwg.org/#sniffing-in-an-image-context
// https://en.wikipedia.org/wiki/BMP_file_format
private func bmpSignature() -> [UInt8] {
return "BM".map { $0.asciiValue! }
}
// https://en.wikipedia.org/wiki/GIF
private func gif87aSignature() -> [UInt8] {
return "GIF87a".map { $0.asciiValue! }
}
private func gif89aSignature() -> [UInt8] {
return "GIF89a".map { $0.asciiValue! }
}
// https://en.wikipedia.org/wiki/High_Efficiency_Image_File_Format
private func heicSignature() -> [UInt8] {
return [0x00, 0x00, 0x00, 0x18] + "ftypheic".map { $0.asciiValue! }
}
// https://en.wikipedia.org/wiki/ILBM
private func iffSignature() -> [UInt8] {
return "FORM".map { $0.asciiValue! }
}
// https://en.wikipedia.org/wiki/JPEG
private func jpgSignature() -> [UInt8] {
return [0xff, 0xd8, 0xff]
}
// https://en.wikipedia.org/wiki/JPEG_2000
private func jp2Signature() -> [UInt8] {
return [0x00, 0x00, 0x00, 0x0c, 0x6a, 0x50, 0x20, 0x20, 0x0d, 0x0a, 0x87, 0x0a]
}
// https://en.wikipedia.org/wiki/Portable_Network_Graphics
private func pngSignature() -> [UInt8] {
return [0x89] + "PNG".map { $0.asciiValue! } + [0x0d, 0x0a, 0x1a, 0x0a]
}
// https://en.wikipedia.org/wiki/Adobe_Photoshop#File_format
private func psdSignature() -> [UInt8] {
return "8BPS".map { $0.asciiValue! }
}
// https://en.wikipedia.org/wiki/TIFF
private func tif_iiSignature() -> [UInt8] {
return "II".map { $0.asciiValue! } + [0x2a, 0x00]
}
private func tif_mmSignature() -> [UInt8] {
return "MM".map { $0.asciiValue! } + [0x00, 0x2a]
}
// https://en.wikipedia.org/wiki/WebP
private func webpSignature() -> [UInt8] {
return "RIFF".map { $0.asciiValue! }
}
// https://en.wikipedia.org/wiki/ICO_(file_format)
private func win_icoSignature() -> [UInt8] {
return [0x00, 0x00, 0x01, 0x00]
}
private func win_curSignature() -> [UInt8] {
return [0x00, 0x00, 0x02, 0x00]
}
// MARK: Piwgo Response Checker
// Clean and check the response returned by the server
public mutating func isPiwigoResponseValid<T: Decodable>(for type: T.Type) -> Bool {
// Is this an empty object?
if self.isEmpty { return false }
// Is this a valid JSON object?
let decoder = JSONDecoder()
if let _ = try? decoder.decode(type, from: self) {
return true
}
// Remove HTML data located
/// - before the first opening curly brace
/// - after the last closing curly brace
let dataStr = String(decoding: self, as: UTF8.self)
var filteredDataStr = ""
var filteredData = Data()
if let openingCBindex = dataStr.firstIndex(of: "{"),
let closingCBIndex = dataStr.lastIndex(of: "}") {
filteredDataStr = String(dataStr[openingCBindex...closingCBIndex])
} else {
// Did not find an opening curly brace
return false
}
// Is this now a valid JSON object?
filteredData = filteredDataStr.data(using: String.Encoding.utf8)!
if let _ = try? decoder.decode(type, from: filteredData) {
self = filteredData
return true
}
// Loop over the possible blocks between curly braces
repeat {
// Look for the first closing curly brace at the same level
// and extract the block of data in between the curly braces.
var blockStr = ""
var level:Int = 0
for (index, char) in filteredDataStr.enumerated() {
if char == "{" { level += 1 }
if char == "}" { level -= 1 }
if level == 0 {
// Found "}" of same level -> extract object
let strIndex = dataStr.index(filteredDataStr.startIndex, offsetBy: index)
blockStr = String(filteredDataStr[...strIndex])
break
}
}
// Did we identified a block of data?
if (level != 0) || blockStr.isEmpty {
// No -> Remove the current opening curly brace
let newDataStr = String(filteredDataStr.dropFirst())
// Look for the next opening curly brace
if let openingCBindex = newDataStr.firstIndex(of: "{"),
let closingCBIndex = newDataStr.lastIndex(of: "}") {
// Look for the next block of data
filteredDataStr = String(newDataStr[openingCBindex...closingCBIndex])
} else {
// Did not find an opening curly brace
filteredDataStr = ""
}
continue
}
// Is this block a valid JSON object?
let blockData = blockStr.data(using: String.Encoding.utf8)!
if let _ = try? decoder.decode(type, from: blockData) {
self = blockData
return true
}
// No -> Remove the current opening curly brace
let newDataStr = String(filteredDataStr.dropFirst())
if let openingCBindex = newDataStr.firstIndex(of: "{"),
let closingCBIndex = newDataStr.lastIndex(of: "}") {
// Look for the next block of data
filteredDataStr = String(newDataStr[openingCBindex...closingCBIndex])
} else {
// Did not find an opening curly brace
filteredDataStr = ""
continue
}
} while filteredDataStr.isEmpty == false
self = Data()
return false
}
}
| mit | 515ecd9078fe04fb69f58c07dda6188c | 35.634069 | 101 | 0.551537 | 3.859422 | false | false | false | false |
chinesemanbobo/PPDemo | Pods/Down/Source/AST/Styling/Attribute Collections/FontCollection.swift | 3 | 1954 | //
// FontCollection.swift
// Down
//
// Created by John Nguyen on 22.06.19.
// Copyright © 2016-2019 Down. All rights reserved.
//
#if !os(watchOS) && !os(Linux)
#if canImport(UIKit)
import UIKit
public typealias DownFont = UIFont
#elseif canImport(AppKit)
import AppKit
public typealias DownFont = NSFont
#endif
public protocol FontCollection {
var heading1: DownFont { get }
var heading2: DownFont { get }
var heading3: DownFont { get }
var heading4: DownFont { get }
var heading5: DownFont { get }
var heading6: DownFont { get }
var body: DownFont { get }
var code: DownFont { get }
var listItemPrefix: DownFont { get }
}
public struct StaticFontCollection: FontCollection {
public var heading1: DownFont
public var heading2: DownFont
public var heading3: DownFont
public var heading4: DownFont
public var heading5: DownFont
public var heading6: DownFont
public var body: DownFont
public var code: DownFont
public var listItemPrefix: DownFont
public init(
heading1: DownFont = .boldSystemFont(ofSize: 28),
heading2: DownFont = .boldSystemFont(ofSize: 24),
heading3: DownFont = .boldSystemFont(ofSize: 20),
heading4: DownFont = .boldSystemFont(ofSize: 20),
heading5: DownFont = .boldSystemFont(ofSize: 20),
heading6: DownFont = .boldSystemFont(ofSize: 20),
body: DownFont = .systemFont(ofSize: 17),
code: DownFont = DownFont(name: "menlo", size: 17) ?? .systemFont(ofSize: 17),
listItemPrefix: DownFont = DownFont.monospacedDigitSystemFont(ofSize: 17, weight: .regular)
) {
self.heading1 = heading1
self.heading2 = heading2
self.heading3 = heading3
self.heading4 = heading4
self.heading5 = heading5
self.heading6 = heading6
self.body = body
self.code = code
self.listItemPrefix = listItemPrefix
}
}
#endif
| mit | 26f34c965079c84dfae9f8b07f258191 | 26.507042 | 99 | 0.665643 | 3.844488 | false | false | false | false |
PSSWD/psswd-ios | psswd/AuthSignupMasterpassVC.swift | 1 | 4774 | //
// AuthSignupMasterpassVC.swift
// psswd
//
// Created by Daniil on 02.01.15.
// Copyright (c) 2015 kirick. All rights reserved.
//
import UIKit
class AuthSignupMasterpassVC: UITableViewController
{
@IBOutlet weak var masterpassField: UITextField!
@IBOutlet weak var masterpassRetypeField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
}
@IBAction func nextPressed(sender: AnyObject) {
println("next pressed")
let masterpass = masterpassField.text
if count(masterpass) < 10 {
UIAlertView(title: "Ошибка", message: "Мастерпароль слишком короткий. Минимальная длина мастерпароля — 10 символов.", delegate: self, cancelButtonTitle: "OK").show()
return
}
if count(masterpass) > 64 {
UIAlertView(title: "Ошибка", message: "Мастерпароль слишком длинный. Максимальная длина мастерпароля — 64 символа.", delegate: self, cancelButtonTitle: "OK").show()
return
}
if masterpass != masterpassRetypeField.text {
UIAlertView(title: "Ошибка", message: "Введённые мастерпароли не совпадают.", delegate: self, cancelButtonTitle: "OK").show()
return
}
var passcodeVC = self.storyboard?.instantiateViewControllerWithIdentifier("SystemPasscodeVC") as! SystemPasscodeVC
passcodeVC.topTitle = "Придумайте пароль"
passcodeVC.onSubmit = { (code_user: String) -> Void in
var passcodeRetypeVC = self.storyboard?.instantiateViewControllerWithIdentifier("SystemPasscodeVC") as! SystemPasscodeVC
passcodeRetypeVC.topTitle = "Повторите пароль"
passcodeRetypeVC.onSubmit = { (codeRetype: String) -> Void in
if code_user != codeRetype {
UIAlertView(title: "Ошибка", message: "Пароли не совпадают", delegate: passcodeRetypeVC, cancelButtonTitle: "OK").show()
self.navigationController!.popViewControllerAnimated(true)
return
}
var email = Storage.getString("email")
assert(nil != email, "Can't get email.")
var code_client = Crypto.Bytes(randomWithLength: 20)
, code_client_pass = Crypto.Bytes(randomWithLength: 32)
, code_client_getdata = Crypto.Bytes(randomWithLength: 32)
var masterpass_getCodes_public = Crypto.Bytes(fromString: masterpass).append(API.constants.salt_masterpass_getcodes_public).getSHA1()
, masterpass_getCodes_private = Crypto.Bytes(fromString: masterpass).append(API.constants.salt_masterpass_getcodes_private).getSHA1()
var clientCodes_toenc = Schemas.utils.dataToSchemaBytes(0x3003, input_data: [Crypto.Bytes(fromString: code_user), code_client, code_client_pass, code_client_getdata])
var clientCodes_enc = Crypto.Cryptoblender.encrypt(clientCodes_toenc, withKey: masterpass_getCodes_private)
var clientCodes_enc_enc = Crypto.Cryptoblender.encrypt(clientCodes_enc, withKey: masterpass_getCodes_public)
var clientCodes_enc_enc_hash = clientCodes_enc_enc.getSHA1()
//var pass = Crypto.SHA1(code_user + code_client + code_client_pass + constants.salt_pass)
var pass = Crypto.Bytes(fromString: code_user)
.append(code_client)
.append(code_client_pass)
.append(API.constants.salt_pass)
.getSHA1()
var requestData = [
"email": email!,
"pass": pass,
"clientCodes_enc_enc": clientCodes_enc_enc,
"clientCodes_enc_enc_hash": clientCodes_enc_enc_hash,
"app_id": API.app.app_id,
"app_secret": API.app.app_secret
] as [String: AnyObject]
API.call("reg.start", params: requestData, callback: { rdata in
let code = rdata["code"] as! Int
switch code {
case 0:
Storage.setBytes(code_client, forKey: "code_client")
Storage.setBytes(code_client_pass, forKey: "code_client_pass")
Storage.setBytes(code_client_getdata, forKey: "code_client_getdata")
API.code_user = code_user
var vc = self.storyboard?.instantiateViewControllerWithIdentifier("AuthSignupConfirmVC") as! UITableViewController
self.navigationController!.pushViewController(vc, animated: true)
default:
API.unknownCode(rdata)
}
})
}
self.navigationController!.pushViewController(passcodeRetypeVC, animated: true)
}
self.navigationController!.pushViewController(passcodeVC, animated: true)
}
private func randomString(length: Int) -> String {
var syms = Array("0123456789" + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "!@#$%&§.")
var res = ""
while count(res) < length {
res = "\(res)\(syms[ Int( MTRandom().randomUInt32From(0, to: UInt32(syms.count - 1)) ) ])"
}
return res
}
}
| gpl-2.0 | acdddc66c6484bcbc5937ad890b6444f | 37.803419 | 170 | 0.708811 | 3.380491 | false | false | false | false |
tinyfool/GoodMorning | GoodMorning/GoodMorning/GoodMorning/AppDelegate.swift | 1 | 5325 | //
// AppDelegate.swift
// GoodMorning
//
// Created by pei hao on 1/23/15.
// Copyright (c) 2015 pei hao. All rights reserved.
//
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
var synthesizer = AVSpeechSynthesizer();
var utterance = AVSpeechUtterance(string: "");
//synthesizer.speakUtterance(utterance);
utterance = AVSpeechUtterance(string: "主人,您好,上海今日最低气温1度,最高气温8度,空气质量指数185,不健康,建议戴口罩,不要开窗,尽量不要到户外运动。你有三个预约,最早的是早上10点,离现在还有10分钟。今天你的星座运势为:往前冲的马力加大,行动力就像被升起的炉火般火力十足。 但是另一方面也加强了你的攻击力,要注意别让火力给烧偏了,别将精力给浪费在无意义的玩乐上,有可能引火上身烧伤自己喔。旺盛的精力当然要运用在好的方面,需要好精神去做的事情都趁早去吧。。最新热门新闻有微软发布了Windows10,无人问津,但微软的眼镜获得了大量的追捧。著名演员陈赫,被爆出已于半年前离婚,在微博以及各大网络社区粉丝的声讨声中,他诚挚道歉,并称希望大家不要继续纠缠他的前妻。埃及的局势继续紧张,伊斯兰国仍旧没有释放日本人质。今天早晨的新闻播送完了。");
utterance.voice = AVSpeechSynthesisVoice(language:"zh-CN");
utterance.rate = 0.1;
// utterance = AVSpeechUtterance(string: "所有者、こんにちは、上海の今日、1度、8度の最高温度、185の空気品質指数の最低温度は、不健康な、それはウィンドウを開き、アウトドアスポーツにはないしようとしない、マスクを着用することをお勧めします。あなたは最も古い朝の10時は、10分の距離にまだあるある、3の予定を持っている。今日のあなたのホロスコープ:フォワード馬力に行くには、火の上昇のような火の完全なものとして機動性を増加させた。しかし、それはまた、火災が邪魔にまかせるないように注意を払う、あなたの攻撃力を強化し、意味のない遊びに無駄なエネルギーを与えていない、自分がああ火傷があっ焼くことがあります。もちろん、良い面を利用する強力な努力が、あなたは物事ができるだけ早期に行く行うには良い精神を必要とする。 。最新のトップニュースは、MicrosoftがWindows10をリリースしている、誰も気にしないが、Microsoftのガラスは、ホット追求の多くを得る。有名な俳優陳氏は、破産が6ヶ月前に離婚した、マイクロブログネットワークのファンのコミュニティだけでなく、主要な抗議され、彼は心から私たちは彼の元妻に苦労し続けるべきではないと言って、謝罪した。エジプトの緊迫した状況では、日本のイスラム国家はまだ人質を解放されませんし続ける。今朝のニュース放送が終了しました。");
// utterance.voice = AVSpeechSynthesisVoice(language:"ja-JP");
// utterance.rate = 0.1;
//synthesizer.speakUtterance(utterance);
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 | 389293e893e5c7ff8cc00ca611890cf1 | 59.05 | 619 | 0.776575 | 2.672849 | false | false | false | false |
lzamudio/swift-book | Inheritance.playground/section-1.swift | 2 | 1349 | // Playground for Inheritance section
class Vehicle {
var currentSpeed = 0.0
var description: String {
return "traveling at \(currentSpeed) miles per hour"
}
func makeNoise() {
// Do nothing
}
}
let someVehicle = Vehicle()
println("Vehicle: \(someVehicle.description)")
// Subclassing
class Bicycle: Vehicle {
var hasBasket = false
}
let bicycle = Bicycle()
bicycle.hasBasket = true
bicycle.currentSpeed = 15.0
println("Bicycle: \(bicycle.description)")
class Tandem: Bicycle {
var currentNumberOfPassengers = 0
}
let tandem = Tandem()
tandem.hasBasket = true
tandem.currentNumberOfPassengers = 2
tandem.currentSpeed = 22.0
println("Tandem: \(tandem.description)")
// Overriding
class Train: Vehicle {
override func makeNoise() {
println("Choo Choo")
}
}
let train = Train()
train.makeNoise()
class Car: Vehicle {
var gear = 1
override var description: String {
return super.description + " in gear \(gear)"
}
}
let car = Car()
car.currentSpeed = 25.0
car.gear = 3
println("Car: \(car.description)")
class AutomaticCar: Car {
override var currentSpeed: Double {
didSet {
gear = Int(currentSpeed / 10.0) + 1
}
}
}
let automatic = AutomaticCar()
automatic.currentSpeed = 35.0
println("AutomaticCar: \(automatic.description)") | mit | 55977d3083488650476bc60cf9873839 | 19.454545 | 60 | 0.66642 | 3.8 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/TinyConstraints/TinyConstraints/Classes/Abstraction.swift | 1 | 1924 | //
// MIT License
//
// Copyright (c) 2017 Robert-Hein Hooijmans <[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
#if os(OSX)
import AppKit
public typealias View = NSView
public typealias LayoutGuide = NSLayoutGuide
public typealias ConstraintAxis = NSLayoutConstraint.Orientation
public typealias LayoutPriority = NSLayoutConstraint.Priority
public typealias TinyEdgeInsets = NSEdgeInsets
public extension NSEdgeInsets {
static var zero = NSEdgeInsetsZero
}
#else
import UIKit
public typealias View = UIView
public typealias LayoutGuide = UILayoutGuide
public typealias ConstraintAxis = NSLayoutConstraint.Axis
public typealias LayoutPriority = UILayoutPriority
public typealias TinyEdgeInsets = UIEdgeInsets
#endif
| mit | dd96f2685966858fd46fef0aba7119b9 | 39.083333 | 83 | 0.737006 | 4.908163 | false | false | false | false |
niceandcoolusername/cosmos | code/data_structures/tree/binary_tree/binary_tree.swift | 6 | 1302 | public indirect enum BinaryTree<T> {
case empty
case node(BinaryTree, T, BinaryTree)
}
extension BinaryTree: CustomStringConvertible {
public var description: String {
switch self {
case let .node(left, value, right):
return "value: \(value), left = [\(left.description)], right = [\(right.description)]"
case .empty:
return ""
}
}
}
extension BinaryTree {
public func traverseInOrder(process: (T) -> Void) {
if case let .node(left, value, right) = self {
left.traverseInOrder(process: process)
process(value)
right.traverseInOrder(process: process)
}
}
public func traversePreOrder(process: (T) -> Void) {
if case let .node(left, value, right) = self {
process(value)
left.traversePreOrder(process: process)
right.traversePreOrder(process: process)
}
}
public func traversePostOrder(process: (T) -> Void) {
if case let .node(left, value, right) = self {
left.traversePostOrder(process: process)
right.traversePostOrder(process: process)
process(value)
}
}
}
extension BinaryTree {
func invert() -> BinaryTree {
if case let .node(left, value, right) = self {
return .node(right.invert(), value, left.invert())
} else {
return .empty
}
}
}
| gpl-3.0 | 03c2a163dd2926eb12826834ec50ee88 | 24.529412 | 92 | 0.638249 | 3.886567 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/SensorData/CopyImportedFilesOperation.swift | 1 | 4038 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
enum CopyImportedFilesError: Error {
/// The operation did not have the required `ImportExperimentOperation` as a dependency.
case importExperimentOperationNotFound
/// The destination directory could not be created.
case cannotCreateDestinationDirectory
/// The destination assets directroy could not be created.
case cannotCreateAssetsDirectory
}
/// An operation that copies the imported files to a destination experiment directory. Requires
/// an `ImportExperimentOperation` as a dependency.
class CopyImportedFilesOperation: GroupOperation {
private let destinationExperimentURL: URL
/// Designated initializer.
///
/// - Parameter destinationExperimentURL: The destination directory to which files should
/// be copied.
init(destinationExperimentURL: URL) {
self.destinationExperimentURL = destinationExperimentURL
// Operations are added at execution time.
super.init(operations: [])
}
override func execute() {
guard let importExperimentOperation =
(dependencies.compactMap { $0 as? ImportExperimentOperation }).first else {
finish(withErrors: [CopyImportedFilesError.importExperimentOperationNotFound])
return
}
do {
try FileManager.default.createDirectory(at: destinationExperimentURL,
withIntermediateDirectories: true,
attributes: nil)
} catch {
finish(withErrors: [CopyImportedFilesError.cannotCreateDestinationDirectory])
return
}
var copyOperations = [CopyFileOperation]()
if let experimentProtoURL = importExperimentOperation.experimentProtoURL {
let experimentDestinationURL =
destinationExperimentURL.appendingPathComponent(experimentProtoURL.lastPathComponent)
copyOperations.append(CopyFileOperation(fromURL: experimentProtoURL,
toURL: experimentDestinationURL))
}
if let sensorDataProtoURL = importExperimentOperation.sensorDataProtoURL {
let sensorDataDestinationURL =
destinationExperimentURL.appendingPathComponent(sensorDataProtoURL.lastPathComponent)
copyOperations.append(CopyFileOperation(fromURL: sensorDataProtoURL,
toURL: sensorDataDestinationURL))
}
if importExperimentOperation.assets.count > 0 {
let assetsURL =
destinationExperimentURL.appendingPathComponent(MetadataManager.assetsDirectoryName)
do {
try FileManager.default.createDirectory(at: assetsURL,
withIntermediateDirectories: true,
attributes: nil)
} catch {
finish(withErrors: [CopyImportedFilesError.cannotCreateAssetsDirectory])
return
}
for assetURL in importExperimentOperation.assets {
let destinationAssetURL = assetsURL.appendingPathComponent(assetURL.lastPathComponent)
copyOperations.append(CopyFileOperation(fromURL: assetURL, toURL: destinationAssetURL))
}
}
for copyOp in copyOperations {
addDependency(copyOp)
addOperation(copyOp)
}
// GroupOperation's execute method begins the execution of all sub-operations, so it must be
// called last.
super.execute()
}
}
| apache-2.0 | c95ebe2610be1451757b0d8f08bfb482 | 37.826923 | 96 | 0.692917 | 5.486413 | false | false | false | false |
aleckretch/Bloom | iOS/Bloom/Bloom/Components/Add Card/Cells/AddCardHeaderTableViewCell.swift | 1 | 1010 | //
// AddCardHeaderTableViewCell.swift
// Bloom
//
// Created by Alec Kretch on 10/22/17.
// Copyright © 2017 Alec Kretch. All rights reserved.
//
import Foundation
import UIKit
class AddCardHeaderTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel! {
didSet {
titleLabel.font = UIFont.boldSystemFont(ofSize: 24.0)
titleLabel.numberOfLines = 0
}
}
@IBOutlet weak var dismissButton: UIButton! {
didSet {
dismissButton.isExclusiveTouch = true
dismissButton.tintColor = Constant.Color.lightGray
dismissButton.setImage(UIImage(named:"iconDismiss"), for: .normal)
dismissButton.contentMode = .center
}
}
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: UIScreen.main.bounds.size.width * 2)
// Initialization code
}
}
| mit | cba7627a181da62a53b365d61f66d43d | 26.27027 | 109 | 0.629336 | 4.714953 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.