repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
andrewcar/hoods | refs/heads/master | Project/hoods/hoods/HoodView.swift | mit | 1 | //
// HoodView.swift
// hoods
//
// Created by Andrew Carvajal on 9/22/17.
// Copyright © 2017 YugeTech. All rights reserved.
//
import UIKit
class HoodView: UIView {
var closedHoodConstraints = [NSLayoutConstraint]()
var openHoodConstraints = [NSLayoutConstraint]()
let primaryLabel = UILabel()
let secondaryLabel = UILabel()
let weatherLabel = UILabel()
var composeView = ComposeView()
var button = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
let labels = [primaryLabel, secondaryLabel, weatherLabel]
for label in labels {
label.translatesAutoresizingMaskIntoConstraints = false
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 0
}
primaryLabel.font = UIFont(name: Fonts.HelveticaNeue.bold, size: 100)
primaryLabel.textAlignment = .center
primaryLabel.textColor = UIColor(red: 142/255, green: 68/255, blue: 173/255, alpha: 1)
primaryLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 150), for: .vertical)
secondaryLabel.font = UIFont(name: Fonts.HelveticaNeue.bold, size: 50)
secondaryLabel.textAlignment = .right
secondaryLabel.textColor = UIColor(red: 46/255, green: 204/255, blue: 113/255, alpha: 1)
secondaryLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 151), for: .vertical)
weatherLabel.font = UIFont(name: Fonts.HelveticaNeue.bold, size: 50)
weatherLabel.textAlignment = .left
weatherLabel.textColor = .peterRiver
weatherLabel.text = "🤷🏻♂️"
composeView = ComposeView(frame: CGRect.zero)
composeView.translatesAutoresizingMaskIntoConstraints = false
composeView.textView.text = "blah blah blah"
button.translatesAutoresizingMaskIntoConstraints = false
addSubview(primaryLabel)
addSubview(secondaryLabel)
addSubview(weatherLabel)
addSubview(composeView)
addSubview(button)
activateClosedConstraints()
}
func activateClosedConstraints() {
NSLayoutConstraint.deactivate(closedHoodConstraints)
NSLayoutConstraint.deactivate(openHoodConstraints)
closedHoodConstraints = [
primaryLabel.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor),
primaryLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: 5),
primaryLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -5),
primaryLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.6),
secondaryLabel.topAnchor.constraint(equalTo: primaryLabel.bottomAnchor, constant: 0),
secondaryLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor, constant: 20),
secondaryLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -20),
secondaryLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.2),
weatherLabel.topAnchor.constraint(equalTo: primaryLabel.bottomAnchor, constant: 0),
weatherLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: 20),
weatherLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor, constant: -20),
weatherLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.2),
composeView.topAnchor.constraint(equalTo: weatherLabel.bottomAnchor, constant: Frames.si.padding),
composeView.leftAnchor.constraint(equalTo: leftAnchor, constant: Frames.si.padding),
composeView.rightAnchor.constraint(equalTo: rightAnchor, constant: -Frames.si.padding),
composeView.heightAnchor.constraint(equalToConstant: Frames.si.buttonSize.height + 8),
button.topAnchor.constraint(equalTo: topAnchor),
button.leftAnchor.constraint(equalTo: leftAnchor),
button.rightAnchor.constraint(equalTo: rightAnchor),
button.bottomAnchor.constraint(equalTo: bottomAnchor),
]
NSLayoutConstraint.activate(closedHoodConstraints)
}
func activateOpenConstraints() {
NSLayoutConstraint.deactivate(closedHoodConstraints)
NSLayoutConstraint.deactivate(openHoodConstraints)
openHoodConstraints = [
primaryLabel.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor),
primaryLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: 5),
primaryLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -5),
primaryLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.6),
secondaryLabel.topAnchor.constraint(equalTo: primaryLabel.bottomAnchor, constant: 0),
secondaryLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor, constant: 20),
secondaryLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -20),
secondaryLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.2),
weatherLabel.topAnchor.constraint(equalTo: primaryLabel.bottomAnchor, constant: 0),
weatherLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: 20),
weatherLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor, constant: -20),
weatherLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.2),
composeView.topAnchor.constraint(equalTo: weatherLabel.bottomAnchor, constant: Frames.si.padding),
composeView.leftAnchor.constraint(equalTo: leftAnchor, constant: Frames.si.padding),
composeView.rightAnchor.constraint(equalTo: rightAnchor, constant: -Frames.si.padding),
composeView.heightAnchor.constraint(equalToConstant: Frames.si.buttonSize.height + 8),
button.topAnchor.constraint(equalTo: topAnchor),
button.leftAnchor.constraint(equalTo: leftAnchor),
button.rightAnchor.constraint(equalTo: rightAnchor),
button.bottomAnchor.constraint(equalTo: bottomAnchor),
]
NSLayoutConstraint.activate(openHoodConstraints)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 75e87368c00960d110118ba01e8e44b1 | 49.151079 | 111 | 0.6966 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | KsApi/models/lenses/User.NewsletterSubscriptionsLenses.swift | apache-2.0 | 1 | import Prelude
extension User.NewsletterSubscriptions {
public enum lens {
public static let arts = Lens<User.NewsletterSubscriptions, Bool?>(
view: { $0.arts },
set: { User.NewsletterSubscriptions(
arts: $0,
games: $1.games,
happening: $1.happening,
invent: $1.invent,
promo: $1.promo,
weekly: $1.weekly,
films: $1.films,
publishing: $1.publishing,
alumni: $1.alumni,
music: $1.music
) }
)
public static let games = Lens<User.NewsletterSubscriptions, Bool?>(
view: { $0.games },
set: { User.NewsletterSubscriptions(
arts: $1.arts,
games: $0,
happening: $1.happening,
invent: $1.invent,
promo: $1.promo,
weekly: $1.weekly,
films: $1.films,
publishing: $1.publishing,
alumni: $1.alumni,
music: $1.music
) }
)
public static let happening = Lens<User.NewsletterSubscriptions, Bool?>(
view: { $0.happening },
set: { User.NewsletterSubscriptions(
arts: $1.arts,
games: $1.games,
happening: $0,
invent: $1.invent,
promo: $1.promo,
weekly: $1.weekly,
films: $1.films,
publishing: $1.publishing,
alumni: $1.alumni,
music: $1.music
) }
)
public static let invent = Lens<User.NewsletterSubscriptions, Bool?>(
view: { $0.invent },
set: { User.NewsletterSubscriptions(
arts: $1.arts,
games: $1.games,
happening: $1.happening,
invent: $0,
promo: $1.promo,
weekly: $1.weekly,
films: $1.films,
publishing: $1.publishing,
alumni: $1.alumni,
music: $1.music
) }
)
public static let promo = Lens<User.NewsletterSubscriptions, Bool?>(
view: { $0.promo },
set: { User.NewsletterSubscriptions(
arts: $1.arts,
games: $1.games,
happening: $1.happening,
invent: $1.invent,
promo: $0,
weekly: $1.weekly,
films: $1.films,
publishing: $1.publishing,
alumni: $1.alumni,
music: $1.music
) }
)
public static let weekly = Lens<User.NewsletterSubscriptions, Bool?>(
view: { $0.weekly },
set: { User.NewsletterSubscriptions(
arts: $1.arts,
games: $1.games,
happening: $1.happening,
invent: $1.invent,
promo: $1.promo,
weekly: $0,
films: $1.films,
publishing: $1.publishing,
alumni: $1.alumni,
music: $1.music
) }
)
public static let films = Lens<User.NewsletterSubscriptions, Bool?>(
view: { $0.films },
set: { User.NewsletterSubscriptions(
arts: $1.arts,
games: $1.games,
happening: $1.happening,
invent: $1.invent,
promo: $1.promo,
weekly: $1.weekly,
films: $0,
publishing: $1.publishing,
alumni: $1.alumni,
music: $1.music
) }
)
public static let publishing = Lens<User.NewsletterSubscriptions, Bool?>(
view: { $0.publishing },
set: { User.NewsletterSubscriptions(
arts: $1.arts,
games: $1.games,
happening: $1.happening,
invent: $1.invent,
promo: $1.promo,
weekly: $1.weekly,
films: $1.films,
publishing: $0,
alumni: $1.alumni,
music: $1.music
) }
)
public static let alumni = Lens<User.NewsletterSubscriptions, Bool?>(
view: { $0.alumni },
set: { User.NewsletterSubscriptions(
arts: $1.arts,
games: $1.games,
happening: $1.happening,
invent: $1.invent,
promo: $1.promo,
weekly: $1.weekly,
films: $1.films,
publishing: $1.publishing,
alumni: $0,
music: $1.music
) }
)
public static let music = Lens<User.NewsletterSubscriptions, Bool?>(
view: { $0.music },
set: { User.NewsletterSubscriptions(
arts: $1.arts,
games: $1.games,
happening: $1.happening,
invent: $1.invent,
promo: $1.promo,
weekly: $1.weekly,
films: $1.films,
publishing: $1.publishing,
alumni: $1.alumni,
music: $0
) }
)
}
}
| 546563dedf5409a4e7dce2acafa83da7 | 25.266667 | 77 | 0.529303 | false | false | false | false |
SwiftGFX/SwiftMath | refs/heads/master | Sources/Vector3+nosimd.swift | bsd-2-clause | 1 | //
// Vector3f+nosimd.swift
// SwiftMath
//
// Created by Andrey Volodin on 07.10.16.
//
//
#if NOSIMD
#if (os(OSX) || os(iOS) || os(tvOS) || os(watchOS))
import Darwin
#elseif os(Linux) || os(Android)
import Glibc
#endif
@frozen
public struct Vector3f {
public var x: Float = 0.0
public var y: Float = 0.0
public var z: Float = 0.0
public var r: Float { get { return x } set { x = newValue } }
public var g: Float { get { return y } set { y = newValue } }
public var b: Float { get { return z } set { z = newValue } }
public var s: Float { get { return x } set { x = newValue } }
public var t: Float { get { return y } set { y = newValue } }
public var p: Float { get { return z } set { z = newValue } }
public subscript(x: Int) -> Float {
get {
if x == 0 { return self.x }
if x == 1 { return self.y }
if x == 2 { return self.z }
fatalError("Index outside of bounds")
}
set {
if x == 0 { self.x = newValue; return }
if x == 1 { self.y = newValue; return }
if x == 2 { self.z = newValue; return }
fatalError("Index outside of bounds")
}
}
public init() {}
public init(_ x: Float, _ y: Float, _ z: Float) {
self.x = x
self.y = y
self.z = z
}
public init(_ scalar: Float) {
self.init(scalar, scalar, scalar)
}
public init(x: Float, y: Float, z: Float) {
self.init(x, y, z)
}
}
extension Vector3f {
public var lengthSquared: Float {
return x * x + y * y + z * z
}
public var length: Float {
return sqrt(self.lengthSquared)
}
public func dot(_ v: Vector3f) -> Float {
return x * v.x + y * v.y + z * v.z
}
public func cross(_ v: Vector3f) -> Vector3f {
return Vector3f(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x)
}
public var normalized: Vector3f {
let lengthSquared = self.lengthSquared
if lengthSquared ~= 0 || lengthSquared ~= 1 {
return self
}
return self / sqrt(lengthSquared)
}
public func interpolated(with v: Vector3f, by t: Float) -> Vector3f {
return self + (v - self) * t
}
public static prefix func -(v: Vector3f) -> Vector3f {
return Vector3f(-v.x, -v.y, -v.z)
}
public static func +(lhs: Vector3f, rhs: Vector3f) -> Vector3f {
return Vector3f(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z)
}
public static func -(lhs: Vector3f, rhs: Vector3f) -> Vector3f {
return Vector3f(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z)
}
public static func *(lhs: Vector3f, rhs: Vector3f) -> Vector3f {
return Vector3f(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z)
}
public static func *(lhs: Vector3f, rhs: Float) -> Vector3f {
return Vector3f(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs)
}
public static func /(lhs: Vector3f, rhs: Vector3f) -> Vector3f {
return Vector3f(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z)
}
public static func /(lhs: Vector3f, rhs: Float) -> Vector3f {
return Vector3f(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs)
}
public static func ~=(lhs: Vector3f, rhs: Vector3f) -> Bool {
return lhs.x ~= rhs.x && lhs.y ~= rhs.y && lhs.z ~= rhs.z
}
public static func *(lhs: Vector3f, rhs: Matrix3x3f) -> Vector3f {
return Vector3f(
lhs.x * rhs.m11 + lhs.y * rhs.m21 + lhs.z * rhs.m31,
lhs.x * rhs.m12 + lhs.y * rhs.m22 + lhs.z * rhs.m32,
lhs.x * rhs.m13 + lhs.y * rhs.m23 + lhs.z * rhs.m33
)
}
public static func *(lhs: Matrix3x3f, rhs: Vector3f) -> Vector3f {
return rhs * lhs
}
}
extension Vector3f: Equatable {
public static func ==(lhs: Vector3f, rhs: Vector3f) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
}
}
#endif
| 29e88b54976feace11e6c5a3d7fe0eb1 | 27.368056 | 80 | 0.521175 | false | false | false | false |
sschiau/swift | refs/heads/master | test/decl/func/dynamic_self.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -swift-version 5 -enable-objc-interop
// ----------------------------------------------------------------------------
// DynamicSelf is only allowed on the return type of class and
// protocol methods.
func global() -> Self { } // expected-error{{global function cannot return 'Self'}}
func inFunction() {
func local() -> Self { } // expected-error{{local function cannot return 'Self'}}
}
struct S0 {
func f() -> Self { }
func g(_ ds: Self) { }
}
enum E0 {
func f() -> Self { }
func g(_ ds: Self) { }
}
class C0 {
func f() -> Self { } // okay
func g(_ ds: Self) { } // expected-error{{covariant 'Self' can only appear as the type of a property, subscript or method result; did you mean 'C0'?}}
func h(_ ds: Self) -> Self { } // expected-error{{covariant 'Self' can only appear as the type of a property, subscript or method result; did you mean 'C0'?}}
}
protocol P0 {
func f() -> Self // okay
func g(_ ds: Self) // okay
}
extension P0 {
func h() -> Self { // okay
func g(_ t : Self) -> Self { // okay
return t
}
return g(self)
}
}
protocol P1: class {
func f() -> Self // okay
func g(_ ds: Self) // okay
}
extension P1 {
func h() -> Self { // okay
func g(_ t : Self) -> Self { // okay
return t
}
return g(self)
}
}
// ----------------------------------------------------------------------------
// The 'self' type of a Self method is based on Self
class C1 {
required init(int i: Int) {} // expected-note {{'init(int:)' declared here}}
// Instance methods have a self of type Self.
func f(_ b: Bool) -> Self {
// FIXME: below diagnostic should complain about C1 -> Self conversion
if b { return C1(int: 5) } // expected-error{{cannot convert return expression of type 'C1' to return type 'Self'}}
// One can use `type(of:)` to attempt to construct an object of type Self.
if !b { return type(of: self).init(int: 5) }
// Can utter Self within the body of a method.
var _: Self = self
// Okay to return 'self', because it has the appropriate type.
return self // okay
}
// Type methods have a self of type Self.Type.
class func factory(_ b: Bool) -> Self {
// Check directly.
var x: Int = self // expected-error{{cannot convert value of type 'Self.Type' to specified type 'Int'}}
// Can't utter Self within the body of a method.
var c1 = C1(int: 5) as Self // expected-error{{'C1' is not convertible to 'Self'; did you mean to use 'as!' to force downcast?}}
if b { return self.init(int: 5) }
return Self() // expected-error{{missing argument for parameter 'int' in call}} {{17-17=int: <#Int#>}}
}
// This used to crash because metatype construction went down a
// different code path that didn't handle DynamicSelfType.
class func badFactory() -> Self {
return self(int: 0)
// expected-error@-1 {{initializing from a metatype value must reference 'init' explicitly}}
}
}
// ----------------------------------------------------------------------------
// Using a method with a Self result carries the receiver type.
class X {
func instance() -> Self {
}
class func factory() -> Self {
}
func produceX() -> X { }
}
class Y : X {
func produceY() -> Y { }
}
func testInvokeInstanceMethodSelf() {
// Trivial case: invoking on the declaring class.
var x = X()
var x2 = x.instance()
x = x2 // at least an X
x2 = x // no more than an X
// Invoking on a subclass.
var y = Y()
var y2 = y.instance();
y = y2 // at least a Y
y2 = y // no more than a Y
}
func testInvokeTypeMethodSelf() {
// Trivial case: invoking on the declaring class.
var x = X()
var x2 = X.factory()
x = x2 // at least an X
x2 = x // no more than an X
// Invoking on a subclass.
var y = Y()
var y2 = Y.factory()
y = y2 // at least a Y
y2 = y // no more than a Y
}
func testCurryInstanceMethodSelf() {
// Trivial case: currying on the declaring class.
var produceX = X.produceX
var produceX2 = X.instance
produceX = produceX2
produceX2 = produceX
// Currying on a subclass.
var produceY = Y.produceY
var produceY2 = Y.instance
produceY = produceY2
produceY2 = produceY
}
class GX<T> {
func instance() -> Self {
}
class func factory() -> Self {
}
func produceGX() -> GX { }
}
class GY<T> : GX<[T]> {
func produceGY() -> GY { }
}
func testInvokeInstanceMethodSelfGeneric() {
// Trivial case: invoking on the declaring class.
var x = GX<Int>()
var x2 = x.instance()
x = x2 // at least an GX<Int>
x2 = x // no more than an GX<Int>
// Invoking on a subclass.
var y = GY<Int>()
var y2 = y.instance();
y = y2 // at least a GY<Int>
y2 = y // no more than a GY<Int>
}
func testInvokeTypeMethodSelfGeneric() {
// Trivial case: invoking on the declaring class.
var x = GX<Int>()
var x2 = GX<Int>.factory()
x = x2 // at least an GX<Int>
x2 = x // no more than an GX<Int>
// Invoking on a subclass.
var y = GY<Int>()
var y2 = GY<Int>.factory();
y = y2 // at least a GY<Int>
y2 = y // no more than a GY<Int>
}
func testCurryInstanceMethodSelfGeneric() {
// Trivial case: currying on the declaring class.
var produceGX = GX<Int>.produceGX
var produceGX2 = GX<Int>.instance
produceGX = produceGX2
produceGX2 = produceGX
// Currying on a subclass.
var produceGY = GY<Int>.produceGY
var produceGY2 = GY<Int>.instance
produceGY = produceGY2
produceGY2 = produceGY
}
// ----------------------------------------------------------------------------
// Overriding a method with a Self
class Z : Y {
override func instance() -> Self {
}
override class func factory() -> Self {
}
}
func testOverriddenMethodSelfGeneric() {
var z = Z()
var z2 = z.instance();
z = z2
z2 = z
var z3 = Z.factory()
z = z3
z3 = z
}
// ----------------------------------------------------------------------------
// Generic uses of Self methods.
protocol P {
func f() -> Self
}
func testGenericCall<T: P>(_ t: T) {
var t = t
var t2 = t.f()
t2 = t
t = t2
}
// ----------------------------------------------------------------------------
// Existential uses of Self methods.
func testExistentialCall(_ p: P) {
_ = p.f()
}
// ----------------------------------------------------------------------------
// Dynamic lookup of Self methods.
@objc class SomeClass {
@objc func method() -> Self { return self }
}
func testAnyObject(_ ao: AnyObject) {
var ao = ao
var result : AnyObject = ao.method!()
result = ao
ao = result
}
// ----------------------------------------------------------------------------
// Name lookup on Self values
extension Y {
func testInstance() -> Self {
if false { return self.instance() }
return instance()
}
class func testFactory() -> Self {
if false { return self.factory() }
return factory()
}
}
// ----------------------------------------------------------------------------
// Optional Self returns
extension X {
func tryToClone() -> Self? { return nil }
func tryHarderToClone() -> Self! { return nil }
func cloneOrFail() -> Self { return self }
func cloneAsObjectSlice() -> X? { return self }
}
extension Y {
func operationThatOnlyExistsOnY() {}
}
func testOptionalSelf(_ y : Y) {
if let clone = y.tryToClone() {
clone.operationThatOnlyExistsOnY()
}
// Sanity-checking to make sure that the above succeeding
// isn't coincidental.
if let clone = y.cloneOrFail() { // expected-error {{initializer for conditional binding must have Optional type, not 'Y'}}
clone.operationThatOnlyExistsOnY()
}
// Sanity-checking to make sure that the above succeeding
// isn't coincidental.
if let clone = y.cloneAsObjectSlice() {
clone.operationThatOnlyExistsOnY() // expected-error {{value of type 'X' has no member 'operationThatOnlyExistsOnY'}}
}
if let clone = y.tryHarderToClone().tryToClone() {
clone.operationThatOnlyExistsOnY();
}
}
// ----------------------------------------------------------------------------
// Conformance lookup on Self
protocol Runcible {
associatedtype Runcer
}
extension Runcible {
func runce() {}
func runced(_: Runcer) {}
}
func wantsRuncible<T : Runcible>(_: T) {}
class Runce : Runcible {
typealias Runcer = Int
func getRunced() -> Self {
runce()
wantsRuncible(self)
runced(3)
return self
}
}
// ----------------------------------------------------------------------------
// Forming a type with 'Self' in invariant position
struct Generic<T> { init(_: T) {} } // expected-note {{arguments to generic parameter 'T' ('Self' and 'InvariantSelf') are expected to be equal}}
// expected-note@-1 {{arguments to generic parameter 'T' ('Self' and 'FinalInvariantSelf') are expected to be equal}}
class InvariantSelf {
func me() -> Self {
let a = Generic(self)
let _: Generic<InvariantSelf> = a
// expected-error@-1 {{cannot assign value of type 'Generic<Self>' to type 'Generic<InvariantSelf>'}}
return self
}
}
// FIXME: This should be allowed
final class FinalInvariantSelf {
func me() -> Self {
let a = Generic(self)
let _: Generic<FinalInvariantSelf> = a
// expected-error@-1 {{cannot assign value of type 'Generic<Self>' to type 'Generic<FinalInvariantSelf>'}}
return self
}
}
// ----------------------------------------------------------------------------
// Semi-bogus factory init pattern
protocol FactoryPattern {
init(factory: @autoclosure () -> Self)
}
extension FactoryPattern {
init(factory: @autoclosure () -> Self) { self = factory() }
}
class Factory : FactoryPattern {
init(_string: String) {}
convenience init(string: String) {
self.init(factory: Factory(_string: string))
// expected-error@-1 {{incorrect argument label in call (have 'factory:', expected '_string:')}}
// FIXME: Bogus diagnostic
}
}
// Final classes are OK
final class FinalFactory : FactoryPattern {
init(_string: String) {}
convenience init(string: String) {
self.init(factory: FinalFactory(_string: string))
}
}
// Operators returning Self
class SelfOperator {
required init() {}
static func +(lhs: SelfOperator, rhs: SelfOperator) -> Self {
return self.init()
}
func double() -> Self {
// FIXME: Should this work?
return self + self // expected-error {{cannot convert return expression of type 'SelfOperator' to return type 'Self'}}
}
}
func useSelfOperator() {
let s = SelfOperator()
_ = s + s
}
// for ... in loops
struct DummyIterator : IteratorProtocol {
func next() -> Int? { return nil }
}
class Iterable : Sequence {
func returnsSelf() -> Self {
for _ in self {}
return self
}
func makeIterator() -> DummyIterator {
return DummyIterator()
}
}
// Default arguments of methods cannot capture 'Self' or 'self'
class MathClass {
func invalidDefaultArg(s: Int = Self.intMethod()) {}
// expected-error@-1 {{covariant 'Self' type cannot be referenced from a default argument expression}}
static func intMethod() -> Int { return 0 }
}
| 73c25adf37e3974546a4ca3b98f0bb28 | 23.791946 | 160 | 0.584642 | false | false | false | false |
Brandon-J-Campbell/codemash | refs/heads/master | AutoLayoutSession/completed/demo10/codemash/ScheduleCollectionViewController.swift | mit | 7 | //
// ScheduleCollectionViewController.swift
// codemash
//
// Created by Brandon Campbell on 12/30/16.
// Copyright © 2016 Brandon Campbell. All rights reserved.
//
import Foundation
import UIKit
class ScheduleeRow {
var header : String?
var items = Array<ScheduleeRow>()
var session : Session?
convenience init(withHeader: String, items: Array<ScheduleeRow>) {
self.init()
self.header = withHeader
self.items = items
}
convenience init(withSession: Session) {
self.init()
self.session = withSession
}
}
class ScheduleCollectionCell : UICollectionViewCell {
@IBOutlet var titleLabel : UILabel?
@IBOutlet var roomLabel: UILabel?
@IBOutlet var speakerImageView: UIImageView?
var session : Session?
var isHeightCalculated: Bool = false
static func cellIdentifier() -> String {
return "ScheduleCollectionCell"
}
static func cell(forCollectionView collectionView: UICollectionView, indexPath: IndexPath, session: Session) -> ScheduleCollectionCell {
let cell : ScheduleCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: ScheduleCollectionCell.cellIdentifier(), for: indexPath) as! ScheduleCollectionCell
cell.speakerImageView?.image = nil
cell.titleLabel?.text = session.title
cell.roomLabel?.text = session.rooms[0]
cell.session = session
if let url = URL.init(string: "https:" + (session.speakers[0].gravatarUrl)) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
cell.speakerImageView?.image = UIImage(data: data)
}
}.resume()
}
return cell
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
setNeedsLayout()
layoutIfNeeded()
var layoutSize : CGSize = layoutAttributes.size
layoutSize.height = 80.0
let size = contentView.systemLayoutSizeFitting(layoutSize)
var newFrame = layoutAttributes.frame
newFrame.size.height = CGFloat(ceilf(Float(size.height)))
layoutAttributes.frame = newFrame
return layoutAttributes
}
}
class ScheduleCollectionHeaderView : UICollectionReusableView {
@IBOutlet var headerLabel : UILabel?
static func cellIdentifier() -> String {
return "ScheduleCollectionHeaderView"
}
}
class ScheduleCollectionViewController : UICollectionViewController {
var sections = Array<ScheduleTableRow>()
var sessions : Array<Session> = Array<Session>.init() {
didSet {
self.data = Dictionary<Date, Array<Session>>()
self.setupSections()
}
}
var data = Dictionary<Date, Array<Session>>()
override func viewDidLoad() {
super.viewDidLoad()
var width : CGFloat
let flowLayout : UICollectionViewFlowLayout = collectionViewLayout as! UICollectionViewFlowLayout
if (self.view.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.compact) {
width = ((self.collectionView?.bounds.size.width)! - flowLayout.minimumLineSpacing - flowLayout.minimumInteritemSpacing - flowLayout.sectionInset.left - flowLayout.sectionInset.right)
} else {
width = ((self.collectionView?.bounds.size.width)! - flowLayout.minimumLineSpacing - flowLayout.minimumInteritemSpacing - flowLayout.sectionInset.left - flowLayout.sectionInset.right) / ((self.collectionView?.bounds.size.width)! > 800.0 ? 3.0 : 2.0)
}
flowLayout.estimatedItemSize = CGSize(width: width, height: 100)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showSession" {
let vc = segue.destination as! SessionViewController
let cell = sender as! ScheduleCollectionCell
vc.session = cell.session
}
}
func setupSections() {
let timeFormatter = DateFormatter.init()
timeFormatter.dateFormat = "EEEE h:mm:ssa"
for session in self.sessions {
if data[session.startTime] == nil {
data[session.startTime] = Array<Session>()
}
data[session.startTime]?.append(session)
}
var sections : Array<ScheduleTableRow> = []
for key in data.keys.sorted() {
var rows : Array<ScheduleTableRow> = []
for session in data[key]! {
rows.append(ScheduleTableRow.init(withSession: session))
}
let time = timeFormatter.string(from: key)
sections.append(ScheduleTableRow.init(withHeader: time, items: rows))
}
self.sections = sections
self.collectionView?.reloadData()
}
}
extension ScheduleCollectionViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.sections.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let section = self.sections[section]
return section.items.count
}
}
extension ScheduleCollectionViewController {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let section = self.sections[indexPath.section]
let row = section.items[indexPath.row]
let cell = ScheduleCollectionCell.cell(forCollectionView: collectionView, indexPath: indexPath, session: row.session!)
cell.contentView.layer.cornerRadius = 10
cell.contentView.layer.borderColor = UIColor.black.cgColor
if (self.view.traitCollection.horizontalSizeClass != UIUserInterfaceSizeClass.compact) {
cell.contentView.layer.borderWidth = 1.0
} else {
cell.contentView.layer.borderWidth = 0.0
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let section = self.sections[indexPath.section]
let headerView: ScheduleCollectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ScheduleCollectionHeaderView.cellIdentifier(), for: indexPath) as! ScheduleCollectionHeaderView
headerView.headerLabel?.text = section.header
return headerView
}
}
| 0e3bc1e733c78094a1b7b2da6b132517 | 37.60221 | 261 | 0.657936 | false | false | false | false |
tiagomartinho/FastBike | refs/heads/master | FastBikeWatchOS Extension/InterfaceController+CLManagerDelegate.swift | mit | 1 | import CoreLocation
import MapKit
extension InterfaceController: CLLocationManagerDelegate {
func getUserPosition() {
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let coordinate = locations.last?.coordinate {
location = CLLocation(latitude: coordinate.latitude,
longitude: coordinate.longitude)
setMapZoomIfNeeded(location: location!)
}
}
func setMapZoomIfNeeded(location: CLLocation) {
if mapZoomSet { return }
mapZoomSet = true
let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let locationRegion = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: locationRegion, span: span)
mapView.setRegion(region)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
}
}
| f142841840ec91d1859f797aaa33742f | 37.705882 | 133 | 0.692249 | false | false | false | false |
kevinhankens/runalysis | refs/heads/master | Runalysis/RockerStepper.swift | mit | 1 | //
// RockerStepper.swift
// Runalysis
//
// Created by Kevin Hankens on 7/14/14.
// Copyright (c) 2014 Kevin Hankens. All rights reserved.
//
import Foundation
import UIKit
/*!
* @class RockerStepper
*
* This is a custom implementation of a UIStepper which provides defaults
* as well as custom formatting for the value.
*/
class RockerStepper: UIStepper {
/*!
* Constructor.
*
* @param CGRect frame
*/
override init(frame: CGRect) {
super.init(frame: frame)
minimumValue = 0.0
maximumValue = 100.0
stepValue = 0.25
autorepeat = true
}
required init(coder aDecoder: NSCoder) {
//fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
}
/*!
* Gets a custom label based upon the internal value.
*
* @param Double miles
*
* @return String
*/
class func getLabel(miles:Double)->String {
var mval = Int(miles)
var dval = Int(round((miles - Double(mval)) * 100))
var dtext = "\(dval)"
if dval < 10 {
dtext = "0\(dval)"
}
//var numerator = Int(4.0 * rval)
//
//var fraction = ""
//switch numerator {
//case 1.0:
// fraction = "¼"
//case 2.0:
// fraction = "½"
//case 3.0:
// fraction = "¾"
//default:
// fraction = ""
//}
return "\(Int(miles)).\(dtext)"
}
}
| 2dd2fa2465422b6bb4cc2cacbc2bab69 | 21.367647 | 73 | 0.520053 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Controllers/Preferences/ChangeAppIcon/ChangeAppIconCell.swift | mit | 1 | //
// ChangeAppIconCell.swift
// Rocket.Chat
//
// Created by Artur Rymarz on 08.02.2018.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
final class ChangeAppIconCell: UICollectionViewCell {
@IBOutlet private weak var iconImageView: UIImageView! {
didSet {
iconImageView.isAccessibilityElement = true
}
}
@IBOutlet private weak var checkImageView: UIImageView!
@IBOutlet private weak var checkImageViewBackground: UIView!
func setIcon(name: (String, String), selected: Bool) {
iconImageView.image = UIImage(named: name.0)
iconImageView.accessibilityLabel = VOLocalizedString(name.1)
if selected {
iconImageView.layer.borderColor = UIColor.RCBlue().cgColor
iconImageView.layer.borderWidth = 3
iconImageView.accessibilityTraits = .selected
checkImageView.image = checkImageView.image?.imageWithTint(UIColor.RCBlue())
checkImageView.isHidden = false
checkImageViewBackground.isHidden = false
} else {
iconImageView.layer.borderColor = UIColor.RCLightGray().cgColor
iconImageView.layer.borderWidth = 1
iconImageView.accessibilityTraits = .none
checkImageView.isHidden = true
checkImageViewBackground.isHidden = true
}
}
}
| e46eef6e44080d2d0c8be9077a780975 | 31.023256 | 88 | 0.668119 | false | false | false | false |
shamanskyh/FluidQ | refs/heads/master | FluidQ/Magic Sheet/InstrumentGroup.swift | mit | 1 | //
// InstrumentGroup.swift
// FluidQ
//
// Created by Harry Shamansky on 11/16/15.
// Copyright © 2015 Harry Shamansky. All rights reserved.
//
import UIKit
class InstrumentGroup: NSObject {
var instruments: [[Instrument]] {
didSet {
var lowestChannel: Int?
for row in instruments {
for instrument in row {
if let channel = instrument.channel where channel < lowestChannel || lowestChannel == nil {
lowestChannel = channel
}
}
}
if let lowest = lowestChannel {
startingChannelNumber = lowest
} else {
startingChannelNumber = Int.max
}
}
}
var purpose: String?
var startingChannelNumber: Int = Int.max
init(withInstruments instruments: [Instrument], purpose: String?) {
var yPositions: [Double] = []
var groupedInstruments: [[Instrument]] = []
let filteredInstruments = instruments.filter({ $0.location != nil })
for i in 0..<filteredInstruments.count {
if yPositions.count == 0 {
yPositions.append(filteredInstruments[i].location!.y)
groupedInstruments.append([filteredInstruments[i]])
} else {
var foundMatch = false
for j in 0..<yPositions.count {
if abs(filteredInstruments[i].location!.y - yPositions[j]) < kMagicSheetRowThreshold {
groupedInstruments[j].append(filteredInstruments[i])
foundMatch = true
}
}
if !foundMatch {
yPositions.append(filteredInstruments[i].location!.y)
groupedInstruments.append([filteredInstruments[i]])
}
}
}
// sort instruments by channel within row
for i in 0..<groupedInstruments.count {
groupedInstruments[i] = groupedInstruments[i].sort({ $0.channel < $1.channel })
}
// create tuples to easily sort rows from highest to lowest (since iOS origin is top-left)
var tempRows: [(Double, [Instrument])] = []
for i in 0..<yPositions.count {
tempRows.append((yPositions[i], groupedInstruments[i]))
}
tempRows.sortInPlace({ $0.0 > $1.0 })
self.instruments = []
self.purpose = purpose
super.init()
// add the instruments
tempRows.forEach({ self.instruments.append($0.1) })
}
}
| 3f16136d8cd501061c1d96acb482d5f6 | 33.441558 | 111 | 0.53356 | false | false | false | false |
dasdom/Swiftandpainless | refs/heads/master | SwiftAndPainlessPlayground.playground/Pages/Classes - Basics.xcplaygroundpage/Contents.swift | mit | 1 | import Foundation
/*:
[⬅️](@previous) [➡️](@next)
# Classes: Basics
*/
class ToDo {
var name: String = "er"
let dueDate: NSDate
let locationName: String
init(name: String, date: NSDate, locationName: String) {
self.name = name
dueDate = date
self.locationName = locationName
}
}
let todo = ToDo(name: "Give talk", date: NSDate(), locationName: "Köln")
print(todo)
/*:
Classes don't have automatic initializers and they also don't print nicely by their own.
*/
| deec4b739381e57a2ac2a1d747be0c91 | 20.391304 | 89 | 0.660569 | false | false | false | false |
Quick/Nimble | refs/heads/main | Bootstrap/Pods/Nimble/Sources/Nimble/Expression.swift | apache-2.0 | 2 | // Memoizes the given closure, only calling the passed
// closure once; even if repeat calls to the returned closure
private func memoizedClosure<T>(_ closure: @escaping () throws -> T) -> (Bool) throws -> T {
var cache: T?
return { withoutCaching in
if withoutCaching || cache == nil {
cache = try closure()
}
return cache!
}
}
/// Expression represents the closure of the value inside expect(...).
/// Expressions are memoized by default. This makes them safe to call
/// evaluate() multiple times without causing a re-evaluation of the underlying
/// closure.
///
/// - Warning: Since the closure can be any code, Objective-C code may choose
/// to raise an exception. Currently, SyncExpression does not memoize
/// exception raising.
///
/// This provides a common consumable API for matchers to utilize to allow
/// Nimble to change internals to how the captured closure is managed.
public struct Expression<Value> {
internal let _expression: (Bool) throws -> Value?
internal let _withoutCaching: Bool
public let location: SourceLocation
public let isClosure: Bool
/// Creates a new expression struct. Normally, expect(...) will manage this
/// creation process. The expression is memoized.
///
/// - Parameter expression: The closure that produces a given value.
/// - Parameter location: The source location that this closure originates from.
/// - Parameter isClosure: A bool indicating if the captured expression is a
/// closure or internally produced closure. Some matchers
/// may require closures. For example, toEventually()
/// requires an explicit closure. This gives Nimble
/// flexibility if @autoclosure behavior changes between
/// Swift versions. Nimble internals always sets this true.
public init(expression: @escaping () throws -> Value?, location: SourceLocation, isClosure: Bool = true) {
self._expression = memoizedClosure(expression)
self.location = location
self._withoutCaching = false
self.isClosure = isClosure
}
/// Creates a new expression struct. Normally, expect(...) will manage this
/// creation process.
///
/// - Parameter expression: The closure that produces a given value.
/// - Parameter location: The source location that this closure originates from.
/// - Parameter withoutCaching: Indicates if the struct should memoize the given
/// closure's result. Subsequent evaluate() calls will
/// not call the given closure if this is true.
/// - Parameter isClosure: A bool indicating if the captured expression is a
/// closure or internally produced closure. Some matchers
/// may require closures. For example, toEventually()
/// requires an explicit closure. This gives Nimble
/// flexibility if @autoclosure behavior changes between
/// Swift versions. Nimble internals always sets this true.
public init(memoizedExpression: @escaping (Bool) throws -> Value?, location: SourceLocation, withoutCaching: Bool, isClosure: Bool = true) {
self._expression = memoizedExpression
self.location = location
self._withoutCaching = withoutCaching
self.isClosure = isClosure
}
/// Returns a new Expression from the given expression. Identical to a map()
/// on this type. This should be used only to typecast the Expression's
/// closure value.
///
/// The returned expression will preserve location and isClosure.
///
/// - Parameter block: The block that can cast the current Expression value to a
/// new type.
public func cast<U>(_ block: @escaping (Value?) throws -> U?) -> Expression<U> {
return Expression<U>(
expression: ({ try block(self.evaluate()) }),
location: self.location,
isClosure: self.isClosure
)
}
public func evaluate() throws -> Value? {
return try self._expression(_withoutCaching)
}
public func withoutCaching() -> Expression<Value> {
return Expression(
memoizedExpression: self._expression,
location: location,
withoutCaching: true,
isClosure: isClosure
)
}
}
| b12ba498de08f515f44bc0c429d46ded | 45.319588 | 144 | 0.638104 | false | false | false | false |
ScoutHarris/WordPress-iOS | refs/heads/develop | WordPress/Classes/Utility/Media/MediaFileManager.swift | gpl-2.0 | 2 | import Foundation
import CocoaLumberjack
/// Type of the local Media directory URL in implementation.
///
enum MediaDirectory {
/// Default, system Documents directory, for persisting media files for upload.
case uploads
/// System Caches directory, for creating discardable media files, such as thumbnails.
case cache
/// System temporary directory, used for unit testing or temporary media files.
case temporary
/// Returns the directory URL for the directory type.
///
fileprivate var url: URL {
let fileManager = FileManager.default
// Get a parent directory, based on the type.
let parentDirectory: URL
switch self {
case .uploads:
parentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
case .cache:
parentDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
case .temporary:
parentDirectory = fileManager.temporaryDirectory
}
return parentDirectory.appendingPathComponent(MediaFileManager.mediaDirectoryName, isDirectory: true)
}
}
/// Encapsulates Media functions relative to the local Media directory.
///
class MediaFileManager: NSObject {
fileprivate static let mediaDirectoryName = "Media"
let directory: MediaDirectory
// MARK: - Class init
/// The default instance of a MediaFileManager.
///
@objc (defaultManager)
static let `default`: MediaFileManager = {
return MediaFileManager()
}()
/// Helper method for getting a MediaFileManager for the .cache directory.
///
@objc (cacheManager)
class var cache: MediaFileManager {
return MediaFileManager(directory: .cache)
}
// MARK: - Init
/// Init with default directory of .uploads.
///
/// - Note: This is particularly because the original Media directory was in the NSFileManager's documents directory.
/// We shouldn't change this default directory lightly as older versions of the app may rely on Media files being in
/// the documents directory for upload.
///
init(directory: MediaDirectory = .uploads) {
self.directory = directory
}
// MARK: - Instance methods
/// Returns filesystem URL for the local Media directory.
///
func directoryURL() throws -> URL {
let fileManager = FileManager.default
let mediaDirectory = directory.url
// Check whether or not the file path exists for the Media directory.
// If the filepath does not exist, or if the filepath does exist but it is not a directory, try creating the directory.
// Note: This way, if unexpectedly a file exists but it is not a dir, an error will throw when trying to create the dir.
var isDirectory: ObjCBool = false
if fileManager.fileExists(atPath: mediaDirectory.path, isDirectory: &isDirectory) == false || isDirectory.boolValue == false {
try fileManager.createDirectory(at: mediaDirectory, withIntermediateDirectories: true, attributes: nil)
}
return mediaDirectory
}
/// Returns a unique filesystem URL for a Media filename and extension, within the local Media directory.
///
/// - Note: if a file already exists with the same name, the file name is appended with a number
/// and incremented until a unique filename is found.
///
func makeLocalMediaURL(withFilename filename: String, fileExtension: String?, incremented: Bool = true) throws -> URL {
let baseURL = try directoryURL()
var url: URL
if let fileExtension = fileExtension {
let basename = (filename as NSString).deletingPathExtension.lowercased()
url = baseURL.appendingPathComponent(basename, isDirectory: false)
url.appendPathExtension(fileExtension)
} else {
url = baseURL.appendingPathComponent(filename, isDirectory: false)
}
// Increment the filename as needed to ensure we're not
// providing a URL for an existing file of the same name.
return incremented ? url.incrementalFilename() : url
}
/// Objc friendly signature without specifying the `incremented` parameter.
///
func makeLocalMediaURL(withFilename filename: String, fileExtension: String?) throws -> URL {
return try makeLocalMediaURL(withFilename: filename, fileExtension: fileExtension, incremented: true)
}
/// Returns a string appended with the thumbnail naming convention for local Media files.
///
func mediaFilenameAppendingThumbnail(_ filename: String) -> String {
var filename = filename as NSString
let pathExtension = filename.pathExtension
filename = filename.deletingPathExtension.appending("-thumbnail") as NSString
return filename.appendingPathExtension(pathExtension)!
}
/// Returns the size of a Media image located at the file URL, or zero if it doesn't exist.
///
/// - Note: once we drop ObjC, this should be an optional that would return nil instead of zero.
///
func imageSizeForMediaAt(fileURL: URL?) -> CGSize {
guard let fileURL = fileURL else {
return CGSize.zero
}
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
guard fileManager.fileExists(atPath: fileURL.path, isDirectory: &isDirectory) == true, isDirectory.boolValue == false else {
return CGSize.zero
}
guard
let imageSource = CGImageSourceCreateWithURL(fileURL as CFURL, nil),
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? Dictionary<String, AnyObject>
else {
return CGSize.zero
}
var width = CGFloat(0), height = CGFloat(0)
if let widthProperty = imageProperties[kCGImagePropertyPixelWidth as String] as? CGFloat {
width = widthProperty
}
if let heightProperty = imageProperties[kCGImagePropertyPixelHeight as String] as? CGFloat {
height = heightProperty
}
return CGSize(width: width, height: height)
}
/// Calculates the allocated size of the Media directory, in bytes, or nil if an error was thrown.
///
func calculateSizeOfDirectory(onCompletion: @escaping (Int64?) -> Void) {
DispatchQueue.global(qos: .default).async {
let fileManager = FileManager.default
let allocatedSize = try? fileManager.allocatedSizeOf(directoryURL: self.directoryURL())
DispatchQueue.main.async {
onCompletion(allocatedSize)
}
}
}
/// Clear the local Media directory of any files that are no longer in use or can be fetched again,
/// such as Media without a blog or with a remote URL.
///
/// - Note: These files can show up because of the app being killed while a media object
/// was being created or when a CoreData migration fails and the database is recreated.
///
func clearUnusedFilesFromDirectory(onCompletion: (() -> Void)?, onError: ((Error) -> Void)?) {
purgeMediaFiles(exceptMedia: NSPredicate(format: "blog != NULL || remoteURL == NULL"),
onCompletion: onCompletion,
onError: onError)
}
/// Clear the local Media directory of any cached media files that are available remotely.
///
func clearFilesFromDirectory(onCompletion: (() -> Void)?, onError: ((Error) -> Void)?) {
do {
try purgeDirectory(exceptFiles: [])
onCompletion?()
} catch {
onError?(error)
}
}
// MARK: - Class methods
/// Helper method for clearing unused Media upload files.
///
class func clearUnusedMediaUploadFiles(onCompletion: (() -> Void)?, onError: ((Error) -> Void)?) {
MediaFileManager.default.clearUnusedFilesFromDirectory(onCompletion: onCompletion, onError: onError)
}
/// Helper method for calculating the size of the Media cache directory.
///
class func calculateSizeOfMediaCacheDirectory(onCompletion: @escaping (Int64?) -> Void) {
let cacheManager = MediaFileManager(directory: .cache)
cacheManager.calculateSizeOfDirectory(onCompletion: onCompletion)
}
/// Helper method for clearing the Media cache directory.
///
class func clearAllMediaCacheFiles(onCompletion: (() -> Void)?, onError: ((Error) -> Void)?) {
let cacheManager = MediaFileManager(directory: .cache)
cacheManager.clearFilesFromDirectory(onCompletion: onCompletion, onError: onError)
}
/// Helper method for getting the default upload directory URL.
///
class func uploadsDirectoryURL() throws -> URL {
return try MediaFileManager.default.directoryURL()
}
// MARK: - Private
/// Removes any local Media files, except any Media matching the predicate.
///
fileprivate func purgeMediaFiles(exceptMedia predicate: NSPredicate, onCompletion: (() -> Void)?, onError: ((Error) -> Void)?) {
let context = ContextManager.sharedInstance().newDerivedContext()
context.perform {
let fetch = NSFetchRequest<NSDictionary>(entityName: Media.classNameWithoutNamespaces())
fetch.predicate = predicate
fetch.resultType = .dictionaryResultType
let localURLProperty = #selector(getter: Media.localURL).description
let localThumbnailURLProperty = #selector(getter: Media.localThumbnailURL).description
fetch.propertiesToFetch = [localURLProperty,
localThumbnailURLProperty]
do {
let mediaToKeep = try context.fetch(fetch)
var filesToKeep: Set<String> = []
for dictionary in mediaToKeep {
if let localPath = dictionary[localURLProperty] as? String,
let localURL = URL(string: localPath) {
filesToKeep.insert(localURL.lastPathComponent)
}
if let localThumbnailPath = dictionary[localThumbnailURLProperty] as? String,
let localThumbnailURL = URL(string: localThumbnailPath) {
filesToKeep.insert(localThumbnailURL.lastPathComponent)
}
}
try self.purgeDirectory(exceptFiles: filesToKeep)
if let onCompletion = onCompletion {
DispatchQueue.main.async {
onCompletion()
}
}
} catch {
DDLogError("Error while attempting to clean local media: \(error.localizedDescription)")
if let onError = onError {
DispatchQueue.main.async {
onError(error)
}
}
}
}
}
/// Removes files in the Media directory, except any files found in the set.
///
fileprivate func purgeDirectory(exceptFiles: Set<String>) throws {
let fileManager = FileManager.default
let contents = try fileManager.contentsOfDirectory(at: try directoryURL(),
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles)
var removedCount = 0
for url in contents {
if exceptFiles.contains(url.lastPathComponent) {
continue
}
if fileManager.fileExists(atPath: url.path) {
do {
try fileManager.removeItem(at: url)
removedCount += 1
} catch {
DDLogError("Error while removing unused Media at path: \(error.localizedDescription) - \(url.path)")
}
}
}
if removedCount > 0 {
DDLogInfo("Media: removed \(removedCount) file(s) during cleanup.")
}
}
}
| ad9cd285a1bc9e87169aaaa2e2d9f2dc | 42.174377 | 134 | 0.631635 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | refs/heads/main | Buy/Generated/Storefront/SellingPlanFixedPriceAdjustment.swift | mit | 1 | //
// SellingPlanFixedPriceAdjustment.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// A fixed price adjustment for a variant that's purchased with a selling
/// plan.
open class SellingPlanFixedPriceAdjustmentQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = SellingPlanFixedPriceAdjustment
/// A new price of the variant when it's purchased with the selling plan.
@discardableResult
open func price(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> SellingPlanFixedPriceAdjustmentQuery {
let subquery = MoneyV2Query()
subfields(subquery)
addField(field: "price", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// A fixed price adjustment for a variant that's purchased with a selling
/// plan.
open class SellingPlanFixedPriceAdjustment: GraphQL.AbstractResponse, GraphQLObject, SellingPlanPriceAdjustmentValue {
public typealias Query = SellingPlanFixedPriceAdjustmentQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "price":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: SellingPlanFixedPriceAdjustment.self, field: fieldName, value: fieldValue)
}
return try MoneyV2(fields: value)
default:
throw SchemaViolationError(type: SellingPlanFixedPriceAdjustment.self, field: fieldName, value: fieldValue)
}
}
/// A new price of the variant when it's purchased with the selling plan.
open var price: Storefront.MoneyV2 {
return internalGetPrice()
}
func internalGetPrice(alias: String? = nil) -> Storefront.MoneyV2 {
return field(field: "price", aliasSuffix: alias) as! Storefront.MoneyV2
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "price":
response.append(internalGetPrice())
response.append(contentsOf: internalGetPrice().childResponseObjectMap())
default:
break
}
}
return response
}
}
}
| 81feab08f2790475e4ce2a76be87a390 | 36.47191 | 119 | 0.73913 | false | false | false | false |
Brightify/ReactantUI | refs/heads/master | Sources/Live/Debug/DebugAlertController.swift | mit | 1 | //
// DebugAlertController.swift
// ReactantUI
//
// Created by Tadeas Kriz on 4/25/17.
// Copyright © 2017 Brightify. All rights reserved.
//
import UIKit
class DebugAlertController: UIAlertController {
override var canBecomeFirstResponder: Bool {
return true
}
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: "d", modifierFlags: .command, action: #selector(close), discoverabilityTitle: "Close Debug Menu")
]
}
@objc
func close() {
dismiss(animated: true)
}
static func create(manager: ReactantLiveUIManager, window: UIWindow) -> DebugAlertController {
let controller = DebugAlertController(title: "Debug menu", message: "Reactant Live UI", preferredStyle: .actionSheet)
controller.popoverPresentationController?.sourceView = window
controller.popoverPresentationController?.sourceRect = window.bounds
let hasMultipleThemes = manager.workers.contains { $0.context.globalContext.applicationDescription.themes.count > 1 }
let hasMultipleWorkers = manager.workers.count > 1
if hasMultipleThemes {
let switchTheme = UIAlertAction(title: "Switch theme ..", style: .default) { [weak window] _ in
guard let controller = window?.rootViewController else { return }
if hasMultipleWorkers {
manager.presentWorkerSelection(in: controller) { selection in
guard case .worker(let worker) = selection else { return }
worker.presentThemeSelection(in: controller)
}
} else if let worker = manager.workers.first {
worker.presentThemeSelection(in: controller)
}
}
controller.addAction(switchTheme)
}
let reloadFiles = UIAlertAction(title: "Reload files\(hasMultipleWorkers ? " .." : "")", style: .default) { [weak window] _ in
guard let controller = window?.rootViewController else { return }
if hasMultipleWorkers {
manager.presentWorkerSelection(in: controller, allowAll: true) { selection in
switch selection {
case .all:
manager.reloadFiles()
case .worker(let worker):
worker.reloadFiles()
}
}
} else if let worker = manager.workers.first {
worker.reloadFiles()
}
}
controller.addAction(reloadFiles)
let preview = UIAlertAction(title: "Preview ..", style: .default) { [weak window] _ in
guard let controller = window?.rootViewController else { return }
if hasMultipleWorkers {
manager.presentWorkerSelection(in: controller) { selection in
guard case .worker(let worker) = selection else { return }
worker.presentPreview(in: controller)
}
} else if let worker = manager.workers.first {
worker.presentPreview(in: controller)
}
}
controller.addAction(preview)
controller.addAction(UIAlertAction(title: "Close menu", style: UIAlertAction.Style.cancel))
return controller
}
}
| 8d0d423be8a9a508ff0cd81250a6fa59 | 37.712644 | 134 | 0.594715 | false | false | false | false |
miraving/GPSGrabber | refs/heads/master | GPSGrabber/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// GPSGrabber
//
// Created by Vitalii Obertynskyi on 10/27/16.
// Copyright © 2016 Vitalii Obertynskyi. All rights reserved.
//
import UIKit
import GoogleMaps
import AWSCore
import AWSCognito
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var dataManager = DataManager()
var reachability: AWSKSReachability!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// google
GMSServices.provideAPIKey("AIzaSyCqdO8rNETPFysAp18baxr8EckWAYc33SA")
// amazon
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .euCentral1, identityPoolId:"eu-central-1:cea63a1d-de3f-4dca-bf03-af4c80162a3d")
let configuration = AWSServiceConfiguration(region: .euCentral1, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
reachabilitySetup()
// internal settings set
registerSettingBundle()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
dataManager.saveContext()
}
func applicationWillEnterForeground(_ application: UIApplication) {
registerSettingBundle()
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
dataManager.saveContext()
}
func registerSettingBundle() {
let pathStr = Bundle.main.bundlePath
let settingsBundlePath = pathStr.appending("/Settings.bundle")
let finalPath = settingsBundlePath.appending("/Root.plist")
let settingsDict = NSDictionary(contentsOfFile: finalPath)
let prefSpecifierArray = settingsDict?.object(forKey: "PreferenceSpecifiers") as! NSArray
var defaults:[String:AnyObject] = [:]
for item in prefSpecifierArray {
if let dict = item as? [String: AnyObject] {
if let key = dict["Key"] as! String! {
let defaultValue = dict["DefaultValue"] as? NSNumber
defaults[key] = defaultValue
}
}
}
UserDefaults.standard.register(defaults: defaults)
}
func reachabilitySetup() {
self.reachability = AWSKSReachability.toInternet()
self.reachability.onReachabilityChanged = { reachabile in
if self.reachability.reachable == true {
self.dataManager.uploadCache()
}
}
}
}
| ff6ee3f192f9d991977592639a96de0c | 31.627907 | 156 | 0.659301 | false | false | false | false |
YinSiQian/SQAutoScrollView | refs/heads/master | SQAutoScrollView/Source/SQDotView.swift | mit | 1 | //
// SQDotView.swift
// SQAutoScrollView
//
// Created by ysq on 2017/10/11.
// Copyright © 2017年 ysq. All rights reserved.
//
import UIKit
public enum SQDotState {
case normal
case selected
}
public class SQDotView: UIView {
private var normalColor: UIColor? {
willSet {
guard newValue != nil else {
return
}
backgroundColor = newValue!
}
}
private var selectedColor: UIColor? {
willSet {
guard newValue != nil else {
return
}
backgroundColor = newValue!
}
}
public var isSelected: Bool = false {
didSet {
assert(selectedColor != nil || normalColor != nil, "please set color value")
if isSelected {
backgroundColor = selectedColor!
} else {
backgroundColor = normalColor!
}
}
}
public var style: SQPageControlStyle = .round {
didSet {
switch style {
case .round:
layer.cornerRadius = bounds.size.width / 2
case .rectangle:
layer.cornerRadius = 0
}
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
}
public func set(fillColor: UIColor, state: SQDotState) {
switch state {
case .normal:
self.normalColor = fillColor
case .selected:
self.selectedColor = fillColor
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 0a9ebc234022e62a213965d56d3d7e22 | 21.363636 | 88 | 0.507549 | false | false | false | false |
material-foundation/github-comment | refs/heads/develop | Sources/GitHub/HunkCorrelation.swift | apache-2.0 | 1 | /*
Copyright 2018-present the Material Foundation authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/**
Returns a GitHub pull request comment "position" for a given hunk in a given list of hunks.
Context:
One might hope you could post comments to GitHub pull requests given a file and line range.
Alas, GitHub instead requires that you post comments to the pull request diff's hunks.
For example, if a pull request made changes to lines 20-50 on file A, and you want to post a
comment to line 25 of that file, you need to post a comment to "6" (line 20 is line "1" of the
hunk).
From the docs: https://developer.github.com/v3/pulls/comments/#create-a-comment
> The position value equals the number of lines down from the first "@@" hunk header in the
> file you want to add a comment. The line just below the "@@" line is position 1, the next
> line is position 2, and so on. The position in the diff continues to increase through lines
> of whitespace and additional hunks until the beginning of a new file.
*/
public func githubPosition(for hunk: Hunk, in hunks: [Hunk]) -> Int? {
// Our hunk ranges line up like so:
// hunks.beforeRange = original code
// hunks.afterRange = pull request changes
// hunk.beforeRange = pull request changes
// hunk.afterRange = after suggested changes
guard let index = hunks.index(where: { $0.afterRange.overlaps(hunk.beforeRange) }) else {
return nil
}
// Position is counted by number of lines in the hunk content, so we start by counting the number
// of lines in all of the preceeding hunks.
let numberOfPrecedingHunkLines = hunks[0..<index].map { $0.contents.count }.reduce(0, +)
// Each hunk's header (including the current one) has as an implicit line
let numberOfHunksHeaders = index + 1
// The position should be the last line of code we intend to change in the index'd hunk.
// First, count how many lines our hunk intends to change:
let linesChanged = hunk.contents.index(where: { !$0.starts(with: "-") }) ?? hunk.contents.count
let lastLineChanged = hunk.beforeRange.lowerBound + linesChanged
// We now know the line number. Now we need to calculate the position.
var numberOfLinesToCount = lastLineChanged - hunks[index].afterRange.lowerBound
for (hunkPosition, line) in hunks[index].contents.enumerated() {
if line.hasPrefix("-") { // Ignore removed lines
continue
}
numberOfLinesToCount = numberOfLinesToCount - 1
if numberOfLinesToCount == 0 {
return numberOfPrecedingHunkLines + numberOfHunksHeaders + hunkPosition
}
}
return nil
}
| 7e6cdbd5844639fb775c04b4480039fa | 44.882353 | 99 | 0.737821 | false | false | false | false |
jonasman/TeslaSwift | refs/heads/master | Sources/Extensions/Rx/TeslaSwift+Rx.swift | mit | 1 | //
// TeslaSwift+Combine.swift
// TeslaSwift
//
// Created by Joao Nunes on 08/07/2019.
// Copyright © 2019 Joao Nunes. All rights reserved.
//
import Foundation
import RxSwift
#if COCOAPODS
#else // SPM
import TeslaSwift
#endif
extension TeslaSwift {
public func revokeWeb() -> Single<Bool> {
let future = Single<Bool>.create { (single: @escaping (SingleEvent<Bool>) -> Void) -> Disposable in
Task {
do {
let result = try await self.revokeWeb()
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getVehicles() -> Single<[Vehicle]> {
let future = Single<[Vehicle]>.create { (single: @escaping (SingleEvent<[Vehicle]>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getVehicles()
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getVehicle(_ vehicleID: String) -> Single<Vehicle> {
let future = Single<Vehicle>.create { (single: @escaping (SingleEvent<Vehicle>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getVehicle(vehicleID)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getVehicle(_ vehicle: Vehicle) -> Single<Vehicle> {
let future = Single<Vehicle>.create { (single: @escaping (SingleEvent<Vehicle>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getVehicle(vehicle)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getAllData(_ vehicle: Vehicle) -> Single<VehicleExtended> {
let future = Single<VehicleExtended>.create { (single: @escaping (SingleEvent<VehicleExtended>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getAllData(vehicle)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getVehicleMobileAccessState(_ vehicle: Vehicle) -> Single<Bool> {
let future = Single<Bool>.create { (single: @escaping (SingleEvent<Bool>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getVehicleMobileAccessState(vehicle)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getVehicleChargeState(_ vehicle: Vehicle) -> Single<ChargeState> {
let future = Single<ChargeState>.create { (single: @escaping (SingleEvent<ChargeState>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getVehicleChargeState(vehicle)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getVehicleClimateState(_ vehicle: Vehicle) -> Single<ClimateState> {
let future = Single<ClimateState>.create { (single: @escaping (SingleEvent<ClimateState>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getVehicleClimateState(vehicle)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getVehicleDriveState(_ vehicle: Vehicle) -> Single<DriveState> {
let future = Single<DriveState>.create { (single: @escaping (SingleEvent<DriveState>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getVehicleDriveState(vehicle)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getVehicleGuiSettings(_ vehicle: Vehicle) -> Single<GuiSettings> {
let future = Single<GuiSettings>.create { (single: @escaping (SingleEvent<GuiSettings>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getVehicleGuiSettings(vehicle)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getVehicleState(_ vehicle: Vehicle) -> Single<VehicleState> {
let future = Single<VehicleState>.create { (single: @escaping (SingleEvent<VehicleState>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getVehicleState(vehicle)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getVehicleConfig(_ vehicle: Vehicle) -> Single<VehicleConfig> {
let future = Single<VehicleConfig>.create { (single: @escaping (SingleEvent<VehicleConfig>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getVehicleConfig(vehicle)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func wakeUp(_ vehicle: Vehicle) -> Single<Vehicle> {
let future = Single<Vehicle>.create { (single: @escaping (SingleEvent<Vehicle>) -> Void) -> Disposable in
Task {
do {
let result = try await self.wakeUp(vehicle)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func sendCommandToVehicle(_ vehicle: Vehicle, command: VehicleCommand) -> Single<CommandResponse> {
let future = Single<CommandResponse>.create { (single: @escaping (SingleEvent<CommandResponse>) -> Void) -> Disposable in
Task {
do {
let result = try await self.sendCommandToVehicle(vehicle, command: command)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getProducts() -> Single<[Product]> {
let future = Single<[Product]>.create { (single: @escaping (SingleEvent<[Product]>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getProducts()
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getEnergySiteStatus(siteID: String) -> Single<EnergySiteStatus> {
let future = Single<EnergySiteStatus>.create { (single: @escaping (SingleEvent<EnergySiteStatus>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getEnergySiteStatus(siteID: siteID)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getEnergySiteLiveStatus(siteID: String) -> Single<EnergySiteLiveStatus> {
let future = Single<EnergySiteLiveStatus>.create { (single: @escaping (SingleEvent<EnergySiteLiveStatus>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getEnergySiteLiveStatus(siteID: siteID)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getEnergySiteInfo(siteID: String) -> Single<EnergySiteInfo> {
let future = Single<EnergySiteInfo>.create { (single: @escaping (SingleEvent<EnergySiteInfo>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getEnergySiteInfo(siteID: siteID)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getEnergySiteHistory(siteID: String, period: EnergySiteHistory.Period) -> Single<EnergySiteHistory> {
let future = Single<EnergySiteHistory>.create { (single: @escaping (SingleEvent<EnergySiteHistory>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getEnergySiteHistory(siteID: siteID, period: period)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getBatteryStatus(batteryID: String) -> Single<BatteryStatus> {
let future = Single<BatteryStatus>.create { (single: @escaping (SingleEvent<BatteryStatus>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getBatteryStatus(batteryID: batteryID)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getBatteryData(batteryID: String) -> Single<BatteryData> {
let future = Single<BatteryData>.create { (single: @escaping (SingleEvent<BatteryData>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getBatteryData(batteryID: batteryID)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
public func getBatteryPowerHistory(batteryID: String) -> Single<BatteryPowerHistory> {
let future = Single<BatteryPowerHistory>.create { (single: @escaping (SingleEvent<BatteryPowerHistory>) -> Void) -> Disposable in
Task {
do {
let result = try await self.getBatteryPowerHistory(batteryID: batteryID)
single(.success(result))
} catch let error {
single(.failure(error))
}
}
return Disposables.create { }
}
return future
}
}
| 95951a25f0ee23a16096c9a3aef1797f | 35.407514 | 139 | 0.505517 | false | false | false | false |
davirdgs/ABC4 | refs/heads/master | MN4/Level.swift | gpl-3.0 | 1 | //
// Level.swift
// MN4
//
// Created by Pedro Rodrigues Grijó on 8/24/15.
// Copyright (c) 2015 Pedro Rodrigues Grijó. All rights reserved.
/**
* To obtain a level, call setLevel and then getLevelWords
*/
import Foundation
class Level {
fileprivate var dataBase: [Category]
fileprivate var rightCategoryId: UInt32 // Category Id of the 3 correct words
fileprivate var wrongCategoryId: UInt32 // Category Id of the incorrect word
fileprivate var wrongWord: Word // Incorrect word choice
fileprivate var levelWords: [Word] // Words of the current level
init() {
let langId = Locale.preferredLanguages[0]
//print(langId)
// Gets the dataBase
if(langId == "pt-BR" || langId == "pt-PT") {
self.dataBase = WordDataBase.getDataBase()
} else if(langId == "es-BR" || langId == "es-ES" || langId == "es-419" || langId == "es-MX") {
self.dataBase = WordDataBaseSpanish.getDataBase()
} else {
self.dataBase = WordDataBaseEnglish.getDataBase()
}
self.rightCategoryId = 0
self.wrongCategoryId = 0
self.wrongWord = Word(word: "", difficulty: "")
self.levelWords = [Word]()
}
// MARK: - Setters
// Models a level
func setLevel() {
setCategoryIds()
setLevelWords()
randomizeLevelWords()
}
fileprivate func setCategoryIds() {
// Randomly chooses the category Ids of the right and wrong words
self.rightCategoryId = arc4random_uniform(UInt32(dataBase.count))
self.wrongCategoryId = arc4random_uniform(UInt32(dataBase.count))
// Loops until an acceptable wrong category Id is generated
while wrongCategoryId == rightCategoryId {
self.wrongCategoryId = arc4random_uniform(UInt32(dataBase.count))
}
}
fileprivate func setLevelWords() {
var wrongWordIndex: Int
var rightWordIndexes: [Int] = [Int](repeating: 0, count: 3)
// Generates random indexes to get the words from the database
wrongWordIndex = Int(arc4random_uniform(UInt32(dataBase[Int(wrongCategoryId)].words.count)))
rightWordIndexes[0] = Int(arc4random_uniform(UInt32(dataBase[Int(rightCategoryId)].words.count)))
rightWordIndexes[1] = Int(arc4random_uniform(UInt32(dataBase[Int(rightCategoryId)].words.count)))
rightWordIndexes[2] = Int(arc4random_uniform(UInt32(dataBase[Int(rightCategoryId)].words.count)))
// Checks for duplicates
while rightWordIndexes[1] == rightWordIndexes[0] {
rightWordIndexes[1] = Int(arc4random_uniform(UInt32(dataBase[Int(rightCategoryId)].words.count)))
}
while rightWordIndexes[2] == rightWordIndexes[1] || rightWordIndexes[2] == rightWordIndexes[0] {
rightWordIndexes[2] = Int(arc4random_uniform(UInt32(dataBase[Int(rightCategoryId)].words.count)))
}
// Gets the words from the database and appends them into the levelWords array
self.wrongWord = dataBase[Int(wrongCategoryId)].words[wrongWordIndex]
self.levelWords.append(self.wrongWord)
self.levelWords.append(dataBase[Int(rightCategoryId)].words[rightWordIndexes[0]])
self.levelWords.append(dataBase[Int(rightCategoryId)].words[rightWordIndexes[1]])
self.levelWords.append(dataBase[Int(rightCategoryId)].words[rightWordIndexes[2]])
}
// MARK: - Getters
func getCategoryIds()->[UInt32] {
return [rightCategoryId, wrongCategoryId]
}
func getLevelWords()->[Word] {
return levelWords
}
func getWrongWord()->Word {
return wrongWord
}
// MARK: - Other Methods
// Fisher-Yates/Knuth Shuffle
fileprivate func randomizeLevelWords() {
let size: Int = self.levelWords.count
for i in 0...(size - 1) {//(var i=0; i<size; i += 1) {
let j = i + Int(arc4random_uniform(UInt32(size-i)))
if(j<size && !(j==i)) {
swap(&levelWords[i], &levelWords[j])
}
}
}
// func printLevelWords() {
// println(self.levelWords)
// }
}
| bdae3e6fe416d82d4b648caf9e5f3574 | 31.338346 | 109 | 0.617531 | false | false | false | false |
IngmarStein/swift | refs/heads/master | benchmark/single-source/SevenBoom.swift | apache-2.0 | 10 | //===--- SevenBoom.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
@inline(never)
func filter_seven(_ input : Int) throws {
guard case 7 = input else {
throw NSError(domain: "AnDomain", code: 42, userInfo: nil)
}
}
@inline(never)
public func run_SevenBoom(_ N: Int) {
var c = 0
for i in 1...N*5000 {
do {
try filter_seven(i)
c += 1
}
catch _ {
}
}
CheckResults(c == 1, "IncorrectResults in SevenBoom")
}
| 44a3f91621c474d5a393df5499d88ce2 | 25.055556 | 80 | 0.566098 | false | false | false | false |
OSzhou/MyTestDemo | refs/heads/master | 17_SwiftTestCode/TestCode/CustomAlbum/Source/Scene/Picker/HEPhotoPickerViewController.swift | apache-2.0 | 1 | //
// HEPhotoPickerViewController.swift
// SwiftPhotoSelector
//
// Created by heyode on 2018/9/19.
// Copyright (c) 2018 heyode <[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
import Photos
//屏宽
let kScreenWidth = UIScreen.main.bounds.size.width
//屏高
let kScreenHeight = UIScreen.main.bounds.size.height
@objc public protocol HEPhotoPickerViewControllerDelegate
{
/// 选择照片完成后调用的代理
///
/// - Parameters:
/// - picker: 选择图片的控制器
/// - selectedImages: 选择的图片数组(如果是视频,就取视频第一帧作为图片保存)
/// - selectedModel: 选择的数据模型
func pickerController(_ picker:UIViewController, didFinishPicking selectedImages:[UIImage],selectedModel:[HEPhotoAsset])
/// 选择照片取消后调用的方法
///
/// - Parameter picker: 选择图片的控制器
@objc optional func pickerControllerDidCancel(_ picker:UIViewController)
}
public class HEPhotoPickerViewController: HEBaseViewController {
// MARK : - Public
/// 选择器配置
public var pickerOptions : HEPickerOptions!
/// 选择完成后的相关代理
public var delegate : HEPhotoPickerViewControllerDelegate?
// MARK : - Private
/// 图片列表的数据模型
private var models : [HEPhotoAsset]!
/// 选中的数据模型
private var selectedModels = [HEPhotoAsset](){
didSet{
if let first = selectedModels.first{
// 记录上一次选中模型集合中的数据类型
preSelecetdType = first.asset.mediaType
}
}
}
/// 选中的图片模型(若有视频,则取它第一帧作为图片保存)
private lazy var selectedImages = [UIImage]()
/// 用于处理选中的数组
private lazy var todoArray = [HEPhotoAsset]()
/// 相册请求项
private let photosOptions = PHFetchOptions()
/// 过场动画
private var animator = HEPhotoBrowserAnimator()
/// 相册原有数据
private var smartAlbums :PHFetchResult<PHAssetCollection>!
/// 整理过后的相册
private var albumModels : [HEAlbum]!
/// 所有展示的多媒体数据集合
private var phAssets : PHFetchResult<PHAsset>!
/// 相册按钮
private var titleBtn : UIButton!
/// titleBtn展开的tableView的上一个选中的IndexPath
private var preSelectedTableViewIndex = IndexPath.init(row: 0, section: 0 )
/// titleBtn展开的tableView的上一个选中的con
private var preSelectedTableViewContentOffset = CGPoint.zero
/// 待刷新的IndexPath(imageOrVideo模式下更新cell可用状态专用)
private var willUpadateIndex = Set<IndexPath>()
/// 当选中数组为空时,记录上一次选中模型集合中的数据类型(imageOrVideo模式下更新cell可用状态专用)
private var preSelecetdType : PHAssetMediaType!
/// 图片视图
private lazy var collectionView : UICollectionView = {
let cellW = (self.view.frame.width - 3) / 4.0
let layout = UICollectionViewFlowLayout.init()
layout.itemSize = CGSize.init(width: cellW, height: cellW)
layout.minimumLineSpacing = 1
layout.minimumInteritemSpacing = 1
var height = CGFloat(0)
if UIDevice.isContansiPhoneX(){
height = kScreenHeight - 88
}else{
height = kScreenHeight - 64
}
let collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.width, height:height), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 34, right: 0)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(HEPhotoPickerCell.classForCoder(), forCellWithReuseIdentifier: HEPhotoPickerCell.className)
return collectionView
}()
// MARK:- 初始化
/// 初始化方法
///
/// - Parameters:
/// - delegate: 控制器的代理
/// - options: 配置项
public init(delegate: HEPhotoPickerViewControllerDelegate,options:HEPickerOptions = HEPickerOptions() ) {
super.init(nibName: nil, bundle: nil)
self.delegate = delegate
self.pickerOptions = options
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- 控制器生命周期和设置UI
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
edgesForExtendedLayout = []
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
public override func viewDidLoad() {
super.viewDidLoad()
animator.pushDelegate = self
navigationController?.delegate = self
configPickerOption()
requestAndFetchAssets()
}
private func requestAndFetchAssets() {
if HETool.canAccessPhotoLib() {
self.getAllPhotos()
} else {
HETool.requestAuthorizationForPhotoAccess(authorized:self.getAllPhotos, rejected: HETool.openIphoneSetting)
}
}
deinit {
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
func configUI() {
view.addSubview(collectionView)
let btn = HEAlbumTitleView.init(type: .custom)
titleBtn = btn
if let title = albumModels.first?.title{
btn.setTitle(title, for: .normal)
}
btn.addTarget(self, action: #selector(HEPhotoPickerViewController.titleViewClick(_:)), for: .touchUpInside)
navigationItem.titleView = btn
let rightBtn = HESeletecedButton.init(type: .custom)
rightBtn.setTitle(pickerOptions.selectDoneButtonTitle)
rightBtn.addTarget(self, action: #selector(nextBtnClick), for: .touchUpInside)
let right = UIBarButtonItem.init(customView: rightBtn)
navigationItem.rightBarButtonItem = right
rightBtn.isEnabled = false
}
override public func configNavigationBar() {
super.configNavigationBar()
navigationItem.leftBarButtonItem = setLeftBtn()
}
func setLeftBtn() -> UIBarButtonItem{
let leftBtn = UIButton.init(type: .custom)
leftBtn.setTitle(pickerOptions.cancelButtonTitle, for: .normal)
leftBtn.addTarget(self, action: #selector(goBack), for: .touchUpInside)
leftBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
leftBtn.setTitleColor(UIColor.gray, for: .normal)
let left = UIBarButtonItem.init(customView: leftBtn)
return left
}
/// 将给定类型模型设为不可点击状态
///
/// - Parameter type: 给定媒体数据类型
func setCellDisableEnable(with type:PHAssetMediaType){
for item in models{
if item.asset.mediaType == type{
item.isEnable = false
}
}
collectionView.reloadData()
}
func updateNextBtnTitle() {
let rightBtn = navigationItem.rightBarButtonItem?.customView as! HESeletecedButton
rightBtn.isEnabled = selectedModels.count > 0
if selectedModels.count > 0 {
rightBtn.setTitle(String.init(format: "%@(%d)",pickerOptions.selectDoneButtonTitle, selectedModels.count))
}else{
rightBtn.setTitle(pickerOptions.selectDoneButtonTitle)
}
}
/// 数据源重置后更新UI
func updateUI(){
updateNextBtnTitle()
setCellState(selectedIndex: nil, isUpdateSelecetd: true)
}
// MARK: - 更新cell
/// 更新cell的选中状态
///
/// - Parameters:
/// - selectedIndex: 选中的索引
/// - selectedBtn: 选择按钮
func updateSelectedCell(selectedIndex:Int,selectedBtn:UIButton) {
let model = self.models[selectedIndex]
if selectedBtn.isSelected {
switch model.asset.mediaType {
case .image:
let selectedImageCount = self.selectedModels.count{$0.asset.mediaType == .image}
guard selectedImageCount < self.pickerOptions.maxCountOfImage else{
let title = String.init(format: pickerOptions.maxPhotoWaringTips, self.pickerOptions.maxCountOfImage)
presentAlert(title: title)
selectedBtn.isSelected = false
return
}
case .video:
let selectedVideoCount = self.selectedModels.count{$0.asset.mediaType == .video}
guard selectedVideoCount < self.pickerOptions.maxCountOfVideo else{
let title = String.init(format: pickerOptions.maxVideoWaringTips, self.pickerOptions.maxCountOfVideo)
presentAlert(title: title)
selectedBtn.isSelected = false
return
}
default:
break
}
selectedBtn.isSelected = true
self.selectedModels.append(model)
}else{// 切勿使用index去匹配
self.selectedModels.removeAll(where: {$0.asset.localIdentifier == model.asset.localIdentifier})
selectedBtn.isSelected = false
}
models[selectedIndex].isSelected = selectedBtn.isSelected
updateNextBtnTitle()
// 根据当前用户选中的个数,将所有未选中的cell重置给定可用状态
setCellState(selectedIndex: selectedIndex)
}
/// 设置cell的可用和选中状态
///
/// - Parameters:
/// - selectedIndex:当前选中的cell索引
/// - isUpdateSelecetd: 是否更新选中状态
func setCellState(selectedIndex:Int?,isUpdateSelecetd:Bool = false){
// 初始化将要刷新的索引集合
willUpadateIndex = Set<IndexPath>()
let selectedCount = selectedModels.count
let optionMaxCount = pickerOptions.maxCountOfImage + pickerOptions.maxCountOfVideo
// 尽量将所有需要更新状态的操作都放在这个循环里面,节约开销
for item in models{
if isUpdateSelecetd == true{// 整个数据源重置,要重设选中状态
// item.isSelected = selectedModels.contains(where: {$0.asset.localIdentifier == item.asset.localIdentifier})
if let selectItem = selectedModels.first(where: {$0.asset.localIdentifier == item.asset.localIdentifier}) {
item.isSelected = true
item.selecteIndex = selectItem.selecteIndex
if let selIndex = selectedModels.firstIndex(of: selectItem) {
selectedModels.remove(at: selIndex)
selectedModels.insert(item, at: selIndex)
}
}
}
// 如果未选中的话,并且是imageOrVideo,就需要更新cell的可用状态
// 根据当前用户选中的个数,将所有未选中的cell重置给定可用状态
if item.isSelected == false && pickerOptions.mediaType == .imageOrVideo{
// 选中的数量小于允许选中的最大数,就可用
if selectedCount < optionMaxCount && item.isEnable == false{
// 选中的数量小于允许选中的最大数,就可用
item.isEnable = true
// 将待刷新的索引加入到数组
willUpadateIndex.insert(IndexPath.init(row: item.index, section: 0))
}else if selectedCount >= optionMaxCount && item.isEnable == true{//选中的数量大于或等于最大数,就不可用
item.isEnable = false
// 将待刷新的索引加入到数组
willUpadateIndex.insert(IndexPath.init(row: item.index, section: 0))
}
if selectedModels.count > 0{
if selectedModels.first?.asset.mediaType == .image{ // 用户选中的是图片的话,就把视频类型的cell都设置为不可选中
if item.asset.mediaType == .video{
item.isEnable = false
if let i = selectedIndex,item.index != i{// 点击是自动刷新,所以要排除
// 将待刷新的索引加入到数组
willUpadateIndex.insert(IndexPath.init(row: item.index, section: 0))
}
}
}else if selectedModels.first?.asset.mediaType == .video{
if item.asset.mediaType == .image{
item.isEnable = false
if let i = selectedIndex,item.index != i{// 点击是自动刷新,所以要排除
willUpadateIndex.insert(IndexPath.init(row: item.index, section: 0))
}
}
}
}
}
if selectedModels.count <= 0 && pickerOptions.mediaType == .imageOrVideo{//是imageOrVideo状态下,取消所有选择,要找出哪些cell需要刷新可用状态
item.isEnable = true
// 将待刷新的索引加入到数组
willUpadateIndex.insert(IndexPath.init(row: item.index, section: 0))
}
}
for (i, item) in selectedModels.enumerated() {
item.selecteIndex = i + 1
}
// if isUpdateSelecetd {// 整个数据源重置,必须刷新所有cell
collectionView.reloadData()
// }else{
//
// collectionView.reloadItems(at: Array.init(willUpadateIndex) )
// }
}
// MARK:- 初始化配置项
func configPickerOption() {
switch pickerOptions.mediaType {
case .imageAndVideo:
pickerOptions.singlePicture = false
pickerOptions.singleVideo = false
case .imageOrVideo:
pickerOptions.singlePicture = false
case .image:
pickerOptions.maxCountOfVideo = 0
case .video:
pickerOptions.maxCountOfImage = 0
}
if pickerOptions.singleVideo {
pickerOptions.maxCountOfVideo = 0
}
if pickerOptions.singlePicture{
pickerOptions.maxCountOfImage = 0
}
if let models = pickerOptions.defaultSelections{
selectedModels = models
}
}
func isSinglePicture(model:HEPhotoAsset) ->Bool{
return model.asset.mediaType == .image && pickerOptions.singlePicture == true
}
func isSingleVideo(model:HEPhotoAsset) ->Bool{
return model.asset.mediaType == .video && pickerOptions.singleVideo == true
}
/// 如果当前模型是单选模式隐藏多选按钮
///
/// - Parameter model: 当前模型
func checkIsSingle(model:HEPhotoAsset){
if isSinglePicture(model: model) || isSingleVideo(model: model) {
model.isEnableSelected = false
}
}
// MARK:- UI Actions
@objc func titleViewClick(_ sender:UIButton){
sender.isSelected = true
let popViewFrame : CGRect!
popViewFrame = CGRect.init(x: 0, y: (navigationController?.navigationBar.frame.maxY)!, width: kScreenWidth, height: kScreenHeight/2)
let listView = HEAlbumListView.showOnKeyWidows(rect: popViewFrame, assetCollections: albumModels, cellClick: { [weak self](list,ablum,selecedIndex) in
self?.preSelectedTableViewIndex = selecedIndex
// self?.preSelectedTableViewContentOffset = list.tableView.contentOffset
self?.titleBtn.setTitle(ablum.title, for: .normal)
self?.titleBtn.sizeToFit()
self?.fetchPhotoModels(photos: ablum.fetchResult)
self?.updateUI()
},dismiss:{
sender.isSelected = false
})
listView.tableView.selectRow(at: preSelectedTableViewIndex, animated: false, scrollPosition:.middle)
}
@objc func nextBtnClick(){
todoArray = selectedModels
getImages()
}
@objc func goBack(){
navigationController?.dismiss(animated: true, completion: nil)
delegate?.pickerControllerDidCancel?(self)
}
// MARK:- 获取全部图片
private func getAllPhotos() {
switch pickerOptions.mediaType{
case .image:
photosOptions.predicate = NSPredicate.init(format: "mediaType == %ld", PHAssetMediaType.image.rawValue)
case .video:
photosOptions.predicate = NSPredicate.init(format: "mediaType == %ld", PHAssetMediaType.video.rawValue)
default:
break
}
photosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: pickerOptions.ascendingOfCreationDateSort)]
phAssets = PHAsset.fetchAssets(with: photosOptions)
fetchPhotoModels(photos: phAssets)
getAllAlbums()
// 注册相册库的通知(要写在getAllPhoto后面)
PHPhotoLibrary.shared().register(self)
configUI()
if selectedModels.count > 0{
updateUI()
}
}
func getAllAlbums(){
smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil)
fetchAlbumsListModels(albums: smartAlbums)
}
private func fetchPhotoModels(photos:PHFetchResult<PHAsset>){
var models = [HEPhotoAsset]()
photos.enumerateObjects {[weak self] (asset, index, ff) in
let model = HEPhotoAsset.init(asset: asset)
self?.checkIsSingle(model: model)
model.index = index
models.append(model)
}
self.models = models
self.collectionView.reloadData()
/*models = [HEPhotoAsset]()
let queue = DispatchQueue.global()
let group = DispatchGroup()
photos.enumerateObjects { [weak self] (asset, index, ff) in
group.enter()
let item = DispatchWorkItem {
HETool.wb_RequestImageData(asset, options: nil) { (imageData, flag) in
if !flag {
let model = HEPhotoAsset.init(asset: asset)
self?.checkIsSingle(model: model)
model.index = index
models.append(model)
}
group.leave()
}
}
queue.async(group: group, execute: item)
}
group.notify(queue: DispatchQueue.main) {
self.collectionView.reloadData()
}*/
}
private func fetchAlbumsListModels(albums:PHFetchResult<PHAssetCollection>){
albumModels = [HEAlbum]()
albums.enumerateObjects { [weak self] (collection, index, stop) in
let asset = PHAsset.fetchAssets(in: collection, options: self!.photosOptions)
let album = HEAlbum.init(result: asset, title: collection.localizedTitle)
if asset.count > 0 && collection.localizedTitle != "最近删除" && collection.localizedTitle != "Recently Deleted"{
self?.albumModels.append(album)
}
}
}
func getImages(){
let option = PHImageRequestOptions()
option.deliveryMode = .highQualityFormat
if todoArray.count == 0 {
delegate?.pickerController(self, didFinishPicking: selectedImages,selectedModel: selectedModels)
dismiss(animated: true, completion: nil)
}
if todoArray.count > 0 {
HETool.heRequestImage(for: (todoArray.first?.asset)!, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill) {[weak self] (image, _) in
DispatchQueue.main.async {
self?.todoArray.removeFirst()
self?.selectedImages.append(image ?? UIImage())
self?.getImages()
}
}
}
}
}
extension HEPhotoPickerViewController: PHPhotoLibraryChangeObserver{
open func photoLibraryDidChange(_ changeInstance: PHChange) {
DispatchQueue.main.sync {
if let changeDetails = changeInstance.changeDetails(for: phAssets){
phAssets = changeDetails.fetchResultAfterChanges
fetchPhotoModels(photos: phAssets)
}
// Update the cached fetch results, and reload the table sections to match.
if let changeDetails = changeInstance.changeDetails(for: smartAlbums) {
smartAlbums = changeDetails.fetchResultAfterChanges
fetchAlbumsListModels(albums: smartAlbums)
if let title = albumModels.first?.title{
titleBtn.setTitle(title, for: .normal)
titleBtn.sizeToFit()
}
}
}
}
}
extension HEPhotoPickerViewController : UICollectionViewDelegate,UICollectionViewDataSource{
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return models.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:HEPhotoPickerCell.className , for: indexPath) as! HEPhotoPickerCell
let model = models[indexPath.row]
cell.model = model
cell.pickerOptions = self.pickerOptions
cell.checkBtnnClickClosure = {[unowned self] (selectedBtn) in
self.updateSelectedCell(selectedIndex: indexPath.row, selectedBtn: selectedBtn)
}
return cell
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
animator.selIndex = indexPath
let size = CGSize.init(width: kScreenWidth, height: kScreenWidth)
HETool.heRequestImage(for: phAssets[indexPath.row] ,
targetSize: size,
contentMode: .aspectFill)
{ (image, nil) in
let photoDetail = HEPhotoBrowserViewController()
photoDetail.delegate = self.delegate
photoDetail.pickerOptions = self.pickerOptions
photoDetail.imageIndex = indexPath
photoDetail.models = self.models
photoDetail.selectedModels = self.selectedModels
photoDetail.canScroll = !self.pickerOptions.singlePicture
photoDetail.selectedCloser = { selectedIndex in
self.models[selectedIndex].isSelected = true
self.selectedModels.append(self.models[selectedIndex])
self.updateUI()
}
photoDetail.unSelectedCloser = { selectedIndex in
self.models[selectedIndex].isSelected = false
self.selectedModels.removeAll{$0 == self.models[selectedIndex]}
self.updateUI()
}
photoDetail.clickBottomCellCloser = { selectedIndex in
collectionView.scrollToItem(at: IndexPath.init(item: selectedIndex, section: 0), at: .centeredVertically, animated: false)
}
self.animator.popDelegate = photoDetail
self.navigationController?.pushViewController(photoDetail, animated: true)
}
}
}
extension HEPhotoPickerViewController : UINavigationControllerDelegate{
public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
animator.operation = operation
return animator
}
}
extension HEPhotoPickerViewController: HEPhotoBrowserAnimatorPushDelegate{
public func imageViewRectOfAnimatorStart(at indexPath: IndexPath) -> CGRect {
// 获取指定cell的laout
let cellLayout = collectionView.layoutAttributesForItem(at: indexPath)
let homeFrame = UIApplication.shared.keyWindow?.convert(cellLayout?.frame ?? CGRect.zero, from: collectionView) ?? CGRect.zero
//返回具体的尺寸
return homeFrame
}
public func imageViewRectOfAnimatorEnd(at indexPath: IndexPath) -> CGRect {
//取出cell
let cell = (collectionView.cellForItem(at: indexPath))! as! HEPhotoPickerCell
//取出cell中显示的图片
let image = cell.imageView.image
let x: CGFloat = 0
let width: CGFloat = kScreenWidth
let height: CGFloat = width / (image!.size.width) * (image!.size.height)
var y: CGFloat = 0
if height < kScreenHeight {
y = (kScreenHeight - height) * 0.5
}
//计算方法后的图片的frame
return CGRect(x: x, y: y, width: width, height: height)
}
}
| 354df3add572269bf32b572c811e7268 | 38.578864 | 254 | 0.61284 | false | false | false | false |
xeo-it/poggy | refs/heads/master | Pods/Eureka/Source/Rows/SliderRow.swift | apache-2.0 | 1 | // SliderRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// The cell of the SliderRow
public class SliderCell: Cell<Float>, CellType {
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .Value1, reuseIdentifier: reuseIdentifier)
}
public var titleLabel: UILabel! {
textLabel?.translatesAutoresizingMaskIntoConstraints = false
textLabel?.setContentHuggingPriority(500, forAxis: .Horizontal)
return textLabel
}
public var valueLabel: UILabel! {
detailTextLabel?.translatesAutoresizingMaskIntoConstraints = false
detailTextLabel?.setContentHuggingPriority(500, forAxis: .Horizontal)
return detailTextLabel
}
lazy public var slider: UISlider = {
let result = UISlider()
result.translatesAutoresizingMaskIntoConstraints = false
result.setContentHuggingPriority(500, forAxis: .Horizontal)
return result
}()
public var formatter: NSNumberFormatter?
public override func setup() {
super.setup()
selectionStyle = .None
slider.minimumValue = sliderRow.minimumValue
slider.maximumValue = sliderRow.maximumValue
slider.addTarget(self, action: #selector(SliderCell.valueChanged), forControlEvents: .ValueChanged)
if shouldShowTitle() {
contentView.addSubview(titleLabel)
contentView.addSubview(valueLabel!)
}
contentView.addSubview(slider)
let views = ["titleLabel" : titleLabel, "valueLabel" : valueLabel, "slider" : slider]
let metrics = ["hPadding" : 16.0, "vPadding" : 12.0, "spacing" : 12.0]
if shouldShowTitle() {
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-hPadding-[titleLabel]-[valueLabel]-hPadding-|", options: NSLayoutFormatOptions.AlignAllLastBaseline, metrics: metrics, views: views))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-vPadding-[titleLabel]-spacing-[slider]-vPadding-|", options: NSLayoutFormatOptions.AlignAllLeft, metrics: metrics, views: views))
} else {
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-vPadding-[slider]-vPadding-|", options: NSLayoutFormatOptions.AlignAllLeft, metrics: metrics, views: views))
}
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-hPadding-[slider]-hPadding-|", options: NSLayoutFormatOptions.AlignAllLastBaseline, metrics: metrics, views: views))
}
public override func update() {
super.update()
if !shouldShowTitle() {
textLabel?.text = nil
detailTextLabel?.text = nil
}
slider.value = row.value ?? 0.0
}
func valueChanged() {
let roundedValue: Float
let steps = Float(sliderRow.steps)
if steps > 0 {
let stepValue = round((slider.value - slider.minimumValue) / (slider.maximumValue - slider.minimumValue) * steps)
let stepAmount = (slider.maximumValue - slider.minimumValue) / steps
roundedValue = stepValue * stepAmount + self.slider.minimumValue
}
else {
roundedValue = slider.value
}
row.value = roundedValue
if shouldShowTitle() {
valueLabel.text = "\(row.value!)"
}
}
private func shouldShowTitle() -> Bool {
return row.title?.isEmpty == false
}
private var sliderRow: SliderRow {
return row as! SliderRow
}
}
/// A row that displays a UISlider. If there is a title set then the title and value will appear above the UISlider.
public final class SliderRow: Row<Float, SliderCell>, RowType {
public var minimumValue: Float = 0.0
public var maximumValue: Float = 10.0
public var steps: UInt = 20
required public init(tag: String?) {
super.init(tag: tag)
}
}
| 04dbc162874c36b580eb96fee057a316 | 41.008065 | 224 | 0.681513 | false | false | false | false |
blomma/stray | refs/heads/master | stray/Event+CloudKitStack.swift | gpl-3.0 | 1 | import Foundation
import CloudKit
extension Event: CloudKitStackEntity {
var recordType: String { return Event.entityName }
var recordName: String { return "\(recordType).\(id)" }
var recordZoneName: String { return Event.entityName }
func record() -> CKRecord {
let id = recordID()
let record = CKRecord(recordType: recordType, recordID: id)
record["startDate"] = startDate as CKRecordValue
if let stopDate = stopDate { record["stopDate"] = stopDate as CKRecordValue }
if let tag = tag { record["tag"] = tag as CKRecordValue }
return record
}
}
| 2a23e4677f1e494093f2b35db48f79db | 29.105263 | 79 | 0.715035 | false | false | false | false |
leizh007/HiPDA | refs/heads/master | HiPDA/HiPDA/Sections/Message/UnReadMessagesCountManager.swift | mit | 1 | //
// MessageManager.swift
// HiPDA
//
// Created by leizh007 on 2017/6/27.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
import RxSwift
class UnReadMessagesCountManager {
private let disposeBag = DisposeBag()
static let shared = UnReadMessagesCountManager()
private init() {
observeEventBus()
}
fileprivate func observeEventBus() {
EventBus.shared.activeAccount.asObservable()
.subscribe(onNext: { loginResult in
guard let loginResult = loginResult, case .success(_) = loginResult else {
return
}
// 去请求一下首页,获取一下未读消息的数量
NetworkUtilities.html(from: "/forum/index.php")
})
.disposed(by: disposeBag)
}
static func handleUnReadMessagesCount(from html: String) {
guard let threadMessagesCount = try? HtmlParser.messageCount(of: "帖子消息", from: html),
let pmMessagesCount = try? HtmlParser.messageCount(of: "私人消息", from: html),
let friendMessagesCount = try? HtmlParser.messageCount(of: "好友消息", from: html) else { return }
let model = UnReadMessagesCountModel(threadMessagesCount: threadMessagesCount,
privateMessagesCount: pmMessagesCount,
friendMessagesCount: friendMessagesCount)
EventBus.shared.dispatch(UnReadMessagesCountAction(model: model))
}
}
| 31e1e314382b2604b58126eb8a670bc4 | 36.3 | 106 | 0.616622 | false | false | false | false |
liufengting/FTChatMessageDemoProject | refs/heads/master | FTChatMessage/FTChatMessageModel.swift | mit | 1 | //
// FTChatMessageModel.swift
// FTChatMessage
//
// Created by liufengting on 16/2/28.
// Copyright © 2016年 liufengting <https://github.com/liufengting>. All rights reserved.
//
import UIKit
// MARK: - FTChatMessageDeliverStatus
enum FTChatMessageDeliverStatus {
case sending
case succeeded
case failed
}
// MARK: - FTChatMessageModel
class FTChatMessageModel: NSObject {
var targetId : String!
var isUserSelf : Bool = false;
var messageText : String!
var messageTimeStamp : String!
var messageType : FTChatMessageType = .text
var messageSender : FTChatMessageUserModel!
var messageExtraData : NSDictionary?
var messageDeliverStatus : FTChatMessageDeliverStatus = FTChatMessageDeliverStatus.succeeded
// MARK: - convenience init
convenience init(data : String? ,time : String?, from : FTChatMessageUserModel, type : FTChatMessageType){
self.init()
self.transformMessage(data,time : time,extraDic: nil,from: from,type: type)
}
convenience init(data : String?,time : String?, extraDic : NSDictionary?, from : FTChatMessageUserModel, type : FTChatMessageType){
self.init()
self.transformMessage(data,time : time,extraDic: extraDic,from: from,type: type)
}
// MARK: - transformMessage
fileprivate func transformMessage(_ data : String? ,time : String?, extraDic : NSDictionary?, from : FTChatMessageUserModel, type : FTChatMessageType){
messageType = type
messageText = data
messageTimeStamp = time
messageSender = from
isUserSelf = from.isUserSelf
if (extraDic != nil) {
messageExtraData = extraDic;
}
}
}
class FTChatMessageImageModel: FTChatMessageModel {
var image : UIImage!
var imageUrl : String!
}
| 29bfd67bf3f6faf241d43276cc87c5db | 27.59375 | 155 | 0.680874 | false | false | false | false |
inket/stts | refs/heads/master | stts/EditorTableView/EditorTableViewController.swift | mit | 1 | //
// EditorTableViewController.swift
// stts
//
import Cocoa
class EditorTableViewController: NSObject, SwitchableTableViewController {
let contentView: NSStackView
let scrollView: CustomScrollView
let bottomBar: BottomBar
let tableView = NSTableView()
let allServices: [BaseService] = BaseService.all().sorted()
let allServicesWithoutSubServices: [BaseService] = BaseService.allWithoutSubServices().sorted()
var filteredServices: [BaseService]
var selectedServices: [BaseService] = Preferences.shared.selectedServices
var selectionChanged = false
let settingsView = SettingsView()
var hidden: Bool = true
var savedScrollPosition: CGPoint = .zero
var selectedCategory: ServiceCategory? {
didSet {
// Save the scroll position between screens
let scrollToPosition: CGPoint?
if selectedCategory != nil && oldValue == nil {
savedScrollPosition = CGPoint(x: 0, y: tableView.visibleRect.minY)
scrollToPosition = .zero
} else if selectedCategory == nil && oldValue != nil {
scrollToPosition = savedScrollPosition
} else {
scrollToPosition = nil
}
// Adjust UI
bottomBar.openedCategory(selectedCategory, backCallback: { [weak self] in
self?.selectedCategory = nil
})
guard let category = selectedCategory else {
// Show the unfiltered services
filteredServices = allServicesWithoutSubServices
tableView.reloadData()
if let scrollPosition = scrollToPosition {
tableView.scroll(scrollPosition)
}
return
}
// Find the sub services
var subServices = allServices.filter {
// Can't check superclass matches without mirror
Mirror(reflecting: $0).superclassMirror?.subjectType == category.subServiceSuperclass
// Exclude the category so that we can add it at the top
&& $0 != category as? BaseService
}.sorted()
// Add the category as the top item
(category as? BaseService).flatMap { subServices.insert($0, at: 0) }
filteredServices = subServices
tableView.reloadData()
if let scrollPosition = scrollToPosition {
tableView.scroll(scrollPosition)
}
}
}
var isSearching: Bool {
settingsView.searchField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) != ""
}
private var cachedTableViewWidth: CGFloat = 0
private var cachedMaxNameWidth: CGFloat?
private var maxNameWidth: CGFloat? {
if cachedTableViewWidth != tableView.frame.width || cachedMaxNameWidth == nil {
cachedTableViewWidth = tableView.frame.width
cachedMaxNameWidth = EditorTableCell.maxNameWidth(for: tableView)
return cachedMaxNameWidth!
}
return cachedMaxNameWidth
}
init(contentView: NSStackView, scrollView: CustomScrollView, bottomBar: BottomBar) {
self.contentView = contentView
self.scrollView = scrollView
self.filteredServices = allServicesWithoutSubServices
self.bottomBar = bottomBar
super.init()
setup()
}
func setup() {
tableView.frame = scrollView.bounds
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "editorColumnIdentifier"))
column.width = 200
tableView.addTableColumn(column)
tableView.autoresizesSubviews = true
tableView.wantsLayer = true
tableView.layer?.cornerRadius = 6
tableView.headerView = nil
tableView.gridStyleMask = NSTableView.GridLineStyle.init(rawValue: 0)
tableView.dataSource = self
tableView.delegate = self
tableView.selectionHighlightStyle = .none
tableView.backgroundColor = NSColor.clear
if #available(OSX 11.0, *) {
tableView.style = .fullWidth
}
settingsView.isHidden = true
settingsView.searchCallback = { [weak self] searchString in
guard
let strongSelf = self,
let allServices = strongSelf.allServices as? [Service],
let allServicesWithoutSubServices = strongSelf.allServicesWithoutSubServices as? [Service]
else { return }
if searchString.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
strongSelf.filteredServices = allServicesWithoutSubServices
} else {
// Can't filter array with NSPredicate without making Service inherit KVO from NSObject, therefore
// we create an array of service names that we can run the predicate on
let allServiceNames = allServices.compactMap { $0.name } as NSArray
let predicate = NSPredicate(format: "SELF LIKE[cd] %@", argumentArray: ["*\(searchString)*"])
guard let filteredServiceNames = allServiceNames.filtered(using: predicate) as? [String] else { return }
strongSelf.filteredServices = allServices.filter { filteredServiceNames.contains($0.name) }
}
if strongSelf.selectedCategory != nil {
strongSelf.selectedCategory = nil
}
strongSelf.tableView.reloadData()
}
settingsView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(settingsView)
NSLayoutConstraint.activate([
settingsView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
settingsView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
settingsView.topAnchor.constraint(equalTo: contentView.topAnchor),
settingsView.heightAnchor.constraint(equalToConstant: 170)
])
}
func willShow() {
self.selectionChanged = false
scrollView.topConstraint?.constant = settingsView.frame.size.height
scrollView.documentView = tableView
settingsView.isHidden = false
// We should be using NSWindow's makeFirstResponder: instead of the search field's selectText:,
// but in this case, makeFirstResponder is causing a bug where the search field "gets focused" twice
// (focus ring animation) the first time it's drawn.
settingsView.searchField.selectText(nil)
resizeViews()
}
func resizeViews() {
tableView.frame = scrollView.bounds
tableView.tableColumns.first?.width = tableView.frame.size.width
scrollView.frame.size.height = 400
(NSApp.delegate as? AppDelegate)?.popupController.resizePopup(
height: scrollView.frame.size.height + 30 // bottomBar.frame.size.height
)
}
func willOpenPopup() {
resizeViews()
}
func didOpenPopup() {
settingsView.searchField.window?.makeFirstResponder(settingsView.searchField)
}
func willHide() {
settingsView.isHidden = true
}
@objc func deselectCategory() {
selectedCategory = nil
}
}
extension EditorTableViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return filteredServices.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
return nil
}
func tableViewSelectionDidChange(_ notification: Notification) {
guard tableView.selectedRow != -1 else { return }
// We're only interested in selections of categories
guard
selectedCategory == nil,
let category = filteredServices[tableView.selectedRow] as? ServiceCategory
else { return }
// Change the selected category
selectedCategory = category
}
}
extension EditorTableViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
guard
let maxNameWidth = maxNameWidth,
let service = filteredServices[row] as? Service
else { return EditorTableCell.defaultHeight }
return EditorTableCell.estimatedHeight(for: service, maxWidth: maxNameWidth)
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let identifier = tableColumn?.identifier ?? NSUserInterfaceItemIdentifier(rawValue: "identifier")
let cell = tableView.makeView(withIdentifier: identifier, owner: self) ?? EditorTableCell()
guard let view = cell as? EditorTableCell else { return nil }
guard let service = filteredServices[row] as? Service else { return nil }
if isSearching || selectedCategory != nil {
view.type = .service
} else {
view.type = (service is ServiceCategory) ? .category : .service
}
switch view.type {
case .service:
view.textField?.stringValue = service.name
view.selected = selectedServices.contains(service)
view.toggleCallback = { [weak self] in
guard let strongSelf = self else { return }
strongSelf.selectionChanged = true
if view.selected {
self?.selectedServices.append(service)
} else {
if let index = self?.selectedServices.firstIndex(of: service) {
self?.selectedServices.remove(at: index)
}
}
Preferences.shared.selectedServices = strongSelf.selectedServices
}
case .category:
view.textField?.stringValue = (service as? ServiceCategory)?.categoryName ?? service.name
view.selected = false
view.toggleCallback = {}
}
return view
}
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
let cellIdentifier = NSUserInterfaceItemIdentifier(rawValue: "rowView")
let cell = tableView.makeView(withIdentifier: cellIdentifier, owner: self) ?? ServiceTableRowView()
guard let view = cell as? ServiceTableRowView else { return nil }
view.showSeparator = row + 1 < filteredServices.count
return view
}
}
| 6e9f027b87b24955e56f4264500d43dd | 35.356401 | 120 | 0.636052 | false | false | false | false |
Ivacker/swift | refs/heads/master | test/IRGen/generic_casts.swift | apache-2.0 | 12 | // RUN: rm -rf %t && mkdir %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | FileCheck %s
// REQUIRES: CPU=x86_64
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
import gizmo
// -- Protocol records for cast-to ObjC protocols
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ = private constant
// CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section "__DATA,__objc_protolist,coalesced,no_dead_strip"
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section "__DATA,__objc_protorefs,coalesced,no_dead_strip"
// CHECK: @_PROTOCOL_NSRuncing = private constant
// CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section "__DATA,__objc_protolist,coalesced,no_dead_strip"
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section "__DATA,__objc_protorefs,coalesced,no_dead_strip"
// CHECK: @_PROTOCOLS__TtC13generic_casts10ObjCClass2 = private constant { i64, [1 x i8*] } {
// CHECK: i64 1,
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto2_
// CHECK: }
// CHECK: @_DATA__TtC13generic_casts10ObjCClass2 = private constant {{.*}} @_PROTOCOLS__TtC13generic_casts10ObjCClass2
// CHECK: @_PROTOCOL_PROTOCOLS__TtP13generic_casts10ObjCProto2_ = private constant { i64, [1 x i8*] } {
// CHECK: i64 1,
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_
// CHECK: }
// CHECK: define hidden i64 @_TF13generic_casts8allToInt{{.*}}(%swift.opaque* noalias nocapture, %swift.type* %T)
func allToInt<T>(x: T) -> Int {
return x as! Int
// CHECK: [[BUF:%.*]] = alloca [[BUFFER:.24 x i8.]],
// CHECK: [[INT_TEMP:%.*]] = alloca %Si,
// CHECK: [[TEMP:%.*]] = call %swift.opaque* {{.*}}([[BUFFER]]* [[BUF]], %swift.opaque* %0, %swift.type* %T)
// CHECK: [[T0:%.*]] = bitcast %Si* [[INT_TEMP]] to %swift.opaque*
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* [[T0]], %swift.opaque* [[TEMP]], %swift.type* %T, %swift.type* @_TMSi, i64 7)
// CHECK: [[T0:%.*]] = getelementptr inbounds %Si, %Si* [[INT_TEMP]], i32 0, i32 0
// CHECK: [[INT_RESULT:%.*]] = load i64, i64* [[T0]],
// CHECK: ret i64 [[INT_RESULT]]
}
// CHECK: define hidden void @_TF13generic_casts8intToAll{{.*}}(%swift.opaque* noalias nocapture sret, i64, %swift.type* %T) {{.*}} {
func intToAll<T>(x: Int) -> T {
// CHECK: [[INT_TEMP:%.*]] = alloca %Si,
// CHECK: [[T0:%.*]] = getelementptr inbounds %Si, %Si* [[INT_TEMP]], i32 0, i32 0
// CHECK: store i64 %1, i64* [[T0]],
// CHECK: [[T0:%.*]] = bitcast %Si* [[INT_TEMP]] to %swift.opaque*
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[T0]], %swift.type* @_TMSi, %swift.type* %T, i64 7)
return x as! T
}
// CHECK: define hidden i64 @_TF13generic_casts8anyToInt{{.*}}(%"protocol<>"* noalias nocapture dereferenceable({{.*}}))
func anyToInt(x: protocol<>) -> Int {
return x as! Int
}
@objc protocol ObjCProto1 {
static func forClass()
static func forInstance()
var prop: NSObject { get }
}
@objc protocol ObjCProto2 : ObjCProto1 {}
@objc class ObjCClass {}
// CHECK: define hidden %objc_object* @_TF13generic_casts9protoCast{{.*}}(%C13generic_casts9ObjCClass*) {{.*}} {
func protoCast(x: ObjCClass) -> protocol<ObjCProto1, NSRuncing> {
// CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_"
// CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing"
// CHECK: call %objc_object* @swift_dynamicCastObjCProtocolUnconditional(%objc_object* {{%.*}}, i64 2, i8** {{%.*}})
return x as! protocol<ObjCProto1, NSRuncing>
}
@objc class ObjCClass2 : NSObject, ObjCProto2 {
class func forClass() {}
class func forInstance() {}
var prop: NSObject { return self }
}
// <rdar://problem/15313840>
// Class existential to opaque archetype cast
// CHECK: define hidden void @_TF13generic_casts33classExistentialToOpaqueArchetype{{.*}}(%swift.opaque* noalias nocapture sret, %objc_object*, %swift.type* %T)
func classExistentialToOpaqueArchetype<T>(x: ObjCProto1) -> T {
var x = x
// CHECK: [[X:%.*]] = alloca %P13generic_casts10ObjCProto1_
// CHECK: [[LOCAL:%.*]] = alloca %P13generic_casts10ObjCProto1_
// CHECK: [[LOCAL_OPAQUE:%.*]] = bitcast %P13generic_casts10ObjCProto1_* [[LOCAL]] to %swift.opaque*
// CHECK: [[PROTO_TYPE:%.*]] = call %swift.type* @_TMaP13generic_casts10ObjCProto1_()
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[LOCAL_OPAQUE]], %swift.type* [[PROTO_TYPE]], %swift.type* %T, i64 7)
return x as! T
}
| c27d859ee866161e9eb89c3fb23d7153 | 49.111111 | 228 | 0.663576 | false | false | false | false |
YesVideo/swix | refs/heads/master | swix/swix/swix/matrix/m-initing.swift | mit | 1 | //
// twoD-initing.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
public func zeros(shape: (Int, Int)) -> matrix{
return matrix(columns: shape.1, rows: shape.0)
}
public func zeros_like(x: matrix) -> matrix{
let y:matrix = zeros((x.shape.0, x.shape.1))
return y
}
public func ones_like(x: matrix) -> matrix{
return zeros_like(x) + 1
}
public func ones(shape: (Int, Int)) -> matrix{
return zeros(shape)+1
}
public func eye(N: Int) -> matrix{
return diag(ones(N))
}
public func diag(x:ndarray)->matrix{
var y = zeros((x.n, x.n))
y["diag"] = x
return y
}
public func randn(N: (Int, Int), mean: Double=0, sigma: Double=1) -> matrix{
var x = zeros(N)
let y = randn(N.0 * N.1, mean:mean, sigma:sigma)
x.flat = y
return x
}
public func rand(N: (Int, Int)) -> matrix{
var x = zeros(N)
let y = rand(N.0 * N.1)
x.flat = y
return x
}
public func reshape(x: ndarray, shape:(Int, Int))->matrix{
return x.reshape(shape)
}
public func meshgrid(x: ndarray, y:ndarray) -> (matrix, matrix){
assert(x.n > 0 && y.n > 0, "If these matrices are empty meshgrid fails")
let z1 = reshape(`repeat`(y, N: x.n), shape: (x.n, y.n))
let z2 = reshape(`repeat`(x, N: y.n, axis: 1), shape: (x.n, y.n))
return (z2, z1)
}
/// array("1 2 3; 4 5 6; 7 8 9") works like matlab. note that string format has to be followed to the dot. String parsing has bugs; I'd use arange(9).reshape((3,3)) or something similar
public func array(matlab_like_string: String)->matrix{
let mls = matlab_like_string
var rows = mls.componentsSeparatedByString(";")
let r = rows.count
var c = 0
for char in rows[0].characters{
if char == " " {}
else {c += 1}
}
var x = zeros((r, c))
var start:Int
var i:Int=0, j:Int=0
for row in rows{
var nums = row.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if nums[0] == ""{start=1}
else {start=0}
j = 0
for n in start..<nums.count{
x[i, j] = nums[n].floatValue.double
j += 1
}
i += 1
}
return x
}
| 868aed706291fb4543237487285b13dc | 26.45122 | 185 | 0.593514 | false | false | false | false |
narner/AudioKit | refs/heads/master | Playgrounds/AudioKitPlaygrounds/Playgrounds/Basics.playground/Pages/Playgrounds to Production.xcplaygroundpage/Contents.swift | mit | 1 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//: ## Playgrounds to Production
//:
//: The intention of most of the AudioKit Playgrounds is to highlight a particular
//: concept. To keep things clear, we have kept the amount of code to a minimum.
//: But the flipside of that decision is that code from playgrounds will look a little
//: different from production. In general, to see best practices, you can check out
//: the AudioKit examples project, but here in this playground we'll highlight some
//: important ways playground code differs from production code.
//:
//: In production, you would only import AudioKit, not AudioKitPlaygrounds
import AudioKitPlaygrounds
import AudioKit
//: ### Memory management
//:
//: In a playground, you don't have to worry about whether a node is retained, so you can
//: just write:
let oscillator = AKOscillator()
AudioKit.output = oscillator
AudioKit.start()
//: But if you did the same type of thing in a project:
class BadAudioEngine {
init() {
let oscillator = AKOscillator()
AudioKit.output = oscillator
AudioKit.start()
}
}
//: It wouldn't work because the oscillator node would be lost right after the init
//: method completed. Instead, make sure it is declared as an instance variable:
class AudioEngine {
var oscillator: AKOscillator
init() {
oscillator = AKOscillator()
AudioKit.output = oscillator
AudioKit.start()
}
}
//: ### Error Handling
//:
//: In AudioKit playgrounds, failable initializers are just one line:
let file = try AKAudioFile()
var player = try AKAudioPlayer(file: file)
//: In production code, this would need to be wrapped in a do-catch block
do {
let file = try AKAudioFile(readFileName: "drumloop.wav")
player = try AKAudioPlayer(file: file)
} catch {
AKLog("File Not Found")
}
//: ---
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| 4f98e054e8ac9e96a6a286c9a0e4e79c | 31.213115 | 89 | 0.698219 | false | false | false | false |
tensorflow/swift-apis | refs/heads/main | Sources/TensorFlow/Epochs/Algorithms.swift | apache-2.0 | 1 | //===--- Algorithms.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -g -Onone -DUSE_STDLIBUNITTEST %s -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
#if USE_STDLIBUNITTEST
import Swift
import StdlibUnittest
#endif
//===--- Rotate -----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// Provides customization points for `MutableCollection` algorithms.
///
/// If incorporated into the standard library, these requirements would just be
/// part of `MutableCollection`. In the meantime, you can declare conformance
/// of a collection to `MutableCollectionAlgorithms` to get these customization
/// points to be used from other algorithms defined on
/// `MutableCollectionAlgorithms`.
public protocol MutableCollectionAlgorithms: MutableCollection
where SubSequence: MutableCollectionAlgorithms {
/// Rotates the elements of the collection so that the element
/// at `middle` ends up first.
///
/// - Returns: The new index of the element that was first
/// pre-rotation.
/// - Complexity: O(*n*)
@discardableResult
mutating func rotate(shiftingToStart middle: Index) -> Index
}
// Conformances of common collection types to MutableCollectionAlgorithms.
// If rotate was a requirement of MutableCollection, these would not be needed.
extension Array: MutableCollectionAlgorithms {}
extension ArraySlice: MutableCollectionAlgorithms {}
extension Slice: MutableCollectionAlgorithms
where Base: MutableCollection {}
extension MutableCollection {
/// Swaps the elements of the two given subranges, up to the upper bound of
/// the smaller subrange. The returned indices are the ends of the two ranges
/// that were actually swapped.
///
/// Input:
/// [a b c d e f g h i j k l m n o p]
/// ^^^^^^^ ^^^^^^^^^^^^^
/// lhs rhs
///
/// Output:
/// [i j k l e f g h a b c d m n o p]
/// ^ ^
/// p q
///
/// - Precondition: !lhs.isEmpty && !rhs.isEmpty
/// - Postcondition: For returned indices `(p, q)`:
/// - distance(from: lhs.lowerBound, to: p) ==
/// distance(from: rhs.lowerBound, to: q)
/// - p == lhs.upperBound || q == rhs.upperBound
@inline(__always)
internal mutating func _swapNonemptySubrangePrefixes(
_ lhs: Range<Index>, _ rhs: Range<Index>
) -> (Index, Index) {
assert(!lhs.isEmpty)
assert(!rhs.isEmpty)
var p = lhs.lowerBound
var q = rhs.lowerBound
repeat {
swapAt(p, q)
formIndex(after: &p)
formIndex(after: &q)
} while p != lhs.upperBound && q != rhs.upperBound
return (p, q)
}
/// Rotates the elements of the collection so that the element
/// at `middle` ends up first.
///
/// - Returns: The new index of the element that was first
/// pre-rotation.
/// - Complexity: O(*n*)
@discardableResult
public mutating func rotate(shiftingToStart middle: Index) -> Index {
var m = middle
var s = startIndex
let e = endIndex
// Handle the trivial cases
if s == m { return e }
if m == e { return s }
// We have two regions of possibly-unequal length that need to be
// exchanged. The return value of this method is going to be the
// position following that of the element that is currently last
// (element j).
//
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
// ^ ^ ^ ^ ^ ^
// s m e s m e
//
var ret = e // start with a known incorrect result.
while true {
// Exchange the leading elements of each region (up to the
// length of the shorter region).
//
// [a b c d e f g|h i j] or [a b c|d e f g h i j]
// ^^^^^ ^^^^^ ^^^^^ ^^^^^
// [h i j d e f g|a b c] or [d e f|a b c g h i j]
// ^ ^ ^ ^ ^ ^ ^ ^
// s s1 m m1/e s s1/m m1 e
//
let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)
if m1 == e {
// Left-hand case: we have moved element j into position. if
// we haven't already, we can capture the return value which
// is in s1.
//
// Note: the STL breaks the loop into two just to avoid this
// comparison once the return value is known. I'm not sure
// it's a worthwhile optimization, though.
if ret == e { ret = s1 }
// If both regions were the same size, we're done.
if s1 == m { break }
}
// Now we have a smaller problem that is also a rotation, so we
// can adjust our bounds and repeat.
//
// h i j[d e f g|a b c] or d e f[a b c|g h i j]
// ^ ^ ^ ^ ^ ^
// s m e s m e
s = s1
if s == m { m = m1 }
}
return ret
}
}
extension MutableCollection where Self: BidirectionalCollection {
/// Reverses the elements of the collection, moving from each end until
/// `limit` is reached from either direction. The returned indices are the
/// start and end of the range of unreversed elements.
///
/// Input:
/// [a b c d e f g h i j k l m n o p]
/// ^
/// limit
/// Output:
/// [p o n m e f g h i j k l d c b a]
/// ^ ^
/// f l
///
/// - Postcondition: For returned indices `(f, l)`:
/// `f == limit || l == limit`
@inline(__always)
@discardableResult
internal mutating func _reverseUntil(_ limit: Index) -> (Index, Index) {
var f = startIndex
var l = endIndex
while f != limit && l != limit {
formIndex(before: &l)
swapAt(f, l)
formIndex(after: &f)
}
return (f, l)
}
/// Rotates the elements of the collection so that the element
/// at `middle` ends up first.
///
/// - Returns: The new index of the element that was first
/// pre-rotation.
/// - Complexity: O(*n*)
@discardableResult
public mutating func rotate(shiftingToStart middle: Index) -> Index {
// FIXME: this algorithm should be benchmarked on arrays against
// the forward Collection algorithm above to prove that it's
// actually faster. The other one sometimes does more swaps, but
// has better locality properties. Similarly, we've omitted a
// specialization of rotate for RandomAccessCollection that uses
// cycles per section 11.4 in "From Mathematics to Generic
// Programming" by A. Stepanov because it has *much* worse
// locality properties than either of the other implementations.
// Benchmarks should be performed for that algorithm too, just to
// be sure.
self[..<middle].reverse()
self[middle...].reverse()
let (p, q) = _reverseUntil(middle)
self[p..<q].reverse()
return middle == p ? q : p
}
}
/// Returns the greatest common denominator for `m` and `n`.
internal func _gcd(_ m: Int, _ n: Int) -> Int {
var (m, n) = (m, n)
while n != 0 {
let t = m % n
m = n
n = t
}
return m
}
extension MutableCollection where Self: RandomAccessCollection {
/// Rotates elements through a cycle, using `sourceForIndex` to generate
/// the source index for each movement.
@inline(__always)
internal mutating func _rotateCycle(
start: Index,
sourceOffsetForIndex: (Index) -> Int
) {
let tmp = self[start]
var i = start
var j = index(start, offsetBy: sourceOffsetForIndex(start))
while j != start {
self[i] = self[j]
i = j
j = index(j, offsetBy: sourceOffsetForIndex(j))
}
self[i] = tmp
}
/// Rotates the elements of the collection so that the element
/// at `middle` ends up first.
///
/// - Returns: The new index of the element that was first
/// pre-rotation.
/// - Complexity: O(*n*)
@discardableResult
public mutating func rotateRandomAccess(
shiftingToStart middle: Index
) -> Index {
if middle == startIndex { return endIndex }
if middle == endIndex { return startIndex }
// The distance to move an element that is moving ->
let plus = distance(from: startIndex, to: middle)
// The distance to move an element that is moving <-
let minus = distance(from: endIndex, to: middle)
// The new pivot point, aka the destination for the first element
let pivot = index(startIndex, offsetBy: -minus)
// If the difference moving forward and backward are relative primes,
// the entire rotation will be completed in one cycle. Otherwise, repeat
// cycle, moving the start point forward with each cycle.
let cycles = _gcd(numericCast(plus), -numericCast(minus))
for cycle in 1...cycles {
_rotateCycle(
start: index(startIndex, offsetBy: numericCast(cycle)),
sourceOffsetForIndex: { $0 < pivot ? plus : minus })
}
return pivot
}
}
//===--- Concatenation ----------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Concatenation improves on a flattened array or other collection by
// allowing random-access traversal if the underlying collections are
// random-access.
/// A concatenation of two sequences with the same element type.
public struct Concatenation<Base1: Sequence, Base2: Sequence>: Sequence
where Base1.Element == Base2.Element {
let _base1: Base1
let _base2: Base2
init(_base1: Base1, base2: Base2) {
self._base1 = _base1
self._base2 = base2
}
public struct Iterator: IteratorProtocol {
var _iterator1: Base1.Iterator
var _iterator2: Base2.Iterator
init(_ concatenation: Concatenation) {
_iterator1 = concatenation._base1.makeIterator()
_iterator2 = concatenation._base2.makeIterator()
}
public mutating func next() -> Base1.Element? {
return _iterator1.next() ?? _iterator2.next()
}
}
public func makeIterator() -> Iterator {
Iterator(self)
}
}
extension Concatenation: Collection where Base1: Collection, Base2: Collection {
/// A position in a `Concatenation`.
public struct Index: Comparable {
internal enum _Representation: Equatable {
case first(Base1.Index)
case second(Base2.Index)
}
/// Creates a new index into the first underlying collection.
internal init(first i: Base1.Index) {
_position = .first(i)
}
/// Creates a new index into the second underlying collection.
internal init(second i: Base2.Index) {
_position = .second(i)
}
internal let _position: _Representation
public static func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs._position, rhs._position) {
case (.first, .second):
return true
case (.second, .first):
return false
case let (.first(l), .first(r)):
return l < r
case let (.second(l), .second(r)):
return l < r
}
}
}
public var startIndex: Index {
// If `_base1` is empty, then `_base2.startIndex` is either a valid position
// of an element or equal to `_base2.endIndex`.
return _base1.isEmpty
? Index(second: _base2.startIndex)
: Index(first: _base1.startIndex)
}
public var endIndex: Index {
return Index(second: _base2.endIndex)
}
public subscript(i: Index) -> Base1.Element {
switch i._position {
case let .first(i):
return _base1[i]
case let .second(i):
return _base2[i]
}
}
public func index(after i: Index) -> Index {
switch i._position {
case let .first(i):
assert(i != _base1.endIndex)
let next = _base1.index(after: i)
return next == _base1.endIndex
? Index(second: _base2.startIndex)
: Index(first: next)
case let .second(i):
return Index(second: _base2.index(after: i))
}
}
}
extension Concatenation: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection {
public func index(before i: Index) -> Index {
assert(i != startIndex, "Can't advance before startIndex")
switch i._position {
case let .first(i):
return Index(first: _base1.index(before: i))
case let .second(i):
return i == _base2.startIndex
? Index(first: _base1.index(before: _base1.endIndex))
: Index(second: _base2.index(before: i))
}
}
}
extension Concatenation: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {
public func index(_ i: Index, offsetBy n: Int) -> Index {
if n == 0 { return i }
return n > 0 ? _offsetForward(i, by: n) : _offsetBackward(i, by: -n)
}
internal func _offsetForward(
_ i: Index, by n: Int
) -> Index {
switch i._position {
case let .first(i):
let d: Int = _base1.distance(from: i, to: _base1.endIndex)
if n < d {
return Index(first: _base1.index(i, offsetBy: numericCast(n)))
} else {
return Index(
second: _base2.index(_base2.startIndex, offsetBy: numericCast(n - d)))
}
case let .second(i):
return Index(second: _base2.index(i, offsetBy: numericCast(n)))
}
}
internal func _offsetBackward(
_ i: Index, by n: Int
) -> Index {
switch i._position {
case let .first(i):
return Index(first: _base1.index(i, offsetBy: -numericCast(n)))
case let .second(i):
let d: Int = _base2.distance(from: _base2.startIndex, to: i)
if n <= d {
return Index(second: _base2.index(i, offsetBy: -numericCast(n)))
} else {
return Index(
first: _base1.index(_base1.endIndex, offsetBy: -numericCast(n - d)))
}
}
}
}
/// Returns a new collection that presents a view onto the elements of the
/// first collection and then the elements of the second collection.
func concatenate<S1: Sequence, S2: Sequence>(
_ first: S1,
_ second: S2
) -> Concatenation<S1, S2> where S1.Element == S2.Element {
return Concatenation(_base1: first, base2: second)
}
extension Sequence {
func followed<S: Sequence>(by other: S) -> Concatenation<Self, S>
where Element == S.Element {
return concatenate(self, other)
}
}
//===--- RotatedCollection ------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A rotated view onto a collection.
public struct RotatedCollection<Base: Collection>: Collection {
let _base: Base
let _indices: Concatenation<Base.Indices, Base.Indices>
init(_base: Base, shiftingToStart i: Base.Index) {
self._base = _base
self._indices = concatenate(_base.indices[i...], _base.indices[..<i])
}
/// A position in a rotated collection.
public struct Index: Comparable {
internal let _index: Concatenation<Base.Indices, Base.Indices>.Index
public static func < (lhs: Index, rhs: Index) -> Bool {
return lhs._index < rhs._index
}
}
public var startIndex: Index {
return Index(_index: _indices.startIndex)
}
public var endIndex: Index {
return Index(_index: _indices.endIndex)
}
public subscript(i: Index) -> Base.SubSequence.Element {
return _base[_indices[i._index]]
}
public func index(after i: Index) -> Index {
return Index(_index: _indices.index(after: i._index))
}
public func index(_ i: Index, offsetBy n: Int) -> Index {
return Index(_index: _indices.index(i._index, offsetBy: n))
}
public func distance(from start: Index, to end: Index) -> Int {
return _indices.distance(from: start._index, to: end._index)
}
/// The shifted position of the base collection's `startIndex`.
public var shiftedStartIndex: Index {
return Index(
_index: Concatenation<Base.Indices, Base.Indices>.Index(
second: _indices._base2.startIndex)
)
}
public func rotated(shiftingToStart i: Index) -> RotatedCollection<Base> {
return RotatedCollection(_base: _base, shiftingToStart: _indices[i._index])
}
}
extension RotatedCollection: BidirectionalCollection
where Base: BidirectionalCollection {
public func index(before i: Index) -> Index {
return Index(_index: _indices.index(before: i._index))
}
}
extension RotatedCollection: RandomAccessCollection
where Base: RandomAccessCollection {}
extension Collection {
/// Returns a view of this collection with the elements reordered such the
/// element at the given position ends up first.
///
/// The subsequence of the collection up to `i` is shifted to after the
/// subsequence starting at `i`. The order of the elements within each
/// partition is otherwise unchanged.
///
/// let a = [10, 20, 30, 40, 50, 60, 70]
/// let r = a.rotated(shiftingToStart: 3)
/// // r.elementsEqual([40, 50, 60, 70, 10, 20, 30])
///
/// - Parameter i: The position in the collection that should be first in the
/// result. `i` must be a valid index of the collection.
/// - Returns: A rotated view on the elements of this collection, such that
/// the element at `i` is first.
func rotated(shiftingToStart i: Index) -> RotatedCollection<Self> {
return RotatedCollection(_base: self, shiftingToStart: i)
}
}
//===--- Stable Partition -------------------------------------------------===//
//===----------------------------------------------------------------------===//
extension MutableCollectionAlgorithms {
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, preserving their relative order, and returns the start of the
/// resulting suffix.
///
/// - Complexity: O(n) where n is the number of elements.
@discardableResult
mutating func stablePartition(
isSuffixElement: (Element) throws -> Bool
) rethrows -> Index {
return try stablePartition(count: count, isSuffixElement: isSuffixElement)
}
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, preserving their relative order, and returns the start of the
/// resulting suffix.
///
/// - Complexity: O(n) where n is the number of elements.
/// - Precondition: `n == self.count`
fileprivate mutating func stablePartition(
count n: Int, isSuffixElement: (Element) throws -> Bool
) rethrows -> Index {
if n == 0 { return startIndex }
if n == 1 {
return try isSuffixElement(self[startIndex]) ? startIndex : endIndex
}
let h = n / 2
let i = index(startIndex, offsetBy: h)
let j = try self[..<i].stablePartition(
count: h, isSuffixElement: isSuffixElement)
let k = try self[i...].stablePartition(
count: n - h, isSuffixElement: isSuffixElement)
return self[j..<k].rotate(shiftingToStart: i)
}
}
extension Collection {
func stablyPartitioned(
isSuffixElement p: (Element) -> Bool
) -> [Element] {
var a = Array(self)
a.stablePartition(isSuffixElement: p)
return a
}
}
extension LazyCollectionProtocol
where Element == Elements.Element, Elements: Collection {
func stablyPartitioned(
isSuffixElement p: (Element) -> Bool
) -> LazyCollection<[Element]> {
return elements.stablyPartitioned(isSuffixElement: p).lazy
}
}
extension Collection {
/// Returns the index of the first element in the collection
/// that matches the predicate.
///
/// The collection must already be partitioned according to the
/// predicate, as if `self.partition(by: predicate)` had already
/// been called.
///
/// - Efficiency: At most log(N) invocations of `predicate`, where
/// N is the length of `self`. At most log(N) index offsetting
/// operations if `self` conforms to `RandomAccessCollection`;
/// at most N such operations otherwise.
func partitionPoint(
where predicate: (Element) throws -> Bool
) rethrows -> Index {
var n = distance(from: startIndex, to: endIndex)
var l = startIndex
while n > 0 {
let half = n / 2
let mid = index(l, offsetBy: half)
if try predicate(self[mid]) {
n = half
} else {
l = index(after: mid)
n -= half + 1
}
}
return l
}
}
| 7c79318fe598643e275202e1d67bc291 | 31.862559 | 80 | 0.606384 | false | false | false | false |
shelleyweiss/softsurvey | refs/heads/master | SoftSurvey/SoftQuestion.swift | artistic-2.0 | 1 | //
// SoftQuestion.swift
// SoftSurvey
//
// Created by shelley weiss on 3/4/15.
// Copyright (c) 2015 shelley weiss. All rights reserved.
//
import UIKit
class SoftQuestion {
let value: Int!
let question: String!
var response: String? = nil
//let content: String
private enum Answer {
case Single(NSArray)
case Multiple(String)
case FreeText(String, String -> String)
}
//private var answerStack = [Answer]()
var optionalAnswers: [String]! = []
//var isAnswered: Bool = false
init(value: Int, text: String)//answers: [String])
{
self.question = text
self.value = value
optionalAnswers.append( "")
}
convenience init()
{
//Rule 2: Calling another initializer in same class
self.init( value:-2 , text: "Nothing" )
}
func pushAnswer(answer: String )
{
if optionalAnswers.count <= 4
{
self.optionalAnswers.append(answer)
}
}
func ask(index : Int) -> String {
var result = ""
if !optionalAnswers.isEmpty
{
result = optionalAnswers[index]
}
return result
}
/*private func popAnswer()->Answer
{
return answerStack.removeLast()
}
func pushMultiple(answer: String )
{
answerStack.append(Answer.Multiple(answer))
}
func pushSingle(answer: NSDictionary )
{
answerStack.append(Answer.Single(answer))
}
func pushFreeText(index: Int)
{
if (isAnswered)
{
}
}*/
private func evaluate(answers: [Answer]) -> ( result: NSDictionary?, remainingAnswers: [Answer] )
{
if !answers.isEmpty
{
var remainingAnswers = answers
let answer = remainingAnswers.removeLast()
switch answer{
case .Single (let a ):
println("Single")
case .Multiple:
println("Multiple")
case .FreeText:
println("FreeText")
}
}
return ( nil, answers)
}
private func performOperation(operation: Answer)
{
switch operation {
case .Single:
println("Single")
case .Multiple:
println("Multiple")
case .FreeText:
println("FreeText")
}
}
} | 775d29268277ea25f4c1630e2c4ff2df | 19.061069 | 101 | 0.493338 | false | false | false | false |
andrucuna/ios | refs/heads/master | Swiftris/Swiftris/GameScene.swift | gpl-2.0 | 1 | //
// GameScene.swift
// Swiftris
//
// Created by Andrés Ruiz on 9/24/14.
// Copyright (c) 2014 Andrés Ruiz. All rights reserved.
//
import SpriteKit
// We simply define the point size of each block sprite - in our case 20.0 x 20.0 - the lower of the
// available resolution options for each block image. We also declare a layer position which will give us an
// offset from the edge of the screen.
let BlockSize:CGFloat = 20.0
// This variable will represent the slowest speed at which our shapes will travel.
let TickLengthLevelOne = NSTimeInterval(600)
class GameScene: SKScene
{
// #2
let gameLayer = SKNode()
let shapeLayer = SKNode()
let LayerPosition = CGPoint(x: 6, y: -6)
// In tick, its type is (() -> ())? which means that it's a closure which takes no parameters and
// returns nothing. Its question mark indicates that it is optional and therefore may be nil.
var tick: (() ->())?
var tickLengthMillis = TickLengthLevelOne
var lastTick: NSDate?
var textureCache = Dictionary<String, SKTexture>()
required init( coder aDecoder: (NSCoder!) )
{
fatalError( "NSCoder not supported" )
}
override init( size: CGSize )
{
super.init( size: size )
anchorPoint = CGPoint( x: 0, y: 1.0 )
let background = SKSpriteNode( imageNamed: "background" )
background.position = CGPoint( x: 0, y: 0 )
background.anchorPoint = CGPoint( x: 0, y: 1.0 )
addChild( background )
addChild(gameLayer)
let gameBoardTexture = SKTexture(imageNamed: "gameboard")
let gameBoard = SKSpriteNode(texture: gameBoardTexture, size: CGSizeMake(BlockSize * CGFloat(NumColumns), BlockSize * CGFloat(NumRows)))
gameBoard.anchorPoint = CGPoint(x:0, y:1.0)
gameBoard.position = LayerPosition
shapeLayer.position = LayerPosition
shapeLayer.addChild(gameBoard)
gameLayer.addChild(shapeLayer)
// We set up a looping sound playback action of our theme song.
runAction(SKAction.repeatActionForever(SKAction.playSoundFileNamed("theme.mp3", waitForCompletion: true)))
}
// We added a method which GameViewController may use to play any sound file on demand.
func playSound(sound:String)
{
runAction(SKAction.playSoundFileNamed(sound, waitForCompletion: false))
}
override func update(currentTime: CFTimeInterval)
{
/* Called before each frame is rendered */
// If lastTick is missing, we are in a paused state, not reporting elapsed ticks to anyone,
// therefore we simply return.
if lastTick == nil
{
return
}
var timePassed = lastTick!.timeIntervalSinceNow * -1000.0
if timePassed > tickLengthMillis
{
lastTick = NSDate.date()
tick?()
}
}
// We provide accessor methods to let external classes stop and start the ticking process.
func startTicking() {
lastTick = NSDate.date()
}
func stopTicking() {
lastTick = nil
}
// The math here looks funky but just know that each sprite will be anchored at its center, therefore we
// need to find its center coordinate before placing it in our shapeLayer object.
func pointForColumn(column: Int, row: Int) -> CGPoint
{
let x: CGFloat = LayerPosition.x + (CGFloat(column) * BlockSize) + (BlockSize / 2)
let y: CGFloat = LayerPosition.y - ((CGFloat(row) * BlockSize) + (BlockSize / 2))
return CGPointMake(x, y)
}
func addPreviewShapeToScene(shape:Shape, completion:() -> ())
{
for (idx, block) in enumerate(shape.blocks)
{
// We've created a method which will add a shape for the first time to the scene as a preview
// shape. We use a dictionary to store copies of re-usable SKTexture objects since each shape
// will require multiple copies of the same image.
var texture = textureCache[block.spriteName]
if texture == nil
{
texture = SKTexture(imageNamed: block.spriteName)
textureCache[block.spriteName] = texture
}
let sprite = SKSpriteNode(texture: texture)
// We use our convenient pointForColumn(Int, Int) method to place each block's sprite in the
// proper location. We start it at row - 2, such that the preview piece animates smoothly into
// place from a higher location.
sprite.position = pointForColumn(block.column, row:block.row - 2)
shapeLayer.addChild(sprite)
block.sprite = sprite
// Animation
sprite.alpha = 0
// We introduce SKAction objects which are responsible for visually manipulating SKNode objects.
// Each block will fade and move into place as it appears as part of the next piece. It will
// move two rows down and fade from complete transparency to 70% opacity.
let moveAction = SKAction.moveTo(pointForColumn(block.column, row: block.row), duration: NSTimeInterval(0.2))
moveAction.timingMode = .EaseOut
let fadeInAction = SKAction.fadeAlphaTo(0.7, duration: 0.4)
fadeInAction.timingMode = .EaseOut
sprite.runAction(SKAction.group([moveAction, fadeInAction]))
}
runAction(SKAction.waitForDuration(0.4), completion: completion)
}
func movePreviewShape(shape:Shape, completion:() -> ())
{
for (idx, block) in enumerate(shape.blocks)
{
let sprite = block.sprite!
let moveTo = pointForColumn(block.column, row:block.row)
let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: 0.2)
moveToAction.timingMode = .EaseOut
sprite.runAction(
SKAction.group([moveToAction, SKAction.fadeAlphaTo(1.0, duration: 0.2)]), completion:nil)
}
runAction(SKAction.waitForDuration(0.2), completion: completion)
}
func redrawShape(shape:Shape, completion:() -> ())
{
for (idx, block) in enumerate(shape.blocks)
{
let sprite = block.sprite!
let moveTo = pointForColumn(block.column, row:block.row)
let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: 0.05)
moveToAction.timingMode = .EaseOut
sprite.runAction(moveToAction, completion: nil)
}
runAction(SKAction.waitForDuration(0.05), completion: completion)
}
// You can see that we take in precisely the tuple data which Swiftris returns each time a line is
// removed. This will ensure that GameViewController need only pass those elements to GameScene in order
// for them to animate properly.
func animateCollapsingLines(linesToRemove: Array<Array<Block>>, fallenBlocks: Array<Array<Block>>, completion:() -> ())
{
var longestDuration: NSTimeInterval = 0
// We also established a longestDuration variable which will determine precisely how long we should
// wait before calling the completion closure.
for (columnIdx, column) in enumerate(fallenBlocks)
{
for (blockIdx, block) in enumerate(column)
{
let newPosition = pointForColumn(block.column, row: block.row)
let sprite = block.sprite!
// We wrote code which will produce this pleasing effect for eye balls to enjoy. Based on
// the block and column indices, we introduce a directly proportional delay.
let delay = (NSTimeInterval(columnIdx) * 0.05) + (NSTimeInterval(blockIdx) * 0.05)
let duration = NSTimeInterval(((sprite.position.y - newPosition.y) / BlockSize) * 0.1)
let moveAction = SKAction.moveTo(newPosition, duration: duration)
moveAction.timingMode = .EaseOut
sprite.runAction(
SKAction.sequence([
SKAction.waitForDuration(delay),
moveAction]))
longestDuration = max(longestDuration, duration + delay)
}
}
for (rowIdx, row) in enumerate(linesToRemove)
{
for (blockIdx, block) in enumerate(row)
{
// We make their blocks shoot off the screen like explosive debris. In order to accomplish
// this we will employ UIBezierPath. Our arch requires a radius and we've chosen to generate
// one randomly in order to introduce a natural variance among the explosive paths.
// Furthermore, we've randomized whether the block flies left or right.
let randomRadius = CGFloat(UInt(arc4random_uniform(400) + 100))
let goLeft = arc4random_uniform(100) % 2 == 0
var point = pointForColumn(block.column, row: block.row)
point = CGPointMake(point.x + (goLeft ? -randomRadius : randomRadius), point.y)
let randomDuration = NSTimeInterval(arc4random_uniform(2)) + 0.5
// We choose beginning and starting angles, these are clearly in radians
// When going left, we begin at 0 radians and end at π. When going right, we go from π to
// 2π. Math FTW!
var startAngle = CGFloat(M_PI)
var endAngle = startAngle * 2
if goLeft
{
endAngle = startAngle
startAngle = 0
}
let archPath = UIBezierPath(arcCenter: point, radius: randomRadius, startAngle: startAngle, endAngle: endAngle, clockwise: goLeft)
let archAction = SKAction.followPath(archPath.CGPath, asOffset: false, orientToPath: true, duration: randomDuration)
archAction.timingMode = .EaseIn
let sprite = block.sprite!
// We place the block sprite above the others such that they animate above the other blocks
// and begin the sequence of actions which concludes with the sprite being removed from the
// scene.
sprite.zPosition = 100
sprite.runAction(
SKAction.sequence(
[SKAction.group([archAction, SKAction.fadeOutWithDuration(NSTimeInterval(randomDuration))]),
SKAction.removeFromParent()]))
}
}
// We run the completion action after a duration matching the time it will take to drop the last
// block to its new resting place.
runAction(SKAction.waitForDuration(longestDuration), completion:completion)
}
}
| e15e3283b7d09287f97266f75bbabeda | 44.040984 | 146 | 0.612739 | false | false | false | false |
ruddfawcett/Notepad | refs/heads/master | Notepad/Storage.swift | mit | 1 | //
// Storage.swift
// Notepad
//
// Created by Rudd Fawcett on 10/14/16.
// Copyright © 2016 Rudd Fawcett. All rights reserved.
//
#if os(iOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
public class Storage: NSTextStorage {
/// The Theme for the Notepad.
public var theme: Theme? {
didSet {
let wholeRange = NSRange(location: 0, length: (self.string as NSString).length)
self.beginEditing()
self.applyStyles(wholeRange)
self.edited(.editedAttributes, range: wholeRange, changeInLength: 0)
self.endEditing()
}
}
/// The underlying text storage implementation.
var backingStore = NSTextStorage()
override public var string: String {
get {
return backingStore.string
}
}
override public init() {
super.init()
}
override public init(attributedString attrStr: NSAttributedString) {
super.init(attributedString:attrStr)
backingStore.setAttributedString(attrStr)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required public init(itemProviderData data: Data, typeIdentifier: String) throws {
fatalError("init(itemProviderData:typeIdentifier:) has not been implemented")
}
#if os(macOS)
required public init?(pasteboardPropertyList propertyList: Any, ofType type: String) {
fatalError("init(pasteboardPropertyList:ofType:) has not been implemented")
}
required public init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) {
fatalError("init(pasteboardPropertyList:ofType:) has not been implemented")
}
#endif
/// Finds attributes within a given range on a String.
///
/// - parameter location: How far into the String to look.
/// - parameter range: The range to find attributes for.
///
/// - returns: The attributes on a String within a certain range.
override public func attributes(at location: Int, longestEffectiveRange range: NSRangePointer?, in rangeLimit: NSRange) -> [NSAttributedString.Key : Any] {
return backingStore.attributes(at: location, longestEffectiveRange: range, in: rangeLimit)
}
/// Replaces edited characters within a certain range with a new string.
///
/// - parameter range: The range to replace.
/// - parameter str: The new string to replace the range with.
override public func replaceCharacters(in range: NSRange, with str: String) {
self.beginEditing()
backingStore.replaceCharacters(in: range, with: str)
let len = (str as NSString).length
let change = len - range.length
self.edited([.editedCharacters, .editedAttributes], range: range, changeInLength: change)
self.endEditing()
}
/// Sets the attributes on a string for a particular range.
///
/// - parameter attrs: The attributes to add to the string for the range.
/// - parameter range: The range in which to add attributes.
public override func setAttributes(_ attrs: [NSAttributedString.Key : Any]?, range: NSRange) {
self.beginEditing()
backingStore.setAttributes(attrs, range: range)
self.edited(.editedAttributes, range: range, changeInLength: 0)
self.endEditing()
}
/// Retrieves the attributes of a string for a particular range.
///
/// - parameter at: The location to begin with.
/// - parameter range: The range in which to retrieve attributes.
public override func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [NSAttributedString.Key : Any] {
return backingStore.attributes(at: location, effectiveRange: range)
}
/// Processes any edits made to the text in the editor.
override public func processEditing() {
let backingString = backingStore.string
if let nsRange = backingString.range(from: NSMakeRange(NSMaxRange(editedRange), 0)) {
let indexRange = backingString.lineRange(for: nsRange)
let extendedRange: NSRange = NSUnionRange(editedRange, backingString.nsRange(from: indexRange))
applyStyles(extendedRange)
}
super.processEditing()
}
/// Applies styles to a range on the backingString.
///
/// - parameter range: The range in which to apply styles.
func applyStyles(_ range: NSRange) {
guard let theme = self.theme else { return }
let backingString = backingStore.string
backingStore.setAttributes(theme.body.attributes, range: range)
for (style) in theme.styles {
style.regex.enumerateMatches(in: backingString, options: .withoutAnchoringBounds, range: range, using: { (match, flags, stop) in
guard let match = match else { return }
backingStore.addAttributes(style.attributes, range: match.range(at: 0))
})
}
}
}
| 590a8fe9694517f26a7ab57beef2bf60 | 36.932331 | 159 | 0.661447 | false | false | false | false |
tomboates/BrilliantSDK | refs/heads/master | Pod/Classes/NPSScoreViewController.swift | mit | 1 | //
// NSPScoreViewController.swift
// Pods
//
// Created by Phillip Connaughton on 1/24/16.
//
//
import Foundation
protocol NPSScoreViewControllerDelegate: class{
func closePressed(_ state: SurveyViewControllerState)
func npsScorePressed(_ npsScore: Int)
}
class NPSScoreViewController : UIViewController
{
@IBOutlet var closeButton: UIButton!
@IBOutlet var questionLabel: UILabel!
@IBOutlet var button0: UIButton!
@IBOutlet var button1: UIButton!
@IBOutlet var button2: UIButton!
@IBOutlet var button3: UIButton!
@IBOutlet var button4: UIButton!
@IBOutlet var button5: UIButton!
@IBOutlet var button6: UIButton!
@IBOutlet var button7: UIButton!
@IBOutlet var button8: UIButton!
@IBOutlet var button9: UIButton!
@IBOutlet var button10: UIButton!
@IBOutlet weak var notLikelyBtn: UILabel!
@IBOutlet weak var likelyBtn: UILabel!
@IBOutlet var labelWidthConstraint: NSLayoutConstraint!
internal weak var delegate : NPSScoreViewControllerDelegate?
override func viewDidLoad() {
let image = UIImage(named: "brilliant-icon-close", in:Brilliant.imageBundle(), compatibleWith: nil)
self.closeButton.setImage(image, for: UIControlState())
self.closeButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 25, right: 25)
self.questionLabel.textColor = Brilliant.sharedInstance().mainLabelColor()
self.questionLabel.font = Brilliant.sharedInstance().mainLabelFont()
if (Brilliant.sharedInstance().appName != nil)
{
self.questionLabel.text = String(format: "How likely is it that you will recommend %@ to a friend or colleague?", Brilliant.sharedInstance().appName!)
}
else
{
self.questionLabel.text = "How likely is it that you will recommend this app to a friend or colleague?"
}
self.button0.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button1.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button2.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button3.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button4.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button5.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button6.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button7.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button8.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button9.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button10.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button0.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button1.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button2.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button3.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button4.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button5.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button6.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button7.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button8.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button9.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button10.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.notLikelyBtn.font = Brilliant.sharedInstance().levelLabelFont()
self.likelyBtn.font = Brilliant.sharedInstance().levelLabelFont()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// self.updateConstraints()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { (completion) in
// self.updateConstraints()
}
}
func updateConstraints() {
let size = UIDeviceHelper.deviceWidth()
switch size
{
case .small:
self.labelWidthConstraint.constant = 280
break
case .medium:
self.labelWidthConstraint.constant = 300
break
case .large:
self.labelWidthConstraint.constant = 420
break
}
}
@IBAction func closePressed(_ sender: AnyObject) {
Brilliant.sharedInstance().completedSurvey!.dismissAction = "x_npsscreen"
self.delegate?.closePressed(.ratingScreen)
}
@IBAction func zeroPressed(_ sender: AnyObject) {
self.npsNumberResponse(0)
}
@IBAction func onePressed(_ sender: AnyObject) {
self.npsNumberResponse(1)
}
@IBAction func twoPressed(_ sender: AnyObject) {
self.npsNumberResponse(2)
}
@IBAction func threePressed(_ sender: AnyObject) {
self.npsNumberResponse(3)
}
@IBAction func fourPressed(_ sender: AnyObject) {
self.npsNumberResponse(4)
}
@IBAction func fivePressed(_ sender: AnyObject) {
self.npsNumberResponse(5)
}
@IBAction func sixPressed(_ sender: AnyObject) {
self.npsNumberResponse(6)
}
@IBAction func sevenPressed(_ sender: AnyObject) {
self.npsNumberResponse(7)
}
@IBAction func eightPressed(_ sender: AnyObject) {
self.npsNumberResponse(8)
}
@IBAction func ninePressed(_ sender: AnyObject) {
self.npsNumberResponse(9)
}
@IBAction func tenPressed(_ sender: AnyObject) {
self.npsNumberResponse(10)
}
func npsNumberResponse(_ npsNumber: Int)
{
Brilliant.sharedInstance().completedSurvey!.npsRating = npsNumber
self.delegate?.npsScorePressed(npsNumber)
}
}
| 9f8df59c99410f5d9017bc129212b310 | 35.350877 | 162 | 0.670367 | false | false | false | false |
apple/swift-protobuf | refs/heads/main | Sources/SwiftProtobufCore/JSONScanner.swift | apache-2.0 | 2 | // Sources/SwiftProtobuf/JSONScanner.swift - JSON format decoding
//
// Copyright (c) 2014 - 2019 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/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// JSON format decoding engine.
///
// -----------------------------------------------------------------------------
import Foundation
private let asciiBell = UInt8(7)
private let asciiBackspace = UInt8(8)
private let asciiTab = UInt8(9)
private let asciiNewLine = UInt8(10)
private let asciiVerticalTab = UInt8(11)
private let asciiFormFeed = UInt8(12)
private let asciiCarriageReturn = UInt8(13)
private let asciiZero = UInt8(ascii: "0")
private let asciiOne = UInt8(ascii: "1")
private let asciiSeven = UInt8(ascii: "7")
private let asciiNine = UInt8(ascii: "9")
private let asciiColon = UInt8(ascii: ":")
private let asciiPeriod = UInt8(ascii: ".")
private let asciiPlus = UInt8(ascii: "+")
private let asciiComma = UInt8(ascii: ",")
private let asciiSemicolon = UInt8(ascii: ";")
private let asciiDoubleQuote = UInt8(ascii: "\"")
private let asciiSingleQuote = UInt8(ascii: "\'")
private let asciiBackslash = UInt8(ascii: "\\")
private let asciiForwardSlash = UInt8(ascii: "/")
private let asciiHash = UInt8(ascii: "#")
private let asciiEqualSign = UInt8(ascii: "=")
private let asciiUnderscore = UInt8(ascii: "_")
private let asciiQuestionMark = UInt8(ascii: "?")
private let asciiSpace = UInt8(ascii: " ")
private let asciiOpenSquareBracket = UInt8(ascii: "[")
private let asciiCloseSquareBracket = UInt8(ascii: "]")
private let asciiOpenCurlyBracket = UInt8(ascii: "{")
private let asciiCloseCurlyBracket = UInt8(ascii: "}")
private let asciiOpenAngleBracket = UInt8(ascii: "<")
private let asciiCloseAngleBracket = UInt8(ascii: ">")
private let asciiMinus = UInt8(ascii: "-")
private let asciiLowerA = UInt8(ascii: "a")
private let asciiUpperA = UInt8(ascii: "A")
private let asciiLowerB = UInt8(ascii: "b")
private let asciiLowerE = UInt8(ascii: "e")
private let asciiUpperE = UInt8(ascii: "E")
private let asciiLowerF = UInt8(ascii: "f")
private let asciiUpperI = UInt8(ascii: "I")
private let asciiLowerL = UInt8(ascii: "l")
private let asciiLowerN = UInt8(ascii: "n")
private let asciiUpperN = UInt8(ascii: "N")
private let asciiLowerR = UInt8(ascii: "r")
private let asciiLowerS = UInt8(ascii: "s")
private let asciiLowerT = UInt8(ascii: "t")
private let asciiLowerU = UInt8(ascii: "u")
private let asciiLowerZ = UInt8(ascii: "z")
private let asciiUpperZ = UInt8(ascii: "Z")
private func fromHexDigit(_ c: UnicodeScalar) -> UInt32? {
let n = c.value
if n >= 48 && n <= 57 {
return UInt32(n - 48)
}
switch n {
case 65, 97: return 10
case 66, 98: return 11
case 67, 99: return 12
case 68, 100: return 13
case 69, 101: return 14
case 70, 102: return 15
default:
return nil
}
}
// Decode both the RFC 4648 section 4 Base 64 encoding and the RFC
// 4648 section 5 Base 64 variant. The section 5 variant is also
// known as "base64url" or the "URL-safe alphabet".
// Note that both "-" and "+" decode to 62 and "/" and "_" both
// decode as 63.
let base64Values: [Int] = [
/* 0x00 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* 0x10 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* 0x20 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63,
/* 0x30 */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
/* 0x40 */ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
/* 0x50 */ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63,
/* 0x60 */ -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
/* 0x70 */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
/* 0x80 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* 0x90 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* 0xa0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* 0xb0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* 0xc0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* 0xd0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* 0xe0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
/* 0xf0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
]
/// Returns a `Data` value containing bytes equivalent to the given
/// Base64-encoded string, or nil if the conversion fails.
///
/// Notes on Google's implementation (Base64Unescape() in strutil.cc):
/// * Google's C++ implementation accepts arbitrary whitespace
/// mixed in with the base-64 characters
/// * Google's C++ implementation ignores missing '=' characters
/// but if present, there must be the exact correct number of them.
/// * The conformance test requires us to accept both standard RFC4648
/// Base 64 encoding and the "URL and Filename Safe Alphabet" variant.
///
private func parseBytes(
source: UnsafeRawBufferPointer,
index: inout UnsafeRawBufferPointer.Index,
end: UnsafeRawBufferPointer.Index
) throws -> Data {
let c = source[index]
if c != asciiDoubleQuote {
throw JSONDecodingError.malformedString
}
source.formIndex(after: &index)
// Count the base-64 digits
// Ignore most unrecognized characters in this first pass,
// stop at the closing double quote.
let digitsStart = index
var rawChars = 0
var sawSection4Characters = false
var sawSection5Characters = false
while index != end {
var digit = source[index]
if digit == asciiDoubleQuote {
break
}
if digit == asciiBackslash {
source.formIndex(after: &index)
if index == end {
throw JSONDecodingError.malformedString
}
let escaped = source[index]
switch escaped {
case asciiLowerU:
// TODO: Parse hex escapes such as \u0041. Note that
// such escapes are going to be extremely rare, so
// there's little point in optimizing for them.
throw JSONDecodingError.malformedString
case asciiForwardSlash:
digit = escaped
default:
// Reject \b \f \n \r \t \" or \\ and all illegal escapes
throw JSONDecodingError.malformedString
}
}
if digit == asciiPlus || digit == asciiForwardSlash {
sawSection4Characters = true
} else if digit == asciiMinus || digit == asciiUnderscore {
sawSection5Characters = true
}
let k = base64Values[Int(digit)]
if k >= 0 {
rawChars += 1
}
source.formIndex(after: &index)
}
// We reached the end without seeing the close quote
if index == end {
throw JSONDecodingError.malformedString
}
// Reject mixed encodings.
if sawSection4Characters && sawSection5Characters {
throw JSONDecodingError.malformedString
}
// Allocate a Data object of exactly the right size
var value = Data(count: rawChars * 3 / 4)
// Scan the digits again and populate the Data object.
// In this pass, we check for (and fail) if there are
// unexpected characters. But we don't check for end-of-input,
// because the loop above already verified that there was
// a closing double quote.
index = digitsStart
try value.withUnsafeMutableBytes {
(body: UnsafeMutableRawBufferPointer) in
if var p = body.baseAddress, body.count > 0 {
var n = 0
var chars = 0 // # chars in current group
var padding = 0 // # padding '=' chars
digits: while true {
let digit = source[index]
var k = base64Values[Int(digit)]
if k < 0 {
switch digit {
case asciiDoubleQuote:
break digits
case asciiBackslash:
source.formIndex(after: &index)
let escaped = source[index]
switch escaped {
case asciiForwardSlash:
k = base64Values[Int(escaped)]
default:
// Note: Invalid backslash escapes were caught
// above; we should never get here.
throw JSONDecodingError.malformedString
}
case asciiSpace:
source.formIndex(after: &index)
continue digits
case asciiEqualSign: // Count padding
while true {
switch source[index] {
case asciiDoubleQuote:
break digits
case asciiSpace:
break
case 61:
padding += 1
default: // Only '=' and whitespace permitted
throw JSONDecodingError.malformedString
}
source.formIndex(after: &index)
}
default:
throw JSONDecodingError.malformedString
}
}
n <<= 6
n |= k
chars += 1
if chars == 4 {
p[0] = UInt8(truncatingIfNeeded: n >> 16)
p[1] = UInt8(truncatingIfNeeded: n >> 8)
p[2] = UInt8(truncatingIfNeeded: n)
p += 3
chars = 0
n = 0
}
source.formIndex(after: &index)
}
switch chars {
case 3:
p[0] = UInt8(truncatingIfNeeded: n >> 10)
p[1] = UInt8(truncatingIfNeeded: n >> 2)
if padding == 1 || padding == 0 {
return
}
case 2:
p[0] = UInt8(truncatingIfNeeded: n >> 4)
if padding == 2 || padding == 0 {
return
}
case 0:
if padding == 0 {
return
}
default:
break
}
throw JSONDecodingError.malformedString
}
}
source.formIndex(after: &index)
return value
}
// JSON encoding allows a variety of \-escapes, including
// escaping UTF-16 code points (which may be surrogate pairs).
private func decodeString(_ s: String) -> String? {
var out = String.UnicodeScalarView()
var chars = s.unicodeScalars.makeIterator()
while let c = chars.next() {
switch c.value {
case UInt32(asciiBackslash): // backslash
if let escaped = chars.next() {
switch escaped.value {
case UInt32(asciiLowerU): // "\u"
// Exactly 4 hex digits:
if let digit1 = chars.next(),
let d1 = fromHexDigit(digit1),
let digit2 = chars.next(),
let d2 = fromHexDigit(digit2),
let digit3 = chars.next(),
let d3 = fromHexDigit(digit3),
let digit4 = chars.next(),
let d4 = fromHexDigit(digit4) {
let codePoint = ((d1 * 16 + d2) * 16 + d3) * 16 + d4
if let scalar = UnicodeScalar(codePoint) {
out.append(scalar)
} else if codePoint < 0xD800 || codePoint >= 0xE000 {
// Not a valid Unicode scalar.
return nil
} else if codePoint >= 0xDC00 {
// Low surrogate without a preceding high surrogate.
return nil
} else {
// We have a high surrogate (in the range 0xD800..<0xDC00), so
// verify that it is followed by a low surrogate.
guard chars.next() == "\\", chars.next() == "u" else {
// High surrogate was not followed by a Unicode escape sequence.
return nil
}
if let digit1 = chars.next(),
let d1 = fromHexDigit(digit1),
let digit2 = chars.next(),
let d2 = fromHexDigit(digit2),
let digit3 = chars.next(),
let d3 = fromHexDigit(digit3),
let digit4 = chars.next(),
let d4 = fromHexDigit(digit4) {
let follower = ((d1 * 16 + d2) * 16 + d3) * 16 + d4
guard 0xDC00 <= follower && follower < 0xE000 else {
// High surrogate was not followed by a low surrogate.
return nil
}
let high = codePoint - 0xD800
let low = follower - 0xDC00
let composed = 0x10000 | high << 10 | low
guard let composedScalar = UnicodeScalar(composed) else {
// Composed value is not a valid Unicode scalar.
return nil
}
out.append(composedScalar)
} else {
// Malformed \u escape for low surrogate
return nil
}
}
} else {
// Malformed \u escape
return nil
}
case UInt32(asciiLowerB): // \b
out.append("\u{08}")
case UInt32(asciiLowerF): // \f
out.append("\u{0c}")
case UInt32(asciiLowerN): // \n
out.append("\u{0a}")
case UInt32(asciiLowerR): // \r
out.append("\u{0d}")
case UInt32(asciiLowerT): // \t
out.append("\u{09}")
case UInt32(asciiDoubleQuote), UInt32(asciiBackslash),
UInt32(asciiForwardSlash): // " \ /
out.append(escaped)
default:
return nil // Unrecognized escape
}
} else {
return nil // Input ends with backslash
}
default:
out.append(c)
}
}
return String(out)
}
///
/// The basic scanner support is entirely private
///
/// For performance, it works directly against UTF-8 bytes in memory.
///
internal struct JSONScanner {
private let source: UnsafeRawBufferPointer
private var index: UnsafeRawBufferPointer.Index
private var numberParser = DoubleParser()
internal let options: JSONDecodingOptions
internal let extensions: ExtensionMap
internal var recursionBudget: Int
/// True if the scanner has read all of the data from the source, with the
/// exception of any trailing whitespace (which is consumed by reading this
/// property).
internal var complete: Bool {
mutating get {
skipWhitespace()
return !hasMoreContent
}
}
/// True if the scanner has not yet reached the end of the source.
private var hasMoreContent: Bool {
return index != source.endIndex
}
/// The byte (UTF-8 code unit) at the scanner's current position.
private var currentByte: UInt8 {
return source[index]
}
internal init(
source: UnsafeRawBufferPointer,
options: JSONDecodingOptions,
extensions: ExtensionMap?
) {
self.source = source
self.index = source.startIndex
self.recursionBudget = options.messageDepthLimit
self.options = options
self.extensions = extensions ?? SimpleExtensionMap()
}
internal mutating func incrementRecursionDepth() throws {
recursionBudget -= 1
if recursionBudget < 0 {
throw JSONDecodingError.messageDepthLimit
}
}
internal mutating func decrementRecursionDepth() {
recursionBudget += 1
// This should never happen, if it does, something is probably corrupting memory, and
// simply throwing doesn't make much sense.
if recursionBudget > options.messageDepthLimit {
fatalError("Somehow JSONDecoding unwound more objects than it started")
}
}
/// Advances the scanner to the next position in the source.
private mutating func advance() {
source.formIndex(after: &index)
}
/// Skip whitespace
private mutating func skipWhitespace() {
while hasMoreContent {
let u = currentByte
switch u {
case asciiSpace, asciiTab, asciiNewLine, asciiCarriageReturn:
advance()
default:
return
}
}
}
/// Returns (but does not consume) the next non-whitespace
/// character. This is used by google.protobuf.Value, for
/// example, for custom JSON parsing.
internal mutating func peekOneCharacter() throws -> Character {
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
return Character(UnicodeScalar(UInt32(currentByte))!)
}
// Parse the leading UInt64 from the provided utf8 bytes.
//
// This is called in three different situations:
//
// * Unquoted number.
//
// * Simple quoted number. If a number is quoted but has no
// backslashes, the caller can use this directly on the UTF8 by
// just verifying the quote marks. This code returns `nil` if it
// sees a backslash, in which case the caller will need to handle ...
//
// * Complex quoted number. In this case, the caller must parse the
// quoted value as a string, then convert the string to utf8 and
// use this to parse the result. This is slow but fortunately
// rare.
//
// In the common case where the number is written in integer form,
// this code does a simple straight conversion. If the number is in
// floating-point format, this uses a slower and less accurate
// approach: it identifies a substring comprising a float, and then
// uses Double() and UInt64() to convert that string to an unsigned
// integer. In particular, it cannot preserve full 64-bit integer
// values when they are written in floating-point format.
//
// If it encounters a "\" backslash character, it returns a nil. This
// is used by callers that are parsing quoted numbers. See nextSInt()
// and nextUInt() below.
private func parseBareUInt64(
source: UnsafeRawBufferPointer,
index: inout UnsafeRawBufferPointer.Index,
end: UnsafeRawBufferPointer.Index
) throws -> UInt64? {
if index == end {
throw JSONDecodingError.truncated
}
let start = index
let c = source[index]
switch c {
case asciiZero: // 0
source.formIndex(after: &index)
if index != end {
let after = source[index]
switch after {
case asciiZero...asciiNine: // 0...9
// leading '0' forbidden unless it is the only digit
throw JSONDecodingError.leadingZero
case asciiPeriod, asciiLowerE, asciiUpperE: // . e
// Slow path: JSON numbers can be written in floating-point notation
index = start
if let d = try parseBareDouble(source: source,
index: &index,
end: end) {
if let u = UInt64(exactly: d) {
return u
}
}
throw JSONDecodingError.malformedNumber
case asciiBackslash:
return nil
default:
return 0
}
}
return 0
case asciiOne...asciiNine: // 1...9
var n = 0 as UInt64
while index != end {
let digit = source[index]
switch digit {
case asciiZero...asciiNine: // 0...9
let val = UInt64(digit - asciiZero)
if n > UInt64.max / 10 || n * 10 > UInt64.max - val {
throw JSONDecodingError.numberRange
}
source.formIndex(after: &index)
n = n * 10 + val
case asciiPeriod, asciiLowerE, asciiUpperE: // . e
// Slow path: JSON allows floating-point notation for integers
index = start
if let d = try parseBareDouble(source: source,
index: &index,
end: end) {
if let u = UInt64(exactly: d) {
return u
}
}
throw JSONDecodingError.malformedNumber
case asciiBackslash:
return nil
default:
return n
}
}
return n
case asciiBackslash:
return nil
default:
throw JSONDecodingError.malformedNumber
}
}
// Parse the leading Int64 from the provided utf8.
//
// This uses parseBareUInt64() to do the heavy lifting;
// we just check for a leading minus and negate the result
// as necessary.
//
// As with parseBareUInt64(), if it encounters a "\" backslash
// character, it returns a nil. This allows callers to use this to
// do a "fast-path" decode of simple quoted numbers by parsing the
// UTF8 directly, only falling back to a full String decode when
// absolutely necessary.
private func parseBareSInt64(
source: UnsafeRawBufferPointer,
index: inout UnsafeRawBufferPointer.Index,
end: UnsafeRawBufferPointer.Index
) throws -> Int64? {
if index == end {
throw JSONDecodingError.truncated
}
let c = source[index]
if c == asciiMinus { // -
source.formIndex(after: &index)
if index == end {
throw JSONDecodingError.truncated
}
// character after '-' must be digit
let digit = source[index]
if digit < asciiZero || digit > asciiNine {
throw JSONDecodingError.malformedNumber
}
if let n = try parseBareUInt64(source: source, index: &index, end: end) {
let limit: UInt64 = 0x8000000000000000 // -Int64.min
if n >= limit {
if n > limit {
// Too large negative number
throw JSONDecodingError.numberRange
} else {
return Int64.min // Special case for Int64.min
}
}
return -Int64(bitPattern: n)
} else {
return nil
}
} else if let n = try parseBareUInt64(source: source, index: &index, end: end) {
if n > UInt64(bitPattern: Int64.max) {
throw JSONDecodingError.numberRange
}
return Int64(bitPattern: n)
} else {
return nil
}
}
// Identify a floating-point token in the upcoming UTF8 bytes.
//
// This implements the full grammar defined by the JSON RFC 7159.
// Note that Swift's string-to-number conversions are much more
// lenient, so this is necessary if we want to accurately reject
// malformed JSON numbers.
//
// This is used by nextDouble() and nextFloat() to parse double and
// floating-point values, including values that happen to be in quotes.
// It's also used by the slow path in parseBareSInt64() and parseBareUInt64()
// above to handle integer values that are written in float-point notation.
private func parseBareDouble(
source: UnsafeRawBufferPointer,
index: inout UnsafeRawBufferPointer.Index,
end: UnsafeRawBufferPointer.Index
) throws -> Double? {
// RFC 7159 defines the grammar for JSON numbers as:
// number = [ minus ] int [ frac ] [ exp ]
if index == end {
throw JSONDecodingError.truncated
}
let start = index
var c = source[index]
if c == asciiBackslash {
return nil
}
// Optional leading minus sign
if c == asciiMinus { // -
source.formIndex(after: &index)
if index == end {
index = start
throw JSONDecodingError.truncated
}
c = source[index]
if c == asciiBackslash {
return nil
}
} else if c == asciiUpperN { // Maybe NaN?
// Return nil, let the caller deal with it.
return nil
}
if c == asciiUpperI { // Maybe Infinity, Inf, -Infinity, or -Inf ?
// Return nil, let the caller deal with it.
return nil
}
// Integer part can be zero or a series of digits not starting with zero
// int = zero / (digit1-9 *DIGIT)
switch c {
case asciiZero:
// First digit can be zero only if not followed by a digit
source.formIndex(after: &index)
if index == end {
return 0.0
}
c = source[index]
if c == asciiBackslash {
return nil
}
if c >= asciiZero && c <= asciiNine {
throw JSONDecodingError.leadingZero
}
case asciiOne...asciiNine:
while c >= asciiZero && c <= asciiNine {
source.formIndex(after: &index)
if index == end {
if let d = numberParser.utf8ToDouble(bytes: source, start: start, end: index) {
return d
} else {
throw JSONDecodingError.invalidUTF8
}
}
c = source[index]
if c == asciiBackslash {
return nil
}
}
default:
// Integer part cannot be empty
throw JSONDecodingError.malformedNumber
}
// frac = decimal-point 1*DIGIT
if c == asciiPeriod {
source.formIndex(after: &index)
if index == end {
// decimal point must have a following digit
throw JSONDecodingError.truncated
}
c = source[index]
switch c {
case asciiZero...asciiNine: // 0...9
while c >= asciiZero && c <= asciiNine {
source.formIndex(after: &index)
if index == end {
if let d = numberParser.utf8ToDouble(bytes: source, start: start, end: index) {
return d
} else {
throw JSONDecodingError.invalidUTF8
}
}
c = source[index]
if c == asciiBackslash {
return nil
}
}
case asciiBackslash:
return nil
default:
// decimal point must be followed by at least one digit
throw JSONDecodingError.malformedNumber
}
}
// exp = e [ minus / plus ] 1*DIGIT
if c == asciiLowerE || c == asciiUpperE {
source.formIndex(after: &index)
if index == end {
// "e" must be followed by +,-, or digit
throw JSONDecodingError.truncated
}
c = source[index]
if c == asciiBackslash {
return nil
}
if c == asciiPlus || c == asciiMinus { // + -
source.formIndex(after: &index)
if index == end {
// must be at least one digit in exponent
throw JSONDecodingError.truncated
}
c = source[index]
if c == asciiBackslash {
return nil
}
}
switch c {
case asciiZero...asciiNine:
while c >= asciiZero && c <= asciiNine {
source.formIndex(after: &index)
if index == end {
if let d = numberParser.utf8ToDouble(bytes: source, start: start, end: index) {
return d
} else {
throw JSONDecodingError.invalidUTF8
}
}
c = source[index]
if c == asciiBackslash {
return nil
}
}
default:
// must be at least one digit in exponent
throw JSONDecodingError.malformedNumber
}
}
if let d = numberParser.utf8ToDouble(bytes: source, start: start, end: index) {
return d
} else {
throw JSONDecodingError.invalidUTF8
}
}
/// Returns a fully-parsed string with all backslash escapes
/// correctly processed, or nil if next token is not a string.
///
/// Assumes the leading quote has been verified (but not consumed)
private mutating func parseOptionalQuotedString() -> String? {
// Caller has already asserted that currentByte == quote here
var sawBackslash = false
advance()
let start = index
while hasMoreContent {
switch currentByte {
case asciiDoubleQuote: // "
let s = utf8ToString(bytes: source, start: start, end: index)
advance()
if let t = s {
if sawBackslash {
return decodeString(t)
} else {
return t
}
} else {
return nil // Invalid UTF8
}
case asciiBackslash: // \
advance()
guard hasMoreContent else {
return nil // Unterminated escape
}
sawBackslash = true
default:
break
}
advance()
}
return nil // Unterminated quoted string
}
/// Parse an unsigned integer, whether or not its quoted.
/// This also handles cases such as quoted numbers that have
/// backslash escapes in them.
///
/// This supports the full range of UInt64 (whether quoted or not)
/// unless the number is written in floating-point format. In that
/// case, we decode it with only Double precision.
internal mutating func nextUInt() throws -> UInt64 {
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
let c = currentByte
if c == asciiDoubleQuote {
let start = index
advance()
if let u = try parseBareUInt64(source: source,
index: &index,
end: source.endIndex) {
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
if currentByte != asciiDoubleQuote {
throw JSONDecodingError.malformedNumber
}
advance()
return u
} else {
// Couldn't parse because it had a "\" in the string,
// so parse out the quoted string and then reparse
// the result to get a UInt
index = start
let s = try nextQuotedString()
let raw = s.data(using: String.Encoding.utf8)!
let n = try raw.withUnsafeBytes {
(body: UnsafeRawBufferPointer) -> UInt64? in
if body.count > 0 {
var index = body.startIndex
let end = body.endIndex
if let u = try parseBareUInt64(source: body,
index: &index,
end: end) {
if index == end {
return u
}
}
}
return nil
}
if let n = n {
return n
}
}
} else if let u = try parseBareUInt64(source: source,
index: &index,
end: source.endIndex) {
return u
}
throw JSONDecodingError.malformedNumber
}
/// Parse a signed integer, quoted or not, including handling
/// backslash escapes for quoted values.
///
/// This supports the full range of Int64 (whether quoted or not)
/// unless the number is written in floating-point format. In that
/// case, we decode it with only Double precision.
internal mutating func nextSInt() throws -> Int64 {
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
let c = currentByte
if c == asciiDoubleQuote {
let start = index
advance()
if let s = try parseBareSInt64(source: source,
index: &index,
end: source.endIndex) {
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
if currentByte != asciiDoubleQuote {
throw JSONDecodingError.malformedNumber
}
advance()
return s
} else {
// Couldn't parse because it had a "\" in the string,
// so parse out the quoted string and then reparse
// the result as an SInt
index = start
let s = try nextQuotedString()
let raw = s.data(using: String.Encoding.utf8)!
let n = try raw.withUnsafeBytes {
(body: UnsafeRawBufferPointer) -> Int64? in
if body.count > 0 {
var index = body.startIndex
let end = body.endIndex
if let s = try parseBareSInt64(source: body,
index: &index,
end: end) {
if index == end {
return s
}
}
}
return nil
}
if let n = n {
return n
}
}
} else if let s = try parseBareSInt64(source: source,
index: &index,
end: source.endIndex) {
return s
}
throw JSONDecodingError.malformedNumber
}
/// Parse the next Float value, regardless of whether it
/// is quoted, including handling backslash escapes for
/// quoted strings.
internal mutating func nextFloat() throws -> Float {
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
let c = currentByte
if c == asciiDoubleQuote { // "
let start = index
advance()
if let d = try parseBareDouble(source: source,
index: &index,
end: source.endIndex) {
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
if currentByte != asciiDoubleQuote {
throw JSONDecodingError.malformedNumber
}
advance()
return Float(d)
} else {
// Slow Path: parseBareDouble returned nil: It might be
// a valid float, but had something that
// parseBareDouble cannot directly handle. So we reset,
// try a full string parse, then examine the result:
index = start
let s = try nextQuotedString()
switch s {
case "NaN": return Float.nan
case "Inf": return Float.infinity
case "-Inf": return -Float.infinity
case "Infinity": return Float.infinity
case "-Infinity": return -Float.infinity
default:
let raw = s.data(using: String.Encoding.utf8)!
let n = try raw.withUnsafeBytes {
(body: UnsafeRawBufferPointer) -> Float? in
if body.count > 0 {
var index = body.startIndex
let end = body.endIndex
if let d = try parseBareDouble(source: body,
index: &index,
end: end) {
let f = Float(d)
if index == end && f.isFinite {
return f
}
}
}
return nil
}
if let n = n {
return n
}
}
}
} else {
if let d = try parseBareDouble(source: source,
index: &index,
end: source.endIndex) {
let f = Float(d)
if f.isFinite {
return f
}
}
}
throw JSONDecodingError.malformedNumber
}
/// Parse the next Double value, regardless of whether it
/// is quoted, including handling backslash escapes for
/// quoted strings.
internal mutating func nextDouble() throws -> Double {
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
let c = currentByte
if c == asciiDoubleQuote { // "
let start = index
advance()
if let d = try parseBareDouble(source: source,
index: &index,
end: source.endIndex) {
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
if currentByte != asciiDoubleQuote {
throw JSONDecodingError.malformedNumber
}
advance()
return d
} else {
// Slow Path: parseBareDouble returned nil: It might be
// a valid float, but had something that
// parseBareDouble cannot directly handle. So we reset,
// try a full string parse, then examine the result:
index = start
let s = try nextQuotedString()
switch s {
case "NaN": return Double.nan
case "Inf": return Double.infinity
case "-Inf": return -Double.infinity
case "Infinity": return Double.infinity
case "-Infinity": return -Double.infinity
default:
let raw = s.data(using: String.Encoding.utf8)!
let n = try raw.withUnsafeBytes {
(body: UnsafeRawBufferPointer) -> Double? in
if body.count > 0 {
var index = body.startIndex
let end = body.endIndex
if let d = try parseBareDouble(source: body,
index: &index,
end: end) {
if index == end {
return d
}
}
}
return nil
}
if let n = n {
return n
}
}
}
} else {
if let d = try parseBareDouble(source: source,
index: &index,
end: source.endIndex) {
return d
}
}
throw JSONDecodingError.malformedNumber
}
/// Return the contents of the following quoted string,
/// or throw an error if the next token is not a string.
internal mutating func nextQuotedString() throws -> String {
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
let c = currentByte
if c != asciiDoubleQuote {
throw JSONDecodingError.malformedString
}
if let s = parseOptionalQuotedString() {
return s
} else {
throw JSONDecodingError.malformedString
}
}
/// Return the contents of the following quoted string,
/// or nil if the next token is not a string.
/// This will only throw an error if the next token starts
/// out as a string but is malformed in some way.
internal mutating func nextOptionalQuotedString() throws -> String? {
skipWhitespace()
guard hasMoreContent else {
return nil
}
let c = currentByte
if c != asciiDoubleQuote {
return nil
}
return try nextQuotedString()
}
/// Return a Data with the decoded contents of the
/// following base-64 string.
///
/// Notes on Google's implementation:
/// * Google's C++ implementation accepts arbitrary whitespace
/// mixed in with the base-64 characters
/// * Google's C++ implementation ignores missing '=' characters
/// but if present, there must be the exact correct number of them.
/// * Google's C++ implementation accepts both "regular" and
/// "web-safe" base-64 variants (it seems to prefer the
/// web-safe version as defined in RFC 4648
internal mutating func nextBytesValue() throws -> Data {
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
return try parseBytes(source: source, index: &index, end: source.endIndex)
}
/// Private function to help parse keywords.
private mutating func skipOptionalKeyword(bytes: [UInt8]) -> Bool {
let start = index
for b in bytes {
guard hasMoreContent else {
index = start
return false
}
let c = currentByte
if c != b {
index = start
return false
}
advance()
}
if hasMoreContent {
let c = currentByte
if (c >= asciiUpperA && c <= asciiUpperZ) ||
(c >= asciiLowerA && c <= asciiLowerZ) {
index = start
return false
}
}
return true
}
/// If the next token is the identifier "null", consume it and return true.
internal mutating func skipOptionalNull() -> Bool {
skipWhitespace()
if hasMoreContent && currentByte == asciiLowerN {
return skipOptionalKeyword(bytes: [
asciiLowerN, asciiLowerU, asciiLowerL, asciiLowerL
])
}
return false
}
/// Return the following Bool "true" or "false", including
/// full processing of quoted boolean values. (Used in map
/// keys, for instance.)
internal mutating func nextBool() throws -> Bool {
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
let c = currentByte
switch c {
case asciiLowerF: // f
if skipOptionalKeyword(bytes: [
asciiLowerF, asciiLowerA, asciiLowerL, asciiLowerS, asciiLowerE
]) {
return false
}
case asciiLowerT: // t
if skipOptionalKeyword(bytes: [
asciiLowerT, asciiLowerR, asciiLowerU, asciiLowerE
]) {
return true
}
default:
break
}
throw JSONDecodingError.malformedBool
}
/// Return the following Bool "true" or "false", including
/// full processing of quoted boolean values. (Used in map
/// keys, for instance.)
internal mutating func nextQuotedBool() throws -> Bool {
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
if currentByte != asciiDoubleQuote {
throw JSONDecodingError.unquotedMapKey
}
if let s = parseOptionalQuotedString() {
switch s {
case "false": return false
case "true": return true
default: break
}
}
throw JSONDecodingError.malformedBool
}
/// Returns pointer/count spanning the UTF8 bytes of the next regular
/// key or nil if the key contains a backslash (and therefore requires
/// the full string-parsing logic to properly parse).
private mutating func nextOptionalKey() throws -> UnsafeRawBufferPointer? {
skipWhitespace()
let stringStart = index
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
if currentByte != asciiDoubleQuote {
return nil
}
advance()
let nameStart = index
while hasMoreContent && currentByte != asciiDoubleQuote {
if currentByte == asciiBackslash {
index = stringStart // Reset to open quote
return nil
}
advance()
}
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
let buff = UnsafeRawBufferPointer(
start: source.baseAddress! + nameStart,
count: index - nameStart)
advance()
return buff
}
/// Parse a field name, look it up in the provided field name map,
/// and return the corresponding field number.
///
/// Throws if field name cannot be parsed.
/// If it encounters an unknown field name, it throws
/// unless `options.ignoreUnknownFields` is set, in which case
/// it silently skips it.
internal mutating func nextFieldNumber(
names: _NameMap,
messageType: Message.Type
) throws -> Int? {
while true {
var fieldName: String
if let key = try nextOptionalKey() {
// Fast path: We parsed it as UTF8 bytes...
try skipRequiredCharacter(asciiColon) // :
if let fieldNumber = names.number(forJSONName: key) {
return fieldNumber
}
if let s = utf8ToString(bytes: key.baseAddress!, count: key.count) {
fieldName = s
} else {
throw JSONDecodingError.invalidUTF8
}
} else {
// Slow path: We parsed a String; lookups from String are slower.
fieldName = try nextQuotedString()
try skipRequiredCharacter(asciiColon) // :
if let fieldNumber = names.number(forJSONName: fieldName) {
return fieldNumber
}
}
if let first = fieldName.utf8.first, first == UInt8(ascii: "["),
let last = fieldName.utf8.last, last == UInt8(ascii: "]")
{
fieldName.removeFirst()
fieldName.removeLast()
if let fieldNumber = extensions.fieldNumberForProto(messageType: messageType, protoFieldName: fieldName) {
return fieldNumber
}
}
if !options.ignoreUnknownFields {
throw JSONDecodingError.unknownField(fieldName)
}
// Unknown field, skip it and try to parse the next field name
try skipValue()
if skipOptionalObjectEnd() {
return nil
}
try skipRequiredComma()
}
}
/// Parse the next token as a string or numeric enum value. Throws
/// unrecognizedEnumValue if the string/number can't initialize the
/// enum. Will throw other errors if the JSON is malformed.
internal mutating func nextEnumValue<E: Enum>() throws -> E? {
func throwOrIgnore() throws -> E? {
if options.ignoreUnknownFields {
return nil
} else {
throw JSONDecodingError.unrecognizedEnumValue
}
}
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
if currentByte == asciiDoubleQuote {
if let name = try nextOptionalKey() {
if let e = E(rawUTF8: name) {
return e
} else {
return try throwOrIgnore()
}
}
let name = try nextQuotedString()
if let e = E(name: name) {
return e
} else {
return try throwOrIgnore()
}
} else {
let n = try nextSInt()
if let i = Int(exactly: n) {
if let e = E(rawValue: i) {
return e
} else {
return try throwOrIgnore()
}
} else {
throw JSONDecodingError.numberRange
}
}
}
/// Helper for skipping a single-character token.
private mutating func skipRequiredCharacter(_ required: UInt8) throws {
skipWhitespace()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
let next = currentByte
if next == required {
advance()
return
}
throw JSONDecodingError.failure
}
/// Skip "{", throw if that's not the next character
internal mutating func skipRequiredObjectStart() throws {
try skipRequiredCharacter(asciiOpenCurlyBracket) // {
try incrementRecursionDepth()
}
/// Skip ",", throw if that's not the next character
internal mutating func skipRequiredComma() throws {
try skipRequiredCharacter(asciiComma)
}
/// Skip ":", throw if that's not the next character
internal mutating func skipRequiredColon() throws {
try skipRequiredCharacter(asciiColon)
}
/// Skip "[", throw if that's not the next character
internal mutating func skipRequiredArrayStart() throws {
try skipRequiredCharacter(asciiOpenSquareBracket) // [
}
/// Helper for skipping optional single-character tokens
private mutating func skipOptionalCharacter(_ c: UInt8) -> Bool {
skipWhitespace()
if hasMoreContent && currentByte == c {
advance()
return true
}
return false
}
/// If the next non-whitespace character is "[", skip it
/// and return true. Otherwise, return false.
internal mutating func skipOptionalArrayStart() -> Bool {
return skipOptionalCharacter(asciiOpenSquareBracket)
}
/// If the next non-whitespace character is "]", skip it
/// and return true. Otherwise, return false.
internal mutating func skipOptionalArrayEnd() -> Bool {
return skipOptionalCharacter(asciiCloseSquareBracket) // ]
}
/// If the next non-whitespace character is "}", skip it
/// and return true. Otherwise, return false.
internal mutating func skipOptionalObjectEnd() -> Bool {
let result = skipOptionalCharacter(asciiCloseCurlyBracket) // }
if result {
decrementRecursionDepth()
}
return result
}
/// Return the next complete JSON structure as a string.
/// For example, this might return "true", or "123.456",
/// or "{\"foo\": 7, \"bar\": [8, 9]}"
///
/// Used by Any to get the upcoming JSON value as a string.
/// Note: The value might be an object or array.
internal mutating func skip() throws -> String {
skipWhitespace()
let start = index
try skipValue()
if let s = utf8ToString(bytes: source, start: start, end: index) {
return s
} else {
throw JSONDecodingError.invalidUTF8
}
}
/// Advance index past the next value. This is used
/// by skip() and by unknown field handling.
/// Note: This handles objects {...} recursively but arrays [...] non-recursively
/// This avoids us requiring excessive stack space for deeply nested
/// arrays (which are not included in the recursion budget check).
private mutating func skipValue() throws {
skipWhitespace()
var totalArrayDepth = 0
while true {
var arrayDepth = 0
while skipOptionalArrayStart() {
arrayDepth += 1
}
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
switch currentByte {
case asciiDoubleQuote: // " begins a string
try skipString()
case asciiOpenCurlyBracket: // { begins an object
try skipObject()
case asciiCloseSquareBracket: // ] ends an empty array
if arrayDepth == 0 {
throw JSONDecodingError.failure
}
// We also close out [[]] or [[[]]] here
while arrayDepth > 0 && skipOptionalArrayEnd() {
arrayDepth -= 1
}
case asciiLowerN: // n must be null
if !skipOptionalKeyword(bytes: [
asciiLowerN, asciiLowerU, asciiLowerL, asciiLowerL
]) {
throw JSONDecodingError.truncated
}
case asciiLowerF: // f must be false
if !skipOptionalKeyword(bytes: [
asciiLowerF, asciiLowerA, asciiLowerL, asciiLowerS, asciiLowerE
]) {
throw JSONDecodingError.truncated
}
case asciiLowerT: // t must be true
if !skipOptionalKeyword(bytes: [
asciiLowerT, asciiLowerR, asciiLowerU, asciiLowerE
]) {
throw JSONDecodingError.truncated
}
default: // everything else is a number token
_ = try nextDouble()
}
totalArrayDepth += arrayDepth
while totalArrayDepth > 0 && skipOptionalArrayEnd() {
totalArrayDepth -= 1
}
if totalArrayDepth > 0 {
try skipRequiredComma()
} else {
return
}
}
}
/// Advance the index past the next complete {...} construct.
private mutating func skipObject() throws {
try skipRequiredObjectStart()
if skipOptionalObjectEnd() {
return
}
while true {
skipWhitespace()
try skipString()
try skipRequiredColon()
try skipValue()
if skipOptionalObjectEnd() {
return
}
try skipRequiredComma()
}
}
/// Advance the index past the next complete quoted string.
///
// Caveat: This does not fully validate; it will accept
// strings that have malformed \ escapes.
//
// It would be nice to do better, but I don't think it's critical,
// since there are many reasons that strings (and other tokens for
// that matter) may be skippable but not parseable. For example:
// Old clients that don't know new field types will skip fields
// they don't know; newer clients may reject the same input due to
// schema mismatches or other issues.
private mutating func skipString() throws {
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
if currentByte != asciiDoubleQuote {
throw JSONDecodingError.malformedString
}
advance()
while hasMoreContent {
let c = currentByte
switch c {
case asciiDoubleQuote:
advance()
return
case asciiBackslash:
advance()
guard hasMoreContent else {
throw JSONDecodingError.truncated
}
advance()
default:
advance()
}
}
throw JSONDecodingError.truncated
}
}
| 9e49a51f4da619f729abfb5e9f71b163 | 32.41386 | 114 | 0.576108 | false | false | false | false |
amezcua/actor-platform | refs/heads/master | actor-apps/app-ios/ActorApp/Controllers/Conversation/ConversationViewController.swift | mit | 2 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
import UIKit
import MobileCoreServices
class ConversationViewController: ConversationBaseViewController {
// MARK: -
// MARK: Private vars
private let BubbleTextIdentifier = "BubbleTextIdentifier"
private let BubbleMediaIdentifier = "BubbleMediaIdentifier"
private let BubbleDocumentIdentifier = "BubbleDocumentIdentifier"
private let BubbleServiceIdentifier = "BubbleServiceIdentifier"
private let BubbleBannerIdentifier = "BubbleBannerIdentifier"
private let binder: Binder = Binder();
private let titleView: UILabel = UILabel()
private let subtitleView: UILabel = UILabel()
private let navigationView: UIView = UIView()
private let avatarView = BarAvatarView(frameSize: 36, type: .Rounded)
private let backgroundView: UIView = UIView()
override init(peer: ACPeer) {
super.init(peer: peer);
// Messages
backgroundView.clipsToBounds = true
backgroundView.backgroundColor = UIColor(
patternImage:UIImage(named: "bg_foggy_birds")!.tintBgImage(MainAppTheme.bubbles.chatBgTint))
view.insertSubview(backgroundView, atIndex: 0)
// Text Input
self.textInputbar.backgroundColor = MainAppTheme.chat.chatField
self.textInputbar.autoHideRightButton = false;
self.textView.placeholder = NSLocalizedString("ChatPlaceholder",comment: "Placeholder")
self.rightButton.setTitle(NSLocalizedString("ChatSend", comment: "Send"), forState: UIControlState.Normal)
self.rightButton.setTitleColor(MainAppTheme.chat.sendEnabled, forState: UIControlState.Normal)
self.rightButton.setTitleColor(MainAppTheme.chat.sendDisabled, forState: UIControlState.Disabled)
self.keyboardPanningEnabled = true
self.registerPrefixesForAutoCompletion(["@"])
self.textView.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
self.leftButton.setImage(UIImage(named: "conv_attach")!
.tintImage(MainAppTheme.chat.attachColor)
.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal),
forState: UIControlState.Normal)
// Navigation Title
navigationView.frame = CGRectMake(0, 0, 200, 44);
navigationView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
titleView.font = UIFont.mediumSystemFontOfSize(17)
titleView.adjustsFontSizeToFitWidth = false;
titleView.textColor = Resources.PrimaryLightText
titleView.textAlignment = NSTextAlignment.Center;
titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail;
titleView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
subtitleView.font = UIFont.systemFontOfSize(13);
subtitleView.adjustsFontSizeToFitWidth = true;
subtitleView.textColor = Resources.SecondaryLightText
subtitleView.textAlignment = NSTextAlignment.Center;
subtitleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail;
subtitleView.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
navigationView.addSubview(titleView)
navigationView.addSubview(subtitleView)
self.navigationItem.titleView = navigationView;
// Navigation Avatar
avatarView.frame = CGRectMake(0, 0, 36, 36)
let avatarTapGesture = UITapGestureRecognizer(target: self, action: "onAvatarTap");
avatarTapGesture.numberOfTapsRequired = 1
avatarTapGesture.numberOfTouchesRequired = 1
avatarView.addGestureRecognizer(avatarTapGesture)
let barItem = UIBarButtonItem(customView: avatarView)
self.navigationItem.rightBarButtonItem = barItem
}
required init(coder aDecoder: NSCoder!) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
textView.text = Actor.loadDraftWithPeer(peer)
// Installing bindings
if (UInt(peer.getPeerType().ordinal()) == ACPeerType.PRIVATE.rawValue) {
let user = Actor.getUserWithUid(peer.getPeerId())
let nameModel = user.getNameModel();
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!);
self.navigationView.sizeToFit();
})
binder.bind(user.getAvatarModel(), closure: { (value: ACAvatar?) -> () in
self.avatarView.bind(user.getNameModel().get(), id: user.getId(), avatar: value)
})
binder.bind(Actor.getTypingWithUid(peer.getPeerId())!, valueModel2: user.getPresenceModel()!, closure:{ (typing:JavaLangBoolean?, presence:ACUserPresence?) -> () in
if (typing != nil && typing!.booleanValue()) {
self.subtitleView.text = Actor.getFormatter().formatTyping();
self.subtitleView.textColor = Resources.PrimaryLightText
} else {
let stateText = Actor.getFormatter().formatPresence(presence, withSex: user.getSex())
self.subtitleView.text = stateText;
let state = UInt(presence!.getState().ordinal())
if (state == ACUserPresence_State.ONLINE.rawValue) {
self.subtitleView.textColor = Resources.PrimaryLightText
} else {
self.subtitleView.textColor = Resources.SecondaryLightText
}
}
})
} else if (UInt(peer.getPeerType().ordinal()) == ACPeerType.GROUP.rawValue) {
let group = Actor.getGroupWithGid(peer.getPeerId())
let nameModel = group.getNameModel()
binder.bind(nameModel, closure: { (value: NSString?) -> () in
self.titleView.text = String(value!);
self.navigationView.sizeToFit();
})
binder.bind(group.getAvatarModel(), closure: { (value: ACAvatar?) -> () in
self.avatarView.bind(group.getNameModel().get(), id: group.getId(), avatar: value)
})
binder.bind(Actor.getGroupTypingWithGid(group.getId())!, valueModel2: group.getMembersModel(), valueModel3: group.getPresenceModel(), closure: { (typingValue:IOSIntArray?, members:JavaUtilHashSet?, onlineCount:JavaLangInteger?) -> () in
// if (!group.isMemberModel().get().booleanValue()) {
// self.subtitleView.text = NSLocalizedString("ChatNoGroupAccess", comment: "You is not member")
// self.textInputbar.hidden = true
// return
// } else {
// self.textInputbar.hidden = false
// }
if (typingValue != nil && typingValue!.length() > 0) {
self.subtitleView.textColor = Resources.PrimaryLightText
if (typingValue!.length() == 1) {
let uid = typingValue!.intAtIndex(0);
let user = Actor.getUserWithUid(uid)
self.subtitleView.text = Actor.getFormatter().formatTypingWithName(user.getNameModel().get())
} else {
self.subtitleView.text = Actor.getFormatter().formatTypingWithCount(typingValue!.length());
}
} else {
var membersString = Actor.getFormatter().formatGroupMembers(members!.size())
if (onlineCount == nil || onlineCount!.integerValue == 0) {
self.subtitleView.textColor = Resources.SecondaryLightText
self.subtitleView.text = membersString;
} else {
membersString = membersString + ", ";
let onlineString = Actor.getFormatter().formatGroupOnline(onlineCount!.intValue());
let attributedString = NSMutableAttributedString(string: (membersString + onlineString))
attributedString.addAttribute(NSForegroundColorAttributeName, value: Resources.PrimaryLightText, range: NSMakeRange(membersString.length, onlineString.length))
self.subtitleView.attributedText = attributedString
}
}
})
}
Actor.onConversationOpenWithPeer(peer)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
backgroundView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)
titleView.frame = CGRectMake(0, 4, (navigationView.frame.width - 0), 20)
subtitleView.frame = CGRectMake(0, 22, (navigationView.frame.width - 0), 20)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem = UIBarButtonItem(title: nil, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
Actor.onConversationClosedWithPeer(peer)
(UIApplication.sharedApplication().delegate as! AppDelegate).hideBadge()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
(UIApplication.sharedApplication().delegate as! AppDelegate).showBadge()
if navigationController!.viewControllers.count > 2 {
let firstController = navigationController!.viewControllers[0]
let currentController = navigationController!.viewControllers[navigationController!.viewControllers.count - 1]
navigationController!.setViewControllers([firstController, currentController], animated: false)
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated);
Actor.saveDraftWithPeer(peer, withDraft: textView.text);
}
// MARK: -
// MARK: Methods
func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.Began {
let point = gesture.locationInView(self.collectionView)
let indexPath = self.collectionView.indexPathForItemAtPoint(point)
if indexPath != nil {
if let cell = collectionView.cellForItemAtIndexPath(indexPath!) as? AABubbleCell {
if cell.bubble.superview != nil {
var bubbleFrame = cell.bubble.frame
bubbleFrame = collectionView.convertRect(bubbleFrame, fromView: cell.bubble.superview)
if CGRectContainsPoint(bubbleFrame, point) {
// cell.becomeFirstResponder()
let menuController = UIMenuController.sharedMenuController()
menuController.setTargetRect(bubbleFrame, inView:collectionView)
menuController.menuItems = [UIMenuItem(title: "Copy", action: "copy")]
menuController.setMenuVisible(true, animated: true)
}
}
}
}
}
}
func onAvatarTap() {
let id = Int(peer.getPeerId())
var controller: AAViewController
if (UInt(peer.getPeerType().ordinal()) == ACPeerType.PRIVATE.rawValue) {
controller = UserViewController(uid: id)
} else if (UInt(peer.getPeerType().ordinal()) == ACPeerType.GROUP.rawValue) {
controller = GroupViewController(gid: id)
} else {
return
}
if (isIPad) {
let navigation = AANavigationController()
navigation.viewControllers = [controller]
let popover = UIPopoverController(contentViewController: navigation)
controller.popover = popover
popover.presentPopoverFromBarButtonItem(navigationItem.rightBarButtonItem!,
permittedArrowDirections: UIPopoverArrowDirection.Up,
animated: true)
} else {
navigateNext(controller, removeCurrent: false)
}
}
override func textWillUpdate() {
super.textWillUpdate();
Actor.onTypingWithPeer(peer);
}
override func didPressRightButton(sender: AnyObject!) {
Actor.trackTextSendWithPeer(peer)
Actor.sendMessageWithMentionsDetect(peer, withText: textView.text)
super.didPressRightButton(sender)
}
override func didPressLeftButton(sender: AnyObject!) {
super.didPressLeftButton(sender)
let hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
let buttons = hasCamera ? ["PhotoCamera", "PhotoLibrary", "SendDocument"] : ["PhotoLibrary", "SendDocument"]
let tapBlock = { (index: Int) -> () in
if index == 0 || (hasCamera && index == 1) {
let pickerController = AAImagePickerController()
pickerController.sourceType = (hasCamera && index == 0) ?
UIImagePickerControllerSourceType.Camera : UIImagePickerControllerSourceType.PhotoLibrary
pickerController.mediaTypes = [kUTTypeImage as String]
pickerController.view.backgroundColor = MainAppTheme.list.bgColor
pickerController.navigationBar.tintColor = MainAppTheme.navigation.barColor
pickerController.delegate = self
pickerController.navigationBar.tintColor = MainAppTheme.navigation.titleColor
pickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: MainAppTheme.navigation.titleColor]
self.presentViewController(pickerController, animated: true, completion: nil)
} else if index >= 0 {
if #available(iOS 8.0, *) {
let documentPicker = UIDocumentMenuViewController(documentTypes: UTTAll as! [String], inMode: UIDocumentPickerMode.Import)
documentPicker.view.backgroundColor = UIColor.clearColor()
documentPicker.delegate = self
self.presentViewController(documentPicker, animated: true, completion: nil)
} else {
// Fallback on earlier versions
}
}
}
if !isIPad {
// For iPhone fast action sheet
showActionSheetFast(buttons, cancelButton: "AlertCancel", tapClosure: tapBlock)
} else {
// For iPad use old action sheet
showActionSheet(buttons, cancelButton: "AlertCancel", destructButton: nil, sourceView: self.leftButton, sourceRect: self.leftButton.bounds, tapClosure: tapBlock)
}
}
override func needFullReload(item: AnyObject?, cell: UICollectionViewCell) -> Bool {
let message = (item as! ACMessage);
if cell is AABubbleTextCell {
if (message.content is ACPhotoContent) {
return true
}
}
return false
}
// Completition
var filteredMembers = [ACMentionFilterResult]()
override func canShowAutoCompletion() -> Bool {
if UInt(self.peer.getPeerType().ordinal()) == ACPeerType.GROUP.rawValue {
if self.foundPrefix == "@" {
let oldCount = filteredMembers.count
filteredMembers.removeAll(keepCapacity: true)
let res = Actor.findMentionsWithGid(self.peer.getPeerId(), withQuery: self.foundWord)
for index in 0..<res.size() {
filteredMembers.append(res.getWithInt(index) as! ACMentionFilterResult)
}
if oldCount == filteredMembers.count {
self.autoCompletionView.reloadData()
}
return filteredMembers.count > 0
}
return false
}
return false
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredMembers.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let res = AutoCompleteCell(style: UITableViewCellStyle.Default, reuseIdentifier: "user_name")
res.bindData(filteredMembers[indexPath.row], highlightWord: foundWord)
return res
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let user = filteredMembers[indexPath.row]
var postfix = " "
if foundPrefixRange.location == 0 {
postfix = ": "
}
acceptAutoCompletionWithString(user.getMentionString() + postfix, keepPrefix: !user.isNickname())
}
override func heightForAutoCompletionView() -> CGFloat {
let cellHeight: CGFloat = 44.0;
return cellHeight * CGFloat(filteredMembers.count)
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath)
{
// Remove separator inset
if cell.respondsToSelector("setSeparatorInset:") {
cell.separatorInset = UIEdgeInsetsZero
}
// Prevent the cell from inheriting the Table View's margin settings
if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:") {
if #available(iOS 8.0, *) {
cell.preservesSuperviewLayoutMargins = false
} else {
// Fallback on earlier versions
}
}
// Explictly set your cell's layout margins
if cell.respondsToSelector("setLayoutMargins:") {
if #available(iOS 8.0, *) {
cell.layoutMargins = UIEdgeInsetsZero
} else {
// Fallback on earlier versions
}
}
}
}
// MARK: -
// MARK: UIDocumentPicker Delegate
extension ConversationViewController: UIDocumentPickerDelegate {
@available(iOS 8.0, *)
func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
let path = url.path!;
let fileName = url.lastPathComponent
let range = path.rangeOfString("/tmp", options: NSStringCompareOptions(), range: nil, locale: nil)
let descriptor = path.substringFromIndex(range!.startIndex)
NSLog("Picked file: \(descriptor)")
Actor.trackDocumentSendWithPeer(peer)
Actor.sendDocumentWithPeer(peer, withName: fileName, withMime: "application/octet-stream", withDescriptor: descriptor)
}
}
// MARK: -
// MARK: UIImagePickerController Delegate
extension ConversationViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
MainAppTheme.navigation.applyStatusBar()
picker.dismissViewControllerAnimated(true, completion: nil)
Actor.trackPhotoSendWithPeer(peer)
Actor.sendUIImage(image, peer: peer)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
MainAppTheme.navigation.applyStatusBar()
picker.dismissViewControllerAnimated(true, completion: nil)
Actor.sendUIImage(info[UIImagePickerControllerOriginalImage] as! UIImage, peer: peer)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
MainAppTheme.navigation.applyStatusBar()
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
extension ConversationViewController: UIDocumentMenuDelegate {
@available(iOS 8.0, *)
func documentMenu(documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
self.presentViewController(documentPicker, animated: true, completion: nil)
}
} | 6b94088dd41cee1d831be070865bf3cc | 43.437768 | 248 | 0.628048 | false | false | false | false |
daltoniam/JSONJoy-Swift | refs/heads/master | Source/JSONJoy.swift | apache-2.0 | 1 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// JSONJoy.swift
//
// Created by Dalton Cherry on 9/17/14.
// Copyright (c) 2014 Vluxe. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
public protocol JSONBasicType {}
extension String: JSONBasicType {}
extension Int: JSONBasicType {}
extension UInt: JSONBasicType {}
extension Double: JSONBasicType {}
extension Float: JSONBasicType {}
extension NSNumber: JSONBasicType {}
extension Bool: JSONBasicType {}
public enum JSONError: Error {
case wrongType
}
open class JSONLoader {
var value: Any?
/**
Converts any raw object like a String or Data into a JSONJoy object
*/
public init(_ raw: Any, isSub: Bool = false) {
var rawObject: Any = raw
if let str = rawObject as? String, !isSub {
rawObject = str.data(using: String.Encoding.utf8)! as Any
}
if let data = rawObject as? Data {
var response: Any?
do {
try response = JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
rawObject = response!
}
catch let error as NSError {
value = error
return
}
}
if let array = rawObject as? NSArray {
var collect = [JSONLoader]()
for val: Any in array {
collect.append(JSONLoader(val, isSub: true))
}
value = collect as Any?
} else if let dict = rawObject as? NSDictionary {
var collect = Dictionary<String,JSONLoader>()
for (key,val) in dict {
collect[key as! String] = JSONLoader(val as AnyObject, isSub: true)
}
value = collect as Any?
} else {
value = rawObject
}
}
/**
get typed `Array` of `JSONJoy` and have it throw if it doesn't work
*/
public func get<T: JSONJoy>() throws -> [T] {
guard let a = getOptionalArray() else { throw JSONError.wrongType }
return try a.reduce([T]()) { $0 + [try T($1)] }
}
/**
get typed `Array` and have it throw if it doesn't work
*/
open func get<T: JSONBasicType>() throws -> [T] {
guard let a = getOptionalArray() else { throw JSONError.wrongType }
return try a.reduce([T]()) { $0 + [try $1.get()] }
}
/**
get any type and have it throw if it doesn't work
*/
open func get<T>() throws -> T {
if let val = value as? Error {
throw val
}
guard let val = value as? T else {throw JSONError.wrongType}
return val
}
/**
get any type as an optional
*/
open func getOptional<T>() -> T? {
do { return try get() }
catch { return nil }
}
/**
get an array
*/
open func getOptionalArray() -> [JSONLoader]? {
return value as? [JSONLoader]
}
/**
get typed `Array` of `JSONJoy` as an optional
*/
public func getOptional<T: JSONJoy>() -> [T]? {
guard let a = getOptionalArray() else { return nil }
do { return try a.reduce([T]()) { $0 + [try T($1)] } }
catch { return nil }
}
/**
get typed `Array` of `JSONJoy` as an optional
*/
public func getOptional<T: JSONBasicType>() -> [T]? {
guard let a = getOptionalArray() else { return nil }
do { return try a.reduce([T]()) { $0 + [try $1.get()] } }
catch { return nil }
}
/**
Array access support
*/
open subscript(index: Int) -> JSONLoader {
get {
if let array = value as? NSArray {
if array.count > index {
return array[index] as! JSONLoader
}
}
return JSONLoader(createError("index: \(index) is greater than array or this is not an Array type."))
}
}
/**
Dictionary access support
*/
open subscript(key: String) -> JSONLoader {
get {
if let dict = value as? NSDictionary {
if let value: Any = dict[key] {
return value as! JSONLoader
}
}
return JSONLoader(createError("key: \(key) does not exist or this is not a Dictionary type"))
}
}
/**
Simple helper method to create an error
*/
func createError(_ text: String) -> Error {
return NSError(domain: "JSONJoy", code: 1002, userInfo: [NSLocalizedDescriptionKey: text]) as Error
}
}
/**
Implement this protocol on all objects you want to use JSONJoy with
*/
public protocol JSONJoy {
init(_ decoder: JSONLoader) throws
}
extension JSONLoader: CustomStringConvertible {
public var description: String {
if let value = value {
return String(describing: value)
} else {
return String(describing: value)
}
}
}
extension JSONLoader: CustomDebugStringConvertible {
public var debugDescription: String {
if let value = value {
return String(reflecting: value)
} else {
return String(reflecting: value)
}
}
}
| 1b95adcf505da81b6202c639fac39392 | 27.898396 | 116 | 0.523131 | false | false | false | false |
mauryat/firefox-ios | refs/heads/master | Client/Frontend/Settings/SearchSettingsTableViewController.swift | mpl-2.0 | 3 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import WebImage
import Shared
protocol SearchEnginePickerDelegate: class {
func searchEnginePicker(_ searchEnginePicker: SearchEnginePicker?, didSelectSearchEngine engine: OpenSearchEngine?)
}
class SearchSettingsTableViewController: UITableViewController {
fileprivate let SectionDefault = 0
fileprivate let ItemDefaultEngine = 0
fileprivate let ItemDefaultSuggestions = 1
fileprivate let ItemAddCustomSearch = 2
fileprivate let NumberOfItemsInSectionDefault = 2
fileprivate let SectionOrder = 1
fileprivate let NumberOfSections = 2
fileprivate let IconSize = CGSize(width: OpenSearchEngine.PreferredIconSize, height: OpenSearchEngine.PreferredIconSize)
fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier"
fileprivate var showDeletion = false
var profile: Profile?
var tabManager: TabManager?
fileprivate var isEditable: Bool {
// If the default engine is a custom one, make sure we have more than one since we can't edit the default.
// Otherwise, enable editing if we have at least one custom engine.
let customEngineCount = model.orderedEngines.filter({$0.isCustomEngine}).count
return model.defaultEngine.isCustomEngine ? customEngineCount > 1 : customEngineCount > 0
}
var model: SearchEngines!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Search", comment: "Navigation title for search settings.")
// To allow re-ordering the list of search engines at all times.
tableView.isEditing = true
// So that we push the default search engine controller on selection.
tableView.allowsSelectionDuringEditing = true
tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
// Insert Done button if being presented outside of the Settings Nav stack
if !(self.navigationController is SettingsNavigationController) {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: Strings.SettingsSearchDoneButton, style: .done, target: self, action: #selector(self.dismissAnimated))
}
let footer = SettingsTableSectionHeaderFooterView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 44))
footer.showBottomBorder = false
tableView.tableFooterView = footer
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
navigationItem.rightBarButtonItem = UIBarButtonItem(title: Strings.SettingsSearchEditButton, style: .plain, target: self,
action: #selector(SearchSettingsTableViewController.beginEditing))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Only show the Edit button if custom search engines are in the list.
// Otherwise, there is nothing to delete.
navigationItem.rightBarButtonItem?.isEnabled = isEditable
tableView.reloadData()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
setEditing(false, animated: false)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell!
var engine: OpenSearchEngine!
if indexPath.section == SectionDefault {
switch indexPath.item {
case ItemDefaultEngine:
engine = model.defaultEngine
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
cell.editingAccessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.accessibilityLabel = NSLocalizedString("Default Search Engine", comment: "Accessibility label for default search engine setting.")
cell.accessibilityValue = engine.shortName
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image.createScaled(IconSize)
cell.imageView?.layer.cornerRadius = 4
cell.imageView?.layer.masksToBounds = true
case ItemDefaultSuggestions:
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
cell.textLabel?.text = NSLocalizedString("Show Search Suggestions", comment: "Label for show search suggestions setting.")
let toggle = UISwitch()
toggle.onTintColor = UIConstants.ControlTintColor
toggle.addTarget(self, action: #selector(SearchSettingsTableViewController.didToggleSearchSuggestions(_:)), for: UIControlEvents.valueChanged)
toggle.isOn = model.shouldShowSearchSuggestions
cell.editingAccessoryView = toggle
cell.selectionStyle = .none
default:
// Should not happen.
break
}
} else {
// The default engine is not a quick search engine.
let index = indexPath.item + 1
if index < model.orderedEngines.count {
engine = model.orderedEngines[index]
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
cell.showsReorderControl = true
let toggle = UISwitch()
toggle.onTintColor = UIConstants.ControlTintColor
// This is an easy way to get from the toggle control to the corresponding index.
toggle.tag = index
toggle.addTarget(self, action: #selector(SearchSettingsTableViewController.didToggleEngine(_:)), for: UIControlEvents.valueChanged)
toggle.isOn = model.isEngineEnabled(engine)
cell.editingAccessoryView = toggle
cell.textLabel?.text = engine.shortName
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.minimumScaleFactor = 0.5
cell.imageView?.image = engine.image.createScaled(IconSize)
cell.imageView?.layer.cornerRadius = 4
cell.imageView?.layer.masksToBounds = true
cell.selectionStyle = .none
} else {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
cell.editingAccessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.accessibilityLabel = Strings.SettingsAddCustomEngineTitle
cell.accessibilityIdentifier = "customEngineViewButton"
cell.textLabel?.text = Strings.SettingsAddCustomEngine
}
}
// So that the seperator line goes all the way to the left edge.
cell.separatorInset = UIEdgeInsets.zero
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return NumberOfSections
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == SectionDefault {
return NumberOfItemsInSectionDefault
} else {
// The first engine -- the default engine -- is not shown in the quick search engine list.
// But the option to add Custom Engine is.
return AppConstants.MOZ_CUSTOM_SEARCH_ENGINE ? model.orderedEngines.count : model.orderedEngines.count - 1
}
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == SectionDefault && indexPath.item == ItemDefaultEngine {
let searchEnginePicker = SearchEnginePicker()
// Order alphabetically, so that picker is always consistently ordered.
// Every engine is a valid choice for the default engine, even the current default engine.
searchEnginePicker.engines = model.orderedEngines.sorted { e, f in e.shortName < f.shortName }
searchEnginePicker.delegate = self
searchEnginePicker.selectedSearchEngineName = model.defaultEngine.shortName
navigationController?.pushViewController(searchEnginePicker, animated: true)
} else if indexPath.item + 1 == model.orderedEngines.count {
let customSearchEngineForm = CustomSearchViewController()
customSearchEngineForm.profile = self.profile
navigationController?.pushViewController(customSearchEngineForm, animated: true)
}
return nil
}
// Don't show delete button on the left.
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
if indexPath.section == SectionDefault || indexPath.item + 1 == model.orderedEngines.count {
return UITableViewCellEditingStyle.none
}
let index = indexPath.item + 1
let engine = model.orderedEngines[index]
return (self.showDeletion && engine.isCustomEngine) ? .delete : .none
}
// Don't reserve space for the delete button on the left.
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
// Hide a thin vertical line that iOS renders between the accessoryView and the reordering control.
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if cell.isEditing {
for v in cell.subviews where v.frame.width == 1.0 {
v.backgroundColor = UIColor.clear
}
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView
var sectionTitle: String
if section == SectionDefault {
sectionTitle = NSLocalizedString("Default Search Engine", comment: "Title for default search engine settings section.")
} else {
sectionTitle = NSLocalizedString("Quick-Search Engines", comment: "Title for quick-search engines settings section.")
}
headerView.titleLabel.text = sectionTitle
return headerView
}
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == SectionDefault || indexPath.item + 1 == model.orderedEngines.count {
return false
} else {
return true
}
}
override func tableView(_ tableView: UITableView, moveRowAt indexPath: IndexPath, to newIndexPath: IndexPath) {
// The first engine (default engine) is not shown in the list, so the indices are off-by-1.
let index = indexPath.item + 1
let newIndex = newIndexPath.item + 1
let engine = model.orderedEngines.remove(at: index)
model.orderedEngines.insert(engine, at: newIndex)
tableView.reloadData()
}
// Snap to first or last row of the list of engines.
override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
// You can't drag or drop on the default engine.
if sourceIndexPath.section == SectionDefault || proposedDestinationIndexPath.section == SectionDefault {
return sourceIndexPath
}
//Can't drag/drop over "Add Custom Engine button"
if sourceIndexPath.item + 1 == model.orderedEngines.count || proposedDestinationIndexPath.item + 1 == model.orderedEngines.count {
return sourceIndexPath
}
if sourceIndexPath.section != proposedDestinationIndexPath.section {
var row = 0
if sourceIndexPath.section < proposedDestinationIndexPath.section {
row = tableView.numberOfRows(inSection: sourceIndexPath.section) - 1
}
return IndexPath(row: row, section: sourceIndexPath.section)
}
return proposedDestinationIndexPath
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let index = indexPath.item + 1
let engine = model.orderedEngines[index]
model.deleteCustomEngine(engine)
tableView.deleteRows(at: [indexPath], with: .right)
// End editing if we are no longer edit since we've deleted all editable cells.
if !isEditable {
finishEditing()
}
}
}
override func setEditing(_ editing: Bool, animated: Bool) {
showDeletion = editing
UIView.performWithoutAnimation {
self.navigationItem.rightBarButtonItem?.title = editing ? Strings.SettingsSearchDoneButton : Strings.SettingsSearchEditButton
}
navigationItem.rightBarButtonItem?.isEnabled = isEditable
navigationItem.rightBarButtonItem?.action = editing ?
#selector(SearchSettingsTableViewController.finishEditing) : #selector(SearchSettingsTableViewController.beginEditing)
tableView.reloadData()
}
}
// MARK: - Selectors
extension SearchSettingsTableViewController {
func didToggleEngine(_ toggle: UISwitch) {
let engine = model.orderedEngines[toggle.tag] // The tag is 1-based.
if toggle.isOn {
model.enableEngine(engine)
} else {
model.disableEngine(engine)
}
}
func didToggleSearchSuggestions(_ toggle: UISwitch) {
// Setting the value in settings dismisses any opt-in.
model.shouldShowSearchSuggestionsOptIn = false
model.shouldShowSearchSuggestions = toggle.isOn
}
func cancel() {
_ = navigationController?.popViewController(animated: true)
}
func dismissAnimated() {
self.dismiss(animated: true, completion: nil)
}
func beginEditing() {
setEditing(true, animated: false)
}
func finishEditing() {
setEditing(false, animated: false)
}
}
extension SearchSettingsTableViewController: SearchEnginePickerDelegate {
func searchEnginePicker(_ searchEnginePicker: SearchEnginePicker?, didSelectSearchEngine searchEngine: OpenSearchEngine?) {
if let engine = searchEngine {
model.defaultEngine = engine
self.tableView.reloadData()
}
_ = navigationController?.popViewController(animated: true)
}
}
| 6a9ead945a7bf5f00104a0a032de6ce4 | 45.504587 | 189 | 0.677188 | false | false | false | false |
jacobwhite/firefox-ios | refs/heads/master | Shared/UserAgent.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import AVFoundation
import UIKit
open class UserAgent {
private static var defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)!
private static func clientUserAgent(prefix: String) -> String {
return "\(prefix)/\(AppInfo.appVersion)b\(AppInfo.buildNumber) (\(DeviceInfo.deviceModel()); iPhone OS \(UIDevice.current.systemVersion)) (\(AppInfo.displayName))"
}
open static var syncUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS-Sync")
}
open static var tokenServerClientUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS-Token")
}
open static var fxaUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS-FxA")
}
open static var defaultClientUserAgent: String {
return clientUserAgent(prefix: "Firefox-iOS")
}
/**
* Use this if you know that a value must have been computed before your
* code runs, or you don't mind failure.
*/
open static func cachedUserAgent(checkiOSVersion: Bool = true,
checkFirefoxVersion: Bool = true,
checkFirefoxBuildNumber: Bool = true) -> String? {
let currentiOSVersion = UIDevice.current.systemVersion
let lastiOSVersion = defaults.string(forKey: "LastDeviceSystemVersionNumber")
let currentFirefoxBuildNumber = AppInfo.buildNumber
let currentFirefoxVersion = AppInfo.appVersion
let lastFirefoxVersion = defaults.string(forKey: "LastFirefoxVersionNumber")
let lastFirefoxBuildNumber = defaults.string(forKey: "LastFirefoxBuildNumber")
if let firefoxUA = defaults.string(forKey: "UserAgent") {
if (!checkiOSVersion || (lastiOSVersion == currentiOSVersion))
&& (!checkFirefoxVersion || (lastFirefoxVersion == currentFirefoxVersion)
&& (!checkFirefoxBuildNumber || (lastFirefoxBuildNumber == currentFirefoxBuildNumber))) {
return firefoxUA
}
}
return nil
}
/**
* This will typically return quickly, but can require creation of a UIWebView.
* As a result, it must be called on the UI thread.
*/
open static func defaultUserAgent() -> String {
assert(Thread.current.isMainThread, "This method must be called on the main thread.")
if let firefoxUA = UserAgent.cachedUserAgent(checkiOSVersion: true) {
return firefoxUA
}
let webView = UIWebView()
let appVersion = AppInfo.appVersion
let buildNumber = AppInfo.buildNumber
let currentiOSVersion = UIDevice.current.systemVersion
defaults.set(currentiOSVersion, forKey: "LastDeviceSystemVersionNumber")
defaults.set(appVersion, forKey: "LastFirefoxVersionNumber")
defaults.set(buildNumber, forKey: "LastFirefoxBuildNumber")
let userAgent = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")!
// Extract the WebKit version and use it as the Safari version.
let webKitVersionRegex = try! NSRegularExpression(pattern: "AppleWebKit/([^ ]+) ", options: [])
let match = webKitVersionRegex.firstMatch(in: userAgent, options: [],
range: NSRange(location: 0, length: userAgent.count))
if match == nil {
print("Error: Unable to determine WebKit version in UA.")
return userAgent // Fall back to Safari's.
}
let webKitVersion = (userAgent as NSString).substring(with: match!.range(at: 1))
// Insert "FxiOS/<version>" before the Mobile/ section.
let mobileRange = (userAgent as NSString).range(of: "Mobile/")
if mobileRange.location == NSNotFound {
print("Error: Unable to find Mobile section in UA.")
return userAgent // Fall back to Safari's.
}
let mutableUA = NSMutableString(string: userAgent)
mutableUA.insert("FxiOS/\(appVersion)b\(AppInfo.buildNumber) ", at: mobileRange.location)
let firefoxUA = "\(mutableUA) Safari/\(webKitVersion)"
defaults.set(firefoxUA, forKey: "UserAgent")
return firefoxUA
}
open static func desktopUserAgent() -> String {
let userAgent = NSMutableString(string: defaultUserAgent())
// Spoof platform section
let platformRegex = try! NSRegularExpression(pattern: "\\([^\\)]+\\)", options: [])
guard let platformMatch = platformRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else {
print("Error: Unable to determine platform in UA.")
return String(userAgent)
}
userAgent.replaceCharacters(in: platformMatch.range, with: "(Macintosh; Intel Mac OS X 10_11_1)")
// Strip mobile section
let mobileRegex = try! NSRegularExpression(pattern: " FxiOS/[^ ]+ Mobile/[^ ]+", options: [])
guard let mobileMatch = mobileRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else {
print("Error: Unable to find Mobile section in UA.")
return String(userAgent)
}
userAgent.replaceCharacters(in: mobileMatch.range, with: "")
return String(userAgent)
}
}
| 6bbea07fa94cedb387a401420e958b8d | 41.450382 | 171 | 0.654738 | false | false | false | false |
Harshvk/CarsGalleryApp | refs/heads/master | ListToGridApp/ListCell.swift | mit | 1 | //
// ListCell.swift
// ListToGridApp
//
// Created by appinventiv on 13/02/17.
// Copyright © 2017 appinventiv. All rights reserved.
//
import UIKit
class ListCell: UICollectionViewCell {
@IBOutlet weak var carPic: UIImageView!
@IBOutlet weak var carName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func prepareForReuse() {
self.backgroundColor = nil
}
func configureCell(withCar car: CarModel){
carPic.image = UIImage(named: car.image)
carName.text = car.name
carPic.layer.borderWidth = 1
carPic.layer.borderColor = UIColor.darkGray.cgColor
}
}
class ProductsListFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
setupLayout()
}
/**
Init method
- parameter aDecoder: aDecoder
- returns: self
*/
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayout()
}
/**
Sets up the layout for the collectionView. 0 distance between each cell, and vertical layout
*/
func setupLayout() {
minimumInteritemSpacing = 0
minimumLineSpacing = 1
scrollDirection = .vertical
}
func itemWidth() -> CGFloat {
return collectionView!.frame.width
}
override var itemSize: CGSize {
set {
self.itemSize = CGSize(width: itemWidth(), height: 89)
}
get {
return CGSize(width: itemWidth(), height: 89)
}
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return collectionView!.contentOffset
}
}
| fb96d40c6e51b62c05b9a81d1ca4eb26 | 20.104651 | 107 | 0.590634 | false | false | false | false |
fxdemolisher/newscats | refs/heads/master | ios/NewsCats/BridgeMethodWrapper.swift | apache-2.0 | 1 | import React
/**
* Defines various kind of wrapped performers we support with our BridgeMethodWrapper.
*/
enum BridgeMethodWrappedPerformer {
// A call from JS to native, without a return value or callback.
case oneWay((RCTBridge, [Any]) throws -> Void)
// A call from JS to native, providing a callback function to call on completion.
// NOTE(gennadiy): The completion callback is expected to accept two parameters: error and result, in node.js style.
case callback((RCTBridge, [Any], @escaping (Any?, Any?) -> Void) throws -> Void)
// A call from JS to native, expecting a returned promise.
case promise((RCTBridge, [Any], @escaping RCTPromiseResolveBlock, @escaping RCTPromiseRejectBlock) throws -> Void)
}
/**
* A simple wrapper around swift functions and closures that can be exposed over an RN bridge.
*/
class BridgeMethodWrapper : NSObject, RCTBridgeMethod {
private let name: String
private let performer: BridgeMethodWrappedPerformer
init(name: String, _ performer: BridgeMethodWrappedPerformer) {
self.name = name
self.performer = performer
}
public var jsMethodName: UnsafePointer<Int8>! {
return UnsafePointer<Int8>(name)
}
public var functionType: RCTFunctionType {
switch performer {
case .promise: return .promise
default: return .normal
}
}
/**
* Called by the RN bridge to invoke the native function wrapped by this instance.
*/
public func invoke(with bridge: RCTBridge!, module: Any!, arguments: [Any]!) -> Any! {
switch performer {
// One way calls are simple passthroughs, with void returns.
case let .oneWay(closure):
try! closure(bridge, arguments)
return Void()
// Callback wrappers pass all except the last parameter to the native code, and wrap the last parameter
// in a swift completion closure. The native code being executed should use that closure to communicate
// results back to JS. By convention the resulting call should contains two arguments: error and result.
case let .callback(closure):
let closureArgs = Array<Any>(arguments.prefix(upTo: arguments.count - 1))
let callbackClosure = { (error: Any?, result: Any?) -> Void in
let callbackId = arguments.last as! NSNumber
let errorActual = error ?? NSNull()
let resultActual = result ?? NSNull()
bridge.enqueueCallback(callbackId, args: [errorActual, resultActual])
}
try! closure(bridge, closureArgs, callbackClosure)
return Void()
case let .promise(closure):
let closureArgs = Array<Any>(arguments.prefix(upTo: arguments.count - 2))
let resolveBlockCallbackId = arguments[arguments.count - 2] as! NSNumber
let resolveBlock: RCTPromiseResolveBlock = { value in
bridge.enqueueCallback(resolveBlockCallbackId, args: [value ?? ""])
}
let rejectBlockCallbackId = arguments[arguments.count - 1] as! NSNumber
let rejectBlock: RCTPromiseRejectBlock = { tag, message, error in
bridge.enqueueCallback(rejectBlockCallbackId, args: [tag!, message!, error!])
}
do {
try closure(bridge, closureArgs, resolveBlock, rejectBlock)
} catch let error {
rejectBlock("bridgeError", "Failed to call bridge function", error)
}
return Void()
}
}
}
| bf156546cf9cf6674525799ffda2e274 | 42.177778 | 120 | 0.594184 | false | false | false | false |
apurushottam/IPhone-Learning-Codes | refs/heads/master | Project 7-Easy Browser/Project 7-Easy Browser/WebsitesTableViewController.swift | apache-2.0 | 1 | //
// WebsitesTableViewController.swift
// Project 7-Easy Browser
//
// Created by Ashutosh Purushottam on 9/28/15.
// Copyright © 2015 Vivid Designs. All rights reserved.
//
import UIKit
class WebsitesTableViewController: UITableViewController {
var websites = ["apple.com", "hackingwithswift.com", "youtube.com"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = .SingleLine
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return websites.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("WebsiteCell")!
cell.textLabel?.text = websites[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// present new controller here
let callingUrl = websites[indexPath.row]
let newController = storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! ViewController
newController.webUrl = callingUrl
navigationController?.pushViewController(newController, animated: true)
}
}
| e765465328bb41f04623ab2674a86212 | 29.636364 | 119 | 0.698071 | false | false | false | false |
AlexZd/SwiftUtils | refs/heads/master | Pod/Utils/UIView+Helpers/UIView+Helpers.swift | mit | 1 | //
// UIView+Helpers.swift
//
// Created by Alex Zdorovets on 6/18/15.
// Copyright (c) 2015 Alex Zdorovets. All rights reserved.
//
import UIKit
extension UIView {
public static func loadNib<T>() -> T {
return Bundle.main.loadNibNamed(self.className, owner: self, options: nil)!.first as! T
}
/** Returns UIView's class name. */
public class var className: String {
return NSStringFromClass(self.classForCoder()).components(separatedBy: ".").last!
}
/** Returns UIView's nib. */
public class var nib: UINib {
return UINib(nibName: self.className, bundle: nil)
}
/** Get value of height constraint of UIView*/
public var heightOfContstraint: CGFloat {
let cnst = constraints.filter({$0.firstAttribute == NSLayoutConstraint.Attribute.height && $0.isMember(of: NSLayoutConstraint.self)}).first!
return cnst.constant
}
/** Returns entity from it's nib. Nib should have same name as class name. */
public class func getFromNib() -> Any {
return Bundle.main.loadNibNamed(self.className, owner: self, options: nil)!.first!
}
/** Changes UIView width constraint and updates for superview */
public func setWidth(width: CGFloat, update: Bool) {
var cnst = constraints.filter({$0.firstAttribute == NSLayoutConstraint.Attribute.width && $0.isMember(of: NSLayoutConstraint.self)}).first
if cnst == nil {
if #available(iOS 9, *) {
self.widthAnchor.constraint(equalToConstant: width).isActive = true
} else {
cnst = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width)
self.addConstraint(cnst!)
}
}
cnst?.constant = width
if update {
self.updateConstraints()
}
}
/** Changes UIView height constraint and updates for superview */
public func setHeight(height: CGFloat, update: Bool) {
var cnst = constraints.filter({$0.firstAttribute == NSLayoutConstraint.Attribute.height && $0.isMember(of: NSLayoutConstraint.self)}).first
if cnst == nil {
if #available(iOS 9, *) {
self.heightAnchor.constraint(equalToConstant: height).isActive = true
} else {
cnst = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)
self.addConstraint(cnst!)
}
}
cnst?.constant = height
if update {
self.updateConstraints()
}
}
/** Adds constraints to superview */
public func setEdgeConstaints(edges: UIEdgeInsets, update: Bool) {
guard let superview = self.superview else { return }
self.translatesAutoresizingMaskIntoConstraints = false
let leading = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: superview, attribute: .leading, multiplier: 1, constant: edges.left)
let trailing = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: superview, attribute: .trailing, multiplier: 1, constant: -1 * edges.right)
let top = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: superview, attribute: .top, multiplier: 1, constant: edges.top)
let bottom = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: superview, attribute: .bottom, multiplier: 1, constant: -1 * edges.bottom)
superview.addConstraints([top, leading, trailing, bottom])
if update {
superview.updateConstraints()
}
}
/** Perform shake animation for UIView*/
public func shake() {
let animation = CAKeyframeAnimation()
animation.keyPath = "position.x"
animation.values = [0, 20, -20, 10, 0];
animation.keyTimes = [0, NSNumber(value: (1 / 6.0)), NSNumber(value: (3 / 6.0)), NSNumber(value: (5 / 6.0)), 1]
animation.duration = 0.3
animation.timingFunction = CAMediaTimingFunction(name: .easeOut)
animation.isAdditive = true
self.layer.add(animation, forKey: "shake")
}
/** Screenshot of current view */
public var screenshot: UIImage {
UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
public func addSubview(_ view: UIView, top: CGFloat?, left: CGFloat?, bottom: CGFloat?, right: CGFloat?) {
self.addSubview(view)
if let top = top {
view.topAnchor.constraint(equalTo: self.topAnchor, constant: top).isActive = true
}
if let left = left {
view.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: left).isActive = true
}
if let bottom = bottom {
view.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: bottom * -1).isActive = true
}
if let right = right {
view.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: right * -1).isActive = true
}
}
}
| f51cd5a1d24be48851e79cd8154819a2 | 43.434426 | 178 | 0.636414 | false | false | false | false |
renatogg/iOSTamagochi | refs/heads/master | Tamagochi/ViewController.swift | cc0-1.0 | 1 | //
// ViewController.swift
// Tamagochi
//
// Created by Renato Gasoto on 5/9/16.
// Copyright © 2016 Renato Gasoto. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var monsterImg: MonsterImg!
@IBOutlet weak var heartImg: DragImg!
@IBOutlet weak var foodImg: DragImg!
@IBOutlet var lifes: Array<UIView>!
var musicPlayer: AVAudioPlayer!
var sfxBite: AVAudioPlayer!
var sfxHeart: AVAudioPlayer!
var sfxDeath: AVAudioPlayer!
var sfxSkull: AVAudioPlayer!
let DIM_ALPHA: CGFloat = 0.2 //Opacity of disabled items / Lost Lifes
let OPAQUE: CGFloat = 1.0
var penalties = 0
var timer: NSTimer!
var monsterHappy = true
var currentItem: UInt32 = 0
override func viewDidLoad() {
super.viewDidLoad()
foodImg.dropTarget = monsterImg
heartImg.dropTarget = monsterImg
foodImg.alpha = DIM_ALPHA
foodImg.userInteractionEnabled = false
heartImg.alpha = DIM_ALPHA
heartImg.userInteractionEnabled = false
loadAudios()
for life in lifes{
life.alpha = DIM_ALPHA
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.itemDroppedOnCharacter(_:)), name: "onTargetDropped", object: nil)
startTimer()
}
func loadAudios(){
do{
try musicPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("cave-music", ofType: "mp3")!))
try sfxSkull = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("skull", ofType: "wav")!))
try sfxBite = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bite", ofType: "wav")!))
try sfxHeart = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("heart", ofType: "wav")!))
try sfxDeath = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("death", ofType: "wav")!))
musicPlayer.prepareToPlay()
sfxSkull.prepareToPlay()
sfxBite.prepareToPlay()
sfxHeart.prepareToPlay()
sfxDeath.prepareToPlay()
musicPlayer.play()
}catch let err as NSError{
print (err.debugDescription)
}
}
func itemDroppedOnCharacter(notif: AnyObject){
monsterHappy = true
foodImg.alpha = DIM_ALPHA
foodImg.userInteractionEnabled = false
heartImg.alpha = DIM_ALPHA
heartImg.userInteractionEnabled = false
startTimer()
if currentItem == 0{
sfxHeart.play()
}else{
sfxBite.play()
}
}
func startTimer(){
if timer != nil{
timer.invalidate()
}
timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: #selector(ViewController.changeGameState), userInfo: nil, repeats: true)
}
func changeGameState(){
if !monsterHappy
{
penalties += 1
sfxSkull.play()
for i in 0..<penalties{
lifes[i].alpha = OPAQUE
}
for i in penalties..<lifes.endIndex{
lifes[i].alpha = DIM_ALPHA
}
if penalties == lifes.endIndex{
gameOver()
}
}
if penalties < lifes.endIndex {
let rand = arc4random_uniform(2)
if rand == 0{
foodImg.alpha = DIM_ALPHA
foodImg.userInteractionEnabled = false
heartImg.alpha = OPAQUE
heartImg.userInteractionEnabled = true
}
else{
foodImg.alpha = OPAQUE
foodImg.userInteractionEnabled = true
heartImg.alpha = DIM_ALPHA
heartImg.userInteractionEnabled = false
}
currentItem = rand
monsterHappy = false
}
}
func gameOver(){
timer.invalidate()
foodImg.alpha = DIM_ALPHA
foodImg.userInteractionEnabled = false
heartImg.alpha = DIM_ALPHA
heartImg.userInteractionEnabled = false
monsterImg.playAnimation(true)
sfxDeath.play()
musicPlayer.stop()
}
}
| 619162340a2ffe1f40429b039c451cd2 | 31.119718 | 172 | 0.585836 | false | false | false | false |
steve228uk/PeachKit | refs/heads/master | ImageMessage.swift | mit | 1 | //
// ImageMessage.swift
// Peach
//
// Created by Stephen Radford on 17/01/2016.
// Copyright © 2016 Cocoon Development Ltd. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
public class ImageMessage: Message {
public required init() { }
/// Source URL of any image
public var src: String?
/// Width of any image
public var width: Int?
/// Height of any image
public var height: Int?
/**
Fetch the image related to the message
- parameter callback: Callback with NSImage
*/
public func getImage(callback: (NSImage) -> Void) {
if let url = src {
Alamofire.request(.GET, url)
.responseData { response in
if response.result.isSuccess {
if let img = NSImage(data: response.result.value!) {
callback(img)
}
}
}
}
}
/**
Fetch the image data related to the message
- parameter callback: Callback with NSImage
*/
public func getImageData(callback: (NSData) -> Void) {
if let url = src {
Alamofire.request(.GET, url)
.responseData { response in
if response.result.isSuccess {
callback(response.result.value!)
}
}
}
}
// MARK: - Message Protocol
public var type: MessageType = .Image
public static func messageFromJson(json: JSON) -> Message {
let msg = ImageMessage()
if let stringWidth = json["width"].string {
msg.width = Int(stringWidth)
} else {
msg.width = json["width"].int
}
if let stringHeight = json["height"].string {
msg.height = Int(stringHeight)
} else {
msg.height = json["height"].int
}
msg.src = json["src"].string
return msg
}
public var dictionary: [String:AnyObject] {
get {
return [
"type": type.stringValue.lowercaseString,
"width": (width != nil) ? width! : 0,
"height": (height != nil) ? height! : 0,
"src": (src != nil) ? src! : ""
]
}
}
} | ad849f35d7a3a85243641dbb4a47f1fb | 24.860215 | 76 | 0.493344 | false | false | false | false |
grpc/grpc-swift | refs/heads/main | Sources/GRPCSampleData/GRPCSwiftCertificate.swift | apache-2.0 | 1 | /*
* Copyright 2022, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//-----------------------------------------------------------------------------
// THIS FILE WAS GENERATED WITH make-sample-certs.py
//
// DO NOT UPDATE MANUALLY
//-----------------------------------------------------------------------------
#if canImport(NIOSSL)
import struct Foundation.Date
import NIOSSL
/// Wraps `NIOSSLCertificate` to provide the certificate common name and expiry date.
public struct SampleCertificate {
public var certificate: NIOSSLCertificate
public var commonName: String
public var notAfter: Date
public static let ca = SampleCertificate(
certificate: try! NIOSSLCertificate(bytes: .init(caCert.utf8), format: .pem),
commonName: "some-ca",
notAfter: Date(timeIntervalSince1970: 1699960773)
)
public static let otherCA = SampleCertificate(
certificate: try! NIOSSLCertificate(bytes: .init(otherCACert.utf8), format: .pem),
commonName: "some-other-ca",
notAfter: Date(timeIntervalSince1970: 1699960773)
)
public static let server = SampleCertificate(
certificate: try! NIOSSLCertificate(bytes: .init(serverCert.utf8), format: .pem),
commonName: "localhost",
notAfter: Date(timeIntervalSince1970: 1699960773)
)
public static let exampleServer = SampleCertificate(
certificate: try! NIOSSLCertificate(bytes: .init(exampleServerCert.utf8), format: .pem),
commonName: "example.com",
notAfter: Date(timeIntervalSince1970: 1699960773)
)
public static let serverSignedByOtherCA = SampleCertificate(
certificate: try! NIOSSLCertificate(bytes: .init(serverSignedByOtherCACert.utf8), format: .pem),
commonName: "localhost",
notAfter: Date(timeIntervalSince1970: 1699960773)
)
public static let client = SampleCertificate(
certificate: try! NIOSSLCertificate(bytes: .init(clientCert.utf8), format: .pem),
commonName: "localhost",
notAfter: Date(timeIntervalSince1970: 1699960773)
)
public static let clientSignedByOtherCA = SampleCertificate(
certificate: try! NIOSSLCertificate(bytes: .init(clientSignedByOtherCACert.utf8), format: .pem),
commonName: "localhost",
notAfter: Date(timeIntervalSince1970: 1699960773)
)
public static let exampleServerWithExplicitCurve = SampleCertificate(
certificate: try! NIOSSLCertificate(bytes: .init(serverExplicitCurveCert.utf8), format: .pem),
commonName: "localhost",
notAfter: Date(timeIntervalSince1970: 1699960773)
)
}
extension SampleCertificate {
/// Returns whether the certificate has expired.
public var isExpired: Bool {
return self.notAfter < Date()
}
}
/// Provides convenience methods to make `NIOSSLPrivateKey`s for corresponding `GRPCSwiftCertificate`s.
public struct SamplePrivateKey {
private init() {}
public static let server = try! NIOSSLPrivateKey(bytes: .init(serverKey.utf8), format: .pem)
public static let exampleServer = try! NIOSSLPrivateKey(
bytes: .init(exampleServerKey.utf8),
format: .pem
)
public static let client = try! NIOSSLPrivateKey(bytes: .init(clientKey.utf8), format: .pem)
public static let exampleServerWithExplicitCurve = try! NIOSSLPrivateKey(
bytes: .init(serverExplicitCurveKey.utf8),
format: .pem
)
}
// MARK: - Certificates and private keys
private let caCert = """
-----BEGIN CERTIFICATE-----
MIICoDCCAYgCCQCf2sGvEIOvlDANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDDAdz
b21lLWNhMB4XDTIyMTExNDExMTkzM1oXDTIzMTExNDExMTkzM1owEjEQMA4GA1UE
AwwHc29tZS1jYTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOjCRRWS
ezh/izFLT4g8lAjVUGbjckCnJRPfwgWDAC1adTDi4QhzONVlmYUzUkx6VPCcVVou
vc/WM8hHC6cRDdf/ubGRZondGw6bzaO2yqc8K6BNSvqFnkuQHRpPoSc/RKHe+qTT
glhygm3GlAUaNl0hJpXWlLqOoIb0mn8emF7afbyyWariPPQyzY2rywPLPXipitmW
Jw7GxVC+Q2yx5GQxPvutCdtkAsrS1AsYxpvpW+kHmtj0Dj40N7yhTz1cw2QtCD2i
CQuk9oRwtIiJi54USy/r6oq5NOlwqHyq+DGDt5XZx1RKvGJTn3ujHPEJVipoTkdX
/K+RpqQxJNGhyO8CAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAjKgbr1hwRMUwEYLe
AAf0ODw0iRfch9QG6qYTOFjuC3KyDKdzf52OGm49Ep4gVmgMPLcA3YGtUXd8dJSf
WYZ0pSJYeLVJiEkkV/0gwpc+vK2OxZe1XBPbW3JN+wmRBxi3MiL7bbSvDlYIj7Dv
8c1vs8SxE4VuSkFRrcrVV0V95xs01X1/M9aa8z9Lf59ecKytaLvKysorDrCN8nC3
zlMDehPCLH9y4UlBqp8ClUpKk/5/P8HXr40ZGq+5TFrR80YABPSVX7krRMcxIhfu
IFIT2yhjkxMQWj8SCDUZxamBElAXY9KHSlEv3y+teRQABBVNxslHXqLKfKTF3q4S
tUVJuA==
-----END CERTIFICATE-----
"""
private let otherCACert = """
-----BEGIN CERTIFICATE-----
MIICrDCCAZQCCQDQxWAzi9Y9LTANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDDA1z
b21lLW90aGVyLWNhMB4XDTIyMTExNDExMTkzM1oXDTIzMTExNDExMTkzM1owGDEW
MBQGA1UEAwwNc29tZS1vdGhlci1jYTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBANOr3vaYLkfnqk0lREo0VJD/rnUGQ6BiVtKiou0uksb9gX4oHdKlnqyi
dvFuwaJHIzjBhdWD2EqgWwuBTB3y/UybD/ZvkojnLD+QNMnbgG5aCnO03gVlVBOf
JggEtAEM31C7Fi6X7Gr/QwRI721+kqNSB48Rj3BT93cDW73aSeL6IZ8jlvefWYR7
1UI3bP+4WG58PSJOhUs2edaOn0G5wRZ5LyK6A77noll90cP+CVNlqLj8HRapqhf1
XZhGwwaEYxNV1oDroxq9mcM+6E8LdWCsdE3N4Dx6pdL0lOjwvhevZ2ct/fb31NYE
fMstojwKf9Of5/J4kZaC1mp44IwPS00CAwEAATANBgkqhkiG9w0BAQsFAAOCAQEA
iUuX1YYdVwqamg13eji1I9/8eMP5demBnXjM7DYP3JqDhClTYNnN8aB+o1YW51ce
3V1FtN/f3g3YMgYB4YSOb241G9uXGCz5CwcYeBCJbUT/PdNZOrTW1EzA+gAy8GxS
yMbK+ZrXy+7mJr79sumIO2WGk//eznvgrmlKq+eZtVf/TDTYs5TdbqI4sqoN+qPQ
WyuBXEkU2D259VvZ+GLljVr7JCysciALKDk3QAb6cfjhFh3aOqb40m5i4Jg6g2G6
iFS1kE3KjaWhYYn66BRVOYzfT25RkFBxxJh2Pg6DQOyVUWsWJ+VrstpQlcGMElmq
/LaIwNYfuUNcKb90L+M6vg==
-----END CERTIFICATE-----
"""
private let serverCert = """
-----BEGIN CERTIFICATE-----
MIICmjCCAYICAQEwDQYJKoZIhvcNAQELBQAwEjEQMA4GA1UEAwwHc29tZS1jYTAe
Fw0yMjExMTQxMTE5MzNaFw0yMzExMTQxMTE5MzNaMBQxEjAQBgNVBAMMCWxvY2Fs
aG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANEQLRL2oOHPHN7K
ozmP8Ks8CcndChJrunNTJAWCiMA/HFEVVfylnQpPyc/t+W2yD+d+PsJknu2hI1O5
o53SBsEDm1taHaCJt9ur5NKpEphzOI7VuwkgcoGqmY0Hz7GmBmbG06Z6ne8EZfg5
a/rjxhW3GyOmIT3s9xWiU3MW7VX0PDlVmkZzVYtcSp9+AXQMDpvLK48INu1mUC6u
1nbEzj6KuFwpU5+V1cRLHer+I9HVA7qBcgsIDDEdUDG0/l0MivAyDbNHGHDZcsfj
jwTMsGRcd+IONItHyYb72+JBEKv3/qFAe4XIeR6iJQP4OxZ4CoxeUFgkVQwqBNd+
1JYDuvECAwEAATANBgkqhkiG9w0BAQsFAAOCAQEASoyiLe/ak0nH5Bl7RvwAsO+Y
J2kA/oIUCpFEmsqDxK9Nt4eGIvknGzWsfTsVM4jXQo1MYCE7XrjpG9H6fubeQvxG
b+eU3VaHztflxLouzBIM6LnzoXnt2/rjQWIMbWZri2Gwl4incvVDLOv3jm5VD1Uw
OePLd+DvD/NzQ4nWdqCqhZAjopEPUpOT7fP8OkJVjGddvAn/0KyXkg3tutmUMB9m
8KctofAp1fKmd056Lgj+j6DIFDxxWEiihTO1ae8FlS4X/teeGSEVGv5M4baWRrcD
29V9XNIbMiwCNa7DJlPpxkjHdT4KifwPDHJ92RfK54SU1k0i8LD9KByuV4av9w==
-----END CERTIFICATE-----
"""
private let serverSignedByOtherCACert = """
-----BEGIN CERTIFICATE-----
MIICoDCCAYgCAQEwDQYJKoZIhvcNAQELBQAwGDEWMBQGA1UEAwwNc29tZS1vdGhl
ci1jYTAeFw0yMjExMTQxMTE5MzNaFw0yMzExMTQxMTE5MzNaMBQxEjAQBgNVBAMM
CWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANEQLRL2
oOHPHN7KozmP8Ks8CcndChJrunNTJAWCiMA/HFEVVfylnQpPyc/t+W2yD+d+PsJk
nu2hI1O5o53SBsEDm1taHaCJt9ur5NKpEphzOI7VuwkgcoGqmY0Hz7GmBmbG06Z6
ne8EZfg5a/rjxhW3GyOmIT3s9xWiU3MW7VX0PDlVmkZzVYtcSp9+AXQMDpvLK48I
Nu1mUC6u1nbEzj6KuFwpU5+V1cRLHer+I9HVA7qBcgsIDDEdUDG0/l0MivAyDbNH
GHDZcsfjjwTMsGRcd+IONItHyYb72+JBEKv3/qFAe4XIeR6iJQP4OxZ4CoxeUFgk
VQwqBNd+1JYDuvECAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAZN5RQsfPP09YIfYo
UGu9m5+lpzYhE0S2+szysTg2IpWug0ZK4xhnqQYd9cGRks+U6hiLPdiyHCwOykf6
OplIp5fMxPWZipREb9nA33Ra1G9vpB/tZxQJxDTvUeCH88SQOszdZk79+zWyVkaF
+TCa3jDXb/vT20+wKxpPUjse5w2j0VOh21KaP82EMyOY/ZvhbMC60QyHnFDvJAEV
sle77vbdLjYELpYUpf9N+TxFDZ2B4dY/edprLZGt3LcUUFv/WB8FxZdWcjdZML2F
TMqicbP7H27+V1HF1rFUJWKzDNh4Wg6bY6lQNTZeHUyLwf/WlUraXTKYpqSH8FQ1
703RGQ==
-----END CERTIFICATE-----
"""
private let serverKey = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA0RAtEvag4c8c3sqjOY/wqzwJyd0KEmu6c1MkBYKIwD8cURVV
/KWdCk/Jz+35bbIP534+wmSe7aEjU7mjndIGwQObW1odoIm326vk0qkSmHM4jtW7
CSBygaqZjQfPsaYGZsbTpnqd7wRl+Dlr+uPGFbcbI6YhPez3FaJTcxbtVfQ8OVWa
RnNVi1xKn34BdAwOm8srjwg27WZQLq7WdsTOPoq4XClTn5XVxEsd6v4j0dUDuoFy
CwgMMR1QMbT+XQyK8DINs0cYcNlyx+OPBMywZFx34g40i0fJhvvb4kEQq/f+oUB7
hch5HqIlA/g7FngKjF5QWCRVDCoE137UlgO68QIDAQABAoIBAEumodjh2/e6PYU1
KHl0567e69/bF4Dw8Kg4pqlDwf5nF/UTVmk0+K25j5qpT3/tVin7mfQ3+vacP69V
VqqOTJldl8Mnyd7E1v4rpoLAYZU+5HFzT9oOnsDjHetVr0dmf5yDSCVO64WJPuji
xnskHxLOjoiI3jCNZh+y/KWB32IhdofSwBccw852JM2qC5l8vgE+sfjOeWXDiPRI
YLlVRlxZFv7N2kn+EDnPEQ8m2OGYKvNzU0d9nz05NdkRXzMh9zegTTL4EQhTaMf0
2AXy2ekKFVvWouV4y8QW1shz5Tun2y4ZQJnwiCyldED9sMxaziQxfdJ6N7f4+K5c
Sh4+Ct0CgYEA7bGvY02jQfHcDPOjZ/xkXb98lr1uLGTSvwK3zw+rI0+nrUJwH6fB
nSaXyWk059OqHTKPpa/d8DxFL2LP6vbvfTWCv9mnn61WWWDmP0Eo/k93XgWkmclb
vQGfXV2wtCTnhz+iUSSJA8f8jZhCtOD6xa8pLsaYrGD6oR5wzfs0nysCgYEA4SoC
/JWDMkw4mndI2vQ8GqDzBFtJCMr/dva7YGCGtbimDzxuOI68vW/y4X8Izg2i1hVz
iKRYCI9KzRdQrQ7masZF2d4DeaqPeA72JN4hoUOw0TZjP8yD4ECifUt786ZNvV1n
NlEhNb55zD73Cl6v0OJZkEfp1MC5ZQwLw7bMYFMCgYEAvNu5Z0WAuhzZotDSvQSl
GnfTHlJU/6D8chhOw47Hg77+k4N+Yyh/hcXsRHP7PVfIinpp+FPMG91He2cfnKmn
j+y8foMJ1K19NnbvesLjN20cgvAo4KhE4+AuJ5kRlZDdBXFiHubQltiHqlmYZu97
USbjqe7Rz+UePnZZWtCF9xECgYEAjGODZTVbjdrUWAsT0+EAMKI1o3u/N8pKKkSA
ZAELPPaaI1nMZ1sn9v179HkeZks+QjkxxfqiIQQm4WUuGhj2NZDWMJcql4tu1K6P
bkFJuqDX+Dnu+/JqL0Jdjb2o1SvVwMIh/k3rZPUUP/LqWP7cpGLc8QbFlq9raMNv
+mFZYJ0CgYEA5IQzp7SymcKgQqwcq5no2YOr76AykSCjOnLYYrotFqbxGJ19Cnol
Z74Habxjv89Kc7bfIwbz/AolkhAS2y0CYwSJL4wZIUb8W2mroSmaHhsk3A4DMPBB
wgSsdiBpixQqNDUAvnHc3FIyAGdpA73TJQrGY2F6QyQ9re3a/R8Dc3k=
-----END RSA PRIVATE KEY-----
"""
private let exampleServerCert = """
-----BEGIN CERTIFICATE-----
MIICnDCCAYQCAQEwDQYJKoZIhvcNAQELBQAwEjEQMA4GA1UEAwwHc29tZS1jYTAe
Fw0yMjExMTQxMTE5MzRaFw0yMzExMTQxMTE5MzRaMBYxFDASBgNVBAMMC2V4YW1w
bGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5UPdc3MERjIj
rKNMcsCJEPJtzFZG7T99rDaENxl5hF5TdlCuMfKQMyf4rmUk2KdQXduWDmP/9keO
Btc3Hw9xm7mHn7UPbK0kHjlncqTCnjZzVQ2j0stg4Q0WjGeS0aB8k1AHPiBaOnvJ
LYcBJrA8mZK+inEE0gWEJsODTM+bKb3+5I69qVoHAkU2tXTDV9g1YKfP4H3rufEg
622AR1yAo8UxaGjY3amWps6XF/9R2iaSDAPLH1dCBw/YWrIH51n75S+n/H3Rz0+H
/aT9Eze0M2F2Nj1cU8fVcbDNR0smssgXVmE2mvQ+OvbO0H7VTS1HK2q2aPOPkRWh
yhFnOvPnbQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAWk5KHkWVsbXqz6/MnwxD5
fn7JrBR77Vz3mxQO9NDKN/vczNMJf5cli6thrB5VPprl5LFXWwQ+LUQhP+XprigQ
8owU1gMNqDzxVHn7By2lnAehLcWYxDoGc8xgTuf2aEjFAyW9xB67YP/kDx9uNFwY
z+zWc6eMVr6dtKcsHcrIEoxLPBO9kuC/wlNY+73q04mmy9XQny15iQLy4sQT0wk4
xV4p86rqDZcGepdV2/bLk2coF9cUOPOGwUBqEIc7n5GekC2WTXSnjOEK5c+2Wkbw
Yt4jXnvsaQ8bwpchHfM1K3mLn+2rCEZ3F4E5Ug7DKebrwU4z/Nccf1DwM4pdI0EI
-----END CERTIFICATE-----
"""
private let exampleServerKey = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA5UPdc3MERjIjrKNMcsCJEPJtzFZG7T99rDaENxl5hF5TdlCu
MfKQMyf4rmUk2KdQXduWDmP/9keOBtc3Hw9xm7mHn7UPbK0kHjlncqTCnjZzVQ2j
0stg4Q0WjGeS0aB8k1AHPiBaOnvJLYcBJrA8mZK+inEE0gWEJsODTM+bKb3+5I69
qVoHAkU2tXTDV9g1YKfP4H3rufEg622AR1yAo8UxaGjY3amWps6XF/9R2iaSDAPL
H1dCBw/YWrIH51n75S+n/H3Rz0+H/aT9Eze0M2F2Nj1cU8fVcbDNR0smssgXVmE2
mvQ+OvbO0H7VTS1HK2q2aPOPkRWhyhFnOvPnbQIDAQABAoIBAQDk0+vAQ1hMx9ab
hRHUpx8nbxDwFl0Mh4Zj0LX+WMrUt2EOglCbQcNzi73GMuWn6LdqNrV6/4yGv7ye
T0iRE9UM3Qzk9s7CZb3a/OinoJMvXqGWjtqolp3HgkyzLt13pXsxfXr9I0Vrggm2
Cz2248hYcAMGIu/wv9i66AGxNLVl3nzlo3K3J+6LwGYSrM5MMsN8p/RIc7RD30cg
Qer6uiGdYemD2hbOuqcqImzhMLvoYn683uLOoDhiFLmAPIU+VxtHs2pMpp4ebjrl
PpS8TtHnV85v/fhX6RE/jo5razdSU4LxW/p/fF5Zte+QR6FJgFFWaQvZd6/Vtuh6
K0Hadt1xAoGBAP1fuBjUElQgWBtoXb422X2/LurnyHfNSqSDM3z8OiCSN08r5GmM
ylWqh7k1sQWBzQ4OAsZcbwvrpvxMGYEd1K99LtUcM235WcKTomz7QRRUKG74tyFk
VdCgcMF+q2DdBE+hlF08bTNk1dM6uPlinNiMklydhLFjjhLlfDkiteGTAoGBAOek
LXqKMK4H5I1VQBgNKAv25tVItDabX5MPqhJVxmsvbNNTh/pfaNW7ietZNkec8FXs
UtS2Hv2hwNMVSb8l9bk96b2x9wiww2exI4oWKjKkJrSVsIcWc4BgeZ2xUtnV6QR5
XSNm7D4E11KhuHPbB01cAZeC0Cf/4rTZ5ERhULL/AoGAS/UpHJBfGkdEAptsFv0c
gH0TFKr9xySNLvqCMgLvbhpHaH2xEQ97DOl9nMGC2zLJhWAf5tWJGNrBibtKnhGS
VDXEF3FH3b018oYN2HwOS4jbQkFfrSwGKfAfPXK67+PySekXsEfQOOsOyy88is7M
VIL30boLMJ621eVkM0C7o+8CgYBLiiK6n24YksJZxL9OGJxCqpXEYB1E4Y5davJP
YGGAesrGb6scXxjU+n+TnFgzKl7F5ndsnqeklqdHLt4J09s6OZKMJgklcF+I5R9t
3KSONzHYGiijJRMtfkiqwDUAjN2cc+eHr/zCjNmbPNnmDjtnYuWx/xrasHvB9nyW
QBYNCQKBgQCDqdvchLcreSdbXKr6swvBz8XxzCaEParbm7iOvdLlv93svvCaHgI8
6E+FlXk68Qc2Dj8de/xEnl/OonNQRgIQh7czBJmYP8+TCPECm8fvv2TsddNvjTmF
TTx8wf9gixHffRtXZ4ILrP1sX7c4if3bfaMxKz+0ZyfzWZry8qZtVQ==
-----END RSA PRIVATE KEY-----
"""
private let clientCert = """
-----BEGIN CERTIFICATE-----
MIICmjCCAYICAQEwDQYJKoZIhvcNAQELBQAwEjEQMA4GA1UEAwwHc29tZS1jYTAe
Fw0yMjExMTQxMTE5MzRaFw0yMzExMTQxMTE5MzRaMBQxEjAQBgNVBAMMCWxvY2Fs
aG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOMSDHjt5P3MOmtw
atYP0PnCfr2sxsMd1uxKeb+x5mpYuckcsnm1UR0LcBCizwBZ7yYAZQkFyK7vdJge
Hv9P3Rki6+6Jj/ngLdpOirtUcOfnfzbdlA2k6qJtY6G+ZKyczDICWaZHzNRycDkL
Yv4kzUT8PynIRIK/LPyXQa+tGty9+G2exVPdpzKpCgE8fKd8FeCOLW06Z0RsP0FS
ySPSJxdDq0BRbfurhplhawh7uJ+7IoVfdWV2wwDvLztCEXHn2iiNpyzIixYapnVB
PX1MXelsPRJaa9EKwOiqJB5ZcV9JWk9wa4W7mJrRfFTRh/9HRsoXIAaJPIqjTmqI
ffat/1cCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAWpPkMzjKLAnxbfyasR6cPk3t
ZanuBQ9RqVJw2gPem+SmSpvyPZ3CJTi0ZeUbPRSJ2W8YHyogaA5XShZSm8JJQKye
TNYqUewVbU18OwVco0l7Wc8R1iiZgYEUcvMF2f/EWEMoCTmS3JlpbLl7LmdTy7iQ
gIrR+iQ649nLw1T4Q5kp7zxjI6WJ3eZVNUjlTrUzKapSY4Tm2/+GafD+WNVRRACh
Y9VNkaQ6qYy4SaLw6+bX2YdbDhIi275vAONHIZcAsMt6/aLJzKgfTxRqqmEvmJdQ
KSVRRaSKZ/qe9UBdl4oFn1wupFAoNDQWkXT/Q3kVhxVXZ8ZE+ylZnuWcj3CHvQ==
-----END CERTIFICATE-----
"""
private let clientSignedByOtherCACert = """
-----BEGIN CERTIFICATE-----
MIICoDCCAYgCAQEwDQYJKoZIhvcNAQELBQAwGDEWMBQGA1UEAwwNc29tZS1vdGhl
ci1jYTAeFw0yMjExMTQxMTE5MzRaFw0yMzExMTQxMTE5MzRaMBQxEjAQBgNVBAMM
CWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOMSDHjt
5P3MOmtwatYP0PnCfr2sxsMd1uxKeb+x5mpYuckcsnm1UR0LcBCizwBZ7yYAZQkF
yK7vdJgeHv9P3Rki6+6Jj/ngLdpOirtUcOfnfzbdlA2k6qJtY6G+ZKyczDICWaZH
zNRycDkLYv4kzUT8PynIRIK/LPyXQa+tGty9+G2exVPdpzKpCgE8fKd8FeCOLW06
Z0RsP0FSySPSJxdDq0BRbfurhplhawh7uJ+7IoVfdWV2wwDvLztCEXHn2iiNpyzI
ixYapnVBPX1MXelsPRJaa9EKwOiqJB5ZcV9JWk9wa4W7mJrRfFTRh/9HRsoXIAaJ
PIqjTmqIffat/1cCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAIqGPpw/m3oIb+Ok7
eZCEph/IcEwvkJXAFYeYjQHDsK1EW/HNoyjKKU3CaLJuWtvNbW+8GpmiVdAcO0XS
RN+xwDOLmB+9Ob70tZRsR/4/695WkkCm/70Y89YqTq3ev86vZmPWBGZsdXB/rvfs
sJbEkNeDRAquEbVQ3K8qmG7w8oC+VdzdQfQHY6hdkzsb0Q99aPASwGjxPVDz12Tb
v9g9f9yVwI+vxxabHr4nvKJ/GfuHRzG2eSW2TNBY/Kxp10+lCdMfbPq2p0LsV4eZ
eHPCFqiBe6CK80Pdpy7CNCPBBvGkGb7nfxBi4/tNVDgMlOQy6pA3PLjib8NLMCIA
5iUEvw==
-----END CERTIFICATE-----
"""
private let clientKey = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA4xIMeO3k/cw6a3Bq1g/Q+cJ+vazGwx3W7Ep5v7Hmali5yRyy
ebVRHQtwEKLPAFnvJgBlCQXIru90mB4e/0/dGSLr7omP+eAt2k6Ku1Rw5+d/Nt2U
DaTqom1job5krJzMMgJZpkfM1HJwOQti/iTNRPw/KchEgr8s/JdBr60a3L34bZ7F
U92nMqkKATx8p3wV4I4tbTpnRGw/QVLJI9InF0OrQFFt+6uGmWFrCHu4n7sihV91
ZXbDAO8vO0IRcefaKI2nLMiLFhqmdUE9fUxd6Ww9Elpr0QrA6KokHllxX0laT3Br
hbuYmtF8VNGH/0dGyhcgBok8iqNOaoh99q3/VwIDAQABAoIBAQC5gA4mYJoY6FW1
XcI5m/QphcWKaHJ8BY2FvZXWj5vftxoXfNUk7oYURzrGrGqVK+Nd1Sa1Bz+aAc7r
UngaNQE3vrqlRUYUaRqsZEubm/Ec0pavmLaRqu9vwBOLmAGgrft2w0q/t5pS2CZr
w6ycWC5FNBjZplypv0oeE+c6gB0YxKJ2mjKEYHWOop+uBPql2G6TfCeu4mMekZPH
cHbMuMlBPN23HT7BmGCvk1YSaGbMt0iCTM0zThfe53AtLSVKn33szHm/XjLYJYGM
7N+SttwM+O88diFShWHUHmWsy5Lv0Mrkw3NRz37yQ8Uh1fJ0TMeLZEIzKSLrI8lv
XrBVE89ZAoGBAP8bBSytb6Aof6p1noIx8nu31d5/5mvRSUxoF1Lu/B/EeaNTGXxD
HvJEi4Lh/txm6/3IeC5gfJ0jExxoWyTD3wLqVvmf+FEMntXqnATC832uw3vkxZpd
E/MldDHE4UkWGBUvii7JN1fisyyZKLUu517crebJthpwk5Sf/1FgK1SbAoGBAOPd
3VTQ7uaD2zPn4QM9KZsFJ+7cS7l1qtupplj9e12T7r53tQLoFjcery2Ja7ZrF3aq
y07D2ww8y8v1ShxqTgSOdeqPCX1a4OS7Z93zsy58Jv3ZcXbfbSGiLbpoueQJbUZ0
vKlDIf4uHn78fz8WIbe87UwKneKnaRrO64DtHQX1AoGBAIH11vYCySozV46UaxLy
tRB3//lg+RcWQJwvLyqt2z2nzzv4OrSGUT6k0tnzne3UdQcN2MPvnaxD0RmYxE3/
hx4qGfMDnvJTVput8JuwYXE21hnI2y4fmuk0vHQaU5bzLYOle2UIVyxrrlHbGNTs
tywpimJXgnEHxvdhZyWis5BfAoGBAN45P2M6J+KzcRGb8DuiaHMAgkNWoJsMAEcd
mldrTeajINCsGeHtycyTpi/4tw0+P7HBO2ljZLr4h6AvZcl0ewXCkYjhWlXgTTeE
9PTmeDa7aaNjbl6J4vpMGeCTxcZ40xNFQcCo8fvbqm4ZfVdfFB8Gpz3jlLq4na5B
YjdoB0gJAoGAZCK3JbIN56KnmyENuZ6szWTZwkCMZq3kPVKBK8LAITVLVxg7Emjs
GyTU+JhMx9Hk2tU/tftM/dTZ2TRRMwmPbZNadtkQdDgsXDhfkrW9JmVewx4ECCcI
gBfWFOoABVTmVM9oNc74FeWu3nDjqGix5ZJ8+Zjjr8wUEcrU2TPZKn4=
-----END RSA PRIVATE KEY-----
"""
private let serverExplicitCurveCert = """
-----BEGIN CERTIFICATE-----
MIICEDCCAbYCCQDCeNe2vM7d6DAKBggqhkjOPQQDAjAWMRQwEgYDVQQDDAtleGFt
cGxlLmNvbTAeFw0yMjExMTQxMTE5MzRaFw0yMzExMTQxMTE5MzRaMBYxFDASBgNV
BAMMC2V4YW1wbGUuY29tMIIBSzCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0B
AQIhAP////8AAAABAAAAAAAAAAAAAAAA////////////////MFsEIP////8AAAAB
AAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxT
sPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vObl
Y6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBo
N79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8YyVRAgEBA0IABDmd
3Pzv6HbsUTmNd7RljKbkYP+36ljl6qVZKZ+8m3Exq4DvtIzLKho/4NluAhWCsRev
2pWTfEiqiYS/U40TnfQwCgYIKoZIzj0EAwIDSAAwRQIhAI+BpDBjiqZD7r5vhPrG
TT9Kq9s4ekIc1/a4AoTioT8CAiAluJHscXt+vBcqEI9sH0wudusCdPJyLbvNtMZd
wdduCw==
-----END CERTIFICATE-----
"""
private let serverExplicitCurveKey = """
-----BEGIN EC PRIVATE KEY-----
MIIBaAIBAQQgBLTFlKchn4c+dQphsqJ2hWVpLPeRQ0opnSwvRsH+63iggfowgfcC
AQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA////////////////
MFsEIP////8AAAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57Pr
vVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEE
axfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54W
K84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8
YyVRAgEBoUQDQgAEOZ3c/O/oduxROY13tGWMpuRg/7fqWOXqpVkpn7ybcTGrgO+0
jMsqGj/g2W4CFYKxF6/alZN8SKqJhL9TjROd9A==
-----END EC PRIVATE KEY-----
"""
#endif // canImport(NIOSSL)
| eb7b3a7697f9a9b5a55f06b785c012dd | 47.137363 | 103 | 0.872617 | false | false | false | false |
chenchangqing/travelMapMvvm | refs/heads/master | travelMapMvvm/travelMapMvvm/ViewModels/FilterViewModel.swift | apache-2.0 | 1 | //
// FilterViewModjel.swift
// travelMapMvvm
//
// Created by green on 15/8/31.
// Copyright (c) 2015年 travelMapMvvm. All rights reserved.
//
import ReactiveCocoa
import ReactiveViewModel
class FilterViewModel: RVMViewModel {
private var selectionViewDataSourceProtocol:SelectionViewDataSourceProtocol = SelectionViewDataSource.shareInstance()
// 被观察数据源
var dataSource = DataSource(dataSource: OrderedDictionary<CJCollectionViewHeaderModel, [CJCollectionViewCellModel]>())
var filterSelectionDicSearch : RACCommand!
override init() {
super.init()
// 初始化命令
setupFilterSelectionDicSearch()
}
private func setupFilterSelectionDicSearch() {
filterSelectionDicSearch = RACCommand(signalBlock: { (any:AnyObject!) -> RACSignal! in
let signal = self.selectionViewDataSourceProtocol.queryFilterDictionary()
let scheduler = RACScheduler(priority: RACSchedulerPriorityBackground)
return signal.subscribeOn(scheduler)
})
filterSelectionDicSearch.executionSignals.switchToLatest().deliverOn(RACScheduler.mainThreadScheduler()).subscribeNextAs { (dataSource:DataSource) -> () in
self.setValue(dataSource, forKey: "dataSource")
}
}
}
| a03c1f3bba0931a93ff9703271d06018 | 30.534884 | 163 | 0.676991 | false | false | false | false |
varshylmobile/VMXMLParser | refs/heads/master | XMLParserTest/XMLParserTest/ViewController.swift | mit | 1 | //
// ViewController.swift
// XMLParserTest
//
// Created by Jimmy Jose on 21/08/14.
// Copyright (c) 2014 Varshyl Mobile Pvt. Ltd. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableview:UITableView! = UITableView()
var activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0,0, 50, 50)) as UIActivityIndicatorView
var tagsArray = NSArray()
var selectedIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.delegate = self
self.tableview.dataSource = self
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
activityIndicator.color = UIColor.blueColor()
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
let url:String="http://images.apple.com/main/rss/hotnews/hotnews.rss"
/*
VMXMLParser.initParserWithURLString(url, completionHandler: {
(tags, error) -> Void in
if(error != nil){
println(error)
}else{
dispatch_async(dispatch_get_main_queue()){
self.tagsArray = tags!
self.tableview.reloadData()
self.activityIndicator.stopAnimating()
}
}
})*/
let tagName = "item"
VMXMLParser().parseXMLFromURLString(url, takeChildOfTag: tagName) { (tags, error) -> Void in
if(error != nil){
print(error!)
}else{
dispatch_async(dispatch_get_main_queue()) {
self.tagsArray = tags!
self.tableview.reloadData()
self.activityIndicator.stopAnimating()
}
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tagsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
let idxForValue:Int = indexPath.row
let dictTable:NSDictionary = tagsArray[idxForValue] as! NSDictionary
let title = dictTable["title"] as? String
let subtitle = dictTable["pubDate"] as? String
cell.textLabel!.text = title ?? ""
cell.detailTextLabel!.text = subtitle ?? ""
cell.backgroundColor = UIColor.clearColor()
cell.textLabel!.font = UIFont(name: "Helvetica Neue Light", size: 15.0)
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
tableView.deselectRowAtIndexPath(indexPath, animated: true)
selectedIndex = indexPath.row
self.performSegueWithIdentifier("Detail", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let detailView = segue.destinationViewController as! DetailView
detailView.title = "Detail"
let dictTable:NSDictionary = tagsArray[selectedIndex] as! NSDictionary
let description = dictTable["description"] as! NSString?
let link = dictTable["link"] as! NSString?
detailView.text = description!
detailView.urlString = link!
}
} | 3279850fe6e8e41f98bc4e7fce03232d | 29.294118 | 114 | 0.593105 | false | false | false | false |
algolia/algoliasearch-client-swift | refs/heads/master | Sources/AlgoliaSearchClient/Index/Index+Index.swift | mit | 1 | //
// Index+Index.swift
//
//
// Created by Vladislav Fitc on 01/04/2020.
//
import Foundation
public extension Index {
// MARK: - Delete index
/**
Delete the index and all its settings, including links to its replicas.
- Parameter requestOptions: Configure request locally with RequestOptions.
- Returns: Launched asynchronous operation
*/
@discardableResult func delete(requestOptions: RequestOptions? = nil,
completion: @escaping ResultTaskCallback<IndexDeletion>) -> Operation & TransportTask {
let command = Command.Index.DeleteIndex(indexName: name, requestOptions: requestOptions)
return execute(command, completion: completion)
}
/**
Delete the index and all its settings, including links to its replicas.
- Parameter requestOptions: Configure request locally with RequestOptions.
- Returns: DeletionIndex object
*/
@discardableResult func delete(requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<IndexDeletion> {
let command = Command.Index.DeleteIndex(indexName: name, requestOptions: requestOptions)
return try execute(command)
}
// MARK: - Exists
/**
Return whether an index exists or not
- Parameter completion: Result completion
- Returns: Launched asynchronous operation
*/
@discardableResult func exists(completion: @escaping ResultCallback<Bool>) -> Operation & TransportTask {
let command = Command.Settings.GetSettings(indexName: name, requestOptions: nil)
return execute(command) { (result: Result<Settings, Swift.Error>) in
switch result {
case .success:
completion(.success(true))
case .failure(let error) where (error as? HTTPError)?.statusCode == .notFound:
completion(.success(false))
case .failure(let error):
completion(.failure(error))
}
}
}
/**
Return whether an index exists or not
- Returns: Bool
*/
@discardableResult func exists() throws -> Bool {
let command = Command.Settings.GetSettings(indexName: name, requestOptions: nil)
let result = Result { try execute(command) as Settings }
switch result {
case .success:
return true
case .failure(let error):
switch error {
case TransportError.httpError(let httpError) where httpError.statusCode == .notFound:
return false
default:
throw error
}
}
}
// MARK: - Copy index
/**
Make a copy of an index, including its objects, settings, synonyms, and query rules.
- Note: This method enables you to copy the entire index (objects, settings, synonyms, and rules) OR one or more of the following index elements:
- setting
- synonyms
- and rules (query rules)
- Parameter scope: Scope set. If empty (.all alias), then all objects and all scopes are copied.
- Parameter destination: IndexName of the destination Index.
- Parameter requestOptions: Configure request locally with RequestOptions
- Parameter completion: Result completion
- Returns: Launched asynchronous operation
*/
@discardableResult func copy(_ scope: Scope = .all,
to destination: IndexName,
requestOptions: RequestOptions? = nil,
completion: @escaping ResultTaskCallback<IndexRevision>) -> Operation & TransportTask {
let command = Command.Index.Operation(indexName: name, operation: .init(action: .copy, destination: destination, scopes: scope.components), requestOptions: requestOptions)
return execute(command, completion: completion)
}
/**
Make a copy of an index, including its objects, settings, synonyms, and query rules.
- Note: This method enables you to copy the entire index (objects, settings, synonyms, and rules) OR one or more of the following index elements:
- setting
- synonyms
- and rules (query rules)
- Parameter scope: Scope set. If empty (.all alias), then all objects and all scopes are copied.
- Parameter destination: IndexName of the destination Index.
- Parameter requestOptions: Configure request locally with RequestOptions
- Returns: RevisionIndex object
*/
@discardableResult func copy(_ scope: Scope = .all,
to destination: IndexName,
requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<IndexRevision> {
let command = Command.Index.Operation(indexName: name, operation: .init(action: .copy, destination: destination, scopes: scope.components), requestOptions: requestOptions)
return try execute(command)
}
// MARK: - Move index
/**
Rename an index. Normally used to reindex your data atomically, without any down time.
The move index method is a safe and atomic way to rename an index.
- Parameter destination: IndexName of the destination Index.
- Parameter requestOptions: Configure request locally with RequestOptions
- Parameter completion: Result completion
- Returns: Launched asynchronous operation
*/
@discardableResult func move(to destination: IndexName,
requestOptions: RequestOptions? = nil,
completion: @escaping ResultTaskCallback<IndexRevision>) -> Operation & TransportTask {
let command = Command.Index.Operation(indexName: name, operation: .init(action: .move, destination: destination, scopes: nil), requestOptions: requestOptions)
return execute(command, completion: completion)
}
/**
Rename an index. Normally used to reindex your data atomically, without any down time.
The move index method is a safe and atomic way to rename an index.
- Parameter destination: IndexName of the destination Index.
- Parameter requestOptions: Configure request locally with RequestOptions
- Returns: RevisionIndex object
*/
@discardableResult func move(to destination: IndexName,
requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<IndexRevision> {
let command = Command.Index.Operation(indexName: name, operation: .init(action: .move, destination: destination, scopes: nil), requestOptions: requestOptions)
return try execute(command)
}
}
| ec825d060185e36098d8f2c1e917732c | 39.314103 | 175 | 0.692479 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode | refs/heads/master | 精通Swift设计模式/Chapter 10/AbstractFactory/AbstractFactory/Drivetrains.swift | mit | 1 | protocol Drivetrain {
var driveType:DriveOption { get };
}
enum DriveOption : String {
case FRONT = "Front"; case REAR = "Rear"; case ALL = "4WD";
}
class FrontWheelDrive : Drivetrain {
var driveType = DriveOption.FRONT;
}
class RearWheelDrive : Drivetrain {
var driveType = DriveOption.REAR;
}
class AllWheelDrive : Drivetrain {
var driveType = DriveOption.ALL;
}
| b3f3549ba5179bd28baf800cf55f5b25 | 19.473684 | 63 | 0.691517 | false | false | false | false |
Palleas/romain-pouclet.com | refs/heads/master | _snippets/batman-colours.swift | mit | 1 | enum ProjectColor: String {
case darkPink = "dark-pink"
case darkGreen = "dark-green"
case darkBlue = "dark-blue"
case darkRed = "dark-red"
case darkTeal = "dark-teal"
case darkBrown = "dark-brown"
case darkOrange = "dark-orange"
case darkPurple = "dark-purple"
case darkWarmGray = "dark-warm-gray"
case lightPink = "light-pink"
case lightGreen = "light-green"
case lightBlue = "light-blue"
case lightRed = "light-red"
case lightTeal = "light-teal"
case lightYellow = "light-yellow"
case lightOrange = "light-orange"
case lightPurple = "light-purple"
case lightWarmGray = "light-warm-gray"
var raw: UIColor { /* ... */ }
}
| 810d826d391d705797523cbed4eb5e63 | 30.863636 | 42 | 0.643367 | false | false | false | false |
hoffmanjon/SwiftyBones | refs/heads/master | examples/BlinkingLed/SwiftyBones/SwiftyBonesDigitalGPIO.swift | mit | 2 | #if arch(arm) && os(Linux)
import Glibc
#else
import Darwin
#endif
/**
The list of available GPIO.
*/
var DigitalGPIOPins:[String: BBExpansionPin] = [
"gpio38": (header:.P8, pin:3),
"gpio39": (header:.P8, pin:4),
"gpio34": (header:.P8, pin:5),
"gpio35": (header:.P8, pin:6),
"gpio66": (header:.P8, pin:7),
"gpio67": (header:.P8, pin:8),
"gpio69": (header:.P8, pin:9),
"gpio68": (header:.P8, pin:10),
"gpio45": (header:.P8, pin:11),
"gpio44": (header:.P8, pin:12),
"gpio23": (header:.P8, pin:13),
"gpio26": (header:.P8, pin:14),
"gpio47": (header:.P8, pin:15),
"gpio46": (header:.P8, pin:16),
"gpio27": (header:.P8, pin:17),
"gpio65": (header:.P8, pin:18),
"gpio22": (header:.P8, pin:19),
"gpio63": (header:.P8, pin:20),
"gpio62": (header:.P8, pin:21),
"gpio37": (header:.P8, pin:22),
"gpio36": (header:.P8, pin:23),
"gpio33": (header:.P8, pin:24),
"gpio32": (header:.P8, pin:25),
"gpio61": (header:.P8, pin:26),
"gpio86": (header:.P8, pin:27),
"gpio88": (header:.P8, pin:28),
"gpio87": (header:.P8, pin:29),
"gpio89": (header:.P8, pin:30),
"gpio10": (header:.P8, pin:31),
"gpio11": (header:.P8, pin:32),
"gpio9": (header:.P8, pin:33),
"gpio81": (header:.P8, pin:34),
"gpio8": (header:.P8, pin:35),
"gpio80": (header:.P8, pin:36),
"gpio78": (header:.P8, pin:37),
"gpio79": (header:.P8, pin:38),
"gpio76": (header:.P8, pin:39),
"gpio77": (header:.P8, pin:40),
"gpio74": (header:.P8, pin:41),
"gpio75": (header:.P8, pin:42),
"gpio72": (header:.P8, pin:43),
"gpio73": (header:.P8, pin:44),
"gpio70": (header:.P8, pin:45),
"gpio71": (header:.P8, pin:46),
"gpio30": (header:.P9, pin:11),
"gpio60": (header:.P9, pin:12),
"gpio31": (header:.P9, pin:13),
"gpio50": (header:.P9, pin:14),
"gpio48": (header:.P9, pin:15),
"gpio51": (header:.P9, pin:16),
"gpio5": (header:.P9, pin:17),
"gpio4": (header:.P9, pin:18),
"gpio3": (header:.P9, pin:21),
"gpio2": (header:.P9, pin:22),
"gpio49": (header:.P9, pin:23),
"gpio15": (header:.P9, pin:24),
"gpio117": (header:.P9, pin:25),
"gpio14": (header:.P9, pin:26),
"gpio115": (header:.P9, pin:27),
"gpio113": (header:.P9, pin:28),
"gpio111": (header:.P9, pin:29),
"gpio112": (header:.P9, pin:30),
"gpio110": (header:.P9, pin:31),
"gpio20": (header:.P9, pin:41),
"gpio7": (header:.P9, pin:42)
]
/**
Direction that pin can be configured for
*/
enum DigitalGPIODirection: String {
case IN="in"
case OUT="out"
}
/**
The value of the digitial GPIO pins
*/
enum DigitalGPIOValue: String {
case HIGH="1"
case LOW="0"
}
/**
Type that represents a GPIO pin on the Beaglebone Black
*/
struct SBDigitalGPIO: GPIO {
/**
Variables and paths needed
*/
private static let GPIO_BASE_PATH = "/sys/class/gpio/"
private static let GPIO_EXPORT_PATH = GPIO_BASE_PATH + "export"
private static let GPIO_DIRECTION_FILE = "/direction"
private static let GPIO_VALUE_FILE = "/value"
private var header: BBExpansionHeader
private var pin: Int
private var id: String
private var direction: DigitalGPIODirection
/**
Failable initiator which will fail if an invalid ID is entered
- Parameter id: The ID of the pin. The ID starts with gpio and then contains the gpio number
- Parameter direction: The direction to configure the pin for
*/
init?(id: String, direction: DigitalGPIODirection) {
if let val = DigitalGPIOPins[id] {
self.id = id
self.header = val.header
self.pin = val.pin
self.direction = direction
if !initPin() {
return nil
}
} else {
return nil
}
}
/**
Failable initiator which will fail if either the header or pin number is invalid
- Parameter header: This is the header which will be either .P8 or .P9
- pin: the pin number
- Parameter direction: The direction to configure the pin for
*/
init?(header: BBExpansionHeader, pin: Int, direction: DigitalGPIODirection) {
for (key, expansionPin) in DigitalGPIOPins where expansionPin.header == header && expansionPin.pin == pin {
self.header = header
self.pin = pin
self.id = key
self.direction = direction
if !initPin() {
return nil
}
return
}
return nil
}
/**
This method configures the pin for Digital I/O
- Returns: true if the pin was successfully configured for digitial I/O
*/
func initPin() -> Bool {
let range = id.startIndex.advancedBy(4)..<id.endIndex.advancedBy(0)
let gpioId = id[range]
let gpioSuccess = writeStringToFile(gpioId, path: SBDigitalGPIO.GPIO_EXPORT_PATH)
let directionSuccess = writeStringToFile(direction.rawValue, path: getDirectionPath())
if !gpioSuccess || !directionSuccess {
return false
}
return true
}
/**
This function checks to see if the pin is configured for Digital I/O
- Returns: true if the pin is already configured otherwise false
*/
func isPinActive() -> Bool {
if let _ = getValue() {
return true
} else {
return false
}
}
/**
Gets the present value from the pin
- Returns: returns the value for the pin eith .HIGH or .LOW
*/
func getValue() -> DigitalGPIOValue? {
if let valueStr = readStringFromFile(getValuePath()) {
return valueStr == DigitalGPIOValue.HIGH.rawValue ? DigitalGPIOValue.HIGH : DigitalGPIOValue.LOW
} else {
return nil
}
}
/**
Sets the value for the pin
- Parameter value: The value for the pin either .HIGH or .LOW
*/
func setValue(value: DigitalGPIOValue) {
writeStringToFile(value.rawValue, path: getValuePath())
}
/**
Determines the path to the file for this particular digital pin direction file
- Returns: Path to file
*/
private func getDirectionPath() -> String {
return SBDigitalGPIO.GPIO_BASE_PATH + id + SBDigitalGPIO.GPIO_DIRECTION_FILE
}
/**
Determines the path to the file for this particular digital pin
- Returns: Path to file
*/
private func getValuePath() -> String {
return SBDigitalGPIO.GPIO_BASE_PATH + id + SBDigitalGPIO.GPIO_VALUE_FILE
}
}
| 8b979e9781ae0fd911c3d8f74db2bb46 | 29.976744 | 115 | 0.578979 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Legacy/Neocom/Neocom/NCEventTableViewCell.swift | lgpl-2.1 | 2 | //
// NCEventTableViewCell.swift
// Neocom
//
// Created by Artem Shimanski on 05.05.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import EVEAPI
import CoreData
class NCEventTableViewCell: NCTableViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var stateLabel: UILabel!
}
extension Prototype {
enum NCEventTableViewCell {
static let `default` = Prototype(nib: nil, reuseIdentifier: "NCEventTableViewCell")
}
}
class NCEventRow: TreeRow {
let event: ESI.Calendar.Summary
init(event: ESI.Calendar.Summary) {
self.event = event
super.init(prototype: Prototype.NCEventTableViewCell.default, route: Router.Calendar.Event(event: event))
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCEventTableViewCell else {return}
cell.titleLabel.text = event.title
if let date = event.eventDate {
cell.dateLabel.text = DateFormatter.localizedString(from: date, dateStyle: .none, timeStyle: .short)
}
else {
cell.dateLabel.text = nil
}
cell.stateLabel.text = (event.eventResponse ?? .notResponded).title
}
override var hash: Int {
return event.hashValue
}
override func isEqual(_ object: Any?) -> Bool {
return (object as? NCEventRow)?.hashValue == hashValue
}
}
| d6076289f0c3918cd05ddbd054feb338 | 23.4 | 107 | 0.723547 | false | false | false | false |
AaoIi/FMPhoneTextField | refs/heads/master | FMPhoneTextField/FMPhoneTextField/FMPhoneTextField.swift | mit | 1 | //
// FMPhoneTextField.swift
//
//
// Created by Saad Basha on 5/16/17.
// Copyright © 2017 Saad Basha. All rights reserved.
//
import UIKit
import CoreTelephony
public protocol FMPhoneDelegate : class{
func didGetDefaultCountry(success:Bool,country: CountryElement?)
func didSelectCountry(_ country:CountryElement)
}
public class FMPhoneTextField: UITextField {
public enum CodeDisplay {
case isoShortCode
case internationlKey
case bothIsoShortCodeAndInternationlKey
case countryName
}
public enum SearchType {
case cellular
case locale
case both
}
// Views
private var contentViewholder : UIView!
private var countryButton: UIButton!
private var countryCodeLabel : UILabel!
private var separator : UIView!
// Default Styles
private var borderColor = UIColor(red: 232/255, green: 232/255, blue: 232/255, alpha: 1.0)
private var borderWidth : CGFloat = 1
private var cornerRadius : CGFloat = 7
private var backgroundTintColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1.0)
private var codeTextColor = UIColor(red: 107/255, green: 174/255, blue: 242/255, alpha: 1.0)
private var separatorBackgroundColor = UIColor(red: 226/255, green: 226/255, blue: 226/255, alpha: 1.0)
private var separatorWidth : CGFloat = 1
private var defaultRegex = "(\\d{9,10})"
private var selectedCountry : CountryElement?
private weak var countryDelegate : FMPhoneDelegate?
private var language : language! = .english
private var defaultsSearchType : SearchType = .locale
private var countryCodeDisplay : CodeDisplay = .bothIsoShortCodeAndInternationlKey
private var isCountryCodeInListHidden : Bool = false
//MARK: - Life cycle
/// It will setup the view and layout, including getting the default country
///
/// - Parameters:
/// - delegate: managing the details of country and phone field.
/// - language: selected language (arabic,english)
public func initiate(delegate:FMPhoneDelegate,language:language){
// update local variables
self.countryDelegate = delegate
self.language = language
// force layout to be left to right
self.semanticContentAttribute = .forceLeftToRight
// Add country left View
self.setupCountryView()
// Setup TextField Keyboard
if #available(iOS 10, *){
self.keyboardType = .asciiCapableNumberPad
}else {
self.keyboardType = .phonePad
}
self.getCurrentCountryCode()
}
//MARK: - Update Views
/// This is called automaticaly after country is being selected, its responsible for displaying the country/code details
///
/// - Parameter country: object to be displayed
public func updateCountryDisplay(country: CountryElement){
var text = ""
switch countryCodeDisplay {
case .bothIsoShortCodeAndInternationlKey:
text = "\(country.isoShortCode ?? "") \(country.countryInternationlKey ?? "")"
break;
case .countryName:
let name = language == .arabic ? country.nameAr : country.nameEn
text = "\(name ?? "")"
break;
case .isoShortCode:
text = "\(country.isoShortCode ?? "")"
break;
case .internationlKey:
text = "\(country.countryInternationlKey ?? "")"
break;
}
self.setupCountryView(text: text)
self.selectedCountry = country
}
/// Get the phone number in full shape,
/// IAC : International Access Code which is + or 00
/// - Parameter withPlus: will return 00 if passed false else will return +
/// - Returns: the full phone number including country code.
public func getPhoneNumberIncludingIAC(withPlus:Bool = false)->String{
guard let code = self.selectedCountry?.countryInternationlKey else { print("Error: Could not get country"); return "" }
if withPlus {
let text = self.text ?? ""
if text.count > 0 {
if text.first == "0" {
let phone = String(text.dropFirst())
self.text = phone
}
}
return code + (self.text ?? "")
}else {
let code = code.replacingOccurrences(of: "+", with: "00")
let text = self.text ?? ""
if text.count > 0 {
if text.first == "0" {
let phone = String(text.dropFirst())
self.text = phone
}
}
return code + (self.text ?? "")
}
}
//MARK: - Validation Method
/// Will use the regex provided in each country object to validate the phone
///
/// - Returns: valid phone or not
public func validatePhone()->Bool{
if self.selectedCountry == nil {
return self.evaluate(text: self.text ?? "", regex: defaultRegex)
}else {
let mobile = self.text ?? ""
let regex = self.selectedCountry?.phoneRegex ?? defaultRegex
return self.evaluate(text: mobile, regex: regex)
}
}
private func evaluate(text:String, regex:String)->Bool{
let phoneRegex = regex
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
return phoneTest.evaluate(with: text)
}
//MARK: - Helping Methods
private func getCurrentCountryCode(){
var countryCode : String? = nil
if self.defaultsSearchType == .locale {
countryCode = FMPhoneTextField.getCountryCodeFromLocale()
}else if self.defaultsSearchType == .cellular {
countryCode = FMPhoneTextField.getCountryCodeFromCellularProvider()
}else {
countryCode = FMPhoneTextField.getCountryCodeFromCellularProvider() ?? FMPhoneTextField.getCountryCodeFromLocale()
}
guard let countries = CountriesDataSource.getCountries(language: language) else {return}
for country in countries {
if country.isoShortCode?.lowercased() == countryCode?.lowercased() {
self.updateCountryDisplay(country: country)
guard let delegate = self.countryDelegate else {print("Error:delegate is not set"); return }
delegate.didGetDefaultCountry(success: true, country: country)
return;
}
}
guard let delegate = self.countryDelegate else { return }
delegate.didGetDefaultCountry(success: false, country: nil)
}
private func getTopMostViewController()->UIViewController?{
guard let keyWindow = UIApplication.shared.keyWindow else { return nil}
guard let visableVC = keyWindow.visibleViewController() else { return nil}
return visableVC
}
//MARK: - Country Left View
private func setupCountryView(text:String? = nil){
// setup default size for leftview
let height = self.frame.size.height;
let frame = CGRect(x:0,y:0,width: self.frame.size.width / 2.9,height: height)
// Setup main View
self.contentViewholder = UIView(frame: frame)
self.contentViewholder.backgroundColor = .clear
// Setup Button and should be equal to left view frame
self.countryButton = UIButton(frame: frame)
self.countryButton.backgroundColor = .clear
// Setup label size to be dynamicly resized
let startPadding = self.frame.size.width / 3.2
let labelOriginX = frame.width - startPadding
let labelWidth = frame.width - labelOriginX - labelOriginX
self.countryCodeLabel = UILabel(frame: CGRect(x:labelOriginX,y:frame.origin.y,width: labelWidth,height: height))
self.countryCodeLabel.text = text
self.countryCodeLabel.textAlignment = .center
self.countryCodeLabel.sizeToFit()
// Setup separator to be at trailing of left view
let topPadding = height / 3.5
let leftPadding : CGFloat = 8
self.separator = UIView(frame: CGRect(x: self.countryCodeLabel.frame.width + labelOriginX + leftPadding,y:topPadding,width: separatorWidth,height: height - topPadding*2))
// Set default style
self.separator.backgroundColor = separatorBackgroundColor
self.countryCodeLabel.textColor = codeTextColor
self.layer.borderColor = self.borderColor.cgColor
self.layer.borderWidth = self.borderWidth
self.layer.cornerRadius = self.cornerRadius
self.layer.masksToBounds = true
self.backgroundColor = self.backgroundTintColor
// Add Target To Button
self.countryButton.addTarget(self, action: #selector(presentCountries(_:)), for: .touchUpInside)
// resize the left view depending on the views inside (label/separator/padding)
let leftViewRightPadding : CGFloat = 8
let newContentViewFrame = CGRect(x:0,y:0,width: self.countryCodeLabel.frame.width + labelOriginX + leftPadding + separatorWidth + leftViewRightPadding,height: height)
self.contentViewholder = UIView(frame: newContentViewFrame)
// Setup contentView
self.contentViewholder.addSubview(countryCodeLabel)
self.contentViewholder.addSubview(countryButton)
self.contentViewholder.addSubview(separator)
// set left view
self.leftViewMode = UITextField.ViewMode.always
self.leftView = self.contentViewholder
// re center country code label
self.countryCodeLabel.center.y = self.contentViewholder.center.y
}
//MARK: - Style
public func setStyle(backgroundTint:UIColor,separatorColor:UIColor,borderColor:UIColor,borderWidth:CGFloat,cornerRadius:CGFloat,countryCodeTextColor:UIColor){
self.setBorderColor(borderColor, width: borderWidth)
self.setCornerRadius(cornerRadius)
self.setBackgroundTint(backgroundTint)
self.setCountryCodeTextColor(countryCodeTextColor)
self.setSeparatorColor(separatorColor)
}
public func setBorderColor(_ color: UIColor,width:CGFloat){
self.layer.borderColor = color.cgColor
self.layer.borderWidth = width
}
public func setCornerRadius(_ size:CGFloat){
self.layer.cornerRadius = size
self.layer.masksToBounds = true
}
public func setBackgroundTint(_ color:UIColor){
self.backgroundColor = color
}
public func setCountryCodeTextColor(_ color:UIColor){
countryCodeLabel.textColor = color
}
public func setSeparatorColor(_ color:UIColor){
separator.backgroundColor = color
}
//MARK:- Display Customizations
/// This is responsible to set the search algo for finding the country eather using locale or sim card, or even both.
///
/// - Parameter type: SearchType
public func setDefaultCountrySearch(to type:SearchType){
self.defaultsSearchType = type
}
/// It will hide the country international key in the countries list
///
/// - Parameter hidden: true or false
public func setCountryCodeInList(hidden:Bool ){
self.isCountryCodeInListHidden = hidden
}
/// This is responsible for setting your prefered way of showing the selected country in code field, Example US +1 or US or +1 etc.
///
/// - Parameter type: CodeDisplay
public func setCountryCodeDisplay(type:CodeDisplay){
self.countryCodeDisplay = type
}
//MARK: - Actions and Selectors
@objc private func presentCountries(_ textField:FMPhoneTextField){
let vc = CountriesViewController(delegate: self, language: language,isCountryCodeHidden: self.isCountryCodeInListHidden)
let navigation = UINavigationController(rootViewController: vc)
guard let topMostViewController = self.getTopMostViewController() else { print("Could not present"); return }
topMostViewController.present(navigation, animated: true, completion: nil)
}
}
//MARK: - Country Delegate
extension FMPhoneTextField:CountriesDelegate {
internal func didSelectCountry(country: CountryElement) {
DispatchQueue.main.async {
// update the country and the code
self.updateCountryDisplay(country: country)
}
guard let delegate = self.countryDelegate else {return}
delegate.didSelectCountry(country)
}
}
//MARK: - Country Code Getters
fileprivate extension FMPhoneTextField {
class func getCountryCodeFromCellularProvider() -> String? {
let networkInfo = CTTelephonyNetworkInfo()
let carrier = networkInfo.subscriberCellularProvider
return carrier?.isoCountryCode
}
class func getCountryCodeFromLocale() -> String? {
let currentLocale : NSLocale = NSLocale.current as NSLocale
let countryCode = currentLocale.object(forKey: NSLocale.Key.countryCode) as? String
return countryCode
}
}
//MARK: - View Controller Getter
fileprivate extension UIWindow {
func visibleViewController() -> UIViewController? {
if let rootViewController: UIViewController = self.rootViewController {
return UIWindow.getVisibleViewControllerFrom(rootViewController)
}
return nil
}
class func getVisibleViewControllerFrom(_ vc:UIViewController) -> UIViewController {
if vc.isKind(of: UINavigationController.self) {
let navigationController = vc as! UINavigationController
return UIWindow.getVisibleViewControllerFrom( navigationController.visibleViewController!)
} else if vc.isKind(of: UITabBarController.self) {
let tabBarController = vc as! UITabBarController
return UIWindow.getVisibleViewControllerFrom(tabBarController.selectedViewController!)
} else {
if let presentedViewController = vc.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(presentedViewController)
} else {
return vc;
}
}
}
}
| 81cba7b25f029481806e0faee002c2d2 | 33.462243 | 178 | 0.619588 | false | false | false | false |
spark/photon-tinker-ios | refs/heads/master | Photon-Tinker/Global/Controls/FocusRectView.swift | apache-2.0 | 1 | //
// Created by Raimundas Sakalauskas on 2019-05-30.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
class FocusRectView: UIView {
var focusRectSize: CGSize?
var focusRectFrameColor: UIColor?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = .clear
}
override func draw(_ rect: CGRect) {
super.draw(rect)
if let ct = UIGraphicsGetCurrentContext(), let focusRectSize = focusRectSize {
let color = (self.focusRectFrameColor ?? UIColor.black.withAlphaComponent(0.65)).cgColor
ct.setFillColor(color)
ct.fill(self.bounds)
let targetHalfHeight = min(focusRectSize.height, self.bounds.height) / 2
let targetHalfWidth = min(focusRectSize.width, self.bounds.width) / 2
let cutoutRect = CGRect(x: self.bounds.midX - targetHalfWidth, y: self.bounds.midY - targetHalfHeight, width: targetHalfWidth * 2, height: targetHalfHeight * 2)
let path = UIBezierPath(roundedRect: cutoutRect, cornerRadius: 8)
ct.setBlendMode(.destinationOut)
path.fill()
}
}
}
| 267d5bc65099e1b159e774534b8a189e | 30.02381 | 172 | 0.650038 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | refs/heads/master | PopcornTime/Extensions/PCTPlayerViewController+MediaPlayer.swift | gpl-3.0 | 1 |
import Foundation
import MediaPlayer
import AlamofireImage
extension PCTPlayerViewController {
func addRemoteCommandCenterHandlers() {
let center = MPRemoteCommandCenter.shared()
center.pauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.playandPause()
return self.mediaplayer.state == .paused ? .success : .commandFailed
}
center.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.playandPause()
return self.mediaplayer.state == .playing ? .success : .commandFailed
}
if #available(iOS 9.1, tvOS 9.1, *) {
center.changePlaybackPositionCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.mediaplayer.time = VLCTime(number: NSNumber(value: (event as! MPChangePlaybackPositionCommandEvent).positionTime * 1000))
return .success
}
}
center.stopCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.mediaplayer.stop()
return .success
}
center.changePlaybackRateCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.mediaplayer.rate = (event as! MPChangePlaybackRateCommandEvent).playbackRate
return .success
}
center.skipForwardCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.mediaplayer.jumpForward(Int32((event as! MPSkipIntervalCommandEvent).interval))
return .success
}
center.skipBackwardCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.mediaplayer.jumpBackward(Int32((event as! MPSkipIntervalCommandEvent).interval))
return .success
}
}
func removeRemoteCommandCenterHandlers() {
nowPlayingInfo = nil
UIApplication.shared.endReceivingRemoteControlEvents()
}
func configureNowPlayingInfo() {
nowPlayingInfo = [MPMediaItemPropertyTitle: media.title,
MPMediaItemPropertyPlaybackDuration: TimeInterval(streamDuration/1000),
MPNowPlayingInfoPropertyElapsedPlaybackTime: mediaplayer.time.value.doubleValue/1000,
MPNowPlayingInfoPropertyPlaybackRate: Double(mediaplayer.rate),
MPMediaItemPropertyMediaType: MPMediaType.movie.rawValue]
if let image = media.mediumCoverImage ?? media.mediumBackgroundImage, let request = try? URLRequest(url: image, method: .get) {
ImageDownloader.default.download(request) { (response) in
guard let image = response.result.value else { return }
if #available(iOS 10.0, tvOS 10.0, *) {
self.nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { (_) -> UIImage in
return image
}
} else {
self.nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: image)
}
}
}
}
override func remoteControlReceived(with event: UIEvent?) {
guard let event = event else { return }
switch event.subtype {
case .remoteControlPlay:
fallthrough
case .remoteControlPause:
fallthrough
case .remoteControlTogglePlayPause:
playandPause()
case .remoteControlStop:
mediaplayer.stop()
default:
break
}
}
}
| 04c2a3967644c3ccb80bfb9a2f289473 | 39.107527 | 142 | 0.606434 | false | false | false | false |
Lollipop95/WeiBo | refs/heads/master | WeiBo/WeiBo/Classes/View/Main/NewFeature/WBNewFeatureView.swift | mit | 1 | //
// WBNewFeatureView.swift
// WeiBo
//
// Created by Ning Li on 2017/5/5.
// Copyright © 2017年 Ning Li. All rights reserved.
//
import UIKit
/// 新特性视图
class WBNewFeatureView: UIView {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var enterButton: UIButton!
@IBOutlet weak var pageControl: UIPageControl!
/// 创建新特性视图
class func newFeatureView() -> WBNewFeatureView {
let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView
v.frame = UIScreen.main.bounds
return v
}
override func awakeFromNib() {
super.awakeFromNib()
let count = 4
let rect = scrollView.bounds
for i in 1...count {
let imageName = "new_feature_\(i)"
let imageView = UIImageView(image: UIImage(named: imageName))
imageView.frame = rect.offsetBy(dx: CGFloat(i - 1) * rect.width, dy: 0)
scrollView.addSubview(imageView)
}
scrollView.contentSize = CGSize(width: CGFloat(count) * rect.width, height: 0)
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.isPagingEnabled = true
scrollView.bounces = false
scrollView.delegate = self
enterButton.isHidden = true
}
// MARK: - 监听方法
/// 进入微博
@IBAction func enterStatus() {
removeFromSuperview()
}
}
// MARK: - UIScrollViewDelegate
extension WBNewFeatureView: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
pageControl.currentPage = page
pageControl.isHidden = (page > scrollView.subviews.count - 2)
enterButton.isHidden = true
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
enterButton.isHidden = (page != scrollView.subviews.count - 1)
}
}
| dd42cdc83eddd2d5043b5479a9e049e5 | 26.634146 | 86 | 0.606355 | false | false | false | false |
iToto/swiftNetworkManager | refs/heads/master | network_connectivity/Managers/Network/Controllers/NetworkManagerViewController.swift | mit | 1 | //
// ViewController.swift
// network_connectivity
//
// Created by Salvatore D'Agostino on 2015-03-01.
// Copyright (c) 2015 dressed. All rights reserved.
//
import UIKit
class NetworkManagerViewController: UIViewController {
let networkLossNotification = "com.dressed.networkLossNotification"
let networkFoundNotification = "com.dressed.networkFoundNotification"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Register observer for network lost
NSNotificationCenter.defaultCenter().addObserverForName(self.networkLossNotification,object:nil , queue:nil){ _ in
self.displayNoConnectionView()
}
// Register observer for network found
NSNotificationCenter.defaultCenter().addObserverForName(self.networkFoundNotification,object:nil , queue:nil){ _ in
self.hideNoConnectionView()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func testConnectivity() {
if IJReachability.isConnectedToNetwork() {
// Animate fade-in of view
self.displayNoConnectionView()
}
}
func displayNoConnectionView() {
let screenSize: CGRect = UIScreen.mainScreen().bounds
let noConnectionView = NoConnectionView(frame: screenSize)
noConnectionView.alpha = 0
// Will animate fade-in of view
UIView.animateWithDuration(0.5, delay: 0, options:UIViewAnimationOptions.CurveEaseOut, animations: {() in
noConnectionView.alpha = 0.8
}, completion: nil)
self.view.addSubview(noConnectionView)
}
func hideNoConnectionView() {
NSLog("Remove no connection view")
for view in self.view.subviews {
view.removeFromSuperview()
}
}
}
| 6f96c3c05895b8a9242649358a39b5cf | 29.208955 | 123 | 0.65168 | false | false | false | false |
gewill/Feeyue | refs/heads/develop | Feeyue/Main/Twitter/TwitterUser/TwitterUserViewModel.swift | mit | 1 | //
// TwitterUserViewModel.swift
// Feeyue
//
// Created by Will on 2018/7/3.
// Copyright © 2018 Will. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
import Moya
import RxSwift
import Moya_SwiftyJSONMapper
import SwifterSwift
class TwitterUserViewModel {
private var timeline: TwitterTimeline!
private var token: NotificationToken?
private var userToken: NotificationToken?
private var realm: Realm!
private var userId: String?
private var userName: String?
var statuses: Results<TwitterStatus> {
return timeline.statuses.sorted(byKeyPath: TwitterStatus.Property.createdAt.rawValue, ascending: false)
}
var user: TwitterUser?
// MARK: - life cycle
init(userId: String?, userName: String?, realm: Realm = RealmProvider.twitterInMemory.realm) {
self.userId = userId
self.userName = userName
self.realm = realm
timeline = TwitterTimeline.create(idStr: UUID().uuidString, realm: realm)
guard let userId = userId else { return }
user = TwitterUser.getUser(userId: userId)
}
deinit {
token?.invalidate()
userToken?.invalidate()
removeCache()
}
var didUpdate: VoidClosure? = nil {
didSet {
guard let didUpdate = didUpdate,
let timeline = timeline else {
token?.invalidate()
return
}
token = timeline.observe({ changes in
switch changes {
case .change:
didUpdate()
case .deleted:
didUpdate()
case .error:
break
}
})
}
}
var userUpdate: VoidClosure? = nil {
didSet {
guard let userUpdate = userUpdate,
let user = user else {
userToken?.invalidate()
return
}
userToken = user.observe({ changes in
switch changes {
case .change:
userUpdate()
case .deleted:
userUpdate()
case .error:
break
}
})
}
}
func removeCache() {
try? self.realm.write {
self.realm.delete(self.timeline)
}
}
// MARK: - load data
func reloadData() -> Observable<[TwitterStatus]> {
return twitterProvider.rx.request(.userTimeline(userId, userName, 200, nil, nil))
//.debug()
.map(to: [TwitterStatus.self])
.asObservable()
.do(onNext: { response in
try! self.realm.write {
self.realm.add(response, update: true)
self.timeline.statuses.append(objectsIn: response)
self.realm.add(self.timeline, update: true)
}
})
}
func moreOldData() -> Observable<[TwitterStatus]> {
let maxId = statuses.last?.idStr
return twitterProvider.rx.request(.userTimeline(userId, userName, 50, nil, maxId))
//.debug()
.map(to: [TwitterStatus.self])
.asObservable()
.do(onNext: { response in
try! self.realm.write {
self.realm.add(response, update: true)
self.timeline.statuses.append(objectsIn: response)
self.realm.add(self.timeline, update: true)
}
})
}
func moreNewData() -> Observable<[TwitterStatus]> {
let sinceId = statuses.first?.idStr
return twitterProvider.rx.request(.userTimeline(userId, userName, 50, sinceId, nil))
//.debug()
.map(to: [TwitterStatus.self])
.asObservable()
.do(onNext: { response in
try! self.realm.write {
self.realm.add(response, update: true)
self.timeline.statuses.append(objectsIn: response)
self.realm.add(self.timeline, update: true)
}
})
}
func userInfo() -> Observable<TwitterUser> {
return twitterProvider.rx.request(.userInfo(userId, userName))
.debug()
.map(to: TwitterUser.self)
.asObservable()
.do(onNext: { response in
TwitterUser.addUser(user: response)
self.user = response
self.userUpdate?()
})
}
}
| cadda2f4ed1a58d2b0e3e5f3b0e90847 | 28.649351 | 111 | 0.52869 | false | false | false | false |
sourcebitsllc/Asset-Generator-Mac | refs/heads/master | XCAssetGenerator/ImagesDropViewController.swift | mit | 1 | //
// ImagesDropViewController.swift
// XCAssetGenerator
//
// Created by Bader on 5/11/15.
// Copyright (c) 2015 Bader Alabdulrazzaq. All rights reserved.
//
import ReactiveCocoa
// TODO: Swift 2.0: Protocol extension
enum DropState {
case None
case Hovering
case Accepted
case Rejected
}
let thin: (border: CGFloat, width: CGFloat) = (border: 1, width: 125)
let fat: (border: CGFloat, width: CGFloat) = (border: 3, width: 130)
class ImagesDropViewController: NSViewController {
@IBOutlet var dropView: RoundedDropView!
@IBOutlet var dropImageView: NSImageView!
@IBOutlet var well: NSImageView!
@IBOutlet var label: NSTextField!
@IBOutlet var heightConstraint: NSLayoutConstraint!
@IBOutlet var widthConstraint: NSLayoutConstraint!
let viewModel: ImagesGroupViewModel
init?(viewModel: ImagesGroupViewModel) {
self.viewModel = viewModel
super.init(nibName: "ImagesDropView", bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
dropView.delegate = self
dropView.mouse = self
dropImageView.unregisterDraggedTypes()
well.unregisterDraggedTypes()
viewModel.currentSelectionValid.producer
|> on(next: { valid in
self.layoutUI(valid ? .Accepted : .None) })
|> start()
viewModel.label.producer
|> on(next: { label in
self.label.stringValue = label })
|> start()
}
private func layoutUI(state: DropState) {
switch state {
case .Hovering:
dropView.layer?.borderWidth = fat.border
heightConstraint.constant = fat.width
widthConstraint.constant = fat.width
dropView.layer?.borderColor = NSColor.dropViewHoveringColor().CGColor
case .Accepted:
dropView.layer?.borderWidth = fat.border
heightConstraint.constant = fat.width
widthConstraint.constant = fat.width
dropView.layer?.borderColor = NSColor.dropViewAcceptedColor().CGColor
dropView.layer?.backgroundColor = NSColor.whiteColor().CGColor
well.hidden = true
dropImageView.image = self.viewModel.systemImageForCurrentPath()
case .None:
dropView.layer?.borderWidth = thin.border
heightConstraint.constant = thin.width
widthConstraint.constant = thin.width
dropView.layer?.borderColor = NSColor(calibratedRed: 0.652 , green: 0.673, blue: 0.696, alpha: 1).CGColor
dropView.layer?.backgroundColor = NSColor.clearColor().CGColor
well.hidden = false
dropImageView.image = nil
case .Rejected:
dropView.layer?.borderWidth = fat.border
heightConstraint.constant = fat.width
widthConstraint.constant = fat.width
dropView.layer?.borderColor = NSColor.dropViewRejectedColor().CGColor
}
}
}
// MARK:- DropView drag delegate
extension ImagesDropViewController: DropViewDelegate {
func dropViewDidDragFileOutOfView(dropView: DropView) {
viewModel.isCurrentSelectionValid() ? layoutUI(.Accepted) : layoutUI(.None)
}
func dropViewDidDragInvalidFileIntoView(dropView: DropView) {
layoutUI(.Rejected)
let anim = CABasicAnimation.shakeAnimation(magnitude: 10)
view.layer?.addAnimation(anim, forKey: "x")
}
func dropViewDidDragValidFileIntoView(dropView: DropView) {
layoutUI(.Hovering)
}
func dropViewDidDropFileToView(dropView: DropView, paths: [Path]) {
viewModel.newPathSelected(paths)
}
func dropViewShouldAcceptDraggedPath(dropView: DropView, paths: [Path]) -> Bool {
return viewModel.shouldAcceptSelection(paths)
}
func dropViewNumberOfAcceptableItems(dropView: DropView, items: [Path]) -> Int {
return viewModel.acceptableItemsOfSelection(items)
}
}
// MARK:- DropView mouse delegate
extension ImagesDropViewController: DropViewMouseDelegate {
func dropViewDidRightClick(dropView: DropView, event: NSEvent) {
let enabled = viewModel.isCurrentSelectionValid()
let reveal = NSMenuItem(title: "Show in Finder", action:Selector("revealMenuPressed"), keyEquivalent: "")
reveal.enabled = enabled
let clear = NSMenuItem(title: "Clear Selection", action: Selector("clearMenuPressed"), keyEquivalent: "")
clear.enabled = enabled
let menu = NSMenu(title: "Asset Generator")
menu.autoenablesItems = false
menu.insertItem(reveal, atIndex: 0)
menu.insertItem(clear, atIndex: 1)
NSMenu.popUpContextMenu(menu, withEvent: event, forView: self.view)
}
func clearMenuPressed() {
viewModel.clearSelection()
}
func revealMenuPressed() {
let items = viewModel.urlRepresentation()
NSWorkspace.sharedWorkspace().activateFileViewerSelectingURLs(items)
}
} | a797a51275ecfc3c222251b75b5ec012 | 33.526667 | 117 | 0.652955 | false | false | false | false |
devpunk/velvet_room | refs/heads/master | Source/Model/Vita/MVitaLinkFactory.swift | mit | 1 | import Foundation
import CocoaAsyncSocket
extension MVitaLink
{
private static let kStatusStrategyMap:[
MVitaPtpLocalStatus:
MVitaLinkStrategySendLocalStatus.Type] = [
MVitaPtpLocalStatus.connection:
MVitaLinkStrategySendLocalStatusConnection.self,
MVitaPtpLocalStatus.connectionEnd:
MVitaLinkStrategySendLocalStatusConnectionEnd.self]
private static let kCommandQueueLabel:String = "velvetRoom.vitaLink.socketCommand"
private static let kEventQueueLabel:String = "velvetRoom.vitaLink.socketEvent"
//MARK: private
private class func factoryCommandQueue() -> DispatchQueue
{
let queue = DispatchQueue(
label:kCommandQueueLabel,
qos:DispatchQoS.background,
attributes:DispatchQueue.Attributes(),
autoreleaseFrequency:
DispatchQueue.AutoreleaseFrequency.inherit,
target:DispatchQueue.global(
qos:DispatchQoS.QoSClass.background))
return queue
}
private class func factoryEventQueue() -> DispatchQueue
{
let queue = DispatchQueue(
label:kEventQueueLabel,
qos:DispatchQoS.background,
attributes:DispatchQueue.Attributes(),
autoreleaseFrequency:
DispatchQueue.AutoreleaseFrequency.inherit,
target:DispatchQueue.global(
qos:DispatchQoS.QoSClass.background))
return queue
}
//MARK: internal
class func factorySocketCommand() -> MVitaLinkSocketCommand
{
let delegate:MVitaLinkSocketCommandDelegate = MVitaLinkSocketCommandDelegate()
let queue:DispatchQueue = factoryCommandQueue()
let socket:GCDAsyncSocket = GCDAsyncSocket(
delegate:delegate,
delegateQueue:queue,
socketQueue:queue)
let linkCommand:MVitaLinkSocketCommand = MVitaLinkSocketCommand(
socket:socket,
delegate:delegate,
queue:queue)
delegate.model = linkCommand
return linkCommand
}
class func factorySocketEvent() -> MVitaLinkSocketEvent
{
let delegate:MVitaLinkSocketEventDelegate = MVitaLinkSocketEventDelegate()
let queue:DispatchQueue = factoryEventQueue()
let socket:GCDAsyncSocket = GCDAsyncSocket(
delegate:delegate,
delegateQueue:queue,
socketQueue:queue)
let linkEvent:MVitaLinkSocketEvent = MVitaLinkSocketEvent(
socket:socket,
delegate:delegate,
queue:queue)
delegate.model = linkEvent
return linkEvent
}
class func factoryStrategyStatus(
status:MVitaPtpLocalStatus) -> MVitaLinkStrategySendLocalStatus.Type
{
guard
let strategy:MVitaLinkStrategySendLocalStatus.Type = kStatusStrategyMap[
status]
else
{
return MVitaLinkStrategySendLocalStatus.self
}
return strategy
}
class func factoryDispatchGroup() -> DispatchGroup
{
let dispatchGroup:DispatchGroup = DispatchGroup()
dispatchGroup.setTarget(
queue:DispatchQueue.global(
qos:DispatchQoS.QoSClass.background))
return dispatchGroup
}
}
| 2c225499bcc6341f24f997db426676c5 | 30.290909 | 86 | 0.631028 | false | false | false | false |
qinting513/Learning-QT | refs/heads/master | 2016 Plan/5月/数据持久化/CoreDataSw/CoreDataSw/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// CoreDataSw
//
// Created by Qinting on 16/5/9.
// Copyright © 2016年 Qinting. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
var context : NSManagedObjectContext?
override func viewDidLoad() {
super.viewDidLoad()
let context = NSManagedObjectContext.init()
let model = NSManagedObjectModel.mergedModelFromBundles(nil)
let docPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last
let sqlPath = docPath?.stringByAppendingString("/company.sqlite")
let store = NSPersistentStoreCoordinator.init(managedObjectModel: model!)
let url = NSURL.fileURLWithPath(sqlPath!)
do {
try store.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch _ {
}
context.persistentStoreCoordinator = store
self.context = context
}
@IBAction func insertData(sender: AnyObject) {
let emp = NSEntityDescription.insertNewObjectForEntityForName("Employee", inManagedObjectContext: context!) as! Employee
emp.name = "zhangsan"
emp.age = 126
do{
try context!.save()
print("成功插入")
} catch let error as NSError {
print(error)
}
}
@IBAction func queryData(sender: AnyObject) {
let fetch = NSFetchRequest.init(entityName: "Employee")
do {
let emps : [AnyObject] = try context!.executeFetchRequest(fetch)
for emp in emps as! [Employee] {
print("name:\(emp.name!) age: \(emp.age!)")
}
}catch let error as NSError {
print("error:\( error)")
}
}
}
| ead38bc28633db0780e9d82f3dfe4e6b | 27.169231 | 128 | 0.614418 | false | false | false | false |
weby/PathKit | refs/heads/master | Sources/PathKit.swift | bsd-2-clause | 1 | // PathKit - Effortless path operations
#if os(Linux)
import Glibc
let system_glob = Glibc.glob
#else
import Darwin
let system_glob = Darwin.glob
#endif
import Foundation
#if !swift(>=3.0)
typealias Collection = CollectionType
typealias Sequence = SequenceType
typealias IteratorProtocol = GeneratorType
#endif
/// Represents a filesystem path.
public struct Path {
/// The character used by the OS to separate two path elements
public static let separator = "/"
/// The underlying string representation
internal var path: String
#if os(OSX)
internal static var fileManager = NSFileManager.default()
#else
internal static var fileManager = NSFileManager.defaultManager()
#endif
// MARK: Init
public init() {
self.path = ""
}
/// Create a Path from a given String
public init(_ path: String) {
self.path = path
}
/// Create a Path by joining multiple path components together
#if !swift(>=3.0)
public init<S : Collection where S.Generator.Element == String>(components: S) {
if components.isEmpty {
path = "."
} else if components.first == Path.separator && components.count > 1 {
let p = components.joinWithSeparator(Path.separator)
#if os(Linux)
let index = p.startIndex.distanceTo(p.startIndex.successor())
path = NSString(string: p).substringFromIndex(index)
#else
path = p.substringFromIndex(p.startIndex.successor())
#endif
} else {
path = components.joinWithSeparator(Path.separator)
}
}
#else
public init<S : Collection where S.Iterator.Element == String>(components: S) {
if components.isEmpty {
path = "."
} else if components.first == Path.separator && components.count > 1 {
let p = components.joined(separator: Path.separator)
path = p.substring(from: p.index(after: p.startIndex))
} else {
path = components.joined(separator: Path.separator)
}
}
#endif
}
// MARK: StringLiteralConvertible
extension Path : StringLiteralConvertible {
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public typealias UnicodeScalarLiteralType = StringLiteralType
public init(extendedGraphemeClusterLiteral path: StringLiteralType) {
self.init(stringLiteral: path)
}
public init(unicodeScalarLiteral path: StringLiteralType) {
self.init(stringLiteral: path)
}
public init(stringLiteral value: StringLiteralType) {
self.path = value
}
}
// MARK: CustomStringConvertible
extension Path : CustomStringConvertible {
public var description: String {
return self.path
}
}
// MARK: Hashable
extension Path : Hashable {
public var hashValue: Int {
return path.hashValue
}
}
// MARK: Path Info
extension Path {
/// Test whether a path is absolute.
///
/// - Returns: `true` iff the path begings with a slash
///
public var isAbsolute: Bool {
return path.hasPrefix(Path.separator)
}
/// Test whether a path is relative.
///
/// - Returns: `true` iff a path is relative (not absolute)
///
public var isRelative: Bool {
return !isAbsolute
}
/// Concatenates relative paths to the current directory and derives the normalized path
///
/// - Returns: the absolute path in the actual filesystem
///
public func absolute() -> Path {
if isAbsolute {
return normalize()
}
return (Path.current + self).normalize()
}
/// Normalizes the path, this cleans up redundant ".." and ".", double slashes
/// and resolves "~".
///
/// - Returns: a new path made by removing extraneous path components from the underlying String
/// representation.
///
public func normalize() -> Path {
#if !swift(>=3.0)
return Path(NSString(string: self.path).stringByStandardizingPath)
#else
#if os(Linux)
return Path(NSString(string: self.path).stringByStandardizingPath)
#else
return Path(NSString(string: self.path).standardizingPath)
#endif
#endif
}
/// De-normalizes the path, by replacing the current user home directory with "~".
///
/// - Returns: a new path made by removing extraneous path components from the underlying String
/// representation.
///
public func abbreviate() -> Path {
#if os(Linux)
// TODO: actually de-normalize the path
return self
#else
#if !swift(>=3.0)
return Path(NSString(string: self.path).stringByAbbreviatingWithTildeInPath)
#else
return Path(NSString(string: self.path).abbreviatingWithTildeInPath)
#endif
#endif
}
/// Returns the path of the item pointed to by a symbolic link.
///
/// - Returns: the path of directory or file to which the symbolic link refers
///
public func symlinkDestination() throws -> Path {
let symlinkDestination = try Path.fileManager.destinationOfSymbolicLink(atPath:path)
let symlinkPath = Path(symlinkDestination)
if symlinkPath.isRelative {
return self + ".." + symlinkPath
} else {
return symlinkPath
}
}
}
// MARK: Path Components
extension Path {
/// The last path component
///
/// - Returns: the last path component
///
public var lastComponent: String {
return NSString(string: path).lastPathComponent
}
/// The last path component without file extension
///
/// - Note: This returns "." for "..".
///
/// - Returns: the last path component without file extension
///
public var lastComponentWithoutExtension: String {
#if !swift(>=3.0)
return NSString(string: lastComponent).stringByDeletingPathExtension
#else
#if os(Linux)
return NSString(string: lastComponent).stringByDeletingPathExtension
#else
return NSString(string: lastComponent).deletingPathExtension
#endif
#endif
}
/// Splits the string representation on the directory separator.
/// Absolute paths remain the leading slash as first component.
///
/// - Returns: all path components
///
public var components: [String] {
return NSString(string: path).pathComponents
}
/// The file extension behind the last dot of the last component.
///
/// - Returns: the file extension
///
public var `extension`: String? {
let pathExtension = NSString(string: path).pathExtension
if pathExtension.isEmpty {
return nil
}
return pathExtension
}
}
// MARK: File Info
extension Path {
/// Test whether a file or directory exists at a specified path
///
/// - Returns: `false` iff the path doesn't exist on disk or its existence could not be
/// determined
///
public var exists: Bool {
return Path.fileManager.fileExists(atPath:self.path)
}
/// Test whether a path is a directory.
///
/// - Returns: `true` if the path is a directory or a symbolic link that points to a directory;
/// `false` if the path is not a directory or the path doesn't exist on disk or its existence
/// could not be determined
///
public var isDirectory: Bool {
var directory = ObjCBool(false)
guard Path.fileManager.fileExists(atPath: normalize().path, isDirectory: &directory) else {
return false
}
return directory.boolValue
}
/// Test whether a path is a regular file.
///
/// - Returns: `true` if the path is neither a directory nor a symbolic link that points to a
/// directory; `false` if the path is a directory or a symbolic link that points to a
/// directory or the path doesn't exist on disk or its existence
/// could not be determined
///
public var isFile: Bool {
var directory = ObjCBool(false)
guard Path.fileManager.fileExists(atPath: normalize().path, isDirectory: &directory) else {
return false
}
return !directory.boolValue
}
/// Test whether a path is a symbolic link.
///
/// - Returns: `true` if the path is a symbolic link; `false` if the path doesn't exist on disk
/// or its existence could not be determined
///
public var isSymlink: Bool {
do {
let _ = try Path.fileManager.destinationOfSymbolicLink(atPath: path)
return true
} catch {
return false
}
}
/// Test whether a path is readable
///
/// - Returns: `true` if the current process has read privileges for the file at path;
/// otherwise `false` if the process does not have read privileges or the existence of the
/// file could not be determined.
///
public var isReadable: Bool {
return Path.fileManager.isReadableFile(atPath: self.path)
}
/// Test whether a path is writeable
///
/// - Returns: `true` if the current process has write privileges for the file at path;
/// otherwise `false` if the process does not have write privileges or the existence of the
/// file could not be determined.
///
public var isWritable: Bool {
return Path.fileManager.isWritableFile(atPath: self.path)
}
/// Test whether a path is executable
///
/// - Returns: `true` if the current process has execute privileges for the file at path;
/// otherwise `false` if the process does not have execute privileges or the existence of the
/// file could not be determined.
///
public var isExecutable: Bool {
return Path.fileManager.isExecutableFile(atPath: self.path)
}
/// Test whether a path is deletable
///
/// - Returns: `true` if the current process has delete privileges for the file at path;
/// otherwise `false` if the process does not have delete privileges or the existence of the
/// file could not be determined.
///
public var isDeletable: Bool {
return Path.fileManager.isDeletableFile(atPath: self.path)
}
}
// MARK: File Manipulation
extension Path {
/// Create the directory.
///
/// - Note: This method fails if any of the intermediate parent directories does not exist.
/// This method also fails if any of the intermediate path elements corresponds to a file and
/// not a directory.
///
public func mkdir() throws -> () {
try Path.fileManager.createDirectory(atPath: self.path, withIntermediateDirectories: false, attributes: nil)
}
/// Create the directory and any intermediate parent directories that do not exist.
///
/// - Note: This method fails if any of the intermediate path elements corresponds to a file and
/// not a directory.
///
public func mkpath() throws -> () {
try Path.fileManager.createDirectory(atPath: self.path, withIntermediateDirectories: true, attributes: nil)
}
/// Delete the file or directory.
///
/// - Note: If the path specifies a directory, the contents of that directory are recursively
/// removed.
///
public func delete() throws -> () {
try Path.fileManager.removeItem(atPath: self.path)
}
/// Move the file or directory to a new location synchronously.
///
/// - Parameter destination: The new path. This path must include the name of the file or
/// directory in its new location.
///
public func move(destination: Path) throws -> () {
try Path.fileManager.moveItem(atPath: self.path, toPath: destination.path)
}
/// Copy the file or directory to a new location synchronously.
///
/// - Parameter destination: The new path. This path must include the name of the file or
/// directory in its new location.
///
public func copy(destination: Path) throws -> () {
try Path.fileManager.copyItem(atPath: self.path, toPath: destination.path)
}
/// Creates a hard link at a new destination.
///
/// - Parameter destination: The location where the link will be created.
///
public func link(destination: Path) throws -> () {
try Path.fileManager.linkItem(atPath: self.path, toPath: destination.path)
}
/// Creates a symbolic link at a new destination.
///
/// - Parameter destintation: The location where the link will be created.
///
public func symlink(destination: Path) throws -> () {
try Path.fileManager.createSymbolicLink(atPath: self.path, withDestinationPath: destination.path)
}
}
// MARK: Current Directory
extension Path {
/// The current working directory of the process
///
/// - Returns: the current working directory of the process
///
public static var current: Path {
get {
return self.init(Path.fileManager.currentDirectoryPath)
}
set {
Path.fileManager.changeCurrentDirectoryPath(newValue.description)
}
}
/// Changes the current working directory of the process to the path during the execution of the
/// given block.
///
/// - Note: The original working directory is restored when the block returns or throws.
/// - Parameter closure: A closure to be executed while the current directory is configured to
/// the path.
///
public func chdir(closure: @noescape () throws -> ()) rethrows {
let previous = Path.current
Path.current = self
defer { Path.current = previous }
try closure()
}
}
// MARK: Temporary
extension Path {
/// - Returns: the path to either the user’s or application’s home directory,
/// depending on the platform.
///
public static var home: Path {
#if os(Linux)
return Path(NSProcessInfo.processInfo().environment["HOME"] ?? "/")
#else
return Path(NSHomeDirectory())
#endif
}
/// - Returns: the path of the temporary directory for the current user.
///
public static var temporary: Path {
#if os(Linux)
return Path(NSProcessInfo.processInfo().environment["TMP"] ?? "/tmp")
#else
return Path(NSTemporaryDirectory())
#endif
}
/// - Returns: the path of a temporary directory unique for the process.
/// - Note: Based on `NSProcessInfo.globallyUniqueString`.
///
public static func processUniqueTemporary() throws -> Path {
let path = temporary + NSProcessInfo.processInfo().globallyUniqueString
if !path.exists {
try path.mkdir()
}
return path
}
/// - Returns: the path of a temporary directory unique for each call.
/// - Note: Based on `NSUUID`.
///
public static func uniqueTemporary() throws -> Path {
#if !swift(>=3.0)
let path = try processUniqueTemporary() + NSUUID().UUIDString
#else
#if os(Linux)
let path = try processUniqueTemporary() + NSUUID().UUIDString
#else
let path = try processUniqueTemporary() + NSUUID().uuidString
#endif
#endif
try path.mkdir()
return path
}
}
// MARK: Contents
extension Path {
/// Reads the file.
///
/// - Returns: the contents of the file at the specified path.
///
public func read() throws -> NSData {
return try NSData(contentsOfFile: path, options: NSDataReadingOptions(rawValue: 0))
}
/// Reads the file contents and encoded its bytes to string applying the given encoding.
///
/// - Parameter encoding: the encoding which should be used to decode the data.
/// (by default: `NSUTF8StringEncoding`)
///
/// - Returns: the contents of the file at the specified path as string.
///
public func read(encoding: NSStringEncoding = NSUTF8StringEncoding) throws -> String {
return try NSString(contentsOfFile: path, encoding: encoding).substring(from: 0) as String
}
/// Write a file.
///
/// - Note: Works atomically: the data is written to a backup file, and then — assuming no
/// errors occur — the backup file is renamed to the name specified by path.
///
/// - Parameter data: the contents to write to file.
///
public func write(data: NSData) throws {
try data.write(toFile:normalize().path, options: .dataWritingAtomic)
}
/// Reads the file.
///
/// - Note: Works atomically: the data is written to a backup file, and then — assuming no
/// errors occur — the backup file is renamed to the name specified by path.
///
/// - Parameter string: the string to write to file.
///
/// - Parameter encoding: the encoding which should be used to represent the string as bytes.
/// (by default: `NSUTF8StringEncoding`)
///
/// - Returns: the contents of the file at the specified path as string.
///
public func write(string: String, encoding: NSStringEncoding = NSUTF8StringEncoding) throws {
try NSString(string: string).write(toFile: normalize().path, atomically: true, encoding: encoding)
}
}
// MARK: Traversing
extension Path {
/// Get the parent directory
///
/// - Returns: the normalized path of the parent directory
///
public func parent() -> Path {
return self + ".."
}
/// Performs a shallow enumeration in a directory
///
/// - Returns: paths to all files, directories and symbolic links contained in the directory
///
public func children() throws -> [Path] {
return try Path.fileManager.contentsOfDirectory(atPath:path).map {
self + Path($0)
}
}
/// Performs a deep enumeration in a directory
///
/// - Returns: paths to all files, directories and symbolic links contained in the directory or
/// any subdirectory.
///
public func recursiveChildren() throws -> [Path] {
return try Path.fileManager.subpathsOfDirectory(atPath:path).map {
self + Path($0)
}
}
}
// MARK: Globbing
extension Path {
public static func glob(pattern: String) -> [Path] {
var gt = glob_t()
let cPattern = strdup(pattern)
defer {
globfree(>)
free(cPattern)
}
let flags = GLOB_TILDE | GLOB_BRACE | GLOB_MARK
if system_glob(cPattern, flags, nil, >) == 0 {
#if os(Linux)
let matchc = gt.gl_pathc
#else
let matchc = gt.gl_matchc
#endif
#if !swift(>=3.0)
return (0..<Int(matchc)).flatMap { index in
if let path = String.fromCString(gt.gl_pathv[index]) {
return Path(path)
}
return nil
}
#else
return (0..<Int(matchc)).flatMap { index in
if let path = String(validatingUTF8: gt.gl_pathv[index]!) {
return Path(path)
}
return nil
}
#endif
}
// GLOB_NOMATCH
return []
}
public func glob(pattern: String) -> [Path] {
return Path.glob(pattern: (self + pattern).description)
}
}
// MARK: SequenceType
extension Path : Sequence {
/// Enumerates the contents of a directory, returning the paths of all files and directories
/// contained within that directory. These paths are relative to the directory.
public struct DirectoryEnumerator : IteratorProtocol {
public typealias Element = Path
let path: Path
let directoryEnumerator: NSDirectoryEnumerator
init(path: Path) {
self.path = path
self.directoryEnumerator = Path.fileManager.enumerator(atPath:path.path)!
}
public func next() -> Path? {
if let next = directoryEnumerator.nextObject() as! String? {
return path + next
}
return nil
}
/// Skip recursion into the most recently obtained subdirectory.
public func skipDescendants() {
directoryEnumerator.skipDescendants()
}
}
/// Perform a deep enumeration of a directory.
///
/// - Returns: a directory enumerator that can be used to perform a deep enumeration of the
/// directory.
///
#if !swift(>=3.0)
public func generate() -> DirectoryEnumerator {
return DirectoryEnumerator(path: self)
}
#else
public func makeIterator() -> DirectoryEnumerator {
return DirectoryEnumerator(path: self)
}
#endif
}
// MARK: Equatable
extension Path : Equatable {}
/// Determines if two paths are identical
///
/// - Note: The comparison is string-based. Be aware that two different paths (foo.txt and
/// ./foo.txt) can refer to the same file.
///
public func ==(lhs: Path, rhs: Path) -> Bool {
return lhs.path == rhs.path
}
// MARK: Pattern Matching
/// Implements pattern-matching for paths.
///
/// - Returns: `true` iff one of the following conditions is true:
/// - the paths are equal (based on `Path`'s `Equatable` implementation)
/// - the paths can be normalized to equal Paths.
///
public func ~=(lhs: Path, rhs: Path) -> Bool {
return lhs == rhs
|| lhs.normalize() == rhs.normalize()
}
// MARK: Comparable
extension Path : Comparable {}
/// Defines a strict total order over Paths based on their underlying string representation.
public func <(lhs: Path, rhs: Path) -> Bool {
return lhs.path < rhs.path
}
// MARK: Operators
/// Appends a Path fragment to another Path to produce a new Path
public func +(lhs: Path, rhs: Path) -> Path {
return lhs.path + rhs.path
}
/// Appends a String fragment to another Path to produce a new Path
public func +(lhs: Path, rhs: String) -> Path {
return lhs.path + rhs
}
/// Appends a String fragment to another String to produce a new Path
internal func +(lhs: String, rhs: String) -> Path {
if rhs.hasPrefix(Path.separator) {
// Absolute paths replace relative paths
return Path(rhs)
} else {
var lSlice = NSString(string: lhs).pathComponents.fullSlice
var rSlice = NSString(string: rhs).pathComponents.fullSlice
// Get rid of trailing "/" at the left side
if lSlice.count > 1 && lSlice.last == Path.separator {
lSlice.removeLast()
}
// Advance after the first relevant "."
lSlice = lSlice.filter { $0 != "." }.fullSlice
rSlice = rSlice.filter { $0 != "." }.fullSlice
// Eats up trailing components of the left and leading ".." of the right side
while lSlice.last != ".." && rSlice.first == ".." {
if (lSlice.count > 1 || lSlice.first != Path.separator) && !lSlice.isEmpty {
// A leading "/" is never popped
lSlice.removeLast()
}
if !rSlice.isEmpty {
rSlice.removeFirst()
}
switch (lSlice.isEmpty, rSlice.isEmpty) {
case (true, _):
break
case (_, true):
break
default:
continue
}
}
return Path(components: lSlice + rSlice)
}
}
extension Array {
var fullSlice: ArraySlice<Element> {
return self[0..<self.endIndex]
}
}
| 052719a7bf82c427a36e98555bf32a5e | 27.029487 | 112 | 0.66656 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | refs/heads/master | Solutions/SolutionsTests/Medium/Medium_064_Minimum_Path_Sum_Test.swift | mit | 1 | //
// Medium_064_Minimum_Path_Sum_Test.swift
// Solutions
//
// Created by Di Wu on 7/10/15.
// Copyright © 2015 diwu. All rights reserved.
//
import XCTest
class Medium_064_Minimum_Path_Sum_Test: XCTestCase, SolutionsTestCase {
func test_001() {
let input: [[Int]] = [
[0,0,0],
[0,1,0],
[0,0,0]
]
let expected: Int = 0
asyncHelper(input: input, expected: expected)
}
func test_002() {
let input: [[Int]] = [
]
let expected: Int = 0
asyncHelper(input: input, expected: expected)
}
func test_003() {
let input: [[Int]] = [
[0,0,2],
[0,1,0],
[2,0,0]
]
let expected: Int = 1
asyncHelper(input: input, expected: expected)
}
func test_004() {
let input: [[Int]] = [
[1,5,2],
[4,1,6],
[2,0,0],
[2,5,0]
]
let expected: Int = 6
asyncHelper(input: input, expected: expected)
}
func test_005() {
let input: [[Int]] = [
[1,5,2,3],
[4,1,6,1],
[2,0,3,0],
[2,5,0,3]
]
let expected: Int = 12
asyncHelper(input: input, expected: expected)
}
private func asyncHelper(input: [[Int]], expected: Int) {
weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
serialQueue().async(execute: { () -> Void in
let result = Medium_064_Minimum_Path_Sum.minPathSum(input)
assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
if let unwrapped = expectation {
unwrapped.fulfill()
}
})
waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
if error != nil {
assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
}
}
}
}
| 3442c219109dcdc977b1f694ae0aa298 | 28.577465 | 138 | 0.510476 | false | true | false | false |
sschiau/swift-package-manager | refs/heads/master | Sources/PackageLoading/ToolsVersionLoader.swift | apache-2.0 | 1 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import PackageModel
import Utility
import Foundation
/// Protocol for the manifest loader interface.
public protocol ToolsVersionLoaderProtocol {
/// Load the tools version at the give package path.
///
/// - Parameters:
/// - path: The path to the package.
/// - fileSystem: The file system to use to read the file which contains tools version.
/// - Returns: The tools version.
/// - Throws: ToolsVersion.Error
func load(at path: AbsolutePath, fileSystem: FileSystem) throws -> ToolsVersion
}
public class ToolsVersionLoader: ToolsVersionLoaderProtocol {
public init() {
}
public enum Error: Swift.Error, CustomStringConvertible {
case malformed(specifier: String, file: AbsolutePath)
public var description: String {
switch self {
case .malformed(let versionSpecifier, let file):
return "the version specifier '\(versionSpecifier)' in '\(file.asString)' is not valid"
}
}
}
public func load(at path: AbsolutePath, fileSystem: FileSystem) throws -> ToolsVersion {
// The file which contains the tools version.
let file = Manifest.path(atPackagePath: path, fileSystem: fileSystem)
guard fileSystem.isFile(file) else {
// FIXME: We should return an error from here but Workspace tests rely on this in order to work.
// This doesn't really cause issues (yet) in practice though.
return ToolsVersion.currentToolsVersion
}
// FIXME: We don't need the entire file, just the first line.
let contents = try fileSystem.readFileContents(file)
// Get the version specifier string from tools version file.
guard let versionSpecifier = ToolsVersionLoader.split(contents).versionSpecifier else {
// Try to diagnose if there is a misspelling of the swift-tools-version comment.
let splitted = contents.contents.split(
separator: UInt8(ascii: "\n"),
maxSplits: 1,
omittingEmptySubsequences: false)
let misspellings = ["swift-tool", "tool-version"]
if let firstLine = ByteString(splitted[0]).asString,
misspellings.first(where: firstLine.lowercased().contains) != nil {
throw Error.malformed(specifier: firstLine, file: file)
}
// Otherwise assume the default to be v3.
return .v3
}
// Ensure we can construct the version from the specifier.
guard let version = ToolsVersion(string: versionSpecifier) else {
throw Error.malformed(specifier: versionSpecifier, file: file)
}
return version
}
/// Splits the bytes to the version specifier (if present) and rest of the contents.
public static func split(_ bytes: ByteString) -> (versionSpecifier: String?, rest: [UInt8]) {
let splitted = bytes.contents.split(
separator: UInt8(ascii: "\n"),
maxSplits: 1,
omittingEmptySubsequences: false)
// Try to match our regex and see if a valid specifier line.
guard let firstLine = ByteString(splitted[0]).asString,
let match = ToolsVersionLoader.regex.firstMatch(
in: firstLine, options: [], range: NSRange(location: 0, length: firstLine.count)),
match.numberOfRanges >= 2 else {
return (nil, bytes.contents)
}
let versionSpecifier = NSString(string: firstLine).substring(with: match.range(at: 1))
// FIXME: We can probably optimize here and return array slice.
return (versionSpecifier, splitted.count == 1 ? [] : Array(splitted[1]))
}
// The regex to match swift tools version specification:
// * It should start with `//` followed by any amount of whitespace.
// * Following that it should contain the case insensitive string `swift-tools-version:`.
// * The text between the above string and `;` or string end becomes the tools version specifier.
static let regex = try! NSRegularExpression(
pattern: "^// swift-tools-version:(.*?)(?:;.*|$)",
options: [.caseInsensitive])
}
| fe760661d221d15f0043a8fd91afd4b8 | 42.778846 | 108 | 0.65056 | false | false | false | false |
rdhiggins/PythonMacros | refs/heads/master | PythonMacros/PythonCaptureOutput.swift | mit | 1 | //
// PythonCaptureOutput.swift
// MIT License
//
// Copyright (c) 2016 Spazstik Software, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
/// A class that is used to capture the output streams from CPython. It loads
/// the capture_output.py script and executes it. This script creates two
/// python objects that capture standard out and standard error.
///
/// The refreshOutput is called after CPython executes something. The Python
/// objects a queryied for any text, which is then appended to the stdOutput or
/// stdError buffers.
class PythonCaptureOutput {
fileprivate let kValueKey = "value"
fileprivate let kCaptureScriptName = "capture_output"
fileprivate let kPythonStandardOutputName = "standardOutput"
fileprivate let kPythonStandardErrorName = "standardError"
fileprivate var module: PythonObject?
fileprivate var standardOutput: PythonObject?
fileprivate var standardError: PythonObject?
fileprivate var engine: PythonMacroEngine!
/// Property that contains the standard output from CPython
var stdOutput: String = String("")
/// Property that contains the standard error output from CPython
var stdError: String = String("")
/// Initialization method that is called by PythonMacroEngine during
/// it's initialization process.
///
/// - parameter module: A PythonObject reference to the __main__ module.
/// - parameter engine: A PythonMacroEngine reference used by the new object
/// to monitor.
init(module: PythonObject, engine: PythonMacroEngine) {
self.engine = engine
self.module = module
loadCaptureScript()
}
deinit {
module = nil
standardOutput = nil
standardError = nil
}
/// Method used to query the Python objects used to capture the streams.
func refreshOutput() {
refreshChannel(standardOutput!, channel: &stdOutput)
refreshChannel(standardError!, channel: &stdError)
}
/// Method used to clear the stdOutput and stdError buffers
func clearBuffers() {
stdOutput = ""
stdError = ""
}
/// A private method used to query a Python object for the captured output.
/// The PythonObject reference to the particular python channel. The Python
/// object's captured output is then cleared.
///
/// - parameter object: A PythonObject reference to the python object used
/// to capture the stream output.
/// - parameter channel: The String buffer to append any new output to.
fileprivate func refreshChannel(_ object: PythonObject, channel: inout String) {
// This queries the python object for its new content
guard let output = object.getAttrString(kValueKey) else {
return
}
// content is appended to the buffer
channel += output
// This clears the python objects content
object.setAttrString(kValueKey, value: "")
}
/// A private method that performs the setup for capturing the streams
/// from CPython. It first loads the capture_python.py script from the
/// applications resource bundle and then executes it in the CPython
/// runtime.
///
/// The two python objects are then looked up and references
/// are stored so the the stream output can be queried.
fileprivate func loadCaptureScript() {
guard let module = self.module,
let captureScript = PythonScriptDirectory.sharedInstance.load(kCaptureScriptName, location: .resource) else {
print("No module reference")
fatalError()
}
if captureScript.run(engine) {
// Get a reference to the python objects used to capture the
// output streams.
standardOutput = module.getAttr(kPythonStandardOutputName)
standardError = module.getAttr(kPythonStandardErrorName)
}
}
}
/// Extension used to provide description and debug description string
extension PythonCaptureOutput: CustomStringConvertible, CustomDebugStringConvertible {
var description: String {
return customDescription()
}
var debugDescription: String {
return
"PythonCaptureOutput {\n" +
" module: \(module.debugDescription)\n" +
" std_out: \(standardOutput.debugDescription)\n" +
" std_err: \(standardError.debugDescription)\n" +
"}"
}
fileprivate func customDescription() -> String {
return "Python StandardOutput: \(stdOutput)\nPython StandardError: \(stdError)\n"
}
}
| 91310afd9f795e293943519e3f7d3174 | 35.433962 | 121 | 0.674953 | false | false | false | false |
lingyijie/DYZB | refs/heads/master | DYZB/DYZB/Class/Home/View/GameRecommendView.swift | mit | 1 | //
// GameRecommendView.swift
// DYZB
//
// Created by ling yijie on 2017/9/15.
// Copyright © 2017年 ling yijie. All rights reserved.
//
import UIKit
fileprivate let kCollectionCellID = "kCollectionCellID"
fileprivate let kNumberOfSections = 2
fileprivate let kNumberOfItemsInSection = 8
class GameRecommendView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
var groups : [AnchorModelGroup]? {
didSet {
if groups == nil {return}
// 移除“热门”
groups?.removeFirst()
// 添加“更多”图标,一共16组数据
let group : AnchorModelGroup = AnchorModelGroup()
group.tag_name = "更多"
group.icon_url = ""
groups?.append(group)
//
pageControl.numberOfPages = kNumberOfSections
// 展示数据
collectionView.reloadData()
}
}
override func awakeFromNib() {
autoresizingMask = UIViewAutoresizing(rawValue: 0)
collectionView.register(UINib(nibName: "CollectionViewGameCell", bundle: nil), forCellWithReuseIdentifier: kCollectionCellID)
}
}
// 快速创建类方法
extension GameRecommendView {
class func gameRecommendView() -> GameRecommendView {
let gameRecommendView = Bundle.main.loadNibNamed("GameRecommendView", owner: nil, options: nil)?.first as! GameRecommendView
return gameRecommendView
}
}
// 遵守collection数据源协议、代理协议
extension GameRecommendView : UICollectionViewDataSource,UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return kNumberOfSections
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return kNumberOfItemsInSection
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCollectionCellID, for: indexPath) as! CollectionViewGameCell
cell.group = groups?[indexPath.item + indexPath.section * kNumberOfItemsInSection]
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x
pageControl.currentPage = Int(offsetX / scrollView.bounds.width)
}
}
| 8cbea448face75fe7b158dca767c3f1b | 32.873239 | 136 | 0.686071 | false | false | false | false |
IBM-Swift/Kitura | refs/heads/master | Sources/Kitura/RouterMiddlewareWalker.swift | apache-2.0 | 1 | /*
* Copyright IBM Corporation 2016
*
* 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 LoggerAPI
// MARK: RouterMiddlewareWalker
class RouterMiddlewareWalker {
/// The array of middlewares to handle
private let middlewares: [RouterMiddleware]
/// The current router method
private let method: RouterMethod
/// The current router request
private let request: RouterRequest
/// The current router response
private let response: RouterResponse
/// Callback to call once all middlewares have been handled
private let callback: () -> Void
/// Index of the current middleware being handled
private var middlewareIndex = -1
/// Copy of request parameters to enable mergeParams
private let parameters: [String: String]
init(middlewares: [RouterMiddleware], method: RouterMethod, request: RouterRequest, response: RouterResponse, callback: @escaping () -> Void) {
self.middlewares = middlewares
self.method = method
self.request = request
self.response = response
self.callback = callback
self.parameters = request.parameters
}
/// Handle the next middleware
func next() {
middlewareIndex += 1
if middlewareIndex < middlewares.count && (response.error == nil || method == .error) {
do {
let closure = middlewareIndex == middlewares.count-1 ? callback : {
// Purposefully capture self here
self.next()
}
// reset parameters before processing next middleware
request.parameters = parameters
try middlewares[middlewareIndex].handle(request: request, response: response, next: closure)
} catch {
response.error = error
// print error logs before the callback
Log.error("\(error)")
self.next()
}
} else {
callback()
}
}
}
| 4312a9bc7080c88e6d5c8a0084ea630b | 30.8 | 147 | 0.634827 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/Interpreter/defer.swift | apache-2.0 | 8 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
do {
defer { print("deferred 1") }
defer { print("deferred 2") }
print("start!")
// CHECK-NOT: deferred
// CHECK-LABEL: start!
// CHECK-NEXT: deferred 2
// CHECK-NEXT: deferred 1
}
// ensure #function ignores defer blocks
do {
print("top-level #function")
let name = #function
defer { print(name == #function ? "good" : "bad") }
// CHECK-LABEL: top-level #function
// CHECK-NEXT: good
}
func foo() {
print("foo()")
let name = #function
defer { print(name == #function ? "good" : "bad") }
// CHECK-LABEL: foo()
// CHECK-NEXT: good
}
foo()
| cc2761a1b506bd5bef9bddc6abf222ba | 19.878788 | 55 | 0.577649 | false | false | false | false |
Roommate-App/roomy | refs/heads/master | roomy/roomy/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// roomy
//
// Created by Ryan Liszewski on 4/4/17.
// Copyright © 2017 Poojan Dave. All rights reserved.
//
import UIKit
import Parse
import ParseLiveQuery
import MBProgressHUD
import MapKit
import UserNotifications
import IBAnimatable
import QuartzCore
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIViewControllerTransitioningDelegate, RoomySettingsDelegate{
@IBOutlet weak var homeTableView: UITableView!
var region: CLCircularRegion!
var roomiesHome: [Roomy]? = []
var roomiesNotHome: [Roomy]? = []
var roomies: [Roomy]? = []
var hud = MBProgressHUD()
@IBOutlet weak var currentRoomyProfilePoster: AnimatableImageView!
@IBOutlet weak var currentRoomynameLabel: UILabel!
@IBOutlet weak var currentRoomyStatus: AnimatableLabel!
@IBOutlet weak var currentRoomyHomeBadge: AnimatableImageView!
var homeTableViewSection: RoomyTableViewCell!
var notHomeTableViewSection: RoomyTableViewCell!
private var subscription: Subscription<Roomy>!
override func viewDidLoad() {
super.viewDidLoad()
LocationService.shared.setUpHouseFence()
LocationService.shared.isRoomyHome()
homeTableView.dataSource = self
homeTableView.delegate = self
homeTableView.sizeToFit()
loadCurrentRoomyProfileView()
addRoomiesToHome()
let roomyQuery = getRoomyQuery()
subscription = ParseLiveQuery.Client.shared.subscribe(roomyQuery).handle(Event.updated) { (query, roomy) in
if(roomy.username != Roomy.current()?.username){
self.roomyChangedHomeStatus(roomy: roomy)
let content = UNMutableNotificationContent()
content.title = roomy.username!
let roomyIsHome = roomy["is_home"] as! Bool
if(roomyIsHome) {
content.body = "Came Home!"
} else {
content.body = "Left Home!"
}
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 20, repeats: false)
let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error: Error?) in
})
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
print("test")
showProgressHud()
updateRoomies()
loadCurrentRoomyProfileView()
}
//MARK: Roomy settings delegate.
func updateRoomyProfile(userName: String, profileImage: UIImage?){
if(userName != ""){
currentRoomynameLabel.text = userName
}
currentRoomyProfilePoster.image = profileImage
}
//MARK: Loads the current roomy's profile view.
func loadCurrentRoomyProfileView(){
let roomy = Roomy.current()
currentRoomynameLabel.text = roomy?.username
//currentRoomyProfilePoster.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720")
let pfImage = roomy?["profile_image"] as! PFFile
currentRoomyStatus.text = roomy?["status_message"] as? String ?? ""
pfImage.getDataInBackground(block: { (image: Data?, error: Error?) in
if error == nil {
self.currentRoomyProfilePoster.image = UIImage(data: image!)
} else {
}
})
if(checkIfRoomyIsHome(roomy: Roomy.current()!)){
currentRoomyHomeBadge.image = #imageLiteral(resourceName: "home")
} else {
//currentRoomyHomeStatusLabel.text = "Not Home"
currentRoomyHomeBadge.image = #imageLiteral(resourceName: "not-home")
}
}
//MARK: PROGRESSHUD FUNCTIONS
func showProgressHud(){
hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = MBProgressHUDMode.indeterminate
hud.animationType = .zoomIn
}
func hideProgressHud(){
hud.hide(animated: true, afterDelay: 1)
}
//MARK: TABLE VIEW FUNCTIONS
func reloadTableView(){
hud.hide(animated: true, afterDelay: 1)
homeTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: R.Identifier.Cell.homeTableViewCell, for: indexPath)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath){
guard let tableViewCell = cell as? RoomyTableViewCell
else {
return
}
if(indexPath.section == 0){
homeTableViewSection = tableViewCell
} else {
notHomeTableViewSection = tableViewCell
}
tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.section)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 30))
let homeTextLabel = UILabel(frame: CGRect(x: 20, y: 5, width: 100, height: 30))
homeTextLabel.adjustsFontSizeToFitWidth = true
homeTextLabel.font = UIFont (name: "HelveticaNeue-UltraLight", size: 20)
let iconImage = UIImageView(frame: CGRect(x: 0, y: 5, width: 20, height: 20))
if(section == 0){
homeTextLabel.text = R.Header.home
} else {
homeTextLabel.text = R.Header.notHome
}
headerView.addSubview(homeTextLabel)
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
//MARK: PARSE QUERY TO GET ROOMIES
func getRoomyQuery() -> PFQuery<Roomy>{
let query: PFQuery<Roomy> = PFQuery(className: "_User")
query.whereKey("house", equalTo: House._currentHouse!)
do {
let roomies = try query.findObjects()
self.roomies = roomies
} catch let error as Error? {
print(error?.localizedDescription ?? "ERROR")
}
return query
}
//MARK: ROOMY HOME FUNCTIONS
func addRoomiesToHome() {
//addCurrentRoomyToHome()
for roomy in self.roomies! {
if(roomy.objectId != Roomy.current()?.objectId){
if(self.checkIfRoomyIsHome(roomy: roomy)){
self.roomiesHome?.append(roomy)
} else {
self.roomiesNotHome?.append(roomy)
}
}
}
hideProgressHud()
self.homeTableView.reloadData()
}
func addCurrentRoomyToHome(){
print(Roomy.current()?["is_home"])
if(checkIfRoomyIsHome(roomy: Roomy.current()!)){
roomiesHome?.append(Roomy.current()!)
}else {
roomiesNotHome?.append(Roomy.current()!)
}
homeTableView.reloadData()
}
func checkIfRoomyIsHome(roomy: Roomy) -> Bool{
return roomy["is_home"] as? Bool ?? false
}
func updateRoomies(){
roomiesHome = []
roomiesNotHome = []
for roomy in self.roomies! {
do {
try roomy.fetch()
} catch let error as Error? {
print(error?.localizedDescription ?? "ERROR")
}
}
addRoomiesToHome()
}
func roomyChangedHomeStatus(roomy: Roomy){
let isRoomyHome = roomy["is_home"] as? Bool ?? false
if(isRoomyHome){
roomiesNotHome = roomiesNotHome?.filter({$0.username != roomy.username})
roomiesHome?.append(roomy)
notHomeTableViewSection.reloadCollectionViewData()
} else {
roomiesHome = roomiesHome?.filter({$0.username != roomy.username})
roomiesNotHome?.append(roomy)
}
//reloadTableView()
notHomeTableViewSection.reloadCollectionViewData()
homeTableViewSection.reloadCollectionViewData()
}
//MARK: Displays directions home in Google Maps (If available) or in Maps.
@IBAction func onDirectionsHomeButtonTapped(_ sender: Any) {
let directionsURL = URL(string: "comgooglemaps://?&daddr=\((House._currentHouse?.latitude)!),\((House._currentHouse?.longitude)!)&zoom=10")
UIApplication.shared.open(directionsURL!) { (success: Bool) in
if success {
} else {
let coordinate = CLLocationCoordinate2DMake(Double((House._currentHouse?.latitude)!)!, Double((House._currentHouse?.longitude)!)!)
let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: coordinate))
mapItem.name = "Home"
mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving])
}
}
}
//MARK: CHANGES CURRENT ROOMY'S STATUS
@IBAction func onChangedStatusButtonTapped(_ sender: Any) {
let storyboard = UIStoryboard(name: R.Identifier.Storyboard.Status, bundle: nil)
let updateStatusViewController = storyboard.instantiateViewController(withIdentifier: R.Identifier.ViewController.updateStatusViewController) as! UpdateStatusViewController
updateStatusViewController.transitioningDelegate = self
updateStatusViewController.modalPresentationStyle = .custom
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
self.present(updateStatusViewController, animated: true, completion: nil)
}
//MARK: Pop Custom Animation Controller
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PopPresentingAnimationController()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
currentRoomyStatus.text = Roomy.current()?[R.Parse.Key.StatusMessage] as! String
currentRoomyStatus.animate()
return PopDismissingAnimationController()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == R.Identifier.Segue.SettingsSegue){
let navigationController = segue.destination as! UINavigationController
let settingsViewController = navigationController.topViewController as! SettingsViewController
settingsViewController.settingsDelegate = self
}
}
}
extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView.tag == 0 {
return (roomiesHome?.count)!
} else {
return roomiesNotHome!.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: R.Identifier.Cell.homeCollectionViewCell, for: indexPath) as! RoomyCollectionViewCell
var statusText = ""
if(collectionView.tag == 0) {
let roomy = roomiesHome?[indexPath.row]
statusText = roomy?["status_message"] as? String ?? ""
cell.roomyUserNameLabel.text = roomy?.username
cell.roomyPosterView.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720")
let pfImage = roomy?["profile_image"] as! PFFile
pfImage.getDataInBackground(block: { (image: Data?, error: Error?) in
if error == nil && image != nil {
print(image!)
cell.roomyPosterView.image = UIImage(data: image!)!
//cell.roomyPosterView.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720")
} else {
print("no image")
//cell.roomyPosterView.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720")
}
})
} else {
let roomy = roomiesNotHome?[indexPath.row]
statusText = roomy?["status_message"] as? String ?? ""
cell.roomyUserNameLabel.text = roomy?.username
//cell.roomyStatusMessageLabel.text = roomy?["status_message"] as? //String ?? ""
let pfImage = roomy?["profile_image"] as! PFFile
pfImage.getDataInBackground(block: { (image: Data?, error: Error?) in
if error == nil && image != nil{
cell.roomyPosterView.image = UIImage(data: image!)!
//print(image!)
//cell.roomyPosterView.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720")
} else {
print("no image")
//cell.roomyPosterView.image = #imageLiteral(resourceName: "blank-profile-picture-973460_960_720")
}
})
}
if(statusText != ""){
let index = statusText.index((statusText.startIndex), offsetBy: 1)
let emoji = statusText.substring(to: index)
cell.roomyBadgeView.image = emoji.image()
}
return cell
}
//MARK: Draws a badge on an UIImageView
func drawImageView(mainImage: UIImage, withBadge badge: UIImage) -> UIImage {
UIGraphicsBeginImageContextWithOptions(mainImage.size, false, 0.0)
mainImage.draw(in: CGRect(x: 0, y: 0, width: mainImage.size.width, height: mainImage.size.height))
badge.draw(in: CGRect(x: mainImage.size.width - badge.size.width, y: 0, width: badge.size.width, height: badge.size.height))
let resultImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return resultImage
}
}
//MARK: USER NOTIFICATION DELEGATE CLASS EXTENSION. DISPLAYS NOTFICATION TO ROOMY.
extension HomeViewController: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let storyboard = UIStoryboard(name: R.Identifier.Storyboard.tabBar, bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: R.Identifier.ViewController.tabBarViewController) as! UITabBarController
viewController.selectedIndex = R.TabBarController.SelectedIndex.messagingViewController
self.present(viewController, animated: true, completion: nil)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("Notification being triggered")
completionHandler( [.alert,.sound,.badge])
}
}
//MARK: Converts a string to an UIImage. Used to convert emoji's to UIImages in roomy status.
extension String {
func image() -> UIImage? {
let size = CGSize(width: 30, height: 35)
UIGraphicsBeginImageContextWithOptions(size, false, 0);
UIColor.white.set()
let rect = CGRect(origin: CGPoint(), size: size)
UIRectFill(CGRect(origin: CGPoint(), size: size))
(self as NSString).draw(in: rect, withAttributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 30)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| ae40b2eeee2f8978e3f6fd8baad35d5c | 37.065022 | 207 | 0.620722 | false | false | false | false |
huangboju/Moots | refs/heads/master | UICollectionViewLayout/wwdc_demo/ImageFeed/Model/Person.swift | mit | 1 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Model object representing a single person.
*/
import Foundation
enum PersonUpdate {
case delete(Int)
case insert(Person, Int)
case move(Int, Int)
case reload(Int)
}
struct Person: CustomStringConvertible {
var name: String?
var imgName: String?
var lastUpdate = Date()
init(name: String, month: Int, day: Int, year: Int) {
self.name = name
self.imgName = name.lowercased()
var components = DateComponents()
components.day = day
components.month = month
components.year = year
if let date = Calendar.current.date(from: components) {
lastUpdate = date
}
}
var isUpdated: Bool? {
didSet {
lastUpdate = Date()
}
}
var description: String {
if let name = self.name {
return "<\(type(of: self)): name = \(name)>"
} else {
return "<\(type(of: self))>"
}
}
}
| 7fd72ac39800835e8feda43532b8ee80 | 20.653061 | 63 | 0.557964 | false | false | false | false |
iSapozhnik/SILoadingControllerDemo | refs/heads/master | LoadingControllerDemo/LoadingControllerDemo/LoadingController/Views/LoadingViews/ActivityViews/StrokeActivityView.swift | mit | 1 | //
// StrokeActivityView.swift
// LoadingControllerDemo
//
// Created by Sapozhnik Ivan on 28.06.16.
// Copyright © 2016 Sapozhnik Ivan. All rights reserved.
//
import UIKit
class StrokeActivityView: UIView {
static let defaultColor = UIColor.lightGrayColor()
static let defaultLineWidth: CGFloat = 2.0
static let defaultCircleTime: Double = 1.5
private var strokeAnimation: CAAnimationGroup {
get {
return generateAnimation()
}
}
private var rotationAnimation: CABasicAnimation {
get {
return generateRotationAnimation()
}
}
private var circleLayer: CAShapeLayer = CAShapeLayer()
@IBInspectable
var strokeColor: UIColor = UIColor.lightGrayColor() {
didSet {
circleLayer.strokeColor = strokeColor.CGColor
}
}
@IBInspectable
var animating: Bool = true {
didSet {
updateAnimation()
}
}
@IBInspectable
var lineWidth: CGFloat = CGFloat(2) {
didSet {
circleLayer.lineWidth = lineWidth
}
}
@IBInspectable
var circleTime: Double = 1.5 {
didSet {
circleLayer.removeAllAnimations()
updateAnimation()
}
}
//init methods
override init(frame: CGRect) {
lineWidth = StrokeActivityView.defaultLineWidth
circleTime = StrokeActivityView.defaultCircleTime
strokeColor = StrokeActivityView.defaultColor
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
lineWidth = StrokeActivityView.defaultLineWidth
circleTime = StrokeActivityView.defaultCircleTime
strokeColor = StrokeActivityView.defaultColor
super.init(coder: aDecoder)
setupView()
}
convenience init() {
self.init(frame: CGRect.zero)
lineWidth = StrokeActivityView.defaultLineWidth
circleTime = StrokeActivityView.defaultCircleTime
strokeColor = StrokeActivityView.defaultColor
setupView()
}
func generateAnimation() -> CAAnimationGroup {
let headAnimation = CABasicAnimation(keyPath: "strokeStart")
headAnimation.beginTime = self.circleTime/3.0
headAnimation.fromValue = 0
headAnimation.toValue = 1
headAnimation.duration = self.circleTime/1.5
headAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let tailAnimation = CABasicAnimation(keyPath: "strokeEnd")
tailAnimation.fromValue = 0
tailAnimation.toValue = 1
tailAnimation.duration = self.circleTime/1.5
tailAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let groupAnimation = CAAnimationGroup()
groupAnimation.duration = self.circleTime
groupAnimation.repeatCount = Float.infinity
groupAnimation.animations = [headAnimation, tailAnimation]
return groupAnimation
}
func generateRotationAnimation() -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.fromValue = 0
animation.toValue = 2*M_PI
animation.duration = self.circleTime
animation.repeatCount = Float.infinity
return animation
}
func setupView() {
layer.addSublayer(self.circleLayer)
backgroundColor = UIColor.clearColor()
circleLayer.fillColor = nil
circleLayer.lineWidth = lineWidth
circleLayer.lineCap = kCALineCapRound
circleLayer.strokeColor = strokeColor.CGColor
updateAnimation()
}
override func layoutSubviews() {
super.layoutSubviews()
let center = CGPoint(x: bounds.size.width/2.0, y: bounds.size.height/2.0)
let radius = min(bounds.size.width, bounds.size.height)/2.0 - circleLayer.lineWidth/2.0
let endAngle = CGFloat(2*M_PI)
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true)
circleLayer.path = path.CGPath
circleLayer.frame = bounds
}
func updateAnimation() {
if animating {
circleLayer.addAnimation(strokeAnimation, forKey: "strokeLineAnimation")
circleLayer.addAnimation(rotationAnimation, forKey: "rotationAnimation")
} else {
circleLayer.removeAllAnimations()
}
}
deinit {
circleLayer.removeAllAnimations()
circleLayer.removeFromSuperlayer()
}
}
| 6d917ebf1fb37bb74a75dba60352ab1e | 25.573333 | 112 | 0.758655 | false | false | false | false |
BoltApp/bolt-ios | refs/heads/master | 125-iOSTips-master/Demo/47.给App的某个功能添加快捷方式/Pods/Swifter/Sources/String+BASE64.swift | apache-2.0 | 6 | //
// String+BASE64.swift
// Swifter
//
// Copyright © 2016 Damian Kołakowski. All rights reserved.
//
import Foundation
extension String {
private static let CODES = [UInt8]("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".utf8)
public static func toBase64(_ data: [UInt8]) -> String? {
// Based on: https://en.wikipedia.org/wiki/Base64#Sample_Implementation_in_Java
var result = [UInt8]()
var tmp: UInt8
for index in stride(from: 0, to: data.count, by: 3) {
let byte = data[index]
tmp = (byte & 0xFC) >> 2;
result.append(CODES[Int(tmp)])
tmp = (byte & 0x03) << 4;
if index + 1 < data.count {
tmp |= (data[index + 1] & 0xF0) >> 4;
result.append(CODES[Int(tmp)]);
tmp = (data[index + 1] & 0x0F) << 2;
if (index + 2 < data.count) {
tmp |= (data[index + 2] & 0xC0) >> 6;
result.append(CODES[Int(tmp)]);
tmp = data[index + 2] & 0x3F;
result.append(CODES[Int(tmp)]);
} else {
result.append(CODES[Int(tmp)]);
result.append(contentsOf: [UInt8]("=".utf8));
}
} else {
result.append(CODES[Int(tmp)]);
result.append(contentsOf: [UInt8]("==".utf8));
}
}
return String(bytes: result, encoding: .utf8)
}
}
| 79dc5cc5652005c8512bb89b3c526552 | 32.5 | 112 | 0.481506 | false | false | false | false |
Dimillian/HackerSwifter | refs/heads/master | Hacker Swifter/Hacker Swifter/HTTP/Fetcher.swift | mit | 1 | //
// Fetcher.swift
// Hacker Swifter
//
// Created by Thomas Ricouard on 11/07/14.
// Copyright (c) 2014 Thomas Ricouard. All rights reserved.
//
import Foundation
private let _Fetcher = Fetcher()
public class Fetcher {
internal let baseURL = "https://news.ycombinator.com/"
internal let APIURL = "https://hacker-news.firebaseio.com/v0/"
internal let APIFormat = ".json"
private let session = NSURLSession.sharedSession()
public typealias FetchCompletion = (object: AnyObject!, error: ResponseError!, local: Bool) -> Void
public typealias FetchParsing = (html: String!) -> AnyObject!
public typealias FetchParsingAPI = (json: AnyObject) -> AnyObject!
public enum ResponseError: String {
case NoConnection = "You are not connected to the internet"
case ErrorParsing = "An error occurred while fetching the requested page"
case UnknownError = "An unknown error occurred"
}
public enum APIEndpoint: String {
case Post = "item/"
case User = "user/"
case Top = "topstories"
case New = "newstories"
case Ask = "askstories"
case Jobs = "jobstories"
case Show = "showstories"
}
public class var sharedInstance: Fetcher {
return _Fetcher
}
class func Fetch(ressource: String, parsing: FetchParsing, completion: FetchCompletion) {
let cacheKey = Cache.generateCacheKey(ressource)
Cache.sharedCache.objectForKey(cacheKey, completion: {(object: AnyObject!) in
if let realObject: AnyObject = object {
completion(object: realObject, error: nil, local: true)
}
})
let path = _Fetcher.baseURL + ressource
let task = _Fetcher.session.dataTaskWithURL(NSURL(string: path)! , completionHandler: {(data: NSData?, response, error: NSError?) in
if !(error != nil) {
if let realData = data {
let object: AnyObject! = parsing(html: NSString(data: realData, encoding: NSUTF8StringEncoding) as! String)
if let realObject: AnyObject = object {
Cache.sharedCache.setObject(realObject, key: cacheKey)
}
dispatch_async(dispatch_get_main_queue(), { ()->() in
completion(object: object, error: nil, local: false)
})
}
else {
dispatch_async(dispatch_get_main_queue(), { ()->() in
completion(object: nil, error: ResponseError.UnknownError, local: false)
})
}
}
else {
completion(object: nil, error: ResponseError.UnknownError, local: false)
}
})
task.resume()
}
//In the future, all scraping will be removed and we'll use only the Algolia API
//At the moment this function is sufixed for testing purpose
class func FetchJSON(endpoint: APIEndpoint, ressource: String?, parsing: FetchParsingAPI, completion: FetchCompletion) {
var path: String
if let realRessource: String = ressource {
path = _Fetcher.APIURL + endpoint.rawValue + realRessource + _Fetcher.APIFormat
}
else {
path = _Fetcher.APIURL + endpoint.rawValue + _Fetcher.APIFormat
}
let cacheKey = Cache.generateCacheKey(path)
Cache.sharedCache.objectForKey(cacheKey, completion: {(object: AnyObject!) in
if let realObject: AnyObject = object {
completion(object: realObject, error: nil, local: true)
}
})
let task = _Fetcher.session.dataTaskWithURL(NSURL(string: path)! , completionHandler: {(data: NSData?, response, error: NSError?) in
if let data = data {
var error: NSError? = nil
var JSON: AnyObject!
do {
JSON = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
} catch let error1 as NSError {
error = error1
JSON = nil
} catch {
fatalError()
}
if error == nil {
let object: AnyObject! = parsing(json: JSON)
if let object: AnyObject = object {
if let realObject: AnyObject = object {
Cache.sharedCache.setObject(realObject, key: cacheKey)
}
dispatch_async(dispatch_get_main_queue(), { ()->() in
completion(object: object, error: nil, local: false)
})
}
else {
dispatch_async(dispatch_get_main_queue(), { ()->() in
completion(object: nil, error: ResponseError.ErrorParsing, local: false)
})
}
}
else {
completion(object: nil, error: ResponseError.UnknownError, local: false)
}
}
})
task.resume()
}
} | cbef89f93db9b3e1e6a18c7169e03b8b | 38.567164 | 140 | 0.541407 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes | refs/heads/master | Example/Pods/RxSwift/RxSwift/Observables/Merge.swift | apache-2.0 | 6 | //
// Merge.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) throws -> Source)
-> Observable<Source.Element> {
return FlatMap(source: self.asObservable(), selector: selector)
}
}
extension ObservableType {
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
If element is received while there is some projected observable sequence being merged it will simply be ignored.
- seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated.
*/
public func flatMapFirst<Source: ObservableConvertibleType>(_ selector: @escaping (Element) throws -> Source)
-> Observable<Source.Element> {
return FlatMapFirst(source: self.asObservable(), selector: selector)
}
}
extension ObservableType where Element : ObservableConvertibleType {
/**
Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public func merge() -> Observable<Element.Element> {
return Merge(source: self.asObservable())
}
/**
Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently.
- returns: The observable sequence that merges the elements of the inner sequences.
*/
public func merge(maxConcurrent: Int)
-> Observable<Element.Element> {
return MergeLimited(source: self.asObservable(), maxConcurrent: maxConcurrent)
}
}
extension ObservableType where Element : ObservableConvertibleType {
/**
Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
public func concat() -> Observable<Element.Element> {
return self.merge(maxConcurrent: 1)
}
}
extension ObservableType {
/**
Merges elements from all observable sequences from collection into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> Observable<Element> where Collection.Element == Observable<Element> {
return MergeArray(sources: Array(sources))
}
/**
Merges elements from all observable sequences from array into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: [Observable<Element>]) -> Observable<Element> {
return MergeArray(sources: sources)
}
/**
Merges elements from all observable sequences into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: Observable<Element>...) -> Observable<Element> {
return MergeArray(sources: sources)
}
}
// MARK: concatMap
extension ObservableType {
/**
Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
public func concatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) throws -> Source)
-> Observable<Source.Element> {
return ConcatMap(source: self.asObservable(), selector: selector)
}
}
private final class MergeLimitedSinkIter<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType>
: ObserverType
, LockOwnerType
, SynchronizedOnType where SourceSequence.Element == Observer.Element {
typealias Element = Observer.Element
typealias DisposeKey = CompositeDisposable.DisposeKey
typealias Parent = MergeLimitedSink<SourceElement, SourceSequence, Observer>
private let _parent: Parent
private let _disposeKey: DisposeKey
var _lock: RecursiveLock {
return self._parent._lock
}
init(parent: Parent, disposeKey: DisposeKey) {
self._parent = parent
self._disposeKey = disposeKey
}
func on(_ event: Event<Element>) {
self.synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next:
self._parent.forwardOn(event)
case .error:
self._parent.forwardOn(event)
self._parent.dispose()
case .completed:
self._parent._group.remove(for: self._disposeKey)
if let next = self._parent._queue.dequeue() {
self._parent.subscribe(next, group: self._parent._group)
}
else {
self._parent._activeCount -= 1
if self._parent._stopped && self._parent._activeCount == 0 {
self._parent.forwardOn(.completed)
self._parent.dispose()
}
}
}
}
}
private final class ConcatMapSink<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType>: MergeLimitedSink<SourceElement, SourceSequence, Observer> where Observer.Element == SourceSequence.Element {
typealias Selector = (SourceElement) throws -> SourceSequence
private let _selector: Selector
init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) {
self._selector = selector
super.init(maxConcurrent: 1, observer: observer, cancel: cancel)
}
override func performMap(_ element: SourceElement) throws -> SourceSequence {
return try self._selector(element)
}
}
private final class MergeLimitedBasicSink<SourceSequence: ObservableConvertibleType, Observer: ObserverType>: MergeLimitedSink<SourceSequence, SourceSequence, Observer> where Observer.Element == SourceSequence.Element {
override func performMap(_ element: SourceSequence) throws -> SourceSequence {
return element
}
}
private class MergeLimitedSink<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType>
: Sink<Observer>
, ObserverType where Observer.Element == SourceSequence.Element {
typealias QueueType = Queue<SourceSequence>
let _maxConcurrent: Int
let _lock = RecursiveLock()
// state
var _stopped = false
var _activeCount = 0
var _queue = QueueType(capacity: 2)
let _sourceSubscription = SingleAssignmentDisposable()
let _group = CompositeDisposable()
init(maxConcurrent: Int, observer: Observer, cancel: Cancelable) {
self._maxConcurrent = maxConcurrent
super.init(observer: observer, cancel: cancel)
}
func run(_ source: Observable<SourceElement>) -> Disposable {
_ = self._group.insert(self._sourceSubscription)
let disposable = source.subscribe(self)
self._sourceSubscription.setDisposable(disposable)
return self._group
}
func subscribe(_ innerSource: SourceSequence, group: CompositeDisposable) {
let subscription = SingleAssignmentDisposable()
let key = group.insert(subscription)
if let key = key {
let observer = MergeLimitedSinkIter(parent: self, disposeKey: key)
let disposable = innerSource.asObservable().subscribe(observer)
subscription.setDisposable(disposable)
}
}
func performMap(_ element: SourceElement) throws -> SourceSequence {
rxAbstractMethod()
}
@inline(__always)
final private func nextElementArrived(element: SourceElement) -> SourceSequence? {
self._lock.lock(); defer { self._lock.unlock() } // {
let subscribe: Bool
if self._activeCount < self._maxConcurrent {
self._activeCount += 1
subscribe = true
}
else {
do {
let value = try self.performMap(element)
self._queue.enqueue(value)
} catch {
self.forwardOn(.error(error))
self.dispose()
}
subscribe = false
}
if subscribe {
do {
return try self.performMap(element)
} catch {
self.forwardOn(.error(error))
self.dispose()
}
}
return nil
// }
}
func on(_ event: Event<SourceElement>) {
switch event {
case .next(let element):
if let sequence = self.nextElementArrived(element: element) {
self.subscribe(sequence, group: self._group)
}
case .error(let error):
self._lock.lock(); defer { self._lock.unlock() }
self.forwardOn(.error(error))
self.dispose()
case .completed:
self._lock.lock(); defer { self._lock.unlock() }
if self._activeCount == 0 {
self.forwardOn(.completed)
self.dispose()
}
else {
self._sourceSubscription.dispose()
}
self._stopped = true
}
}
}
final private class MergeLimited<SourceSequence: ObservableConvertibleType>: Producer<SourceSequence.Element> {
private let _source: Observable<SourceSequence>
private let _maxConcurrent: Int
init(source: Observable<SourceSequence>, maxConcurrent: Int) {
self._source = source
self._maxConcurrent = maxConcurrent
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element {
let sink = MergeLimitedBasicSink<SourceSequence, Observer>(maxConcurrent: self._maxConcurrent, observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
// MARK: Merge
private final class MergeBasicSink<Source: ObservableConvertibleType, Observer: ObserverType> : MergeSink<Source, Source, Observer> where Observer.Element == Source.Element {
override func performMap(_ element: Source) throws -> Source {
return element
}
}
// MARK: flatMap
private final class FlatMapSink<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType> : MergeSink<SourceElement, SourceSequence, Observer> where Observer.Element == SourceSequence.Element {
typealias Selector = (SourceElement) throws -> SourceSequence
private let _selector: Selector
init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) {
self._selector = selector
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: SourceElement) throws -> SourceSequence {
return try self._selector(element)
}
}
// MARK: FlatMapFirst
private final class FlatMapFirstSink<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType> : MergeSink<SourceElement, SourceSequence, Observer> where Observer.Element == SourceSequence.Element {
typealias Selector = (SourceElement) throws -> SourceSequence
private let _selector: Selector
override var subscribeNext: Bool {
return self._activeCount == 0
}
init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) {
self._selector = selector
super.init(observer: observer, cancel: cancel)
}
override func performMap(_ element: SourceElement) throws -> SourceSequence {
return try self._selector(element)
}
}
private final class MergeSinkIter<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType> : ObserverType where Observer.Element == SourceSequence.Element {
typealias Parent = MergeSink<SourceElement, SourceSequence, Observer>
typealias DisposeKey = CompositeDisposable.DisposeKey
typealias Element = Observer.Element
private let _parent: Parent
private let _disposeKey: DisposeKey
init(parent: Parent, disposeKey: DisposeKey) {
self._parent = parent
self._disposeKey = disposeKey
}
func on(_ event: Event<Element>) {
self._parent._lock.lock(); defer { self._parent._lock.unlock() } // lock {
switch event {
case .next(let value):
self._parent.forwardOn(.next(value))
case .error(let error):
self._parent.forwardOn(.error(error))
self._parent.dispose()
case .completed:
self._parent._group.remove(for: self._disposeKey)
self._parent._activeCount -= 1
self._parent.checkCompleted()
}
// }
}
}
private class MergeSink<SourceElement, SourceSequence: ObservableConvertibleType, Observer: ObserverType>
: Sink<Observer>
, ObserverType where Observer.Element == SourceSequence.Element {
typealias ResultType = Observer.Element
typealias Element = SourceElement
let _lock = RecursiveLock()
var subscribeNext: Bool {
return true
}
// state
let _group = CompositeDisposable()
let _sourceSubscription = SingleAssignmentDisposable()
var _activeCount = 0
var _stopped = false
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func performMap(_ element: SourceElement) throws -> SourceSequence {
rxAbstractMethod()
}
@inline(__always)
final private func nextElementArrived(element: SourceElement) -> SourceSequence? {
self._lock.lock(); defer { self._lock.unlock() } // {
if !self.subscribeNext {
return nil
}
do {
let value = try self.performMap(element)
self._activeCount += 1
return value
}
catch let e {
self.forwardOn(.error(e))
self.dispose()
return nil
}
// }
}
func on(_ event: Event<SourceElement>) {
switch event {
case .next(let element):
if let value = self.nextElementArrived(element: element) {
self.subscribeInner(value.asObservable())
}
case .error(let error):
self._lock.lock(); defer { self._lock.unlock() }
self.forwardOn(.error(error))
self.dispose()
case .completed:
self._lock.lock(); defer { self._lock.unlock() }
self._stopped = true
self._sourceSubscription.dispose()
self.checkCompleted()
}
}
func subscribeInner(_ source: Observable<Observer.Element>) {
let iterDisposable = SingleAssignmentDisposable()
if let disposeKey = self._group.insert(iterDisposable) {
let iter = MergeSinkIter(parent: self, disposeKey: disposeKey)
let subscription = source.subscribe(iter)
iterDisposable.setDisposable(subscription)
}
}
func run(_ sources: [Observable<Observer.Element>]) -> Disposable {
self._activeCount += sources.count
for source in sources {
self.subscribeInner(source)
}
self._stopped = true
self.checkCompleted()
return self._group
}
@inline(__always)
func checkCompleted() {
if self._stopped && self._activeCount == 0 {
self.forwardOn(.completed)
self.dispose()
}
}
func run(_ source: Observable<SourceElement>) -> Disposable {
_ = self._group.insert(self._sourceSubscription)
let subscription = source.subscribe(self)
self._sourceSubscription.setDisposable(subscription)
return self._group
}
}
// MARK: Producers
final private class FlatMap<SourceElement, SourceSequence: ObservableConvertibleType>: Producer<SourceSequence.Element> {
typealias Selector = (SourceElement) throws -> SourceSequence
private let _source: Observable<SourceElement>
private let _selector: Selector
init(source: Observable<SourceElement>, selector: @escaping Selector) {
self._source = source
self._selector = selector
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element {
let sink = FlatMapSink(selector: self._selector, observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
final private class FlatMapFirst<SourceElement, SourceSequence: ObservableConvertibleType>: Producer<SourceSequence.Element> {
typealias Selector = (SourceElement) throws -> SourceSequence
private let _source: Observable<SourceElement>
private let _selector: Selector
init(source: Observable<SourceElement>, selector: @escaping Selector) {
self._source = source
self._selector = selector
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element {
let sink = FlatMapFirstSink<SourceElement, SourceSequence, Observer>(selector: self._selector, observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
final class ConcatMap<SourceElement, SourceSequence: ObservableConvertibleType>: Producer<SourceSequence.Element> {
typealias Selector = (SourceElement) throws -> SourceSequence
private let _source: Observable<SourceElement>
private let _selector: Selector
init(source: Observable<SourceElement>, selector: @escaping Selector) {
self._source = source
self._selector = selector
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element {
let sink = ConcatMapSink<SourceElement, SourceSequence, Observer>(selector: self._selector, observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
final class Merge<SourceSequence: ObservableConvertibleType> : Producer<SourceSequence.Element> {
private let _source: Observable<SourceSequence>
init(source: Observable<SourceSequence>) {
self._source = source
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element {
let sink = MergeBasicSink<SourceSequence, Observer>(observer: observer, cancel: cancel)
let subscription = sink.run(self._source)
return (sink: sink, subscription: subscription)
}
}
final private class MergeArray<Element>: Producer<Element> {
private let _sources: [Observable<Element>]
init(sources: [Observable<Element>]) {
self._sources = sources
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = MergeBasicSink<Observable<Element>, Observer>(observer: observer, cancel: cancel)
let subscription = sink.run(self._sources)
return (sink: sink, subscription: subscription)
}
}
| 089d44f008bcb815505dae3941ad6000 | 36.535117 | 225 | 0.665196 | false | false | false | false |
17thDimension/AudioKit | refs/heads/develop | Examples/iOS/Swift/AudioKitDemo/AudioKitDemo/Processing/AudioFilePlayer.swift | lgpl-3.0 | 2 | //
// AudioFilePlayer.swift
// AudioKitDemo
//
// Created by Nicholas Arner on 3/1/15.
// Copyright (c) 2015 AudioKit. All rights reserved.
//
class AudioFilePlayer: AKInstrument {
var auxilliaryOutput = AKAudio()
// INSTRUMENT BASED CONTROL ============================================
var speed = AKInstrumentProperty(value: 1, minimum: -2, maximum: 2)
var scaling = AKInstrumentProperty(value: 1, minimum: 0.0, maximum: 3.0)
var sampleMix = AKInstrumentProperty(value: 0, minimum: 0, maximum: 1)
// INSTRUMENT DEFINITION ===============================================
override init() {
super.init()
addProperty(speed)
addProperty(scaling)
addProperty(sampleMix)
let file1 = String(NSBundle.mainBundle().pathForResource("PianoBassDrumLoop", ofType: "wav")!)
let file2 = String(NSBundle.mainBundle().pathForResource("808loop", ofType: "wav")!)
let fileIn1 = AKFileInput(filename: file1)
fileIn1.speed = speed
fileIn1.loop = true
let fileIn2 = AKFileInput(filename: file2)
fileIn2.speed = speed
fileIn2.loop = true
var fileInLeft = AKMix(input1: fileIn1.leftOutput, input2: fileIn2.leftOutput, balance: sampleMix)
var fileInRight = AKMix(input1: fileIn1.rightOutput, input2: fileIn2.rightOutput, balance: sampleMix)
var leftF = AKFFT(
input: fileInLeft.scaledBy(0.25.ak),
fftSize: 1024.ak,
overlap: 256.ak,
windowType: AKFFT.hammingWindow(),
windowFilterSize: 1024.ak
)
var leftR = AKFFT(
input: fileInRight.scaledBy(0.25.ak),
fftSize: 1024.ak,
overlap: 256.ak,
windowType: AKFFT.hammingWindow(),
windowFilterSize: 1024.ak
)
var scaledLeftF = AKScaledFFT(
signal: leftF,
frequencyRatio: scaling
)
var scaledLeftR = AKScaledFFT(
signal: leftR,
frequencyRatio: scaling
)
var scaledLeft = AKResynthesizedAudio(signal: scaledLeftF)
var scaledRight = AKResynthesizedAudio(signal: scaledLeftR)
var mono = AKMix(input1: scaledLeft, input2: scaledRight, balance: 0.5.ak)
// Output to global effects processing
auxilliaryOutput = AKAudio.globalParameter()
assignOutput(auxilliaryOutput, to: mono)
}
} | c16c69d8c6e83b65fa46c3d6ac9ffeb5 | 32.103896 | 109 | 0.576923 | false | false | false | false |
robertherdzik/RHPlaygroundFreestyle | refs/heads/master | Hypnotize/RHHypnotize.playground/Contents.swift | mit | 1 | import UIKit
import PlaygroundSupport
let sideLenght = 200
let viewFrame = CGRect(x: 0, y: 0, width: sideLenght, height: sideLenght)
let baseView = UIView(frame: viewFrame)
baseView.backgroundColor = UIColor.gray
// Creating our circle path
let circlePath = UIBezierPath(arcCenter: baseView.center,
radius: viewFrame.size.width/2,
startAngle: CGFloat(0),
endAngle: CGFloat.pi * 2,
clockwise: true)
let lineWidth = CGFloat(3)
let shapeLayer = CAShapeLayer()
shapeLayer.frame = viewFrame
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.cyan.cgColor
shapeLayer.lineWidth = lineWidth
// Now the magic 🎩 begins, we create our Replicator 🎉 which will multiply our shapeLayer.
let replicator = CAReplicatorLayer()
replicator.frame = viewFrame
replicator.instanceDelay = 0.05
replicator.instanceCount = 30
replicator.instanceTransform = CATransform3DMakeScale(1, 1, 1)
replicator.addSublayer(shapeLayer)
baseView.layer.addSublayer(replicator)
let fade = CABasicAnimation(keyPath: "opacity")
fade.fromValue = 0.05
fade.toValue = 0.3
fade.duration = 1.5
fade.beginTime = CACurrentMediaTime()
fade.repeatCount = .infinity
fade.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
shapeLayer.add(fade, forKey: "shapeLayerOpacity")
let scale = CABasicAnimation(keyPath: "transform")
scale.fromValue = NSValue(caTransform3D: CATransform3DMakeScale(0, 0, 1))
scale.toValue = NSValue(caTransform3D: CATransform3DMakeScale(1, 1, 1))
scale.duration = 1.5
scale.repeatCount = .infinity
scale.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
shapeLayer.add(scale, forKey: "shapeLayerScale")
PlaygroundPage.current.liveView = baseView
| 26dd10bfc87fca9292fb09f3bae92d5e | 31.947368 | 91 | 0.749201 | false | false | false | false |
JunDang/SwiftFoundation | refs/heads/develop | Sources/UnitTests/UUIDTests.swift | mit | 1 | //
// UUIDTests.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 7/2/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
import XCTest
import SwiftFoundation
import SwiftFoundation
final class UUIDTests: XCTestCase {
lazy var allTests: [(String, () -> ())] =
[("testCreateRandomUUID", self.testCreateRandomUUID),
("testUUIDString", self.testUUIDString),
("testCreateFromString", self.testCreateFromString)]
// MARK: - Functional Tests
func testCreateRandomUUID() {
// try to create without crashing
let uuid = UUID()
print(uuid)
}
func testUUIDString() {
let stringValue = "5BFEB194-68C4-48E8-8F43-3C586364CB6F"
guard let uuid = UUID(rawValue: stringValue)
else { XCTFail("Could not create UUID from " + stringValue); return }
XCTAssert(uuid.rawValue == stringValue, "UUID is \(uuid), should be \(stringValue)")
}
func testCreateFromString() {
let stringValue = "5BFEB194-68C4-48E8-8F43-3C586364CB6F"
XCTAssert((UUID(rawValue: stringValue) != nil), "Could not create UUID with string \"\(stringValue)\"")
XCTAssert((UUID(rawValue: "BadInput") == nil), "UUID should not be created")
}
}
| 9a39a93ccdb16bac003e91a98b8e30f9 | 27.104167 | 111 | 0.60934 | false | true | false | false |
AlexeyGolovenkov/DevHelper | refs/heads/master | DevHelper/Ext/CommentCommand.swift | mit | 1 | //
// CommentCommand.swift
// DevHelper
//
// Created by Alexey Golovenkov on 12.03.17.
// Copyright © 2017 Alexey Golovenkov. All rights reserved.
//
import Cocoa
import XcodeKit
class CommentCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) {
for selection in invocation.buffer.selections {
guard let range = DHTextRange(textRange: selection as? XCSourceTextRange) else {
continue
}
let newSelection = invocation.buffer.lines.comment(range: range)
guard let textSelection = selection as? XCSourceTextRange else {
continue
}
textSelection.start.column = newSelection.start.column
textSelection.start.line = newSelection.start.line
textSelection.end.column = newSelection.end.column
textSelection.end.line = newSelection.end.line
}
completionHandler(nil)
}
}
| 3d036863ffc24e89dce0754e70100de9 | 27.875 | 116 | 0.745671 | false | false | false | false |
caicai0/ios_demo | refs/heads/master | load/Carthage/Checkouts/SwiftSoup/Example/Pods/SwiftSoup/Sources/TextNode.swift | mit | 3 | //
// TextNode.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
A text node.
*/
open class TextNode: Node {
/*
TextNode is a node, and so by default comes with attributes and children. The attributes are seldom used, but use
memory, and the child nodes are never used. So we don't have them, and override accessors to attributes to create
them as needed on the fly.
*/
private static let TEXT_KEY: String = "text"
var _text: String
/**
Create a new TextNode representing the supplied (unencoded) text).
@param text raw text
@param baseUri base uri
@see #createFromEncoded(String, String)
*/
public init(_ text: String, _ baseUri: String?) {
self._text = text
super.init()
self.baseUri = baseUri
}
open override func nodeName() -> String {
return "#text"
}
/**
* Get the text content of this text node.
* @return Unencoded, normalised text.
* @see TextNode#getWholeText()
*/
open func text() -> String {
return TextNode.normaliseWhitespace(getWholeText())
}
/**
* Set the text content of this text node.
* @param text unencoded text
* @return this, for chaining
*/
@discardableResult
public func text(_ text: String) -> TextNode {
self._text = text
guard let attributes = attributes else {
return self
}
do {
try attributes.put(TextNode.TEXT_KEY, text)
} catch {
}
return self
}
/**
Get the (unencoded) text of this text node, including any newlines and spaces present in the original.
@return text
*/
open func getWholeText() -> String {
return attributes == nil ? _text : attributes!.get(key: TextNode.TEXT_KEY)
}
/**
Test if this text node is blank -- that is, empty or only whitespace (including newlines).
@return true if this document is empty or only whitespace, false if it contains any text content.
*/
open func isBlank() -> Bool {
return StringUtil.isBlank(getWholeText())
}
/**
* Split this text node into two nodes at the specified string offset. After splitting, this node will contain the
* original text up to the offset, and will have a new text node sibling containing the text after the offset.
* @param offset string offset point to split node at.
* @return the newly created text node containing the text after the offset.
*/
open func splitText(_ offset: Int)throws->TextNode {
try Validate.isTrue(val: offset >= 0, msg: "Split offset must be not be negative")
try Validate.isTrue(val: offset < _text.characters.count, msg: "Split offset must not be greater than current text length")
let head: String = getWholeText().substring(0, offset)
let tail: String = getWholeText().substring(offset)
text(head)
let tailNode: TextNode = TextNode(tail, self.getBaseUri())
if (parent() != nil) {
try parent()?.addChildren(siblingIndex+1, tailNode)
}
return tailNode
}
override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings)throws {
if (out.prettyPrint() &&
((siblingIndex == 0 && (parentNode as? Element) != nil && (parentNode as! Element).tag().formatAsBlock() && !isBlank()) ||
(out.outline() && siblingNodes().count > 0 && !isBlank()) )) {
indent(accum, depth, out)
}
let par: Element? = parent() as? Element
let normaliseWhite = out.prettyPrint() && par != nil && !Element.preserveWhitespace(par!)
Entities.escape(accum, getWholeText(), out, false, normaliseWhite, false)
}
override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {
}
/**
* Create a new TextNode from HTML encoded (aka escaped) data.
* @param encodedText Text containing encoded HTML (e.g. &lt;)
* @param baseUri Base uri
* @return TextNode containing unencoded data (e.g. <)
*/
open static func createFromEncoded(_ encodedText: String, _ baseUri: String)throws->TextNode {
let text: String = try Entities.unescape(encodedText)
return TextNode(text, baseUri)
}
static open func normaliseWhitespace(_ text: String) -> String {
let _text = StringUtil.normaliseWhitespace(text)
return _text
}
static open func stripLeadingWhitespace(_ text: String) -> String {
return text.replaceFirst(of: "^\\s+", with: "")
//return text.replaceFirst("^\\s+", "")
}
static open func lastCharIsWhitespace(_ sb: StringBuilder) -> Bool {
return sb.toString().characters.last == " "
}
// attribute fiddling. create on first access.
private func ensureAttributes() {
if (attributes == nil) {
attributes = Attributes()
do {
try attributes?.put(TextNode.TEXT_KEY, _text)
} catch {}
}
}
open override func attr(_ attributeKey: String)throws->String {
ensureAttributes()
return try super.attr(attributeKey)
}
open override func getAttributes() -> Attributes {
ensureAttributes()
return super.getAttributes()!
}
open override func attr(_ attributeKey: String, _ attributeValue: String)throws->Node {
ensureAttributes()
return try super.attr(attributeKey, attributeValue)
}
open override func hasAttr(_ attributeKey: String) -> Bool {
ensureAttributes()
return super.hasAttr(attributeKey)
}
open override func removeAttr(_ attributeKey: String)throws->Node {
ensureAttributes()
return try super.removeAttr(attributeKey)
}
open override func absUrl(_ attributeKey: String)throws->String {
ensureAttributes()
return try super.absUrl(attributeKey)
}
public override func copy(with zone: NSZone? = nil) -> Any {
let clone = TextNode(_text, baseUri)
return super.copy(clone: clone)
}
public override func copy(parent: Node?) -> Node {
let clone = TextNode(_text, baseUri)
return super.copy(clone: clone, parent: parent)
}
public override func copy(clone: Node, parent: Node?) -> Node {
return super.copy(clone: clone, parent: parent)
}
}
| 5519e8c8a773aaed00e24d3d389d4781 | 31.477387 | 131 | 0.630976 | false | false | false | false |
rambler-digital-solutions/rambler-it-ios | refs/heads/develop | Carthage/Checkouts/rides-ios-sdk/examples/Swift SDK/Swift SDK/RideRequestWidgetExampleViewController.swift | mit | 1 | //
// RideRequestWidgetExampleViewController.swift
// Swift SDK
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import UberRides
import CoreLocation
/// This class provides an example of how to use the RideRequestButton to initiate
/// a ride request using the Ride Request Widget
class RideRequestWidgetExampleViewController: ButtonExampleViewController {
var blackRideRequestButton: RideRequestButton!
var whiteRideRequestButton: RideRequestButton!
let locationManger:CLLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.navigationItem.title = "Ride Request Widget"
blackRideRequestButton = buildRideRequestWidgetButton(.native)
whiteRideRequestButton = buildRideRequestWidgetButton(.implicit)
whiteRideRequestButton.colorStyle = .white
topView.addSubview(blackRideRequestButton)
bottomView.addSubview(whiteRideRequestButton)
addBlackRequestButtonConstraints()
addWhiteRequestButtonConstraints()
locationManger.delegate = self
if !checkLocationServices() {
locationManger.requestWhenInUseAuthorization()
}
}
// Mark: Private Interface
fileprivate func buildRideRequestWidgetButton(_ loginType: LoginType) -> RideRequestButton {
let loginManager = LoginManager(loginType: loginType)
let requestBehavior = RideRequestViewRequestingBehavior(presentingViewController: self, loginManager: loginManager)
requestBehavior.modalRideRequestViewController.delegate = self
let rideParameters = RideParametersBuilder().build()
let accessTokenString = "access_token_string"
let token = AccessToken(tokenString: accessTokenString)
if TokenManager.save(accessToken: token){
// Success
} else {
// Unable to save
}
TokenManager.fetchToken()
TokenManager.deleteToken()
return RideRequestButton(rideParameters: rideParameters, requestingBehavior: requestBehavior)
}
fileprivate func addBlackRequestButtonConstraints() {
blackRideRequestButton.translatesAutoresizingMaskIntoConstraints = false
let centerYConstraint = NSLayoutConstraint(item: blackRideRequestButton, attribute: .centerY, relatedBy: .equal, toItem: topView, attribute: .centerY, multiplier: 1.0, constant: 0.0)
let centerXConstraint = NSLayoutConstraint(item: blackRideRequestButton, attribute: .centerX, relatedBy: .equal, toItem: topView, attribute: .centerX, multiplier: 1.0, constant: 0.0)
topView.addConstraints([centerYConstraint, centerXConstraint])
}
fileprivate func addWhiteRequestButtonConstraints() {
whiteRideRequestButton.translatesAutoresizingMaskIntoConstraints = false
let centerYConstraint = NSLayoutConstraint(item: whiteRideRequestButton, attribute: .centerY, relatedBy: .equal, toItem: bottomView, attribute: .centerY, multiplier: 1.0, constant: 0.0)
let centerXConstraint = NSLayoutConstraint(item: whiteRideRequestButton, attribute: .centerX, relatedBy: .equal, toItem: bottomView, attribute: .centerX, multiplier: 1.0, constant: 0.0)
bottomView.addConstraints([centerYConstraint, centerXConstraint])
}
fileprivate func checkLocationServices() -> Bool {
let locationEnabled = CLLocationManager.locationServicesEnabled()
let locationAuthorization = CLLocationManager.authorizationStatus()
let locationAuthorized = locationAuthorization == .authorizedWhenInUse || locationAuthorization == .authorizedAlways
return locationEnabled && locationAuthorized
}
fileprivate func showMessage(_ message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.alert)
let okayAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)
alert.addAction(okayAction)
self.present(alert, animated: true, completion: nil)
}
}
//MARK: ModalViewControllerDelegate
extension RideRequestWidgetExampleViewController : ModalViewControllerDelegate {
func modalViewControllerDidDismiss(_ modalViewController: ModalViewController) {
print("did dismiss")
}
func modalViewControllerWillDismiss(_ modalViewController: ModalViewController) {
print("will dismiss")
}
}
//MARK: CLLocationManagerDelegate
extension RideRequestWidgetExampleViewController : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .denied || status == .restricted {
showMessage("Location Services disabled.")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManger.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationManger.stopUpdatingLocation()
showMessage("There was an error locating you.")
}
}
| d61ac2fd398397e114b5def60aebd19f | 41.86755 | 193 | 0.722694 | false | false | false | false |
charmaex/JDTransition | refs/heads/master | JDTransition/JDSegueScaleOut.swift | mit | 1 | //
// JDSegueScaleOut.swift
// JDSegues
//
// Created by Jan Dammshäuser on 29.08.16.
// Copyright © 2016 Jan Dammshäuser. All rights reserved.
//
import UIKit
/// Segue where the current screen scales out to a point or the center of the screen.
@objc
open class JDSegueScaleOut: UIStoryboardSegue, JDSegueOriginable {
/// Defines at which point the animation should start
/// - parameter Default: center of the screen
open var animationOrigin: CGPoint?
/// Time the transition animation takes
/// - parameter Default: 0.5 seconds
open var transitionTime: TimeInterval = 0.5
/// Animation Curve
/// - parameter Default: CurveLinear
open var animationOption: UIViewAnimationOptions = .curveLinear
open override func perform() {
let fromVC = source
let toVC = destination
guard let window = fromVC.view.window else {
return NSLog("[JDTransition] JDSegueScaleOut could not get views window")
}
JDAnimationScale.out(inWindow: window, fromVC: fromVC, toVC: toVC, duration: transitionTime, options: animationOption) { _ in
self.finishSegue(nil)
}
}
}
| 5149d6d5b5cd14b169b2c2057c79e1d2 | 29.076923 | 133 | 0.681159 | false | false | false | false |
iosdevelopershq/code-challenges | refs/heads/master | CodeChallenge/Challenges/LetterCombinationsOfPhoneNumber/Entries/BugKrushaLetterCombinationsOfPhoneNumberEntry.swift | mit | 1 | //
// BugKrusha.swift
// CodeChallenge
//
// Created by Jon-Tait Beason on 11/2/15.
// Copyright © 2015 iosdevelopers. All rights reserved.
//
import Foundation
let bugKrushaLetterCombinationOfPhoneNumberEntry = CodeChallengeEntry<LetterCombinationsOfPhoneNumberChallenge>(name: "bugKrusha") { input in
return getCombinations(digitString: input)
}
private enum Digit: String {
case Two = "abc"
case Three = "def"
case Four = "ghi"
case Five = "jkl"
case Six = "mno"
case Seven = "pqrs"
case Eight = "tuv"
case Nine = "wxyz"
}
private func getCharactersForNumber(number: String) -> Digit? {
switch number {
case "2": return Digit.Two
case "3": return Digit.Three
case "4": return Digit.Four
case "5": return Digit.Five
case "6": return Digit.Six
case "7": return Digit.Seven
case "8": return Digit.Eight
case "9": return Digit.Nine
default: break
}
return nil
}
private func getCombinations(digitString: String) -> [String] {
var arrayOfCharacterSets = [String]()
for (index, character) in digitString.characters.enumerated() {
if let charactersForNumber = getCharactersForNumber(number: "\(character)")?.rawValue {
if index == 0 {
arrayOfCharacterSets = charactersForNumber.characters.map { "\($0)" }
} else {
var tempArray = [String]()
for char in charactersForNumber.characters {
for characterSet in arrayOfCharacterSets {
let newString = characterSet + "\(char)"
tempArray.append(newString)
}
}
arrayOfCharacterSets = tempArray
}
}
}
return arrayOfCharacterSets
}
| bd62aed9df3d928e8c6b8d24ef77e082 | 26.769231 | 141 | 0.607202 | false | false | false | false |
IAskWind/IAWExtensionTool | refs/heads/master | IAWExtensionTool/IAWExtensionTool/Classes/UIKit/IAW_ImageView+Extension.swift | mit | 1 | //
// IAWImageView.swift
// IAWExtensionTool
//
// Created by winston on 16/11/17.
// Copyright © 2016年 winston. All rights reserved.
//
import Foundation
import UIKit
import Kingfisher
extension UIImageView {
open func iawCircleHeader(_ url: String,radius:Int){
if url != "" {
self.kf.setImage(with: URL(string:url)!, placeholder: IAW_ImgXcassetsTool.headerPhoto.image)
}else{
self.image = IAW_ImgXcassetsTool.headerPhoto.image
}
self.layer.cornerRadius = CGFloat(radius)
self.layer.borderColor = UIColor.white.cgColor
self.layer.borderWidth = 2
self.layer.masksToBounds = true
}
open func showView(){
}
// 360度旋转图片
open func rotate360Degree() {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z") // 让其在z轴旋转
rotationAnimation.toValue = NSNumber(value: .pi * 2.0) // 旋转角度
rotationAnimation.duration = 0.6 // 旋转周期
rotationAnimation.isCumulative = true // 旋转累加角度
rotationAnimation.repeatCount = MAXFLOAT // 旋转次数
layer.add(rotationAnimation, forKey: "rotationAnimation")
}
// 停止旋转
open func stopRotate() {
layer.removeAllAnimations()
}
}
| c0f70d7629e02fec2e35a2ca5c4723f0 | 26.413043 | 104 | 0.642347 | false | false | false | false |
shirai/SwiftLearning | refs/heads/master | playground/メソッド.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
/*
*
*インスタンスメソッド
*
*/
/* 職種 */
enum Job {
case Warrior, Mage, Thief, Priest
func initialHitPoint() -> Int {
switch self {
case .Warrior:
return 100
case .Mage:
return 40
case .Thief:
return 60
case .Priest:
return 30
}
}
}
/* キャラクタ */
class GameCharacter {
var name: String
var job: Job
var maxHitPoint: Int {
didSet {
self.hitPoint = self.maxHitPoint
}
}
var hitPoint: Int = 0
// イニシャライザ
init(name: String, job: Job) {
self.name = name
self.job = job
self.maxHitPoint = self.job.initialHitPoint()
}
// ダメージを与える
func addDamage(damage: Int) {
hitPoint -= damage
if hitPoint <= 0 {
print("死んだ")
}
}
}
//インスタンスメソッドを呼び出す場合は、フロパティと同様、.(ドット)をつけて呼び出します。
var player = GameCharacter(name: "ヨシヒコ", job: .Warrior)
print(player.hitPoint)
player.addDamage(damage: 40)
print(player.hitPoint)
/*
*
*破壊的メソッド
構造体、列挙型のメソッドはプロパティを変更することはできない
mutatingをfuncの前につけて宣言することで属性値を変更できる
定数の構造体、列挙型ではmutatingメソッドを呼び出すことはできない
クラスの場合は変更可能
*
*/
/* キャラクタ */
struct Character {
var name: String
var job: Job
var level: Int
// func changeJob(newJob: Job) {
// self.job = newJob //コンパイルエラー
mutating func changeJob(newJob: Job) {
self.job = newJob // OK
}
}
//定数の構造体や列挙型の破壊的メソッドを呼び出す事はできない。変数であれば可能。
let player1 = Character(name: "ヨシヒコ", job: .Warrior, level: 10)
//player.changeJob(newJob:.Mage) // コンパイルエラー
var player2 = Character(name: "ダンジョー", job: .Warrior, level: 10)
player2.changeJob(newJob: .Mage) // OK
//破壊的メソッドでは、次のようにself自体を変更することも可能。
/* ゲームキャラクタ */
struct GameCharacter2 {
var name: String
var job: Job
var level: Int
mutating func changeJob(newJob: Job) {
self = GameCharacter2(name: self.name, job: newJob, level: self.level)
}
}
var player3 = GameCharacter2(name: "ヨシヒコ", job: .Warrior, level: 10)
player3.changeJob(newJob: .Mage)
print(player.job == .Mage)
/* オセロの駒 */
enum OthelloPiece {
case White, Black
mutating func reverse() {
self = (self == .White ? .Black : .White)
}
}
var piece = OthelloPiece.White
piece.reverse();
print(piece == .Black)
/*
*
*型メソッド
*
*/
/* じゃんけん */
enum Janken {
case goo, choki, paa
static func sayPriming() {
print("最初はグー")
}
}
Janken.sayPriming()
/* ログイン情報 */
struct LoginInfo {
static var url = "https://login.example.com/"
static func isSecure() -> Bool {
return url.hasPrefix("https:")
}
var userid: String
var password: String
}
print(LoginInfo.isSecure())
/* パーソンクラス */
class Person {
class var tableName: String {
return "people" //データペーステーブル名
}
class func tableNameWithPrefix(prefix: String) -> String {
return "\(prefix)_\(tableName)"
}
var name: String
var address: String
var tel: String
var email: String
init(name: String, address: String, tel: String, email: String) {
self.name = name
self.address = address
self.tel = tel
self.email = email
}
}
print(Person.tableNameWithPrefix(prefix: "bak"))
| 1be566c53b4babf8753baf623bb3267c | 19.294479 | 78 | 0.603386 | false | false | false | false |
xiajinchun/NimbleNinja | refs/heads/master | NimbleNinja/GameScene.swift | mit | 1 | //
// GameScene.swift
// NimbleNinja
//
// Created by Jinchun Xia on 15/4/14.
// Copyright (c) 2015 TEAM. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var movingGround: NNMovingGround!
var hero: NNHero!
var cloudGenerator: NNCloudGenerator!
var wallGenerator: NNWallGenerator!
var isStarted = false
var isGameOver = false
override func didMoveToView(view: SKView) {
/* Setup your scene here */
backgroundColor = UIColor(red: 159.0/255.0, green: 201.0/255.0, blue: 244.0/255.0, alpha: 1.0)
/* add ground */
addMovingGround()
/* add hero */
addHero()
/* add cloud generator */
addCloudGenerator()
/* add wall generator */
addWallGenerator()
/* add start label */
addTapToStartLabel()
/* add physics world */
addPhysicsWorld()
}
func addMovingGround() {
movingGround = NNMovingGround(size: CGSizeMake(view!.frame.width, kMLGroundHeight))
movingGround.position = CGPointMake(0, view!.frame.size.height / 2)
self.addChild(movingGround)
}
func addHero() {
hero = NNHero()
hero.position = CGPointMake(70, movingGround.position.y + movingGround.frame.size.height / 2 + hero.frame.size.height / 2)
self.addChild(hero)
hero.breath()
}
func addCloudGenerator() {
cloudGenerator = NNCloudGenerator(color: UIColor.clearColor(), size: view!.frame.size)
cloudGenerator.position = view!.center
cloudGenerator.zPosition = -10
addChild(cloudGenerator)
cloudGenerator.populate(7)
cloudGenerator.startGeneratingWithSpawnTime(5)
}
func addWallGenerator() {
wallGenerator = NNWallGenerator(color: UIColor.clearColor(), size: view!.frame.size)
wallGenerator.position = view!.center
addChild(wallGenerator)
}
func addTapToStartLabel() {
let tapToStartLabel = SKLabelNode(text: "Tap to start!")
tapToStartLabel.name = "tapToStartLabel"
tapToStartLabel.position.x = view!.center.x
tapToStartLabel.position.y = view!.center.y + 40
tapToStartLabel.fontName = "Helvetice"
tapToStartLabel.fontColor = UIColor.blackColor()
tapToStartLabel.fontSize = 22.0
addChild(tapToStartLabel)
tapToStartLabel.runAction(blinkAnimation())
}
func addPhysicsWorld() {
physicsWorld.contactDelegate = self
}
// MARK: - Game Lifecycle
func start() {
isStarted = true
/* find the ndoe by named "tapToStartLabel" and then remove it from parent node */
let tapToStartLabel = childNodeWithName("tapToStartLabel")
tapToStartLabel?.removeFromParent()
hero.stop()
hero.startRuning()
movingGround.start()
wallGenerator.startGeneratingWallsEvery(1)
}
func gameOver() {
isGameOver = true
// stop everthing
hero.fail()
wallGenerator.stopWalls()
movingGround.stop()
hero.stop()
// create game over label
let gameOverLabel = SKLabelNode(text: "Game Over!")
gameOverLabel.fontColor = UIColor.blackColor()
gameOverLabel.fontName = "Helvetice"
gameOverLabel.position.x = view!.center.x
gameOverLabel.position.y = view!.center.y + 40
gameOverLabel.fontSize = 22.0
addChild(gameOverLabel)
gameOverLabel.runAction(blinkAnimation())
}
func restart() {
cloudGenerator.stopGenerating()
let newScene = GameScene(size: view!.bounds.size)
newScene.scaleMode = SKSceneScaleMode.AspectFill
view!.presentScene(newScene)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
if isGameOver {
restart()
} else if !isStarted {
start()
} else {
hero.flip()
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
// MARK: - SKPhysiscContactDeleagte
func didBeginContact(contact: SKPhysicsContact) {
if !isGameOver{
gameOver()
}
}
// MARK: - Animation
func blinkAnimation() -> SKAction {
let duration = 0.4
let fadeOut = SKAction.fadeAlphaTo(0.0, duration: duration)
let fadeIn = SKAction.fadeAlphaTo(1.0, duration: duration)
let blink = SKAction.sequence([fadeOut, fadeIn])
return SKAction.repeatActionForever(blink)
}
} | 64c0725056ffe065b60c53cd99ea9155 | 28.567073 | 130 | 0.603135 | false | false | false | false |
syoung-smallwisdom/ResearchUXFactory-iOS | refs/heads/master | ResearchUXFactory/SBAPermissionsManager.swift | bsd-3-clause | 1 | //
// SBAPermissionsManager.swift
// ResearchUXFactory
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
extension SBAPermissionsManager {
public static var shared: SBAPermissionsManager {
return __shared()
}
/**
Are all the permissions granted?
@param permissionTypes Permissions to check
@return Whether or not all have been granted
*/
public func allPermissionsAuthorized(for permissionTypes:[SBAPermissionObjectType]) -> Bool {
for permissionType in permissionTypes {
if !self.isPermissionGranted(for: permissionType) {
return false
}
}
return true
}
/**
Request permission for each permission in the list.
@param permissions List of the permissions being requested
@param alertPresenter Alert presenter to use for showing alert messages
@param completion Completion handler to call when all the permissions have been requested
*/
public func requestPermissions(for permissions: [SBAPermissionObjectType], alertPresenter: SBAAlertPresenter?, completion: ((Bool) -> Void)?) {
// Exit early if there are no permissions
guard permissions.count > 0 else {
completion?(true)
return
}
DispatchQueue.main.async(execute: {
// Use an enumerator to recursively step thorough each permission and request permission
// for that type.
var allGranted = true
let enumerator = (permissions as NSArray).objectEnumerator()
func enumerateRequest() {
guard let permission = enumerator.nextObject() as? SBAPermissionObjectType else {
completion?(allGranted)
return
}
if self.isPermissionGranted(for: permission) {
enumerateRequest()
}
else {
self.requestPermission(for: permission, completion: { [weak alertPresenter] (success, error) in
DispatchQueue.main.async(execute: {
allGranted = allGranted && success
if !success, let presenter = alertPresenter {
let title = Localization.localizedString("SBA_PERMISSIONS_FAILED_TITLE")
let message = error?.localizedDescription ?? Localization.localizedString("SBA_PERMISSIONS_FAILED_MESSAGE")
presenter.showAlertWithOk(title: title, message: message, actionHandler: { (_) in
enumerateRequest()
})
}
else {
enumerateRequest()
}
})
})
}
}
enumerateRequest()
})
}
// MARK: Deprecated methods included for reverse-compatibility
@available(*, deprecated)
@objc(permissionTitleForType:)
open func permissionTitle(for type: SBAPermissionsType) -> String {
return self.typeIdentifierFor(for: type)?.defaultTitle() ?? ""
}
@available(*, deprecated)
@objc(permissionDescriptionForType:)
open func permissionDescription(for type: SBAPermissionsType) -> String {
return self.typeIdentifierFor(for: type)?.defaultDescription() ?? ""
}
}
| bba903094dd06ae4f53ddd903e21fd0d | 41.5 | 147 | 0.614939 | false | false | false | false |
WildDogTeam/lib-ios-streambase | refs/heads/master | StreamBaseExample/StreamBaseKit/StreamTableViewAdapter.swift | mit | 1 | //
// StreamTableViewAdapter.swift
// StreamBaseKit
//
// Created by IMacLi on 15/10/12.
// Copyright © 2015年 liwuyang. All rights reserved.
//
import Foundation
import UIKit
/**
An adapter for connecting streams to table views.
Optionally you can set the section, which is useful for attaching different streams to
different sections. For example,
class MyViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
stream1?.delegate = StreamTableViewAdapter(tableView: tableView, section: 0)
stream2?.delegate = StreamTableViewAdapter(tableView: tableView, section: 1)
// ...
}
}
And then in the data source you do something like this:
extension MyViewContoller : UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return stream1?.count ?? 0
case 1:
return stream2?.count ?? 0
default:
fatalError("unknown section \(section)")
}
}
// ...
}
*/
public class StreamTableViewAdapter : StreamBaseDelegate {
let tableView: UITableView
let section: Int?
var isInitialLoad = true
public init(tableView: UITableView, section: Int? = nil) {
self.tableView = tableView
self.section = section
tableView.reloadData()
}
public func streamWillChange() {
tableView.beginUpdates()
}
public func streamDidChange() {
if isInitialLoad {
UIView.performWithoutAnimation {
self.tableView.endUpdates()
}
} else {
tableView.endUpdates()
}
}
public func streamItemsAdded(paths: [NSIndexPath]) {
if let s = section {
let mappedPaths = paths.map{ NSIndexPath(forItem: $0.row, inSection: s) }
tableView.insertRowsAtIndexPaths(mappedPaths, withRowAnimation: .None)
} else {
tableView.insertRowsAtIndexPaths(paths, withRowAnimation: .None)
}
}
public func streamItemsDeleted(paths: [NSIndexPath]) {
if let s = section {
let mappedPaths = paths.map{ NSIndexPath(forItem: $0.row, inSection: s) }
tableView.deleteRowsAtIndexPaths(mappedPaths, withRowAnimation: .None)
} else {
tableView.deleteRowsAtIndexPaths(paths, withRowAnimation: .None)
}
}
public func streamItemsChanged(paths: [NSIndexPath]) {
if let s = section {
let mappedPaths = paths.map{ NSIndexPath(forItem: $0.row, inSection: s) }
tableView.reloadRowsAtIndexPaths(mappedPaths, withRowAnimation: .None)
} else {
tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: .None)
}
}
public func streamDidFinishInitialLoad(error: NSError?) {
isInitialLoad = false
}
}
| 7dd79704caa598d8a4b13dc132a31234 | 30.636364 | 95 | 0.59387 | false | false | false | false |
eleks/digital-travel-book | refs/heads/master | src/Swift/Weekend In Lviv/ViewControllers/Photo Gallery/WLPhotoGalleryVCSw.swift | mit | 1 | //
// WLPhotoGalleryVCSw.swift
// Weekend In Lviv
//
// Created by Admin on 13.06.14.
// Copyright (c) 2014 rnd. All rights reserved.
//
import UIKit
class ImageViewController:UIViewController {
// Instance variables
var index:UInt = 0
var imageView:UIImageView? = nil
var _imagePath:String = ""
var imagePath:String {
get {
return _imagePath
}
set (imagePath) {
_imagePath = imagePath
if let imageView_ = imageView? {
imageView_.removeFromSuperview()
}
self.imageView = UIImageView(image: UIImage(contentsOfFile: self.imagePath))
self.imageView!.frame = self.view.bounds
self.imageView!.contentMode = UIViewContentMode.ScaleAspectFit
self.view = self.imageView!
}
}
}
class WLPhotoGalleryVCSw: UIViewController, UIScrollViewDelegate, UIPageViewControllerDataSource {
// Outlets
@IBOutlet weak var scrollImages:UIScrollView?
@IBOutlet weak var lblSwipe:UILabel?
@IBOutlet weak var btnClose:UIButton?
// Instance variables
var imagePathList: [String] = []
var selectedImageIndex:UInt = 0
var pageController:UIPageViewController? = nil
// Instance methods
override func viewDidLoad() {
super.viewDidLoad()
self.lblSwipe!.font = WLFontManager.sharedManager.gentiumItalic15
self.pageController = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.Scroll,
navigationOrientation: UIPageViewControllerNavigationOrientation.Horizontal,
options:nil)
let initialViewController:UIViewController? = self.viewControllerAtIndex(Int(self.selectedImageIndex))
if let initVC_ = initialViewController? {
self.pageController!.setViewControllers([initVC_],
direction:UIPageViewControllerNavigationDirection.Forward,
animated:false,
completion:nil)
}
self.addChildViewController(self.pageController!)
self.view.addSubview(self.pageController!.view)
self.pageController!.didMoveToParentViewController(self)
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
self.pageController!.dataSource = self
self.pageController!.view.frame = self.view.bounds
self.pageController!.view.frame = self.scrollImages!.frame
self.view.addSubview(self.pageController!.view)
self.view.bringSubviewToFront(self.btnClose!)
self.btnClose!.enabled = true
self.view.bringSubviewToFront(self.lblSwipe!)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView())
}
override func viewWillDisappear(animated: Bool)
{
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().postNotificationName("ShowPlayer", object:nil)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle
{
return UIStatusBarStyle.LightContent
}
/* Unavailable in Swift
override func shouldAutorotateToInterfaceOrientation(toInterfaceOrientation:UIInterfaceOrientation) -> Bool
{
return true
}*/
func btnMenuTouch(sender:AnyObject)
{
self.mm_drawerController!.toggleDrawerSide(MMDrawerSide.Left, animated:true, completion:nil)
}
//#pragma mark - Page view controller delegate
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let imageController = viewController as ImageViewController
return self.viewControllerAtIndex(Int(imageController.index) - 1)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController?
{
let imageController = viewController as ImageViewController
return self.viewControllerAtIndex(Int(imageController.index) + 1)
}
func viewControllerAtIndex(index:Int) -> ImageViewController?
{
var photoVC:ImageViewController? = nil
if index >= 0 && index < self.imagePathList.count {
photoVC = ImageViewController()
photoVC!.imagePath = self.imagePathList[Int(index)]
photoVC!.index = UInt(index)
}
return photoVC
}
//#pragma mark - Page view controller data source
// Actions
@IBAction func btnCloseTouch(sender:AnyObject)
{
self.navigationController!.popViewControllerAnimated(true)
}
}
| 907f9ae82f9085bf416c68046a57f969 | 32.763514 | 161 | 0.644187 | false | false | false | false |
cafielo/iOS_BigNerdRanch_5th | refs/heads/master | Chap13_Homepwner_bronze_silver_gold/Homepwner/Item.swift | mit | 1 | //
// Item.swift
// Homepwner
//
// Created by Joonwon Lee on 7/31/16.
// Copyright © 2016 Joonwon Lee. All rights reserved.
//
import UIKit
class Item: NSObject {
var name: String
var valueInDollars: Int
var serialNumber: String?
var dateCreated: NSDate
init(name: String, serialNumber: String?, valueInDollars:Int) {
self.name = name
self.valueInDollars = valueInDollars
self.serialNumber = serialNumber
self.dateCreated = NSDate()
super.init()
}
convenience init(random: Bool = false) {
if random {
let adjectives = ["Fluffy", "Rusty", "Shiny"]
let nouns = ["Bear", "Spork", "Mac"]
var idx = arc4random_uniform(UInt32(adjectives.count))
let randomAdjective = nouns[Int(idx)]
idx = arc4random_uniform(UInt32(nouns.count))
let randomNoun = nouns[Int(idx)]
let randomName = "\(randomAdjective) \(randomNoun)"
let randomwValue = Int(arc4random_uniform(100))
let randomSerialNumber = NSUUID().UUIDString.componentsSeparatedByString("-").first!
self.init(name: randomName, serialNumber: randomSerialNumber, valueInDollars: randomwValue)
} else {
self.init(name: "", serialNumber: nil, valueInDollars: 0)
}
}
}
| b5ed525fcdc7ed27abf897c87119aca8 | 29.06383 | 103 | 0.584572 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | refs/heads/master | Pods/HXPHPicker/Sources/HXPHPicker/Camera/View/PreviewMetalView.swift | mit | 1 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
The Metal preview view.
*/
import CoreMedia
import Metal
import MetalKit
class PreviewMetalView: MTKView {
enum Rotation: Int {
case rotate0Degrees
case rotate90Degrees
case rotate180Degrees
case rotate270Degrees
}
var mirroring = false {
didSet {
syncQueue.sync {
internalMirroring = mirroring
}
}
}
private var internalMirroring: Bool = false
var rotation: Rotation = .rotate0Degrees {
didSet {
syncQueue.sync {
internalRotation = rotation
}
}
}
private var internalRotation: Rotation = .rotate0Degrees
var pixelBuffer: CVPixelBuffer? {
didSet {
if pixelBuffer == nil {
isPreviewing = false
}
syncQueue.sync {
internalPixelBuffer = pixelBuffer
}
}
}
var isPreviewing: Bool = false
var didPreviewing: ((Bool) -> Void)?
private var internalPixelBuffer: CVPixelBuffer?
private let syncQueue = DispatchQueue(
label: "com.silence.previewViewSyncQueue",
qos: .userInitiated,
attributes: [],
autoreleaseFrequency: .workItem
)
private var textureCache: CVMetalTextureCache?
private var textureWidth: Int = 0
private var textureHeight: Int = 0
private var textureMirroring = false
private var textureRotation: Rotation = .rotate0Degrees
private var sampler: MTLSamplerState!
private var renderPipelineState: MTLRenderPipelineState!
private var commandQueue: MTLCommandQueue?
private var vertexCoordBuffer: MTLBuffer!
private var textCoordBuffer: MTLBuffer!
private var internalBounds: CGRect!
private var textureTranform: CGAffineTransform?
func texturePointForView(point: CGPoint) -> CGPoint? {
var result: CGPoint?
guard let transform = textureTranform else {
return result
}
let transformPoint = point.applying(transform)
if CGRect(origin: .zero, size: CGSize(width: textureWidth, height: textureHeight)).contains(transformPoint) {
result = transformPoint
} else {
print("Invalid point \(point) result point \(transformPoint)")
}
return result
}
func viewPointForTexture(point: CGPoint) -> CGPoint? {
var result: CGPoint?
guard let transform = textureTranform?.inverted() else {
return result
}
let transformPoint = point.applying(transform)
if internalBounds.contains(transformPoint) {
result = transformPoint
} else {
print("Invalid point \(point) result point \(transformPoint)")
}
return result
}
func flushTextureCache() {
textureCache = nil
}
private func setupTransform(width: Int, height: Int, mirroring: Bool, rotation: Rotation) {
var scaleX: Float = 1.0
var scaleY: Float = 1.0
var resizeAspect: Float = 1.0
internalBounds = self.bounds
textureWidth = width
textureHeight = height
textureMirroring = mirroring
textureRotation = rotation
if textureWidth > 0 && textureHeight > 0 {
switch textureRotation {
case .rotate0Degrees, .rotate180Degrees:
scaleX = Float(internalBounds.width / CGFloat(textureWidth))
scaleY = Float(internalBounds.height / CGFloat(textureHeight))
case .rotate90Degrees, .rotate270Degrees:
scaleX = Float(internalBounds.width / CGFloat(textureHeight))
scaleY = Float(internalBounds.height / CGFloat(textureWidth))
}
}
// Resize aspect ratio.
resizeAspect = min(scaleX, scaleY)
if scaleX < scaleY {
scaleY = scaleX / scaleY
scaleX = 1.0
} else {
scaleX = scaleY / scaleX
scaleY = 1.0
}
if textureMirroring {
scaleX *= -1.0
}
// Vertex coordinate takes the gravity into account.
let vertexData: [Float] = [
-scaleX, -scaleY, 0.0, 1.0,
scaleX, -scaleY, 0.0, 1.0,
-scaleX, scaleY, 0.0, 1.0,
scaleX, scaleY, 0.0, 1.0
]
vertexCoordBuffer = device!.makeBuffer(
bytes: vertexData,
length: vertexData.count * MemoryLayout<Float>.size,
options: []
)
// Texture coordinate takes the rotation into account.
var textData: [Float]
switch textureRotation {
case .rotate0Degrees:
textData = [
0.0, 1.0,
1.0, 1.0,
0.0, 0.0,
1.0, 0.0
]
case .rotate180Degrees:
textData = [
1.0, 0.0,
0.0, 0.0,
1.0, 1.0,
0.0, 1.0
]
case .rotate90Degrees:
textData = [
1.0, 1.0,
1.0, 0.0,
0.0, 1.0,
0.0, 0.0
]
case .rotate270Degrees:
textData = [
0.0, 0.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0
]
}
textCoordBuffer = device?.makeBuffer(
bytes: textData,
length: textData.count * MemoryLayout<Float>.size,
options: []
)
// Calculate the transform from texture coordinates to view coordinates
var transform = CGAffineTransform.identity
if textureMirroring {
transform = transform.concatenating(CGAffineTransform(scaleX: -1, y: 1))
transform = transform.concatenating(CGAffineTransform(translationX: CGFloat(textureWidth), y: 0))
}
switch textureRotation {
case .rotate0Degrees:
transform = transform.concatenating(CGAffineTransform(rotationAngle: CGFloat(0)))
case .rotate180Degrees:
transform = transform.concatenating(CGAffineTransform(rotationAngle: CGFloat(Double.pi)))
transform = transform.concatenating(
CGAffineTransform(
translationX: CGFloat(textureWidth),
y: CGFloat(textureHeight)
)
)
case .rotate90Degrees:
transform = transform.concatenating(CGAffineTransform(rotationAngle: CGFloat(Double.pi) / 2))
transform = transform.concatenating(CGAffineTransform(translationX: CGFloat(textureHeight), y: 0))
case .rotate270Degrees:
transform = transform.concatenating(CGAffineTransform(rotationAngle: 3 * CGFloat(Double.pi) / 2))
transform = transform.concatenating(CGAffineTransform(translationX: 0, y: CGFloat(textureWidth)))
}
transform = transform.concatenating(CGAffineTransform(scaleX: CGFloat(resizeAspect), y: CGFloat(resizeAspect)))
let tranformRect = CGRect(
origin: .zero,
size: CGSize(width: textureWidth, height: textureHeight)
).applying(transform)
let xShift = (internalBounds.size.width - tranformRect.size.width) / 2
let yShift = (internalBounds.size.height - tranformRect.size.height) / 2
transform = transform.concatenating(CGAffineTransform(translationX: xShift, y: yShift))
textureTranform = transform.inverted()
}
init() {
super.init(frame: .zero, device: MTLCreateSystemDefaultDevice())
configureMetal()
createTextureCache()
colorPixelFormat = .bgra8Unorm
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureMetal() {
guard let device = device else {
return
}
let defaultLibrary: MTLLibrary
PhotoManager.shared.createBundle()
if let bundle = PhotoManager.shared.bundle,
let path = bundle.path(forResource: "metal/default", ofType: "metallib"),
let library = try? device.makeLibrary(filepath: path) {
defaultLibrary = library
}else {
do {
defaultLibrary = try device.makeDefaultLibrary(bundle: .main)
} catch {
return
}
}
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineDescriptor.vertexFunction = defaultLibrary.makeFunction(name: "vertexPassThrough")
pipelineDescriptor.fragmentFunction = defaultLibrary.makeFunction(name: "fragmentPassThrough")
let samplerDescriptor = MTLSamplerDescriptor()
samplerDescriptor.sAddressMode = .clampToEdge
samplerDescriptor.tAddressMode = .clampToEdge
samplerDescriptor.minFilter = .linear
samplerDescriptor.magFilter = .linear
sampler = device.makeSamplerState(descriptor: samplerDescriptor)
do {
renderPipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor)
} catch {
fatalError("Unable to create preview Metal view pipeline state. (\(error))")
}
preferredFramesPerSecond = 30
commandQueue = device.makeCommandQueue()
}
func createTextureCache() {
guard let device = device else { return }
var newTextureCache: CVMetalTextureCache?
if CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device, nil, &newTextureCache) == kCVReturnSuccess {
textureCache = newTextureCache
}
}
/// - Tag: DrawMetalTexture
override func draw(_ rect: CGRect) {
var pixelBuffer: CVPixelBuffer?
var mirroring = false
var rotation: Rotation = .rotate0Degrees
syncQueue.sync {
pixelBuffer = internalPixelBuffer
mirroring = internalMirroring
rotation = internalRotation
}
guard let drawable = currentDrawable,
let currentRenderPassDescriptor = currentRenderPassDescriptor,
let previewPixelBuffer = pixelBuffer else {
return
}
// Create a Metal texture from the image buffer.
let width = CVPixelBufferGetWidth(previewPixelBuffer)
let height = CVPixelBufferGetHeight(previewPixelBuffer)
if textureCache == nil {
createTextureCache()
}
guard let textureCache = textureCache else { return }
var cvTextureOut: CVMetalTexture?
CVMetalTextureCacheCreateTextureFromImage(
kCFAllocatorDefault,
textureCache,
previewPixelBuffer,
nil,
.bgra8Unorm,
width,
height,
0,
&cvTextureOut
)
guard let cvTexture = cvTextureOut, let texture = CVMetalTextureGetTexture(cvTexture) else {
print("Failed to create preview texture")
CVMetalTextureCacheFlush(textureCache, 0)
return
}
if texture.width != textureWidth ||
texture.height != textureHeight ||
self.bounds != internalBounds ||
mirroring != textureMirroring ||
rotation != textureRotation {
setupTransform(
width: texture.width,
height: texture.height,
mirroring: mirroring,
rotation: rotation
)
}
// Set up command buffer and encoder
guard let commandQueue = commandQueue else {
print("Failed to create Metal command queue")
CVMetalTextureCacheFlush(textureCache, 0)
return
}
guard let commandBuffer = commandQueue.makeCommandBuffer() else {
print("Failed to create Metal command buffer")
CVMetalTextureCacheFlush(textureCache, 0)
return
}
guard let commandEncoder = commandBuffer.makeRenderCommandEncoder(
descriptor: currentRenderPassDescriptor
) else {
print("Failed to create Metal command encoder")
CVMetalTextureCacheFlush(textureCache, 0)
return
}
commandEncoder.label = "Preview display"
commandEncoder.setRenderPipelineState(renderPipelineState!)
commandEncoder.setVertexBuffer(vertexCoordBuffer, offset: 0, index: 0)
commandEncoder.setVertexBuffer(textCoordBuffer, offset: 0, index: 1)
commandEncoder.setFragmentTexture(texture, index: 0)
commandEncoder.setFragmentSamplerState(sampler, index: 0)
commandEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
commandEncoder.endEncoding()
// Draw to the screen.
commandBuffer.present(drawable)
commandBuffer.commit()
DispatchQueue.main.async {
self.didPreviewing?(!self.isPreviewing)
self.isPreviewing = true
}
}
}
| af757e2c4101c991eeb4d99990d8f068 | 32.562963 | 119 | 0.580299 | false | false | false | false |
kevintulod/CascadeKit-iOS | refs/heads/master | CascadeExample/CascadeExample/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// CascadeExample
//
// Created by Kevin Tulod on 1/7/17.
// Copyright © 2017 Kevin Tulod. All rights reserved.
//
import UIKit
import CascadeKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let first = CascadingNavigationController(tableNumber: 1)
let second = CascadingNavigationController(tableNumber: 2)
let cascadeController = CascadeController.create()
cascadeController.setup(first: first, second: second)
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = cascadeController
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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 11f55b433ab2418026a9cb64ea9444c5 | 44.553571 | 285 | 0.740886 | false | false | false | false |
blackmirror-media/BMAccordion | refs/heads/develop | Pod/Classes/BMAccordionTheme.swift | mit | 1 | //
// BMAccordionTheme.swift
//
//
// Created by Adam Eri on 03/08/2015.
//
//
import UIKit
public class BMAccordionTheme: NSObject {
// Section headers
static var sectionHeight: CGFloat = 60.0
static var sectionBackgroundColor: UIColor = UIColor.whiteColor()
static var sectionTextColor: UIColor = UIColor.blackColor()
static var sectionFont: UIFont = UIFont.systemFontOfSize(17)
// static var sectionFont: UIFont = UIFont.systemFontOfSize(17, weight: UIFontWeightRegular)
static var sectionCaretColor: UIColor = UIColor.blackColor()
// Badges
static var badgeBackgroundColor: UIColor = UIColor.blackColor()
static var badgeTextColor: UIColor = UIColor.whiteColor()
static var badgeFont: UIFont = UIFont.systemFontOfSize(12)
// static var badgeFont: UIFont = UIFont.systemFontOfSize(12, weight: UIFontWeightMedium)
static var badgeCornerRadius: CGFloat = 9
// Cells
static var cellFont: UIFont = UIFont.systemFontOfSize(17)
// static var cellFont: UIFont = UIFont.systemFontOfSize(17, weight: UIFontWeightMedium)
static var cellTextColor: UIColor = UIColor.lightGrayColor()
static var cellBackgroundColor: UIColor = UIColor.whiteColor()
// Animations
static var sectionOpeningAnimation: UITableViewRowAnimation = .Left
static var sectionClosingAnimation: UITableViewRowAnimation = .Left
}
| f495b3997cd2eed231b69a7bb5b9fc0b | 35.368421 | 95 | 0.74602 | false | false | false | false |
WangCrystal/actor-platform | refs/heads/master | actor-apps/app-ios/ActorApp/Controllers/Group/AddParticipantViewController.swift | mit | 7 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class AddParticipantViewController: ContactsBaseViewController {
var tableView: UITableView!
let gid: Int
init (gid: Int) {
self.gid = gid
super.init(contentSection: 1)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
title = NSLocalizedString("GroupAddParticipantTitle", comment: "Participant Title")
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("NavigationCancel", comment: "Cancel"),
style: UIBarButtonItemStyle.Plain,
target: self, action: Selector("dismiss"))
tableView = UITableView(frame: view.bounds, style: UITableViewStyle.Plain)
tableView.backgroundColor = UIColor.whiteColor()
view = tableView
bindTable(tableView, fade: true);
super.viewDidLoad();
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0) {
return 1
} else {
return super.tableView(tableView, numberOfRowsInSection: section)
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.section == 0) {
let reuseId = "cell_invite";
let res = ContactActionCell(reuseIdentifier: reuseId)
res.bind("ic_invite_user",
actionTitle: NSLocalizedString("GroupAddParticipantUrl", comment: "Action Title"),
isLast: false)
return res
} else {
return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.section == 0 {
navigateNext(InviteLinkViewController(gid: gid), removeCurrent: false)
} else {
let contact = objectAtIndexPath(indexPath) as! ACContact;
execute(Actor.inviteMemberCommandWithGid(jint(gid), withUid: contact.getUid()), successBlock: { (val) -> () in
self.dismiss()
}, failureBlock: { (val) -> () in
self.dismiss()
})
}
}
}
| 168282e4da4cbe59a40e7ed733598af1 | 33.051282 | 122 | 0.605045 | false | false | false | false |
pecuniabanking/pecunia-client | refs/heads/master | Source/ExSwift/ExSwift.swift | gpl-2.0 | 1 | //
// ExSwift.swift
// ExSwift
//
// Created by pNre on 07/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
infix operator =~
infix operator |~
infix operator ..
infix operator <=>
public typealias Ex = ExSwift
open class ExSwift {
/**
Creates a wrapper that, executes function only after being called n times.
- parameter n: No. of times the wrapper has to be called before function is invoked
- parameter function: Function to wrap
- returns: Wrapper function
*/
open class func after <P, T> (_ n: Int, function: @escaping (P...) -> T) -> ((P...) -> T?) {
typealias Function = ([P]) -> T
var times = n
return {
(params: P...) -> T? in
// Workaround for the now illegal (T...) type.
let adaptedFunction = unsafeBitCast(function, to: Function.self)
if times <= 0 {
return adaptedFunction(params)
}
times = times - 1;
return nil
}
}
/**
Creates a wrapper that, executes function only after being called n times
- parameter n: No. of times the wrapper has to be called before function is invoked
- parameter function: Function to wrap
- returns: Wrapper function
*/
/*public class func after <T> (n: Int, function: Void -> T) -> (Void -> T?) {
func callAfter (args: Any?...) -> T {
return function()
}
let f = ExSwift.after(n, function: callAfter)
return { f([nil]) }
}*/
/**
Creates a wrapper function that invokes function once.
Repeated calls to the wrapper function will return the value of the first call.
- parameter function: Function to wrap
- returns: Wrapper function
*/
open class func once <P, T> (_ function: @escaping (P...) -> T) -> ((P...) -> T) {
typealias Function = ([P]) -> T
var returnValue: T? = nil
return { (params: P...) -> T in
if returnValue != nil {
return returnValue!
}
let adaptedFunction = unsafeBitCast(function, to: Function.self)
returnValue = adaptedFunction(params)
return returnValue!
}
}
/**
Creates a wrapper function that invokes function once.
Repeated calls to the wrapper function will return the value of the first call.
- parameter function: Function to wrap
- returns: Wrapper function
*/
/*public class func once <T> (function: Void -> T) -> (Void -> T) {
let f = ExSwift.once {
(params: Any?...) -> T in
return function()
}
return { f([nil]) }
}*/
/**
Creates a wrapper that, when called, invokes function with any additional
partial arguments prepended to those provided to the new function.
- parameter function: Function to wrap
- parameter parameters: Arguments to prepend
- returns: Wrapper function
*/
open class func partial <P, T> (_ function: @escaping (P...) -> T, _ parameters: P...) -> ((P...) -> T) {
typealias Function = ([P]) -> T
return { (params: P...) -> T in
let adaptedFunction = unsafeBitCast(function, to: Function.self)
return adaptedFunction(parameters + params)
}
}
/**
Creates a wrapper for function that caches the result of function's invocations.
- parameter function: Function with one parameter to cache
- returns: Wrapper function
*/
open class func cached <P: Hashable, R> (_ function: @escaping (P) -> R) -> ((P) -> R) {
var cache = [P:R]()
return { (param: P) -> R in
let key = param
if let cachedValue = cache[key] {
return cachedValue
} else {
let value = function(param)
cache[key] = value
return value
}
}
}
/**
Creates a wrapper for function that caches the result of function's invocations.
- parameter function: Function to cache
- parameter hash: Parameters based hashing function that computes the key used to store each result in the cache
- returns: Wrapper function
*/
open class func cached <P: Hashable, R> (_ function: @escaping (P...) -> R, hash: @escaping ((P...) -> P)) -> ((P...) -> R) {
typealias Function = ([P]) -> R
typealias Hash = ([P]) -> P
var cache = [P:R]()
return { (params: P...) -> R in
let adaptedFunction = unsafeBitCast(function, to: Function.self)
let adaptedHash = unsafeBitCast(hash, to: Hash.self)
let key = adaptedHash(params)
if let cachedValue = cache[key] {
return cachedValue
} else {
let value = adaptedFunction(params)
cache[key] = value
return value
}
}
}
/**
Creates a wrapper for function that caches the result of function's invocations.
- parameter function: Function to cache
- returns: Wrapper function
*/
open class func cached <P: Hashable, R> (_ function: @escaping (P...) -> R) -> ((P...) -> R) {
return cached(function, hash: { (params: P...) -> P in return params[0] })
}
/**
Utility method to return an NSRegularExpression object given a pattern.
- parameter pattern: Regex pattern
- parameter ignoreCase: If true the NSRegularExpression is created with the NSRegularExpressionOptions.CaseInsensitive flag
- returns: NSRegularExpression object
*/
internal class func regex (_ pattern: String, ignoreCase: Bool = false) throws -> NSRegularExpression? {
var options = NSRegularExpression.Options.dotMatchesLineSeparators.rawValue
if ignoreCase {
options = NSRegularExpression.Options.caseInsensitive.rawValue | options
}
return try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: options))
}
}
func <=> <T: Comparable>(lhs: T, rhs: T) -> Int {
if lhs < rhs {
return -1
} else if lhs > rhs {
return 1
} else {
return 0
}
}
/**
* Internal methods
*/
extension ExSwift {
/**
* Converts, if possible, and flattens an object from its Objective-C
* representation to the Swift one.
* @param object Object to convert
* @returns Flattenend array of converted values
*/
internal class func bridgeObjCObject <T, S> (_ object: S) -> [T] {
var result = [T]()
let reflection = Mirror(reflecting: object)
let mirrorChildrenCollection = AnyRandomAccessCollection(reflection.children)
// object has an Objective-C type
if let obj = object as? T {
// object has type T
result.append(obj)
} else if reflection.subjectType == NSArray.self {
// If it is an NSArray, flattening will produce the expected result
if let array = object as? NSArray {
result += array.flatten()
} else if let bridged = mirrorChildrenCollection as? T {
result.append(bridged)
}
} else if object is Array<T> {
// object is a native Swift array
// recursively convert each item
for (_, value) in mirrorChildrenCollection! {
result += Ex.bridgeObjCObject(value)
}
}
return result
}
}
| 9b0953a72b1c8c490a7cb865c1db994a | 29.877863 | 131 | 0.538813 | false | false | false | false |
1d4Nf6/RazzleDazzle | refs/heads/develop | API_Moya/Pods/Quick/Quick/Callsite.swift | apache-2.0 | 201 | /**
An object encapsulating the file and line number at which
a particular example is defined.
*/
@objc final public class Callsite: Equatable {
/**
The absolute path of the file in which an example is defined.
*/
public let file: String
/**
The line number on which an example is defined.
*/
public let line: Int
internal init(file: String, line: Int) {
self.file = file
self.line = line
}
}
/**
Returns a boolean indicating whether two Callsite objects are equal.
If two callsites are in the same file and on the same line, they must be equal.
*/
public func ==(lhs: Callsite, rhs: Callsite) -> Bool {
return lhs.file == rhs.file && lhs.line == rhs.line
}
| bcdb77e9d094e9eb0edc9180f17d1a21 | 25.607143 | 83 | 0.638926 | false | false | false | false |
khizkhiz/swift | refs/heads/master | test/SILGen/witnesses.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s
infix operator <~> {}
func archetype_method<T: X>(x x: T, y: T) -> T {
var x = x
var y = y
return x.selfTypes(x: y)
}
// CHECK-LABEL: sil hidden @_TF9witnesses16archetype_method{{.*}} : $@convention(thin) <T where T : X> (@in T, @in T) -> @out T {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.selfTypes!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
// CHECK: apply [[METHOD]]<T>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
// CHECK: }
func archetype_generic_method<T: X>(x x: T, y: Loadable) -> Loadable {
var x = x
return x.generic(x: y)
}
// CHECK-LABEL: sil hidden @_TF9witnesses24archetype_generic_method{{.*}} : $@convention(thin) <T where T : X> (@in T, Loadable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.generic!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in τ_1_0, @inout τ_0_0) -> @out τ_1_0
// CHECK: apply [[METHOD]]<T, Loadable>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in τ_1_0, @inout τ_0_0) -> @out τ_1_0
// CHECK: }
// CHECK-LABEL: sil hidden @_TF9witnesses32archetype_associated_type_method{{.*}} : $@convention(thin) <T where T : WithAssoc> (@in T, @in T.AssocType) -> @out T
// CHECK: apply %{{[0-9]+}}<T, T.AssocType>
func archetype_associated_type_method<T: WithAssoc>(x x: T, y: T.AssocType) -> T {
return x.useAssocType(x: y)
}
protocol StaticMethod { static func staticMethod() }
// CHECK-LABEL: sil hidden @_TF9witnesses23archetype_static_method{{.*}} : $@convention(thin) <T where T : StaticMethod> (@in T) -> ()
func archetype_static_method<T: StaticMethod>(x x: T) {
// CHECK: [[METHOD:%.*]] = witness_method $T, #StaticMethod.staticMethod!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : StaticMethod> (@thick τ_0_0.Type) -> ()
// CHECK: apply [[METHOD]]<T>
T.staticMethod()
}
protocol Existentiable {
func foo() -> Loadable
func generic<T>() -> T
}
func protocol_method(x x: Existentiable) -> Loadable {
return x.foo()
}
// CHECK-LABEL: sil hidden @_TF9witnesses15protocol_methodFT1xPS_13Existentiable__VS_8Loadable : $@convention(thin) (@in Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.foo!1
// CHECK: apply [[METHOD]]<[[OPENED]]>({{%.*}})
// CHECK: }
func protocol_generic_method(x x: Existentiable) -> Loadable {
return x.generic()
}
// CHECK-LABEL: sil hidden @_TF9witnesses23protocol_generic_methodFT1xPS_13Existentiable__VS_8Loadable : $@convention(thin) (@in Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.generic!1
// CHECK: apply [[METHOD]]<[[OPENED]], Loadable>({{%.*}}, {{%.*}})
// CHECK: }
@objc protocol ObjCAble {
func foo()
}
// CHECK-LABEL: sil hidden @_TF9witnesses20protocol_objc_methodFT1xPS_8ObjCAble__T_ : $@convention(thin) (@owned ObjCAble) -> ()
// CHECK: witness_method [volatile] $@opened({{.*}}) ObjCAble, #ObjCAble.foo!1.foreign
func protocol_objc_method(x x: ObjCAble) {
x.foo()
}
struct Loadable {}
protocol AddrOnly {}
protocol Classes : class {}
protocol X {
mutating
func selfTypes(x x: Self) -> Self
mutating
func loadable(x x: Loadable) -> Loadable
mutating
func addrOnly(x x: AddrOnly) -> AddrOnly
mutating
func generic<A>(x x: A) -> A
mutating
func classes<A2: Classes>(x x: A2) -> A2
func <~>(x: Self, y: Self) -> Self
}
protocol Y {}
protocol WithAssoc {
associatedtype AssocType
func useAssocType(x x: AssocType) -> Self
}
protocol ClassBounded : class {
func selfTypes(x x: Self) -> Self
}
struct ConformingStruct : X {
mutating
func selfTypes(x x: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformingStruct, @inout ConformingStruct) -> @out ConformingStruct {
// CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct):
// CHECK-NEXT: %3 = load %1 : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %4 = function_ref @_TFV9witnesses16ConformingStruct9selfTypes{{.*}} : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: %5 = apply %4(%3, %2) : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store %5 to %0 : $*ConformingStruct
// CHECK-NEXT: %7 = tuple ()
// CHECK-NEXT: return %7 : $()
// CHECK-NEXT: }
mutating
func loadable(x x: Loadable) -> Loadable { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_8loadable{{.*}} : $@convention(witness_method) (Loadable, @inout ConformingStruct) -> Loadable {
// CHECK: bb0(%0 : $Loadable, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @_TFV9witnesses16ConformingStruct8loadable{{.*}} : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: %3 = apply %2(%0, %1) : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: return %3 : $Loadable
// CHECK-NEXT: }
mutating
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_8addrOnly{{.*}} : $@convention(witness_method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly {
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses16ConformingStruct8addrOnly{{.*}} : $@convention(method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
mutating
func generic<C>(x x: C) -> C { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_7generic{{.*}} : $@convention(witness_method) <A> (@in A, @inout ConformingStruct) -> @out A {
// CHECK: bb0(%0 : $*A, %1 : $*A, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses16ConformingStruct7generic{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<A>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
mutating
func classes<C2: Classes>(x x: C2) -> C2 { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_7classes{{.*}} : $@convention(witness_method) <A2 where A2 : Classes> (@owned A2, @inout ConformingStruct) -> @owned A2 {
// CHECK: bb0(%0 : $A2, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @_TFV9witnesses16ConformingStruct7classes{{.*}} : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: %3 = apply %2<A2>(%0, %1) : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: return %3 : $A2
// CHECK-NEXT: }
}
func <~>(x: ConformingStruct, y: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> @out ConformingStruct {
// CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct, %3 : $@thick ConformingStruct.Type):
// CHECK-NEXT: %4 = load %1 : $*ConformingStruct
// CHECK-NEXT: %5 = load %2 : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %6 = function_ref @_TZF9witnessesoi3ltgFTVS_16ConformingStructS0__S0_ : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: %7 = apply %6(%4, %5) : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store %7 to %0 : $*ConformingStruct
// CHECK-NEXT: %9 = tuple ()
// CHECK-NEXT: return %9 : $()
// CHECK-NEXT: }
final class ConformingClass : X {
func selfTypes(x x: ConformingClass) -> ConformingClass { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses15ConformingClassS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformingClass, @inout ConformingClass) -> @out ConformingClass {
// CHECK: bb0(%0 : $*ConformingClass, %1 : $*ConformingClass, %2 : $*ConformingClass):
// -- load and retain 'self' from inout witness 'self' parameter
// CHECK-NEXT: %3 = load %2 : $*ConformingClass
// CHECK-NEXT: strong_retain %3 : $ConformingClass
// CHECK-NEXT: %5 = load %1 : $*ConformingClass
// CHECK: %6 = function_ref @_TFC9witnesses15ConformingClass9selfTypes
// CHECK-NEXT: %7 = apply %6(%5, %3) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK-NEXT: store %7 to %0 : $*ConformingClass
// CHECK-NEXT: %9 = tuple ()
// CHECK-NEXT: strong_release %3
// CHECK-NEXT: return %9 : $()
// CHECK-NEXT: }
func loadable(x x: Loadable) -> Loadable { return x }
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x x: D) -> D { return x }
func classes<D2: Classes>(x x: D2) -> D2 { return x }
}
func <~>(x: ConformingClass, y: ConformingClass) -> ConformingClass { return x }
extension ConformingClass : ClassBounded { }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses15ConformingClassS_12ClassBoundedS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass {
// CHECK: bb0([[C0:%.*]] : $ConformingClass, [[C1:%.*]] : $ConformingClass):
// CHECK-NEXT: strong_retain [[C1]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @_TFC9witnesses15ConformingClass9selfTypes
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[C0]], [[C1]]) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK-NEXT: strong_release [[C1]]
// CHECK-NEXT: return [[RESULT]] : $ConformingClass
// CHECK-NEXT: }
struct ConformingAOStruct : X {
var makeMeAO : AddrOnly
mutating
func selfTypes(x x: ConformingAOStruct) -> ConformingAOStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses18ConformingAOStructS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct {
// CHECK: bb0(%0 : $*ConformingAOStruct, %1 : $*ConformingAOStruct, %2 : $*ConformingAOStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses18ConformingAOStruct9selfTypes{{.*}} : $@convention(method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
func loadable(x x: Loadable) -> Loadable { return x }
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x x: D) -> D { return x }
func classes<D2: Classes>(x x: D2) -> D2 { return x }
}
func <~>(x: ConformingAOStruct, y: ConformingAOStruct) -> ConformingAOStruct { return x }
struct ConformsWithMoreGeneric : X, Y {
mutating
func selfTypes<E>(x x: E) -> E { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGeneric, @inout ConformsWithMoreGeneric) -> @out ConformsWithMoreGeneric {
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TFV9witnesses23ConformsWithMoreGeneric9selfTypes{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
func loadable<F>(x x: F) -> F { return x }
mutating
func addrOnly<G>(x x: G) -> G { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_8addrOnly{{.*}} : $@convention(witness_method) (@in AddrOnly, @inout ConformsWithMoreGeneric) -> @out AddrOnly {
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric8addrOnly{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<AddrOnly>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
mutating
func generic<H>(x x: H) -> H { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_7generic{{.*}} : $@convention(witness_method) <A> (@in A, @inout ConformsWithMoreGeneric) -> @out A {
// CHECK: bb0(%0 : $*A, %1 : $*A, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric7generic{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<A>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
mutating
func classes<I>(x x: I) -> I { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_7classes{{.*}} : $@convention(witness_method) <A2 where A2 : Classes> (@owned A2, @inout ConformsWithMoreGeneric) -> @owned A2 {
// CHECK: bb0(%0 : $A2, %1 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $A2
// CHECK-NEXT: store %0 to [[SELF_BOX]] : $*A2
// CHECK-NEXT: // function_ref witnesses.ConformsWithMoreGeneric.classes
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TFV9witnesses23ConformsWithMoreGeneric7classes{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $A2
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<A2>([[RESULT_BOX]], [[SELF_BOX]], %1) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = load [[RESULT_BOX]] : $*A2
// CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*A2
// CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*A2
// CHECK-NEXT: return [[RESULT]] : $A2
// CHECK-NEXT: }
}
func <~> <J: Y, K: Y>(x: J, y: K) -> K { return y }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @thick ConformsWithMoreGeneric.Type) -> @out ConformsWithMoreGeneric {
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric, %3 : $@thick ConformsWithMoreGeneric.Type):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TZF9witnessesoi3ltg{{.*}} : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in τ_0_0, @in τ_0_1) -> @out τ_0_1
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric, ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in τ_0_0, @in τ_0_1) -> @out τ_0_1
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
protocol LabeledRequirement {
func method(x x: Loadable)
}
struct UnlabeledWitness : LabeledRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16UnlabeledWitnessS_18LabeledRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (Loadable, @in_guaranteed UnlabeledWitness) -> ()
func method(x _: Loadable) {}
}
protocol LabeledSelfRequirement {
func method(x x: Self)
}
struct UnlabeledSelfWitness : LabeledSelfRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses20UnlabeledSelfWitnessS_22LabeledSelfRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (@in UnlabeledSelfWitness, @in_guaranteed UnlabeledSelfWitness) -> ()
func method(x _: UnlabeledSelfWitness) {}
}
protocol UnlabeledRequirement {
func method(x _: Loadable)
}
struct LabeledWitness : UnlabeledRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14LabeledWitnessS_20UnlabeledRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (Loadable, @in_guaranteed LabeledWitness) -> ()
func method(x x: Loadable) {}
}
protocol UnlabeledSelfRequirement {
func method(_: Self)
}
struct LabeledSelfWitness : UnlabeledSelfRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses18LabeledSelfWitnessS_24UnlabeledSelfRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (@in LabeledSelfWitness, @in_guaranteed LabeledSelfWitness) -> ()
func method(x: LabeledSelfWitness) {}
}
protocol ReadOnlyRequirement {
var prop: String { get }
static var prop: String { get }
}
struct ImmutableModel: ReadOnlyRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14ImmutableModelS_19ReadOnlyRequirementS_FS1_g4propSS : $@convention(witness_method) (@in_guaranteed ImmutableModel) -> @owned String
let prop: String = "a"
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14ImmutableModelS_19ReadOnlyRequirementS_ZFS1_g4propSS : $@convention(witness_method) (@thick ImmutableModel.Type) -> @owned String
static let prop: String = "b"
}
protocol FailableRequirement {
init?(foo: Int)
}
protocol NonFailableRefinement: FailableRequirement {
init(foo: Int)
}
protocol IUOFailableRequirement {
init!(foo: Int)
}
struct NonFailableModel: FailableRequirement, NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_19FailableRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out Optional<NonFailableModel>
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_21NonFailableRefinementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out NonFailableModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_22IUOFailableRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out ImplicitlyUnwrappedOptional<NonFailableModel>
init(foo: Int) {}
}
struct FailableModel: FailableRequirement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses13FailableModelS_19FailableRequirementS_FS1_C{{.*}}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses13FailableModelS_22IUOFailableRequirementS_FS1_C{{.*}}
// CHECK: bb0([[SELF:%[0-9]+]] : $*ImplicitlyUnwrappedOptional<FailableModel>, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick FailableModel.Type):
// CHECK: [[FN:%.*]] = function_ref @_TFV9witnesses13FailableModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FN]](
// CHECK: [[OUTER:%.*]] = unchecked_trivial_bit_cast [[INNER]] : $Optional<FailableModel> to $ImplicitlyUnwrappedOptional<FailableModel>
// CHECK: store [[OUTER]] to %0
// CHECK: return
init?(foo: Int) {}
}
struct IUOFailableModel : NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16IUOFailableModelS_21NonFailableRefinementS_FS1_C{{.*}}
// CHECK: bb0([[SELF:%[0-9]+]] : $*IUOFailableModel, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick IUOFailableModel.Type):
// CHECK: [[META:%[0-9]+]] = metatype $@thin IUOFailableModel.Type
// CHECK: [[INIT:%[0-9]+]] = function_ref @_TFV9witnesses16IUOFailableModelC{{.*}} : $@convention(thin) (Int, @thin IUOFailableModel.Type) -> ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[FOO]], [[META]]) : $@convention(thin) (Int, @thin IUOFailableModel.Type) -> ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[IUO_RESULT_TEMP:%[0-9]+]] = alloc_stack $ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: store [[IUO_RESULT]] to [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[FORCE_FN:%[0-9]+]] = function_ref @_TFs45_stdlib_ImplicitlyUnwrappedOptional_unwrappedurFGSQx_x{{.*}} : $@convention(thin) <τ_0_0> (@in ImplicitlyUnwrappedOptional<τ_0_0>) -> @out τ_0_0
// CHECK: [[RESULT_TEMP:%[0-9]+]] = alloc_stack $IUOFailableModel
// CHECK: apply [[FORCE_FN]]<IUOFailableModel>([[RESULT_TEMP]], [[IUO_RESULT_TEMP]]) : $@convention(thin) <τ_0_0> (@in ImplicitlyUnwrappedOptional<τ_0_0>) -> @out τ_0_0
// CHECK: [[RESULT:%[0-9]+]] = load [[RESULT_TEMP]] : $*IUOFailableModel
// CHECK: store [[RESULT]] to [[SELF]] : $*IUOFailableModel
// CHECK: dealloc_stack [[RESULT_TEMP]] : $*IUOFailableModel
// CHECK: dealloc_stack [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: return
init!(foo: Int) { return nil }
}
protocol FailableClassRequirement: class {
init?(foo: Int)
}
protocol NonFailableClassRefinement: FailableClassRequirement {
init(foo: Int)
}
protocol IUOFailableClassRequirement: class {
init!(foo: Int)
}
final class NonFailableClassModel: FailableClassRequirement, NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned Optional<NonFailableClassModel>
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_26NonFailableClassRefinementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned NonFailableClassModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned ImplicitlyUnwrappedOptional<NonFailableClassModel>
init(foo: Int) {}
}
final class FailableClassModel: FailableClassRequirement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses18FailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses18FailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}}
// CHECK: [[FUNC:%.*]] = function_ref @_TFC9witnesses18FailableClassModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: [[OUTER:%.*]] = unchecked_ref_cast [[INNER]] : $Optional<FailableClassModel> to $ImplicitlyUnwrappedOptional<FailableClassModel>
// CHECK: return [[OUTER]] : $ImplicitlyUnwrappedOptional<FailableClassModel>
init?(foo: Int) {}
}
final class IUOFailableClassModel: NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_26NonFailableClassRefinementS_FS1_C{{.*}}
// CHECK: function_ref @_TFs45_stdlib_ImplicitlyUnwrappedOptional_unwrappedurFGSQx_x
// CHECK: return [[RESULT:%[0-9]+]] : $IUOFailableClassModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}}
init!(foo: Int) {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}}
// CHECK: [[FUNC:%.*]] = function_ref @_TFC9witnesses21IUOFailableClassModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: [[OUTER:%.*]] = unchecked_ref_cast [[INNER]] : $ImplicitlyUnwrappedOptional<IUOFailableClassModel> to $Optional<IUOFailableClassModel>
// CHECK: return [[OUTER]] : $Optional<IUOFailableClassModel>
}
protocol HasAssoc {
associatedtype Assoc
}
protocol GenericParameterNameCollisionProtocol {
func foo<T>(x: T)
associatedtype Assoc2
func bar<T>(x: T -> Assoc2)
}
struct GenericParameterNameCollision<T: HasAssoc> :
GenericParameterNameCollisionProtocol {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTW{{.*}}GenericParameterNameCollision{{.*}}GenericParameterNameCollisionProtocol{{.*}}foo{{.*}} : $@convention(witness_method) <T1 where T1 : HasAssoc><T> (@in T, @in_guaranteed GenericParameterNameCollision<T1>) -> () {
// CHECK: bb0(%0 : $*T, %1 : $*GenericParameterNameCollision<T1>):
// CHECK: apply {{%.*}}<T1, T1.Assoc, T>
func foo<U>(x: U) {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTW{{.*}}GenericParameterNameCollision{{.*}}GenericParameterNameCollisionProtocol{{.*}}bar{{.*}} : $@convention(witness_method) <T1 where T1 : HasAssoc><T> (@owned @callee_owned (@in T) -> @out T1.Assoc, @in_guaranteed GenericParameterNameCollision<T1>) -> () {
// CHECK: bb0(%0 : $@callee_owned (@in T) -> @out T1.Assoc, %1 : $*GenericParameterNameCollision<T1>):
// CHECK: apply {{%.*}}<T1, T1.Assoc, T>
func bar<V>(x: V -> T.Assoc) {}
}
protocol PropertyRequirement {
var width: Int { get set }
static var height: Int { get set }
var depth: Int { get set }
}
class PropertyRequirementBase {
var width: Int = 12
static var height: Int = 13
}
class PropertyRequirementWitnessFromBase : PropertyRequirementBase, PropertyRequirement {
var depth: Int = 14
// Make sure the contravariant return type in materializeForSet works correctly
// If the witness is in a base class of the conforming class, make sure we have a bit_cast in there:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_FS1_m5widthSi : {{.*}} {
// CHECK: upcast
// CHECK-NEXT: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementBase, #PropertyRequirementBase.width!materializeForSet.1
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0
// CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1
// CHECK-NEXT: [[CAST:%.*]] = unchecked_trivial_bit_cast [[CADR]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CAST]] : {{.*}})
// CHECK-NEXT: strong_release
// CHECK-NEXT: return [[TUPLE]]
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_ZFS1_m6heightSi : {{.*}} {
// CHECK: [[OBJ:%.*]] = upcast %2 : $@thick PropertyRequirementWitnessFromBase.Type to $@thick PropertyRequirementBase.Type
// CHECK: [[METH:%.*]] = function_ref @_TZFC9witnesses23PropertyRequirementBasem6heightSi
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0
// CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1
// CHECK-NEXT: [[CAST:%.*]] = unchecked_trivial_bit_cast [[CADR]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CAST]] : {{.*}})
// CHECK-NEXT: return [[TUPLE]]
// Otherwise, we shouldn't need the bit_cast:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_FS1_m5depthSi
// CHECK: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementWitnessFromBase, #PropertyRequirementWitnessFromBase.depth!materializeForSet.1
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: [[RES:%.*]] = tuple
// CHECK-NEXT: strong_release
// CHECK-NEXT: return [[RES]]
}
| 12a1b7f6313ee056b9bf2483da442de1 | 58.321932 | 314 | 0.668792 | false | false | false | false |
senfi/KSTokenView | refs/heads/master | KSTokenView/KSUtils.swift | mit | 1 | //
// KSUtils.swift
// KSTokenView
//
// Created by Khawar Shahzad on 01/01/2015.
// Copyright (c) 2015 Khawar Shahzad. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
let KSTextEmpty = "\u{200B}"
class KSUtils : NSObject {
class func getRect(str: NSString, width: CGFloat, height: CGFloat, font: UIFont) -> CGRect {
let rectangleStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
rectangleStyle.alignment = NSTextAlignment.Center
let rectangleFontAttributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: rectangleStyle]
return str.boundingRectWithSize(CGSizeMake(width, height), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: rectangleFontAttributes, context: nil)
}
class func getRect(str: NSString, width: CGFloat, font: UIFont) -> CGRect {
let rectangleStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
rectangleStyle.alignment = NSTextAlignment.Center
let rectangleFontAttributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: rectangleStyle]
return str.boundingRectWithSize(CGSizeMake(width, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: rectangleFontAttributes, context: nil)
}
class func widthOfString(str: String, font: UIFont) -> CGFloat {
var attrs = [NSFontAttributeName: font]
var attributedString = NSMutableAttributedString(string:str, attributes:attrs)
return attributedString.size().width
}
class func isIpad() -> Bool {
return UIDevice.currentDevice().userInterfaceIdiom == .Pad
}
class func constrainsEnabled(view: UIView) -> Bool {
if (view.constraints().count > 0) {
return true
} else {
return false
}
}
}
extension UIColor {
func darkendColor(darkRatio: CGFloat) -> UIColor {
var h: CGFloat = 0.0, s: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0
if (getHue(&h, saturation: &s, brightness: &b, alpha: &a)) {
return UIColor(hue: h, saturation: s, brightness: b*darkRatio, alpha: a)
} else {
return self
}
}
}
| 21ce92f1b8409379c29bf412328282dd | 43.756757 | 182 | 0.723732 | false | false | false | false |
taironas/gonawin-engine-ios | refs/heads/master | GonawinEngineTests/GonawinAPITeamsTests.swift | mit | 1 | //
// GonawinAPITeamsTests.swift
// GonawinEngine
//
// Created by Remy JOURDE on 09/03/2016.
// Copyright © 2016 Remy Jourde. All rights reserved.
//
import Quick
import Nimble
import RxSwift
import GonawinEngine
class GonawinAPITeamsTests: QuickSpec {
let disposeBag = DisposeBag()
override func spec() {
describe("Teams endpoint") {
var engine: AuthorizedGonawinEngine!
beforeEach {
engine = GonawinEngine.newStubbingAuthorizedGonawinEngine()
}
it("returns a list of teams") {
var teams: [Team]?
engine.getTeams(1, count: 3)
.catchError(self.log)
.subscribe(onNext: {
teams = $0
})
.addDisposableTo(self.disposeBag)
expect(teams).toNot(beNil())
expect(teams?.count).to(equal(3))
expect(teams?[2].name).to(equal("Substitutes"))
}
}
describe("Team endpoint") {
var engine: AuthorizedGonawinEngine!
beforeEach {
engine = GonawinEngine.newStubbingAuthorizedGonawinEngine()
}
it("returns a team") {
var team: Team?
engine.getTeam(4260034)
.catchError(self.log)
.subscribe(onNext: {
team = $0
})
.addDisposableTo(self.disposeBag)
expect(team).toNot(beNil())
expect(team?.name).to(equal("FooFoo"))
expect(team?.membersCount).to(equal(4))
expect(team?.members?[1].username).to(equal("jsmith"))
expect(team?.tournaments?[2].name).to(equal("2015 Copa America"))
}
}
}
func log(error: Error) -> Observable<[Team]> {
print("error : \(error)")
return Observable.empty()
}
func log(error: Error) -> Observable<Team> {
print("error : \(error)")
return Observable.empty()
}
}
| cd40ba890748cc85852682f65e7eac91 | 27.034884 | 81 | 0.445873 | false | false | false | false |
00aney/Briefinsta | refs/heads/master | Briefinsta/Sources/Services/InstagramService.swift | mit | 1 | //
// InstagramService.swift
// Briefinsta
//
// Created by aney on 2017. 10. 25..
// Copyright © 2017년 Ted Kim. All rights reserved.
//
import Moya
protocol InstagramServiceType {
func user(with username: String, completion: @escaping (Result<[Medium]>) -> () )
func media(with username: String, offset: String?, completion: @escaping (Result<Media>) -> () )
}
final class InstagramService: InstagramServiceType {
private let provider : MoyaProvider<InstagramAPI>
init(
provider: MoyaProvider<InstagramAPI> = MoyaProvider<InstagramAPI>(plugins: [NetworkLoggerPlugin(verbose: true)])
) {
self.provider = provider
}
func user(with username: String, completion: @escaping (Result<[Medium]>) -> () ) {
provider.request(.user(username)) { result in
switch result {
case let .success(response):
let data = response.data
do {
let apiResult = try JSONDecoder().decode(InstagramMediaAPIResult.self, from: data)
let media = apiResult.user.media.items
completion(Result.success(media))
}
catch {
completion(Result.failure(error))
}
case let .failure(error):
completion(Result.failure(error))
}
}
}
func media(with username: String, offset: String?, completion: @escaping (Result<Media>) -> () ) {
provider.request(.media(username, offset)) { result in
switch result {
case let .success(response):
let data = response.data
do {
let apiResult = try JSONDecoder().decode(InstagramMediaAPIResult.self, from: data)
let media = apiResult.user.media
completion(Result.success(media))
}
catch {
completion(Result.failure(error))
}
case let .failure(error):
completion(Result.failure(error))
}
}
}
}
| 5d397675608f331b76a99d95d5d44611 | 27.892308 | 116 | 0.626198 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.