repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lorentey/swift | stdlib/public/core/MigrationSupport.swift | 12 | 36119 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file contains only support for types deprecated from previous versions
// of Swift
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "BidirectionalCollection")
public typealias BidirectionalIndexable = BidirectionalCollection
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "Collection")
public typealias IndexableBase = Collection
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "Collection")
public typealias Indexable = Collection
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "MutableCollection")
public typealias MutableIndexable = MutableCollection
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "RandomAccessCollection")
public typealias RandomAccessIndexable = RandomAccessCollection
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "RangeReplaceableIndexable")
public typealias RangeReplaceableIndexable = RangeReplaceableCollection
@available(swift, deprecated: 4.2, renamed: "EnumeratedSequence.Iterator")
public typealias EnumeratedIterator<T: Sequence> = EnumeratedSequence<T>.Iterator
@available(swift,deprecated: 4.2, obsoleted: 5.0, renamed: "CollectionOfOne.Iterator")
public typealias IteratorOverOne<T> = CollectionOfOne<T>.Iterator
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "EmptyCollection.Iterator")
public typealias EmptyIterator<T> = EmptyCollection<T>.Iterator
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyFilterSequence.Iterator")
public typealias LazyFilterIterator<T: Sequence> = LazyFilterSequence<T>.Iterator
@available(swift, deprecated: 3.1, obsoleted: 5.0, message: "Use Base.Index")
public typealias LazyFilterIndex<Base: Collection> = Base.Index
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyDropWhileSequence.Iterator")
public typealias LazyDropWhileIterator<T> = LazyDropWhileSequence<T>.Iterator where T: Sequence
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyDropWhileCollection.Index")
public typealias LazyDropWhileIndex<T> = LazyDropWhileCollection<T>.Index where T: Collection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyDropWhileCollection")
public typealias LazyDropWhileBidirectionalCollection<T> = LazyDropWhileCollection<T> where T: BidirectionalCollection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyFilterCollection")
public typealias LazyFilterBidirectionalCollection<T> = LazyFilterCollection<T> where T: BidirectionalCollection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyMapSequence.Iterator")
public typealias LazyMapIterator<T, E> = LazyMapSequence<T, E>.Iterator where T: Sequence
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyMapCollection")
public typealias LazyMapBidirectionalCollection<T, E> = LazyMapCollection<T, E> where T: BidirectionalCollection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyMapCollection")
public typealias LazyMapRandomAccessCollection<T, E> = LazyMapCollection<T, E> where T: RandomAccessCollection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyCollection")
public typealias LazyBidirectionalCollection<T> = LazyCollection<T> where T: BidirectionalCollection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyCollection")
public typealias LazyRandomAccessCollection<T> = LazyCollection<T> where T: RandomAccessCollection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "FlattenCollection.Index")
public typealias FlattenCollectionIndex<T> = FlattenCollection<T>.Index where T: Collection, T.Element: Collection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "FlattenCollection.Index")
public typealias FlattenBidirectionalCollectionIndex<T> = FlattenCollection<T>.Index where T: BidirectionalCollection, T.Element: BidirectionalCollection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "FlattenCollection")
public typealias FlattenBidirectionalCollection<T> = FlattenCollection<T> where T: BidirectionalCollection, T.Element: BidirectionalCollection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "JoinedSequence.Iterator")
public typealias JoinedIterator<T: Sequence> = JoinedSequence<T>.Iterator where T.Element: Sequence
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "Zip2Sequence.Iterator")
public typealias Zip2Iterator<T, U> = Zip2Sequence<T, U>.Iterator where T: Sequence, U: Sequence
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyPrefixWhileSequence.Iterator")
public typealias LazyPrefixWhileIterator<T> = LazyPrefixWhileSequence<T>.Iterator where T: Sequence
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyPrefixWhileCollection.Index")
public typealias LazyPrefixWhileIndex<T> = LazyPrefixWhileCollection<T>.Index where T: Collection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyPrefixWhileCollection")
public typealias LazyPrefixWhileBidirectionalCollection<T> = LazyPrefixWhileCollection<T> where T: BidirectionalCollection
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "ReversedCollection")
public typealias ReversedRandomAccessCollection<T: RandomAccessCollection> = ReversedCollection<T>
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "ReversedCollection.Index")
public typealias ReversedIndex<T: BidirectionalCollection> = ReversedCollection<T>.Index
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias BidirectionalSlice<T> = Slice<T> where T: BidirectionalCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias RandomAccessSlice<T> = Slice<T> where T: RandomAccessCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias RangeReplaceableSlice<T> = Slice<T> where T: RangeReplaceableCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias RangeReplaceableBidirectionalSlice<T> = Slice<T> where T: RangeReplaceableCollection & BidirectionalCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias RangeReplaceableRandomAccessSlice<T> = Slice<T> where T: RangeReplaceableCollection & RandomAccessCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias MutableSlice<T> = Slice<T> where T: MutableCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias MutableBidirectionalSlice<T> = Slice<T> where T: MutableCollection & BidirectionalCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias MutableRandomAccessSlice<T> = Slice<T> where T: MutableCollection & RandomAccessCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias MutableRangeReplaceableSlice<T> = Slice<T> where T: MutableCollection & RangeReplaceableCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias MutableRangeReplaceableBidirectionalSlice<T> = Slice<T> where T: MutableCollection & RangeReplaceableCollection & BidirectionalCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")
public typealias MutableRangeReplaceableRandomAccessSlice<T> = Slice<T> where T: MutableCollection & RangeReplaceableCollection & RandomAccessCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "DefaultIndices")
public typealias DefaultBidirectionalIndices<T> = DefaultIndices<T> where T: BidirectionalCollection
@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "DefaultIndices")
public typealias DefaultRandomAccessIndices<T> = DefaultIndices<T> where T: RandomAccessCollection
// Deprecated by SE-0115.
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByNilLiteral")
public typealias NilLiteralConvertible = ExpressibleByNilLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinIntegerLiteral")
public typealias _BuiltinIntegerLiteralConvertible = _ExpressibleByBuiltinIntegerLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByIntegerLiteral")
public typealias IntegerLiteralConvertible = ExpressibleByIntegerLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinFloatLiteral")
public typealias _BuiltinFloatLiteralConvertible = _ExpressibleByBuiltinFloatLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByFloatLiteral")
public typealias FloatLiteralConvertible = ExpressibleByFloatLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinBooleanLiteral")
public typealias _BuiltinBooleanLiteralConvertible = _ExpressibleByBuiltinBooleanLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByBooleanLiteral")
public typealias BooleanLiteralConvertible = ExpressibleByBooleanLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinUnicodeScalarLiteral")
public typealias _BuiltinUnicodeScalarLiteralConvertible = _ExpressibleByBuiltinUnicodeScalarLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByUnicodeScalarLiteral")
public typealias UnicodeScalarLiteralConvertible = ExpressibleByUnicodeScalarLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinExtendedGraphemeClusterLiteral")
public typealias _BuiltinExtendedGraphemeClusterLiteralConvertible = _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByExtendedGraphemeClusterLiteral")
public typealias ExtendedGraphemeClusterLiteralConvertible = ExpressibleByExtendedGraphemeClusterLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinStringLiteral")
public typealias _BuiltinStringLiteralConvertible = _ExpressibleByBuiltinStringLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByStringLiteral")
public typealias StringLiteralConvertible = ExpressibleByStringLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByArrayLiteral")
public typealias ArrayLiteralConvertible = ExpressibleByArrayLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByDictionaryLiteral")
public typealias DictionaryLiteralConvertible = ExpressibleByDictionaryLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByStringInterpolation")
public typealias StringInterpolationConvertible = ExpressibleByStringInterpolation
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByColorLiteral")
public typealias _ColorLiteralConvertible = _ExpressibleByColorLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByImageLiteral")
public typealias _ImageLiteralConvertible = _ExpressibleByImageLiteral
@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByFileReferenceLiteral")
public typealias _FileReferenceLiteralConvertible = _ExpressibleByFileReferenceLiteral
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "ClosedRange.Index")
public typealias ClosedRangeIndex<T> = ClosedRange<T>.Index where T: Strideable, T.Stride: SignedInteger
/// An optional type that allows implicit member access.
///
/// The `ImplicitlyUnwrappedOptional` type is deprecated. To create an optional
/// value that is implicitly unwrapped, place an exclamation mark (`!`) after
/// the type that you want to denote as optional.
///
/// // An implicitly unwrapped optional integer
/// let guaranteedNumber: Int! = 6
///
/// // An optional integer
/// let possibleNumber: Int? = 5
@available(*, unavailable, renamed: "Optional")
public typealias ImplicitlyUnwrappedOptional<Wrapped> = Optional<Wrapped>
extension Range where Bound: Strideable, Bound.Stride: SignedInteger {
/// Now that Range is conditionally a collection when Bound: Strideable,
/// CountableRange is no longer needed. This is a deprecated initializer
/// for any remaining uses of Range(countableRange).
@available(swift, deprecated: 4.2, obsoleted: 5.0, message: "CountableRange is now a Range. No need to convert any more.")
public init(_ other: Range<Bound>) {
self = other
}
}
extension ClosedRange where Bound: Strideable, Bound.Stride: SignedInteger {
/// Now that Range is conditionally a collection when Bound: Strideable,
/// CountableRange is no longer needed. This is a deprecated initializer
/// for any remaining uses of Range(countableRange).
@available(swift, deprecated: 4.2, obsoleted: 5.0, message: "CountableClosedRange is now a ClosedRange. No need to convert any more.")
public init(_ other: ClosedRange<Bound>) {
self = other
}
}
@available(swift, deprecated: 5.0, renamed: "KeyValuePairs")
public typealias DictionaryLiteral<Key, Value> = KeyValuePairs<Key, Value>
extension LazySequenceProtocol {
/// Returns the non-`nil` results of mapping the given transformation over
/// this sequence.
///
/// Use this method to receive a sequence of non-optional values when your
/// transformation produces an optional value.
///
/// - Parameter transform: A closure that accepts an element of this sequence
/// as its argument and returns an optional value.
///
/// - Complexity: O(1)
@available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value")
public func flatMap<ElementOfResult>(
_ transform: @escaping (Elements.Element) -> ElementOfResult?
) -> LazyMapSequence<
LazyFilterSequence<
LazyMapSequence<Elements, ElementOfResult?>>,
ElementOfResult
> {
return self.compactMap(transform)
}
}
extension String {
/// A view of a string's contents as a collection of characters.
///
/// Previous versions of Swift provided this view since String
/// itself was not a collection. String is now a collection of
/// characters, so this type is now just an alias for String.
@available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please use String directly")
public typealias CharacterView = String
/// A view of the string's contents as a collection of characters.
///
/// Previous versions of Swift provided this view since String
/// itself was not a collection. String is now a collection of
/// characters, so this type is now just an alias for String.
@available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please use String directly")
public var characters: String {
get { return self }
set { self = newValue }
}
/// Applies the given closure to a mutable view of the string's characters.
///
/// Previous versions of Swift provided this view since String
/// itself was not a collection. String is now a collection of
/// characters, so this type is now just an alias for String.
@available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please mutate the String directly")
public mutating func withMutableCharacters<R>(
_ body: (inout String) -> R
) -> R {
return body(&self)
}
}
extension String.UnicodeScalarView: _CustomPlaygroundQuickLookable {
@available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UnicodeScalarView.customPlaygroundQuickLook will be removed in Swift 5.0")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .text(description)
}
}
//===--- Slicing Support --------------------------------------------------===//
// @available(swift,deprecated: 5.0, renamed: "Unicode.UTF8")
public typealias UTF8 = Unicode.UTF8
// @available(swift, deprecated: 5.0, renamed: "Unicode.UTF16")
public typealias UTF16 = Unicode.UTF16
// @available(swift, deprecated: 5.0, renamed: "Unicode.UTF32")
public typealias UTF32 = Unicode.UTF32
// @available(swift, deprecated: 5.0, renamed: "Unicode.Scalar")
public typealias UnicodeScalar = Unicode.Scalar
extension String.UTF16View: _CustomPlaygroundQuickLookable {
@available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UTF16View.customPlaygroundQuickLook will be removed in Swift 5.0")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .text(description)
}
}
extension String.UTF8View: _CustomPlaygroundQuickLookable {
@available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UTF8View.customPlaygroundQuickLook will be removed in Swift 5.0")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .text(description)
}
}
extension Substring {
/// A view of a string's contents as a collection of characters.
///
/// Previous versions of Swift provided this view since String
/// itself was not a collection. String is now a collection of
/// characters, so this type is now just an alias for String.
@available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please use Substring directly")
public typealias CharacterView = Substring
/// A view of the string's contents as a collection of characters.
@available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please use Substring directly")
public var characters: Substring {
get {
return self
}
set {
self = newValue
}
}
/// Applies the given closure to a mutable view of the string's characters.
///
/// Previous versions of Swift provided this view since String
/// itself was not a collection. String is now a collection of
/// characters, so this type is now just an alias for String.
@available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please mutate the Substring directly")
public mutating func withMutableCharacters<R>(
_ body: (inout Substring) -> R
) -> R {
return body(&self)
}
private func _boundsCheck(_ range: Range<Index>) {
_precondition(range.lowerBound >= startIndex,
"String index range is out of bounds")
_precondition(range.upperBound <= endIndex,
"String index range is out of bounds")
}
}
extension Substring: _CustomPlaygroundQuickLookable {
@available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "Substring.customPlaygroundQuickLook will be removed in Swift 5.0")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return String(self).customPlaygroundQuickLook
}
}
extension Collection {
// FIXME: <rdar://problem/34142121>
// This typealias should be removed as it predates the source compatibility
// guarantees of Swift 3, but it cannot due to a bug.
@available(*, unavailable, renamed: "Iterator")
public typealias Generator = Iterator
@available(swift, deprecated: 3.2, obsoleted: 5.0, renamed: "Element")
public typealias _Element = Element
@available(swift, deprecated: 4.0, obsoleted: 5.0, message: "all index distances are now of type Int")
public func index<T: BinaryInteger>(_ i: Index, offsetBy n: T) -> Index {
return index(i, offsetBy: Int(n))
}
@available(swift, deprecated: 4.0, obsoleted: 5.0, message: "all index distances are now of type Int")
public func formIndex<T: BinaryInteger>(_ i: inout Index, offsetBy n: T) {
return formIndex(&i, offsetBy: Int(n))
}
@available(swift, deprecated: 4.0, obsoleted: 5.0, message: "all index distances are now of type Int")
public func index<T: BinaryInteger>(_ i: Index, offsetBy n: T, limitedBy limit: Index) -> Index? {
return index(i, offsetBy: Int(n), limitedBy: limit)
}
@available(swift, deprecated: 4.0, obsoleted: 5.0, message: "all index distances are now of type Int")
public func formIndex<T: BinaryInteger>(_ i: inout Index, offsetBy n: T, limitedBy limit: Index) -> Bool {
return formIndex(&i, offsetBy: Int(n), limitedBy: limit)
}
@available(swift, deprecated: 4.0, obsoleted: 5.0, message: "all index distances are now of type Int")
public func distance<T: BinaryInteger>(from start: Index, to end: Index) -> T {
return numericCast(distance(from: start, to: end) as Int)
}
}
extension UnsafeMutablePointer {
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "initialize(repeating:count:)")
public func initialize(to newValue: Pointee, count: Int = 1) {
initialize(repeating: newValue, count: count)
}
@available(swift, deprecated: 4.1, obsoleted: 5.0, message: "the default argument to deinitialize(count:) has been removed, please specify the count explicitly")
@discardableResult
public func deinitialize() -> UnsafeMutableRawPointer {
return deinitialize(count: 1)
}
@available(swift, deprecated: 4.1, obsoleted: 5.0, message: "Swift currently only supports freeing entire heap blocks, use deallocate() instead")
public func deallocate(capacity _: Int) {
self.deallocate()
}
/// Initializes memory starting at this pointer's address with the elements
/// of the given collection.
///
/// The region of memory starting at this pointer and covering `source.count`
/// instances of the pointer's `Pointee` type must be uninitialized or
/// `Pointee` must be a trivial type. After calling `initialize(from:)`, the
/// region is initialized.
///
/// - Parameter source: A collection of elements of the pointer's `Pointee`
/// type.
// This is fundamentally unsafe since collections can underreport their count.
@available(swift, deprecated: 4.2, obsoleted: 5.0, message: "it will be removed in Swift 5.0. Please use 'UnsafeMutableBufferPointer.initialize(from:)' instead")
public func initialize<C: Collection>(from source: C)
where C.Element == Pointee {
let buf = UnsafeMutableBufferPointer(start: self, count: numericCast(source.count))
var (remainders,writtenUpTo) = source._copyContents(initializing: buf)
// ensure that exactly rhs.count elements were written
_precondition(remainders.next() == nil, "rhs underreported its count")
_precondition(writtenUpTo == buf.endIndex, "rhs overreported its count")
}
}
extension UnsafeMutableRawPointer {
@available(*, unavailable, renamed: "init(mutating:)")
public init(@_nonEphemeral _ from: UnsafeRawPointer) { Builtin.unreachable() }
@available(*, unavailable, renamed: "init(mutating:)")
public init?(@_nonEphemeral _ from: UnsafeRawPointer?) { Builtin.unreachable() }
@available(*, unavailable, renamed: "init(mutating:)")
public init<T>(@_nonEphemeral _ from: UnsafePointer<T>) { Builtin.unreachable() }
@available(*, unavailable, renamed: "init(mutating:)")
public init?<T>(@_nonEphemeral _ from: UnsafePointer<T>?) { Builtin.unreachable() }
}
extension UnsafeRawPointer: _CustomPlaygroundQuickLookable {
internal var summary: String {
let ptrValue = UInt64(
bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue))))
return ptrValue == 0
? "UnsafeRawPointer(nil)"
: "UnsafeRawPointer(0x\(_uint64ToString(ptrValue, radix:16, uppercase:true)))"
}
@available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UnsafeRawPointer.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .text(summary)
}
}
extension UnsafeMutableRawPointer: _CustomPlaygroundQuickLookable {
private var summary: String {
let ptrValue = UInt64(
bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue))))
return ptrValue == 0
? "UnsafeMutableRawPointer(nil)"
: "UnsafeMutableRawPointer(0x\(_uint64ToString(ptrValue, radix:16, uppercase:true)))"
}
@available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UnsafeMutableRawPointer.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .text(summary)
}
}
extension UnsafePointer: _CustomPlaygroundQuickLookable {
private var summary: String {
let ptrValue = UInt64(bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue))))
return ptrValue == 0
? "UnsafePointer(nil)"
: "UnsafePointer(0x\(_uint64ToString(ptrValue, radix:16, uppercase:true)))"
}
@available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UnsafePointer.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(summary)
}
}
extension UnsafeMutablePointer: _CustomPlaygroundQuickLookable {
private var summary: String {
let ptrValue = UInt64(bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue))))
return ptrValue == 0
? "UnsafeMutablePointer(nil)"
: "UnsafeMutablePointer(0x\(_uint64ToString(ptrValue, radix:16, uppercase:true)))"
}
@available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UnsafeMutablePointer.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(summary)
}
}
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "UnsafeBufferPointer.Iterator")
public typealias UnsafeBufferPointerIterator<T> = UnsafeBufferPointer<T>.Iterator
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "UnsafeRawBufferPointer.Iterator")
public typealias UnsafeRawBufferPointerIterator<T> = UnsafeBufferPointer<T>.Iterator
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "UnsafeRawBufferPointer.Iterator")
public typealias UnsafeMutableRawBufferPointerIterator<T> = UnsafeBufferPointer<T>.Iterator
extension UnsafeMutableRawPointer {
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "allocate(byteCount:alignment:)")
public static func allocate(
bytes size: Int, alignedTo alignment: Int
) -> UnsafeMutableRawPointer {
return UnsafeMutableRawPointer.allocate(byteCount: size, alignment: alignment)
}
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "deallocate()", message: "Swift currently only supports freeing entire heap blocks, use deallocate() instead")
public func deallocate(bytes _: Int, alignedTo _: Int) {
self.deallocate()
}
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "copyMemory(from:byteCount:)")
public func copyBytes(from source: UnsafeRawPointer, count: Int) {
copyMemory(from: source, byteCount: count)
}
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "initializeMemory(as:repeating:count:)")
@discardableResult
public func initializeMemory<T>(
as type: T.Type, at offset: Int = 0, count: Int = 1, to repeatedValue: T
) -> UnsafeMutablePointer<T> {
return (self + offset * MemoryLayout<T>.stride).initializeMemory(
as: type, repeating: repeatedValue, count: count)
}
@available(swift, deprecated: 4.1, obsoleted: 5.0, message: "it will be removed in Swift 5.0. Please use 'UnsafeMutableRawBufferPointer.initialize(from:)' instead")
@discardableResult
public func initializeMemory<C: Collection>(
as type: C.Element.Type, from source: C
) -> UnsafeMutablePointer<C.Element> {
// TODO: Optimize where `C` is a `ContiguousArrayBuffer`.
// Initialize and bind each element of the container.
var ptr = self
for element in source {
ptr.initializeMemory(as: C.Element.self, repeating: element, count: 1)
ptr += MemoryLayout<C.Element>.stride
}
return UnsafeMutablePointer(_rawValue)
}
}
extension UnsafeMutableRawBufferPointer {
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "allocate(byteCount:alignment:)")
public static func allocate(count: Int) -> UnsafeMutableRawBufferPointer {
return UnsafeMutableRawBufferPointer.allocate(
byteCount: count, alignment: MemoryLayout<UInt>.alignment)
}
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "copyMemory(from:)")
public func copyBytes(from source: UnsafeRawBufferPointer) {
copyMemory(from: source)
}
}
//===----------------------------------------------------------------------===//
// The following overloads of flatMap are carefully crafted to allow the code
// like the following:
// ["hello"].flatMap { $0 }
// return an array of strings without any type context in Swift 3 mode, at the
// same time allowing the following code snippet to compile:
// [0, 1].flatMap { x in
// if String(x) == "foo" { return "bar" } else { return nil }
// }
// Note that the second overload is declared on a more specific protocol.
// See: test/stdlib/StringFlatMap.swift for tests.
extension Sequence {
@available(swift, deprecated: 4.1/*, obsoleted: 5.1 */, renamed: "compactMap(_:)",
message: "Please use compactMap(_:) for the case where closure returns an optional value")
public func flatMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
return try _compactMap(transform)
}
}
extension Collection {
@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "compactMap(_:)",
message: "Please use compactMap(_:) for the case where closure returns an optional value")
public func flatMap(
_ transform: (Element) throws -> String?
) rethrows -> [String] {
return try _compactMap(transform)
}
}
extension Collection {
/// Returns the first index in which an element of the collection satisfies
/// the given predicate.
@available(swift, deprecated: 5.0, renamed: "firstIndex(where:)")
@inlinable
public func index(
where _predicate: (Element) throws -> Bool
) rethrows -> Index? {
return try firstIndex(where: _predicate)
}
}
extension Collection where Element: Equatable {
/// Returns the first index where the specified value appears in the
/// collection.
@available(swift, deprecated: 5.0, renamed: "firstIndex(of:)")
@inlinable
public func index(of element: Element) -> Index? {
return firstIndex(of: element)
}
}
extension Zip2Sequence {
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "Sequence1.Iterator")
public typealias Stream1 = Sequence1.Iterator
@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "Sequence2.Iterator")
public typealias Stream2 = Sequence2.Iterator
}
//===--- QuickLooks -------------------------------------------------------===//
/// The sum of types that can be used as a Quick Look representation.
///
/// The `PlaygroundQuickLook` protocol is deprecated, and will be removed from
/// the standard library in a future Swift release. To customize the logging of
/// your type in a playground, conform to the
/// `CustomPlaygroundDisplayConvertible` protocol, which does not use the
/// `PlaygroundQuickLook` enum.
///
/// If you need to provide a customized playground representation in Swift 4.0
/// or Swift 3.2 or earlier, use a conditional compilation block:
///
/// #if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0))
/// // With Swift 4.1 and later (including Swift 3.3 and later), use
/// // the CustomPlaygroundDisplayConvertible protocol.
/// #else
/// // With Swift 4.0 and Swift 3.2 and earlier, use PlaygroundQuickLook
/// // and the CustomPlaygroundQuickLookable protocol.
/// #endif
@available(swift, deprecated: 4.2, message: "PlaygroundQuickLook will be removed in a future Swift version. For customizing how types are presented in playgrounds, use CustomPlaygroundDisplayConvertible instead.")
public typealias PlaygroundQuickLook = _PlaygroundQuickLook
@frozen // rdar://problem/38719739 - needed by LLDB
public enum _PlaygroundQuickLook {
case text(String)
case int(Int64)
case uInt(UInt64)
case float(Float32)
case double(Float64)
case image(Any)
case sound(Any)
case color(Any)
case bezierPath(Any)
case attributedString(Any)
case rectangle(Float64, Float64, Float64, Float64)
case point(Float64, Float64)
case size(Float64, Float64)
case bool(Bool)
case range(Int64, Int64)
case view(Any)
case sprite(Any)
case url(String)
case _raw([UInt8], String)
}
extension _PlaygroundQuickLook {
/// Creates a new Quick Look for the given instance.
///
/// If the dynamic type of `subject` conforms to
/// `CustomPlaygroundQuickLookable`, the result is found by calling its
/// `customPlaygroundQuickLook` property. Otherwise, the result is
/// synthesized by the language. In some cases, the synthesized result may
/// be `.text(String(reflecting: subject))`.
///
/// - Note: If the dynamic type of `subject` has value semantics, subsequent
/// mutations of `subject` will not observable in the Quick Look. In
/// general, though, the observability of such mutations is unspecified.
///
/// - Parameter subject: The instance to represent with the resulting Quick
/// Look.
@available(swift, deprecated: 4.2, obsoleted: 5.0, message: "PlaygroundQuickLook will be removed in a future Swift version.")
public init(reflecting subject: Any) {
if let customized = subject as? _CustomPlaygroundQuickLookable {
self = customized.customPlaygroundQuickLook
}
else if let customized = subject as? __DefaultCustomPlaygroundQuickLookable {
self = customized._defaultCustomPlaygroundQuickLook
}
else {
if let q = Mirror.quickLookObject(subject) {
self = q
}
else {
self = .text(String(reflecting: subject))
}
}
}
}
/// A type that explicitly supplies its own playground Quick Look.
///
/// The `CustomPlaygroundQuickLookable` protocol is deprecated, and will be
/// removed from the standard library in a future Swift release. To customize
/// the logging of your type in a playground, conform to the
/// `CustomPlaygroundDisplayConvertible` protocol.
///
/// If you need to provide a customized playground representation in Swift 4.0
/// or Swift 3.2 or earlier, use a conditional compilation block:
///
/// #if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0))
/// // With Swift 4.1 and later (including Swift 3.3 and later),
/// // conform to CustomPlaygroundDisplayConvertible.
/// extension MyType: CustomPlaygroundDisplayConvertible { /*...*/ }
/// #else
/// // Otherwise, on Swift 4.0 and Swift 3.2 and earlier,
/// // conform to CustomPlaygroundQuickLookable.
/// extension MyType: CustomPlaygroundQuickLookable { /*...*/ }
/// #endif
@available(swift, deprecated: 4.2, obsoleted: 5.0, message: "CustomPlaygroundQuickLookable will be removed in a future Swift version. For customizing how types are presented in playgrounds, use CustomPlaygroundDisplayConvertible instead.")
public typealias CustomPlaygroundQuickLookable = _CustomPlaygroundQuickLookable
//@available(swift, obsoleted: 5.0)
public protocol _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for this instance.
///
/// If this type has value semantics, the `PlaygroundQuickLook` instance
/// should be unaffected by subsequent mutations.
var customPlaygroundQuickLook: _PlaygroundQuickLook { get }
}
// Double-underscored real version allows us to keep using this in AppKit while
// warning for non-SDK use. This is probably overkill but it doesn't cost
// anything.
@available(swift, deprecated: 4.2, obsoleted: 5.0, message: "_DefaultCustomPlaygroundQuickLookable will be removed in a future Swift version. For customizing how types are presented in playgrounds, use CustomPlaygroundDisplayConvertible instead.")
public typealias _DefaultCustomPlaygroundQuickLookable = __DefaultCustomPlaygroundQuickLookable
// @available(swift, obsoleted: 5.0)
public protocol __DefaultCustomPlaygroundQuickLookable {
var _defaultCustomPlaygroundQuickLook: _PlaygroundQuickLook { get }
}
| apache-2.0 | b5c2ee4636663a0cfa11701718a93068 | 50.087694 | 247 | 0.744567 | 4.476822 | false | false | false | false |
myfreeweb/SwiftCBOR | Sources/SwiftCBOR/CBOR.swift | 1 | 7083 | #if canImport(Foundation)
import Foundation
#endif
public indirect enum CBOR : Equatable, Hashable,
ExpressibleByNilLiteral, ExpressibleByIntegerLiteral, ExpressibleByStringLiteral,
ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral, ExpressibleByBooleanLiteral,
ExpressibleByFloatLiteral {
case unsignedInt(UInt64)
case negativeInt(UInt64)
case byteString([UInt8])
case utf8String(String)
case array([CBOR])
case map([CBOR : CBOR])
case tagged(Tag, CBOR)
case simple(UInt8)
case boolean(Bool)
case null
case undefined
case half(Float32)
case float(Float32)
case double(Float64)
case `break`
#if canImport(Foundation)
case date(Date)
#endif
public func hash(into hasher: inout Hasher) {
switch self {
case let .unsignedInt(l): l.hash(into: &hasher)
case let .negativeInt(l): l.hash(into: &hasher)
case let .byteString(l): Util.djb2Hash(l.map { Int($0) }).hash(into: &hasher)
case let .utf8String(l): l.hash(into: &hasher)
case let .array(l): Util.djb2Hash(l.map { $0.hashValue }).hash(into: &hasher)
case let .map(l): Util.djb2Hash(l.map { $0.hashValue &+ $1.hashValue }).hash(into: &hasher)
case let .tagged(t, l): t.hash(into: &hasher)
l.hash(into: &hasher)
case let .simple(l): l.hash(into: &hasher)
case let .boolean(l): l.hash(into: &hasher)
case .null: (-1).hash(into: &hasher)
case .undefined: (-2).hash(into: &hasher)
case let .half(l): l.hash(into: &hasher)
case let .float(l): l.hash(into: &hasher)
case let .double(l): l.hash(into: &hasher)
#if canImport(Foundation)
case let .date(l): l.hash(into: &hasher)
#endif
case .break: Int.min.hash(into: &hasher)
}
}
public subscript(position: CBOR) -> CBOR? {
get {
switch (self, position) {
case (let .array(l), let .unsignedInt(i)): return l[Int(i)]
case (let .map(l), let i): return l[i]
default: return nil
}
}
set(x) {
switch (self, position) {
case (var .array(l), let .unsignedInt(i)):
l[Int(i)] = x!
self = .array(l)
case (var .map(l), let i):
l[i] = x!
self = .map(l)
default: break
}
}
}
public init(nilLiteral: ()) { self = .null }
public init(integerLiteral value: Int) {
if value < 0 {
self = .negativeInt(~UInt64(bitPattern: Int64(value)))
} else {
self = .unsignedInt(UInt64(value))
}
}
public init(extendedGraphemeClusterLiteral value: String) { self = .utf8String(value) }
public init(unicodeScalarLiteral value: String) { self = .utf8String(value) }
public init(stringLiteral value: String) { self = .utf8String(value) }
public init(arrayLiteral elements: CBOR...) { self = .array(elements) }
public init(dictionaryLiteral elements: (CBOR, CBOR)...) {
var result = [CBOR : CBOR]()
for (key, value) in elements {
result[key] = value
}
self = .map(result)
}
public init(booleanLiteral value: Bool) { self = .boolean(value) }
public init(floatLiteral value: Float32) { self = .float(value) }
public static func ==(lhs: CBOR, rhs: CBOR) -> Bool {
switch (lhs, rhs) {
case (let .unsignedInt(l), let .unsignedInt(r)): return l == r
case (let .negativeInt(l), let .negativeInt(r)): return l == r
case (let .byteString(l), let .byteString(r)): return l == r
case (let .utf8String(l), let .utf8String(r)): return l == r
case (let .array(l), let .array(r)): return l == r
case (let .map(l), let .map(r)): return l == r
case (let .tagged(tl, l), let .tagged(tr, r)): return tl == tr && l == r
case (let .simple(l), let .simple(r)): return l == r
case (let .boolean(l), let .boolean(r)): return l == r
case (.null, .null): return true
case (.undefined, .undefined): return true
case (let .half(l), let .half(r)): return l == r
case (let .float(l), let .float(r)): return l == r
case (let .double(l), let .double(r)): return l == r
#if canImport(Foundation)
case (let .date(l), let .date(r)): return l == r
#endif
case (.break, .break): return true
case (.unsignedInt, _): return false
case (.negativeInt, _): return false
case (.byteString, _): return false
case (.utf8String, _): return false
case (.array, _): return false
case (.map, _): return false
case (.tagged, _): return false
case (.simple, _): return false
case (.boolean, _): return false
case (.null, _): return false
case (.undefined, _): return false
case (.half, _): return false
case (.float, _): return false
case (.double, _): return false
case (.break, _): return false
default: return false
}
}
public struct Tag: RawRepresentable, Equatable, Hashable {
public let rawValue: UInt64
public init(rawValue: UInt64) {
self.rawValue = rawValue
}
public var hashValue : Int {
return rawValue.hashValue
}
}
}
extension CBOR.Tag {
public static let standardDateTimeString = CBOR.Tag(rawValue: 0)
public static let epochBasedDateTime = CBOR.Tag(rawValue: 1)
public static let positiveBignum = CBOR.Tag(rawValue: 2)
public static let negativeBignum = CBOR.Tag(rawValue: 3)
public static let decimalFraction = CBOR.Tag(rawValue: 4)
public static let bigfloat = CBOR.Tag(rawValue: 5)
// 6...20 unassigned
public static let expectedConversionToBase64URLEncoding = CBOR.Tag(rawValue: 21)
public static let expectedConversionToBase64Encoding = CBOR.Tag(rawValue: 22)
public static let expectedConversionToBase16Encoding = CBOR.Tag(rawValue: 23)
public static let encodedCBORDataItem = CBOR.Tag(rawValue: 24)
// 25...31 unassigned
public static let uri = CBOR.Tag(rawValue: 32)
public static let base64Url = CBOR.Tag(rawValue: 33)
public static let base64 = CBOR.Tag(rawValue: 34)
public static let regularExpression = CBOR.Tag(rawValue: 35)
public static let mimeMessage = CBOR.Tag(rawValue: 36)
public static let uuid = CBOR.Tag(rawValue: 37)
// 38...55798 unassigned
public static let selfDescribeCBOR = CBOR.Tag(rawValue: 55799)
}
#if os(Linux)
let NSEC_PER_SEC: UInt64 = 1_000_000_000
#endif
| unlicense | 2e7496d2bb561ddb315a1ed0ad949043 | 38.569832 | 107 | 0.565297 | 3.86205 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/numbers-at-most-n-given-digit-set.swift | 2 | 1807 | /**
* https://leetcode.com/problems/numbers-at-most-n-given-digit-set/
*
*
*/
// Date: Sun Nov 29 17:01:09 PST 2020
class Solution {
/// BFS
/// TLE.
func atMostNGivenDigitSet(_ digits: [String], _ n: Int) -> Int {
let digits = digits.map { Int($0)! }
var queue = digits.filter { $0 <= n }
var result: Set<Int> = Set(queue)
while queue.isEmpty == false {
let num = queue.removeFirst()
for x in digits {
if num * 10 + x <= n, result.contains(num * 10 + x) == false {
result.insert(num * 10 + x)
queue.append(num * 10 + x)
}
}
}
return result.count
}
}
/**
* https://leetcode.com/problems/numbers-at-most-n-given-digit-set/
*
*
*/
// Date: Sun Nov 29 17:17:26 PST 2020
class Solution {
/// - Complexity:
/// - Time: O(log10(n))
/// - Space: O(1)
////
/// Reference: [Tech blog of HuaHua](https://zxi.mytechroad.com/blog/math/leetcode-902-numbers-at-most-n-given-digit-set/)
///
func atMostNGivenDigitSet(_ digits: [String], _ n: Int) -> Int {
let n = Array(String(n)).map { String($0) }
var result = 0
for index in 1 ..< n.count {
result += Int(pow(Double(digits.count), Double(index)))
}
for index in 0 ..< n.count {
var exists = false
for d in digits {
if d < n[index] {
result += Int(pow(Double(digits.count), Double(n.count - 1 - index)))
} else if d == n[index] {
exists = true
break
}
}
if exists == false { return result }
}
return result + 1
}
}
| mit | cd0d0c5a2daad5dec29b576e648d91d3 | 27.234375 | 126 | 0.474267 | 3.635815 | false | false | false | false |
jngd/advanced-ios10-training | T5E01/T5E01KeyboarExtension/KeyboardViewController.swift | 1 | 2148 | //
// KeyboardViewController.swift
// T5E01KeyboarExtension
//
// Created by jngd on 19/02/2017.
// Copyright © 2017 jngd. All rights reserved.
//
import UIKit
class KeyboardViewController: UIInputViewController {
@IBOutlet var nextKeyboardButton: UIButton!
override func updateViewConstraints() {
super.updateViewConstraints()
// Add custom view sizing constraints here
}
@IBAction func buttonPressed(button: UIButton) {
let string = button.titleLabel!.text
(textDocumentProxy as UIKeyInput).insertText("\(string!)")
}
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "KeyboardExtensionView", bundle: nil)
let objects = nib.instantiate(withOwner: self, options: nil)
view = objects[0] as! UIView
// Perform custom UI setup here
self.nextKeyboardButton = UIButton(type: .system)
self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: [])
self.nextKeyboardButton.sizeToFit()
self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false
self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents)
self.view.addSubview(self.nextKeyboardButton)
self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
override func textWillChange(_ textInput: UITextInput?) {
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(_ textInput: UITextInput?) {
// The app has just changed the document's contents, the document context has been updated.
var textColor: UIColor
let proxy = self.textDocumentProxy
if proxy.keyboardAppearance == UIKeyboardAppearance.dark {
textColor = UIColor.white
} else {
textColor = UIColor.black
}
self.nextKeyboardButton.setTitleColor(textColor, for: [])
}
}
| apache-2.0 | 61be2450a31e64473dba06c3a856d696 | 29.671429 | 124 | 0.761528 | 4.251485 | false | false | false | false |
indisee/ITCiosScreenShotUploader | ItunesScreenshotUploader/Code/Managers/ITCMetaXMLHandler.swift | 1 | 9265 | //
// XMLWorker.swift
// ItunesScreenshotUploader
//
// Created by iN on 07/03/16.
// Copyright © 2016 2tickets2dublin. All rights reserved.
//
import Foundation
class ITCMetaXMLHandler {
fileprivate let q = OperationQueue()
//MARK: - -
var metaXmlPath:String {
return "\(ItunesConnectHandler.sharedInstance.itmspPath())/metadata.xml"
}
//MARK: - Helpers -
fileprivate func writeXmlBackToMetaFile(_ xml:AEXMLDocument) {
do {
try xml.root.xmlString.write(toFile: metaXmlPath, atomically: false, encoding: String.Encoding.utf8)
}
catch {
assert(false)
}
}
fileprivate func replaceChildrensOfElement(_ element:AEXMLElement, newChildrens:[AEXMLElement]?) -> AEXMLElement {
for ch in element.children {
ch.removeFromParent()
}
if let new = newChildrens {
for el in new {
element.addChild(el)
}
}
return element
}
//MARK: - Meta stuff -
fileprivate func xmlNodeFromScreenShot(_ screenShot:ScreenShot, position:Int) -> AEXMLElement? {
if position > 5 || screenShot.screenType == .iUndefinedScreenShotType {
return nil
}
/*
<software_screenshot display_target="iOS-3.5-in" position="1">
<size>258477</size>
<file_name>1.png</file_name>
<checksum type="md5">7a8c1d8e5fe8b029fea88d0ea1e30a6d</checksum>
</software_screenshot>
*/
let attributes = [
"display_target" : screenShot.screenType.rawValue,
"position" : "\(position)"
]
let software_screenshot = AEXMLElement("software_screenshot", value: nil, attributes: attributes)
software_screenshot.addChild(name: "size", value: "\(screenShot.fileSize)", attributes: nil)
software_screenshot.addChild(name: "file_name", value: "\(screenShot.nameForUpload)", attributes: nil)
software_screenshot.addChild(name: "checksum", value: "\(screenShot.md5)", attributes: [
"type":"md5"
])
return software_screenshot
}
fileprivate func getMetaData() -> AEXMLDocument? {
guard let
data = try? Data(contentsOf: URL(fileURLWithPath: metaXmlPath))
else { return nil }
do {
let xmlDoc = try AEXMLDocument(xmlData: data)
return xmlDoc
} catch {
print("\(error)")
}
return nil
}
fileprivate func getLocalesForMetadata(_ xml:AEXMLDocument? = nil) -> AEXMLElement? {
var xmlDoc:AEXMLDocument! = xml
if xmlDoc == nil {
xmlDoc = getMetaData()
}
if xmlDoc == nil {
return nil
}
let versions = xmlDoc.root["software"]["software_metadata"]["versions"]
if versions.children.count > 0 {
let versionIndex = indexOfLatestVersionFromElement(versions)
let currentVersion = versions.children[versionIndex]
let locales = currentVersion["locales"]
return locales
}
return nil
}
fileprivate func indexOfLatestVersionFromElement(_ versions:AEXMLElement) -> Int {
var versionNumber = "0"
var versionIndex = 0
for (i,e) in versions.children.enumerated() {
if let eVersion = e.attributes["string"] {
if eVersion > versionNumber {
versionNumber = eVersion
versionIndex = i
}
}
}
return versionIndex
}
//MARK: - XML helpers -
func localesSortedByLang(_ locales:[AEXMLElement]) -> [String:AEXMLElement] {
var localesByLang:[String:AEXMLElement] = [String:AEXMLElement]()
for loc in locales {
if let lang = loc.attributes["name"] {
localesByLang[lang] = loc
}
}
return localesByLang
}
func mandatoryScreenshotsForMode(_ mode:ScreenShotUploadingMode, fromRaw raw:[String:[[ScreenShot]]], forLangs langs:[String:AEXMLElement]) -> [String:[[ScreenShot]]] {
var screenShots = [String:[[ScreenShot]]]()
if mode == .sameScreenShotUploadingMode {
for lang in Array(langs.keys) {
screenShots["[\(lang)]"] = raw[NoLangID]!
}
} else {
screenShots = raw
}
return screenShots
}
//MARK: - -
func updateMetadataForScreenShots(_ rawScreenShots:[String:[[ScreenShot]]], uploadType:ScreenShotUploadingMode, callback:@escaping (_ status:CallbackStatus)->Void) {
let op = BlockOperation()
op.addExecutionBlock { [unowned self, op] () -> Void in
let fail = {()->Void in
if !op.isCancelled {
OperationQueue.main.addOperation({ () -> Void in
callback(.failStatus)
})
}
}
if let localesParent = self.getLocalesForMetadata() {
let locales = localesParent.children
let localesByLang:[String:AEXMLElement] = self.localesSortedByLang(locales)
let screenShots:[String:[[ScreenShot]]] = self.mandatoryScreenshotsForMode(uploadType, fromRaw: rawScreenShots, forLangs: localesByLang)
let finalLocales = self.generateFinalXMLFromCurrentLocales(localesByLang, screenShots: screenShots)
if let document = self.getMetaData() {
let versions = document.root["software"]["software_metadata"]["versions"]
if versions.children.count > 0 {
let versionIndex = self.indexOfLatestVersionFromElement(versions)
self.replaceChildrensOfElement(document.root["software"]["software_metadata"]["versions"].children[versionIndex]["locales"], newChildrens: finalLocales.children)
self.writeXmlBackToMetaFile(document)
} else {
fail()
return
}
} else {
fail()
return
}
if !op.isCancelled {
OperationQueue.main.addOperation({ () -> Void in
callback(.successStatus)
})
}
} else {
fail()
return
}
}
q.addOperation(op)
}
fileprivate func generateFinalXMLFromCurrentLocales(_ localesByLang:[String:AEXMLElement], screenShots:[String:[[ScreenShot]]]) -> AEXMLElement {
let finalLocales = AEXMLElement("locales", value: nil, attributes: nil)
for key in Array(localesByLang.keys) {
let locale = localesByLang[key]!
let lang = "[\(key)]"
if let allPlatformsScreens = screenShots[lang] {
var langScreenshots = [AEXMLElement]()
for platformScreens in allPlatformsScreens {
var i = 1
for screen in platformScreens {
if let el = self.xmlNodeFromScreenShot(screen, position: i) {
i += 1
langScreenshots.append(el)
}
}
}
//fill locale
let children = locale.children
var hasScreenShotSection = false
for ch in children {
if ch.name == "software_screenshots"{
hasScreenShotSection = true
break
}
}
if hasScreenShotSection {
var software_screenshots = locale["software_screenshots"]
software_screenshots = self.replaceChildrensOfElement(software_screenshots, newChildrens: langScreenshots)
} else {
let screens = AEXMLElement("software_screenshots", value: nil, attributes: nil)
for sc in langScreenshots {
screens.addChild(sc)
}
locale.addChild(screens)
}
} else {
locale["software_screenshots"].removeFromParent()
}
finalLocales.addChild(locale)
}
return finalLocales
}
}
| mit | fd4d218c782ea0655b785b01ba5153a5 | 31.166667 | 185 | 0.500108 | 5.587455 | false | false | false | false |
Mathpix/ios-client | MathpixClient/Classes/Camera/Camera Overlay/CropControlOverlay.swift | 1 | 6097 | //
// CropControl.swift
// SliderTest
//
// Created by Gilbert Jolly on 30/04/2016.
// Copyright © 2016 Gilbert Jolly. All rights reserved.
//
import PureLayout
import Foundation
class CropControlOverlay: UIView {
var cropControl : CropControl!
let statusLabel = UILabel()
fileprivate let flashView = UIView()
var regionSelectedCallback: (()->())?
var draggingBeganCallback: (()->())?
var draggingCallback: ((_ bottomCenter : CGPoint)->())?
var isResultViewActive = false
fileprivate var errors : [Error] = []
fileprivate var errorAnimationInProgress = false
fileprivate var resultImageView = UIImageView()
fileprivate let flashCropAnimationDuration = 0.18
init(color: UIColor) {
super.init(frame: CGRect.zero)
self.backgroundColor = UIColor.clear
cropControl = CropControl(color: color)
addSubview(cropControl)
cropControl.autoCenterInSuperview()
cropControl.panStateCallback = { [unowned self] state in
if state == .began {
self.draggingBeganCallback?()
}
if state == .ended {
self.regionSelectedCallback?()
}
}
cropControl.cropFrameDidChangedCallback = { [unowned self] bottomCenter in
self.draggingCallback?(bottomCenter)
}
cropControl.addSubview(flashView)
flashView.backgroundColor = color
flashView.alpha = 0
self.flashView.isHidden = true
flashView.autoPinEdgesToSuperviewEdges()
addSubview(statusLabel)
statusLabel.minimumScaleFactor = 0.5
statusLabel.textColor = UIColor.white
statusLabel.font = UIFont.systemFont(ofSize: 14)
statusLabel.textAlignment = .center
statusLabel.adjustsFontSizeToFitWidth = true
statusLabel.autoPinEdge(.top, to: .bottom, of: cropControl, withOffset: 5)
statusLabel.autoPinEdge(.leading, to: .leading, of: self, withOffset: 20)
statusLabel.autoPinEdge(.trailing, to: .trailing, of: self, withOffset: -20)
cropControl.addSubview(resultImageView)
resultImageView.autoPinEdgesToSuperviewEdges()
resetView()
}
func flashCrop() {
self.flashView.isHidden = false
UIView.animateKeyframes(withDuration: flashCropAnimationDuration, delay: 0, options: [], animations: {
UIView.animateKeyframes(withDuration: 0.5, delay: 0, options: [], animations: {
self.flashView.alpha = 1.0
}, completion: nil)
UIView.animateKeyframes(withDuration: 0.5, delay: 0, options: [], animations: {
self.flashView.alpha = 0.0
}, completion: { (finished) in
if finished {
self.flashView.isHidden = true
}
})
}, completion: nil)
}
func resetStatusLabel() {
self.statusLabel.text = nil
}
func resetView(){
clearResultView(animated: false)
cropControl.resetView()
}
func clearResultView(animated: Bool) {
if animated {
UIView.animate(withDuration: 0.35, animations: {
self.resultImageView.alpha = 0.0
}) { (finished) in
self.resultImageView.image = nil
self.resultImageView.alpha = 1.0
}
} else {
self.resultImageView.image = nil
}
}
/**
* Display errror eventually. This method accept error and displahy it eventually in info label under crop area.
* - Parameter error: error object that need be presented.
*/
func displayErrorEventually(_ error: Error) {
self.errors.insert(error, at: 0)
self.animateErrorMessage()
}
fileprivate func animateErrorMessage() {
guard !errorAnimationInProgress else { return }
if let error = self.errors.popLast() {
self.errorAnimationInProgress = true
self.statusLabel.text = error.localizedDescription
self.statusLabel.alpha = 1
UIView.animate(withDuration: 0.3, delay: 2.0, options: [], animations: {
self.statusLabel.alpha = 0
}, completion: { _ in
self.statusLabel.text = nil
self.errorAnimationInProgress = false
self.animateErrorMessage()
})
}
}
func cropImageAndUpdateDisplay(_ image: UIImage, superview: UIView) -> UIImage{
let croppedImage = cropImage(image, superview: superview)
if isResultViewActive {
resultImageView.image = croppedImage
}
return croppedImage
}
fileprivate func cropImage(_ image: UIImage, superview: UIView) -> UIImage{
let cropRect = cropControl.convert(cropControl.bounds, to: superview)
let imageSize = image.size
let xScale = imageSize.width / superview.bounds.size.width
let yScale = imageSize.height / superview.bounds.size.height
let cropX = cropRect.origin.x * xScale
let cropWidth = cropRect.width * xScale
let cropY = cropRect.origin.y * yScale
let cropHeight = cropRect.height * yScale
let scaledCropRect = CGRect(x: cropX, y: cropY, width: cropWidth, height: cropHeight)
return image.fixOrientation().croppedImage(scaledCropRect)
}
//We only want to allow the cropView to get hit events,
//this view should let them fall through to buttons below
override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let cropViewPoint = cropControl.convert(point, from: self)
return cropControl.hitTest(cropViewPoint, with: event)
}
//Swift... ¯\_(ツ)_/¯
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 4adfbbff691c81ddc20c1b64fa9e7db8 | 33.03352 | 117 | 0.602758 | 4.960912 | false | false | false | false |
nextcloud/ios | iOSClient/Diagnostics/NCCapabilitiesViewController.swift | 1 | 16905 | //
// NCCapabilitiesViewController.swift
// Nextcloud
//
// Created by Marino Faggiana on 28/07/2020.
// Copyright © 2020 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import NextcloudKit
class NCCapabilitiesViewController: UIViewController, UIDocumentInteractionControllerDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var imageFileSharing: UIImageView!
@IBOutlet weak var statusFileSharing: UILabel!
@IBOutlet weak var imageExternalSite: UIImageView!
@IBOutlet weak var statusExternalSite: UILabel!
@IBOutlet weak var imageEndToEndEncryption: UIImageView!
@IBOutlet weak var statusEndToEndEncryption: UILabel!
@IBOutlet weak var imageActivity: UIImageView!
@IBOutlet weak var statusActivity: UILabel!
@IBOutlet weak var imageNotification: UIImageView!
@IBOutlet weak var statusNotification: UILabel!
@IBOutlet weak var imageDeletedFiles: UIImageView!
@IBOutlet weak var statusDeletedFiles: UILabel!
@IBOutlet weak var imageUserStatus: UIImageView!
@IBOutlet weak var statusUserStatus: UILabel!
@IBOutlet weak var imageComments: UIImageView!
@IBOutlet weak var statusComments: UILabel!
@IBOutlet weak var imageText: UIImageView!
@IBOutlet weak var statusText: UILabel!
@IBOutlet weak var imageCollabora: UIImageView!
@IBOutlet weak var statusCollabora: UILabel!
@IBOutlet weak var imageOnlyOffice: UIImageView!
@IBOutlet weak var statusOnlyOffice: UILabel!
@IBOutlet weak var homeImage: UIImageView!
@IBOutlet weak var homeServer: UILabel!
@IBOutlet weak var imageLockFile: UIImageView!
@IBOutlet weak var statusLockFile: UILabel!
private let appDelegate = UIApplication.shared.delegate as! AppDelegate
private var documentController: UIDocumentInteractionController?
private var account: String = ""
private var capabilitiesText = ""
// private var timer: Timer?
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("_capabilities_", comment: "")
let shareImage = UIImage(named: "shareFill")!.image(color: .gray, size: 25)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: shareImage, style: UIBarButtonItem.Style.plain, target: self, action: #selector(share))
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_done_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(close))
textView.layer.cornerRadius = 15
textView.layer.masksToBounds = true
textView.backgroundColor = .secondarySystemBackground
statusFileSharing.layer.cornerRadius = 12.5
statusFileSharing.layer.borderWidth = 0.5
statusFileSharing.layer.borderColor = UIColor.systemGray.cgColor
statusFileSharing.layer.masksToBounds = true
statusFileSharing.backgroundColor = .secondarySystemBackground
statusExternalSite.layer.cornerRadius = 12.5
statusExternalSite.layer.borderWidth = 0.5
statusExternalSite.layer.borderColor = UIColor.systemGray.cgColor
statusExternalSite.layer.masksToBounds = true
statusExternalSite.backgroundColor = .secondarySystemBackground
statusEndToEndEncryption.layer.cornerRadius = 12.5
statusEndToEndEncryption.layer.borderWidth = 0.5
statusEndToEndEncryption.layer.borderColor = UIColor.systemGray.cgColor
statusEndToEndEncryption.layer.masksToBounds = true
statusEndToEndEncryption.backgroundColor = .secondarySystemBackground
statusActivity.layer.cornerRadius = 12.5
statusActivity.layer.borderWidth = 0.5
statusActivity.layer.borderColor = UIColor.systemGray.cgColor
statusActivity.layer.masksToBounds = true
statusActivity.backgroundColor = .secondarySystemBackground
statusNotification.layer.cornerRadius = 12.5
statusNotification.layer.borderWidth = 0.5
statusNotification.layer.borderColor = UIColor.systemGray.cgColor
statusNotification.layer.masksToBounds = true
statusNotification.backgroundColor = .secondarySystemBackground
statusDeletedFiles.layer.cornerRadius = 12.5
statusDeletedFiles.layer.borderWidth = 0.5
statusDeletedFiles.layer.borderColor = UIColor.systemGray.cgColor
statusDeletedFiles.layer.masksToBounds = true
statusDeletedFiles.backgroundColor = .secondarySystemBackground
statusText.layer.cornerRadius = 12.5
statusText.layer.borderWidth = 0.5
statusText.layer.borderColor = UIColor.systemGray.cgColor
statusText.layer.masksToBounds = true
statusText.backgroundColor = .secondarySystemBackground
statusCollabora.layer.cornerRadius = 12.5
statusCollabora.layer.borderWidth = 0.5
statusCollabora.layer.borderColor = UIColor.systemGray.cgColor
statusCollabora.layer.masksToBounds = true
statusCollabora.backgroundColor = .secondarySystemBackground
statusOnlyOffice.layer.cornerRadius = 12.5
statusOnlyOffice.layer.borderWidth = 0.5
statusOnlyOffice.layer.borderColor = UIColor.systemGray.cgColor
statusOnlyOffice.layer.masksToBounds = true
statusOnlyOffice.backgroundColor = .secondarySystemBackground
statusUserStatus.layer.cornerRadius = 12.5
statusUserStatus.layer.borderWidth = 0.5
statusUserStatus.layer.borderColor = UIColor.systemGray.cgColor
statusUserStatus.layer.masksToBounds = true
statusUserStatus.backgroundColor = .secondarySystemBackground
statusComments.layer.cornerRadius = 12.5
statusComments.layer.borderWidth = 0.5
statusComments.layer.borderColor = UIColor.systemGray.cgColor
statusComments.layer.masksToBounds = true
statusComments.backgroundColor = .secondarySystemBackground
statusLockFile.layer.cornerRadius = 12.5
statusLockFile.layer.borderWidth = 0.5
statusLockFile.layer.borderColor = UIColor.systemGray.cgColor
statusLockFile.layer.masksToBounds = true
statusLockFile.backgroundColor = .secondarySystemBackground
imageFileSharing.image = UIImage(named: "share")!.image(color: NCBrandColor.shared.gray, size: 50)
imageExternalSite.image = NCUtility.shared.loadImage(named: "network", color: NCBrandColor.shared.gray)
imageEndToEndEncryption.image = NCUtility.shared.loadImage(named: "lock", color: NCBrandColor.shared.gray)
imageActivity.image = UIImage(named: "bolt")!.image(color: NCBrandColor.shared.gray, size: 50)
imageNotification.image = NCUtility.shared.loadImage(named: "bell", color: NCBrandColor.shared.gray)
imageDeletedFiles.image = NCUtility.shared.loadImage(named: "trash", color: NCBrandColor.shared.gray)
imageText.image = UIImage(named: "text")!.image(color: NCBrandColor.shared.gray, size: 50)
imageCollabora.image = UIImage(named: "collabora")!.image(color: NCBrandColor.shared.gray, size: 50)
imageOnlyOffice.image = UIImage(named: "onlyoffice")!.image(color: NCBrandColor.shared.gray, size: 50)
imageUserStatus.image = UIImage(named: "userStatusAway")!.image(color: NCBrandColor.shared.gray, size: 50)
imageComments.image = UIImage(named: "comments")!.image(color: NCBrandColor.shared.gray, size: 50)
imageLockFile.image = UIImage(named: "lock")!.image(color: NCBrandColor.shared.gray, size: 50)
guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
self.account = activeAccount.account
if let text = NCManageDatabase.shared.getCapabilities(account: activeAccount.account) {
capabilitiesText = text
updateCapabilities()
} else {
let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_no_capabilities_found_")
NCContentPresenter.shared.showError(error: error, priority: .max)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.dismiss(animated: true, completion: nil)
}
}
homeImage.image = UIImage(named: "home")!.image(color: NCBrandColor.shared.gray, size: 50)
homeServer.text = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) + "/"
}
@objc func updateCapabilities() {
NextcloudKit.shared.getCapabilities { account, data, error in
if error == .success && data != nil {
NCManageDatabase.shared.addCapabilitiesJSon(data!, account: account)
// EDITORS
let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
if serverVersionMajor >= NCGlobal.shared.nextcloudVersion18 {
NextcloudKit.shared.NCTextObtainEditorDetails { account, editors, creators, data, error in
if error == .success && account == self.appDelegate.account {
NCManageDatabase.shared.addDirectEditing(account: account, editors: editors, creators: creators)
self.readCapabilities()
}
if self.view.window != nil {
// self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.updateCapabilities), userInfo: nil, repeats: false)
}
}
} else {
if self.view.window != nil {
// self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.updateCapabilities), userInfo: nil, repeats: false)
}
}
if let text = NCManageDatabase.shared.getCapabilities(account: account) {
self.capabilitiesText = text
}
self.readCapabilities()
}
}
readCapabilities()
}
@objc func share() {
// timer?.invalidate()
self.dismiss(animated: true) {
let fileURL = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("capabilities.txt")
do {
try self.capabilitiesText.write(to: fileURL, atomically: true, encoding: .utf8)
if let view = self.appDelegate.window?.rootViewController?.view {
self.documentController = UIDocumentInteractionController(url: fileURL)
self.documentController?.delegate = self
self.documentController?.presentOptionsMenu(from: CGRect.zero, in: view, animated: true)
}
} catch { }
}
}
@objc func close() {
// timer?.invalidate()
self.dismiss(animated: true, completion: nil)
}
func readCapabilities() {
textView.text = capabilitiesText
if NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesFileSharingApiEnabled, exists: false) {
statusFileSharing.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusFileSharing.text = NSLocalizedString("_not_available_", comment: "")
}
if NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesExternalSitesExists, exists: true) {
statusExternalSite.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusExternalSite.text = NSLocalizedString("_not_available_", comment: "")
}
let isE2EEEnabled = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesE2EEEnabled, exists: false)
// let versionE2EE = NCManageDatabase.shared.getCapabilitiesServerString(account: account, elements: NCElementsJSON.shared.capabilitiesE2EEApiVersion)
if isE2EEEnabled {
statusEndToEndEncryption.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusEndToEndEncryption.text = NSLocalizedString("_not_available_", comment: "")
}
let activity = NCManageDatabase.shared.getCapabilitiesServerArray(account: account, elements: NCElementsJSON.shared.capabilitiesActivity)
if activity != nil {
statusActivity.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusActivity.text = NSLocalizedString("_not_available_", comment: "")
}
let notification = NCManageDatabase.shared.getCapabilitiesServerArray(account: account, elements: NCElementsJSON.shared.capabilitiesNotification)
if notification != nil {
statusNotification.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusNotification.text = NSLocalizedString("_not_available_", comment: "")
}
let deleteFiles = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesFilesUndelete, exists: false)
if deleteFiles {
statusDeletedFiles.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusDeletedFiles.text = NSLocalizedString("_not_available_", comment: "")
}
var textEditor = false
var onlyofficeEditors = false
if let editors = NCManageDatabase.shared.getDirectEditingEditors(account: account) {
for editor in editors {
if editor.editor == NCGlobal.shared.editorText {
textEditor = true
} else if editor.editor == NCGlobal.shared.editorOnlyoffice {
onlyofficeEditors = true
}
}
}
if textEditor {
statusText.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusText.text = NSLocalizedString("_not_available_", comment: "")
}
let richdocumentsMimetypes = NCManageDatabase.shared.getCapabilitiesServerArray(account: account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes)
if richdocumentsMimetypes != nil {
statusCollabora.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusCollabora.text = NSLocalizedString("_not_available_", comment: "")
}
if onlyofficeEditors {
statusOnlyOffice.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusOnlyOffice.text = NSLocalizedString("_not_available_", comment: "")
}
let userStatus = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesUserStatusEnabled, exists: false)
if userStatus {
statusUserStatus.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusUserStatus.text = NSLocalizedString("_not_available_", comment: "")
}
let comments = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesFilesComments, exists: false)
if comments {
statusComments.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusComments.text = NSLocalizedString("_not_available_", comment: "")
}
let hasLockCapability = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesFilesLockVersion) >= 1
if hasLockCapability {
statusLockFile.text = "✓ " + NSLocalizedString("_available_", comment: "")
} else {
statusLockFile.text = NSLocalizedString("_not_available_", comment: "")
}
print("end.")
}
}
| gpl-3.0 | eb2f9ff0c8ad2eaa0b771e22c8005615 | 47.228571 | 188 | 0.682761 | 4.98229 | false | false | false | false |
themonki/onebusaway-iphone | Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/Message+JSONAdditions.swift | 1 | 4063 | // Sources/SwiftProtobuf/Message+JSONAdditions.swift - JSON format primitive types
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Extensions to `Message` to support JSON encoding/decoding.
///
// -----------------------------------------------------------------------------
import Foundation
/// JSON encoding and decoding methods for messages.
extension Message {
/// Returns a string containing the JSON serialization of the message.
///
/// Unlike binary encoding, presence of required fields is not enforced when
/// serializing to JSON.
///
/// - Returns: A string containing the JSON serialization of the message.
/// - Parameters:
/// - options: The JSONEncodingOptions to use.
/// - Throws: `JSONEncodingError` if encoding fails.
public func jsonString(
options: JSONEncodingOptions = JSONEncodingOptions()
) throws -> String {
let data = try jsonUTF8Data(options: options)
return String(data: data, encoding: String.Encoding.utf8)!
}
/// Returns a Data containing the UTF-8 JSON serialization of the message.
///
/// Unlike binary encoding, presence of required fields is not enforced when
/// serializing to JSON.
///
/// - Returns: A Data containing the JSON serialization of the message.
/// - Parameters:
/// - options: The JSONEncodingOptions to use.
/// - Throws: `JSONEncodingError` if encoding fails.
public func jsonUTF8Data(
options: JSONEncodingOptions = JSONEncodingOptions()
) throws -> Data {
if let m = self as? _CustomJSONCodable {
let string = try m.encodedJSONString(options: options)
let data = string.data(using: String.Encoding.utf8)! // Cannot fail!
return data
}
var visitor = try JSONEncodingVisitor(message: self, options: options)
visitor.startObject()
try traverse(visitor: &visitor)
visitor.endObject()
return visitor.dataResult
}
/// Creates a new message by decoding the given string containing a
/// serialized message in JSON format.
///
/// - Parameter jsonString: The JSON-formatted string to decode.
/// - Parameter options: The JSONDecodingOptions to use.
/// - Throws: `JSONDecodingError` if decoding fails.
public init(
jsonString: String,
options: JSONDecodingOptions = JSONDecodingOptions()
) throws {
if jsonString.isEmpty {
throw JSONDecodingError.truncated
}
if let data = jsonString.data(using: String.Encoding.utf8) {
try self.init(jsonUTF8Data: data, options: options)
} else {
throw JSONDecodingError.truncated
}
}
/// Creates a new message by decoding the given `Data` containing a
/// serialized message in JSON format, interpreting the data as UTF-8 encoded
/// text.
///
/// - Parameter jsonUTF8Data: The JSON-formatted data to decode, represented
/// as UTF-8 encoded text.
/// - Parameter options: The JSONDecodingOptions to use.
/// - Throws: `JSONDecodingError` if decoding fails.
public init(
jsonUTF8Data: Data,
options: JSONDecodingOptions = JSONDecodingOptions()
) throws {
self.init()
try jsonUTF8Data.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) in
let buffer = UnsafeBufferPointer(start: bytes, count: jsonUTF8Data.count)
var decoder = JSONDecoder(source: buffer, options: options)
if !decoder.scanner.skipOptionalNull() {
try decoder.decodeFullObject(message: &self)
} else if Self.self is _CustomJSONCodable.Type {
if let message = try (Self.self as! _CustomJSONCodable.Type)
.decodedFromJSONNull() {
self = message as! Self
} else {
throw JSONDecodingError.illegalNull
}
}
if !decoder.scanner.complete {
throw JSONDecodingError.trailingGarbage
}
}
}
}
| apache-2.0 | 96be50e77c3414276d3714153e1930dc | 35.603604 | 82 | 0.664041 | 4.702546 | false | false | false | false |
SlackKit/SlackKit | SKCore/Sources/BlockLayout.swift | 2 | 4502 | public protocol Block {
var dictionary: [String: Any] { get }
}
public enum BlockType: String, CaseIterable {
case actions
case button
case context
case datePicker = "datepicker"
case divider
case image
case markdown = "mrkdwn"
case overflow
case plainText = "plain_text"
case section
// Selects
case channelSelect = "channels_select"
case converstationSelect = "conversations_select"
case externalSelect = "external_select"
case staticSelect = "static_select"
case usersSelect = "users_select"
}
/// Defined by https://api.slack.com/reference/messaging/blocks#section
public struct SectionBlock: Block {
/// Type will always be section.
public let type: BlockType
public let text: TextComposition
public let blockId: String?
public let fields: [TextComposition]?
public let accessory: SectionElement?
public init(type: BlockType = .section,
text: TextComposition,
blockId: String? = nil,
fields: [TextComposition]? = nil,
accessory: SectionElement? = nil) {
self.type = type
self.text = text
self.blockId = blockId
self.fields = fields
self.accessory = accessory
}
public var dictionary: [String: Any] {
var block = [String: Any]()
block["type"] = type.rawValue
block["text"] = text.dictionary
block["block_id"] = blockId
block["fields"] = fields?.map { $0.dictionary }
block["accessory"] = accessory?.dictionary
return block
}
}
/// Defined by https://api.slack.com/reference/messaging/blocks#divider
public struct DividerBlock: Block {
/// Type will always be divider.
public let type: BlockType
public let blockId: String?
public init(type: BlockType = .divider,
blockId: String? = nil) {
self.type = type
self.blockId = blockId
}
public var dictionary: [String: Any] {
var block = [String: Any]()
block["type"] = type
block["block_id"] = blockId
return block
}
}
/// Defined by https://api.slack.com/reference/messaging/blocks#image
public struct ImageBlock: Block {
/// Type will always be image.
public let type: BlockType
public let imageURL: String
public let altText: String
public let title: String?
public let blockId: String?
public init(type: BlockType = .image,
imageURL: String,
altText: String,
title: String? = nil,
blockId: String? = nil) {
self.type = type
self.imageURL = imageURL
self.altText = altText
self.title = title
self.blockId = blockId
}
public var dictionary: [String: Any] {
var block = [String: Any]()
block["type"] = type.rawValue
block["image_url"] = imageURL
block["alt_text"] = altText
block["title"] = title
block["block_id"] = blockId
return block
}
}
/// Defined by https://api.slack.com/reference/messaging/blocks#actions
public struct ActionsBlock: Block {
/// Type will always be actions.
public let type: BlockType
public let elements: [ActionsElement]
public let blockId: String?
public init(type: BlockType = .actions,
elements: [ActionsElement],
blockId: String? = nil) {
self.type = type
self.elements = elements
self.blockId = blockId
}
public var dictionary: [String: Any] {
var block = [String: Any]()
block["type"] = type.rawValue
block["elements"] = elements.map { $0.dictionary }
block["block_id"] = blockId
return block
}
}
/// Defined by https://api.slack.com/reference/messaging/blocks#context
public struct ContextBlock: Block {
/// Type will always be actions.
public let type: BlockType
public let elements: [ContextElement]
public let blockId: String?
public init(type: BlockType = .context,
elements: [ContextElement],
blockId: String? = nil) {
self.type = type
self.elements = elements
self.blockId = blockId
}
public var dictionary: [String: Any] {
var block = [String: Any]()
block["type"] = type.rawValue
block["elements"] = elements.map { $0.dictionary }
block["block_id"] = blockId
return block
}
}
| mit | 80f4344a2491e1188d965dc7b2c55c46 | 27.858974 | 71 | 0.603065 | 4.271347 | false | false | false | false |
richardpiazza/SOSwift | Sources/SOSwift/PropertyValueOrText.swift | 1 | 2065 | import Foundation
import CodablePlus
public enum PropertyValueOrText: Codable {
case propertyValue(value: PropertyValue)
case text(value: String)
public init(_ value: PropertyValue) {
self = .propertyValue(value: value)
}
public init(_ value: String) {
self = .text(value: value)
}
public init(from decoder: Decoder) throws {
var dictionary: [String : Any]?
do {
let jsonContainer = try decoder.container(keyedBy: DictionaryKeys.self)
dictionary = try jsonContainer.decode(Dictionary<String, Any>.self)
} catch {
}
guard let jsonDictionary = dictionary else {
let container = try decoder.singleValueContainer()
let value = try container.decode(String.self)
self = .text(value: value)
return
}
guard let type = jsonDictionary[SchemaKeys.type.rawValue] as? String else {
throw SchemaError.typeDecodingError
}
let container = try decoder.singleValueContainer()
switch type {
case PropertyValue.schemaName:
let value = try container.decode(PropertyValue.self)
self = .propertyValue(value: value)
default:
throw SchemaError.typeDecodingError
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .propertyValue(let value):
try container.encode(value)
case .text(let value):
try container.encode(value)
}
}
public var propertyValue: PropertyValue? {
switch self {
case .propertyValue(let value):
return value
default:
return nil
}
}
public var text: String? {
switch self {
case .text(let value):
return value
default:
return nil
}
}
}
| mit | 1d5a14067099c424ce4fbb7830a21c3a | 26.171053 | 83 | 0.560775 | 5.1625 | false | false | false | false |
huangboju/Moots | Examples/Lumia/Lumia/Component/SafeArea/Views/TableView/TableViewCellItem.swift | 1 | 805 | //
// TableViewCellItem.swift
// SafeAreaExample
//
// Created by Evgeny Mikhaylov on 05/10/2017.
// Copyright © 2017 Rosberry. All rights reserved.
//
import UIKit
class TableViewCellItem {
typealias Handler = (() -> Void)
var title: String
var enabled: Bool
var switchable: Bool
var custom: Bool
var height: CGFloat
var selectionHandler: Handler?
init(title: String,
custom: Bool = false,
switchable: Bool = false,
enabled: Bool = false,
height: CGFloat = 44.0,
selectionHandler: Handler? = nil) {
self.title = title
self.custom = custom
self.switchable = switchable
self.enabled = enabled
self.height = height
self.selectionHandler = selectionHandler
}
}
| mit | b93e680224ee7279a4ef8c5c9ed9e21e | 21.971429 | 51 | 0.613184 | 4.322581 | false | false | false | false |
Witcast/witcast-ios | Pods/Material/Sources/Frameworks/Motion/Sources/MotionController.swift | 1 | 16236 | /*
* The MIT License (MIT)
*
* Copyright (C) 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Original Inspiration & Author
* Copyright (c) 2016 Luke Zhao <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
public class MotionController: NSObject {
/// A reference to the MotionContext.
public internal(set) var context: MotionContext!
/// A boolean indicating whether the transition interactive or not.
public var isInteractive: Bool {
return nil == displayLink
}
/// Progress of the current transition. 0 if no transition is happening.
public internal(set) var elapsedTime: TimeInterval = 0 {
didSet {
guard isTransitioning else {
return
}
updateTransitionObservers()
guard isInteractive else {
updatePlugins()
return
}
updateAnimators()
}
}
/// A boolean indicating whether a transition is active.
public var isTransitioning: Bool {
return nil != transitionContainer
}
/**
A view container used to hold all the animating views during a
transition.
*/
public internal(set) var container: UIView?
/// UIKit's supplied transition container.
internal var transitionContainer: UIView?
/// An optional completion callback.
internal var completionCallback: ((Bool) -> Void)?
/// Binds the render cycle to the transition animation.
internal var displayLink: CADisplayLink?
/// An Array of observers that are updated during a transition.
internal var transitionObservers: [MotionTransitionObserver]?
/// Max duration used by MotionAnimators and MotionPlugins.
public internal(set) var totalDuration: TimeInterval = 0
/// The currently running animation duration.
internal var currentAnimationDuration: TimeInterval = 0
/// The start time of the animation.
internal var beginTime: TimeInterval? {
didSet {
guard nil != beginTime else {
displayLink?.isPaused = true
displayLink?.remove(from: RunLoop.main, forMode: RunLoopMode(rawValue: RunLoopMode.commonModes.rawValue))
displayLink = nil
return
}
guard nil == displayLink else {
return
}
displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink(_:)))
displayLink?.add(to: RunLoop.main, forMode: RunLoopMode(rawValue: RunLoopMode.commonModes.rawValue))
}
}
/// A boolean indicating if the transition has finished.
internal var isFinished = true
/// An Array of MotionPreprocessors used during a transition.
internal fileprivate(set) lazy var preprocessors = [MotionPreprocessor]()
/// An Array of MotionAnimators used during a transition.
internal fileprivate(set) lazy var animators = [MotionAnimator]()
/// An Array of MotionPlugins used during a transition.
internal fileprivate(set) lazy var plugins = [MotionPlugin]()
/// The matching fromViews to toViews based on the motionIdentifier value.
internal fileprivate(set) lazy var transitionPairs = [(fromViews: [UIView], toViews: [UIView])]()
/// Plugins that are enabled during the transition.
internal static var enabledPlugins = [MotionPlugin.Type]()
/// Initializer.
internal override init() {}
}
public extension MotionController {
/**
Receive callbacks on each animation frame.
Observers will be cleaned when a transition completes.
- Parameter observer: A MotionTransitionObserver.
*/
func addTransitionObserver(observer: MotionTransitionObserver) {
if nil == transitionObservers {
transitionObservers = []
}
transitionObservers?.append(observer)
}
}
fileprivate extension MotionController {
/// Updates the transition observers.
func updateTransitionObservers() {
guard let observers = transitionObservers else {
return
}
for v in observers {
v.motion(transitionObserver: v, didUpdateWith: elapsedTime)
}
}
/// Updates the animators.
func updateAnimators() {
let t = elapsedTime * totalDuration
for a in animators {
a.seek(to: t)
}
}
/// Updates the plugins.
func updatePlugins() {
let t = elapsedTime * totalDuration
for p in plugins where p.requirePerFrameCallback {
p.seek(to: t)
}
}
}
fileprivate extension MotionController {
/**
Handler for the DisplayLink updates.
- Parameter _ link: CADisplayLink.
*/
@objc
func handleDisplayLink(_ link: CADisplayLink) {
guard isTransitioning else {
return
}
guard 0 < currentAnimationDuration else {
return
}
guard let t = beginTime else {
return
}
let cTime = CACurrentMediaTime() - t
if cTime > currentAnimationDuration {
elapsedTime = isFinished ? 1 : 0
beginTime = nil
complete(isFinished: isFinished)
} else {
var eTime = cTime / totalDuration
if !isFinished {
eTime = 1 - eTime
}
elapsedTime = max(0, min(1, eTime))
}
}
}
public extension MotionController {
/**
Updates the elapsed time for the interactive transition.
- Parameter elapsedTime t: the current progress, must be between -1...1.
*/
public func update(elapsedTime t: TimeInterval) {
guard isTransitioning else {
return
}
beginTime = nil
elapsedTime = max(-1, min(1, t))
}
/**
Finish the interactive transition.
Will stop the interactive transition and animate from the
current state to the **end** state
- Parameter isAnimated: A boolean indicating if the completion is animated.
*/
public func end(isAnimated: Bool = true) {
guard isTransitioning else {
return
}
guard isAnimated else {
complete(isFinished: true)
return
}
var t: TimeInterval = 0
for a in animators {
t = max(t, a.resume(at: elapsedTime * totalDuration, isReversed: false))
}
complete(after: t, isFinished: true)
}
/**
Cancel the interactive transition.
Will stop the interactive transition and animate from the
current state to the **begining** state
- Parameter isAnimated: A boolean indicating if the completion is animated.
*/
public func cancel(isAnimated: Bool = true) {
guard isTransitioning else {
return
}
guard isAnimated else {
complete(isFinished: false)
return
}
var d: TimeInterval = 0
for a in animators {
var t = elapsedTime
if t < 0 {
t = -t
}
d = max(d, a.resume(at: t * totalDuration, isReversed: true))
}
complete(after: d, isFinished: false)
}
/**
Override transition animations during an interactive animation.
For example:
Motion.shared.apply([.position(x:50, y:50)], to: view)
will set the view's position to 50, 50
- Parameter transitions: An Array of MotionTransitions.
- Parameter to view: A UIView.
*/
public func apply(transitions: [MotionTransition], to view: UIView) {
guard isTransitioning else {
return
}
let s = MotionTransitionState(transitions: transitions)
let v = context.transitionPairedView(for: view) ?? view
for a in animators {
a.apply(state: s, to: v)
}
}
}
internal extension MotionController {
/**
Load plugins, processors, animators, container, & context
The transitionContainer must already be set.
Subclasses should call context.set(fromViews: toViews) after
inserting fromViews & toViews into the container
*/
func prepareTransition() {
guard isTransitioning else {
return
}
prepareTransitionContainer()
prepareContext()
preparePreprocessors()
prepareAnimators()
preparePlugins()
}
/// Prepares the transition fromView & toView pairs.
func prepareTransitionPairs() {
guard isTransitioning else {
return
}
for a in animators {
let fv = context.fromViews.filter { (view: UIView) -> Bool in
return a.canAnimate(view: view, isAppearing: false)
}
let tv = context.toViews.filter {
return a.canAnimate(view: $0, isAppearing: true)
}
transitionPairs.append((fv, tv))
}
}
}
internal extension MotionController {
/// Executes the preprocessors' process function.
func processContext() {
guard isTransitioning else {
return
}
for x in preprocessors {
x.process(fromViews: context.fromViews, toViews: context.toViews)
}
}
/**
Animates the views. Subclasses should call `prepareTransition` &
`prepareTransitionPairs` before calling `animate`.
*/
func animate() {
guard isTransitioning else {
return
}
for (fv, tv) in transitionPairs {
for view in fv {
context.hide(view: view)
}
for view in tv {
context.hide(view: view)
}
}
var t: TimeInterval = 0
var b = false
for (i, a) in animators.enumerated() {
let d = a.animate(fromViews: transitionPairs[i].0, toViews: transitionPairs[i].1)
if .infinity == d {
b = true
} else {
t = max(t, d)
}
}
totalDuration = t
if b {
update(elapsedTime: 0)
} else {
complete(after: t, isFinished: true)
}
}
/**
Complete the transition.
- Parameter after: A TimeInterval.
- Parameter isFinished: A Boolean indicating if the transition
has completed.
*/
func complete(after: TimeInterval, isFinished: Bool) {
guard isTransitioning else {
return
}
if after <= 0.001 {
complete(isFinished: isFinished)
return
}
let v = (isFinished ? elapsedTime : 1 - elapsedTime) * totalDuration
self.isFinished = isFinished
currentAnimationDuration = after + v
beginTime = CACurrentMediaTime() - v
}
/**
Complete the transition.
- Parameter isFinished: A Boolean indicating if the transition
has completed.
*/
func complete(isFinished: Bool) {
guard isTransitioning else {
return
}
for a in animators {
a.clean()
}
transitionContainer?.isUserInteractionEnabled = true
let completion = completionCallback
transitionObservers = nil
transitionContainer = nil
completionCallback = nil
container = nil
context = nil
beginTime = nil
elapsedTime = 0
totalDuration = 0
preprocessors.removeAll()
animators.removeAll()
plugins.removeAll()
transitionPairs.removeAll()
completion?(isFinished)
}
}
fileprivate extension MotionController {
/// Prepares the transition container.
func prepareTransitionContainer() {
guard let v = transitionContainer else {
return
}
v.isUserInteractionEnabled = false
// a view to hold all the animating views
container = UIView(frame: v.bounds)
v.addSubview(container!)
}
/// Prepares the context.
func prepareContext() {
guard let v = container else {
return
}
context = MotionContext(container: v)
}
/// Prepares the preprocessors.
func preparePreprocessors() {
for x in [
IgnoreSubviewTransitionsPreprocessor(),
MatchPreprocessor(),
SourcePreprocessor(),
CascadePreprocessor(),
DurationPreprocessor()] as [MotionPreprocessor] {
preprocessors.append(x)
}
for x in preprocessors {
x.context = context
}
}
/// Prepares the animators.
func prepareAnimators() {
animators.append(MotionTransitionAnimator<MotionCoreAnimationViewContext>())
if #available(iOS 10, tvOS 10, *) {
animators.append(MotionTransitionAnimator<MotionViewPropertyViewContext>())
}
for v in animators {
v.context = context
}
}
/// Prepares the plugins.
func preparePlugins() {
for x in Motion.enabledPlugins.map({
return $0.init()
}) {
plugins.append(x)
}
for plugin in plugins {
preprocessors.append(plugin)
animators.append(plugin)
}
}
}
internal extension MotionController {
/**
Checks if a given plugin is enabled.
- Parameter plugin: A MotionPlugin.Type.
- Returns: A boolean indicating if the plugin is enabled or not.
*/
static func isEnabled(plugin: MotionPlugin.Type) -> Bool {
return nil != enabledPlugins.index(where: { return $0 == plugin })
}
/**
Enables a given plugin.
- Parameter plugin: A MotionPlugin.Type.
*/
static func enable(plugin: MotionPlugin.Type) {
disable(plugin: plugin)
enabledPlugins.append(plugin)
}
/**
Disables a given plugin.
- Parameter plugin: A MotionPlugin.Type.
*/
static func disable(plugin: MotionPlugin.Type) {
guard let index = enabledPlugins.index(where: { return $0 == plugin }) else {
return
}
enabledPlugins.remove(at: index)
}
}
internal extension MotionController {
// should call this after `prepareTransitionPairs` & before `processContext`
func insert<T>(preprocessor: MotionPreprocessor, before: T.Type) {
let i = preprocessors.index { $0 is T } ?? preprocessors.count
preprocessor.context = context
preprocessors.insert(preprocessor, at: i)
}
}
| apache-2.0 | 904739d4830b76eabe0b7c9bf7f76330 | 27.838366 | 121 | 0.584873 | 5.269718 | false | false | false | false |
alonecuzzo/MetroBurb | MetroBurb/Class/Location/MetroBurbCoreLocationManager.swift | 1 | 3324 | //
// MetroBurbCoreLocationManager.swift
// MetroBurb
//
// Created by Jabari Bell on 12/22/15.
// Copyright © 2015 Code Mitten. All rights reserved.
//
import Foundation
import Foundation
import RxSwift
import RxCocoa
import CoreLocation
typealias UIAlertActionHandlerBlock = ((UIAlertAction) -> Void)
class MetroBurbCoreLocationManager {
//MARK: Property
private let locationManager: CLLocationManager
private let disposeBag: DisposeBag = DisposeBag()
private let alertKey = "internalCoreLocationAlertHasBeenShownDateKey"
var systemCancelAction: UIAlertActionHandlerBlock?
private let internalAlertBlock: (MetroBurbCoreLocationManager) -> Void
var numberOfDaysUntilNextInternalAlertDisplay = 7
//MARK: Method
init(locationReceivedBlock: (location: CLLocation?) -> Void, internalAlertBlock: (MetroBurbCoreLocationManager) -> Void) {
self.locationManager = CLLocationManager()
self.internalAlertBlock = internalAlertBlock
let status = CLLocationManager.authorizationStatus()
if status == .NotDetermined {
if shouldShowInternalAlert() {
showInternalLocationAlertBlock()
}
}
locationManager.rx_didUpdateLocations
.distinctUntilChanged({ (lhs, rhs) -> Bool in
return lhs.first?.coordinate.latitude == rhs.first?.coordinate.latitude
&& lhs.first?.coordinate.longitude == rhs.first?.coordinate.longitude
})
.subscribeNext { [weak self] locations -> Void in
self?.locationManager.stopUpdatingLocation()
locationReceivedBlock(location: locations.first)
}
.addDisposableTo(disposeBag)
locationManager.rx_didChangeAuthorizationStatus.subscribeNext { [weak self] status -> Void in
guard let status = status else { return }
switch status {
case .Denied, .Restricted:
self?.systemCancelAction?(UIAlertAction()) //we don't need an alert action - change signature
default:
self?.startUpdatingLocationIfAuthorized(status)
}
}.addDisposableTo(disposeBag)
startUpdatingLocationIfAuthorized(status)
}
func requestAlwaysAuthorization() -> Void {
locationManager.requestAlwaysAuthorization()
}
private func startUpdatingLocationIfAuthorized(status: CLAuthorizationStatus) -> Void {
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
}
}
}
// MARK: Internal Alert Stuff
extension MetroBurbCoreLocationManager {
private func shouldShowInternalAlert() -> Bool {
guard let date = NSUserDefaults.standardUserDefaults().objectForKey(alertKey) as? NSDate else { return true }
let elapsedTime = NSDate().timeIntervalSinceDate(date)
let maxSecondsBeforeRePop = numberOfDaysUntilNextInternalAlertDisplay * 60 * 60 * 24
return Int(elapsedTime) > maxSecondsBeforeRePop
}
private func showInternalLocationAlertBlock() -> Void {
internalAlertBlock(self)
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: alertKey)
}
}
| mpl-2.0 | 13699de057a36e3915b11892a0357496 | 36.337079 | 126 | 0.672886 | 5.429739 | false | false | false | false |
raymondjavaxx/SimplePath | Tests/SimplePathTests/PathFormatTests.swift | 1 | 1075 | //
// PathFormatTests.swift
// SimplePathTests
//
// Created by Ramon Torres on 10/22/17.
// Copyright © 2017 Ramon Torres. All rights reserved.
//
import XCTest
@testable import SimplePath
class PathFormatTests: XCTestCase {
func testFormatWithDirAndBasename() {
let result = Path.format([
.dir: "assets/icons",
.base: "settings.png"
])
let expected = "assets/icons/settings.png"
XCTAssertEqual(result, expected)
}
func testFormatWithBaseAndExtension() {
let result = Path.format([
.base: "logo",
.ext: "svg"
])
XCTAssertEqual(result, "logo.svg")
}
func testFormatWithEmptyElements() {
let result = Path.format([:])
XCTAssertEqual(result, "")
}
// For Linux
static var allTests = [
("testFormatWithDirAndBasename", testFormatWithDirAndBasename),
("testFormatWithBaseAndExtension", testFormatWithBaseAndExtension),
("testFormatWithEmptyElements", testFormatWithEmptyElements)
]
}
| mit | b80dfe98e2514ab3fd43e33d7bad347a | 22.347826 | 75 | 0.623836 | 4.261905 | false | true | false | false |
linhaosunny/yeehaiyake | 椰海雅客微博/椰海雅客微博/Classes/Main/Resource/LSXNullViewController.swift | 1 | 3136 | //
// LSXNullViewController.swift
// 椰海雅客微博
//
// Created by 李莎鑫 on 2017/4/2.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
class LSXNullViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | b5f616d3f969b2ac8e0ab8a4ad8f21cc | 31.726316 | 136 | 0.669025 | 5.22521 | false | false | false | false |
SuPair/firefox-ios | Extensions/ShareTo/ClientPickerViewController.swift | 3 | 14797 |
/* 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 Shared
import Storage
import SnapKit
protocol ClientPickerViewControllerDelegate {
func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController)
func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient])
}
private struct ClientPickerViewControllerUX {
static let TableHeaderRowHeight = CGFloat(50)
static let TableHeaderTextFont = UIFont.systemFont(ofSize: 16)
static let TableHeaderTextColor = UIColor.Photon.Grey50
static let TableHeaderTextPaddingLeft = CGFloat(20)
static let DeviceRowTintColor = UIColor.Photon.Green60
static let DeviceRowHeight = CGFloat(50)
static let DeviceRowTextFont = UIFont.systemFont(ofSize: 16)
static let DeviceRowTextPaddingLeft = CGFloat(72)
static let DeviceRowTextPaddingRight = CGFloat(50)
}
/// The ClientPickerViewController displays a list of clients associated with the provided Account.
/// The user can select a number of devices and hit the Send button.
/// This viewcontroller does not implement any specific business logic that needs to happen with the selected clients.
/// That is up to it's delegate, who can listen for cancellation and success events.
enum LoadingState {
case LoadingFromCache
case LoadingFromServer
case Loaded
}
class ClientPickerViewController: UITableViewController {
var profile: Profile?
var profileNeedsShutdown = true
var clientPickerDelegate: ClientPickerViewControllerDelegate?
var loadState = LoadingState.LoadingFromCache
var clients: [RemoteClient] = []
var selectedClients = NSMutableSet()
// ShareItem has been added as we are now using this class outside of the ShareTo extension to provide Share To functionality
// And in this case we need to be able to store the item we are sharing as we may not have access to the
// url later. Currently used only when sharing an item from the Tab Tray from a Preview Action.
var shareItem: ShareItem?
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Send Tab", tableName: "SendTo", comment: "Title of the dialog that allows you to send a tab to a different device")
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(refresh), for: .valueChanged)
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: Strings.SendToCancelButton,
style: .plain,
target: self,
action: #selector(cancel)
)
tableView.register(ClientPickerTableViewHeaderCell.self, forCellReuseIdentifier: ClientPickerTableViewHeaderCell.CellIdentifier)
tableView.register(ClientPickerTableViewCell.self, forCellReuseIdentifier: ClientPickerTableViewCell.CellIdentifier)
tableView.register(ClientPickerNoClientsTableViewCell.self, forCellReuseIdentifier: ClientPickerNoClientsTableViewCell.CellIdentifier)
tableView.tableFooterView = UIView(frame: .zero)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadCachedClients()
}
override func numberOfSections(in tableView: UITableView) -> Int {
if clients.count == 0 {
return 1
} else {
return 2
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if clients.count == 0 {
return 1
} else {
if section == 0 {
return 1
} else {
return clients.count
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
if clients.count > 0 {
if indexPath.section == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: ClientPickerTableViewHeaderCell.CellIdentifier, for: indexPath) as! ClientPickerTableViewHeaderCell
} else {
let clientCell = tableView.dequeueReusableCell(withIdentifier: ClientPickerTableViewCell.CellIdentifier, for: indexPath) as! ClientPickerTableViewCell
clientCell.nameLabel.text = clients[indexPath.row].name
clientCell.clientType = clients[indexPath.row].type == "mobile" ? ClientType.Mobile : ClientType.Desktop
clientCell.checked = selectedClients.contains(indexPath)
cell = clientCell
}
} else {
if self.loadState == .Loaded {
cell = tableView.dequeueReusableCell(withIdentifier: ClientPickerNoClientsTableViewCell.CellIdentifier, for: indexPath) as! ClientPickerNoClientsTableViewCell
} else {
cell = UITableViewCell(style: .default, reuseIdentifier: "ClientCell")
}
}
return cell
}
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return indexPath.section != 0
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if clients.count > 0 && indexPath.section == 1 {
tableView.deselectRow(at: indexPath, animated: true)
if selectedClients.contains(indexPath) {
selectedClients.remove(indexPath)
} else {
selectedClients.add(indexPath)
}
tableView.reloadRows(at: [indexPath], with: .none)
navigationItem.rightBarButtonItem?.isEnabled = (selectedClients.count != 0)
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if clients.count > 0 {
if indexPath.section == 0 {
return ClientPickerViewControllerUX.TableHeaderRowHeight
} else {
return ClientPickerViewControllerUX.DeviceRowHeight
}
} else {
return tableView.frame.height
}
}
fileprivate func ensureOpenProfile() -> Profile {
// If we were not given a profile, open the default profile. This happens in case we are called from an app
// extension. That also means that we need to shut down the profile, otherwise the app extension will be
// terminated when it goes into the background.
if let profile = self.profile {
// Re-open the profile if it was shutdown. This happens when we run from an app extension, where we must
// make sure that the profile is only open for brief moments of time.
if profile.isShutdown {
profile.reopen()
}
return profile
}
let profile = BrowserProfile(localName: "profile")
self.profile = profile
self.profileNeedsShutdown = true
return profile
}
// Load cached clients from the profile, triggering a sync to fetch newer data.
fileprivate func loadCachedClients() {
let profile = self.ensureOpenProfile()
self.loadState = .LoadingFromCache
// Load and display the cached clients.
// Don't shut down the profile here: we immediately call `reloadClients`.
profile.getCachedClients().upon({ result in
withExtendedLifetime(profile) {
if let c = result.successValue {
self.updateClients(clients: c, endRefreshing: false)
if c.isEmpty {
// Show refresh. If we have cached clients, we'll update them silently.
self.refresh()
return
}
}
self.reloadClients()
}
})
}
fileprivate func reloadClients() {
let profile = self.ensureOpenProfile()
self.loadState = .LoadingFromServer
profile.getClients().upon({ result in
withExtendedLifetime(profile) {
self.loadState = .Loaded
// If we are running from an app extension then make sure we shut down the profile as soon as we are
// done with it.
if self.profileNeedsShutdown {
profile.shutdown()
}
self.loadState = .Loaded
guard let c = result.successValue else {
return
}
self.updateClients(clients: c, endRefreshing: true)
}
})
}
fileprivate func updateClients(clients: [RemoteClient], endRefreshing: Bool) {
guard self.clients != clients else {
if endRefreshing {
DispatchQueue.main.async {
self.refreshControl?.endRefreshing()
}
}
return
}
self.clients = clients
DispatchQueue.main.async {
if self.clients.count == 0 {
self.navigationItem.rightBarButtonItem = nil
} else {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Send", tableName: "SendTo", comment: "Navigation bar button to Send the current page to a device"), style: .done, target: self, action: #selector(self.send))
self.navigationItem.rightBarButtonItem?.isEnabled = false
}
self.selectedClients.removeAllObjects()
self.tableView.reloadData()
if endRefreshing {
self.refreshControl?.endRefreshing()
}
}
}
@objc func refresh() {
DispatchQueue.main.async {
if let refreshControl = self.refreshControl {
refreshControl.beginRefreshing()
let height = -(refreshControl.bounds.size.height + (self.navigationController?.navigationBar.bounds.size.height ?? 0))
self.tableView.contentOffset = CGPoint(x: 0, y: height)
}
}
reloadClients()
}
@objc func cancel() {
clientPickerDelegate?.clientPickerViewControllerDidCancel(self)
}
@objc func send() {
var clients = [RemoteClient]()
for indexPath in selectedClients {
clients.append(self.clients[(indexPath as AnyObject).row])
}
clientPickerDelegate?.clientPickerViewController(self, didPickClients: clients)
// Replace the Send button with a loading indicator since it takes a while to sync
// up our changes to the server.
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(width: 25, height: 25))
loadingIndicator.color = UIColor.Photon.Grey60
loadingIndicator.startAnimating()
let customBarButton = UIBarButtonItem(customView: loadingIndicator)
self.navigationItem.rightBarButtonItem = customBarButton
}
}
class ClientPickerTableViewHeaderCell: UITableViewCell {
static let CellIdentifier = "ClientPickerTableViewSectionHeader"
let nameLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(nameLabel)
nameLabel.font = ClientPickerViewControllerUX.TableHeaderTextFont
nameLabel.text = NSLocalizedString("Available devices:", tableName: "SendTo", comment: "Header for the list of devices table")
nameLabel.textColor = ClientPickerViewControllerUX.TableHeaderTextColor
nameLabel.snp.makeConstraints { (make) -> Void in
make.left.equalTo(ClientPickerViewControllerUX.TableHeaderTextPaddingLeft)
make.centerY.equalTo(self)
make.right.equalTo(self)
}
preservesSuperviewLayoutMargins = false
layoutMargins = .zero
separatorInset = .zero
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public enum ClientType: String {
case Mobile = "deviceTypeMobile"
case Desktop = "deviceTypeDesktop"
}
class ClientPickerTableViewCell: UITableViewCell {
static let CellIdentifier = "ClientPickerTableViewCell"
var nameLabel: UILabel
var checked: Bool = false {
didSet {
self.accessoryType = checked ? .checkmark : .none
}
}
var clientType: ClientType = ClientType.Mobile {
didSet {
self.imageView?.image = UIImage(named: clientType.rawValue)
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
nameLabel = UILabel()
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(nameLabel)
nameLabel.font = ClientPickerViewControllerUX.DeviceRowTextFont
nameLabel.numberOfLines = 2
nameLabel.lineBreakMode = .byWordWrapping
self.tintColor = ClientPickerViewControllerUX.DeviceRowTintColor
self.preservesSuperviewLayoutMargins = false
self.selectionStyle = .none
}
override func layoutSubviews() {
super.layoutSubviews()
nameLabel.snp.makeConstraints { (make) -> Void in
make.left.equalTo(ClientPickerViewControllerUX.DeviceRowTextPaddingLeft)
make.centerY.equalTo(self.snp.centerY)
make.right.equalTo(self.snp.right).offset(-ClientPickerViewControllerUX.DeviceRowTextPaddingRight)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ClientPickerNoClientsTableViewCell: UITableViewCell {
static let CellIdentifier = "ClientPickerNoClientsTableViewCell"
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupHelpView(contentView,
introText: NSLocalizedString("You don’t have any other devices connected to this Firefox Account available to sync.", tableName: "SendTo", comment: "Error message shown in the remote tabs panel"),
showMeText: "") // TODO We used to have a 'show me how to ...' text here. But, we cannot open web pages from the extension. So this is clear for now until we decide otherwise.
// Move the separator off screen
separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | 340f0db9d4ebf25b367d085aded06169 | 39.094851 | 256 | 0.657181 | 5.4214 | false | false | false | false |
alfiehanssen/360Player | ThreeSixtyPlayer/ForDemos/Video+Demos.swift | 2 | 2512 | //
// Video.swift
// ThreeSixtyPlayer
//
// Created by Alfred Hanssen on 10/6/16.
// Copyright © 2016 Alfie Hanssen. 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
import CoreGraphics
public extension Video
{
static let Mono = "https://player.vimeo.com/external/187856429.m3u8?s=70eca31df2bc0f134331bb230e80dea855c0a8b0"
static let StereoTopBottom = "https://player.vimeo.com/external/189658493.m3u8?s=e7ce8dc8f367e42df0a22279ccb82fbbe08c0a85"
static let StereoLeftRight = StereoTopBottom // TODO: Need a left/right resource.
static let DefaultMonoResolution = CGSize(width: 1920, height: 1080) // TODO: I believe the correct resolution is 1920x960.
static let DefaultStereoResolution = CGSize(width: 1080, height: 1080) // TODO: For HLS/DASH we don't want to rely on w/h just aspect ratio.
static func demoVideo(ofType type: VideoType) -> Video
{
switch type
{
case .monoscopic:
return Video(urlString: Mono, resolution: DefaultMonoResolution, type: type)
case .stereoscopic(layout: let layout):
switch layout
{
case .topBottom:
return Video(urlString: StereoTopBottom, resolution: DefaultStereoResolution, type: type)
case .leftRight:
return Video(urlString: StereoLeftRight, resolution: DefaultStereoResolution, type: type)
}
}
}
}
| mit | 994dbfb6338de008a90c2ddba4c0335e | 42.293103 | 144 | 0.714855 | 4.063107 | false | false | false | false |
eCrowdMedia/MooApi | Tests/ReadingTests.swift | 1 | 590 | import XCTest
@testable import MooApi
import Argo
import Foundation
final internal class ReadingTests: XCTestCase {
func testDatas() {
let testBundle = Bundle(for: type(of: self))
let path = testBundle.path(forResource: "ReadingInfo", ofType: "json")
let data = try! Data(contentsOf: URL(fileURLWithPath: path!))
let json = JSON(try! JSONSerialization.jsonObject(with: data, options: []))
let result = ApiDocument<Reading>.decode(json)
guard (result.value?.data) != nil else {
XCTFail("\(result.error.debugDescription)")
return
}
}
}
| mit | 1135553cb60a289bdf83fd1b62fea65b | 27.095238 | 79 | 0.681356 | 4.097222 | false | true | false | false |
modocache/swift | validation-test/Sema/OverridesAndOverloads.swift | 7 | 9771 | // RUN: %target-parse-verify-swift -D ERRORS
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
struct Token1 {}
struct Token2 {}
struct Token3 {}
class C1 {}
class C1x : C1 {}
class C1xx : C1x {}
protocol P1 {}
protocol P1x : P1 {}
struct P1ImplS1 : P1 {}
struct P1xImplS1 : P1x {}
class P1ImplC1x : C1, P1 {}
class P1ImplC1xx {}
class P1xImplC1x : C1, P1x {}
var which = ""
var Overrides = TestSuite("Overrides")
Overrides.test("covariant argument override, non-optional to optional") {
class Base {
func foo(_: C1) { which = "Base.foo(C1)" }
}
class Derived : Base {
override func foo(_: C1?) { which = "Derived.foo(C1?)" }
}
Derived().foo(C1())
expectEqual("Derived.foo(C1?)", which)
Derived().foo(nil as C1?)
expectEqual("Derived.foo(C1?)", which)
}
Overrides.test("covariant argument override, derived class to base class") {
class Base {
func foo(_: C1x) { which = "Base.foo(C1x)" }
}
class Derived : Base {
override func foo(_: C1) { which = "Derived.foo(C1)" }
}
Derived().foo(C1())
expectEqual("Derived.foo(C1)", which)
Derived().foo(C1x())
expectEqual("Derived.foo(C1)", which)
}
Overrides.test("covariant argument override, optional derived class to non-optional base class") {
class Base {
func foo(_: C1x) { which = "Base.foo(C1x)" }
}
class Derived : Base {
override func foo(_: C1?) { which = "Derived.foo(C1?)" }
}
Derived().foo(C1())
expectEqual("Derived.foo(C1?)", which)
Derived().foo(C1x())
expectEqual("Derived.foo(C1?)", which)
Derived().foo(nil)
expectEqual("Derived.foo(C1?)", which)
}
Overrides.test("covariant argument override, protocol to protocol") {
// FIXME: https://bugs.swift.org/browse/SR-731
// Covariant overrides don't work with protocols
class Base {
func foo(_: P1x) { which = "Base.foo(P1x)" }
}
class Derived : Base {
/*FIXME: override */ func foo(_: P1) { which = "Derived.foo(P1)" }
}
Derived().foo(P1ImplS1())
expectEqual("Derived.foo(P1)", which)
Derived().foo(P1xImplS1())
expectEqual("Base.foo(P1x)", which)
}
Overrides.test("covariant argument override, struct to protocol") {
// FIXME: https://bugs.swift.org/browse/SR-731
// Covariant overrides don't work with protocols
class Base {
func foo(_: P1ImplS1) { which = "Base.foo(P1ImplS1)" }
}
class Derived : Base {
/*FIXME: override */ func foo(_: P1) { which = "Derived.foo(P1)" }
}
// FIXME: https://bugs.swift.org/browse/SR-731
expectFailure {
Derived().foo(P1ImplS1())
expectEqual("Derived.foo(P1)", which)
}
Derived().foo(P1xImplS1())
expectEqual("Derived.foo(P1)", which)
}
Overrides.test("contravariant return type override, optional to non-optional") {
class Base {
func foo() -> C1? { which = "Base.foo() -> C1?"; return C1() }
}
class Derived : Base {
override func foo() -> C1 {
which = "Derived.foo() -> C1"; return C1()
}
}
_ = Derived().foo() as C1
expectEqual("Derived.foo() -> C1", which)
_ = Derived().foo() as C1?
expectEqual("Derived.foo() -> C1", which)
}
Overrides.test("contravariant return type override, base class to derived class") {
class Base {
func foo() -> C1 { which = "Base.foo() -> C1"; return C1() }
}
class Derived : Base {
override func foo() -> C1x {
which = "Derived.foo() -> C1x"; return C1x()
}
}
_ = Derived().foo() as C1
expectEqual("Derived.foo() -> C1x", which)
_ = Derived().foo() as C1x
expectEqual("Derived.foo() -> C1x", which)
}
Overrides.test("contravariant return type override, optional base class to non-optional derived class") {
class Base {
func foo() -> C1? { which = "Base.foo() -> C1?"; return C1() }
}
class Derived : Base {
override func foo() -> C1x {
which = "Derived.foo() -> C1x"; return C1x()
}
}
_ = Derived().foo() as C1
expectEqual("Derived.foo() -> C1x", which)
_ = Derived().foo() as C1x
expectEqual("Derived.foo() -> C1x", which)
}
Overrides.test("contravariant return type override, protocol to protocol") {
// FIXME: https://bugs.swift.org/browse/SR-733
// Contravariant overrides on return type don't work with protocols
class Base {
func foo() -> P1 { which = "Base.foo() -> P1"; return P1ImplS1() }
}
class Derived : Base {
/*FIXME: override */ func foo() -> P1x {
which = "Derived.foo() -> P1x"; return P1xImplS1()
}
}
// https://bugs.swift.org/browse/SR-733
// FIXME: uncomment when the bug is fixed.
// Derived().foo() as P1 // error: ambiguous use of 'foo()'
// expectEqual("Derived.foo() -> P1x", which)
_ = Derived().foo() as P1x
expectEqual("Derived.foo() -> P1x", which)
}
Overrides.test("contravariant return type override, protocol to struct") {
// FIXME: https://bugs.swift.org/browse/SR-733
// Contravariant overrides on return type don't work with protocols
class Base {
func foo() -> P1 { which = "Base.foo() -> P1"; return P1ImplS1() }
}
class Derived : Base {
/*FIXME: override */ func foo() -> P1ImplS1 {
which = "Derived.foo() -> P1ImplS1"; return P1ImplS1()
}
}
// https://bugs.swift.org/browse/SR-733
// FIXME: uncomment when the bug is fixed.
// Derived().foo() as P1 // error: ambiguous use of 'foo()'
// expectEqual("Derived.foo() -> P1ImplS1", which)
_ = Derived().foo() as P1ImplS1
expectEqual("Derived.foo() -> P1ImplS1", which)
}
Overrides.test("overrides don't affect overload resolution") {
class Base {
func foo(_: P1) { which = "Base.foo(P1)" }
}
class Derived : Base {
func foo(_: P1x) { which = "Derived.foo(P1x)" }
}
class MoreDerived : Derived {
override func foo(_: P1) { which = "MoreDerived.foo(P1)" }
}
Base().foo(P1ImplS1())
expectEqual("Base.foo(P1)", which)
Derived().foo(P1ImplS1())
expectEqual("Base.foo(P1)", which)
Derived().foo(P1xImplS1())
expectEqual("Derived.foo(P1x)", which)
MoreDerived().foo(P1ImplS1())
expectEqual("MoreDerived.foo(P1)", which)
MoreDerived().foo(P1xImplS1())
expectEqual("Derived.foo(P1x)", which)
}
var Overloads = TestSuite("Overloads")
Overloads.test("perfect match") {
class Base {
func foo(_: C1, _: C1, _: C1) { which = "C1, C1, C1" }
func foo(_: C1, _: C1, _: C1x) { which = "C1, C1, C1x" }
func foo(_: C1, _: C1x, _: C1) { which = "C1, C1x, C1" }
func foo(_: C1, _: C1x, _: C1x) { which = "C1, C1x, C1x" }
func foo(_: C1x, _: C1, _: C1) { which = "C1x, C1, C1" }
func foo(_: C1x, _: C1, _: C1x) { which = "C1x, C1, C1x" }
func foo(_: C1x, _: C1x, _: C1) { which = "C1x, C1x, C1" }
func foo(_: C1x, _: C1x, _: C1x) { which = "C1x, C1x, C1x" }
}
Base().foo(C1(), C1(), C1()); expectEqual("C1, C1, C1", which)
Base().foo(C1(), C1(), C1x()); expectEqual("C1, C1, C1x", which)
Base().foo(C1(), C1x(), C1()); expectEqual("C1, C1x, C1", which)
Base().foo(C1(), C1x(), C1x()); expectEqual("C1, C1x, C1x", which)
Base().foo(C1x(), C1(), C1()); expectEqual("C1x, C1, C1", which)
Base().foo(C1x(), C1(), C1x()); expectEqual("C1x, C1, C1x", which)
Base().foo(C1x(), C1x(), C1()); expectEqual("C1x, C1x, C1", which)
Base().foo(C1x(), C1x(), C1x()); expectEqual("C1x, C1x, C1x", which)
}
Overloads.test("implicit conversion to superclass") {
class Base {
func foo(_: C1) { which = "foo(C1)" }
}
Base().foo(C1()); expectEqual("foo(C1)", which)
Base().foo(C1x()); expectEqual("foo(C1)", which)
Base().foo(C1xx()); expectEqual("foo(C1)", which)
}
Overloads.test("implicit conversion to protocol existential") {
class Base {
func foo(_: P1) { which = "foo(P1)" }
}
Base().foo(P1ImplS1()); expectEqual("foo(P1)", which)
Base().foo(P1xImplS1()); expectEqual("foo(P1)", which)
}
Overloads.test("implicit conversion to a superclass is better than conversion to an optional") {
class Base {
func foo(_: C1) { which = "foo(C1)" }
func foo(_: C1x?) { which = "foo(C1x?)" }
}
Base().foo(C1()); expectEqual("foo(C1)", which)
Base().foo(C1x()); expectEqual("foo(C1)", which)
Base().foo(C1xx()); expectEqual("foo(C1)", which)
Base().foo(C1x() as C1x?); expectEqual("foo(C1x?)", which)
Base().foo(C1xx() as C1xx?); expectEqual("foo(C1x?)", which)
}
Overloads.test("implicit conversion to a protocol existential is better than conversion to an optional") {
class Base {
func foo(_: P1) { which = "foo(P1)" }
func foo(_: P1x?) { which = "foo(P1x?)" }
}
Base().foo(P1ImplS1()); expectEqual("foo(P1)", which)
Base().foo(P1xImplS1()); expectEqual("foo(P1)", which)
Base().foo(P1xImplS1() as P1x?); expectEqual("foo(P1x?)", which)
}
Overloads.test("implicit conversion to a superclass is ambiguous with conversion to a protocol existential") {
class Base {
func foo(_: C1) { which = "foo(C1)" } // expected-note {{found this candidate}}
func foo(_: P1) { which = "foo(P1)" } // expected-note {{found this candidate}}
}
Base().foo(C1()); expectEqual("foo(C1)", which)
Base().foo(P1ImplS1()); expectEqual("foo(P1)", which)
#if ERRORS
Base().foo(P1ImplC1x())
// expected-error @-1 {{ambiguous use of 'foo'}}
#endif
}
Overloads.test("generic methods are worse than non-generic") {
class Base {
func foo(_: C1) { which = "foo(C1)" }
func foo(_: Any) { which = "foo(Any)" }
func foo<T>(_: T) { which = "foo(T)" }
// It is not possible to call foo<T>(T). foo(Any) always wins.
func bar(_: C1) { which = "bar(C1)" }
func bar<T>(_: T) { which = "bar(T)" }
}
Base().foo(C1()); expectEqual("foo(C1)", which)
Base().foo(Token1()); expectEqual("foo(Any)", which)
Base().bar(C1()); expectEqual("bar(C1)", which)
Base().bar(Token1()); expectEqual("bar(T)", which)
}
runAllTests()
| apache-2.0 | f2f6d73cff9eb24f4de58d26c6ce0451 | 27.908284 | 110 | 0.605977 | 2.950181 | false | true | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/Models/BlockEditorSettings+GutenbergEditorSettings.swift | 1 | 3749 | import Foundation
import WordPressKit
import Gutenberg
extension BlockEditorSettings: GutenbergEditorSettings {
public var colors: [[String: String]]? {
elementsByType(.color)
}
public var gradients: [[String: String]]? {
elementsByType(.gradient)
}
public var galleryWithImageBlocks: Bool {
return experimentalFeature(.galleryWithImageBlocks)
}
private func elementsByType(_ type: BlockEditorSettingElementTypes) -> [[String: String]]? {
return elements?.sorted(by: { (lhs, rhs) -> Bool in
return lhs.order >= rhs.order
}).compactMap({ (element) -> [String: String]? in
guard element.type == type.rawValue else { return nil }
return element.rawRepresentation
})
}
private func experimentalFeature(_ feature: BlockEditorExperimentalFeatureKeys) -> Bool {
guard let experimentalFeature = elements?.first(where: { (element) -> Bool in
guard element.type == BlockEditorSettingElementTypes.experimentalFeatures.rawValue else { return false }
return element.slug == feature.rawValue
}) else { return false }
return Bool(experimentalFeature.value) ?? false
}
}
extension BlockEditorSettings {
convenience init?(editorTheme: RemoteEditorTheme, context: NSManagedObjectContext) {
self.init(context: context)
self.isFSETheme = false
self.lastUpdated = Date()
self.checksum = editorTheme.checksum
var parsedElements = Set<BlockEditorSettingElement>()
if let themeSupport = editorTheme.themeSupport {
themeSupport.colors?.enumerated().forEach({ (index, color) in
parsedElements.insert(BlockEditorSettingElement(fromRawRepresentation: color, type: .color, order: index, context: context))
})
themeSupport.gradients?.enumerated().forEach({ (index, gradient) in
parsedElements.insert(BlockEditorSettingElement(fromRawRepresentation: gradient, type: .gradient, order: index, context: context))
})
}
self.elements = parsedElements
}
convenience init?(remoteSettings: RemoteBlockEditorSettings, context: NSManagedObjectContext) {
self.init(context: context)
self.isFSETheme = remoteSettings.isFSETheme
self.lastUpdated = Date()
self.checksum = remoteSettings.checksum
self.rawStyles = remoteSettings.rawStyles
self.rawFeatures = remoteSettings.rawFeatures
var parsedElements = Set<BlockEditorSettingElement>()
remoteSettings.colors?.enumerated().forEach({ (index, color) in
parsedElements.insert(BlockEditorSettingElement(fromRawRepresentation: color, type: .color, order: index, context: context))
})
remoteSettings.gradients?.enumerated().forEach({ (index, gradient) in
parsedElements.insert(BlockEditorSettingElement(fromRawRepresentation: gradient, type: .gradient, order: index, context: context))
})
// Experimental Features
let galleryKey = BlockEditorExperimentalFeatureKeys.galleryWithImageBlocks.rawValue
let galleryRefactor = BlockEditorSettingElement(name: galleryKey,
value: "\(remoteSettings.galleryWithImageBlocks)",
slug: galleryKey,
type: .experimentalFeatures,
order: 0,
context: context)
parsedElements.insert(galleryRefactor)
self.elements = parsedElements
}
}
| gpl-2.0 | 7a209f3016e512e749a0f67f984f69c3 | 41.602273 | 146 | 0.635369 | 5.363376 | false | false | false | false |
heyogrady/SpaceEvaders | SpaceEvaders/Iapp.swift | 1 | 1845 | import SpriteKit
class Iapp {
var iapp: SKSpriteNode
init(size: CGSize) {
let x = size.width / 2
let y = size.height / 2
iapp = SKSpriteNode(color: UIColor.blackColor(), size: size)
iapp.position = CGPoint(x: x, y: y)
iapp.zPosition = 20
iapp.name = "iapp"
let bt = Button(x: -x / 3, y: -y / 3, width: x / 3, height: y / 3, label: "Back", id: "back").addTo(iapp)
let purchase = Button(x: x / 4, y: -y / 3, width: x * 2 / 3, height: y / 3, label: "Purchase", id: "purchase").addTo(iapp)
addLabels(x, y: y)
let restore = addText("Restore Purchases", size: 60, x: -25, y: -y / 3 - 250)
restore.name = "restore"
}
func addLabels(x: CGFloat, y: CGFloat) {
Alien(x: -750, y: 70, startAtTop: true).addTo(iapp)
let credit = Sprite(named: "credits", x: -750, y: -25).addTo(iapp)
credit.setScale(0.1)
//Rocket(x: -550, y: 200).addTo(iapp)
addText("Purchase Premium!", size: 130, x: 0, y: 400)
addText("Support the developer :)", size: 80, x: -25, y: 300)
addText("Premium unlocks two neat features and is the only purchase in this app", size: 50, x: 0, y: 200)
addText("Switch between follow(default) and inertia modes", size: 60, x: 0, y: 50)
addText("Add indicators to see where the aliens will spawn next", size: 60, x: 60, y: -50)
}
func addText(text: String, size: CGFloat, x: CGFloat, y: CGFloat) -> SKLabelNode {
let label = SKLabelNode(text: text)
label.fontSize = size
label.position = CGPointMake(x, y)
label.fontName = "timeburner"
label.name = "iapp"
iapp.addChild(label)
return label
}
func addTo(parentNode: SKScene) -> Iapp {
parentNode.addChild(iapp)
return self
}
} | mit | 78bde21c962a160e524225cb3a78a044 | 39.130435 | 130 | 0.57561 | 3.265487 | false | false | false | false |
byu-oit/ios-byuSuite | byuSuite/Apps/DiningAccount/model/DiningAccount.swift | 2 | 1466 | //
// DiningAccount.swift
// byuSuite
//
// Created by Erik Brady on 4/17/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import Foundation
class DiningAccount: NSObject {
var hasMealPlan: Bool?
var averageSpentPerDay: Double?
var balance: Double?
var barPercent: Double?
var currentZone: String?
var idealSpentSoFar: Double?
var planStartTotal: Double?
var recommendedSpendingPerDayFuture: Double?
var redToYellowZone: Double?
var yellowToGreenZone: Double?
var greenToYellowZone: Double?
var yellowToRedZone: Double?
init(dictionary: [String: Any]) {
hasMealPlan = dictionary["hasMealPlan"] as? Bool
averageSpentPerDay = dictionary["averageSpentPerDay"] as? Double
balance = dictionary["balance"] as? Double
barPercent = dictionary["barPercent"] as? Double
currentZone = dictionary["currentZone"] as? String
idealSpentSoFar = dictionary["idealSpentSoFar"] as? Double
planStartTotal = dictionary["planStartTotal"] as? Double
recommendedSpendingPerDayFuture = dictionary["recommendedSpendingPerDayFuture"] as? Double
redToYellowZone = dictionary["leftRedZoneEnd"] as? Double
yellowToGreenZone = dictionary["leftYellowZoneEnd"] as? Double
greenToYellowZone = dictionary["greenZoneEnd"] as? Double
yellowToRedZone = dictionary["rightYellowZoneEnd"] as? Double
}
}
| apache-2.0 | e4343960e046cda385793ea451ac2d66 | 34.731707 | 98 | 0.701706 | 4.296188 | false | false | false | false |
OrangeJam/iSchool | iSchool/FoodWebViewController.swift | 1 | 1660 | //
// FoodWebView.swift
// iSchool
//
// Created by Kári Helgason on 03/11/14.
// Copyright (c) 2014 OrangeJam. All rights reserved.
//
import UIKit
import WebKit
class FoodWebViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
// Don't put stuff under navigation bar
edgesForExtendedLayout = UIRectEdge.None
webView = WKWebView()
webView!.navigationDelegate = self
navigationItem.title = "Málið"
let navbarHeight = self.navigationController != nil ? self.navigationController!.navigationBar.frame.height : 0
let tabbarHeight = self.tabBarController != nil ? self.tabBarController!.tabBar.frame.height : 0
webView?.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height - tabbarHeight - navbarHeight)
self.view.addSubview(webView!)
let url = NSURL(string: "http://malid.ru.is")
let req = NSMutableURLRequest(URL: url!)
self.webView!.loadRequest(req)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func prettifyPage() {
if let jsPath = NSBundle.mainBundle().pathForResource("foodPrettifier", ofType: "js") {
let js = NSString(contentsOfFile: jsPath, encoding: NSUTF8StringEncoding, error: nil)
webView!.evaluateJavaScript(js!, nil)
}
}
// MARK: WKNavigation delegate
func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
prettifyPage()
}
}
| bsd-3-clause | 62db1d369a26c362764755cc57c72779 | 31.490196 | 119 | 0.653591 | 4.654494 | false | false | false | false |
jdbateman/Lendivine | Lendivine/UIView+Extension.swift | 1 | 1175 | //
// UIView+Extension.swift
// Lendivine
//
// Created by john bateman on 4/28/16.
// Copyright © 2016 John Bateman. All rights reserved.
//
// This extension allows any UIView derived class to make a single call to do a fade in or fade out animation.
// Acknowledgement: Andrew Bancroft
import Foundation
import UIKit
extension UIView {
func fadeOutAnimation(duration: NSTimeInterval = 1.0, delay: NSTimeInterval = 0.0, completion: ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.alpha = 0.0
self.center = CGPoint(x: self.center.x, y: self.center.y)
}, completion: completion)
}
func fadeInAnimation(duration: NSTimeInterval = 1.0, delay: NSTimeInterval = 0.0, completion: ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.alpha = 1.0
self.center = CGPoint(x: self.center.x - 600, y: self.center.y)
}, completion: completion)
}
} | mit | be2cafa254bb18c378dcf29b8379c138 | 39.517241 | 150 | 0.672061 | 3.966216 | false | false | false | false |
Pyroh/CoreGeometry | Sources/CoreGeometry/Extensions/CGRectExtension.swift | 1 | 31018 | //
// CGRectExtension.swift
//
// CoreGeometry
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// 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 CoreGraphics
import simd
// MARK: Initializers
public extension CGRect {
/// Creates a rectangle with the specified size.
@inlinable init(size: CGSize) {
self.init(origin: .zero, size: size)
}
/// Creates a rectangle with the specified center and size.
@inlinable init(center: CGPoint, size: CGSize) {
let origin = CGPoint(simd2: center.simd2 - (size.simd2 / 2))
self.init(origin: origin, size: size)
}
@available(*, deprecated)
@inlinable init(ratio: Ratio, maxSize: CGFloat) {
let width: CGFloat, height: CGFloat
switch ratio.orientation {
case .landscape:
width = maxSize
height = maxSize / ratio.factor
case .portrait:
width = maxSize * ratio.factor
height = maxSize
case .square:
width = maxSize
height = maxSize
}
self.init(size: .init(width: width, height: height))
}
@available(*, deprecated)
@inlinable init(center: CGPoint, ratio: Ratio, maxSize: CGFloat) {
let width: CGFloat, height: CGFloat
switch ratio.orientation {
case .landscape:
width = maxSize
height = maxSize / ratio.factor
case .portrait:
width = maxSize * ratio.factor
height = maxSize
case .square:
width = maxSize
height = maxSize
}
self.init(center: center, size: .init(width: width, height: height))
}
@inlinable init(square edge: CGFloat) {
self.init(origin: .zero, size: .init(square: edge))
}
@inlinable init<T: BinaryInteger>(square edge: T) {
self.init(origin: .zero, size: .init(square: edge))
}
@inlinable init<T: BinaryFloatingPoint>(square edge: T) {
self.init(origin: .zero, size: .init(square: edge))
}
@inlinable init(origin: CGPoint, square edge: CGFloat) {
self.init(origin: origin, size: .init(square: edge))
}
@inlinable init<T: BinaryInteger>(origin: CGPoint, square edge: T) {
self.init(origin: origin, size: .init(square: edge))
}
@inlinable init<T: BinaryFloatingPoint>(origin: CGPoint, square edge: T) {
self.init(origin: origin, size: .init(square: edge))
}
@inlinable init(center: CGPoint, square edge: CGFloat) {
self.init(center: center, size: .init(square: edge))
}
@inlinable init<T: BinaryInteger>(center: CGPoint, square edge: T) {
self.init(center: center, size: .init(square: edge))
}
@inlinable init<T: BinaryFloatingPoint>(center: CGPoint, square edge: T) {
self.init(center: center, size: .init(square: edge))
}
@inlinable init<T: BinaryInteger>(_ x: T, _ y: T, _ width: T, _ height: T) {
self.init(x: CGFloat(x), y: CGFloat(y), width: CGFloat(width), height: CGFloat(height))
}
@inlinable init<T: BinaryFloatingPoint>(_ x: T, _ y: T, _ width: T, _ height: T) {
self.init(x: CGFloat(x), y: CGFloat(y), width: CGFloat(width), height: CGFloat(height))
}
@inlinable init<T: BinaryInteger>(_ width: T, _ height: T) {
self.init(size: .init(width, height))
}
@inlinable init<T: BinaryFloatingPoint>(_ width: T, _ height: T) {
self.init(size: .init(width, height))
}
/// Creates the greatest absolute rectangle possible with `p1` and `p2` as opposite corners.
/// - Parameters:
/// - p1: A corner of the rectangle.
/// - p2: The opposite corner.
@inlinable init(p1: CGPoint, p2: CGPoint) {
let x = min(p1.x, p2.x)
let y = min(p1.y, p2.y)
let width = max(p1.x, p2.x) - x
let height = max(p1.y, p2.y) - y
self = .init(x, y, width, height)
}
@inlinable init(origin p1: CGPoint, opposite p2: CGPoint) {
let size = CGSize(simd2: p2.simd2 - p1.simd2)
self.init(origin: p1, size: size)
}
}
public extension CGRect {
@inlinable init(aspectRatio: CGFloat, maxEdge: CGFloat) {
self.init(origin: .zero, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge))
}
@inlinable init<T: BinaryInteger>(aspectRatio: CGFloat, maxEdge: T) {
self.init(origin: .zero, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init<T: BinaryFloatingPoint>(aspectRatio: CGFloat, maxEdge: T) {
self.init(origin: .zero, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryInteger>(aspectRatio: A, maxEdge: E) {
self.init(origin: .zero, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryFloatingPoint>(aspectRatio: A, maxEdge: E) {
self.init(origin: .zero, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init(origin: CGPoint, aspectRatio: CGFloat, maxEdge: CGFloat) {
self.init(origin: origin, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge))
}
@inlinable init<T: BinaryInteger>(origin: CGPoint, aspectRatio: CGFloat, maxEdge: T) {
self.init(origin: origin, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init<T: BinaryFloatingPoint>(origin: CGPoint, aspectRatio: CGFloat, maxEdge: T) {
self.init(origin: origin, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryInteger>(origin: CGPoint, aspectRatio: A, maxEdge: E) {
self.init(origin: origin, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryFloatingPoint>(origin: CGPoint, aspectRatio: A, maxEdge: E) {
self.init(origin: origin, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init(center: CGPoint, aspectRatio: CGFloat, maxEdge: CGFloat) {
let size = CGSize(aspectRatio: aspectRatio, maxEdge: maxEdge)
let origin = CGPoint(simd2: center.simd2 - (size.simd2 / 2))
self.init(origin: origin, size: size)
}
@inlinable init<T: BinaryInteger>(center: CGPoint, aspectRatio: CGFloat, maxEdge: T) {
self.init(center: center, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init<T: BinaryFloatingPoint>(center: CGPoint, aspectRatio: CGFloat, maxEdge: T) {
self.init(center: center, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryInteger>(center: CGPoint, aspectRatio: A, maxEdge: E) {
self.init(center: center, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryFloatingPoint>(center: CGPoint, aspectRatio: A, maxEdge: E) {
self.init(center: center, size: .init(aspectRatio: aspectRatio, maxEdge: maxEdge.cgFloat))
}
}
public extension CGRect {
@inlinable init(aspectRatio: CGFloat, minEdge: CGFloat) {
self.init(origin: .zero, size: .init(aspectRatio: aspectRatio, minEdge: minEdge))
}
@inlinable init<T: BinaryInteger>(aspectRatio: CGFloat, minEdge: T) {
self.init(origin: .zero, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init<T: BinaryFloatingPoint>(aspectRatio: CGFloat, minEdge: T) {
self.init(origin: .zero, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryInteger>(aspectRatio: A, minEdge: E) {
self.init(origin: .zero, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryFloatingPoint>(aspectRatio: A, minEdge: E) {
self.init(origin: .zero, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init(origin: CGPoint, aspectRatio: CGFloat, minEdge: CGFloat) {
self.init(origin: origin, size: .init(aspectRatio: aspectRatio, minEdge: minEdge))
}
@inlinable init<T: BinaryInteger>(origin: CGPoint, aspectRatio: CGFloat, minEdge: T) {
self.init(origin: origin, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init<T: BinaryFloatingPoint>(origin: CGPoint, aspectRatio: CGFloat, minEdge: T) {
self.init(origin: origin, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryInteger>(origin: CGPoint, aspectRatio: A, minEdge: E) {
self.init(origin: origin, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryFloatingPoint>(origin: CGPoint, aspectRatio: A, minEdge: E) {
self.init(origin: origin, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init(center: CGPoint, aspectRatio: CGFloat, minEdge: CGFloat) {
let size = CGSize(aspectRatio: aspectRatio, minEdge: minEdge)
let origin = CGPoint(simd2: center.simd2 - (size.simd2 / 2))
self.init(origin: origin, size: size)
}
@inlinable init<T: BinaryInteger>(center: CGPoint, aspectRatio: CGFloat, minEdge: T) {
self.init(center: center, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init<T: BinaryFloatingPoint>(center: CGPoint, aspectRatio: CGFloat, minEdge: T) {
self.init(center: center, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryInteger>(center: CGPoint, aspectRatio: A, minEdge: E) {
self.init(center: center, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
@inlinable init<A: BinaryFloatingPoint, E: BinaryFloatingPoint>(center: CGPoint, aspectRatio: A, minEdge: E) {
self.init(center: center, size: .init(aspectRatio: aspectRatio, minEdge: minEdge.cgFloat))
}
}
public extension CGRect {
/// The receiver's SIMD representation.
@inlinable var simd4: SIMD4<CGFloat.NativeType> {
get { .init(origin.x.native, origin.y.native, size.width.native, size.height.native) }
set { (origin.simd2, size.simd2) = (newValue.lowHalf, newValue.highHalf) }
}
@inlinable init(simd4: SIMD4<CGFloat.NativeType>) {
self.init(x: simd4.x, y: simd4.y, width: simd4.z, height: simd4.w)
}
}
// MARK: -
// MARK: Corners
public extension CGRect {
/// A point representing the rectangle's center.
@inlinable var center: CGPoint {
get { .init(x: midX, y: midY) }
set { origin.simd2 = newValue.simd2 - (size.simd2 / 2) }
}
@inlinable subscript(xBound: RectBoundary = .mid, yBound: RectBoundary = .mid) -> CGPoint {
get {
let x, y: CGFloat
switch xBound {
case .min: x = minX
case .mid: x = midX
case .max: x = maxX
}
switch yBound {
case .min: y = minY
case .mid: y = midY
case .max: y = maxY
}
return .init(x: x, y: y)
}
set {
origin.simd2 += newValue.simd2 - self[xBound, yBound].simd2
}
}
}
// MARK: -
// MARK: Geometry
public extension CGRect {
/// The biggest square rectangle that `self` can contain.
@inlinable var maxSquare: CGRect {
let maxEdge = max(self.width, self.height)
return CGRect(origin: .zero, size: .init(width: maxEdge, height: maxEdge))
}
/// The smallest square rectangle that can contain `self`.
@inlinable var minSquare: CGRect {
let minEdge = min(self.width, self.height)
return CGRect(origin: .zero, size: .init(width: minEdge, height: minEdge))
}
/// The ratio of `self`.
@inlinable var ratio: CGFloat {
return width / height
}
/// The diagonal of `self`.
@inlinable var diagonal: CGFloat {
length(size.simd2).cgFloat
}
/// The orientation of `self`.
@inlinable var orientation: Orientation {
switch ratio {
case let x where x < 1.0: return .portrait
case let x where x > 1.0: return .landscape
default: return .square
}
}
/// The area of `self`.
@inlinable var area: CGFloat { size.area }
/// The width, halved.
@inlinable var halfWidth: CGFloat { size.halfWidth }
/// The height, halved.
@inlinable var halfHeight: CGFloat { size.halfHeight }
}
// MARK: -
// MARK: Center
public extension CGRect {
/// Returns a copy of `self` centered relative to the given rectangle.
@inlinable func centered(in rect: CGRect) -> CGRect {
guard !isEmpty && !isInfinite else { return self }
return CGRect(center: rect.center, size: size)
}
/// Centers `self` relative to the given rect.
@inlinable mutating func center(in rect: CGRect) {
center = rect.center
}
/// Returns a copy of `self` centered to the given point.
@inlinable func centered(at point: CGPoint) -> CGRect {
.init(center: point, size: size)
}
/// Returns a copy of `self` centered at `(x,y)`.
@inlinable func centered<I: BinaryInteger>(atX x: I, y: I) -> CGRect {
.init(center: .init(x, y), size: size)
}
/// Returns a copy of `self` centered at `(x,y)`.
@inlinable func centered<F: BinaryFloatingPoint>(atX x: F, y: F) -> CGRect {
.init(center: .init(x, y), size: size)
}
/// Returns a copy of `self` centered at `(x,y)`.
@inlinable
func centered(atX x: CGFloat, y: CGFloat) -> CGRect {
.init(center: .init(x, y), size: size)
}
/// Centers `self` relative to the given point.
@inlinable mutating func center(at point: CGPoint) {
center = point
}
/// Centers `self` at `(x,y)`
@inlinable mutating func center<I: BinaryInteger>(atX x: I, y: I) {
center = .init(x, y)
}
/// Centers `self` at `(x,y)`
@inlinable mutating func center<F: BinaryFloatingPoint>(atX x: F, y: F) {
center = .init(x, y)
}
/// Centers `self` at `(x,y)`
@inlinable mutating func center(atX x: CGFloat, y: CGFloat) {
center = .init(x, y)
}
}
// MARK: -
// MARK: Align
public extension CGRect {
/// Return a copy of `self` aligned relative to the given rect following x and y axis contraints.
///
/// - Parameters:
/// - rect: The rect to align against.
/// - xAxis: The x axis' constraint.
/// - yAxis: The y axis' constraint.
/// - Returns: A properly aligned rect.
@inlinable func aligned(relativeTo rect: CGRect, xAxis: AxisAlignment, yAxis: AxisAlignment) -> CGRect {
var origin = origin
switch xAxis {
case .none: break
case .min: origin.x += rect.minX - minX
case .mid: origin.x += rect.midX - midX
case .max: origin.x += rect.maxX - maxX
}
switch yAxis {
case .none: break
case .min: origin.y += rect.minY - minY
case .mid: origin.y += rect.midY - midY
case .max: origin.y += rect.maxY - maxY
}
return .init(origin: origin, size: size)
}
/// Aligns `self` relative to the given rect following x and y axis contraints.
///
/// - Parameters:
/// - rect: The rect to align against.
/// - xAxis: The x axis' constraint.
/// - yAxis: The y axis' constraint.
@inlinable mutating func align(relativeTo rect: CGRect, xAxis: AxisAlignment, yAxis: AxisAlignment) {
switch xAxis {
case .none: break
case .min: origin.x += rect.minX - minX
case .mid: origin.x += rect.midX - midX
case .max: origin.x += rect.maxX - maxX
}
switch yAxis {
case .none: break
case .min: origin.y += rect.minY - minY
case .mid: origin.y += rect.midY - midY
case .max: origin.y += rect.maxY - maxY
}
}
/// Returns a copy of `self` with `origin` equals to `CGPointZero`.
@inlinable func reseted() -> CGRect {
CGRect(x: 0, y: 0, width: width, height: height)
}
/// Makes `self`'s origin equal to `CGPointZero`.
@inlinable mutating func reset() {
origin = .zero
}
}
// MARK: -
// MARK: Transform
public extension CGRect {
/// Returns a copy of `self` translated by the given vector.
@inlinable func translated(by vector: CGVector) -> CGRect {
.init(origin: .init(simd2: origin.simd2 + vector.simd2), size: size)
}
/// Returns a copy of `self` translated by the given vector.
@inlinable func translated(along vector: CGVector) -> CGRect {
.init(origin: .init(simd2: origin.simd2 + vector.simd2), size: size)
}
/// Returns a copy of `self` translated by `(tx,ty)`.
@inlinable func translated<I: BinaryInteger>(byTx tx: I, ty: I) -> CGRect {
.init(origin: .init(simd2: origin.simd2 + .init(tx.native, ty.native)), size: size)
}
/// Returns a copy of `self` translated by `(tx,ty)`.
@inlinable func translated<F: BinaryFloatingPoint>(byTx tx: F, ty: F) -> CGRect {
.init(origin: .init(simd2: origin.simd2 + .init(tx.native, ty.native)), size: size)
}
/// Returns a copy of `self` translated by `(tx,ty)`.
@inlinable func translated(byTx tx: CGFloat.NativeType, ty: CGFloat.NativeType) -> CGRect {
.init(origin: .init(simd2: origin.simd2 + .init(tx, ty)), size: size)
}
/// Translate `self` along the given vector.
@inlinable mutating func translate(along vector: CGVector) {
origin.simd2 += vector.simd2
}
/// Translate `self` by `(tx,ty)`.
@inlinable mutating func translate<I: BinaryInteger>(tx: I, ty: I) {
origin.simd2 += .init(tx.native, ty.native)
}
/// Translate `self` by `(tx,ty)`.
@inlinable mutating func translate<F: BinaryFloatingPoint>(tx: F, ty: F) {
origin.simd2 += .init(tx.native, ty.native)
}
/// Translate `self` by `(tx,ty)`.
@inlinable mutating func translate(tx: CGFloat.NativeType, ty: CGFloat.NativeType) {
origin.simd2 += .init(tx, ty)
}
/// Returns a copy of `self` rotated around the given point by the given angle.
///
/// - note: Rotates clockwise on iOS and counter-clockwise on macOS.
/// - Parameters:
/// - center: The point the rotation will be applied around.
/// - angle: The rotation's angle in radians.
@inlinable func rotated(relativeTo center: CGPoint, by angle: CGFloat) -> CGRect {
var transform = CGAffineTransform(translationX: center.x, y: center.y)
transform = transform.rotated(by: angle)
transform = transform.translatedBy(x: -center.x, y: -center.y)
return applying(transform)
}
/// Rotates `self` around the given point by the given angle.
///
/// - note: Rotates clockwise on iOS and counter-clockwise on macOS.
/// - Parameters:
/// - center: The point the rotation will be applied around.
/// - angle: The rotation's angle in radians.
@inlinable mutating func rotate(relativeTo center: CGPoint, by angle: CGFloat) {
self = self.rotated(relativeTo: center, by: angle)
}
}
// MARK: -
// MARK: Inset
public extension CGRect {
/// Insets `self` in the given edge directions by the given amount.
///
/// - Parameters:
/// - edges: The edges to inset from.
/// - amount: The inset amount.
@inlinable mutating func inset(_ edges: RectangleEdge, by amount: CGFloat) {
guard !edges.isEmpty else { return }
if edges.contains(.minXEdge) {
origin.x += amount
size.width -= amount
}
if edges.contains(.maxXEdge) {
size.width -= amount
}
if edges.contains(.minYEdge) {
origin.y += amount
size.height -= amount
}
if edges.contains(.maxYEdge) {
size.height -= amount
}
}
/// Insets `self` in the given edge directions by the given amount.
/// - Parameter size: The inset amount.
@inlinable mutating func inset(by size: CGSize) {
guard size != .zero else { return }
self.origin.simd2 += size.simd2
self.size.simd2 -= size.simd2 * 2
}
/// Return a copy of `self` inset in the given edge directions by the given amount.
///
/// - Parameters:
/// - edges: The edges to inset from.
/// - amount: The inset amount.
@inlinable func insetting(_ edges: RectangleEdge, by amount: CGFloat) -> CGRect {
guard !edges.isEmpty else { return self }
var origin = self.origin
var size = self.size
if edges.contains(.minXEdge) {
origin.x += amount
size.width -= amount
}
if edges.contains(.maxXEdge) {
size.width -= amount
}
if edges.contains(.minYEdge) {
origin.y += amount
size.height -= amount
}
if edges.contains(.maxYEdge) {
size.height -= amount
}
return .init(origin: origin, size: size)
}
@inlinable func insetting(by size: CGSize) -> CGRect {
guard size != .zero else { return self }
return withMutable(self) {
$0.origin.simd2 += size.simd2
$0.size.simd2 -= size.simd2 * 2
}
}
}
// MARK: -
// MARK: Functional modifiers
public extension CGRect {
/// The rectangle's origin's x position.
@inlinable var x: CGFloat { origin.x }
/// The rectangle's origin's y position.
@inlinable var y: CGFloat { origin.y }
/// Returns a copy of `self` with the given origin.
/// - Parameter origin: The new origin.
@inlinable func with(origin: CGPoint) -> CGRect {
.init(origin: origin, size: size)
}
/// Returns a copy of `self` with the given size.
/// - Parameter origin: The new size.
@inlinable func with(size: CGSize) -> CGRect {
.init(origin: origin, size: size)
}
/// Returns a copy of `self` with the given x position.
/// - Parameter origin: The new x position.
@inlinable func with(x: CGFloat) -> CGRect {
.init(origin: .init(x, y), size: size)
}
/// Returns a copy of `self` with the given x position.
/// - Parameter origin: The new x position.
@inlinable func with<I: BinaryInteger>(x: I) -> CGRect {
.init(origin: .init(x.cgFloat, y), size: size)
}
/// Returns a copy of `self` with the given x position.
/// - Parameter origin: The new x position.
@inlinable func with<F: BinaryFloatingPoint>(x: F) -> CGRect {
.init(origin: .init(x.cgFloat, y), size: size)
}
/// Returns a copy of `self` with the given y position.
/// - Parameter origin: The new y position.
@inlinable func with(y: CGFloat) -> CGRect {
.init(origin: .init(x, y), size: size)
}
/// Returns a copy of `self` with the given y position.
/// - Parameter origin: The new y position.
@inlinable func with<I: BinaryInteger>(y: I) -> CGRect {
.init(origin: .init(x, y.cgFloat), size: size)
}
/// Returns a copy of `self` with the given y position.
/// - Parameter origin: The new y position.
@inlinable func with<F: BinaryFloatingPoint>(y: F) -> CGRect {
.init(origin: .init(x, y.cgFloat), size: size)
}
/// Returns a copy of `self` with the given width.
/// - Parameter origin: The new width.
@inlinable func with(width: CGFloat) -> CGRect {
.init(origin: origin, size: .init(width, height))
}
/// Returns a copy of `self` with the given width.
/// - Parameter origin: The new width.
@inlinable func with<I: BinaryInteger>(width: I) -> CGRect {
.init(origin: origin, size: .init(width.cgFloat, height))
}
/// Returns a copy of `self` with the given width.
/// - Parameter origin: The new width.
@inlinable func with<F: BinaryFloatingPoint>(width: F) -> CGRect {
.init(origin: origin, size: .init(width.cgFloat, height))
}
/// Returns a copy of `self` with the given height.
/// - Parameter origin: The new height.
@inlinable func with(height: CGFloat) -> CGRect {
.init(origin: origin, size: .init(width, height))
}
/// Returns a copy of `self` with the given height.
/// - Parameter origin: The new height.
@inlinable func with<I: BinaryInteger>(height: I) -> CGRect {
.init(origin: origin, size: .init(width, height.cgFloat))
}
/// Returns a copy of `self` with the given height.
/// - Parameter origin: The new height.
@inlinable func with<F: BinaryFloatingPoint>(height: F) -> CGRect {
.init(origin: origin, size: .init(width, height.cgFloat))
}
}
public extension CGRect {
@available(*, deprecated, renamed: "transformingOrigin")
@inlinable func transformOrigin(_ transform: (CGPoint) throws -> CGPoint) rethrows -> CGRect {
with(origin: try transform(origin))
}
@available(*, deprecated, renamed: "transformingX")
@inlinable func transformX(_ transform: (CGFloat) throws -> CGFloat) rethrows -> CGRect {
with(x: try transform(x))
}
@available(*, deprecated, renamed: "transformingY")
@inlinable func transformY(_ transform: (CGFloat) throws -> CGFloat) rethrows -> CGRect {
with(y: try transform(y))
}
@available(*, deprecated, renamed: "transformingSize")
@inlinable func transformSize(_ transform: (CGSize) throws -> CGSize) rethrows -> CGRect {
with(size: try transform(size))
}
@available(*, deprecated, renamed: "transformingWidth")
@inlinable func transformWidth(_ transform: (CGFloat) throws -> CGFloat) rethrows -> CGRect {
with(width: try transform(width))
}
@available(*, deprecated, renamed: "transformingHeight")
@inlinable func transformHeight(_ transform: (CGFloat) throws -> CGFloat) rethrows -> CGRect {
with(height: try transform(height))
}
@inlinable func transformingOrigin(_ transform: (CGPoint) throws -> CGPoint) rethrows -> CGRect {
with(origin: try transform(origin))
}
@inlinable func transformingX(_ transform: (CGFloat) throws -> CGFloat) rethrows -> CGRect {
with(x: try transform(x))
}
@inlinable func transformingY(_ transform: (CGFloat) throws -> CGFloat) rethrows -> CGRect {
with(y: try transform(y))
}
@inlinable func transformingSize(_ transform: (CGSize) throws -> CGSize) rethrows -> CGRect {
with(size: try transform(size))
}
@inlinable func transformingWidth(_ transform: (CGFloat) throws -> CGFloat) rethrows -> CGRect {
with(width: try transform(width))
}
@inlinable func transformingHeight(_ transform: (CGFloat) throws -> CGFloat) rethrows -> CGRect {
with(height: try transform(height))
}
}
public extension CGRect {
@inlinable func map<T>(_ transform: (CGRect) throws -> T) rethrows -> T {
try transform(self)
}
@inlinable func transformed(using transform: (inout CGRect) throws -> ()) rethrows -> CGRect {
var resultRect = self
try transform(&resultRect)
return resultRect
}
}
public extension CGRect {
@inlinable static func <(_ lhs: CGPoint, _ rhs: CGRect) -> (x: Bool, y: Bool) {
let lhs2 = lhs.simd2
let rhs2 = rhs.origin.simd2
return (lhs2.x < rhs2.x, lhs2.y < rhs2.y)
}
@inlinable static func <=(_ lhs: CGPoint, _ rhs: CGRect) -> (x: Bool, y: Bool) {
let lhs2 = lhs.simd2
let rhs2 = rhs.origin.simd2
return (lhs2.x <= rhs2.x, lhs2.y <= rhs2.y)
}
@inlinable static func >(_ lhs: CGPoint, _ rhs: CGRect) -> (x: Bool, y: Bool) {
let lhs2 = lhs.simd2
let rhs2 = rhs.origin.simd2 + rhs.size.simd2
return (lhs2.x > rhs2.x, lhs2.y > rhs2.y)
}
@inlinable static func >=(_ lhs: CGPoint, _ rhs: CGRect) -> (x: Bool, y: Bool) {
let lhs2 = lhs.simd2
let rhs2 = rhs.origin.simd2 + rhs.size.simd2
return (lhs2.x >= rhs2.x, lhs2.y >= rhs2.y)
}
}
public extension CGRect {
@inlinable var integralWidth: Int { size.integralWidth }
@inlinable var integralHeight: Int { size.integralHeight }
@inlinable func integral(_ rule: FloatingPointRoundingRule) -> Self {
.init(simd4: simd4.rounded(rule))
}
}
public extension CGRect {
@inlinable static func *(lhs: Self, rhs: SIMD2<CGFloat.NativeType>) -> Self {
.init(simd4: .init(lowHalf: lhs.origin.simd2, highHalf: lhs.size.simd2 * rhs))
}
@inlinable static func *=(lhs: inout Self, rhs: SIMD2<CGFloat.NativeType>) {
lhs = lhs * rhs
}
@inlinable static func /(lhs: Self, rhs: SIMD2<CGFloat.NativeType>) -> Self {
.init(simd4: .init(lowHalf: lhs.origin.simd2, highHalf: lhs.size.simd2 / rhs))
}
@inlinable static func /=(lhs: inout Self, rhs: SIMD2<CGFloat.NativeType>) {
lhs = lhs / rhs
}
}
| mit | 588b85125b1d66ed6d49e572c123b908 | 34.85896 | 114 | 0.609162 | 3.934796 | false | false | false | false |
ZhaoBingDong/CYPhotosLibrary | CYPhotoKit/View/CYPhotoLibrayGroupCell.swift | 1 | 1568 | //
// CYPhotoLibrayGroupCell.swift
// CYPhotosKit
//
// Created by 董招兵 on 2017/8/7.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import UIKit
class CYPhotoLibrayGroupCell: UITableViewCell {
lazy var photoImageView : UIImageView = {
let imageView = UIImageView(frame: CGRect(x: 10.0, y: 10.0, width: 60.0, height: 60.0))
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.scaleAspectFill
return imageView
}()
lazy var titleLabel : UILabel = {
let label = UILabel(frame: CGRect(x: 80, y: 29.0, width: 200.0, height: 21.5))
return label
}()
lazy var badgeValue : UIView = {
let view = UIView(frame: CGRect(x: 42, y: 3, width: 15, height: 15))
view.backgroundColor = BaseTintColor
view.layer.borderColor = UIColor.white.cgColor
view.layer.borderWidth = 2.0
view.layer.cornerRadius = 7.5
view.isHidden = true
view.layer.masksToBounds = true
return view
}()
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(photoImageView)
contentView.addSubview(titleLabel)
photoImageView.addSubview(badgeValue)
selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | c827529786af539a523cf01a99c50625 | 31.914894 | 95 | 0.61797 | 4.273481 | false | false | false | false |
zxpLearnios/MyProject | test_projectDemo1/childVC/pushByfirstVC.swift | 1 | 6736 | //
// pushByfirstVC.swift
// test_projectDemo1
//
// Created by Jingnan Zhang on 16/5/30.
// Copyright © 2016年 Jingnan Zhang. All rights reserved.
// >= 8.2 用KVC强制屏幕旋转才有效; 8.1 以下必须写最后的三个方法,但还是有问题的,即第一次点击屏幕时,不会响应,会提示“2016-08-22 15:09:04.845 test_projectDemo1[13617:948796] unexpected nil window in _UIApplicationHandleEventFromQueueEvent, _windowServerHitTestWindow: <UIWindow: 0x7fbefb597b70; frame = (0 0; 667 375); gestureRecognizers = <NSArray: 0x7fbefb598300>; layer = <UIWindowLayer: 0x7fbefb597db0>>”, 第二次才会响应。
import UIKit
import PullToRefreshKit
class pushByfirstVC: UIViewController {
fileprivate var direction = UIInterfaceOrientationMask.init(rawValue: 0)
@IBOutlet weak var tableView: UITableView!
var isShow = true
convenience init(){
self.init(nibName: "pushByfirstVC",bundle:nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "pushByFirstVC"
self.view.backgroundColor = UIColor.white // 不设置的话,滑动返回时会出现透明现象
// self.tableView.setUpHeaderRefresh {
//
// }
// self.tableView.beginHeaderRefreshing()
// 1.
// btn.addTarget(self, action: #selector(btnAction), forControlEvents: .TouchUpInside)
// 加通知
// kDevice.beginGeneratingDeviceOrientationNotifications()
// kNotificationCenter.addObserver(self, selector: #selector(orientationDidChange), name: UIDeviceOrientationDidChangeNotification, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if UIDevice.current.orientation == .portrait {
//强制横屏
kApplication.setStatusBarOrientation(.landscapeRight, animated: true)
if kSystemVersion >= 8.2 {
kDevice.setValue(UIDeviceOrientation.landscapeRight.rawValue, forKey: "orientation")
}
//iOS9 填坑方案
if kSystemVersion >= 9.0 {
// if self.mytext.isFirstResponder() {
// self.mytext.resignFirstResponder()
// let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
// dispatch_after(time, dispatch_get_main_queue()) {
// self.mytext.becomeFirstResponder()
// }
}
}else{
//强制竖屏
kApplication.setStatusBarHidden(false, with: .none)
kApplication.setStatusBarOrientation(.portrait, animated: true)
kDevice.setValue(UIDeviceOrientation.portrait.rawValue, forKey: "orientation")
}
}
@IBAction func back(_ btn: UIButton) {
btn.isSelected = !btn.isSelected
if btn.isSelected {
// rotateCurrentView(true)
}else{
// rotateCurrentView(false)
}
// 恢复竖屏
self.navigationController?.dismiss(animated: true) {
if UIDevice.current.orientation == .landscapeRight || UIDevice.current.orientation == .landscapeLeft{
//强制竖屏
kApplication.setStatusBarHidden(false, with: .none) // 主要是防止其他地方隐藏statusBar
kApplication.setStatusBarOrientation(.portrait, animated: true)
kDevice.setValue(UIDeviceOrientation.portrait.rawValue, forKey: "orientation")
}
}
}
// MARK: 旋转
// private func rotateCurrentView(isForLandscape:Bool) {
// let nav = self.navigationController as! MyCustomNav
// var width:CGFloat = 0.0
// var height:CGFloat = 0.0
//
// if isForLandscape {
// direction = .LandscapeRight
// width = kbounds.height
// height = kbounds.width
//
//// UIView.animateWithDuration(0.2, animations: {
//// self.view.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
//// nav.view.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
//// })
//
//// kwindow!.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2))
// kDevice.setValue(UIDeviceOrientation.LandscapeRight.rawValue, forKey: "orientation")
//
//// kApplication.setStatusBarOrientation(.LandscapeRight, animated: false)
// }else{
// direction = .Portrait
// width = kbounds.width
// height = kbounds.height
//// kwindow!.transform = CGAffineTransformIdentity
//// UIView.animateWithDuration(0.2, animations: {
//// self.view.transform = CGAffineTransformIdentity
//// nav.view.transform = CGAffineTransformIdentity
//// })
//
// kDevice.setValue(UIDeviceOrientation.Portrait.rawValue, forKey: "orientation")
//
//// kApplication.setStatusBarOrientation(.Portrait, animated: true)
// }
//// nav.view.bounds = CGRectMake(0, 0, width, height)
//
//// kwindow!.frame = CGRectMake(0, 0, width, height)
//// kwindow!.bounds = CGRectMake(0, 0, width, height)
// let point = CGPointMake(width/2, height/2)
//// kwindow?.center = point
//// kwindow!.bounds = CGRectMake(0, 0, width, height)
//
//// self.view.bounds = CGRectMake(0, 0, width, height)
// debugPrint("\(point), ")
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// -------------- private --------------- //
// 8.1 的话必须写一下三个, >=8.2 则无需写了,直接看viewDidAppear里的即可
override var shouldAutorotate : Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return [.landscapeLeft, .landscapeRight]
}
// 写的话,此句必须要, 但是 是直接显示横屏的(瞬间横屏的)
override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation {
return .landscapeRight
}
}
| mit | 2c689d43b0654df8cfae7923c87c8efb | 34.583333 | 370 | 0.565183 | 4.758544 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/DiffThanker.swift | 1 | 1711 | enum DiffThankerError: LocalizedError {
case thanksStatusNotSuccess
case thanksError(String)
var errorDescription: String? {
switch self {
case .thanksStatusNotSuccess:
return "Thanks did not succeed"
case .thanksError(let message):
return message
}
}
}
struct DiffThankerResult {
var recipient: String
init(recipient:String) {
self.recipient = recipient
}
}
class DiffThanker: Fetcher {
func thank(siteURL: URL, rev: Int, completion: @escaping ((Result<DiffThankerResult, Error>) -> Void)) {
let parameters = [
"action": "thank",
"rev": String(rev),
"source": "diff",
"errorsuselocal": "1",
"format": "json"
]
performTokenizedMediaWikiAPIPOST(to: siteURL, with: parameters) { (result, response, error) in
if let error = error {
completion(.failure(error))
return
}
if let error = result?["error"] as? [String: Any], let info = error["info"] as? String {
completion(.failure(DiffThankerError.thanksError(info)))
return
}
guard
let resultDict = result?["result"] as? [String: Any],
let successInt = resultDict["success"] as? Int,
successInt == 1,
let recipient = resultDict["recipient"] as? String
else {
completion(.failure(DiffThankerError.thanksStatusNotSuccess))
return
}
completion(.success(DiffThankerResult.init(recipient: recipient)))
}
}
}
| mit | 96117691d8db6f495ddb622327292835 | 31.903846 | 108 | 0.544711 | 4.902579 | false | false | false | false |
teechap/kitura-limiter | Sources/Limiter.swift | 1 | 4758 | import Foundation
import Kitura
import KituraNet
import SwiftRedis
import SwiftyJSON
public typealias By = (_ request: RouterRequest) -> String
public typealias NextFunc = () -> Void
public typealias WhiteList = (_ request: RouterRequest) -> Bool
private func now() -> Int { // ms since epoch
return Int(Date().timeIntervalSince1970 * 1000)
}
public func defaultOnRateLimited(request: RouterRequest, response: RouterResponse, next: @escaping NextFunc) throws {
response.status(HTTPStatusCode.tooManyRequests).send("Rate limit exceeded")
try response.end()
}
public func defaultByFunc(request: RouterRequest) -> String {
return request.remoteAddress
}
public func defaultWhitelist(request: RouterRequest) -> Bool {
return false
}
public func defaultOnRedisError(request: RouterRequest, response: RouterResponse, next: @escaping NextFunc) throws {
response.status(HTTPStatusCode.internalServerError).send("Internal server error")
try response.end()
}
public class Limiter: RouterMiddleware {
let by: By
let onRateLimited: RouterHandler
let expire: Int
let total: Int
let defaultLimitJSON: JSON
let redis: Redis
let ignoreErrors: Bool
let whitelist: WhiteList
let onRedisError: RouterHandler
let skipHeaders: Bool
// 150 req/hour default
public init(redis: Redis, by: @escaping By = defaultByFunc, total: Int = 150, expire: Int = 1000 * 60 * 60, onRateLimited: @escaping RouterHandler = defaultOnRateLimited, ignoreErrors: Bool = false, whitelist: @escaping WhiteList = defaultWhitelist, onRedisError: @escaping RouterHandler = defaultOnRedisError, skipHeaders: Bool = false) {
self.redis = redis
self.by = by
self.total = total
self.expire = expire
self.onRateLimited = onRateLimited
self.onRedisError = onRedisError
self.ignoreErrors = ignoreErrors
self.whitelist = whitelist
self.skipHeaders = skipHeaders
self.defaultLimitJSON = JSON([
"total": total,
"remaining": total,
"reset": now() + expire
])
}
public func handle(request: RouterRequest, response: RouterResponse, next: @escaping NextFunc) throws {
if whitelist(request) {
return next()
}
let key = "ratelimit:\(self.by(request))"
redis.get(key) { (string: RedisString?, redisError: NSError?) in
if let _ = redisError {
if ignoreErrors {
return next()
} else {
return try! onRedisError(request, response, next)
}
} else {
var json: JSON
if let string = string?.asData {
json = JSON(data: string)
} else {
// the key does not exist in redis, assign default json
json = defaultLimitJSON
}
let n = now()
if n > json["reset"].int! {
json["reset"] = JSON(n + expire)
json["remaining"] = JSON(total)
}
json["remaining"] = JSON(max((json["remaining"].int!) - 1, -1))
redis.set(key, value: json.rawString()!, expiresIn: Double(expire/1000)) { (result: Bool, redisError: NSError?) in
if let _ = redisError {
if ignoreErrors {
return next()
} else {
return try! onRedisError(request, response, next)
}
} else {
if !skipHeaders {
let lim = json["total"].int!
let rs = ceil((Double(json["reset"].int!) / 1000))
let rem = max(json["remaining"].int!, 0)
response.headers.append("X-RateLimit-Limit", value: "\(lim)")
response.headers.append("X-RateLimit-Reset", value: "\(rs)")
response.headers.append("X-RateLimit-Remaining", value: "\(rem)")
}
if json["remaining"].int! >= 0 {
return next()
} else {
if !skipHeaders {
let after = (json["reset"].int! - now()) / 1000
response.headers.append("Retry-After", value: "\(after)")
}
return try! onRateLimited(request, response, next)
}
}
}
}
}
}
}
| mit | a22edf7d9cba9a6be4d8deffcb49ba54 | 34.774436 | 343 | 0.533207 | 4.88501 | false | false | false | false |
pluralsight/PSOperations | PSOperations/iCloudContainer.swift | 1 | 3391 | #if !os(watchOS)
import CloudKit
import Foundation
public struct iCloudContainer: CapabilityType {
public static let name = "iCloudContainer"
private let container: CKContainer
private let permissions: CKContainer.ApplicationPermissions
public init(container: CKContainer, permissions: CKContainer.ApplicationPermissions = []) {
self.container = container
self.permissions = permissions
}
public func requestStatus(_ completion: @escaping (CapabilityStatus) -> Void) {
verifyAccountStatus(container, permission: permissions, shouldRequest: false, completion: completion)
}
public func authorize(_ completion: @escaping (CapabilityStatus) -> Void) {
verifyAccountStatus(container, permission: permissions, shouldRequest: true, completion: completion)
}
}
private func verifyAccountStatus(_ container: CKContainer, permission: CKContainer.ApplicationPermissions, shouldRequest: Bool, completion: @escaping (CapabilityStatus) -> Void) {
container.accountStatus { accountStatus, accountError in
func completeWithError() {
completion(.error(accountError ?? CKError(.notAuthenticated)))
}
switch accountStatus {
case .noAccount: completion(.notAvailable)
case .restricted: completion(.notAvailable)
case .available:
if permission != [] {
verifyPermission(container, permission: permission, shouldRequest: shouldRequest, completion: completion)
} else {
completion(.authorized)
}
case .couldNotDetermine:
completeWithError()
case .temporarilyUnavailable:
completeWithError()
@unknown default:
completeWithError()
}
}
}
private func verifyPermission(_ container: CKContainer, permission: CKContainer.ApplicationPermissions, shouldRequest: Bool, completion: @escaping (CapabilityStatus) -> Void) {
container.status(forApplicationPermission: permission) { permissionStatus, permissionError in
func completeWithError() {
completion(.error(permissionError ?? CKError(.permissionFailure)))
}
switch permissionStatus {
case .initialState:
if shouldRequest {
requestPermission(container, permission: permission, completion: completion)
} else {
completion(.notDetermined)
}
case .denied: completion(.denied)
case .granted: completion(.authorized)
case .couldNotComplete:
completeWithError()
@unknown default:
completeWithError()
}
}
}
private func requestPermission(_ container: CKContainer, permission: CKContainer.ApplicationPermissions, completion: @escaping (CapabilityStatus) -> Void) {
DispatchQueue.main.async {
container.requestApplicationPermission(permission) { requestStatus, requestError in
switch requestStatus {
case .initialState: completion(.notDetermined)
case .denied: completion(.denied)
case .granted: completion(.authorized)
case .couldNotComplete:
completion(.error(requestError ?? CKError(.permissionFailure)))
@unknown default:
completion(.notDetermined)
}
}
}
}
#endif
| apache-2.0 | 055e67877a90218f7b1ad78a1619d7a5 | 35.074468 | 179 | 0.663226 | 5.623549 | false | false | false | false |
wiltonlazary/kotlin-native | performance/KotlinVsSwift/ring/src/StringBenchmark.swift | 4 | 1686 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
import Foundation
class StringBenchmark {
private var _data: [String]? = nil
var data: [String] {
get {
return _data!
}
}
var csv: String = ""
init() {
var list: [String] = []
list.reserveCapacity(Constants.BENCHMARK_SIZE)
for n in stringValues(Constants.BENCHMARK_SIZE) {
list.append(n)
}
_data = list
csv = ""
for _ in 1...Constants.BENCHMARK_SIZE-1 {
let elem = Double.random(in: 0.0..<100.0)
csv += String(elem)
csv += ","
}
csv += String(0.0)
}
func stringConcat() -> String? {
var string: String = ""
for it in data {
string += it
}
return string
}
func stringConcatNullable() -> String? {
var string: String? = ""
for it in data {
string? += it
}
return string
}
func stringBuilderConcat() -> String {
var string: String = ""
for it in data {
string += it
}
return string
}
func stringBuilderConcatNullable() -> String {
var string: String? = ""
for it in data {
string? += it
}
return string!
}
func summarizeSplittedCsv() -> Double {
let fields = csv.split(separator: ",")
var sum = 0.0
for field in fields {
sum += Double(field) ?? 0.0
}
return sum
}
}
| apache-2.0 | 3c7b9f19b84d399410787534b70215be | 21.783784 | 101 | 0.483393 | 4.132353 | false | false | false | false |
danwey/INSPhotoGallery | INSPhotoGallery/INSPhotosOverlayView.swift | 1 | 7862 | //
// INSPhotosOverlayView.swift
// INSPhotoViewer
//
// Created by Michal Zaborowski on 28.02.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
public protocol INSPhotosOverlayViewable:class {
weak var photosViewController: INSPhotosViewController? { get set }
func populateWithPhoto(photo: INSPhotoViewable)
func setHidden(hidden: Bool, animated: Bool)
func view() -> UIView
}
extension INSPhotosOverlayViewable where Self: UIView {
public func view() -> UIView {
return self
}
}
public class INSPhotosOverlayView: UIView , INSPhotosOverlayViewable {
public private(set) var navigationBar: UINavigationBar!
public private(set) var captionLabel: UILabel!
public private(set) var navigationItem: UINavigationItem!
public weak var photosViewController: INSPhotosViewController?
private var currentPhoto: INSPhotoViewable?
var leftBarButtonItem: UIBarButtonItem? {
didSet {
navigationItem.leftBarButtonItem = leftBarButtonItem
}
}
var rightBarButtonItem: UIBarButtonItem? {
didSet {
navigationItem.rightBarButtonItem = rightBarButtonItem
}
}
var titleTextAttributes: [String : AnyObject] = [:] {
didSet {
navigationBar.titleTextAttributes = titleTextAttributes
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupNavigationBar()
setupCaptionLabel()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Pass the touches down to other views
public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if let hitView = super.hitTest(point, withEvent: event) where hitView != self {
return hitView
}
return nil
}
public override func layoutSubviews() {
// The navigation bar has a different intrinsic content size upon rotation, so we must update to that new size.
// Do it without animation to more closely match the behavior in `UINavigationController`
UIView.performWithoutAnimation { () -> Void in
self.navigationBar.invalidateIntrinsicContentSize()
self.navigationBar.layoutIfNeeded()
}
super.layoutSubviews()
}
public func setHidden(hidden: Bool, animated: Bool) {
if self.hidden == hidden {
return
}
if animated {
self.hidden = false
self.alpha = hidden ? 1.0 : 0.0
UIView.animateWithDuration(0.2, delay: 0.0, options: [.CurveEaseInOut, .AllowAnimatedContent, .AllowUserInteraction], animations: { () -> Void in
self.alpha = hidden ? 0.0 : 1.0
}, completion: { result in
self.alpha = 1.0
self.hidden = hidden
})
} else {
self.hidden = hidden
}
}
public func populateWithPhoto(photo: INSPhotoViewable) {
self.currentPhoto = photo
if let photosViewController = photosViewController {
if let index = photosViewController.dataSource.indexOfPhoto(photo) {
navigationItem.title = "\(index+1) of \(photosViewController.dataSource.numberOfPhotos)"
}
captionLabel.attributedText = photo.attributedTitle
}
}
@objc private func closeButtonTapped(sender: UIBarButtonItem) {
photosViewController?.dismissViewControllerAnimated(true, completion: nil)
}
@objc private func actionButtonTapped(sender: UIBarButtonItem) {
if let currentPhoto = currentPhoto {
currentPhoto.loadImageWithCompletionHandler({ [weak self] (image, error) -> () in
if let image = (image ?? currentPhoto.thumbnailImage) {
let activityController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
self?.photosViewController?.presentViewController(activityController, animated: true, completion: nil)
}
});
}
}
private func setupNavigationBar() {
navigationBar = UINavigationBar()
navigationBar.translatesAutoresizingMaskIntoConstraints = false
navigationBar.backgroundColor = UIColor.clearColor()
navigationBar.barTintColor = nil
navigationBar.translucent = true
navigationBar.shadowImage = UIImage()
navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
navigationItem = UINavigationItem(title: "")
navigationBar.items = [navigationItem]
addSubview(navigationBar)
let topConstraint = NSLayoutConstraint(item: navigationBar, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0.0)
let widthConstraint = NSLayoutConstraint(item: navigationBar, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1.0, constant: 0.0)
let horizontalPositionConstraint = NSLayoutConstraint(item: navigationBar, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
self.addConstraints([topConstraint,widthConstraint,horizontalPositionConstraint])
if let bundlePath = NSBundle(forClass: self.dynamicType).pathForResource("INSPhotoGallery", ofType: "bundle") {
let bundle = NSBundle(path: bundlePath)
leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "INSPhotoGalleryClose", inBundle: bundle, compatibleWithTraitCollection: nil), landscapeImagePhone: UIImage(named: "INSPhotoGalleryCloseLandscape", inBundle: bundle, compatibleWithTraitCollection: nil), style: .Plain, target: self, action: #selector(INSPhotosOverlayView.closeButtonTapped(_:)))
} else {
leftBarButtonItem = UIBarButtonItem(title: "CLOSE".uppercaseString, style: .Plain, target: self, action: #selector(INSPhotosOverlayView.closeButtonTapped(_:)))
}
rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(INSPhotosOverlayView.actionButtonTapped(_:)))
}
private func setupCaptionLabel() {
captionLabel = UILabel()
captionLabel.translatesAutoresizingMaskIntoConstraints = false
captionLabel.backgroundColor = UIColor.clearColor()
captionLabel.numberOfLines = 0
addSubview(captionLabel)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: captionLabel, attribute: .Bottom, multiplier: 1.0, constant: 8.0)
let leadingConstraint = NSLayoutConstraint(item: captionLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: 8.0)
let trailingConstraint = NSLayoutConstraint(item: captionLabel, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: 8.0)
self.addConstraints([bottomConstraint,leadingConstraint,trailingConstraint])
}
} | apache-2.0 | f71af44d6834701da97c73736e0c0394 | 44.172414 | 364 | 0.67604 | 5.295822 | false | false | false | false |
marcosgriselli/ViewAnimator | Sources/ViewAnimator.swift | 1 | 9532 | //
// ViewAnimator.swift
// Pods-ViewAnimator_Example
//
// Created by Marcos Griselli on 10/5/17.
//
import Foundation
import UIKit
// MARK: - UIView extension with animations.
public extension UIView {
// MARK: - Single View
/// Animation based on the UIView.animateWithDuration API
/// - Parameters:
/// - animations: Array of Animations to perform on the animation block.
/// - reversed: Initial state of the animation. Reversed will start from its original position.
/// - initialAlpha: Initial alpha of the view prior to the animation.
/// - finalAlpha: View's alpha after the animation.
/// - delay: Time Delay before the animation.
/// - duration: TimeInterval the animation takes to complete.
/// - options: UIView.AnimationsOptions to pass to the animation block.
/// - completion: block to run after the animation finishes.
func animate(animations: [Animation],
reversed: Bool = false,
initialAlpha: CGFloat = 0.0,
finalAlpha: CGFloat = 1.0,
delay: Double = 0,
duration: TimeInterval = ViewAnimatorConfig.duration,
options: UIView.AnimationOptions = [],
completion: (() -> Void)? = nil) {
let transformFrom = transform
var transformTo = transform
animations.forEach { transformTo = transformTo.concatenating($0.initialTransform) }
if !reversed {
transform = transformTo
}
alpha = initialAlpha
UIView.animate(withDuration: duration,
delay: delay,
options: options,
animations: { [weak self] in
self?.transform = reversed ? transformTo : transformFrom
self?.alpha = finalAlpha
}) { _ in
completion?()
}
}
/// Animation based on UIView.animateWithDuration using springs
///
/// - Parameters:
/// - animations: Array of Animations to perform on the animation block.
/// - reversed: Initial state of the animation. Reversed will start from its original position.
/// - initialAlpha: Initial alpha of the view prior to the animation.
/// - finalAlpha: View's alpha after the animation.
/// - delay: Time Delay before the animation.
/// - duration: TimeInterval the animation takes to complete.
/// - dampingRatio: The damping ratio for the spring animation.
/// - velocity: The initial spring velocity.
/// - options: UIView.AnimationsOptions to pass to the animation block. Timing functions will have no impact on spring based animations.
/// - completion: CompletionBlock after the animation finishes.
func animate(animations: [Animation],
reversed: Bool = false,
initialAlpha: CGFloat = 0.0,
finalAlpha: CGFloat = 1.0,
delay: Double = 0,
duration: TimeInterval = ViewAnimatorConfig.duration,
usingSpringWithDamping dampingRatio: CGFloat,
initialSpringVelocity velocity: CGFloat,
options: UIView.AnimationOptions = [],
completion: (() -> Void)? = nil) {
let transformFrom = transform
var transformTo = transform
animations.forEach { transformTo = transformTo.concatenating($0.initialTransform) }
if !reversed {
transform = transformTo
}
alpha = initialAlpha
UIView.animate(withDuration: duration,
delay: delay,
usingSpringWithDamping: dampingRatio,
initialSpringVelocity: velocity,
options: options,
animations: { [weak self] in
self?.transform = reversed ? transformTo : transformFrom
self?.alpha = finalAlpha
}) { _ in
completion?()
}
}
// MARK: - UIView Array
/// Animates multiples views with cascading effect using the UIView.animateWithDuration API
///
/// - Parameters:
/// - animations: Array of Animations to perform on the animation block.
/// - reversed: Initial state of the animation. Reversed will start from its original position.
/// - initialAlpha: Initial alpha of the view prior to the animation.
/// - finalAlpha: View's alpha after the animation.
/// - delay: Time Delay before the animation.
/// - animationInterval: Interval between the animations of each view.
/// - duration: TimeInterval the animation takes to complete.
/// - dampingRatio: The damping ratio for the spring animation.
/// - velocity: The initial spring velocity.
/// - options: UIView.AnimationsOptions to pass to the animation block. Timing functions will have no impact on spring based animations.
/// - completion: CompletionBlock after the animation finishes.
static func animate(views: [UIView],
animations: [Animation],
reversed: Bool = false,
initialAlpha: CGFloat = 0.0,
finalAlpha: CGFloat = 1.0,
delay: Double = 0,
animationInterval: TimeInterval = 0.05,
duration: TimeInterval = ViewAnimatorConfig.duration,
options: UIView.AnimationOptions = [],
completion: (() -> Void)? = nil) {
performAnimation(views: views, animations: animations, reversed: reversed, initialAlpha: initialAlpha, delay: delay, animationBlock: { view, index, dispatchGroup in
view.animate(animations: animations,
reversed: reversed,
initialAlpha: initialAlpha,
finalAlpha: finalAlpha,
delay: Double(index) * animationInterval,
duration: duration,
options: options,
completion: { dispatchGroup.leave() })
}, completion: completion)
}
/// Animates multiples views with cascading effect using the UIView.animateWithDuration with springs
///
/// - Parameters:
/// - animations: Array of Animations to perform on the animation block.
/// - reversed: Initial state of the animation. Reversed will start from its original position.
/// - initialAlpha: Initial alpha of the view prior to the animation.
/// - finalAlpha: View's alpha after the animation.
/// - delay: Time Delay before the animation.
/// - animationInterval: Interval between the animations of each view.
/// - duration: TimeInterval the animation takes to complete.
/// - dampingRatio: The damping ratio for the spring animation.
/// - velocity: The initial spring velocity.
/// - options: UIView.AnimationsOptions to pass to the animation block. Timing functions will have no impact on spring based animations.
/// - completion: CompletionBlock after the animation finishes.
static func animate(views: [UIView],
animations: [Animation],
reversed: Bool = false,
initialAlpha: CGFloat = 0.0,
finalAlpha: CGFloat = 1.0,
delay: Double = 0,
animationInterval: TimeInterval = 0.05,
duration: TimeInterval = ViewAnimatorConfig.duration,
usingSpringWithDamping dampingRatio: CGFloat,
initialSpringVelocity velocity: CGFloat,
options: UIView.AnimationOptions = [],
completion: (() -> Void)? = nil) {
performAnimation(views: views, animations: animations, reversed: reversed, initialAlpha: initialAlpha, delay: delay, animationBlock: { view, index, dispatchGroup in
view.animate(animations: animations,
reversed: reversed,
initialAlpha: initialAlpha,
finalAlpha: finalAlpha,
delay: Double(index) * animationInterval,
duration: duration,
usingSpringWithDamping: dampingRatio,
initialSpringVelocity: velocity,
options: options,
completion: { dispatchGroup.leave() })
}, completion: completion)
}
static private func performAnimation(
views: [UIView],
animations: [Animation],
reversed: Bool = false,
initialAlpha: CGFloat = 0.0,
delay: Double = 0,
animationBlock: @escaping ((UIView, Int, DispatchGroup) -> Void),
completion: (() -> Void)? = nil) {
guard views.count > 0 else {
completion?()
return
}
views.forEach { $0.alpha = initialAlpha }
let dispatchGroup = DispatchGroup()
for _ in 1...views.count { dispatchGroup.enter() }
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
for (index, view) in views.enumerated() {
animationBlock(view, index, dispatchGroup)
}
}
dispatchGroup.notify(queue: .main) {
completion?()
}
}
}
| mit | 1db8962d84f30838a38f7ce59da0ee52 | 45.048309 | 172 | 0.576794 | 5.516204 | false | false | false | false |
justindhill/Facets | Facets/View Controllers/Form Builder/OZLSwitchFormField.swift | 1 | 2990 | //
// OZLSwitchFormField.swift
// Facets
//
// Created by Justin Hill on 3/17/16.
// Copyright © 2016 Justin Hill. All rights reserved.
//
class OZLSwitchFormField: OZLFormField {
var currentValue: Bool
init(keyPath: String, placeholder: String, currentValue: Bool) {
self.currentValue = currentValue
super.init(keyPath: keyPath, placeholder: placeholder)
self.fieldHeight = 48.0
self.cellClass = OZLSwitchFormFieldCell.self
}
}
class OZLSwitchFormFieldCell: OZLFormFieldCell {
let switchControl = UISwitch()
let titleLabel = UILabel()
var currentValue = false
required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
func setup() {
self.switchControl.addTarget(self, action: #selector(switchValueChanged(_:)), for: .valueChanged)
}
override func applyFormField(_ field: OZLFormField) {
super.applyFormField(field)
guard let field = field as? OZLSwitchFormField else {
assertionFailure("Somehow received the wrong type of field")
return
}
self.titleLabel.text = field.placeholder
self.switchControl.isOn = field.currentValue
self.currentValue = field.currentValue
}
override func layoutSubviews() {
super.layoutSubviews()
self.switchControl.onTintColor = self.tintColor
if self.switchControl.superview == nil {
self.contentView.addSubview(self.switchControl)
self.contentView.addSubview(self.titleLabel)
}
self.switchControl.sizeToFit()
self.switchControl.frame = CGRect(x: self.contentView.frame.size.width - self.layoutMargins.right - self.switchControl.frame.size.width,
y: (self.contentView.frame.size.height - self.switchControl.frame.size.height) / 2.0,
width: self.switchControl.frame.size.width,
height: self.switchControl.frame.size.height)
self.titleLabel.sizeToFit()
self.titleLabel.frame = CGRect(x: self.layoutMargins.left,
y: (self.contentView.frame.size.height - self.titleLabel.frame.size.height) / 2.0,
width: self.titleLabel.frame.size.width,
height: self.titleLabel.frame.size.height)
}
@objc func switchValueChanged(_ sender: UISwitch) {
if sender.isOn != self.currentValue {
self.delegate?.formFieldCell(self, valueChangedFrom: self.currentValue as AnyObject?, toValue: sender.isOn as AnyObject?, atKeyPath: self.keyPath, userInfo: self.userInfo)
self.currentValue = sender.isOn
}
}
}
| mit | eb850e06a3827dd86e40ad8ec015d0ca | 34.164706 | 183 | 0.628638 | 4.744444 | false | false | false | false |
yonadev/yona-app-ios | Yona/Yona/UIControlCell/DayViewLinkCell.swift | 1 | 1126 | //
// DayViewLinkCell.swift
// Yona
//
// Created by Anders Liebl on 25/12/2016.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
class DayViewLinkCell: UITableViewCell {
@IBOutlet weak var cellTitle: UILabel!
@IBOutlet weak var violationLinkURL: UILabel!
@IBOutlet weak var violationTime: UILabel!
@IBOutlet weak var gradientView: GradientSmooth!
//MARK: - override methods
override func layoutSubviews() {
super.layoutSubviews()
//contentView.layoutIfNeeded()
setupGradient()
}
func setupGradient () {
gradientView.setGradientSmooth(UIColor.yiBgGradientTwoColor(), color2: UIColor.yiBgGradientOneColor())
}
func setData(_ linkURL : String, startDate : Date) {
cellTitle.text = NSLocalizedString("link.cell.title", comment: "")
violationLinkURL.text = linkURL
violationLinkURL.sizeToFit()
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
let txt = formatter.string(from: startDate)
violationTime.text = txt
}
}
| mpl-2.0 | dd23ce8e999eb8357633479d7500a8f1 | 24.568182 | 110 | 0.651556 | 4.726891 | false | false | false | false |
vakoc/particle-swift | Sources/Webhooks.swift | 1 | 23885 | // This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2016, 2017 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import Foundation
/// A Particle Cloud Webhook
public struct Webhook {
/// Webhook HTTP methods
///
/// - GET: HTTP Get
/// - POST: HTTP Post
/// - PUT: HTTP Put
/// - DELETE: HTTP Delete
public enum RequestType: String {
case get = "GET", post = "POST", put = "PUT", delete = "DELETE"
}
/// Unique identifier for the webhook
public var id: String
/// The date the webhook was created
public var created: Date?
// The name of the Particle event that will trigger the webhook
public var event: String
/// The web address that will be targeted when the webhook is triggered
public var url: URL
/// Type of web request triggered by the webhook that can be set
public var requestType: RequestType = .get
/// Limits the webhook triggering to devices owned by you
public var mydevices: Bool = true
/// Limits the webhook triggering to a single device
public var deviceID: String?
/// Custom data sent as JSON with the request
public var json: [String : Any]?
/// Custom data sent a form with the request
public var form: [String : Any]?
/// Query parameters added to the URL of the request
public var query: [String : Any]?
/// Custom HTTP headers included with the request
public var headers: [String : String]?
/// A customized webhook response event name that your devices can subscribe to
public var responseTopic: String?
/// You can use the response template parameter to let the webhook dynamically render a new event response down to your devices. This is just like the custom template variables above, but it applies to what your devices see, instead of what your server sees."
public var responseTemplate: String?
/// A customized webhook error response event name that your devices can subscribe to
public var errorResponseTopic: String?
/// The http basic auth username
public var username: String?
/// The http basic auth password
public var password: String?
/// If true, will not add the triggering Particle event's data to the webhook request
public var noDefaults: Bool = false
/// If false, skip SSL certificate validation of the target URL
public var rejectUnauthorized: Bool = true
/// The counters returned by the get webhook command
public var counters: [Counter]?
/// The log entries returned by the get webhook command
public var logs: [Log]?
/// Webhook Counter
public struct Counter {
/// The date of the counter
public var date: Date
/// The success result?
public var success: String
/// Whether an error occurred
public var error: Bool
/// Create a Counter, or nil if the dictionary doesn't contain the required bits
init?(_ dictionary: Dictionary<String,Any>) {
guard let date = dictionary["date"] as? String, let parsedDate = date.dateWithYearMonthDay, let success = dictionary["success"] as? String else {
return nil
}
self.date = parsedDate
self.success = success
self.error = dictionary.bool(for: "error") ?? false
}
/// JSON representation of the counter
public var jsonRepresentation: [String : Any] {
var ret = [String : Any]()
ret["date"] = date.yearMonthDayString
ret["success"] = success
if error == true {
ret["error"] = true
}
return ret
}
}
/// A Webhook log entry
public struct Log {
/// The event that triggered the Webhook
public struct Event {
/// The event data
public var data: String
/// Name of the event
public var event: String
/// The device identifier that triggered the event
public var coreid: String
/// The date the event was published
public var published: Date
/// Create the event, or nil if the dictionary doesn't contain all the required information
init?(_ dictionary: Dictionary<String,Any>) {
guard let coreid = dictionary["coreid"] as? String, let data = dictionary["data"] as? String, let event = dictionary["event"] as? String, let published_at = dictionary["published_at"] as? String,
let published = published_at.dateWithISO8601String else {
return nil
}
self.data = data
self.event = event
self.coreid = coreid
self.published = published
}
/// JSON representation of the event
public var jsonRepresentation: [String : Any] {
var ret = [String : Any]()
ret["data"] = data
ret["event"] = event
ret["coreid"] = coreid
ret["published_at"] = published.ISO8601String
return ret
}
}
/// The triggering event
public var event: Event
/// The webhook request
public var request: String
/// The webhook response
public var response: String
/// The time of the logged evenet
public var time: Date
/// The log type
public var type: String
/// Create a Counter, or nil if the dictionary doesn't contain the required bits
init?(_ dictionary: Dictionary<String,Any>) {
guard let eventString = dictionary["event"] as? [String : Any], let event = Event(eventString),
let response = dictionary["response"] as? String, let request = dictionary["request"] as? String,
let timeNumberString = dictionary["time"] as? CustomStringConvertible,
let timeNumber = Int("\(timeNumberString)"),
let type = dictionary["type"] as? String else {
return nil
}
self.event = event
self.request = request
self.response = response
self.time = Date(timeIntervalSince1970: TimeInterval(timeNumber))
self.type = type
}
/// JSON representation of the counter
public var jsonRepresentation: [String : Any] {
var ret = [String : Any]()
ret["event"] = event.jsonRepresentation
ret["request"] = request
ret["response"] = response
ret["time"] = Int(time.timeIntervalSince1970)
ret["type"] = type
return ret
}
}
/// Creates a webhook
///
/// Webhooks created by this method are intended or use in the ParticleCloud.createWebhook
/// method. Properties are either manually configured or read from a dictionary using the
/// configure(with:) method. The id of all Webhook instances created with this constructor
/// will be an empty string
public init(event: String, url: URL, requestType: RequestType = .get) {
self.id = ""
self.event = event
self.url = url
self.requestType = requestType
}
/// Create a Webhook using the supplied dictionary.
///
/// Returns nil if the dictionary does not contain all the required information
///
/// - parameter dictionary: The dictionary containing the webhook information
public init?(with dictionary: Dictionary<String,Any>) {
guard let event = dictionary["event"] as? String, let urlString = dictionary["url"] as? String, let url = URL(string: urlString) else {
warn("Failed to create Webhook due to missing required values in \(dictionary)")
return nil
}
self.id = dictionary["id"] as? String ?? ""
self.event = event
self.url = url
configure(with: dictionary)
}
/// Initialize the properties of the Webhook from the specified dictionary
///
/// Non-optional properties id, event, and url are not modified by this method. Use
/// an appropriate constructor instead
public mutating func configure(with dictionary: Dictionary<String, Any>) {
if let created_at = dictionary["created_at"] as? String, let created = created_at.dateWithISO8601String {
self.created = created
}
if let deviceID = dictionary["deviceID"] as? String, !deviceID.isEmpty {
self.deviceID = deviceID
}
if let requestType = dictionary["requestType"] as? String, let rt = RequestType(rawValue: requestType.uppercased()) {
self.requestType = rt
}
if let mydevices = dictionary.bool(for: "mydevices") {
self.mydevices = mydevices
}
if let noDefaults = dictionary.bool(for: "noDefaults") {
self.noDefaults = noDefaults
}
if let auth = dictionary["auth"] as? [String : String] {
self.username = auth["username"]
self.password = auth["password"]
}
if let rejectUnauthorized = dictionary.bool(for: "rejectUnauthorized") {
self.rejectUnauthorized = rejectUnauthorized
}
self.form = dictionary["form"] as? Dictionary<String,Any>
self.query = dictionary["query"] as? Dictionary<String,Any>
self.json = dictionary["json"] as? Dictionary<String,Any>
self.headers = dictionary["headers"] as? Dictionary<String,String>
self.responseTopic = dictionary["responseTopic"] as? String
self.errorResponseTopic = dictionary["errorResponseTopic"] as? String
self.responseTemplate = dictionary["responseTemplate"] as? String
// the following are returned only from the GetWebhook command
if let counters = dictionary["counters"] as? [Dictionary<String,Any>] {
self.counters = counters.compactMap { Counter($0) }
}
// the following are returned only from the GetWebhook command
if let logs = dictionary["logs"] as? [Dictionary<String,Any>] {
self.logs = logs.compactMap { Log($0) }
}
}
/// JSON Representation of the webhook
public var jsonRepresentation: [String : Any] {
var ret = [String : Any]()
if !id.isEmpty {
ret["id"] = id
}
ret["event"] = event
ret["url"] = url.absoluteString
ret["requestType"] = requestType.rawValue
ret["mydevices"] = mydevices
ret["noDefaults"] = noDefaults
ret["rejectUnauthorized"] = rejectUnauthorized
if username != nil || password != nil {
var auth = [String : String]()
auth["username"] = username
auth["password"] = password
ret["auth"] = auth
}
if let created = created { ret["created_at"] = created.ISO8601String }
if let deviceID = deviceID { ret["deviceID"] = deviceID }
if let form = form { ret["form"] = form }
if let json = json { ret["json"] = json }
if let query = query { ret["query"] = query }
if let headers = headers { ret["headers "] = headers }
if let responseTopic = responseTopic { ret["responseTopic"] = responseTopic }
if let errorResponseTopic = errorResponseTopic { ret["errorResponseTopic"] = errorResponseTopic }
if let responseTemplate = responseTemplate { ret["responseTemplate"] = responseTemplate }
if let counters = counters {
ret["counters"] = counters.map { $0.jsonRepresentation }
}
if let logs = logs {
ret["logs"] = logs.map { $0.jsonRepresentation }
}
return ret
}
}
extension Webhook: Equatable {
static public func == (lhs: Webhook, rhs: Webhook) -> Bool {
return lhs.id == rhs.id &&
lhs.event == rhs.event &&
lhs.url == rhs.url &&
lhs.requestType == rhs.requestType &&
lhs.mydevices == rhs.mydevices &&
lhs.deviceID == rhs.deviceID &&
// lhs.json == rhs.json &&
// lhs.form == rhs.form &&
// lhs.query == rhs.query &&
// lhs.headers == rhs.query &&
lhs.responseTopic == rhs.responseTopic &&
lhs.errorResponseTopic == rhs.errorResponseTopic &&
lhs.noDefaults == rhs.noDefaults &&
lhs.rejectUnauthorized == rhs.rejectUnauthorized
}
}
// MARK: Webhooks
extension ParticleCloud {
/// Asynchronously create a new webhook in the ParticleCloud
///
/// - parameter webhook: the Webhook to create
/// - parameter productIdOrSlug: Product ID or slug (only for product webhooks)
/// - parameter completion: callback invoked with the asynchronous result
public func create(webhook: Webhook, productIdOrSlug: String? = nil, completion: @escaping (Result<Webhook>) -> Void ) {
self.authenticate(false) { result in
switch result {
case .failure(let error):
return completion(.failure(error))
case .success(let accessToken):
var request = URLRequest(url: productIdOrSlug != nil ? self.baseURL.appendingPathComponent("v1/products/\(String(describing: productIdOrSlug))/webhooks") : self.baseURL.appendingPathComponent("v1/webhooks"))
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = webhook.jsonRepresentation.jsonString?.data(using: .utf8)
let task = self.urlSession.dataTask(with: request) { (data, response, error) in
trace( "Created webhook", request: request, data: data, response: response, error: error)
if let error = self.checkForInvalidToken(request: request, response: response, data: data) {
return completion(.failure(error))
}
if let error = error {
return completion(.failure(ParticleError.createWebhookFailed(error)))
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let j = json, let id = j["id"] as? String, j.bool(for: "ok") == true {
var newWebhook = webhook
newWebhook.configure(with: j)
newWebhook.id = id
return completion(.success(newWebhook))
} else {
let message = data != nil ? String(data: data!, encoding: String.Encoding.utf8) ?? "" : ""
warn("failed to create webhook with response: \(String(describing: response)) and message body \(message)")
return completion(.failure(ParticleError.createWebhookFailed(ParticleError.httpResponseParseFailed(message))))
}
}
task.resume()
}
}
}
/// Asynchronously delete a new webhook in the ParticleCloud
///
/// - parameter webhookID: the id Webhook to delete
/// - parameter productIdOrSlug: Product ID or slug (only for product webhooks)
/// - parameter completion: callback invoked with the asynchronous result
public func delete(webhookID: String, productIdOrSlug: String? = nil, completion: @escaping (Result<Bool>) -> Void ) {
self.authenticate(false) { result in
switch result {
case .failure(let error):
return completion(.failure(error))
case .success(let accessToken):
var request = URLRequest(url: productIdOrSlug != nil ? self.baseURL.appendingPathComponent("v1/products/\(String(describing: productIdOrSlug))/webhooks/\(webhookID)") : self.baseURL.appendingPathComponent("v1/webhooks/\(webhookID)"))
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
request.httpMethod = "DELETE"
let task = self.urlSession.dataTask(with: request) { (data, response, error) in
trace( "Delete webhook", request: request, data: data, response: response, error: error)
if let error = self.checkForInvalidToken(request: request, response: response, data: data) {
return completion(.failure(error))
}
if let error = error {
return completion(.failure(ParticleError.createWebhookFailed(error)))
}
if let response = response as? HTTPURLResponse, response.statusCode == 204 {
return completion(.success(true))
} else {
let message = data != nil ? String(data: data!, encoding: String.Encoding.utf8) ?? "" : ""
warn("failed to delete webhook \(webhookID) with response: \(String(describing:response)) and message body \(message)")
return completion(.failure(ParticleError.deleteWebhookFailed(webhookID, ParticleError.httpResponseParseFailed(message))))
}
}
task.resume()
}
}
}
/// Asynchronously obtain a webhook available by product or account by the webhook id
///
/// This method will invoke authenticate with validateToken = false. Any authentication error will be returned
/// if not successful
///
/// - parameter webhookID: the unique identifier of the webhook to fetch
/// - parameter productIdOrSlug: Product ID or slug (only for product webhooks)
/// - parameter completion: completion handler. Contains an array of Webhook objects
public func webhook(_ webhookID: String, productIdOrSlug: String? = nil, completion: @escaping (Result<Webhook>) -> Void ) {
self.authenticate(false) { (result) in
switch (result) {
case .failure(let error):
return completion(.failure(error))
case .success(let accessToken):
var request = URLRequest(url: productIdOrSlug != nil ? self.baseURL.appendingPathComponent("v1/products/\(String(describing: productIdOrSlug))/webhooks/\(webhookID)") : self.baseURL.appendingPathComponent("v1/webhooks/\(webhookID)"))
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
let task = self.urlSession.dataTask(with: request) { (data, response, error) in
trace( "Get a webhook \(webhookID)", request: request, data: data, response: response, error: error)
if let error = self.checkForInvalidToken(request: request, response: response, data: data) {
return completion(.failure(error))
}
if let error = error {
return completion(.failure(ParticleError.webhookListFailed(error)))
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let j = json, let j2 = j["webhook"] as? Dictionary<String,Any>, let webhook = Webhook(with: j2) {
return completion(.success(webhook))
} else {
let message = data != nil ? String(data: data!, encoding: String.Encoding.utf8) ?? "" : ""
warn("failed to get webhook \(webhookID) with response: \(String(describing: response)) and message body \(message)")
return completion(.failure(ParticleError.webhookGetFailed(webhookID, ParticleError.httpResponseParseFailed(message))))
}
}
task.resume()
}
}
}
/// Asynchronously obtain the webhooks available by product or account
///
/// This method will invoke authenticate with validateToken = false. Any authentication error will be returned
/// if not successful
///
/// - parameter productIdOrSlug: Product ID or slug (only for product webhooks)
/// - parameter completion: completion handler. Contains an array of Webhook objects
public func webhooks(productIdOrSlug: String? = nil, completion: @escaping (Result<[Webhook]>) -> Void ) {
self.authenticate(false) { (result) in
switch (result) {
case .failure(let error):
return completion(.failure(error))
case .success(let accessToken):
var request = URLRequest(url: productIdOrSlug != nil ? self.baseURL.appendingPathComponent("v1/products/\(String(describing: productIdOrSlug))/webhooks") : self.baseURL.appendingPathComponent("v1/webhooks"))
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
let task = self.urlSession.dataTask(with: request) { (data, response, error) in
trace( "Listing all webhooks", request: request, data: data, response: response, error: error)
if let error = self.checkForInvalidToken(request: request, response: response, data: data) {
return completion(.failure(error))
}
if let error = error {
return completion(.failure(ParticleError.webhookListFailed(error)))
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [[String : Any]], let j = json {
return completion(.success(j.compactMap({ return Webhook(with: $0)})))
} else {
let message = data != nil ? String(data: data!, encoding: String.Encoding.utf8) ?? "" : ""
warn("failed to list all webhooks with response: \(String(describing: response)) and message body \(String(describing: message))")
return completion(.failure(ParticleError.webhookListFailed(ParticleError.httpResponseParseFailed(message))))
}
}
task.resume()
}
}
}
}
| apache-2.0 | a39c8aae66bf07b38dfead9bbb414cbe | 42.034234 | 263 | 0.564436 | 5.258476 | false | false | false | false |
ntaku/SwiftEssential | SwiftEssential/DateUtil.swift | 1 | 1679 | import Foundation
public class DateUtil {
// y/m/d -> Date
@objc public static func date(year: Int, month: Int, day: Int) -> Date {
var c = DateComponents()
c.year = year
c.month = month
c.day = day
c.hour = 0
c.minute = 0
c.second = 0
return Calendar.init(identifier: .gregorian).date(from: c)!
}
// Date -> y/m/d
@objc public static func component(from date: Date) -> DateComponents {
let cal = Calendar.init(identifier: .gregorian)
return cal.dateComponents([.year, .month, .day, .hour, .minute, .second, .weekday, .weekOfYear, .weekOfMonth], from: date)
}
// format string
@objc public static func formatString(date: Date, format: String = "yyyy/MM/dd hh:mm:ss") -> String {
let formatter = DateFormatter()
if let langId = Locale.preferredLanguages.first {
formatter.locale = Locale.init(identifier: langId)
}
formatter.dateFormat = format
return formatter.string(from: date)
}
@objc public static func weekdayName(date: Date, shortStyle: Bool = true) -> String {
let cal = Calendar.init(identifier: .gregorian)
let formatter = DateFormatter()
let components = cal.dateComponents([.weekday], from: date)
let weekday = (components.weekday ?? 1) - 1
if shortStyle {
if weekday < formatter.shortWeekdaySymbols.count {
return formatter.shortWeekdaySymbols[weekday]
}
}
if weekday < formatter.weekdaySymbols.count {
return formatter.weekdaySymbols[weekday]
}
return ""
}
}
| mit | 6d94863248283dc69dd9f2dc680c478d | 32.58 | 130 | 0.599762 | 4.349741 | false | false | false | false |
scottkawai/sendgrid-swift | Sources/SendGrid/API/V3/Suppression/Bounces/RetrieveBounces.swift | 1 | 3430 | import Foundation
/// The `RetrieveBounces` class represents the API call to [retrieve the bounce
/// list](https://sendgrid.com/docs/API_Reference/Web_API_v3/bounces.html#List-all-bounces-GET).
/// You can use it to retrieve the entire list, or specific entries in the
/// list.
///
/// ## Get All Bounces
///
/// To retrieve the list of all bounces, use the `RetrieveBounces` class with the
/// `init(start:end:page:)` initializer. The library will automatically map
/// the response to the `Bounce` struct model, accessible via the `model`
/// property on the response instance you get back.
///
/// ```swift
/// do {
/// // If you don't specify any parameters, then the first page of your entire
/// // bounce list will be fetched:
/// let request = RetrieveBounces()
/// try Session.shared.send(modeledRequest: request) { result in
/// switch result {
/// case .success(let response, let model):
/// // The `model` property will be an array of `Bounce` structs.
/// model.forEach { print($0.email) }
///
/// // The response object has a `Pagination` instance on it as well.
/// // You can use this to get the next page, if you wish.
/// if let nextPage = response.pages?.next {
/// let nextRequest = RetrieveBounces(page: nextPage)
/// }
/// case .failure(let err):
/// print(err)
/// }
/// }
/// } catch {
/// print(error)
/// }
/// ```
///
/// You can also specify any or all of the init parameters to filter your
/// search down:
///
/// ```swift
/// do {
/// // Retrieve page 2
/// let page = Page(limit: 500, offset: 500)
/// // Bounces starting from yesterday
/// let now = Date()
/// let start = now.addingTimeInterval(-86400) // 24 hours
///
/// let request = RetrieveBounces(start: start, end: now, page: page)
/// try Session.shared.send(modeledRequest: request) { result in
/// switch result {
/// case .success(_, let model):
/// // The `model` property will be an array of `Bounce` structs.
/// model.forEach { print($0.email) }
/// case .failure(let err):
/// print(err)
/// }
/// }
/// } catch {
/// print(error)
/// }
/// ```
///
/// ## Get Specific Bounce
///
/// If you're looking for a specific email address in the bounce list, you
/// can use the `init(email:)` initializer on `RetrieveBounces`:
///
/// ```swift
/// do {
/// let request = RetrieveBounces(email: "[email protected]")
/// try Session.shared.send(modeledRequest: request) { result in
/// switch result {
/// case .success(_, let model):
/// // The `model` property will be an array of `Bounce` structs.
/// if let match = model.first {
/// print("\(match.email) bounced with reason \"\(match.reason)\"")
/// }
/// case .failure(let err):
/// print(err)
/// }
/// }
/// } catch {
/// print(error)
/// }
/// ```
public class RetrieveBounces: SuppressionListReader<Bounce> {
/// :nodoc:
internal override init(path: String?, email: String?, start: Date?, end: Date?, page: Page?) {
super.init(
path: "/v3/suppression/bounces",
email: email,
start: start,
end: end,
page: page
)
}
}
| mit | cf4860f5d7f91cf0e9ffa7c67d427896 | 33.3 | 98 | 0.559475 | 3.840985 | false | false | false | false |
TeamYYZ/DineApp | Dine/Route.swift | 1 | 2049 | //
// Route.swift
// Dine
//
// Created by you wu on 3/30/16.
// Copyright © 2016 YYZ. All rights reserved.
//
import UIKit
class Route: NSObject {
struct Step {
var distance: String?
var duration: String?
var startLoc: CLLocation?
var endLoc: CLLocation?
var polyLine: String?
var instruction: String?
var maneuver: String?
init(dictionary:NSDictionary) {
distance = dictionary["distance"]?["text"] as? String
duration = dictionary["duration"]?["text"] as? String
if let lat = dictionary["end_location"]?["lat"] as? CLLocationDegrees {
if let lng = dictionary["end_location"]?["lng"] as? CLLocationDegrees {
endLoc = CLLocation(latitude: lat, longitude: lng)
}
}
if let lat = dictionary["start_location"]?["lat"] as? CLLocationDegrees {
if let lng = dictionary["start_location"]?["lng"] as? CLLocationDegrees {
startLoc = CLLocation(latitude: lat, longitude: lng)
}
}
instruction = dictionary["html_instructions"] as? String
if let polyLine = dictionary["polyline"]?["points"] as? String {
self.polyLine = polyLine
}
maneuver = dictionary["maneuver"] as? String
}
}
var steps = [Step]()
init(dictionary: NSDictionary) {
if let legs = dictionary["legs"] as? [NSDictionary] {
if let stepsDic = legs[0]["steps"] as? [NSDictionary] {
for step in stepsDic {
steps.append(Step(dictionary: step))
}
}
}
}
class func routes(array array: [NSDictionary]) -> [Route] {
var routes = [Route]()
for dictionary in array {
let route = Route(dictionary: dictionary)
routes.append(route)
}
return routes
}
}
| gpl-3.0 | ff7dc7ec5d2146d69e6b11833d2f6d9f | 30.507692 | 89 | 0.52002 | 4.94686 | false | false | false | false |
therealglazou/quaxe-for-swift | quaxe/core/Node.swift | 1 | 20586 | /**
* Quaxe for Swift
*
* Copyright 2016-2017 Disruptive Innovations
*
* Original author:
* Daniel Glazman <[email protected]>
*
* Contributors:
*
*/
/**
* https://dom.spec.whatwg.org/#interface-node
*
* status: done
*/
public class Node: EventTarget, pNode {
static let ELEMENT_NODE: ushort = 1;
static let ATTRIBUTE_NODE: ushort = 2; // historical
static let TEXT_NODE: ushort = 3;
static let CDATA_SECTION_NODE: ushort = 4; // historical
static let ENTITY_REFERENCE_NODE: ushort = 5; // historical
static let ENTITY_NODE: ushort = 6; // historical
static let PROCESSING_INSTRUCTION_NODE: ushort = 7;
static let COMMENT_NODE: ushort = 8;
static let DOCUMENT_NODE: ushort = 9;
static let DOCUMENT_TYPE_NODE: ushort = 10;
static let DOCUMENT_FRAGMENT_NODE: ushort = 11;
static let NOTATION_NODE: ushort = 12; // historical
internal var mNodeType: ushort = 1
internal var mOwnerDocument: pDocument?
internal var mParentNode: pNode?
internal var mFirstChild: pNode?
internal var mLastChild: pNode?
internal var mPreviousSibling: pNode?
internal var mNextSibling: pNode?
internal func _getTextContent(_ n: pNode?) -> DOMString {
var node = n
var rv = ""
while nil != node {
switch nodeType {
case Node.DOCUMENT_FRAGMENT_NODE,
Node.ELEMENT_NODE:
rv += _getTextContent(self.firstChild)
case Node.TEXT_NODE,
Node.PROCESSING_INSTRUCTION_NODE,
Node.COMMENT_NODE:
rv += (self as! pCharacterData).data
default: break;
}
node = node!.nextSibling
}
return rv
}
internal func getCounts(_ elementCount: inout UInt, _ textCount: inout UInt) -> Void {
var child = firstChild
elementCount = 0
textCount = 0
while nil != child {
switch child!.nodeType {
case Node.ELEMENT_NODE: elementCount += 1
case Node.TEXT_NODE: textCount += 1
default: break;
}
child = child!.nextSibling
}
}
internal func getChildCount() -> UInt {
var child = firstChild
var count: UInt = 0
while nil != child {
count += 1
child = child!.nextSibling
}
return count
}
internal func hasFollowingDoctype() -> Bool {
var child = self.nextSibling
while nil != child {
switch child!.nodeType {
case Node.DOCUMENT_TYPE_NODE: return true
default: break;
}
child = child!.nextSibling
}
return false
}
internal func hasPrecedingElement() -> Bool {
var child = self.previousSibling
while nil != child {
switch child!.nodeType {
case Node.ELEMENT_NODE: return true
default: break;
}
child = child!.previousSibling
}
return false
}
internal func hasDoctypeChild() -> Bool {
var child = self.firstChild
while nil != child {
switch child!.nodeType {
case Node.DOCUMENT_TYPE_NODE: return true
default: break;
}
child = child!.nextSibling
}
return false
}
override internal func getParent(_ event: Event) -> EventTarget? {
return self.parentNode as? EventTarget
}
/**
* https://dom.spec.whatwg.org/#dom-node-nodetype
*/
public var nodeType: ushort { return mNodeType }
/**
* https://dom.spec.whatwg.org/#dom-node-nodename
*/
public var nodeName: DOMString {
switch nodeType {
case Node.ELEMENT_NODE:
return (self as! pElement).tagName
case Node.TEXT_NODE:
return "#text"
case Node.PROCESSING_INSTRUCTION_NODE:
return (self as! pProcessingInstruction).target
case Node.COMMENT_NODE:
return "#comment"
case Node.DOCUMENT_NODE:
return "#document"
case Node.DOCUMENT_TYPE_NODE:
return (self as! pDocumentType).name
case Node.DOCUMENT_FRAGMENT_NODE:
return "#document-fragment"
default: return "" // should never happen in DOM 4
}
}
/**
* https://dom.spec.whatwg.org/#dom-node-baseuri
*/
public var baseURI: DOMString { return "about:blank" }
/**
* https://dom.spec.whatwg.org/#dom-node-ownerdocument
*/
public var ownerDocument: pDocument? {
if Node.DOCUMENT_NODE == nodeType {
return nil
}
return mOwnerDocument
}
/**
* https://dom.spec.whatwg.org/#dom-node-parentnode
*/
public var parentNode: pNode? { return mParentNode }
/**
* https://dom.spec.whatwg.org/#dom-node-parentelement
*/
public var parentElement: pElement? {
if let pe = mParentNode as? pElement {
return pe
}
return nil
}
/**
* https://dom.spec.whatwg.org/#dom-node-haschildnodes
*/
public func hasChildNodes() -> Bool {
return nil != self.firstChild
}
/**
* https://dom.spec.whatwg.org/#dom-node-childnodes
*/
public var childNodes: pNodeList {
let list = NodeList()
var child = self.firstChild
while nil != child {
list.mNodeArray.append(child!)
child = child!.nextSibling
}
return list
}
/**
* https://dom.spec.whatwg.org/#dom-node-firstchild
* https://dom.spec.whatwg.org/#dom-node-lastchild
* https://dom.spec.whatwg.org/#dom-node-previoussibling
* https://dom.spec.whatwg.org/#dom-node-nextsibling
*/
public var firstChild: pNode? { return mFirstChild }
public var lastChild: pNode? { return mLastChild }
public var previousSibling: pNode? { return mPreviousSibling }
public var nextSibling: pNode? { return mNextSibling }
/**
* https://dom.spec.whatwg.org/#dom-node-nodevalue
*/
public var nodeValue: DOMString? {
get {
switch nodeType {
case Node.TEXT_NODE,
Node.PROCESSING_INSTRUCTION_NODE,
Node.COMMENT_NODE:
return (self as! pCharacterData).data
default: return nil
}
}
set {
let n: DOMString = (nil == newValue) ? "" : newValue!
switch nodeType {
case Node.TEXT_NODE,
Node.PROCESSING_INSTRUCTION_NODE,
Node.COMMENT_NODE:
var characterData = (self as! pCharacterData)
characterData.data = n
default: break;
}
}
}
/**
* https://dom.spec.whatwg.org/#dom-node-textcontent
*/
public var textContent: DOMString? {
get {
switch nodeType {
case Node.DOCUMENT_FRAGMENT_NODE,
Node.ELEMENT_NODE:
return _getTextContent(self.firstChild)
case Node.TEXT_NODE,
Node.PROCESSING_INSTRUCTION_NODE,
Node.COMMENT_NODE:
return (self as! pCharacterData).data
default: return nil
}
}
set {
let n: DOMString = (nil == newValue) ? "" : newValue!
switch nodeType {
case Node.DOCUMENT_FRAGMENT_NODE,
Node.ELEMENT_NODE:
var node: pNode? = nil
if !n.isEmpty {
node = Text(n)
}
// XXX we are force to ignore if replaceAll() throws because
// Swift computed properties don't allow to throw yet...
let _ = try? MutationAlgorithms.replaceAll(node as? Node, self)
case Node.TEXT_NODE,
Node.PROCESSING_INSTRUCTION_NODE,
Node.COMMENT_NODE:
let characterData = (self as! CharacterData)
// XXX we are force to ignore if replaceAll() throws because
// Swift computed properties don't allow to throw yet...
let _ = try? CharacterData._replaceData(characterData, 0, characterData.length, n)
default: break;
}
// TODO
}
}
/*
* https://dom.spec.whatwg.org/#dom-node-normalize
*/
public func normalize() throws -> Void {
var node = self.firstChild
while node != nil {
switch (node!.nodeType) {
case Node.TEXT_NODE:
// Step 2
var length = (node as! Text).length
if 0 == length {
// Step 3
MutationAlgorithms.remove(node as! Node, node!.parentNode as! Node)
}
else {
// Step 4
var data: DOMString = (node as! Text).data
var child = node!.nextSibling
while nil != child && child!.nodeType == Node.TEXT_NODE {
data += (child as! Text).data
child = child!.nextSibling
}
// Step 5
try CharacterData._replaceData(node as! CharacterData, length, 0, data)
// Step 6
var currentNode = node!.nextSibling
// Step 7
let rangeCollection = ((node as! Node).ownerDocument as! Document).rangeCollection
while nil != currentNode && currentNode!.nodeType == Node.TEXT_NODE {
// Step 7.1
rangeCollection.forEach( {
if $0.value!.startContainer as! Node === currentNode as! Node {
$0.value!.setStart(node!, $0.value!.startOffset + length);
}
})
// Step 7.2
rangeCollection.forEach( {
if $0.value!.endContainer as! Node === currentNode as! Node {
$0.value!.setEnd(node!, $0.value!.endOffset + length);
}
})
// Step 7.3
rangeCollection.forEach( {
if $0.value!.startContainer as! Node === currentNode!.parentNode as! Node &&
$0.value!.startOffset == Trees.indexOf(currentNode as! Node) {
$0.value!.setStart(node!, length);
}
})
// Step 7.4
rangeCollection.forEach( {
if $0.value!.endContainer as! Node === currentNode!.parentNode as! Node &&
$0.value!.endOffset == Trees.indexOf(currentNode as! Node) {
$0.value!.setStart(node!, length);
}
})
// Step 7.5
length += (currentNode as! Text).length
// Step 7.6
currentNode = currentNode!.nextSibling
}
// Step 8
var textNode = node!.nextSibling
while nil != textNode && textNode!.nodeType == Node.TEXT_NODE {
let tmp = textNode!.nextSibling
MutationAlgorithms.remove(textNode as! Node, textNode!.parentNode as! Node)
textNode = tmp
}
}
case Node.ELEMENT_NODE:
try node!.normalize()
default: break
}
node = node!.nextSibling as? Node
}
}
/**
* https://dom.spec.whatwg.org/#concept-node-clone
*/
internal func _clone(_ d: pDocument? = nil, _ cloneChildrenFlag: Bool = false) -> Node {
var document = d
// Step 1
if nil == document {
document = self.ownerDocument
}
// Step 2
var copy: Node?
switch self.nodeType {
case Node.DOCUMENT_NODE:
let d = Document()
d.mInputEncoding = (self as! Document).inputEncoding
d.mContentType = (self as! Document).contentType
d.mURL = (self as! Document).URL
d.type = (self as! Document).type
d.mMode = (self as! Document).mMode
copy = d
case Node.DOCUMENT_TYPE_NODE:
let dt = DocumentType((self as! DocumentType).name,
(self as! DocumentType).publicId,
(self as! DocumentType).systemId)
copy = dt
case Node.ELEMENT_NODE:
let e = Element()
e.mNamespaceURI = (self as! Element).namespaceURI
e.mPrefix = (self as! Element).prefix
e.mLocalName = (self as! Element).localName
let attributes = (self as! Element).attributes
for attributeIndex in 0...attributes.length-1 {
var a = attributes.item(attributeIndex)
do {
try e.setAttributeNS(a!.namespaceURI, a!.localName, a!.value)
}
catch _ {}
}
copy = e
case Node.TEXT_NODE:
copy = Text((self as! Text).data)
case Node.COMMENT_NODE:
copy = Comment((self as! Comment).data)
case Node.PROCESSING_INSTRUCTION_NODE:
copy = ProcessingInstruction((self as! ProcessingInstruction).target,
(self as! ProcessingInstruction).data)
default: break
}
// Step 3
if Node.DOCUMENT_NODE == copy!.nodeType {
copy!.mOwnerDocument = copy as? pDocument
document = copy as? pDocument
}
else {
copy!.mOwnerDocument = document
}
// Step 4, clonig steps
// TODO
// Step 5
if cloneChildrenFlag {
var child = self.firstChild
while nil != child {
Trees.append((child as! Node)._clone(document, cloneChildrenFlag), copy!)
child = child!.nextSibling
}
}
// Step 6
return copy!
}
/**
* https://dom.spec.whatwg.org/#dom-node-clonenode
*/
public func cloneNode(_ deep: Bool = false) -> pNode {
// Step 1
// IGNORED, we don't implement Shadow DOM
// Step 2
return self._clone(nil, true)
}
/**
* https://dom.spec.whatwg.org/#dom-node-isequalnode
*/
public func isEqualNode(_ otherNode: pNode?) -> Bool {
if nil != otherNode &&
self === otherNode as! Node {
return true
}
return false
}
static let DOCUMENT_POSITION_DISCONNECTED: ushort = 0x01
static let DOCUMENT_POSITION_PRECEDING: ushort = 0x02
static let DOCUMENT_POSITION_FOLLOWING: ushort = 0x04
static let DOCUMENT_POSITION_CONTAINS: ushort = 0x08
static let DOCUMENT_POSITION_CONTAINED_BY: ushort = 0x10
static let DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: ushort = 0x20
/**
* https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
*/
public func compareDocumentPosition(_ other: pNode) -> ushort {
// Step 1
let reference = self
// Step 2
if other as! Node === reference {
return 0
}
// Step 3
if self.ownerDocument as? Document !== other.ownerDocument as? Document {
return Node.DOCUMENT_POSITION_DISCONNECTED
| Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
| Node.DOCUMENT_POSITION_PRECEDING
}
// Step 4
if Trees.isAncestorOf(other as! Node, reference) {
return Node.DOCUMENT_POSITION_CONTAINS
| Node.DOCUMENT_POSITION_PRECEDING
}
// Step 5
if Trees.isDescendantOf(other as! Node, reference) {
return Node.DOCUMENT_POSITION_CONTAINED_BY
| Node.DOCUMENT_POSITION_FOLLOWING
}
// Step 6
var referenceAncestors: Array<Node> = []
var parent = reference.parentNode
while nil != parent {
referenceAncestors.append(parent as! Node)
parent = parent!.parentNode
}
var otherAncestors: Array<Node> = []
parent = other.parentNode
while nil != parent {
otherAncestors.append(parent as! Node)
parent = parent!.parentNode
}
var index = 1;
while referenceAncestors[referenceAncestors.count - index] === otherAncestors[otherAncestors.count - index] {
index += 1
}
if Trees.isPreceding(otherAncestors[otherAncestors.count - index], referenceAncestors[referenceAncestors.count - index]) {
return Node.DOCUMENT_POSITION_PRECEDING
}
return Node.DOCUMENT_POSITION_FOLLOWING
}
/**
* https://dom.spec.whatwg.org/#dom-node-contains
*/
public func contains(_ other: pNode?) -> Bool {
return (nil != other && Trees.isInclusiveDescendantOf(other as! Node, self))
}
/*
* https://dom.spec.whatwg.org/#locate-a-namespace-prefix
*/
static func locateNamespacePrefix(_ elt: Element, _ ns: DOMString) -> DOMString? {
// Step 1
if elt.namespaceURI == ns && elt.prefix != nil {
return elt.prefix!
}
// Step 2
for attr in (elt.attributes as! NamedNodeMap).mAttributes {
if attr.prefix == "xmlns" &&
attr.value == ns {
return attr.localName
}
}
// Step 3
if elt.parentNode != nil {
return locateNamespacePrefix(elt.parentNode as! Element, ns)
}
// Step 4
return nil
}
/*
* https://dom.spec.whatwg.org/#dom-node-lookupprefix
*/
public func lookupPrefix(_ ns: DOMString?) -> DOMString? {
// step 1
if nil == ns || "" == ns {
return nil
}
// step 2
switch self.nodeType {
case Node.ELEMENT_NODE:
return Node.locateNamespacePrefix(self as! Element, ns!)
case Node.DOCUMENT_NODE:
let docElt = (self as! Document).documentElement
if nil != docElt {
return Node.locateNamespacePrefix(docElt as! Element, ns!)
}
return nil
case Node.DOCUMENT_TYPE_NODE,
Node.DOCUMENT_FRAGMENT_NODE:
return nil
case Node.ATTRIBUTE_NODE:
let elt = (self as! Attr).mOwnerElement
if nil != elt {
return Node.locateNamespacePrefix(elt!, ns!)
}
return nil
default:
let parent = self.parentNode
if nil != parent {
return Node.locateNamespacePrefix(parent as! Element, ns!)
}
return nil
}
}
/*
* https://dom.spec.whatwg.org/#locate-a-namespace
*/
static func locateNamespace(_ node: Node, _ prefix: DOMString?) -> DOMString? {
switch node.nodeType {
case Node.ELEMENT_NODE:
let elt = node as! Element
// Step 1.1
if nil != elt.namespaceURI && prefix == elt.prefix {
return elt.namespaceURI
}
// Step 1.2
var value: DOMString? = ""
if nil != prefix &&
elt.hasAttributeNS(Namespaces.XMLNS_NAMESPACE, prefix!) {
value = elt.getAttributeNS(Namespaces.XMLNS_NAMESPACE, prefix!)
}
else if nil == prefix &&
elt.hasAttributeNS(Namespaces.XMLNS_NAMESPACE, "xmlns") {
value = elt.getAttributeNS(Namespaces.XMLNS_NAMESPACE, "xmlns")
}
if "" != value {
return value
}
// Step 1.3
if nil == node.parentNode {
return nil
}
// Step 1.4
return locateNamespace(node.parentNode as! Node, prefix)
case Node.DOCUMENT_NODE:
// Step 2.1
let elt = (node as! Document).documentElement
if nil == elt {
return nil
}
// Step 2.2
return locateNamespace(elt as! Node, prefix)
case Node.DOCUMENT_TYPE_NODE,
Node.DOCUMENT_FRAGMENT_NODE:
return nil
case Node.ATTRIBUTE_NODE:
// Step 3.1
let elt = (node as! Attr).ownerElement
if nil == elt {
return nil
}
// Step 3.2
return locateNamespace(elt as! Node, prefix)
default:
// Step 4.3
if nil == node.parentNode {
return nil
}
// Step 4.4
return locateNamespace(node.parentNode as! Node, prefix)
}
}
/*
* https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri
*/
public func lookupNamespaceURI(_ prefix: DOMString?) -> DOMString? {
// Step 1
if nil == prefix || "" == prefix {
return nil
}
// Step 2
return Node.locateNamespace(self, prefix)
}
/*
* https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace
*/
public func isDefaultNamespace(_ ns: DOMString?) -> Bool {
// Step 1
var namespace = ns;
if "" == namespace {
namespace = nil
}
// Step 2
let defaultNamespace = Node.locateNamespace(self, nil)
// Step 3
return defaultNamespace == namespace
}
/*
* https://dom.spec.whatwg.org/#dom-node-insertbefore
*/
public func insertBefore(_ node: pNode, _ child: pNode?) throws -> pNode {
return try MutationAlgorithms.preInsert(node as! Node, self, child as? Node)
}
/*
* https://dom.spec.whatwg.org/#dom-node-appendchild
*/
@discardableResult public func appendChild(_ node: pNode) throws -> pNode {
return try MutationAlgorithms.append(node as! Node, self)
}
/*
* https://dom.spec.whatwg.org/#dom-node-replacechild
*/
public func replaceChild(_ node: pNode, _ child: pNode) throws -> pNode {
return try MutationAlgorithms.replace(node as! Node, child as! Node, self)
}
/*
* https://dom.spec.whatwg.org/#dom-node-removechild
*/
public func removeChild(_ child: pNode) throws -> pNode {
return try MutationAlgorithms.preRemove(child as! Node, self)
}
override init() {
}
}
| mpl-2.0 | 2a1afa85980032f503c86c7f1462969c | 27.355372 | 126 | 0.582386 | 4.079667 | false | false | false | false |
BananosTeam/CreativeLab | Assistant/View/MessagesView/MessageTableViewCell.swift | 1 | 1066 | //
// MessageCellViewTableViewCell.swift
// Assistant
//
// Created by Bananos on 5/14/16.
// Copyright © 2016 Bananos. All rights reserved.
//
import UIKit
final class MessageTableViewCell: UITableViewCell {
static let ReuseIdentifier = "MessageCellIdentifier"
static let DefaultReuseIdentifier = "DefaltCellReuseIdentifier"
@IBOutlet weak var messageLabel: UILabel!
func configureWithMessage(message: Message) {
messageLabel.text = message.slackMessage.text
messageLabel.textAlignment = alignmentForMessageType(message.messageType)
messageLabel.textColor = colorForMessageType(message.messageType)
}
private func alignmentForMessageType(type: MessageType) -> NSTextAlignment {
return type == .ToMe ? .Left : .Right
}
private func colorForMessageType(type: MessageType) -> UIColor {
return type == .ToMe ?
UIColor(red: 0 / 256, green: 51 / 256, blue: 153 / 256, alpha: 1) :
UIColor(red: 0 / 256, green: 204 / 256, blue: 0 / 256, alpha: 1)
}
}
| mit | b468e4ad53c664d17de6aaccaccc8b7b | 33.354839 | 81 | 0.68169 | 4.512712 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | ChatExample/MobileChatExample/ViewController.swift | 1 | 2295 | //
// ViewController.swift
// MobileChatExample
//
// Created by okoroleva on 26.04.2020.
// Copyright © 2020 Infobip d.o.o. All rights reserved.
//
import Foundation
import UIKit
import MobileMessaging
class ViewController: UIViewController, MMInAppChatDelegate {
@IBOutlet weak var buttonsStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
MobileMessaging.inAppChat?.delegate = self
}
@IBAction func showChatInNavigationP(_ sender: Any) {
let vc = MMChatViewController.makeChildNavigationViewController()
navigationController?.pushViewController(vc, animated: true)
}
@IBAction func showChatModallyP(_ sender: Any) {
let vc = MMChatViewController.makeModalViewController()
navigationController?.present(vc, animated: true, completion: nil)
}
@IBAction func presentRootNavigationVC(_ sender: Any) {
let vc = MMChatViewController.makeRootNavigationViewController()
navigationController?.present(vc, animated: true, completion: nil)
}
@IBAction func presentNavigationVCCustomTrans(_ sender: Any) {
let vc = MMChatViewController.makeRootNavigationViewControllerWithCustomTransition()
navigationController?.present(vc, animated: true, completion: nil)
}
@IBAction func presentAndSendContextualData(_ sender: Any) {
// We first display the chat, and few seconds later (chat should be loaded and connected) we send
// some contextual data. More data can be sent asynchronously while the chat is active.
let vc = MMChatViewController.makeModalViewController()
navigationController?.present(vc, animated: true, completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
vc.sendContextualData("{ demoKey: 'InAppChat Metadata Value' }") { error in
guard let error = error else {
print("Medatata was sent")
return
}
print("Error sending metadata: \(error.localizedDescription)")
}
}
}
func inAppChatIsEnabled(_ enabled: Bool) {
enableButtons(enabled: enabled)
}
func enableButtons(enabled: Bool) {
buttonsStackView.isUserInteractionEnabled = enabled
buttonsStackView.alpha = enabled ? 1.0 : 0.3
}
}
| apache-2.0 | 3e4d97da90eea5d42c450c70d96356ba | 35.412698 | 105 | 0.700087 | 4.606426 | false | false | false | false |
Ahrodite/LigaFix | LigaFix/UsernameEditViewController.swift | 1 | 3125 | //
// UserInfoViewController.swift
// LigaFix
//
// Created by JiaDuan on 15/12/24.
// Copyright © 2015年 JiaDuan. All rights reserved.
//
import UIKit
import CoreData
class UsernameEditViewController: FormViewController {
var username: String?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.loadDate()
self.loadForm()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// MARK: Private interface
private func loadDate() {
username = UserSingleton.sharedInstance.getActiveUsername()
}
private func loadForm() {
let form = FormDescriptor()
form.title = "昵称"
// user info section
let usernameEditSection = FormSectionDescriptor()
var row: FormRowDescriptor! = FormRowDescriptor(tag: "usernameEdit", rowType: .Name, title: "")
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = [
"textField.placeholder" : { (name: String?) -> String in
if name != nil {
return name!
} else {
return "请输入昵称"
}
}(username),
"textField.textAlignment" : NSTextAlignment.Center.rawValue
]
usernameEditSection.addRow(row)
// confirm edit section
let confirmSection = FormSectionDescriptor()
row = FormRowDescriptor(tag: "confirmUsernameEdit", rowType: .Button, title: "确认")
row.configuration[FormRowDescriptor.Configuration.DidSelectClosure] = {
let formDict = self.form.formValues()
var newName = formDict["usernameEdit"] as? String
newName = newName == nil ? self.username : newName
UserSingleton.sharedInstance.setActiveUsername(newName)
self.navigationController?.popViewControllerAnimated(true)
let settingsViewController = self.navigationController?.topViewController as! SettingsViewController
let indexPath: NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)
let cell = settingsViewController.tableView.cellForRowAtIndexPath(indexPath) as! FormValueCell
cell.valueLabel.text = newName
} as DidSelectClosure
confirmSection.addRow(row)
form.sections = [usernameEditSection, confirmSection]
self.form = form
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | ff3bdb26277fd59de59f0b145ad6766b | 31.673684 | 112 | 0.623067 | 5.426573 | false | true | false | false |
dreamsxin/swift | test/decl/ext/protocol.swift | 2 | 21339 | // RUN: %target-parse-verify-swift
// ----------------------------------------------------------------------------
// Using protocol requirements from inside protocol extensions
// ----------------------------------------------------------------------------
protocol P1 {
@discardableResult
func reqP1a() -> Bool
}
extension P1 {
final func extP1a() -> Bool { return !reqP1a() }
final var extP1b: Bool {
return self.reqP1a()
}
final var extP1c: Bool {
return extP1b && self.extP1a()
}
}
protocol P2 {
associatedtype AssocP2 : P1
func reqP2a() -> AssocP2
}
extension P2 {
final func extP2a() -> AssocP2? { return reqP2a() }
final func extP2b() {
self.reqP2a().reqP1a()
}
final func extP2c() -> Self.AssocP2 { return extP2a()! }
}
protocol P3 {
associatedtype AssocP3 : P2
func reqP3a() -> AssocP3
}
extension P3 {
final func extP3a() -> AssocP3.AssocP2 {
return reqP3a().reqP2a()
}
}
protocol P4 {
associatedtype AssocP4
func reqP4a() -> AssocP4
}
// ----------------------------------------------------------------------------
// Using generics from inside protocol extensions
// ----------------------------------------------------------------------------
func acceptsP1<T : P1>(_ t: T) { }
extension P1 {
final func extP1d() { acceptsP1(self) }
}
func acceptsP2<T : P2>(_ t: T) { }
extension P2 {
final func extP2acceptsP1() { acceptsP1(reqP2a()) }
final func extP2acceptsP2() { acceptsP2(self) }
}
// Use of 'Self' as a return type within a protocol extension.
protocol SelfP1 {
associatedtype AssocType
}
protocol SelfP2 {
}
func acceptSelfP1<T, U : SelfP1 where U.AssocType == T>(_ t: T, _ u: U) -> T {
return t
}
extension SelfP1 {
final func tryAcceptSelfP1<Z : SelfP1 where Z.AssocType == Self>(_ z: Z) -> Self {
return acceptSelfP1(self, z)
}
}
// ----------------------------------------------------------------------------
// Initializers in protocol extensions
// ----------------------------------------------------------------------------
protocol InitP1 {
init(string: String)
}
extension InitP1 {
init(int: Int) { self.init(string: "integer") }
}
struct InitS1 : InitP1 {
init(string: String) { }
}
class InitC1 : InitP1 {
required init(string: String) { }
}
func testInitP1() {
var is1 = InitS1(int: 5)
is1 = InitS1(string: "blah") // check type
_ = is1
var ic1 = InitC1(int: 5)
ic1 = InitC1(string: "blah") // check type
_ = ic1
}
// ----------------------------------------------------------------------------
// Subscript in protocol extensions
// ----------------------------------------------------------------------------
protocol SubscriptP1 {
func readAt(_ i: Int) -> String
func writeAt(_ i: Int, string: String)
}
extension SubscriptP1 {
final subscript(i: Int) -> String {
get { return readAt(i) }
set(newValue) { writeAt(i, string: newValue) }
}
}
struct SubscriptS1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
struct SubscriptC1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
func testSubscriptP1(_ ss1: SubscriptS1, sc1: SubscriptC1,
i: Int, s: String) {
var ss1 = ss1
var sc1 = sc1
_ = ss1[i]
ss1[i] = s
_ = sc1[i]
sc1[i] = s
}
// ----------------------------------------------------------------------------
// Using protocol extensions on types that conform to the protocols.
// ----------------------------------------------------------------------------
struct S1 : P1 {
@discardableResult
func reqP1a() -> Bool { return true }
func once() -> Bool {
return extP1a() && extP1b
}
}
func useS1(_ s1: S1) -> Bool {
s1.reqP1a()
return s1.extP1a() && s1.extP1b
}
extension S1 {
func twice() -> Bool {
return extP1a() && extP1b
}
}
// ----------------------------------------------------------------------------
// Protocol extensions with additional requirements
// ----------------------------------------------------------------------------
extension P4 where Self.AssocP4 : P1 {
final func extP4a() { // expected-note 2 {{found this candidate}}
acceptsP1(reqP4a())
}
}
struct S4aHelper { }
struct S4bHelper : P1 {
func reqP1a() -> Bool { return true }
}
struct S4a : P4 {
func reqP4a() -> S4aHelper { return S4aHelper() }
}
struct S4b : P4 {
func reqP4a() -> S4bHelper { return S4bHelper() }
}
struct S4c : P4 {
func reqP4a() -> Int { return 0 }
}
struct S4d : P4 {
func reqP4a() -> Bool { return false }
}
extension P4 where Self.AssocP4 == Int {
final func extP4Int() { }
}
extension P4 where Self.AssocP4 == Bool {
final func extP4a() -> Bool { return reqP4a() } // expected-note 2 {{found this candidate}}
}
func testP4(_ s4a: S4a, s4b: S4b, s4c: S4c, s4d: S4d) {
s4a.extP4a() // expected-error{{ambiguous reference to member 'extP4a()'}}
s4b.extP4a() // ok
s4c.extP4a() // expected-error{{ambiguous reference to member 'extP4a()'}}
s4c.extP4Int() // okay
var b1 = s4d.extP4a() // okay, "Bool" version
b1 = true // checks type above
s4d.extP4Int() // expected-error{{'Int' is not convertible to 'AssocP4' (aka 'Bool')}}
_ = b1
}
// ----------------------------------------------------------------------------
// Using protocol extensions to satisfy requirements
// ----------------------------------------------------------------------------
protocol P5 {
func reqP5a()
}
// extension of P5 provides a witness for P6
extension P5 {
final func reqP6a() { reqP5a() }
}
protocol P6 {
func reqP6a()
}
// S6a uses P5.reqP6a
struct S6a : P5 {
func reqP5a() { }
}
extension S6a : P6 { }
// S6b uses P5.reqP6a
struct S6b : P5, P6 {
func reqP5a() { }
}
// S6c uses P5.reqP6a
struct S6c : P6 {
}
extension S6c : P5 {
func reqP5a() { }
}
// S6d does not use P5.reqP6a
struct S6d : P6 {
func reqP6a() { }
}
extension S6d : P5 {
func reqP5a() { }
}
protocol P7 {
associatedtype P7Assoc
func getP7Assoc() -> P7Assoc
}
struct P7FromP8<T> { }
protocol P8 {
associatedtype P8Assoc
func getP8Assoc() -> P8Assoc
}
// extension of P8 provides conformance to P7Assoc
extension P8 {
final func getP7Assoc() -> P7FromP8<P8Assoc> { return P7FromP8() }
}
// Okay, P7 requirements satisfied by P8
struct P8a : P8, P7 {
func getP8Assoc() -> Bool { return true }
}
func testP8a(_ p8a: P8a) {
var p7 = p8a.getP7Assoc()
p7 = P7FromP8<Bool>() // okay, check type of above
_ = p7
}
// Okay, P7 requirements explicitly specified
struct P8b : P8, P7 {
func getP7Assoc() -> Int { return 5 }
func getP8Assoc() -> Bool { return true }
}
func testP8b(_ p8b: P8b) {
var p7 = p8b.getP7Assoc()
p7 = 17 // check type of above
_ = p7
}
protocol PConforms1 {
}
extension PConforms1 {
final func pc2() { } // expected-note{{candidate exactly matches}}
}
protocol PConforms2 : PConforms1, MakePC2Ambiguous {
func pc2() // expected-note{{multiple matching functions named 'pc2()' with type '() -> ()'}}
}
protocol MakePC2Ambiguous {
}
extension MakePC2Ambiguous {
final func pc2() { } // expected-note{{candidate exactly matches}}
}
struct SConforms2a : PConforms2 { } // expected-error{{type 'SConforms2a' does not conform to protocol 'PConforms2'}}
struct SConforms2b : PConforms2 {
func pc2() { }
}
// Satisfying requirements via protocol extensions for fun and profit
protocol _MySeq { }
protocol MySeq : _MySeq {
associatedtype Generator : IteratorProtocol
func myGenerate() -> Generator
}
protocol _MyCollection : _MySeq {
associatedtype Index : Strideable
var myStartIndex : Index { get }
var myEndIndex : Index { get }
associatedtype _Element
subscript (i: Index) -> _Element { get }
}
protocol MyCollection : _MyCollection {
}
struct MyIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
struct OtherIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
extension _MyCollection {
final func myGenerate() -> MyIndexedIterator<Self> {
return MyIndexedIterator(container: self, index: self.myEndIndex)
}
}
struct SomeCollection1 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
}
struct SomeCollection2 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
func myGenerate() -> OtherIndexedIterator<SomeCollection2> {
return OtherIndexedIterator(container: self, index: self.myEndIndex)
}
}
func testSomeCollections(_ sc1: SomeCollection1, sc2: SomeCollection2) {
var mig = sc1.myGenerate()
mig = MyIndexedIterator(container: sc1, index: sc1.myStartIndex)
_ = mig
var ig = sc2.myGenerate()
ig = MyIndexedIterator(container: sc2, index: sc2.myStartIndex) // expected-error{{cannot invoke initializer for type 'MyIndexedIterator<_>' with an argument list of type '(container: SomeCollection2, index: Int)'}}
// expected-note @-1 {{expected an argument list of type '(container: C, index: C.Index)'}}
_ = ig
}
public protocol PConforms3 {}
extension PConforms3 {
final public var z: Int {
return 0
}
}
public protocol PConforms4 : PConforms3 {
var z: Int { get }
}
struct PConforms4Impl : PConforms4 {}
let pc4z = PConforms4Impl().z
// rdar://problem/20608438
protocol PConforms5 {
func f() -> Int
}
protocol PConforms6 : PConforms5 {}
extension PConforms6 {
final func f() -> Int { return 42 }
}
func test<T: PConforms6>(_ x: T) -> Int { return x.f() }
struct PConforms6Impl : PConforms6 { }
// Extensions of a protocol that directly satisfy requirements (i.e.,
// default implementations hack N+1).
protocol PConforms7 {
func method()
var property: Int { get }
subscript (i: Int) -> Int { get }
}
extension PConforms7 {
final func method() { }
final var property: Int { return 5 }
final subscript (i: Int) -> Int { return i }
}
struct SConforms7a : PConforms7 { }
protocol PConforms8 {
associatedtype Assoc
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms8 {
final func method() -> Int { return 5 }
final var property: Int { return 5 }
final subscript (i: Int) -> Int { return i }
}
struct SConforms8a : PConforms8 { }
struct SConforms8b : PConforms8 {
func method() -> String { return "" }
var property: String { return "" }
subscript (i: String) -> String { return i }
}
func testSConforms8b() {
let s: SConforms8b.Assoc = "hello"
_ = s
}
struct SConforms8c : PConforms8 {
func method() -> String { return "" }
}
func testSConforms8c() {
let s: SConforms8c.Assoc = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Assoc' (aka 'Int')}}
_ = s
let i: SConforms8c.Assoc = 5
_ = i
}
protocol DefaultInitializable {
init()
}
extension String : DefaultInitializable { }
extension Int : DefaultInitializable { }
protocol PConforms9 {
associatedtype Assoc : DefaultInitializable // expected-note{{protocol requires nested type 'Assoc'}}
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms9 {
final func method() -> Self.Assoc { return Assoc() }
final var property: Self.Assoc { return Assoc() }
final subscript (i: Self.Assoc) -> Self.Assoc { return Assoc() }
}
struct SConforms9a : PConforms9 { // expected-error{{type 'SConforms9a' does not conform to protocol 'PConforms9'}}
}
struct SConforms9b : PConforms9 {
typealias Assoc = Int
}
func testSConforms9b(_ s9b: SConforms9b) {
var p = s9b.property
p = 5
_ = p
}
struct SConforms9c : PConforms9 {
typealias Assoc = String
}
func testSConforms9c(_ s9c: SConforms9c) {
var p = s9c.property
p = "hello"
_ = p
}
struct SConforms9d : PConforms9 {
func method() -> Int { return 5 }
}
func testSConforms9d(_ s9d: SConforms9d) {
var p = s9d.property
p = 6
_ = p
}
protocol PConforms10 {}
extension PConforms10 {
final func f() {}
}
protocol PConforms11 {
func f()
}
struct SConforms11 : PConforms10, PConforms11 {}
// ----------------------------------------------------------------------------
// Typealiases in protocol extensions.
// ----------------------------------------------------------------------------
// Basic support
protocol PTypeAlias1 {
associatedtype AssocType1
}
extension PTypeAlias1 {
typealias ArrayOfAssocType1 = [AssocType1]
}
struct STypeAlias1a: PTypeAlias1 {
typealias AssocType1 = Int
}
struct STypeAlias1b<T>: PTypeAlias1 {
typealias AssocType1 = T
}
func testPTypeAlias1() {
var a: STypeAlias1a.ArrayOfAssocType1 = []
a.append(1)
var b: STypeAlias1b<String>.ArrayOfAssocType1 = []
b.append("hello")
}
// Defaulted implementations to satisfy a requirement.
struct TypeAliasHelper<T> { }
protocol PTypeAliasSuper2 {
}
extension PTypeAliasSuper2 {
final func foo() -> TypeAliasHelper<Self> { return TypeAliasHelper() }
}
protocol PTypeAliasSub2 : PTypeAliasSuper2 {
associatedtype Helper
func foo() -> Helper
}
struct STypeAliasSub2a : PTypeAliasSub2 { }
struct STypeAliasSub2b<T, U> : PTypeAliasSub2 { }
// ----------------------------------------------------------------------------
// Partial ordering of protocol extension members
// ----------------------------------------------------------------------------
// Partial ordering between members of protocol extensions and members
// of concrete types.
struct S1b : P1 {
func reqP1a() -> Bool { return true }
func extP1a() -> Int { return 0 }
}
func useS1b(_ s1b: S1b) {
var x = s1b.extP1a() // uses S1b.extP1a due to partial ordering
x = 5 // checks that "x" deduced to "Int" above
_ = x
var _: Bool = s1b.extP1a() // still uses P1.ext1Pa due to type annotation
}
// Partial ordering between members of protocol extensions for
// different protocols.
protocol PInherit1 { }
protocol PInherit2 : PInherit1 { }
protocol PInherit3 : PInherit2 { }
protocol PInherit4 : PInherit2 { }
extension PInherit1 {
final func order1() -> Int { return 0 }
}
extension PInherit2 {
final func order1() -> Bool { return true }
}
extension PInherit3 {
final func order1() -> Double { return 1.0 }
}
extension PInherit4 {
final func order1() -> String { return "hello" }
}
struct SInherit1 : PInherit1 { }
struct SInherit2 : PInherit2 { }
struct SInherit3 : PInherit3 { }
struct SInherit4 : PInherit4 { }
func testPInherit(_ si2 : SInherit2, si3: SInherit3, si4: SInherit4) {
var b1 = si2.order1() // PInherit2.order1
b1 = true // check that the above returned Bool
_ = b1
var d1 = si3.order1() // PInherit3.order1
d1 = 3.14159 // check that the above returned Double
_ = d1
var s1 = si4.order1() // PInherit4.order1
s1 = "hello" // check that the above returned String
_ = s1
// Other versions are still visible, since they may have different
// types.
b1 = si3.order1() // PInherit2.order1
var _: Int = si3.order1() // PInherit1.order1
}
protocol PConstrained1 {
associatedtype AssocTypePC1
}
extension PConstrained1 {
final func pc1() -> Int { return 0 }
}
extension PConstrained1 where AssocTypePC1 : PInherit2 {
final func pc1() -> Bool { return true }
}
extension PConstrained1 where Self.AssocTypePC1 : PInherit3 {
final func pc1() -> String { return "hello" }
}
struct SConstrained1 : PConstrained1 {
typealias AssocTypePC1 = SInherit1
}
struct SConstrained2 : PConstrained1 {
typealias AssocTypePC1 = SInherit2
}
struct SConstrained3 : PConstrained1 {
typealias AssocTypePC1 = SInherit3
}
func testPConstrained1(_ sc1: SConstrained1, sc2: SConstrained2,
sc3: SConstrained3) {
var i = sc1.pc1() // PConstrained1.pc1
i = 17 // checks type of above
_ = i
var b = sc2.pc1() // PConstrained1 (with PInherit2).pc1
b = true // checks type of above
_ = b
var s = sc3.pc1() // PConstrained1 (with PInherit3).pc1
s = "hello" // checks type of above
_ = s
}
protocol PConstrained2 {
associatedtype AssocTypePC2
}
protocol PConstrained3 : PConstrained2 {
}
extension PConstrained2 where Self.AssocTypePC2 : PInherit1 {
final func pc2() -> Bool { return true }
}
extension PConstrained3 {
final func pc2() -> String { return "hello" }
}
struct SConstrained3a : PConstrained3 {
typealias AssocTypePC2 = Int
}
struct SConstrained3b : PConstrained3 {
typealias AssocTypePC2 = SInherit3
}
func testSConstrained3(_ sc3a: SConstrained3a, sc3b: SConstrained3b) {
var s = sc3a.pc2() // PConstrained3.pc2
s = "hello"
_ = s
_ = sc3b.pc2()
s = sc3b.pc2()
var _: Bool = sc3b.pc2()
}
extension PConstrained3 where AssocTypePC2 : PInherit1 { }
// Extending via a superclass constraint.
class Superclass {
func foo() { }
static func bar() { }
typealias Foo = Int
}
protocol PConstrained4 { }
extension PConstrained4 where Self : Superclass {
final func testFoo() -> Foo {
foo()
self.foo()
return Foo(5)
}
final static func testBar() {
bar()
self.bar()
}
}
protocol PConstrained5 { }
protocol PConstrained6 {
associatedtype Assoc
func foo()
}
protocol PConstrained7 { }
extension PConstrained6 {
final var prop1: Int { return 0 }
final var prop2: Int { return 0 } // expected-note{{'prop2' previously declared here}}
final subscript (key: Int) -> Int { return key }
final subscript (key: Double) -> Double { return key } // expected-note{{'subscript' previously declared here}}
}
extension PConstrained6 {
final var prop2: Int { return 0 } // expected-error{{invalid redeclaration of 'prop2'}}
final subscript (key: Double) -> Double { return key } // expected-error{{invalid redeclaration of 'subscript'}}
}
extension PConstrained6 where Assoc : PConstrained5 {
final var prop1: Int { return 0 } // okay
final var prop3: Int { return 0 } // expected-note{{'prop3' previously declared here}}
final subscript (key: Int) -> Int { return key } // ok
final subscript (key: String) -> String { return key } // expected-note{{'subscript' previously declared here}}
final func foo() { } // expected-note{{'foo()' previously declared here}}
}
extension PConstrained6 where Assoc : PConstrained5 {
final var prop3: Int { return 0 } // expected-error{{invalid redeclaration of 'prop3'}}
final subscript (key: String) -> String { return key } // expected-error{{invalid redeclaration of 'subscript'}}
final func foo() { } // expected-error{{invalid redeclaration of 'foo()'}}
}
extension PConstrained6 where Assoc : PConstrained7 {
final var prop1: Int { return 0 } // okay
final subscript (key: Int) -> Int { return key } // okay
final func foo() { } // okay
}
extension PConstrained6 where Assoc == Int {
final var prop4: Int { return 0 }
final subscript (key: Character) -> Character { return key }
final func foo() { } // okay
}
extension PConstrained6 where Assoc == Double {
final var prop4: Int { return 0 } // okay
final subscript (key: Character) -> Character { return key } // okay
final func foo() { } // okay
}
// Interaction between RawRepresentable and protocol extensions.
public protocol ReallyRaw : RawRepresentable {
}
public extension ReallyRaw where RawValue: SignedInteger {
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
}
enum Foo : Int, ReallyRaw {
case a = 0
}
// ----------------------------------------------------------------------------
// Semantic restrictions
// ----------------------------------------------------------------------------
// Extension cannot have an inheritance clause.
protocol BadProto1 { }
protocol BadProto2 { }
extension BadProto1 : BadProto2 { } // expected-error{{extension of protocol 'BadProto1' cannot have an inheritance clause}}
extension BadProto2 {
struct S { } // expected-error{{type 'S' cannot be defined within a protocol extension}}
class C { } // expected-error{{type 'C' cannot be defined within a protocol extension}}
enum E { } // expected-error{{type 'E' cannot be defined within a protocol extension}}
}
extension BadProto1 {
func foo() { }
var prop: Int { return 0 }
subscript (i: Int) -> String {
return "hello"
}
}
protocol BadProto3 { }
typealias BadProto4 = BadProto3
extension BadProto4 { } // expected-error{{protocol 'BadProto3' in the module being compiled cannot be extended via a typealias}}{{11-20=BadProto3}}
typealias RawRepresentableAlias = RawRepresentable
extension RawRepresentableAlias { } // okay
extension AnyObject { } // expected-error{{'AnyObject' protocol cannot be extended}}
// Members of protocol extensions cannot be overridden.
// rdar://problem/21075287
class BadClass1 : BadProto1 {
func foo() { }
override var prop: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
}
| apache-2.0 | 0af0946966ef70ae3ef9afef78f5adad | 22.683685 | 217 | 0.625709 | 3.668386 | false | false | false | false |
shadanan/mado | Antlr4Runtime/Sources/Antlr4/tree/AbstractParseTreeVisitor.swift | 1 | 5401 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
open class AbstractParseTreeVisitor<T>: ParseTreeVisitor<T> {
public override init() {
super.init()
}
/**
* {@inheritDoc}
*
* <p>The default implementation calls {@link org.antlr.v4.runtime.tree.ParseTree#accept} on the
* specified tree.</p>
*/
open override func visit(_ tree: ParseTree) -> T? {
return tree.accept(self)
}
/**
* {@inheritDoc}
*
* <p>The default implementation initializes the aggregate result to
* {@link #defaultResult defaultResult()}. Before visiting each child, it
* calls {@link #shouldVisitNextChild shouldVisitNextChild}; if the result
* is {@code false} no more children are visited and the current aggregate
* result is returned. After visiting a child, the aggregate result is
* updated by calling {@link #aggregateResult aggregateResult} with the
* previous aggregate result and the result of visiting the child.</p>
*
* <p>The default implementation is not safe for use in visitors that modify
* the tree structure. Visitors that modify the tree should override this
* method to behave properly in respect to the specific algorithm in use.</p>
*/
open override func visitChildren(_ node: RuleNode) -> T? {
var result: T? = defaultResult()
let n: Int = node.getChildCount()
for i in 0..<n {
if !shouldVisitNextChild(node, result) {
break
}
let c: ParseTree? = node.getChild(i) as? ParseTree
let childResult: T? = c?.accept(self)
result = aggregateResult(result, childResult)
}
return result
}
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of
* {@link #defaultResult defaultResult}.</p>
*/
open override func visitTerminal(_ node: TerminalNode) -> T? {
return defaultResult()
}
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of
* {@link #defaultResult defaultResult}.</p>
*/
override
open func visitErrorNode(_ node: ErrorNode) -> T? {
return defaultResult()
}
/**
* Gets the default value returned by visitor methods. This value is
* returned by the default implementations of
* {@link #visitTerminal visitTerminal}, {@link #visitErrorNode visitErrorNode}.
* The default implementation of {@link #visitChildren visitChildren}
* initializes its aggregate result to this value.
*
* <p>The base implementation returns {@code null}.</p>
*
* @return The default value returned by visitor methods.
*/
open func defaultResult() -> T? {
return nil
}
/**
* Aggregates the results of visiting multiple children of a node. After
* either all children are visited or {@link #shouldVisitNextChild} returns
* {@code false}, the aggregate value is returned as the result of
* {@link #visitChildren}.
*
* <p>The default implementation returns {@code nextResult}, meaning
* {@link #visitChildren} will return the result of the last child visited
* (or return the initial value if the node has no children).</p>
*
* @param aggregate The previous aggregate value. In the default
* implementation, the aggregate value is initialized to
* {@link #defaultResult}, which is passed as the {@code aggregate} argument
* to this method after the first child node is visited.
* @param nextResult The result of the immediately preceeding call to visit
* a child node.
*
* @return The updated aggregate result.
*/
open func aggregateResult(_ aggregate: T?, _ nextResult: T?) -> T? {
return nextResult
}
/**
* This method is called after visiting each child in
* {@link #visitChildren}. This method is first called before the first
* child is visited; at that point {@code currentResult} will be the initial
* value (in the default implementation, the initial value is returned by a
* call to {@link #defaultResult}. This method is not called after the last
* child is visited.
*
* <p>The default implementation always returns {@code true}, indicating that
* {@code visitChildren} should only return after all children are visited.
* One reason to override this method is to provide a "short circuit"
* evaluation option for situations where the result of visiting a single
* child has the potential to determine the result of the visit operation as
* a whole.</p>
*
* @param node The {@link org.antlr.v4.runtime.tree.RuleNode} whose children are currently being
* visited.
* @param currentResult The current aggregate result of the children visited
* to the current point.
*
* @return {@code true} to continue visiting children. Otherwise return
* {@code false} to stop visiting children and immediately return the
* current aggregate result from {@link #visitChildren}.
*/
open func shouldVisitNextChild(_ node: RuleNode, _ currentResult: T?) -> Bool {
return true
}
}
| mit | 02af619cdd0592882765ad9e72dd1970 | 37.035211 | 100 | 0.653212 | 4.600511 | false | false | false | false |
TomasVanRoose/SportsCalendarPlanner | SportsCalendarPlanner/TeamsViewController.swift | 1 | 2860 | //
// TeamsViewController.swift
// SportsCalendarPlanner
//
// Created by Tomas Van Roose on 04/09/16.
// Copyright © 2016 Tomas Van Roose. All rights reserved.
//
import UIKit
import CoreData
class TeamsViewController: CoreDataTableViewController {
var season : SeasonMO!
var managedObjectContext: NSManagedObjectContext?
override func viewDidLoad() {
super.viewDidLoad()
self.title = season.name
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let team = self.fetchedResultsController.objectAtIndexPath(indexPath) as! TeamMO
let detailNavController = self.splitViewController?.viewControllers.last as? UINavigationController
let detailViewController = detailNavController?.topViewController
if let detail = detailViewController as? CalendarPresenterViewController {
detail.selectTeam(team)
}
}
override func initializeFetchedResultsController() {
let request = NSFetchRequest(entityName: "Team")
request.predicate = NSPredicate(format: "season == %@", self.season!)
let nameSort = NSSortDescriptor(key: "name", ascending: true)
request.sortDescriptors = [ nameSort ]
self.fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
self.fetchedResultsController.delegate = self
do {
try self.fetchedResultsController.performFetch()
} catch {
fatalError("Failed to initialize FetchedResultsController: \(error)")
}
}
override func configureCell(indexPath: NSIndexPath) -> (UITableViewCell) {
let cell = self.tableView.dequeueReusableCellWithIdentifier("team")!
let team = self.fetchedResultsController.objectAtIndexPath(indexPath) as! TeamMO
cell.textLabel!.text! = team.name!
return cell
}
func didInputTeamName(name : String) {
_ = TeamMO.createNewTeam(name, season: self.season, forContext: self.managedObjectContext!)
do {
try self.managedObjectContext!.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destination = segue.destinationViewController as? UINavigationController {
if let inputController = destination.topViewController as? InputTableViewController {
inputController.didInputFunc = didInputTeamName
}
}
}
}
| mit | a89e465c477ef5cfe16874febf7a2f17 | 31.123596 | 180 | 0.653026 | 5.799189 | false | false | false | false |
ennioma/arek | code/Classes/Permissions/ArekHealth.swift | 1 | 4041 | //
// ArekHealth.swift
// Arek
//
// Copyright (c) 2016 Ennio Masi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import HealthKit
open class ArekHealth: ArekBasePermission, ArekPermissionProtocol {
public struct ArekHealthConfiguration {
public var hkObjectType: HKObjectType?
public var hkSampleTypesToShare: Set<HKSampleType>?
public var hkSampleTypesToRead: Set<HKObjectType>?
public init(hkObjectType: HKObjectType? = nil, hkSampleTypesToShare: Set<HKSampleType>? = nil, hkSampleTypesToRead: Set<HKObjectType>? = nil) {
self.hkObjectType = hkObjectType
self.hkSampleTypesToShare = hkSampleTypesToShare
self.hkSampleTypesToRead = hkSampleTypesToRead
}
func healthAvailable() -> Bool {
return HKHealthStore.isHealthDataAvailable()
}
}
public var identifier: String = "ArekHealth"
var healthConfiguration: ArekHealthConfiguration?
public init() {
super.init(identifier: self.identifier)
}
public init(configuration: ArekConfiguration? = nil, initialPopupData: ArekPopupData? = nil, reEnablePopupData: ArekPopupData? = nil, arekHealthConfiguration: ArekHealthConfiguration) {
self.healthConfiguration = arekHealthConfiguration
super.init(configuration: configuration, initialPopupData: initialPopupData, reEnablePopupData: reEnablePopupData)
}
open func status(completion: @escaping ArekPermissionResponse) {
guard let objectType = self.healthConfiguration?.hkObjectType else {
return completion(.notDetermined)
}
switch HKHealthStore().authorizationStatus(for: objectType) {
case .notDetermined:
return completion(.notDetermined)
case .sharingDenied:
return completion(.denied)
case .sharingAuthorized:
return completion(.authorized)
}
}
open func askForPermission(completion: @escaping ArekPermissionResponse) {
guard
let healthConfiguration = self.healthConfiguration,
self.healthConfiguration?.healthAvailable() == true else {
print("[🚨 Arek 🚨] 📈 no permissions specified 🤔")
return completion(.notDetermined)
}
HKHealthStore().requestAuthorization(toShare: healthConfiguration.hkSampleTypesToShare, read: healthConfiguration.hkSampleTypesToRead) { (granted, error) in
if let error = error {
print("[🚨 Arek 🚨] 📈 permission not determined 🤔 error: \(error)")
return completion(.notDetermined)
}
if granted {
print("[🚨 Arek 🚨] 📈 permission authorized by user ✅")
return completion(.authorized)
}
print("[🚨 Arek 🚨] 📈 permission denied by user ⛔️")
return completion(.denied)
}
}
}
| mit | 5050e4dbb1dad891e175322c171a9d05 | 39.744898 | 189 | 0.679439 | 4.923551 | false | true | false | false |
wesj/firefox-ios-1 | Storage/SQL/JoinedFaviconsHistoryTable.swift | 1 | 5377 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
private let FaviconVisits = "faviconSiteMapping"
// This isn't a real table. Its an abstraction around the history and visits table
// to simpify queries that should join both tables. It also handles making sure that
// inserts/updates/delete update both tables appropriately. i.e.
// 1.) Deleteing a history entry here will also remove all visits to it
// 2.) Adding a visit here will ensure that a site exists for the visit
// 3.) Updates currently only update site information.
class JoinedFaviconsHistoryTable<T>: GenericTable<(site: Site?, icon: Favicon?)> {
private let favicons = FaviconsTable<Favicon>()
private let history = HistoryTable<Site>()
override var name: String { return FaviconVisits }
override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteId INTEGER NOT NULL, " +
"faviconId INTEGER NOT NULL" }
override func getInsertAndArgs(inout item: Type) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
args.append(item.site!.id)
args.append(item.icon!.id)
return ("INSERT INTO \(name) (siteId, faviconId) VALUES (?,?)", args)
}
override func getUpdateAndArgs(inout item: Type) -> (String, [AnyObject?])? {
// We don't support updates here...
return nil
}
override func getDeleteAndArgs(inout item: Type?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
var sql = "DELETE FROM \(FaviconVisits)"
if let item = item {
sql += " WHERE"
if let site = item.site {
args.append(site.id!)
sql += " siteId = ?"
}
if let icon = item.icon {
args.append(icon.id!)
sql += " faviconId = ?"
}
}
println("Delete \(sql) \(args)")
return (sql, args)
}
override func create(db: SQLiteDBConnection, version: Int) -> Bool {
history.create(db, version: version)
favicons.create(db, version: version)
return super.create(db, version: version)
}
override func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
if history.updateTable(db, from: from, to: to) && favicons.updateTable(db, from: from, to: to) {
return super.updateTable(db, from: from, to: to)
}
return false
}
override func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
if let (site, favicon) = item {
if let site = site {
history.insertOrUpdate(db, obj: site)
} else {
println("Must have a site to insert in \(name)")
return -1
}
if let icon = favicon {
favicons.insertOrUpdate(db, obj: icon)
} else {
println("Must have an icon to insert in \(name)")
return -1
}
let args: [AnyObject?] = [item?.icon?.id, item?.site?.id]
let c = db.executeQuery("SELECT * FROM \(FaviconVisits) WHERE faviconId = ? AND siteId = ?", factory: {
(row) -> Type in return (nil, nil)
}, withArgs: args)
if c.count > 0 {
return -1
}
return super.insert(db, item: item, err: &err)
}
return -1
}
override func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
if let (site, favicon) = item {
history.update(db, item: site, err: &err)
favicons.update(db, item: favicon, err: &err)
return super.update(db, item: item, err: &err)
}
return -1
}
func factory(result: SDRow) -> (Site, Favicon) {
let site = Site(url: result["siteUrl"] as String, title: result["title"] as String)
site.guid = result["guid"] as? String
site.id = result["historyId"] as? Int
let favicon = Favicon(url: result["iconUrl"] as String,
date: NSDate(timeIntervalSince1970: result["date"] as Double),
type: IconType(rawValue: result["iconType"] as Int)!)
favicon.id = result["iconId"] as? Int
return (site, favicon)
}
override func query(db: SQLiteDBConnection, options: QueryOptions?) -> Cursor {
var args = [AnyObject?]()
var sql = "SELECT \(history.name).id as historyId, \(history.name).url as siteUrl, title, guid, " +
"\(favicons.name).id as iconId, \(favicons.name).url as iconUrl, date, \(favicons.name).type as iconType FROM \(history.name) " +
"INNER JOIN \(FaviconVisits) ON \(history.name).id = \(FaviconVisits).siteId " +
"INNER JOIN \(favicons.name) ON \(favicons.name).id = \(FaviconVisits).faviconId";
if let filter: AnyObject = options?.filter {
sql += " WHERE siteUrl LIKE ?"
args.append("%\(filter)%")
}
// For now we always look for the biggest one
sql += " ORDER BY \(favicons.name).width DESC"
return db.executeQuery(sql, factory: factory, withArgs: args)
}
}
| mpl-2.0 | 663cc323632a94b10e2c04b1dec60d28 | 37.963768 | 147 | 0.578575 | 4.250593 | false | false | false | false |
jwamin/Xnpm | Xnpm/PackageAnalyser.swift | 1 | 2520 | //
// PackageAnalyser.swift
// Xnpm
//
// Created by Joss Manger on 6/17/17.
// Copyright © 2017 Joss Manger. All rights reserved.
//
import Cocoa
class PackageAnalyser: NSObject {
var url:URL!
var dictionary:[String:Any]!
var valid:Bool = true
var error:NSError?
dynamic var packageTitle:String!
dynamic var author:String!
dynamic var version:String!
dynamic var license:String!
dynamic var packageDescription:String!
dynamic var repoLink:URL!
dynamic var scripts:NSArray!
dynamic var gitBranch:String!
init(packageUrl:URL?) {
super.init()
url = packageUrl
processPackage()
}
func processPackage(){
do{
let str = try String(contentsOf: url, encoding: .utf8)
let data = str.data(using: .utf8)!
do {
let parsedData = try JSONSerialization.jsonObject(with: data) as! [String:Any]
dictionary = parsedData
//print(dictionary)
processDict()
} catch let error as NSError {
print("bad form error")
self.error = error
self.valid = false
}
} catch {
print("didnt work")
}
}
func processDict(){
var dict = dictionary["scripts"] as! [String:String]
dict.removeValue(forKey: "postinstall")
scripts = NSArray(array: Array(dict.keys))
packageTitle = dictionary["name"] as? String ?? "none"
author = dictionary["author"] as? String ?? "none"
license = dictionary["license"] as? String ?? "none"
version = dictionary["version"] as? String ?? "none"
packageDescription = dictionary["description"] as? String ?? "none"
if let repository = dictionary["repository"] as? [String:String]{
repoLink = URL(string: repository["url"]!)
}
// print(packageTitle)
// print(author)
// print(license)
// print(version)
// print(packageDescription)
// print(repoLink)
// print(scripts)
}
func returndict()->[String:Any]{
return dictionary
}
func setBranch(branchString:String){
self.gitBranch = branchString
}
}
| mit | 74388578e93f06c4aa180708cc354015 | 24.19 | 94 | 0.519651 | 4.743879 | false | false | false | false |
qds-hoi/suracare | suracare/suracare/Core/Library/SwiftValidator/Rules/ISBNRule.swift | 1 | 6208 | //
// ISBNRule.swift
// Validator
//
// Created by Bhargav Gurlanka on 2/4/16.
// Copyright © 2016 jpotts18. All rights reserved.
//
import Foundation
/**
`ISBNRule` is a subclass of `Rule`. It is used to verify whether a field is a valid ISBN number.
*/
public class ISBNRule: Rule {
/// String that holds error message
private let message: String
/**
Initializes a `ISBNRule` object to verify that field has text that is a ISBN number.
- parameter message: String of error message.
- returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception.
*/
public init(message: String = "Enter valid ISBN number") {
self.message = message
}
/**
Method used to validate field.
- parameter value: String to checked for validation.
- returns: Boolean value. True if validation is successful; False if validation fails.
*/
public func validate(value: String) -> Bool {
guard let regex = try? NSRegularExpression(pattern: "[\\s-]", options: []) else {
fatalError("Invalid ISBN sanitizing regex")
}
let sanitized = regex.stringByReplacingMatchesInString(value, options: [], range: NSMakeRange(0, value.characters.count), withTemplate: "")
return ISBN10Validator().verify(sanitized) || ISBN13Validator().verify(sanitized)
}
/**
Method used to dispaly error message when field fails validation.
- returns: String of error message.
*/
public func errorMessage() -> String {
return message;
}
}
/**
`ISBNValidator` defines the protocol that objects adopting it must implement.
*/
private protocol ISBNValidator {
/// Regular expression string
var regex: String { get }
/**
Method that actually verifies a ISBN number.
- parameter input: String that is to be validated against `ISBNRule`
- returns: A `Bool` that represents what happened during verification. `false` is returned if
it fails, `true` is returned if it was a success.
*/
func verify(input: String) -> Bool
/**
Method that verifies regular expression is valid.
- parameter input: String that holds ISBN number being validated.
- returns: A `Bool` that represents the status of the ISBN number. `false` if ISBN number
was not valid, `true` if it was valid.
*/
func checkRegex(input: String) -> Bool
/**
Method that verifies `ISBN` being validated is itself valid. It has to be either ISBN10
or ISBN13.
- parameter input: String that holds ISBN number being validated.
- returns: A `Bool` that represents the status of the ISBN number. `false` if ISBN number
was not valid, `true` if it was valid.
*/
func verifyChecksum(input: String) -> Bool
}
/**
`ISBNValidator` defines the extensions that are added to `ISBNValidator`.
*/
extension ISBNValidator {
/**
Method that actually verifies a ISBN number.
- parameter input: String that is to be validated against `ISBNRule`
- returns: A `Bool` that represents what happened during verification. `false` is returned if
it fails, `true` is returned if it was a success.
*/
func verify(input: String) -> Bool {
return checkRegex(input) && verifyChecksum(input)
}
/**
Method that verifies `ISBN` being validated is itself valid. It has to be either ISBN10
or ISBN13.
- parameter input: String that holds ISBN number being validated.
- returns: A `Bool` that represents the status of the ISBN number. `false` if ISBN number
was not valid, `true` if it was valid.
*/
func checkRegex(input: String) -> Bool {
guard let _ = input.rangeOfString(regex, options: [.RegularExpressionSearch, .AnchoredSearch]) else {
return false
}
return true
}
}
/**
`ISBN10Validator` is a struct that adopts the `ISBNValidator` protocol. Used to validate that
a field is an ISBN10 number.
*/
private struct ISBN10Validator: ISBNValidator {
/// Regular expression used to validate ISBN10 number
let regex = "^(?:[0-9]{9}X|[0-9]{10})$"
/**
Checks that a string is an ISBN10 number.
- parameter input: String that is checked for ISBN10 validation.
- returns: `true` if string is a valid ISBN10 and `false` if it is not.
*/
private func verifyChecksum(input: String) -> Bool {
var checksum = 0
for i in 0..<9 {
if let intCharacter = Int(String(input[input.startIndex.advancedBy(i)])) {
checksum += (i + 1) * intCharacter
}
}
if (input[input.startIndex.advancedBy(9)] == "X") {
checksum += 10 * 10
} else {
if let intCharacter = Int(String(input[input.startIndex.advancedBy(9)])) {
checksum += 10 * intCharacter
}
}
return ((checksum % 11) == 0)
}
}
/**
`ISBN13Validator` is a struct that adopts the `ISBNValidator` protocol. Used to validate that
a field is an ISBN13 number.
*/
private struct ISBN13Validator: ISBNValidator {
/// Regular expression used to validate ISBN13 number.
let regex = "^(?:[0-9]{13})$"
/**
Checks that a string is an ISBN13 number.
- parameter input: String that is checked for ISBN13 validation.
- returns: `true` if string is a valid ISBN13 and `false` if it is not.
*/
private func verifyChecksum(input: String) -> Bool {
let factor = [1, 3]
var checksum = 0
for i in 0..<12 {
if let intCharacter = Int(String(input[input.startIndex.advancedBy(i)])) {
print("\(factor[i%2]) * \(intCharacter)")
checksum += factor[i % 2] * intCharacter
}
}
if let lastInt = Int(String(input[input.startIndex.advancedBy(12)])) {
return (lastInt - ((10 - (checksum % 10)) % 10) == 0)
}
return false
}
} | mit | dd1fb35c69964f8d690cdfad2257867c | 31.502618 | 147 | 0.617206 | 4.292531 | false | false | false | false |
aijaz/icw1502 | playgrounds/Week05Homework.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift | 1 | 749 | //: [Previous](@previous) [Next](@next)
enum Planet:Int {
case Mercury = 1
case Venus
case Earth
case Mars
case Jupiter
case Saturn
case Uranus
case Neptune
case Pluto
}
var planet:Planet = .Mercury
planet
enum DistantObject:Int {
case Mercury = 36
case Venus = 67
case Earth = 93
case Mars = 228
case Jupiter = 778
case Saturn = 1427
case Uranus = 2871
case Neptune = 4497
case Pluto = 5913
}
enum ObjectInSpace:String {
case Mercury
case Venus
case Earth
case Mars
case Jupiter
case Saturn
case Uranus
case Neptune
case Pluto
}
var object:ObjectInSpace = .Mercury
object
object.rawValue
//: [Previous](@previous) [Next](@next)
| mit | 47dfccbf1324df4612f63e336cc2e3b6 | 13.403846 | 39 | 0.632844 | 3.921466 | false | false | false | false |
srn214/Floral | Floral/Pods/WCDB.swift/swift/source/core/interface/Update.swift | 1 | 5531 | /*
* Tencent is pleased to support the open source community by making
* WCDB available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of
* the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// The chain call for updating
public final class Update {
private var core: Core
private let statement = StatementUpdate()
private let keys: [CodingTableKeyBase]
/// The number of changed rows in the most recent call.
/// It should be called after executing successfully
public var changes: Int?
init(with core: Core, on propertyConvertibleList: [PropertyConvertible], andTable table: String) throws {
guard propertyConvertibleList.count > 0 else {
throw Error.reportInterface(tag: core.tag,
path: core.path,
operation: .update,
code: .misuse,
message: "Updating \(table) with empty property")
}
guard table.count > 0 else {
throw Error.reportInterface(tag: core.tag,
path: core.path,
operation: .update,
code: .misuse,
message: "Nil table name")
}
self.keys = propertyConvertibleList.asCodingTableKeys()
self.core = core
self.statement
.update(table: table)
.set(propertyConvertibleList.map { (propertyConvertible) -> StatementUpdate.ValueType in
return (propertyConvertible, Expression.bindParameter)
})
}
/// WINQ interface for SQL
///
/// - Parameter condition: Expression convertible
/// - Returns: `self`
@discardableResult
public func `where`(_ condition: Condition) -> Update {
statement.where(condition)
return self
}
/// WINQ interface for SQL
///
/// - Parameter orderList: Order convertible list
/// - Returns: `self`
@discardableResult
public func order(by orderList: OrderBy...) -> Update {
statement.order(by: orderList)
return self
}
/// WINQ interface for SQL
///
/// - Parameter orderList: Order convertible list
/// - Returns: `self`
@discardableResult
public func order(by orderList: [OrderBy]) -> Update {
statement.order(by: orderList)
return self
}
/// WINQ interface for SQL
///
/// - Parameters:
/// - begin: Expression convertible
/// - end: Expression convertible
/// - Returns: `self`
@discardableResult
public func limit(from begin: Limit, to end: Limit) -> Update {
statement.limit(from: begin, to: end)
return self
}
/// WINQ interface for SQL
///
/// - Parameter limit: Expression convertible
/// - Returns: `self`
@discardableResult
public func limit(_ limit: Limit) -> Update {
statement.limit(limit)
return self
}
/// WINQ interface for SQL
///
/// - Parameters:
/// - limit: Expression convertible
/// - offset: Expression convertible
/// - Returns: `self`
@discardableResult
public func limit(_ limit: Limit, offset: Offset) -> Update {
statement.limit(limit, offset: offset)
return self
}
/// Execute the update chain call with object.
///
/// - Parameter object: Table encodable object
/// - Throws: `Error`
public func execute<Object: TableEncodable>(with object: Object) throws {
let recyclableHandleStatement: RecyclableHandleStatement = try core.prepare(statement)
let handleStatement = recyclableHandleStatement.raw
let encoder = TableEncoder(keys, on: recyclableHandleStatement)
try object.encode(to: encoder)
try handleStatement.step()
changes = handleStatement.changes
}
/// Execute the update chain call with row.
///
/// - Parameter row: Column encodable row
/// - Throws: `Error`
public func execute(with row: [ColumnEncodable?]) throws {
let recyclableHandleStatement: RecyclableHandleStatement = try core.prepare(statement)
let handleStatement = recyclableHandleStatement.raw
for (index, value) in row.enumerated() {
let bindingIndex = index + 1
if let archivedValue = value?.archivedValue() {
handleStatement.bind(archivedValue, toIndex: bindingIndex)
} else {
handleStatement.bind(nil, toIndex: bindingIndex)
}
}
try handleStatement.step()
changes = handleStatement.changes
}
}
extension Update: CoreRepresentable {
/// The tag of the related database.
public var tag: Tag? {
return core.tag
}
/// The path of the related database.
public var path: String {
return core.path
}
}
| mit | 2b67f2886d223be537a10f64dac1ac94 | 32.521212 | 109 | 0.606039 | 4.817944 | false | false | false | false |
tkremenek/swift | test/SILOptimizer/enum_payload_modification_opt.swift | 18 | 2287 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -O -module-name=test %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test,swift_stdlib_no_asserts,optimized_stdlib
final class Storage {
var v : Int
init(_ v : Int) {
self.v = v
}
}
struct IntBox {
var s : Storage
init(_ x : Int) {
s = Storage(x)
}
var value: Int { return s.v }
mutating func increment(_ delta: Int = 1) {
if (!isKnownUniquelyReferenced(&s)) {
// We should never see this message
print("## copy on write")
s = Storage(s.v)
}
s.v += delta
}
}
enum E: CustomStringConvertible {
case value(IntBox)
case none
@inline(never)
mutating func simpleIncrement() {
switch self {
case .value(var i):
i.increment()
self = .value(i)
case .none:
break
}
}
@inline(never)
mutating func incrementWithControlFlow(_ n: Int, _ c: Bool) {
switch self {
case .value(var i):
i.increment()
for _ in [0..<n] {
print(" loop iter")
}
if c {
i.increment(10)
self = .value(i)
} else {
i.increment(20)
self = .value(i)
}
case .none:
break
}
}
var description: String {
switch self {
case .value(let i):
return i.s.v.description
case .none:
return "none"
}
}
}
struct ContainingStruct {
var e: E = .value(IntBox(27))
@inline(never)
mutating func doSomething() {
switch self.e {
case .value(var i):
i.increment()
self.e = .value(i)
case .none:
break
}
}
}
// CHECK: simpleIncrement start
print("simpleIncrement start")
var e1 = E.value(IntBox(27))
e1.simpleIncrement()
// CHECK-NEXT: simpleIncrement end: 28
print("simpleIncrement end: \(e1)")
// CHECK-NEXT: incrementWithControlFlow start
print("incrementWithControlFlow start")
var e2 = E.value(IntBox(27))
// CHECK-NEXT: loop iter
e2.incrementWithControlFlow(1, true)
// CHECK-NEXT: incrementWithControlFlow end: 38
print("incrementWithControlFlow end: \(e2)")
// CHECK-NEXT: ContainingStruct start
print("ContainingStruct start")
var s = ContainingStruct()
s.doSomething()
// CHECK-NEXT: ContainingStruct end: 28
print("ContainingStruct end: \(s.e)")
| apache-2.0 | 40c78713bca0b3e3557b1a92bb0b2cb5 | 18.886957 | 69 | 0.60516 | 3.333819 | false | false | false | false |
forwk1990/PropertyExchange | PropertyExchange/YPBankTableViewCell.swift | 1 | 3213 | //
// YPBankTableViewCell.swift
// PropertyExchange
//
// Created by itachi on 16/10/10.
// Copyright © 2016年 com.itachi. All rights reserved.
//
import UIKit
class YPBankTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.createSubviews()
self.createLayoutConstraints()
}
public class func cell(withTableView tableView:UITableView, forReuseIdentifier reuseIdentifier:String) -> UITableViewCell?{
var tableViewCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)
if(tableViewCell == nil){
tableViewCell = YPBankTableViewCell(style: .default,reuseIdentifier: reuseIdentifier)
tableViewCell?.selectionStyle = UITableViewCellSelectionStyle.none
}
tableViewCell?.contentView.backgroundColor = UIColor.colorWithHex(hex: 0xFFFFFF)
tableViewCell?.backgroundColor = UIColor.colorWithHex(hex: 0xFFFFFF)
return tableViewCell
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func createSubviews(){
self.contentView.addSubview(self.titleImageView)
self.contentView.addSubview(self.titleLabel)
self.contentView.addSubview(self.titleDetailLabel)
self.contentView.addSubview(self.indicatorImageView)
}
lazy var titleImageView:UIImageView = {
let imageView = UIImageView()
return imageView
}()
lazy var titleLabel:UILabel = {
let label = UILabel()
label.textColor = UIColor.colorWithHex(hex: 0x1C1F26)
label.font = UIFont.systemFont(ofSize: 14)
return label
}()
lazy var titleDetailLabel:UILabel = {
let label = UILabel()
label.textColor = UIColor.colorWithHex(hex: 0x999999)
label.font = UIFont.systemFont(ofSize: 10)
return label
}()
lazy var indicatorImageView:UIImageView = {
let imageView = UIImageView(image:UIImage(named: "right"))
return imageView
}()
public var model:(title:String,controller:UIViewController.Type,detail:String,image:String)?{
didSet{
guard let _model = self.model else {
return
}
self.titleImageView.image = UIImage(named: _model.image)
self.titleLabel.text = _model.title
self.titleDetailLabel.text = _model.detail
}
}
fileprivate func createLayoutConstraints(){
self.titleImageView.snp.makeConstraints { (make) -> Void in
make.width.height.equalTo(32)
make.left.equalTo(self.contentView).offset(18)
make.centerY.equalTo(self.contentView)
}
self.titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(self.titleImageView.snp.right).offset(15)
make.top.equalTo(self.titleImageView)
}
self.titleDetailLabel.snp.makeConstraints { (make) in
make.left.equalTo(self.titleLabel)
make.bottom.equalTo(self.titleImageView)
}
self.indicatorImageView.snp.makeConstraints { (make) in
make.right.equalTo(self.contentView).offset(-18)
make.centerY.equalTo(self.contentView)
make.width.equalTo(10)
make.height.equalTo(16)
}
}
}
| mit | 3f8cb3c1aef91654983ce668bf948d25 | 29 | 125 | 0.708411 | 4.39726 | false | false | false | false |
tluquet3/MonTennis | MonTennis/Profile/ClassementTableViewController.swift | 1 | 2575 | //
// ClassementTableViewController.swift
// MonTennis
//
// Created by Thomas Luquet on 30/06/2015.
// Copyright (c) 2015 Thomas Luquet. All rights reserved.
//
import UIKit
class ClassementTableViewController: UITableViewController{
private var selectedClassement : String!
private let pickerData = ["NC","40","30/5","30/4","30/3","30/2","30/1","30","15/5","15/4","15/3","15/2","15/1","15","5/6","4/6","3/6","2/6","1/6","0","-2/6","-4/6","-15","N°60-100","N°40-60","1ère Serie"]
override func viewDidLoad() {
super.viewDidLoad()
self.selectedClassement = barCtrl.user.classement.string
let indexPath = NSIndexPath(forRow: barCtrl.user.classement.value, inSection: 0)
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "saveDetails"{
if let cell = sender as? UITableViewCell {
selectedClassement = cell.textLabel?.text
barCtrl.getNSuserDefaults().setInteger(Classement(stringValue: selectedClassement).value, forKey: "classement")
barCtrl.user.classement = Classement(stringValue: selectedClassement)
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return pickerData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("classementCell", forIndexPath: indexPath)
cell.textLabel?.text = pickerData[indexPath.row]
if(indexPath.row == barCtrl.user.classement.value){
cell.textLabel?.textColor = UIColor.orangeColor()
cell.accessoryType = .Checkmark
}else{
cell.accessoryType = .None
cell.textLabel?.textColor = UIColor.blackColor()
}
return cell
}
}
| apache-2.0 | 2178bea77e38ae35ba19821b854edc7b | 37.38806 | 208 | 0.633359 | 4.642599 | false | false | false | false |
Allow2CEO/browser-ios | Client/Frontend/Widgets/Toolbar.swift | 1 | 4446 | /* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import SnapKit
import UIKit
let LeftSwipeToolbarNotification = Notification.Name("LeftSwipeToolbarNotification")
let RightSwipeToolbarNotification = Notification.Name("RightSwipeToolbarNotification")
class Toolbar : UIView {
var drawTopBorder = false
var drawBottomBorder = false
var drawSeperators = false
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
// Allow the view to redraw itself on rotation changes
contentMode = UIViewContentMode.redraw
let swipes = UIPanGestureRecognizer(target: self, action: #selector(handleSwipes(gesture:)))
addGestureRecognizer(swipes)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func drawLine(_ context: CGContext, width: CGFloat, start: CGPoint, end: CGPoint) {
context.setStrokeColor(BraveUX.GreyE.cgColor)
context.setLineWidth(width)
context.move(to: CGPoint(x: start.x, y: start.y))
context.addLine(to: CGPoint(x: end.x, y: end.y))
context.strokePath()
}
var previousX: CGFloat = 0
func handleSwipes(gesture: UIPanGestureRecognizer) {
if gesture.state == .began {
let velocity: CGPoint = gesture.velocity(in: self)
if velocity.x > 100 {
NotificationCenter.default.post(name: RightSwipeToolbarNotification, object: nil)
}
else if velocity.x < -100 {
NotificationCenter.default.post(name: LeftSwipeToolbarNotification, object: nil)
}
let point: CGPoint = gesture.translation(in: self)
previousX = point.x
}
else if gesture.state == .changed {
let point: CGPoint = gesture.translation(in: self)
if point.x > previousX + 50 {
NotificationCenter.default.post(name: RightSwipeToolbarNotification, object: nil)
previousX = point.x
}
else if point.x < previousX - 50 {
NotificationCenter.default.post(name: LeftSwipeToolbarNotification, object: nil)
previousX = point.x
}
}
}
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
if drawTopBorder {
drawLine(context, width: 2, start: CGPoint(x: 0, y: 0), end: CGPoint(x: frame.width, y: 0))
}
if drawBottomBorder {
drawLine(context, width: 2, start: CGPoint(x: 0, y: frame.height), end: CGPoint(x: frame.width, y: frame.height))
}
if drawSeperators {
var skippedFirst = false
for view in subviews {
if skippedFirst {
let frame = view.frame
drawLine(context,
width: 1,
start: CGPoint(x: floor(frame.origin.x), y: 0),
end: CGPoint(x: floor(frame.origin.x), y: self.frame.height))
} else {
skippedFirst = true
}
}
}
}
}
func addButtons(_ buttons: [UIButton]) {
for button in buttons {
button.setTitleColor(BraveUX.GreyG, for: .normal)
button.setTitleColor(BraveUX.GreyF, for: UIControlState.disabled)
button.imageView?.contentMode = UIViewContentMode.scaleAspectFit
addSubview(button)
}
}
override func updateConstraints() {
var prev: UIView? = nil
for view in self.subviews {
view.snp.remakeConstraints { make in
if let prev = prev {
make.left.equalTo(prev.snp.right)
} else {
make.left.equalTo(self)
}
prev = view
make.centerY.equalTo(self)
make.height.equalTo(UIConstants.ToolbarHeight)
make.width.equalTo(self).dividedBy(self.subviews.count)
}
}
super.updateConstraints()
}
}
| mpl-2.0 | 78bb74ab4838493bd77a01377c71966c | 36.361345 | 198 | 0.571525 | 4.770386 | false | false | false | false |
Allow2CEO/browser-ios | brave/src/BraveApp.swift | 1 | 11530 | /* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Deferred
var kIsDevelomentBuild: Bool = {
// Needed to avoid compiler warning when #if condition executes, so no early return
var isDev = false
#if DEBUG || BETA
isDev = true
#endif
if let bid = Bundle.main.bundleIdentifier, bid.contains(".dev") {
isDev = true
}
return isDev
}()
#if !NO_FABRIC
import Mixpanel
#endif
#if !DEBUG
func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {}
#endif
private let _singleton = BraveApp()
let kAppBootingIncompleteFlag = "kAppBootingIncompleteFlag"
let kDesktopUserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_12) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.0 Safari/602.1.31"
#if !TEST
func getApp() -> AppDelegate {
// assertIsMainThread("App Delegate must be accessed on main thread")
return UIApplication.shared.delegate as! AppDelegate
}
#endif
extension URL {
// The url is a local webserver url or an about url, a.k.a something we don't display to users
public func isSpecialInternalUrl() -> Bool {
assert(WebServer.sharedInstance.base.startsWith("http"))
return absoluteString.startsWith(WebServer.sharedInstance.base) || AboutUtils.isAboutURL(self)
}
}
// Any app-level hooks we need from Firefox, just add a call to here
class BraveApp {
static var isSafeToRestoreTabs = true
// If app runs for this long, clear the saved pref that indicates it is safe to restore tabs
static let kDelayBeforeDecidingAppHasBootedOk = (Int64(NSEC_PER_SEC) * 10) // 10 sec
class var singleton: BraveApp {
return _singleton
}
#if !TEST
class func getCurrentWebView() -> BraveWebView? {
return getApp().browserViewController.tabManager.selectedTab?.webView
}
#endif
fileprivate init() {
}
class func isIPhoneLandscape() -> Bool {
return UIDevice.current.userInterfaceIdiom == .phone &&
UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation)
}
class func isIPhonePortrait() -> Bool {
return UIDevice.current.userInterfaceIdiom == .phone &&
UIInterfaceOrientationIsPortrait(UIApplication.shared.statusBarOrientation)
}
class func isIPhoneX() -> Bool {
if #available(iOS 11.0, *) {
if isIPhonePortrait() && getApp().window!.safeAreaInsets.top > 0 {
return true
} else if isIPhoneLandscape() && (getApp().window!.safeAreaInsets.left > 0 || getApp().window!.safeAreaInsets.right > 0) {
return true
}
}
return false
}
class func setupCacheDefaults() {
URLCache.shared.memoryCapacity = 6 * 1024 * 1024; // 6 MB
URLCache.shared.diskCapacity = 40 * 1024 * 1024;
}
class func didFinishLaunching() {
#if !NO_FABRIC
let telemetryOn = getApp().profile!.prefs.intForKey(BraveUX.PrefKeyUserAllowsTelemetry) ?? 1 == 1
if telemetryOn {
if let dict = Bundle.main.infoDictionary, let token = dict["MIXPANEL_TOKEN"] as? String {
// note: setting this in willFinishLaunching is causing a crash, keep it in didFinish
mixpanelInstance = Mixpanel.initialize(token: token)
mixpanelInstance?.serverURL = "https://metric-proxy.brave.com"
checkMixpanelGUID()
// Eventually GCDWebServer `base` could be used with monitoring outgoing posts to /track endpoint
// this would allow data to be swapped out in realtime without the need for a full Mixpanel fork
}
}
#endif
UINavigationBar.appearance().tintColor = BraveUX.BraveOrange
}
private class func checkMixpanelGUID() {
let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let unit: NSCalendar.Unit = [NSCalendar.Unit.month, NSCalendar.Unit.year]
guard let dateComps = calendar?.components(unit, from: Date()), let month = dateComps.month, let year = dateComps.year else {
print("Failed to pull date components for GUID rotation")
return
}
// We only rotate on 'odd' months
let rotationMonth = Int(round(Double(month) / 2.0) * 2 - 1)
// The key for the last reset date
let resetDate = "\(rotationMonth)-\(year)"
let mixpanelGuidKey = "kMixpanelGuid"
let lastResetDate = getApp().profile!.prefs.stringForKey(mixpanelGuidKey)
if lastResetDate != resetDate {
// We have not rotated for this iteration (do not care _how_ far off it is, just that it is not the same)
mixpanelInstance?.distinctId = UUID().uuidString
getApp().profile?.prefs.setString(resetDate, forKey: mixpanelGuidKey)
}
}
// Be aware: the Prefs object has not been created yet
class func willFinishLaunching_begin() {
BraveApp.setupCacheDefaults()
Foundation.URLProtocol.registerClass(URLProtocol);
NotificationCenter.default.addObserver(BraveApp.singleton,
selector: #selector(BraveApp.didEnterBackground(_:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(BraveApp.singleton,
selector: #selector(BraveApp.willEnterForeground(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(BraveApp.singleton,
selector: #selector(BraveApp.memoryWarning(_:)), name: NSNotification.Name.UIApplicationDidReceiveMemoryWarning, object: nil)
#if !TEST
// these quiet the logging from the core of fx ios
// GCDWebServer.setLogLevel(5)
Logger.syncLogger.setup(level: .none)
Logger.browserLogger.setup(level: .none)
#endif
#if DEBUG
// desktop UA for testing
// let defaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())!
// defaults.registerDefaults(["UserAgent": kDesktopUserAgent])
#endif
}
// Prefs are created at this point
class func willFinishLaunching_end() {
BraveApp.isSafeToRestoreTabs = BraveApp.getPrefs()?.stringForKey(kAppBootingIncompleteFlag) == nil
BraveApp.getPrefs()?.setString("remove me when booted", forKey: kAppBootingIncompleteFlag)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(BraveApp.kDelayBeforeDecidingAppHasBootedOk) / Double(NSEC_PER_SEC), execute: {
BraveApp.getPrefs()?.removeObjectForKey(kAppBootingIncompleteFlag)
})
let args = ProcessInfo.processInfo.arguments
if args.contains("BRAVE-TEST-CLEAR-PREFS") {
BraveApp.getPrefs()!.clearAll()
}
if args.contains("BRAVE-TEST-NO-SHOW-INTRO") {
BraveApp.getPrefs()!.setInt(1, forKey: IntroViewControllerSeenProfileKey)
}
if args.contains("BRAVE-TEST-SHOW-OPT-IN") {
BraveApp.getPrefs()!.removeObjectForKey(BraveUX.PrefKeyOptInDialogWasSeen)
}
// Be careful, running it in production will result in destroying all bookmarks
if args.contains("BRAVE-DELETE-BOOKMARKS") {
Bookmark.removeAll()
}
if args.contains("BRAVE-UI-TEST") || AppConstants.IsRunningTest {
// Maybe we will need a specific flag to keep tabs for restoration testing
BraveApp.isSafeToRestoreTabs = false
if args.filter({ $0.startsWith("BRAVE") }).count == 1 || AppConstants.IsRunningTest { // only contains 1 arg
BraveApp.getPrefs()!.setInt(1, forKey: IntroViewControllerSeenProfileKey)
BraveApp.getPrefs()!.setInt(1, forKey: BraveUX.PrefKeyOptInDialogWasSeen)
}
}
if args.contains("LOCALE=RU") {
AdBlocker.singleton.currentLocaleCode = "ru"
}
AdBlocker.singleton.startLoading()
SafeBrowsing.singleton.networkFileLoader.loadData()
TrackingProtection.singleton.networkFileLoader.loadData()
HttpsEverywhere.singleton.networkFileLoader.loadData()
#if !TEST
PrivateBrowsing.singleton.startupCheckIfKilledWhileInPBMode()
CookieSetting.setupOnAppStart()
PasswordManagerButtonSetting.setupOnAppStart()
//BlankTargetLinkHandler.updatedEnabledState()
#endif
Domain.loadShieldsIntoMemory {
guard let shieldState = getApp().tabManager.selectedTab?.braveShieldStateSafeAsync.get() else { return }
if let wv = getCurrentWebView(), let url = wv.URL?.normalizedHost, let dbState = BraveShieldState.perNormalizedDomain[url], shieldState.isNotSet() {
// on init, the webview's shield state doesn't match the db
getApp().tabManager.selectedTab?.braveShieldStateSafeAsync.set(dbState)
wv.reloadFromOrigin()
}
}
}
// This can only be checked ONCE, the flag is cleared after this.
// This is because BrowserViewController asks this question after the startup phase,
// when tabs are being created by user actions. So without more refactoring of the
// Firefox logic, this is the simplest solution.
class func shouldRestoreTabs() -> Bool {
let ok = BraveApp.isSafeToRestoreTabs
BraveApp.isSafeToRestoreTabs = false
return ok
}
@objc func memoryWarning(_: Notification) {
URLCache.shared.memoryCapacity = 0
BraveApp.setupCacheDefaults()
}
@objc func didEnterBackground(_: Notification) {
}
@objc func willEnterForeground(_ : Notification) {
}
class func shouldHandleOpenURL(_ components: URLComponents) -> Bool {
// TODO look at what x-callback is for
let handled = components.scheme == "brave" || components.scheme == "brave-x-callback"
return handled
}
class func getPrefs() -> NSUserDefaultsPrefs? {
return getApp().profile?.prefs
}
static func showErrorAlert(title: String, error: String) {
postAsyncToMain(0) { // this utility function can be called from anywhere
UIAlertView(title: title, message: error, delegate: nil, cancelButtonTitle: "Close").show()
}
}
static func statusBarHeight() -> CGFloat {
if UIScreen.main.traitCollection.verticalSizeClass == .compact {
return 0
}
return 20
}
static var isPasswordManagerInstalled: Bool?
static func is3rdPartyPasswordManagerInstalled(_ refreshLookup: Bool) -> Deferred<Bool> {
let deferred = Deferred<Bool>()
if refreshLookup || isPasswordManagerInstalled == nil {
postAsyncToMain {
isPasswordManagerInstalled = OnePasswordExtension.shared().isAppExtensionAvailable()
deferred.fill(isPasswordManagerInstalled!)
}
} else {
deferred.fill(isPasswordManagerInstalled!)
}
return deferred
}
}
| mpl-2.0 | 5ab002c3ca9a6f331b46eae72b7dc920 | 39.034722 | 198 | 0.647788 | 4.778284 | false | false | false | false |
chenyunguiMilook/SwiftyXML | Sources/SwiftyXML/XML.swift | 1 | 23639 | // SwiftyXML.swift
//
// Copyright (c) 2016 ChenYunGui (陈云贵)
//
// 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
public enum XMLSubscriptKey {
case index(Int) // such as: 1
case key(String) // such as: "childName"
case attribute(String) // such as: "$attributeName"
}
public enum XMLError : Error {
case subscriptFailue(String)
case initFailue(String)
case wrongChain(String)
}
@dynamicMemberLookup
public enum XMLSubscriptResult {
case null(String) // means: null(error: String)
case xml(XML, String) // means: xml(xml: XML, path: String)
case array([XML], String) // means: xml(xmls: [XML], path: String)
case string(String, String) // means: string(value: String, path: String)
public subscript(dynamicMember member: String) -> XMLSubscriptResult {
if let index = Int(member) {
return self[XMLSubscriptKey.index(index)]
} else if member.starts(with: "$") {
let attribute = String(member.dropFirst())
let key = XMLSubscriptKey.attribute(attribute)
return self[key]
} else {
return self[XMLSubscriptKey.key(member)]
}
}
public subscript(key: XMLSubscriptKey) -> XMLSubscriptResult {
func subscriptResult(_ result: XMLSubscriptResult, byIndex index: Int) -> XMLSubscriptResult {
switch result {
case .null(_):
return self
case .string(_, let path):
return .null(path + ": attribute can not subscript by index: \(index)")
case .xml(_, let path):
return .null(path + ": single xml can not subscript by index: \(index)")
case .array(let xmls, let path):
if xmls.indices.contains(index) {
return .xml(xmls[index], path + ".\(index)")
} else {
return .null(path + ": index:\(index) out of bounds: \(xmls.indices)")
}
}
}
func subscriptResult(_ result: XMLSubscriptResult, byKey key: String) -> XMLSubscriptResult {
switch result {
case .null(_):
return self
case .string(_, let path):
return .null(path + ": attribute can not subscript by key: \(key)")
case .xml(let xml, let path):
let array = xml.children.filter{ $0.name == key }
if !array.isEmpty {
return .array(array, path + ".\(key)")
} else {
return .null(path + ": no such children named: \"\(key)\"")
}
case .array(let xmls, let path):
let result = XMLSubscriptResult.xml(xmls[0], path + ".0")
return subscriptResult(result, byKey: key)
}
}
func subscriptResult(_ result: XMLSubscriptResult, byAttribute attribute: String) -> XMLSubscriptResult {
switch result {
case .null(_): return self
case .string(_, let path):
return .null(path + ": attribute can not subscript by attribute: \(attribute)")
case .xml(let xml, let path):
if let attr = xml.attributes[attribute] {
return .string(attr, path + ".$\(attribute)")
} else {
return .null(path + ": no such attribute named: \(attribute)")
}
case .array(let xmls, let path):
if let attr = xmls[0].attributes[attribute] {
return .string(attr, path + ".0.$\(attribute)")
} else {
return .null(path + ".0.$\(attribute)" + ": no such attribute named: \(attribute)")
}
}
}
switch key {
case .index(let index):
return subscriptResult(self, byIndex: index)
case .key(let key):
return subscriptResult(self, byKey: key)
case .attribute(let attribute):
return subscriptResult(self, byAttribute: attribute)
}
}
public var xml:XML? {
switch self {
case .null(_):
return nil
case .string(_, _):
return nil
case .xml(let xml, _): return xml
case .array(let xmls, _): return xmls[0]
}
}
public func getXML() throws -> XML {
switch self {
case .null(let error):
throw XMLError.subscriptFailue(error)
case .string(_, let path):
throw XMLError.subscriptFailue("can not get XML from attribute, from keyChain: \(path)")
case .xml(let xml, _): return xml
case .array(let xmls, _): return xmls[0]
}
}
public var xmlList:[XML]? {
switch self {
case .null(_):
return nil
case .string(_, _):
return nil
case .xml(let xml, _): return [xml]
case .array(let xmls, _): return xmls
}
}
public func getXMLList() throws -> [XML] {
switch self {
case .null(let error):
throw XMLError.subscriptFailue(error)
case .string(_, let path):
throw XMLError.subscriptFailue("can not get list from attribute, from keyChain: \(path)")
case .xml(let xml, _): return [xml]
case .array(let xmls, _): return xmls
}
}
public var error: String {
switch self {
case .null(let error):
return error
default: return ""
}
}
}
@dynamicMemberLookup
open class XML {
fileprivate var name:String
fileprivate var attributes:[String: String] = [:]
fileprivate var value:String?
fileprivate var children:[XML] = []
public var xmlName:String {
get { name }
set { name = newValue }
}
public var xmlAttributes:[String: String] {
get { attributes }
set { attributes = newValue }
}
public var xmlValue:String? {
get { value }
set { value = newValue }
}
public var xmlChildren:[XML] { children }
internal weak var parent:XML?
public init(name:String, attributes:[String:Any] = [:], value: Any? = nil) {
self.name = name
self.addAttributes(attributes)
if let value = value {
self.value = String(describing: value)
}
}
private convenience init(xml: XML) {
self.init(name: xml.name, attributes: xml.attributes, value: xml.value)
self.addChildren(xml.children)
self.parent = nil
}
public convenience init!(data: Data) {
do {
let parser = SimpleXMLParser(data: data)
try parser.parse()
if let xml = parser.root {
self.init(xml: xml)
} else {
fatalError("xml parser exception")
}
} catch {
print(error.localizedDescription)
return nil
}
}
public convenience init!(url: URL) {
do {
let data = try Data(contentsOf: url)
self.init(data: data)
} catch {
print(error.localizedDescription)
return nil
}
}
public convenience init(named name: String) {
guard let url = Bundle.main.resourceURL?.appendingPathComponent(name) else {
fatalError("can not get mainBundle URL")
}
self.init(url: url)
}
public convenience init(string: String, encoding: String.Encoding = .utf8) {
guard let data = string.data(using: encoding) else {
fatalError("string encoding failed")
}
self.init(data: data)
}
public subscript(dynamicMember member: String) -> XMLSubscriptResult {
if let index = Int(member) {
return self[XMLSubscriptKey.index(index)]
} else if member.starts(with: "$") {
let attribute = String(member.dropFirst())
let key = XMLSubscriptKey.attribute(attribute)
return self[key]
} else {
return self[XMLSubscriptKey.key(member)]
}
}
public subscript(key: XMLSubscriptKey) -> XMLSubscriptResult {
switch key {
case .index(let index):
if self.children.indices.contains(index) {
return .xml(self.children[index], "[\(index)]")
} else {
let bounds = self.children.indices
return .null("index:\(index) out of bounds: \(bounds)")
}
case .key(let key):
let array = self.children.filter{ $0.name == key }
if !array.isEmpty {
return .array(array, ".\(key)")
} else {
return .null("no such children named: \"\(key)\"")
}
case .attribute(let attribute):
if let attr = self.attributes[attribute] {
return .string(attr, ".$\(attribute)")
} else {
return .null("no such attribute named: \"\(attribute)\"")
}
}
}
@discardableResult
public func addAttribute(name:String, value:Any) -> XML {
self.attributes[name] = String(describing: value)
return self
}
@discardableResult
public func addAttributes(_ attributes:[String : Any]) -> XML {
for (key, value) in attributes {
self.addAttribute(name: key, value: value)
}
return self
}
@discardableResult
public func addChild(_ xml:XML) -> XML {
guard xml !== self else {
fatalError("can not add self to xml children list!")
}
children.append(xml)
xml.parent = self
return self
}
@discardableResult
public func addChildren(_ xmls: [XML]) -> XML {
xmls.forEach{ self.addChild($0) }
return self
}
}
// MARK: - XMLSubscriptResult implements Sequence protocol
public class XMLSubscriptResultIterator : IteratorProtocol {
var xmls:[XML]
var index:Int = 0
public init(result: XMLSubscriptResult) {
self.xmls = result.xmlList ?? []
}
public func next() -> XML? {
if self.xmls.isEmpty { return nil }
if self.index >= self.xmls.endIndex { return nil }
defer { index += 1 }
return self.xmls[index]
}
}
extension XMLSubscriptResult : Sequence {
public typealias Iterator = XMLSubscriptResultIterator
public func makeIterator() -> XMLSubscriptResult.Iterator {
return XMLSubscriptResultIterator(result: self)
}
}
// MARK: - StringProvider protocol and extensions
public protocol StringProvider {
var string: String? { get }
}
extension XML : StringProvider {
public var string: String? {
return self.value
}
}
extension XMLSubscriptResult : StringProvider {
public var string: String? {
switch self {
case .null(_): return nil
case .string(let string, _): return string
case .xml(let xml, _): return xml.value
case .array(let xmls, _): return xmls[0].value
}
}
}
extension RawRepresentable {
static func initialize(rawValue: RawValue?) throws -> Self {
if let value = rawValue {
if let result = Self.init(rawValue: value) {
return result
} else {
throw XMLError.initFailue("[\(Self.self)] init failed with raw value: [\(value)]")
}
}
throw XMLError.initFailue("[\(Self.self)] init failed with nil value")
}
}
extension StringProvider {
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == String { return try? T.initialize(rawValue: self.string) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == UInt8 { return try? T.initialize(rawValue: self.uInt8) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == UInt16 { return try? T.initialize(rawValue: self.uInt16) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == UInt32 { return try? T.initialize(rawValue: self.uInt32) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == UInt64 { return try? T.initialize(rawValue: self.uInt64) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == UInt { return try? T.initialize(rawValue: self.uInt) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == Int8 { return try? T.initialize(rawValue: self.int8) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == Int16 { return try? T.initialize(rawValue: self.int16) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == Int32 { return try? T.initialize(rawValue: self.int32) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == Int64 { return try? T.initialize(rawValue: self.int64) }
public func `enum`<T>() -> T? where T: RawRepresentable, T.RawValue == Int { return try? T.initialize(rawValue: self.int) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == String { return try T.initialize(rawValue: self.string) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == UInt8 { return try T.initialize(rawValue: self.uInt8) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == UInt16 { return try T.initialize(rawValue: self.uInt16) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == UInt32 { return try T.initialize(rawValue: self.uInt32) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == UInt64 { return try T.initialize(rawValue: self.uInt64) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == UInt { return try T.initialize(rawValue: self.uInt) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == Int8 { return try T.initialize(rawValue: self.int8) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == Int16 { return try T.initialize(rawValue: self.int16) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == Int32 { return try T.initialize(rawValue: self.int32) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == Int64 { return try T.initialize(rawValue: self.int64) }
public func getEnum<T>() throws -> T where T: RawRepresentable, T.RawValue == Int { return try T.initialize(rawValue: self.int) }
}
// optional
extension StringProvider {
public var bool: Bool? {
if let string = self.string { return Bool(string) }
return nil
}
// unsigned integer
public var uInt8: UInt8? {
if let string = self.string { return UInt8(string) }
return nil
}
public var uInt16: UInt16? {
if let string = self.string { return UInt16(string) }
return nil
}
public var uInt32: UInt32? {
if let string = self.string { return UInt32(string) }
return nil
}
public var uInt64: UInt64? {
if let string = self.string { return UInt64(string) }
return nil
}
public var uInt: UInt? {
if let string = self.string { return UInt(string) }
return nil
}
// signed integer
public var int8: Int8? {
if let string = self.string { return Int8(string) }
return nil
}
public var int16: Int16? {
if let string = self.string { return Int16(string) }
return nil
}
public var int32: Int32? {
if let string = self.string { return Int32(string) }
return nil
}
public var int64: Int64? {
if let string = self.string { return Int64(string) }
return nil
}
public var int: Int? {
if let string = self.string { return Int(string) }
return nil
}
// decimal
public var float: Float? {
if let string = self.string { return Float(string) }
return nil
}
public var double: Double? {
if let string = self.string { return Double(string) }
return nil
}
}
// non optional
extension StringProvider {
public var boolValue: Bool {
return bool ?? false
}
// unsigned integer
public var uInt8Value: UInt8 {
return uInt8 ?? 0
}
public var uInt16Value: UInt16 {
return uInt16 ?? 0
}
public var uInt32Value: UInt32 {
return uInt32 ?? 0
}
public var uInt64Value: UInt64 {
return uInt64 ?? 0
}
public var uIntValue: UInt {
return uInt ?? 0
}
// signed integer
public var int8Value: Int8 {
return int8 ?? 0
}
public var int16Value: Int16 {
return int16 ?? 0
}
public var int32Value: Int32 {
return int32 ?? 0
}
public var int64Value: Int64 {
return int64 ?? 0
}
public var intValue: Int {
return int ?? 0
}
// decimal
public var floatValue: Float {
return float ?? 0
}
public var doubleValue: Double {
return double ?? 0
}
public var stringValue: String {
return string ?? ""
}
}
// MARK: - XML Descriptions
extension XML {
public var description:String {
return self.toXMLString()
}
public func toXMLString() -> String {
var result = ""
var depth:Int = 0
describe(xml: self, depth: &depth, result: &result)
return result
}
private func describe(xml: XML, depth:inout Int, result: inout String) {
if xml.children.isEmpty {
result += xml.getCombine(numTabs: depth)
} else {
result += xml.getStartPart(numTabs: depth)
depth += 1
for child in xml.children {
describe(xml: child, depth: &depth, result: &result)
}
depth -= 1
result += xml.getEndPart(numTabs: depth)
}
}
private func getAttributeString() -> String {
return self.attributes.map{ " \($0.0)=\"\($0.1.escaped())\"" }.joined()
}
private func getStartPart(numTabs:Int) -> String {
return getDescription(numTabs: numTabs, closed: false)
}
private func getEndPart(numTabs:Int) -> String {
return String(repeating: "\t", count: numTabs) + "</\(name)>\n"
}
private func getCombine(numTabs:Int) -> String {
return self.getDescription(numTabs: numTabs, closed: true)
}
private func getDescription(numTabs:Int, closed:Bool) -> String {
var attr = self.getAttributeString()
attr = attr.isEmpty ? "" : attr
let tabs = String(repeating: "\t", count: numTabs)
var valueString: String = ""
if let v = self.value {
valueString = v.trimmingCharacters(in: .whitespacesAndNewlines).escaped()
}
if attr.isEmpty {
switch (closed, self.value) {
case (true, .some(_)): return tabs + "<\(name)>\(valueString)</\(name)>\n"
case (true, .none): return tabs + "<\(name)/>\n"
case (false, .some(_)): return tabs + "<\(name)>\(valueString)\n"
case (false, .none): return tabs + "<\(name)>\n"
}
} else {
switch (closed, self.value) {
case (true, .some(_)): return tabs + "<\(name)" + attr + ">\(valueString)</\(name)>\n"
case (true, .none): return tabs + "<\(name)" + attr + "/>\n"
case (false, .some(_)): return tabs + "<\(name)" + attr + ">\(valueString)\n"
case (false, .none): return tabs + "<\(name)" + attr + ">\n"
}
}
}
}
public class SimpleXMLParser: NSObject, XMLParserDelegate {
public var root:XML?
public let data:Data
weak var currentElement:XML?
var parseError:Swift.Error?
deinit {
self.root = nil
self.currentElement = nil
self.parseError = nil
}
public init(data: Data) {
self.data = data
super.init()
}
public func parse() throws {
let parser = XMLParser(data: data)
parser.delegate = self
parser.shouldProcessNamespaces = false
parser.shouldReportNamespacePrefixes = false
parser.shouldResolveExternalEntities = false
parser.parse()
if let error = parseError {
throw error
}
}
// MARK: - XMLParserDelegate
@objc public func parser(_ parser: XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String : String])
{
let element = XML(name: elementName, attributes: attributeDict)
if self.root == nil {
self.root = element
self.currentElement = element
} else {
self.currentElement?.addChild(element)
self.currentElement = element
}
}
@objc public func parser(_ parser: XMLParser, foundCharacters string: String) {
if let currentValue = self.currentElement?.value {
self.currentElement?.value = currentValue + string
} else {
self.currentElement?.value = string
}
}
@objc public func parser(_ parser: XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?)
{
currentElement = currentElement?.parent
}
@objc public func parser(_ parser: XMLParser, parseErrorOccurred parseError: Swift.Error) {
self.parseError = parseError
}
}
extension String {
func escaped() -> String {
return self
.replacingOccurrences(of: "&", with: "&")
.replacingOccurrences(of: "\"", with: """)
.replacingOccurrences(of: "'", with: "'")
.replacingOccurrences(of: ">", with: ">")
.replacingOccurrences(of: "<", with: "<")
}
}
| mit | 38cc9af9b306167145d389400bc5f773 | 33.652493 | 139 | 0.567681 | 4.412435 | false | false | false | false |
wolf81/Nimbl3Survey | Nimbl3Survey/LoadingView.swift | 1 | 2564 | //
// LoadingView.swift
// Nimbl3Survey
//
// Created by Wolfgang Schreurs on 26/03/2017.
// Copyright © 2017 Wolftrail. All rights reserved.
//
import UIKit
protocol LoadingViewDelegate: class {
func loadingViewReloadAction(_ loadingView: LoadingView)
}
class LoadingView: UIView, InterfaceBuilderInstantiable {
weak var delegate: LoadingViewDelegate?
var animationDuration: TimeInterval = 0.2
@IBOutlet weak var imageView: UIImageView?
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var infoLabel: UILabel?
@IBOutlet weak var reloadButton: UIButton?
// MARK: - Initialization & clean-up
override func awakeFromNib() {
super.awakeFromNib()
self.titleLabel?.alpha = 0.0
self.reloadButton?.alpha = 0.0
self.infoLabel?.alpha = 0.0
self.imageView?.alpha = 0.0
self.imageView?.tintColor = .white
}
// MARK: - Actions
@IBAction func reloadAction() {
self.delegate?.loadingViewReloadAction(self)
}
// MARK: - Public
func updateWithError(_ error: Error?) {
self.titleLabel?.text = "Error"
self.infoLabel?.text = error?.localizedDescription ?? "An unknown error occured."
self.imageView?.stopRotation()
UIView.animate(withDuration: self.animationDuration, delay: 0, options: .beginFromCurrentState, animations: {
self.titleLabel?.alpha = 1.0
self.reloadButton?.alpha = 1.0
self.imageView?.alpha = 0.0
self.infoLabel?.alpha = 1.0
}, completion: nil)
}
func startLoading() {
self.titleLabel?.text = "Loading ..."
self.infoLabel?.text = nil
self.imageView?.startRotation(2.0, repeatCount: Float.infinity, clockwise: true)
UIView.animate(withDuration: self.animationDuration, delay: 0, options: .beginFromCurrentState, animations: {
self.titleLabel?.alpha = 1.0
self.reloadButton?.alpha = 0.0
self.imageView?.alpha = 1.0
self.infoLabel?.alpha = 0.0
}, completion: nil)
}
func stopLoading() {
self.imageView?.stopRotation()
UIView.animate(withDuration: self.animationDuration, delay: 0, options: .beginFromCurrentState, animations: {
self.titleLabel?.alpha = 1.0
self.reloadButton?.alpha = 1.0
self.imageView?.alpha = 0.0
self.infoLabel?.alpha = 1.0
}, completion: nil)
}
// MARK: - Private
}
| bsd-2-clause | d5c980471047e80779c6930c65fd578b | 29.511905 | 117 | 0.618026 | 4.512324 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Services/Service.HumidifierDehumidifier.swift | 1 | 2877 | import Foundation
extension Service {
open class HumidifierDehumidifier: Service {
public init(characteristics: [AnyCharacteristic] = []) {
var unwrapped = characteristics.map { $0.wrapped }
active = getOrCreateAppend(
type: .active,
characteristics: &unwrapped,
generator: { PredefinedCharacteristic.active() })
currentHumidifierDehumidifierState = getOrCreateAppend(
type: .currentHumidifierDehumidifierState,
characteristics: &unwrapped,
generator: { PredefinedCharacteristic.currentHumidifierDehumidifierState() })
targetHumidifierDehumidifierState = getOrCreateAppend(
type: .targetHumidifierDehumidifierState,
characteristics: &unwrapped,
generator: { PredefinedCharacteristic.targetHumidifierDehumidifierState() })
currentRelativeHumidity = getOrCreateAppend(
type: .currentRelativeHumidity,
characteristics: &unwrapped,
generator: { PredefinedCharacteristic.currentRelativeHumidity() })
lockPhysicalControls = get(type: .lockPhysicalControls, characteristics: unwrapped)
name = get(type: .name, characteristics: unwrapped)
relativeHumidityDehumidifierThreshold = get(type: .relativeHumidityDehumidifierThreshold, characteristics: unwrapped)
relativeHumidityHumidifierThreshold = get(type: .relativeHumidityHumidifierThreshold, characteristics: unwrapped)
rotationSpeed = get(type: .rotationSpeed, characteristics: unwrapped)
swingMode = get(type: .swingMode, characteristics: unwrapped)
currentWaterLevel = get(type: .currentWaterLevel, characteristics: unwrapped)
super.init(type: .humidifierDehumidifier, characteristics: unwrapped)
}
// MARK: - Required Characteristics
public let active: GenericCharacteristic<Enums.Active>
public let currentHumidifierDehumidifierState: GenericCharacteristic<Enums.CurrentHumidifierDehumidifierState>
public let targetHumidifierDehumidifierState: GenericCharacteristic<Enums.TargetHumidifierDehumidifierState>
public let currentRelativeHumidity: GenericCharacteristic<Float>
// MARK: - Optional Characteristics
public let lockPhysicalControls: GenericCharacteristic<UInt8>?
public let name: GenericCharacteristic<String>?
public let relativeHumidityDehumidifierThreshold: GenericCharacteristic<Float>?
public let relativeHumidityHumidifierThreshold: GenericCharacteristic<Float>?
public let rotationSpeed: GenericCharacteristic<Float>?
public let swingMode: GenericCharacteristic<UInt8>?
public let currentWaterLevel: GenericCharacteristic<Float>?
}
}
| mit | b68c94fc33c985318302136536253e71 | 58.9375 | 129 | 0.709072 | 5.418079 | false | false | false | false |
liuxianghong/GreenBaby | 工程/greenbaby/greenbaby/ViewController/MySelf/MallViewController.swift | 1 | 1389 | //
// MallViewController.swift
// greenbaby
//
// Created by 刘向宏 on 15/12/18.
// Copyright © 2015年 刘向宏. All rights reserved.
//
import UIKit
class MallViewController: UIViewController {
@IBOutlet weak var copyButton : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.copyButton.layer.borderWidth = 1/2.0
self.copyButton.layer.borderColor = UIColor.rgbColor(0xe53051).CGColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func copyButtonClick(){
let hud = MBProgressHUD.showHUDAddedTo(self.view , animated: true)
hud.labelText = "复制成功"
hud.mode = .Text
hud.hide(true, afterDelay: 1.5)
let pasteboard = UIPasteboard.generalPasteboard()
pasteboard.string = "lvbaobaoshangcheng"
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| lgpl-3.0 | 2cf386d67fd71ca239e0d2d3e34bc39b | 28.06383 | 106 | 0.666179 | 4.493421 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Command/Command+Places.swift | 1 | 1554 | //
// Command+Places.swift
//
//
// Created by Vladislav Fitc on 10/04/2020.
//
import Foundation
extension Command {
enum Places {
struct Search: AlgoliaCommand {
let method: HTTPMethod = .post
let callType: CallType = .read
let path: URL
let body: Data?
let requestOptions: RequestOptions?
init(query: PlacesQuery, requestOptions: RequestOptions?) {
self.requestOptions = requestOptions
self.path = URL
.places
.appending(.query)
self.body = query.httpBody
}
}
struct GetObject: AlgoliaCommand {
let method: HTTPMethod = .get
let callType: CallType = .read
let path: URL
let requestOptions: RequestOptions?
init(objectID: ObjectID, requestOptions: RequestOptions?) {
self.requestOptions = requestOptions
self.path = URL
.places
.appending(objectID)
}
}
struct ReverseGeocoding: AlgoliaCommand {
let method: HTTPMethod = .get
let callType: CallType = .read
let path: URL
let requestOptions: RequestOptions?
init(geolocation: Point, language: Language?, hitsPerPage: Int?, requestOptions: RequestOptions?) {
self.requestOptions = requestOptions.updateOrCreate([
.aroundLatLng: geolocation.stringForm,
.hitsPerPage: hitsPerPage.flatMap(String.init),
.language: language?.rawValue
])
self.path = URL
.places
.appending(.reverse)
}
}
}
}
| mit | f4f9cec33f27ec4f262a1350b7f8934f | 21.2 | 105 | 0.612613 | 4.752294 | false | false | false | false |
BlakeBarrett/wndw | wtrmrkr/Brush.swift | 1 | 583 | //
// Brush.swift
// wndw
//
// Created by Blake Barrett on 5/7/16.
// Copyright © 2016 Blake Barrett. All rights reserved.
//
import UIKit
import CoreGraphics
class Brush {
init() {
}
init(red: CGFloat, green: CGFloat, blue: CGFloat, width: CGFloat, alpha: CGFloat) {
self.red = red
self.green = green
self.blue = blue
self.width = width
self.alpha = alpha
}
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var width: CGFloat = 10.0
var alpha: CGFloat = 1.0
}
| mit | 740b86b823626b22fd205523d176e1e1 | 18.4 | 87 | 0.573883 | 3.423529 | false | false | false | false |
Miridescen/M_365key | 365KEY_swift/365KEY_swift/MainController/Class/Produce/controller/productDetailModel/SKProductDetailTeamModel.swift | 1 | 792 | //
// SKProductDetailTeamModel.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/11/17.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
class SKProductDetailTeamModel: NSObject {
var id: Int64 = 0
var info: String?
var inputtime: Date?
var job: String?
var name: String?
var pro_id: Int64 = 0
var role_id: Int64 = 0
var thumbnail: String? {
didSet{
guard let thumb = thumbnail else {
return
}
showThumbnail = thumb.hasPrefix("http") ? thumb : "http://www.365key.com" + thumb
}
}
var showThumbnail: String?
var weight: Int64 = 0
override var description: String{
return yy_modelDescription()
}
}
| apache-2.0 | 0b2962da385a4686c0cf52a606b4ba43 | 18.625 | 93 | 0.563057 | 3.905473 | false | false | false | false |
nickdex/cosmos | code/sorting/src/flash_sort/flash_sort.swift | 5 | 1976 | /* Part of Cosmos by OpenGenus Foundation */
//
// flash_sort.swift
// Created by DaiPei on 2017/10/17.
//
import Foundation
func flashSort(_ array: inout [Int]) {
// find the max and min item
var max = Int.min
var min = Int.max
for item in array {
if item > max {
max = item
}
if item < min {
min = item
}
}
if max == min {
return
}
// divide to m class
let m = Int(0.43 * Double(array.count))
let c = Double(m - 1) / Double(max - min)
// save every class pointer
var pClass = [Int](repeatElement(0, count: m + 1))
for item in array {
let k = Int(c * Double(item - min)) + 1
pClass[k] += 1
}
for k in 1...m {
pClass[k] += pClass[k - 1] // pClass[k]: point to upper bound of class k
}
// move every element to right class
var move = 0
var j = 0
var k = m
// after this loop pClass[k] point to under bound of class k, it means every element is moved to the right class
while move < array.count {
while j >= pClass[k] {
j += 1
k = Int(c * Double(array[j] - min)) + 1
}
var flash = array[j]
while j < pClass[k] {
k = Int(c * Double(flash - min)) + 1
pClass[k] -= 1
swap(&flash, &array[pClass[k]])
move += 1
}
}
// sort every class
for i in 1..<m {
sortCore(&array, from: pClass[i], to: pClass[i + 1])
}
}
private func swap(_ array: inout [Int], at a: Int, and b: Int) {
let tmp = array[a]
array[a] = array[b]
array[b] = tmp
}
private func sortCore(_ array: inout [Int], from a: Int, to b: Int) {
if a >= b {
return
}
for i in a..<b-1 {
var p = i
for j in i+1..<b {
if array[j] < array[p] {
p = j
}
}
swap(&array, at: p, and: i)
}
}
| gpl-3.0 | 4e0cf100649c8d873f2ca64bf40d990c | 22.52381 | 116 | 0.477733 | 3.337838 | false | false | false | false |
SteveRohrlack/CitySimCore | Tests/StatisticlayersContainerTests.swift | 1 | 1952 | //
// StatisticlayersContainerTests.swift
// CitySimCore
//
// Created by Steve Rohrlack on 20.05.16.
// Copyright © 2016 Steve Rohrlack. All rights reserved.
//
import XCTest
#if os(iOS)
@testable import CitySimCoreiOS
#endif
#if os(OSX)
@testable import CitySimCoreMacOS
#endif
class StatisticlayersContainerTests: XCTestCase {
let height = 15
let width = 15
var subject: StatisticlayersContainer?
override func setUp() {
super.setUp()
subject = StatisticlayersContainer(height: height, width: width)
}
override func tearDown() {
super.tearDown()
}
func testLayerSize() {
XCTAssertEqual(height * width, subject!.landvalueLayer.values.count)
}
func testAddStatistics() {
let origin = (4, 4)
let testDouble = SmallParkPloppTestDouble(origin: origin)
subject!.addStatistics(
at: Location(origin: origin),
statistical: testDouble as MapStatistical
)
let testLocationWithRadius = testDouble + 3
XCTAssertEqual(4, subject!.landvalueLayer[testLocationWithRadius.origin])
XCTAssertNil(subject!.noiseLayer[testLocationWithRadius.origin])
}
func testRemoveStatistics() {
let origin = (4, 4)
let testDouble = SmallParkPloppTestDouble(origin: origin)
subject!.addStatistics(
at: Location(origin: origin),
statistical: testDouble as MapStatistical
)
let testLocationWithRadius = testDouble + 3
XCTAssertEqual(4, subject!.landvalueLayer[testLocationWithRadius.origin])
subject!.removeStatistics(
at: Location(origin: origin),
statistical: testDouble as MapStatistical
)
XCTAssertNil(subject!.landvalueLayer[testLocationWithRadius.origin])
}
} | mit | 40b12319322511a5b8b1f6771731029b | 24.684211 | 81 | 0.625833 | 4.781863 | false | true | false | false |
brightify/Bond | Bond/iOS/Bond+UICollectionView.swift | 1 | 9360 | //
// Bond+UICollectionView.swift
// Bond
//
// Created by Srđan Rašić on 06/03/15.
// Copyright (c) 2015 Bond. All rights reserved.
//
import UIKit
@objc class CollectionViewDynamicArrayDataSource: NSObject, UICollectionViewDataSource {
weak var dynamic: ObservableArray<LazyObservableArray<UICollectionViewCell>>?
@objc weak var nextDataSource: UICollectionViewDataSource?
init(dynamic: ObservableArray<LazyObservableArray<UICollectionViewCell>>) {
self.dynamic = dynamic
super.init()
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return self.dynamic?.count ?? 0
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dynamic?[section].count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return self.dynamic?[indexPath.section][indexPath.item]() ?? UICollectionViewCell()
}
// Forwards
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if let result = self.nextDataSource?.collectionView?(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath) {
return result
} else {
fatalError("Defining Supplementary view either in Storyboard or by registering a class or nib file requires you to implement method collectionView:viewForSupplementaryElementOfKind:indexPath in your data soruce! To provide data source, make a class (usually your view controller) adhere to protocol UICollectionViewDataSource and implement method collectionView:viewForSupplementaryElementOfKind:indexPath. Register instance of your class as next data source with UICollectionViewDataSourceBond object by setting its nextDataSource property. Make sure you set it before binding takes place!")
}
}
}
private class UICollectionViewDataSourceSectionBond: ArrayBond<() -> UICollectionViewCell> {
weak var collectionView: UICollectionView?
var section: Int
init(collectionView: UICollectionView?, section: Int, file: String = __FILE__, line: UInt = __LINE__) {
self.collectionView = collectionView
self.section = section
super.init(file: file, line: line)
self.didInsertListener = { [unowned self] a, i in
if let collectionView = self.collectionView {
collectionView.insertItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) })
}
}
self.didRemoveListener = { [unowned self] a, i in
if let collectionView = self.collectionView {
collectionView.deleteItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) })
}
}
self.didUpdateListener = { [unowned self] a, i in
if let collectionView = self.collectionView {
collectionView.reloadItemsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) })
}
}
self.didResetListener = { [weak self] array in
if let collectionView = self?.collectionView {
collectionView.reloadData()
}
}
}
deinit {
self.unbind()
}
}
public class UICollectionViewDataSourceBond: ArrayBond<LazyObservableArray<UICollectionViewCell>> {
weak var collectionView: UICollectionView?
private var dataSource: CollectionViewDynamicArrayDataSource?
private var sectionBonds: [UICollectionViewDataSourceSectionBond] = []
public weak var nextDataSource: UICollectionViewDataSource? {
didSet(newValue) {
dataSource?.nextDataSource = newValue
}
}
public init(collectionView: UICollectionView, file: String = __FILE__, line: UInt = __LINE__) {
self.collectionView = collectionView
super.init(file: file, line: line)
self.didInsertListener = { [weak self] array, range in
guard let s = self, let collectionView = s.collectionView else { return }
collectionView.insertSections(NSIndexSet(array: Array(range)))
for section in range {
let sectionBond = UICollectionViewDataSourceSectionBond(collectionView: collectionView, section: section, file: file, line: line)
let sectionDynamic = array[section]
sectionDynamic.bindTo(sectionBond, fire: false, file: file, line: line)
s.sectionBonds.insert(sectionBond, atIndex: section)
for var idx = section + 1; idx < s.sectionBonds.count; idx++ {
s.sectionBonds[idx].section += 1
}
}
}
self.didRemoveListener = { [weak self] array, range in
guard let s = self, let collectionView = s.collectionView else { return }
collectionView.deleteSections(NSIndexSet(array: Array(range)))
for section in range.sort(>) {
s.sectionBonds[section].unbind(file: file, line: line)
s.sectionBonds.removeAtIndex(section)
for var idx = section; idx < s.sectionBonds.count; idx++ {
s.sectionBonds[idx].section -= 1
}
}
}
self.didUpdateListener = { [weak self] array, range in
guard let s = self, let collectionView = s.collectionView else { return }
collectionView.reloadSections(NSIndexSet(array: Array(range)))
for section in range {
let sectionBond = UICollectionViewDataSourceSectionBond(collectionView: collectionView, section: section, file: file, line: line)
let sectionDynamic = array[section]
sectionDynamic.bindTo(sectionBond, fire: false)
s.sectionBonds[section].unbind(file: file, line: line)
s.sectionBonds[section] = sectionBond
}
}
self.didResetListener = { [weak self] array in
if let collectionView = self?.collectionView {
collectionView.reloadData()
}
}
}
public func bind(dynamic: LazyObservableArray<UICollectionViewCell>, fire: Bool = true, file: String = __FILE__, line: UInt = __LINE__) {
bind(ObservableArray([dynamic], file: file, line: line), fire: fire, file: file, line: line)
}
public override func bind(dynamic: Observable<Array<LazyObservableArray<UICollectionViewCell>>>, fire: Bool, strongly: Bool, file: String = __FILE__, line: UInt = __LINE__) {
super.bind(dynamic, fire: fire, strongly: strongly, file: file, line: line)
if let dynamic = dynamic as? ObservableArray<LazyObservableArray<UICollectionViewCell>> {
for section in 0..<dynamic.count {
let sectionBond = UICollectionViewDataSourceSectionBond(collectionView: self.collectionView, section: section, file: file, line: line)
let sectionDynamic = dynamic[section]
sectionDynamic.bindTo(sectionBond, fire: false, file: file, line: line)
sectionBonds.append(sectionBond)
}
dataSource = CollectionViewDynamicArrayDataSource(dynamic: dynamic)
dataSource?.nextDataSource = self.nextDataSource
collectionView?.dataSource = dataSource
collectionView?.reloadData()
}
}
deinit {
self.unbind()
collectionView?.dataSource = nil
self.dataSource = nil
}
}
private var bondDynamicHandleUICollectionView: UInt8 = 0
extension UICollectionView /*: Bondable */ {
public var designatedBond: UICollectionViewDataSourceBond {
if let d: AnyObject = objc_getAssociatedObject(self, &bondDynamicHandleUICollectionView) {
return (d as? UICollectionViewDataSourceBond)!
} else {
let bond = UICollectionViewDataSourceBond(collectionView: self)
objc_setAssociatedObject(self, &bondDynamicHandleUICollectionView, bond, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return bond
}
}
}
public func ->> (left: LazyObservableArray<UICollectionViewCell>, right: UICollectionViewDataSourceBond) {
right.bind(left)
}
public func ->| (left: LazyObservableArray<UICollectionViewCell>, right: UICollectionViewDataSourceBond) {
right.bind(left, fire: false)
}
public func ->> (left: LazyObservableArray<UICollectionViewCell>, right: UICollectionView) {
left ->> right.designatedBond
}
public func ->| (left: LazyObservableArray<UICollectionViewCell>, right: UICollectionView) {
left ->| right.designatedBond
}
public func ->> (left: ObservableArray<LazyObservableArray<UICollectionViewCell>>, right: UICollectionView) {
left ->> right.designatedBond
}
public func ->| (left: ObservableArray<LazyObservableArray<UICollectionViewCell>>, right: UICollectionView) {
left ->| right.designatedBond
}
| mit | 9a43ad5107236a99a72b39ac1b016249 | 42.119816 | 604 | 0.652239 | 5.322526 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/categories/NSDate+Formatting.swift | 1 | 2998 | //
// NSDate+Formatting.swift
// TripKit
//
// Created by Adrian Schoenig on 19/02/2016.
// Copyright © 2016 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
extension Date {
/**
- returns: '1 hour, 10 minutes'
*/
public static func durationStringLong(forMinutes minutes: Int) -> String {
return durationString(minutes: minutes, unitsStyle: .full)
}
/**
- returns: '1hr 10min'
*/
public static func durationStringMedium(forMinutes minutes: Int) -> String {
return durationString(minutes: minutes, unitsStyle: .short)
}
/**
- returns: '1day'
*/
public static func durationString(forDays days: Int) -> String {
return durationString(days: days, unitsStyle: .abbreviated)
}
/**
- returns: '1h'
*/
public static func durationString(forHours hours: Int) -> String {
return durationString(hours: hours, unitsStyle: .abbreviated)
}
/**
- returns: '1h 10m'
*/
public static func durationString(forMinutes minutes: Int) -> String {
return durationString(minutes: minutes, unitsStyle: .abbreviated)
}
/**
- returns: '60s'
*/
public static func durationString(forSeconds seconds: TimeInterval) -> String {
return durationString(seconds: seconds, unitsStyle: .abbreviated)
}
/**
- returns: '1:10'
*/
public static func durationStringShort(forMinutes minutes: Int) -> String {
return durationString(minutes: minutes, unitsStyle: .positional)
}
private static func durationString(days: Int? = nil, hours: Int? = nil, minutes: Int? = nil, seconds: TimeInterval? = nil, unitsStyle: DateComponentsFormatter.UnitsStyle) -> String {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = unitsStyle
var components = DateComponents()
if let days = days {
components.day = days
} else if let hours = hours {
components.hour = hours
} else if let minutes = minutes {
if minutes > 59 {
components.hour = minutes / 60
}
components.minute = minutes % 60
} else if let seconds = seconds {
components.second = Int(seconds)
}
return formatter.string(from: components)!
}
public func minutesSince(_ other: Date) -> Int {
var o = Int(other.timeIntervalSince1970)
var m = Int(timeIntervalSince1970)
o = (o - o % 60) / 60
m = (m - m % 60) / 60
return m-o
}
public func durationSince(_ other: Date) -> String {
let minutes = minutesSince(other)
if minutes < 1 {
return ""
}
return Date.durationStringMedium(forMinutes:minutes)
}
public func durationShortSince(_ other: Date) -> String {
let minutes = minutesSince(other)
if minutes < 1 {
return ""
}
return Date.durationStringShort(forMinutes: minutes)
}
public func durationLongSince(_ other: Date) -> String {
let minutes = minutesSince(other)
if minutes < 1 {
return ""
}
return Date.durationStringLong(forMinutes: minutes)
}
}
| apache-2.0 | 520001f3b065958d3f179a6c73b2a7d9 | 25.289474 | 184 | 0.652319 | 4.122421 | false | false | false | false |
onthetall/CarouselView | CarouselViewDemoTests/CarouselViewDemoTests.swift | 1 | 2697 | //
// CarouselViewDemoTests.swift
// CarouselViewDemoTests
//
// Created by JERRY LIU on 17/11/2015.
// Copyright © 2015 ONTHETALL. All rights reserved.
//
import XCTest
@testable import CarouselViewDemo
class CarouselViewTests: XCTestCase {
let view = UIView(frame: CGRectMake(0, 0, 375, 200))
var carouselView: CarouselView?
let imageUrls = [
"http://someapi.com/thisimageurl1.jpg",
"http://someapi.com/thisimageurl2.jpg",
"http://someapi.com/thisimageurl3.jpg"]
override func setUp() {
super.setUp()
carouselView = CarouselView(frame: view.frame, imageUrls: imageUrls)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testContentSize() {
let w = self.view.frame.width
// width should be images.count + 1, for circular scroll
let content_width = w * CGFloat(imageUrls.count + 1)
XCTAssertEqual(content_width, carouselView!.scrollView!.contentSize.width)
}
func testPages() {
XCTAssertEqual(imageUrls.count, carouselView!.pageControl!.numberOfPages)
}
// func testPageControl() {
//
// carouselView!.layoutSubviews()
//
// // 8x left and right margin
// let pcWidth = self.view.frame.width - (2 * 8)
//
// // 18px bottom margin
// let pcY = self.view.frame.height - carouselView!.pageControl!.frame.height - 18
//
// XCTAssertEqual(pcWidth, carouselView!.pageControl!.frame.width)
// XCTAssertEqual(pcY, carouselView!.pageControl!.frame.origin.y)
// }
func testTimer() {
XCTAssertNotNil(carouselView!.timer)
XCTAssert(carouselView!.timer.valid)
}
func testsSetImageUrls() {
let newImageUrls = [
"http://api.anotherApp.com/image1.jpg",
"http://api.anotherApp.com/image2.jpg"
]
carouselView!.imageUrls = newImageUrls
XCTAssertEqual(newImageUrls.count, carouselView!.pageControl!.numberOfPages)
let w = self.view.frame.width
// width should be images.count + 1, for circular scroll
let content_width = w * CGFloat(newImageUrls.count + 1)
XCTAssertEqual(content_width, carouselView!.scrollView!.contentSize.width)
}
// func testDeinit() {
// weak var timer = carouselView!.timer
// self.carouselView = nil
//
// XCTAssertNotNil(timer)
// XCTAssert(timer?.valid == false)
//
// }
}
| mit | 3d6f8673423d63ad646d7439500c8c37 | 29.636364 | 111 | 0.606083 | 4.232339 | false | true | false | false |
izotx/iTenWired-Swift | Conference App/FNBJSocialFeed/FNBJSocialFeedTwitterTweet.swift | 1 | 2051 | //
// FNBJSocialFeedTwitterTweet.swift
// FNBJSocialFeed
//
// Created by Felipe on 5/31/16.
// Copyright © 2016 Academic Technology Center. All rights reserved.
//
import Foundation
enum FNBJSocialFeedTwitterTweetEnum : String{
case text
case user
case created_at
case id_str
case retweet_count
case favorite_count
}
class FNBJSocialFeedTwitterTweet{
/// Tweet's ID
var id = ""
/// Tweet Body text
var text = ""
/// Tweet's User
var user: FNBJSocialFeedTwitterUser!
/// Tweet's posted date
var date: NSDate!
/// Retweet Count
var retweetCount = 0
var favoriteCount = 0
init(){
}
init(dictionary: NSDictionary){
if let text = dictionary.objectForKey(FNBJSocialFeedTwitterTweetEnum.text.rawValue) as? String{
self.text = text
}
if let userData = dictionary.objectForKey(FNBJSocialFeedTwitterTweetEnum.user.rawValue) as? NSDictionary{
let user = FNBJSocialFeedTwitterUser(dictionary: userData)
self.user = user
}
if let dateString = dictionary.objectForKey(FNBJSocialFeedTwitterTweetEnum.created_at.rawValue) as? String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss ZZZ yyyy"
self.date = dateFormatter.dateFromString(dateString)
}
if let id = dictionary.objectForKey(FNBJSocialFeedTwitterTweetEnum.id_str.rawValue) as? String{
self.id = id
}
if let retweetCount = dictionary.objectForKey(FNBJSocialFeedTwitterTweetEnum.retweet_count.rawValue) as? Int{
self.retweetCount = retweetCount
}
if let favoriteCount = dictionary.objectForKey(FNBJSocialFeedTwitterTweetEnum.favorite_count.rawValue) as? Int{
self.favoriteCount = favoriteCount
}
}
} | bsd-2-clause | 521cf18f9643e3e7d14f7778da558080 | 24.320988 | 119 | 0.610732 | 5.283505 | false | false | false | false |
RxSwiftCommunity/RxSwiftExt | Tests/RxSwift/materialized+elementsTests.swift | 2 | 1724 | //
// Materialized+elementsTests.swift
// RxSwiftExt
//
// Created by Adam Borek on 12/04/2017.
// Copyright © 2017 RxSwift Community. All rights reserved.
//
import XCTest
import RxTest
import RxSwift
import RxSwiftExt
final class MaterializedElementsTests: XCTestCase {
private var testScheduler: TestScheduler!
private var eventObservable: Observable<Event<Int>>!
private let dummyError = NSError(domain: "dummy", code: -102)
private var disposeBag = DisposeBag()
override func setUp() {
super.setUp()
testScheduler = TestScheduler(initialClock: 0)
eventObservable = testScheduler.createHotObservable([
.next(0, Event.next(0)),
.next(100, Event.next(1)),
.next(200, Event.error(dummyError)),
.next(300, Event.next(2)),
.next(400, Event.error(dummyError)),
.next(500, Event.next(3))
]).asObservable()
}
override func tearDown() {
super.tearDown()
disposeBag = DisposeBag()
}
func test_elementsReturnsOnlyNextEvents() {
let observer = testScheduler.createObserver(Int.self)
eventObservable
.elements()
.subscribe(observer)
.disposed(by: disposeBag)
testScheduler.start()
XCTAssertEqual(observer.events, [
.next(0, 0),
.next(100, 1),
.next(300, 2),
.next(500, 3)
])
}
func test_errorsReturnsOnlyErrorEvents() {
let observer = testScheduler.createObserver(Error.self)
eventObservable
.errors()
.subscribe(observer)
.disposed(by: disposeBag)
testScheduler.start()
XCTAssertEqual(observer.events.map { $0.time }, [200, 400])
XCTAssertEqual(observer.events.map { $0.value.element! as NSError }, [dummyError, dummyError])
}
}
| mit | 45fa7bb52f4278993543b751caaea70e | 24.716418 | 96 | 0.670923 | 3.658174 | false | true | false | false |
gezhixin/MoreThanDrawerMenumDemo | special/PlayGround/MyPlayground.playground/Contents.swift | 1 | 437 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
str = "dasfasf"
for (var i = 0; i < 9; i++)
{
print("\(i)")
}
var img = UIImage(named: "icon_menu.png")
var imgView = UIImageView(image: img)
var a = 12.0
var s = "dafadfadfa\(a)"
var l = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
l.text = "asdfa"
str
func t(inout str: String)
{
str = "adfaf"
}
t(&str)
str
| mit | f86f51befa3e310ec7df146264a7cf35 | 13.096774 | 65 | 0.606407 | 2.540698 | false | false | false | false |
bazelbuild/tulsi | src/TulsiGenerator/TulsiNotifications.swift | 2 | 6896 | // Copyright 2016 The Tulsi 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
/// Sent when message information should be displayed to the user and/or sent to the system log.
/// The userInfo dictionary contains:
/// "level": String - The level of the message (see TulsiMessageLevel)
/// "message": String - The body of the message.
/// "details": String? - Optional detailed information about the message.
/// "context": String? - Optional contextual information about the message.
public let TulsiMessageNotification = "com.google.tulsi.Message"
/// Message levels used by TulsiMessage notifications.
public enum TulsiMessageLevel: String {
case Error, Warning, Syslog, Info, Debug
}
/// Message levels used for identifying priority and ordering in UI. @objc to use from a Storyboard.
@objc
public enum LogMessagePriority: Int {
case error, warning, syslog, info, debug
}
extension TulsiMessageLevel {
public var logRank: LogMessagePriority {
switch self {
case .Error:
return .error
case .Warning:
return .warning
case .Syslog:
return .syslog
case .Info:
return .info
case .Debug:
return .debug
}
}
}
public struct LogMessage {
public let level: TulsiMessageLevel
public let message: String
public let details: String?
public let context: String?
// Sends a notification to display any errors that have been logged with postError.
public static func displayPendingErrors() {
let userInfo = [ "displayErrors" : true ]
NotificationCenter.default.post(name: Notification.Name(rawValue: TulsiMessageNotification),
object: nil,
userInfo: userInfo)
}
// Sends a notification to log an error and adds it to a list of errors that can be displayed
// through the UI. Note that the errors are only displayed through the UI when
// displayPendingErrors() is called.
public static func postError(_ message: String, details: String? = nil, context: String? = nil) {
postMessage(.Error, message: message, details: details, context: context)
}
public static func postWarning(_ message: String, details: String? = nil, context: String? = nil) {
postMessage(.Warning, message: message, details: details, context: context)
}
public static func postInfo(_ message: String, details: String? = nil, context: String? = nil) {
postMessage(.Info, message: message, details: details, context: context)
}
public static func postSyslog(_ message: String, details: String? = nil, context: String? = nil) {
postMessage(.Syslog, message: message, details: details, context: context)
}
public static func postDebug(_ message: String, details: String? = nil, context: String? = nil) {
postMessage(.Debug, message: message, details: details, context: context)
}
/// Convenience method to post a notification that may be converted into a TulsiMessageItem.
private static func postMessage(_ level: TulsiMessageLevel,
message: String,
details: String? = nil,
context: String? = nil) {
var userInfo = [
"level": level.rawValue,
"message": message,
]
if let details = details {
userInfo["details"] = details
}
if let context = context {
userInfo["context"] = context
}
NotificationCenter.default.post(name: Notification.Name(rawValue: TulsiMessageNotification),
object: nil,
userInfo: userInfo)
}
public init?(notification: Notification) {
guard notification.name.rawValue == TulsiMessageNotification,
let userInfo = notification.userInfo,
let levelString = userInfo["level"] as? String,
let message = userInfo["message"] as? String,
let level = TulsiMessageLevel(rawValue: levelString) else {
return nil
}
self.level = level
self.message = message
self.details = userInfo["details"] as? String
self.context = userInfo["context"] as? String
}
}
/// Sent when the Tulsi generator initiates a task whose progress may be tracked.
/// The userInfo dictionary contains:
/// "name": String - The name of the task.
/// "maxValue": Int - The maximum value of the task
/// "progressNotificationName" - The name of the notification that will be sent when progress
/// changes.
/// "startIndeterminate" - Whether or not there might be an indeterminate delay before the first
/// update (for instance if a long initialization is required before actual work is begun).
public let ProgressUpdatingTaskDidStart = "com.google.tulsi.progressUpdatingTaskDidStart"
public let ProgressUpdatingTaskName = "name"
public let ProgressUpdatingTaskMaxValue = "maxValue"
public let ProgressUpdatingTaskStartIndeterminate = "startIndeterminate"
/// Sent when a task's progress changes.
/// The userInfo dictionary contains "value": Int - the new progress
public let ProgressUpdatingTaskProgress = "com.google.tulsi.progressUpdatingTaskProgress"
public let ProgressUpdatingTaskProgressValue = "value"
/// Sent when building source/setting groupings for indexer libraries.
public let GatheringIndexerSources = "gatheringIndexerSources"
/// Sent when creating Xcode build targets.
public let GeneratingBuildTargets = "generatingBuildTargets"
/// Sent when creating Xcode indexer targets.
public let GeneratingIndexerTargets = "generatingIndexerTargets"
/// Sent when copying the build scripts into the output Xcode project.
public let InstallingScripts = "installingScripts"
/// Sent when copying the build utilities into the output Xcode project.
public let InstallingUtilities = "installingUtilities"
/// Sent when copying the generator config into the output Xcode project.
public let InstallingGeneratorConfig = "installingGeneratorConfig"
/// Sent when starting to serialize the Xcode project.
public let SerializingXcodeProject = "serializingXcodeProject"
/// Sent when extracting source files from Bazel rules.
public let SourceFileExtraction = "sourceFileExtraction"
/// Sent when extracting workspace information.
public let WorkspaceInfoExtraction = "workspaceInfoExtraction"
| apache-2.0 | bafc7acec9fc1afc2311d00aca42f270 | 39.564706 | 101 | 0.705626 | 4.650034 | false | false | false | false |
petebarber/KeyChainItemCRUDKit | Example/Example/KeyChainViewController.swift | 1 | 1866 | import UIKit
import KeyChainItemCRUDKit
class KeyChainViewController: UIViewController
{
@IBOutlet weak var text1: UITextField!
@IBOutlet weak var status: UILabel!
let bundleId = NSBundle.mainBundle().bundleIdentifier!
let KEYCHAIN_ITEM_KEY = "FeedlyTokens"
let keyChainItem: KeyChainItem
var someData: SomeType = SomeType()
{
didSet
{
text1?.text = someData.textString1
}
}
required init?(coder aDecoder: NSCoder)
{
self.keyChainItem = KeyChainItem(bundleId: bundleId, keyChainItemKey: KEYCHAIN_ITEM_KEY)
super.init(coder: aDecoder)
}
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBAction func didEndOnExit(sender: UITextField)
{
print("didEndOnExit")
guard let text = sender.text else
{
return
}
someData.textString1 = text
}
@IBAction func clear(sender: AnyObject)
{
someData = SomeType()
}
@IBAction func load(sender: AnyObject)
{
if let someData = keyChainItem.load() as SomeType?
{
self.someData = someData
print("load, someData:\(self.someData.textString1)")
}
updateStatus("load")
}
@IBAction func save(sender: AnyObject)
{
print("save, someData:\(someData.textString1)")
keyChainItem.save(someData)
updateStatus("save")
}
@IBAction func deleteItem(sender: AnyObject)
{
keyChainItem.delete()
updateStatus("delete")
}
private func updateStatus(operation: String)
{
let lastResultAsText: String
switch (keyChainItem.lastResult)
{
case errSecSuccess:
lastResultAsText = "success"
case errSecItemNotFound:
lastResultAsText = "Item not found"
case errSecDuplicateItem:
lastResultAsText = "Duplicate item"
default:
lastResultAsText = "unknown"
}
status.text = "\(operation), lastResult:\(lastResultAsText)"
}
}
| mit | 03dbd57a0a13ebedd147f2f9e14513d2 | 18.040816 | 90 | 0.710611 | 3.494382 | false | false | false | false |
wess/overlook | Sources/overlook/commands/extension.swift | 1 | 327 | //
// base.swift
// overlook
//
// Created by Wesley Cope on 9/30/16.
//
//
import Foundation
import SwiftCLI
import config
extension Equatable where Self : Command {}
public func ==(lhs:Command, rhs:Command) -> Bool {
let left = lhs.name.lowercased()
let right = rhs.name.lowercased()
return left == right
}
| mit | 442da3b6b29139652999a866c1a74e8e | 15.35 | 50 | 0.663609 | 3.336735 | false | false | false | false |
fthomasmorel/insapp-iOS | Insapp/APIManager.swift | 1 | 5031 | //
// APIManager.swift
// Insapp
//
// Created by Florent THOMAS-MOREL on 9/12/16.
// Copyright © 2016 Florent THOMAS-MOREL. All rights reserved.
//
import Foundation
import Alamofire
class APIManager: AnyObject{
static var token:String!
static let group = DispatchGroup()
static func process(request: URLRequestConvertible, completion: @escaping (Optional<AnyObject>) -> (), errorBlock: @escaping (String, Int) -> (Bool)){
{ () -> Void in
var retry = false
//group.enter()
//DispatchQueue.global().async {
Alamofire.request(request).responseJSON { response in
guard let res = response.response else {
retry = errorBlock(kErrorServer, -1)
//group.leave()
return
}
var error = kErrorUnkown
if let dict = response.result.value as? Dictionary<String, AnyObject>{
if let err = dict["error"] as? String {
error = err
}
}
retry = errorBlock(error, res.statusCode)
if !retry {
completion(response.result.value as AnyObject)
}
//group.leave()
}
//}
//group.wait()
//return retry
}()
//DispatchQueue.global().async {
//let retry = proc()
//if retry {
// _ = proc()
//}
//}
}
static func requestWithToken(url:String, method: HTTPMethod, parameters: [String:AnyObject], completion: @escaping (Optional<AnyObject>) -> (), errorBlock:@escaping (String, Int) -> (Bool)){
guard let token = APIManager.token else { errorBlock("", 0) ; return }
let url = URL(string: "\(kAPIHostname)\(url)?token=\(token)")!
var req = URLRequest(url: url)
req.httpMethod = method.rawValue
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [])
APIManager.process(request: req, completion: completion, errorBlock: errorBlock)
}
static func requestWithToken(url:String, method: HTTPMethod, completion: @escaping (Optional<AnyObject>) -> (), errorBlock:@escaping (String, Int) -> (Bool)){
guard let token = APIManager.token else { errorBlock("", 0) ; return }
let url = URL(string: "\(kAPIHostname)\(url)?token=\(token)")!
var req = URLRequest(url: url)
req.httpMethod = method.rawValue
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
APIManager.process(request: req, completion: completion, errorBlock: errorBlock)
}
static func request(url:String, method: HTTPMethod, parameters: [String:AnyObject], completion: @escaping (Optional<AnyObject>) -> (), errorBlock:@escaping (String, Int) -> (Bool)){
let url = URL(string: "\(kAPIHostname)\(url)")!
var req = URLRequest(url: url)
req.httpMethod = method.rawValue
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [])
APIManager.process(request: req, completion: completion, errorBlock: errorBlock)
}
static func request(url:String, method: HTTPMethod, completion: @escaping (Optional<AnyObject>) -> (), errorBlock:@escaping (String, Int) -> (Bool)){
let url = URL(string: "\(kAPIHostname)\(url)")!
var req = URLRequest(url: url)
req.httpMethod = method.rawValue
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
APIManager.process(request: req, completion: completion, errorBlock: errorBlock)
}
static func requestCas(url:String, method: HTTPMethod, parameters: [String:AnyObject], completion: @escaping (Bool) -> (), errorBlock:@escaping (String, Int) -> (Bool)){
let url = URL(string: "\(kCASHostname)\(url)")!
var req = URLRequest(url: url)
guard let username = parameters[kLoginUsername] else { completion(false) ; return }
guard let password = parameters[kLoginPassword] else { completion(false) ; return }
let data = "username=\(username)&password=\(password)"
req.httpMethod = method.rawValue
req.setValue("text/plain", forHTTPHeaderField: "Content-Type")
req.httpBody = data.data(using: .utf8, allowLossyConversion: false)
Alamofire.request(req).response { (response) in
guard let res = response.response, res.statusCode == 201 else {
completion(false)
return
}
completion(true)
}
}
}
| mit | 890e7870970b6df84fc8bcff0749c68d | 41.627119 | 194 | 0.576541 | 4.888241 | false | false | false | false |
wolfposd/Caffeed | FeedbackBeaconContext/FeedbackBeaconContext/FeedbackSheet/View/ToSCell.swift | 1 | 1560 | //
// ToSCell.swift
// DynamicFeedbackSheets
//
// Created by Jan Hennings on 09/06/14.
// Copyright (c) 2014 Jan Hennings. All rights reserved.
//
import UIKit
class ToSCell: ModuleCell {
// MARK: Properties
@IBOutlet var titleLabel: UILabel!
@IBOutlet var textView: UITextView!
@IBOutlet var acceptButton: UIButton!
@IBOutlet var declineButton: UIButton!
override var module: FeedbackSheetModule? {
willSet {
if let toS = newValue as? ToSModule {
titleLabel.text = toS.title
textView.text = toS.text
acceptButton.enabled = true
declineButton.enabled = true
}
}
}
// FIXME: Testing, current Bug in Xcode (Ambiguous use of module)
override func setModule(module: FeedbackSheetModule) {
self.module = module
}
// MARK: View Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
acceptButton.layer.cornerRadius = 3
declineButton.layer.cornerRadius = 3
}
// MARK: IBActions
@IBAction func accept(sender: UIButton) {
if let toS = module as? ToSModule {
toS.responseData = true
delegate?.moduleCell(self, didGetResponse: toS.responseData, forID: toS.ID)
}
}
@IBAction func decline(sender: UIButton) {
if let toS = module as? ToSModule {
toS.responseData = false
delegate?.moduleCell(self, didGetResponse: toS.responseData, forID: toS.ID)
}
}
}
| gpl-3.0 | c0016e0ce768f1d9397f4a9b1f3c944a | 25 | 87 | 0.607051 | 4.382022 | false | false | false | false |
17thDimension/AudioKit | Examples/iOS/Swift/AudioKitDemo/AudioKitDemo/Analysis/AnalysisViewController.swift | 1 | 3577 | //
// AnalysisViewController.swift
// AudioKitDemo
//
// Created by Nicholas Arner on 3/1/15.
// Copyright (c) 2015 AudioKit. All rights reserved.
//
class AnalysisViewController: UIViewController {
@IBOutlet var frequencyLabel: UILabel!
@IBOutlet var amplitudeLabel: UILabel!
@IBOutlet var noteNameLabel: UILabel!
@IBOutlet var amplitudePlot: AKInstrumentPropertyPlot!
@IBOutlet var frequencyPlot: AKInstrumentPropertyPlot!
var normalizedFrequency = AKInstrumentProperty(value: 0, minimum: 16.35, maximum: 30.87)
@IBOutlet var normalizedFrequencyPlot: AKFloatPlot!
let analyzer: AKAudioAnalyzer
let microphone: Microphone
let noteFrequencies = [16.35,17.32,18.35,19.45,20.6,21.83,23.12,24.5,25.96,27.5,29.14,30.87]
let noteNamesWithSharps = ["C", "C♯","D","D♯","E","F","F♯","G","G♯","A","A♯","B"]
let noteNamesWithFlats = ["C", "D♭","D","E♭","E","F","G♭","G","A♭","A","B♭","B"]
let analysisSequence = AKSequence()
let updateAnalysis = AKEvent()
override init() {
microphone = Microphone()
analyzer = AKAudioAnalyzer(audioSource: microphone.auxilliaryOutput)
super.init()
}
required init(coder aDecoder: NSCoder) {
microphone = Microphone()
analyzer = AKAudioAnalyzer(audioSource: microphone.auxilliaryOutput)
super.init(coder: aDecoder)
}
override func viewDidLoad(animated: Bool) {
super.viewDidLoad(animated)
AKOrchestra.addInstrument(microphone)
AKOrchestra.addInstrument(analyzer)
analyzer.play()
microphone.play()
let analysisSequence = AKSequence()
var updateAnalysis = AKEvent()
updateAnalysis = AKEvent(block: {
self.updateUI()
analysisSequence.addEvent(updateAnalysis, afterDuration: 0.1)
})
analysisSequence.addEvent(updateAnalysis)
analysisSequence.play()
amplitudePlot.property = analyzer.trackedAmplitude
frequencyPlot.property = analyzer.trackedFrequency
normalizedFrequencyPlot.minimum = 15
normalizedFrequencyPlot.maximum = 32
}
func updateUI() {
if analyzer.trackedAmplitude.value > 0.1 {
frequencyLabel.text = String(format: "%0.1f", analyzer.trackedFrequency.value)
var frequency = analyzer.trackedFrequency.value
while (frequency > Float(noteFrequencies[noteFrequencies.count-1])) {
frequency = frequency / 2.0
}
while (frequency < Float(noteFrequencies[0])) {
frequency = frequency * 2.0
}
normalizedFrequency.value = frequency
normalizedFrequencyPlot.updateWithValue(frequency)
var minDistance: Float = 10000.0
var index = 0
for (var i = 0; i < noteFrequencies.count; i++){
var distance = fabsf(Float(noteFrequencies[i]) - frequency)
if (distance < minDistance){
index = i
minDistance = distance
}
}
var octave = Int(log2f(analyzer.trackedFrequency.value / frequency))
var noteName = String(format: "%@%d", noteNamesWithSharps[index], octave, noteNamesWithFlats[index], octave)
noteNameLabel.text = noteName
}
amplitudeLabel.text = String(format: "%0.2f", analyzer.trackedAmplitude.value)
}
} | lgpl-3.0 | 6f5e107247f6a74562f25f41ac046f24 | 35.680412 | 120 | 0.609502 | 4.607513 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Cocoa/Components/XCPageViewController.swift | 1 | 9481 | //
// Xcore
// Copyright © 2014 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
// MARK: - PageControlPosition
extension XCPageViewController {
public enum PageControlPosition {
case none
case top
case center
case bottom
}
}
// MARK: - XCPageViewController
open class XCPageViewController: UIViewController {
public let pageControlHeight: CGFloat = 40
open var pageControlPosition: PageControlPosition = .bottom
public let pageControl = UIPageControl().apply {
$0.isUserInteractionEnabled = false
}
private var _pageViewController: XCUIPageViewController? {
pageViewController as? XCUIPageViewController
}
open private(set) var pageViewController: UIPageViewController!
open var viewControllers: [UIViewController] = [] {
didSet {
guard isViewLoaded else { return }
updateIfNeeded(shouldSetInitialViewController: oldValue.isEmpty)
}
}
/// The default value is `false`.
open var isBounceForSinglePageEnabled = false
open var isScrollEnabled = true {
didSet { _pageViewController?.isScrollEnabled = isScrollEnabled }
}
open var scrollView: UIScrollView? {
_pageViewController?.scrollView
}
/// Spacing between between pages. The default value is `0`.
///
/// Page spacing is only valid if the transition style is `.scroll`.
open var pageSpacing: CGFloat = 0
open var transitionStyle: UIPageViewController.TransitionStyle = .scroll
open var navigationOrientation: UIPageViewController.NavigationOrientation = .horizontal
private var didChangeCurrentPage: ((_ index: Int) -> Void)?
/// A callback for listening to page change events.
open func didChangeCurrentPage(_ callback: ((_ index: Int) -> Void)? = nil) {
didChangeCurrentPage = callback
}
public convenience init(viewControllers: [UIViewController], pageSpacing: CGFloat = 0) {
self.init(nibName: nil, bundle: nil)
self.viewControllers = viewControllers
self.pageSpacing = pageSpacing
}
open override func viewDidLoad() {
super.viewDidLoad()
setupPageViewController()
}
private func setupPageViewController() {
pageViewController = XCUIPageViewController(
transitionStyle: transitionStyle,
navigationOrientation: navigationOrientation,
options: [.interPageSpacing: pageSpacing]
).apply {
$0.delegate = self
$0.dataSource = self
}
addViewController(pageViewController, enableConstraints: true)
_pageViewController?.isScrollEnabled = isScrollEnabled
view.addSubview(pageControl)
setupConstraints()
updateIfNeeded(shouldSetInitialViewController: true)
}
private func updateIfNeeded(shouldSetInitialViewController: Bool) {
pageControl.numberOfPages = viewControllers.count
pageControl.isHidden = viewControllers.count < 2
if viewControllers.count == 1 {
_pageViewController?.isBounceForSinglePageEnabled = isBounceForSinglePageEnabled
}
if shouldSetInitialViewController {
setCurrentPage(0)
}
}
private func setupConstraints() {
pageControl.anchor.make {
$0.height.equalTo(pageControlHeight)
guard pageControlPosition != .none else { return }
$0.horizontally.equalToSuperview()
switch pageControlPosition {
case .none:
break
case .top:
$0.top.equalTo(view)
case .center:
$0.centerY.equalTo(view)
case .bottom:
$0.bottom.equalTo(view)
}
}
}
}
// MARK: - UIPageViewControllerDataSource & UIPageViewControllerDelegate
extension XCPageViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate {
open func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController
) -> UIViewController? {
let indexOfCurrentVC = indexOf(viewController)
return indexOfCurrentVC < viewControllers.count - 1 ? viewControllers[indexOfCurrentVC + 1] : nil
}
open func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController
) -> UIViewController? {
let indexOfCurrentVC = indexOf(viewController)
return indexOfCurrentVC > 0 ? viewControllers[indexOfCurrentVC - 1] : nil
}
open func pageViewController(
_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool
) {
guard
completed,
let newViewController = pageViewController.viewControllers?.first
else {
return
}
let index = indexOf(newViewController)
pageControl.currentPage = index
updateStatusBar(for: index)
didChangeCurrentPage?(pageControl.currentPage)
}
}
// MARK: - Navigation API
extension XCPageViewController {
/// Set current view controller index to be displayed.
///
/// - Parameters:
/// - index: The index of the view controller to be displayed.
/// - direction: The navigation direction. The default value is `nil`, meaning
/// automatically determine the direction.
/// - animated: A boolean value that indicates whether the transition is to be
/// animated. The default value is `false`.
/// - completion: A closure to be called when setting the current view
/// controller animation completes. The default value is `nil`.
open func setCurrentPage(
_ index: Int,
direction: UIPageViewController.NavigationDirection? = nil,
animated: Bool = false,
completion: ((Bool) -> Void)? = nil
) {
guard viewControllers.count > index else {
return
}
let viewControllerAtIndex = viewControllers[index]
let direction = direction ?? (index > pageControl.currentPage ? .forward : .reverse)
// swiftlint:disable:next trailing_closure
pageViewController.setViewControllers(
[viewControllerAtIndex],
direction: direction,
animated: animated,
completion: { [weak self] finished in
self?.pageControl.currentPage = index
completion?(finished)
}
)
updateStatusBar(for: index)
}
open func remove(_ viewController: UIViewController) {
guard let index = viewControllers.firstIndex(of: viewController) else {
return
}
viewControllers.remove(at: index)
reloadData()
}
open func replace(
_ viewController: UIViewController,
with newViewControllers: [UIViewController]
) {
guard let index = viewControllers.firstIndex(of: viewController) else {
return
}
viewControllers.remove(at: index)
viewControllers.insert(contentsOf: newViewControllers, at: index)
reloadData()
}
open func reloadData() {
setCurrentPage(pageControl.currentPage)
}
}
// MARK: - Helpers
extension XCPageViewController {
private func indexOf(_ viewController: UIViewController) -> Int {
viewControllers.firstIndex(of: viewController) ?? 0
}
private func updateStatusBar(for index: Int) {
guard let vc = viewControllers.at(index) else { return }
if let nvc = vc as? UINavigationController {
statusBarStyle = nvc.preferredStatusBarStyle
} else {
statusBarStyle = vc.statusBarStyle ?? vc.preferredStatusBarStyle
}
}
}
// MARK: - Statusbar and Orientation
extension XCPageViewController {
open override var prefersStatusBarHidden: Bool {
isStatusBarHidden ?? super.prefersStatusBarHidden
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
statusBarStyle ?? super.preferredStatusBarStyle
}
open override var shouldAutorotate: Bool {
isAutorotateEnabled ?? super.shouldAutorotate
}
open override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
statusBarUpdateAnimation ?? super.preferredStatusBarUpdateAnimation
}
}
// MARK: - XCUIPageViewController
private final class XCUIPageViewController: UIPageViewController {
// Subclasses have to be responsible when using this setting as view controller
// count stays at one when the bounce is disabled.
var isBounceForSinglePageEnabled = true
var isScrollEnabled = true {
didSet {
scrollView?.isScrollEnabled = isScrollEnabled
}
}
var scrollView: UIScrollView? {
didSet {
scrollView?.bounces = isBounceForSinglePageEnabled
scrollView?.isScrollEnabled = isScrollEnabled
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard scrollView == nil else { return }
for view in view.subviews {
if let aScrollView = view as? UIScrollView {
scrollView = aScrollView
}
}
}
}
| mit | e68d3e91151e48934a55573a5ab56fcb | 30.390728 | 105 | 0.653481 | 5.752427 | false | false | false | false |
safx/EJDB-Swift | Source/Database.swift | 1 | 1349 | //
// Database.swift
// EJDB-Swift
//
// Created by Safx Developer on 2015/07/28.
// Copyright © 2015年 Safx Developers. All rights reserved.
//
import Foundation
public final class Database {
internal let jb: COpaquePointer
public init() {
jb = ejdbnew()
}
deinit {
close()
}
public func open(path: String, mode: OpenMode) -> Bool { // TODO: throws
return path.withCString { str in
return ejdbopen(jb, str, Int32(mode.rawValue))
}
}
public func close() -> Bool { // TODO: throws
return ejdbclose(jb)
}
public func delete() {
ejdbdel(jb)
}
public var isOpen: Bool {
return ejdbisopen(jb)
}
public var meta: BSON {
let m = ejdbmeta(jb)
assert(m != nil)
return BSON(b: m.memory)
}
public func sync() -> Bool {
return ejdbsyncdb(jb)
}
public func removeCollection(name: String, database: Database, unlinkFile: Bool) {
return name.withCString { str in
ejdbrmcoll(jb, str, unlinkFile)
}
}
public func getCollection(name: String) -> Collection {
return name.withCString { str in
let coll = ejdbgetcoll(jb, str)
assert(coll != nil)
return Collection(coll: coll)
}
}
} | mit | b147645cca7ae5c2c8e2d6de2c9dd259 | 19.409091 | 86 | 0.562407 | 3.770308 | false | false | false | false |
BlackDragonF/Doooge | My Doooge/AnimationView.swift | 3 | 1880 | //
// AnimationView.swift
// Doooge
//
// Created by VicChan on 2016/11/20.
// Copyright © 2016年 VicChan. All rights reserved.
//
import UIKit
protocol AnimationViewDelegete {
func didStopAnimating()
func touchedImage()
}
class AnimationView: UIImageView {
typealias ImageName = String
var tapGesture: UITapGestureRecognizer!
var delegate: AnimationViewDelegete?
override init(frame: CGRect) {
super.init(frame: frame)
//self.addObserver(self, forKeyPath: #keyPath(AnimationView.isAnimating), options: [.old,.new], context: nil)
tapGesture = UITapGestureRecognizer(target: self, action: #selector(AnimationView.tap(_:)))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
self.isUserInteractionEnabled = true
self.addGestureRecognizer(tapGesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func play(_ imageNames: [ImageName], _ repeated: Bool, _ per: Double = 0.3) {
self.animationImages?.removeAll()
self.animationImages = nil
contentMode = .scaleAspectFill
let images = imageNames.map { (name) -> UIImage in
return AnimationEngine.FileManager.manager.image(name)!
}
self.animationImages = images
let count = images.count
self.animationDuration = Double(count) * per
self.animationRepeatCount = repeated ? 0 : 1
startAnimating()
}
func tap(_ sender: UITapGestureRecognizer) {
delegate?.touchedImage()
}
func stop() {
if isAnimating {
stopAnimating()
}
}
deinit {
// self.removeObserver(self, forKeyPath: #keyPath(AnimationView.isAnimating))
}
}
| apache-2.0 | 59cfcb784e2acaae8f95ee6949101da3 | 25.069444 | 117 | 0.627597 | 4.888021 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Etc/SLVDirectSignPopup.swift | 1 | 3855 | //
// SLVDirectSignPopup.swift
// selluv-ios
//
// Created by 조백근 on 2017. 1. 12..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import UIKit
class SLVDirectSignPopup: UIView {
var config:STZPopupViewConfig?
var controller:UIViewController?
@IBOutlet weak var itemImageView: UIImageView!
@IBOutlet weak var itemNameLabel: UILabel!
@IBOutlet weak var itemDescLabel: UILabel!
@IBOutlet weak var sizeLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var guideImageView: UIView!
@IBOutlet weak var signImageView: DrawableImageView!
@IBOutlet weak var okButton: UIButton!
var isSign = false
override func awakeFromNib() {
super.awakeFromNib()
}
internal required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}
func binding() {
self.isSign = false
self.signImageView.prepare()
self.okButton.backgroundColor = bg_color_g245
self.okButton.setTitleColor(text_color_g181, for: .normal)
self.signImageView.firstTouchBlock = {
self.okButton.backgroundColor = bg_color_blue
self.okButton.setTitleColor(UIColor.white, for: .normal)
self.guideImageView.isHidden = true
self.isSign = true
}
}
func bindingData() {
let image = UIImage(color: UIColor.clear, size: self.signImageView.bounds.size)
self.signImageView.image = image
let model = TempInputInfoModel.shared.currentModel
let photoList = model.photoList
if photoList.count > 0 {
let photo = photoList.first
let image = photo?.thumbnailImage()
itemImageView.image = image
itemImageView.contentMode = .scaleAspectFit
}
var name = model.brandKorean
if model.isEnBrandName == true {
name = model.brandEnglish
}
if let nm = name {
self.itemNameLabel.text = nm
}
var itemDesc = ""
let color = model.additionalColorKey
let modelName = model.additionalModel
let desc = model.additionalDescription
if let col = color {
itemDesc = col
}
if let mName = modelName {
itemDesc = itemDesc + " " + mName
}
if let descript = desc {
itemDesc = itemDesc + " " + descript
}
self.itemDescLabel.text = itemDesc
let sizeInfo = model.itemSizeData
let sizeIndex = model.itemSizeIndex
if sizeInfo != nil && (sizeInfo!.count) > 0 && sizeIndex != nil {
let data = sizeInfo![sizeIndex!]
self.sizeLabel.text = data
}
let price = model.productPrice
if let amount = price {
let value = amount.float
let comma = "₩ " + String.decimalAmountWithForm(value: value!, pointCount: 0)
self.priceLabel.text = comma
}
}
func popBaseConstraints(config: STZPopupViewConfig, parent: UIViewController) {
self.config = config
self.controller = parent
self.translatesAutoresizingMaskIntoConstraints = true
}
func touchClose(sender: AnyObject) {
controller!.dismissPopupView()
}
@IBAction func touchRegister(_ sender: Any) {
if self.isSign == true {
let image = self.signImageView.share()
if image != nil {
TempInputInfoModel.shared.currentModel.isSignature = true
TempInputInfoModel.shared.currentModel.signImage = image
}
}
self.touchClose(sender: sender as AnyObject)
}
}
| mit | 1b7ab0ba07ea5451d02b981f643254d3 | 29.03125 | 89 | 0.596254 | 4.687805 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/Protocol/SLVTypealisa.swift | 1 | 1196 | //
// SLVTypealisa.swift
// selluv-ios
//
// Created by 조백근 on 2017. 1. 16..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
typealias UpdateImagesBlock = (_ photos: [MyPhoto]?) -> ()//SLV_316_SellDirectStep1PhotoController
typealias TouchBlock = (_ button: UIButton?) -> ()//SLVDemageInputCell
typealias TouchBlockTag = (_ isAdd: Bool, _ title: String, _ button: UIButton) -> ()//SLVDemageInputCell
typealias PhotoDeleteBlock = (_ path: IndexPath) -> ()//SLVPhotoEditPageCell
typealias PhotoRatioBlock = (_ path: IndexPath, _ scale: CGFloat, _ frame: CGRect) -> ()//SLVPhotoEditPageCell
typealias PhotoModeBlock = (_ mode: UIViewContentMode) -> ()//SLVPhotoEditPageCell
typealias PhotoControlBlock = (_ myPath: IndexPath, _ isDelete: Bool) -> ()//SLVPhotoSelectionCell
typealias TouchButtonBlock = (_ name: String, _ index: Int, _ button: UIButton) -> ()//SLVPickerButton
typealias TouchRequiredItemButtonBlock = (_ button: UIButton) -> ()//SLVRequiredItemButtonBlock
typealias TouchTypeButtonBlock = (_ key: String, _ button: UIButton) -> ()
typealias TouchPushSwitchBlock = (_ key: String, _ button: UISwitch) -> ()//SLV916MyPagePushCell
| mit | 8df6ac270e87e68cc72da1661b3ccb9c | 34.969697 | 110 | 0.718618 | 3.983221 | false | false | false | false |
frograin/FluidValidator | Pod/Classes/Core/LocalizationHelper.swift | 1 | 1098 | //
// LocalizationHelper.swift
// TestValidator
//
// Created by FrogRain on 31/01/16.
// Copyright © 2016 FrogRain. All rights reserved.
//
import Foundation
class LocalizationHelper {
class func localizeThis(_ key:String) -> String {
let mainBundle = Bundle.main
var localizedString = NSLocalizedString(key, tableName: "object_validator_custom", bundle: mainBundle, comment:"")
if(localizedString != key) {
return localizedString
}
guard let frameworkPath = Bundle(for: LocalizationHelper.self).resourcePath else {
return key
}
guard let path = URL(string: frameworkPath)?.appendingPathComponent("FluidValidator.bundle").path else {
return key
}
guard let bundle = Bundle(path: path) else {
return key
}
localizedString = NSLocalizedString(key, tableName: "object_validator", bundle: bundle, comment:"")
if(localizedString != key) {
return localizedString
}
return key
}
}
| mit | c68758a07bf24719f0461860f5ee5484 | 28.648649 | 122 | 0.608933 | 4.963801 | false | false | false | false |
buttacciot/Hiragana | Hiragana/MasterController.swift | 1 | 4687 | //
// MenuController.swift
// Hiragana
//
// Created by Travis Buttaccio on 6/5/16.
// Copyright © 2016 LangueMatch. All rights reserved.
//
import UIKit
class MasterController: UIViewController {
/*
MARK:- Vars
*/
var selectedQuiz: Int?
/*
MARK:- IBOutlets
*/
@IBOutlet weak var tableView: UITableView!
/*
MARK: - Constants
*/
lazy var helper: TABCoreDataHelper = {
let cdh = TABCoreDataHelper()
cdh.entityName = "TABDrawingSymbol"
cdh.defaultSortAttribute = "romanLetter"
let isInitialized = cdh.hasStore
cdh.setupCoreData()
if !isInitialized { cdh.initializeDrawingSymbols() }
cdh.fetchData()
return cdh
}()
lazy var testing: TABCoreDataHelper = {
let cdh = TABCoreDataHelper()
cdh.entityName = "TABTestingSymbol"
cdh.defaultSortAttribute = "romanLetter"
cdh.setupCoreData()
cdh.initializeTestingSymbols()
cdh.fetchData()
return cdh
}()
/*
MARK: - Lifecycle
*/
override func viewDidLoad() {
super.viewDidLoad()
DefaultTheme.sharedAPI.themeViewController(self, type: .Master)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIApplication.sharedApplication().statusBarHidden = false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Practice" {
guard let destVC = segue.destinationViewController as? PracticeController else { return }
destVC.viewModel = TABMainViewModel(model: helper.context, entity: "TABDrawingSymbol")
} else if segue.identifier == "Selection" {
guard let destVC = segue.destinationViewController as? TABSelectionViewController else { return }
destVC.delegate = self
destVC.viewModel = TABSelectionViewModel(model: testing.context, entity: "TABTestingSymbol")
} else if segue.identifier == "GuessingGame" {
guard let destVC = segue.destinationViewController as? TABQuizViewController else { return }
destVC.viewModel = TABQuizViewModel(model: sender)
}
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
tableView.reloadData()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
extension MasterController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! MenuItemCell
cell.configureMenuItemCell(indexPath.row)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return CGRectGetHeight(tableView.bounds)/3
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0:
performSegueWithIdentifier("Practice", sender: nil)
case 1:
fallthrough
case 2:
performSegueWithIdentifier("Selection", sender: nil)
selectedQuiz = indexPath.item
default: break
}
}
}
extension MasterController: TABSelectionViewDelegate {
func selectionView(controller: TABSelectionViewController!, didPressPlayButton sender: UIButton!, withSymols symbols: [AnyObject]!) {
guard let selectedQuiz = selectedQuiz else { return }
switch selectedQuiz {
case 1:
performSegueWithIdentifier("GuessingGame", sender: symbols)
default: break
}
}
}
class MenuItemCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var customImageView: UIImageView!
func configureMenuItemCell(idx: Int) {
DefaultTheme.sharedAPI.themeView(self, type: .MenuItem(idx: idx))
}
} | mit | 68fd0de148963afc142de47c8ead4bf9 | 31.776224 | 137 | 0.663466 | 5.265169 | false | false | false | false |
austinzheng/swift-compiler-crashes | crashes-duplicates/06115-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 11 | 358 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S<T where T.Element == e) { e: B<T : B<I : d = e) -> c { e: A? {
typealias e = ")
let a {
struct S<T.B == g: NSObject {
class B<D> c { e) { }
protocol A : A")
protocol A : B<D> Void
| mit | 448f84fffd77d80c7e6f7bf3c964d43d | 31.545455 | 87 | 0.639665 | 3.008403 | false | true | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/News/View/CompositionalTableViewDataSourceTests.swift | 1 | 12213 | import EurofurenceApplication
import UIKit
import XCTest
class CompositionalTableViewDataSourceTests: XCTestCase {
private var composition: CompositionalTableViewDataSource!
private var tableView: UITableView!
override func setUp() {
super.setUp()
tableView = UITableView(frame: .zero)
composition = CompositionalTableViewDataSource(tableView: tableView)
}
// MARK: Data source composition
func testActsAsDelegateForTableView() {
XCTAssertIdentical(composition, tableView.delegate)
}
func testAddingSectionAllowsItToRegisterReusableViews() {
let mediator = FakeTableViewMediator()
composition.append(mediator)
XCTAssertIdentical(tableView, mediator.tableViewForReusableViewRegistration)
}
func testNumberOfSectionsEqualsNumberOfDataSources() {
XCTAssertEqual(0, tableView.numberOfSections)
composition.append(FakeTableViewMediator())
XCTAssertEqual(1, tableView.numberOfSections)
}
func testNumberOfRowsInferredFromDataSource() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
firstDataSource.numberOfRows = 5
secondDataSource.numberOfRows = 10
composition.append(firstDataSource)
composition.append(secondDataSource)
XCTAssertEqual(5, tableView.numberOfRows(inSection: 0))
XCTAssertEqual(10, tableView.numberOfRows(inSection: 1))
}
func testDataSourceNotifiesContentsChangedReloadsSection() {
let dataSource = FakeTableViewMediator()
dataSource.numberOfRows = 5
composition.append(dataSource)
dataSource.numberOfRows = 10
XCTAssertEqual(10, tableView.numberOfRows(inSection: 0))
}
func testCellInferredFromDataSource() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
let (firstCell, secondCell) = (UITableViewCell(), UITableViewCell())
firstDataSource.stub(cell: firstCell, forRowAt: IndexPath(row: 0, section: 0))
secondDataSource.stub(cell: secondCell, forRowAt: IndexPath(row: 0, section: 1))
composition.append(firstDataSource)
composition.append(secondDataSource)
XCTAssertIdentical(firstCell, composition.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 0)))
XCTAssertIdentical(secondCell, composition.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 1)))
}
// MARK: Table view delegate composition
func testSelectedCellNotifiesDataSourceForSection() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
composition.append(firstDataSource)
composition.append(secondDataSource)
let firstCellFirstSection = IndexPath(row: 0, section: 0)
let firstCellSecondSection = IndexPath(row: 0, section: 1)
composition.tableView(tableView, didSelectRowAt: firstCellFirstSection)
XCTAssertEqual(firstCellFirstSection, firstDataSource.selectedIndexPath)
XCTAssertNil(secondDataSource.selectedIndexPath)
composition.tableView(tableView, didSelectRowAt: firstCellSecondSection)
XCTAssertEqual(firstCellFirstSection, firstDataSource.selectedIndexPath)
XCTAssertEqual(firstCellSecondSection, secondDataSource.selectedIndexPath)
}
func testEstimatedHeightForHeaderInSectionInferredFromSection() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
composition.append(firstDataSource)
composition.append(secondDataSource)
firstDataSource.numberOfRows = 1
secondDataSource.numberOfRows = 1
firstDataSource.stub(44, asEstimatedHeightForHeaderInSection: 0)
secondDataSource.stub(22, asEstimatedHeightForHeaderInSection: 1)
XCTAssertEqual(44, composition.tableView(tableView, estimatedHeightForHeaderInSection: 0))
XCTAssertEqual(22, composition.tableView(tableView, estimatedHeightForHeaderInSection: 1))
}
func testEstimatedHeightForHeaderInSectionZeroWhenSectionEmpty() {
let dataSource = FakeTableViewMediator()
composition.append(dataSource)
dataSource.numberOfRows = 0
dataSource.stub(44, asEstimatedHeightForHeaderInSection: 0)
XCTAssertEqual(0, composition.tableView(tableView, estimatedHeightForHeaderInSection: 0))
}
func testViewForHeaderInSectionInferredFromSection() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
firstDataSource.numberOfRows = 5
secondDataSource.numberOfRows = 10
composition.append(firstDataSource)
composition.append(secondDataSource)
let (firstHeader, secondHeader) = (UIView(), UIView())
firstDataSource.stub(firstHeader, asViewForHeaderInSection: 0)
secondDataSource.stub(secondHeader, asViewForHeaderInSection: 1)
XCTAssertIdentical(firstHeader, composition.tableView(tableView, viewForHeaderInSection: 0))
XCTAssertIdentical(secondHeader, composition.tableView(tableView, viewForHeaderInSection: 1))
}
func testViewForHeaderInSectionNilWhenSectionEmpty() {
let dataSource = FakeTableViewMediator()
dataSource.numberOfRows = 0
composition.append(dataSource)
let header = UIView()
dataSource.stub(header, asViewForHeaderInSection: 0)
XCTAssertNil(composition.tableView(tableView, viewForHeaderInSection: 0))
}
func testViewForFooterInSectionInferredFromSection() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
composition.append(firstDataSource)
composition.append(secondDataSource)
let (firstHeader, secondHeader) = (UIView(), UIView())
firstDataSource.stub(firstHeader, asViewForFooterInSection: 0)
secondDataSource.stub(secondHeader, asViewForFooterInSection: 1)
XCTAssertIdentical(firstHeader, composition.tableView(tableView, viewForFooterInSection: 0))
XCTAssertIdentical(secondHeader, composition.tableView(tableView, viewForFooterInSection: 1))
}
func testHeightForFooterInSectionInferredFromSection() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
composition.append(firstDataSource)
composition.append(secondDataSource)
firstDataSource.stub(10, asHeightForFooterInSection: 0)
secondDataSource.stub(42, asHeightForFooterInSection: 1)
XCTAssertEqual(10, composition.tableView(tableView, heightForFooterInSection: 0))
XCTAssertEqual(42, composition.tableView(tableView, heightForFooterInSection: 1))
}
func testEstimatedHeightForRowAtInferredFromSection() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
composition.append(firstDataSource)
composition.append(secondDataSource)
let firstCellFirstSection = IndexPath(row: 0, section: 0)
let firstCellSecondSection = IndexPath(row: 0, section: 1)
firstDataSource.stub(44, asEstimatedHeightForRowAt: firstCellFirstSection)
secondDataSource.stub(22, asEstimatedHeightForRowAt: firstCellSecondSection)
XCTAssertEqual(44, composition.tableView(tableView, estimatedHeightForRowAt: firstCellFirstSection))
XCTAssertEqual(22, composition.tableView(tableView, estimatedHeightForRowAt: firstCellSecondSection))
}
func testHeightForRowAtInferredFromSection() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
composition.append(firstDataSource)
composition.append(secondDataSource)
let firstCellFirstSection = IndexPath(row: 0, section: 0)
let firstCellSecondSection = IndexPath(row: 0, section: 1)
firstDataSource.stub(44, asHeightForRowAt: firstCellFirstSection)
secondDataSource.stub(22, asHeightForRowAt: firstCellSecondSection)
XCTAssertEqual(44, composition.tableView(tableView, heightForRowAt: firstCellFirstSection))
XCTAssertEqual(22, composition.tableView(tableView, heightForRowAt: firstCellSecondSection))
}
func testTitleForFooterInSectionInferredFromSection() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
composition.append(firstDataSource)
composition.append(secondDataSource)
firstDataSource.stub("First section footer", asTitleForFooterInSection: 0)
secondDataSource.stub("Second section footer", asTitleForFooterInSection: 1)
XCTAssertEqual("First section footer", composition.tableView(tableView, titleForFooterInSection: 0))
XCTAssertEqual("Second section footer", composition.tableView(tableView, titleForFooterInSection: 1))
}
func testTrailingSwipeActionsConfigurationForRowAtInferredFromSection() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
composition.append(firstDataSource)
composition.append(secondDataSource)
let firstCellFirstSection = IndexPath(row: 0, section: 0)
let firstCellSecondSection = IndexPath(row: 0, section: 1)
let (first, second) = (UISwipeActionsConfiguration(), UISwipeActionsConfiguration())
firstDataSource.stub(first, asTrailingSwipeActionsConfigurationForRowAt: firstCellFirstSection)
secondDataSource.stub(second, asTrailingSwipeActionsConfigurationForRowAt: firstCellSecondSection)
XCTAssertIdentical(
first,
composition.tableView(tableView, trailingSwipeActionsConfigurationForRowAt: firstCellFirstSection)
)
XCTAssertIdentical(
second,
composition.tableView(tableView, trailingSwipeActionsConfigurationForRowAt: firstCellSecondSection)
)
}
func testContextMenuConfigurationForRowAtInferredFromSection() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
composition.append(firstDataSource)
composition.append(secondDataSource)
let firstCellFirstSection = IndexPath(row: 0, section: 0)
let firstCellSecondSection = IndexPath(row: 0, section: 1)
let (first, second) = (UIContextMenuConfiguration(), UIContextMenuConfiguration())
firstDataSource.stub(first, asContextMenuConfigurationForRowAt: firstCellFirstSection)
secondDataSource.stub(second, asContextMenuConfigurationForRowAt: firstCellSecondSection)
XCTAssertIdentical(
first,
composition.tableView(tableView, contextMenuConfigurationForRowAt: firstCellFirstSection, point: .zero)
)
XCTAssertIdentical(
second,
composition.tableView(tableView, contextMenuConfigurationForRowAt: firstCellSecondSection, point: .zero)
)
}
// MARK: Scroll view delegate composition
func testScrollViewDidEndDraggingPropogatedToAllDelegates() {
let (firstDataSource, secondDataSource) = (FakeTableViewMediator(), FakeTableViewMediator())
composition.append(firstDataSource)
composition.append(secondDataSource)
XCTAssertFalse(firstDataSource.notifiedScrollViewDidEndDragging)
XCTAssertFalse(secondDataSource.notifiedScrollViewDidEndDragging)
composition.scrollViewDidEndDragging(tableView, willDecelerate: false)
XCTAssertTrue(firstDataSource.notifiedScrollViewDidEndDragging)
XCTAssertTrue(secondDataSource.notifiedScrollViewDidEndDragging)
}
}
| mit | 3db1cf125668d9c48cc2fa936ce6e688 | 44.233333 | 117 | 0.718497 | 5.824034 | false | true | false | false |
mike4aday/SwiftlySalesforce | Sources/SwiftlySalesforce/DataTransformer.swift | 1 | 647 | import Foundation
public protocol DataTransformer {
associatedtype Output
func transform(data: Data) throws -> Output
}
public extension DataTransformer {
func transform(data: Data) throws -> Output where Output: Decodable {
try JSONDecoder.salesforce.decode(Output.self, from: data)
}
func transform(data: Data) throws -> Output where Output == Data {
return data
}
func transform(data: Data) throws -> Output where Output == String {
return String(data: data) ?? ""
}
func transform(data: Data) throws -> Output where Output == Void {
return
}
}
| mit | 380f324ce398abcfd3968162d52651e6 | 23.884615 | 73 | 0.63524 | 4.688406 | false | false | false | false |
sebastianvarela/iOS-Swift-Helpers | Helpers/Helpers/Value.swift | 2 | 2079 | import Foundation
public struct Value: ValueProtocol, CustomStringConvertible, JSONDecodable, JSONEncodable {
public let id: Int
public var value: String
public init(id: Int, value: String) {
self.id = id
self.value = value
}
// MARK: - Protocol JSONDecodable:
public static func create(fromJSON json: JSON) -> Value? {
guard let id = json["id"] as? Int,
let value = json["value"] as? String else {
print("❌❌❌ Invalid Value metadata!")
return nil
}
return Value(id: id, value: value)
}
// MARK: - Protocol JSONEncodable:
public func toJSON() -> JSON {
return ["id": id, "value": value]
}
// MARK: - Protocol CustomStringConvertible:
public var description: String {
return "Value: \(id) ➡ \(value)"
}
}
public protocol ValueProtocol: Equatable {
var id: Int { get }
var value: String { get }
}
public extension Sequence where Iterator.Element == Value {
public func find(byValueId id: Int) -> Value? {
if let element = filter({ $0.id == id }).first {
return element
}
return nil
}
}
public extension Array where Element: ValueProtocol {
mutating public func upsert(value: Element) {
if let element = filter({ $0 == value }).first,
let index = index(of: element) {
remove(at: index)
insert(value, at: index)
} else {
append(value)
}
}
mutating public func replace(valueId id: Int, withValue value: String) -> Bool {
guard let newElement = Value(id: id, value: value) as? Element else {
return false
}
if let element = filter({ $0.id == id }).first,
let index = index(of: element) {
remove(at: index)
insert(newElement, at: index)
return true
}
return false
}
}
public func == (lhs: Value, rhs: Value) -> Bool {
return lhs.id == rhs.id
}
| mit | 775f486d736664a77659b4da9e257726 | 26.613333 | 91 | 0.553356 | 4.278926 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Requests/LandingURL/LandingURLResponseHandler.swift | 1 | 2328 | //
// LandingURLResponseHandler.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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 ObjectMapper
class LandingURLResponseHandler: ResponseHandler {
fileprivate let completion: LandingURLClosure?
init(completion: LandingURLClosure?) {
self.completion = completion
}
override func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) {
if let response = response,
let mappers = Mapper<LandingURLMapper>().mapArray(JSONObject: response["data"]) {
let landingUrls = mappers.map({ LandingURL(mapper: $0) })
executeOnMainQueue { self.completion?(landingUrls, ErrorTransformer.errorFromResponse(response, error: error)) }
} else if let response = response,
let mapper = Mapper<LandingURLMapper>().map(JSON: response["data"] as! [String : Any]) {
let landingURL = LandingURL(mapper: mapper)
executeOnMainQueue { self.completion?([landingURL], ErrorTransformer.errorFromResponse(response, error: error)) }
} else {
executeOnMainQueue { self.completion?(nil, ErrorTransformer.errorFromResponse(response, error: error)) }
}
}
}
| mit | 021961280ef9005e4fdb56792bccd74c | 48.531915 | 125 | 0.716495 | 4.628231 | false | false | false | false |
yokoe/luckybeast-ios | luckybeast/BossCoreView.swift | 1 | 2753 | import UIKit
class BossCoreView: UIView {
private static let padding: CGFloat = 10
private static let indicatorPadding: CGFloat = 10
private static let indicatorDivisions = 20
var mode: LuckyBeast.Mode = .idle {
didSet {
if mode == .thinking {
startIndicatorTimer()
} else {
stopIndicatorTimer()
}
setNeedsDisplay()
}
}
private var timerStartedAt: Date?
override func draw(_ rect: CGRect) {
UIColor.black.setFill()
UIRectFill(bounds)
drawBackground()
if mode == .thinking {
drawIndicator()
}
}
private func drawBackground() {
switch mode {
case .idle:
UIColor.darkGray.setFill()
case .launching:
UIColor.yellow.setFill()
case .listening, .thinking:
UIColor.lightGray.setFill()
case .playing:
UIColor.green.setFill()
case .panic:
UIColor.white.setFill()
}
UIBezierPath(ovalIn: bounds.insetBy(dx: BossCoreView.padding, dy: BossCoreView.padding)).fill()
}
private func drawIndicator() {
let centerX = bounds.midX
let centerY = bounds.midY
let indicatorRadius = min(centerX, centerY) - BossCoreView.indicatorPadding - BossCoreView.padding
let timeElapsed = -(timerStartedAt?.timeIntervalSinceNow ?? 0)
let indicatorProgress = TimeInterval(Int(round(timeElapsed * 100)) % 100) * 0.01
for i in 0...BossCoreView.indicatorDivisions {
let alpha: CGFloat = indicatorProgress * 4 - TimeInterval(i) * 0.1 > 0 ? 1 : 0
UIColor(white: 1, alpha: min(alpha, 1)).setStroke()
let angle = CGFloat(i) / CGFloat(BossCoreView.indicatorDivisions) * 2 * CGFloat.pi - CGFloat.pi * 0.5
let path = UIBezierPath()
path.move(to: CGPoint(x: centerX + cos(angle) * indicatorRadius, y: centerY + sin(angle) * indicatorRadius))
path.addLine(to: CGPoint(x: centerX + cos(angle) * indicatorRadius * 0.7, y: centerY + sin(angle) * indicatorRadius * 0.7))
path.lineWidth = 10
path.stroke()
}
}
// Indicator timer
private var indicatorTimer: Timer?
private func startIndicatorTimer() {
if indicatorTimer == nil {
timerStartedAt = Date()
indicatorTimer = Timer.scheduledTimer(withTimeInterval: 0.03, repeats: true) { timer in
self.setNeedsDisplay()
}
}
}
private func stopIndicatorTimer() {
indicatorTimer?.invalidate()
indicatorTimer = nil
}
}
| mit | bb0b53832cd580654aa2fec4da7d9db8 | 32.168675 | 135 | 0.574646 | 4.642496 | false | false | false | false |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Frontend/Editor/IMGLYBoxGradientView.swift | 1 | 8133 | //
// Created by Carsten Przyluczky on 01/03/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import UIKit
public struct Line {
public let start: CGPoint
public let end: CGPoint
}
public class IMGLYBoxGradientView : UIView {
public var centerPoint = CGPointZero
public weak var gradientViewDelegate: IMGLYGradientViewDelegate?
public var controllPoint1 = CGPointZero
private var controllPoint2_ = CGPointZero
public var controllPoint2:CGPoint {
get {
return controllPoint2_
}
set (point) {
controllPoint2_ = point
calculateCenterPointFromOtherControlPoints()
layoutCrosshair()
setNeedsDisplay()
if gradientViewDelegate != nil {
gradientViewDelegate!.controlPointChanged()
}
}
}
public var normalizedControlPoint1:CGPoint {
get {
return CGPointMake(controllPoint1.x / frame.size.width, controllPoint1.y / frame.size.height)
}
}
public var normalizedControlPoint2:CGPoint {
get {
return CGPointMake(controllPoint2.x / frame.size.width, controllPoint2.y / frame.size.height)
}
}
private var crossImageView_ = UIImageView()
private var setup = false
// MARK:- setup
public override init(frame:CGRect) {
super.init(frame:frame)
commonInit()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
public func commonInit() {
if setup {
return
}
setup = true
backgroundColor = UIColor.clearColor()
configureControlPoints()
configureCrossImageView()
configurePanGestureRecognizer()
configurePinchGestureRecognizer()
}
public func configureControlPoints() {
controllPoint1 = CGPointMake(100,100);
controllPoint2 = CGPointMake(150,200);
calculateCenterPointFromOtherControlPoints()
}
public func configureCrossImageView() {
crossImageView_.image = UIImage(named: "crosshair", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection:nil)
crossImageView_.userInteractionEnabled = true
crossImageView_.frame = CGRectMake(0, 0, crossImageView_.image!.size.width, crossImageView_.image!.size.height)
addSubview(crossImageView_)
}
public func configurePanGestureRecognizer() {
let panGestureRecognizer = UIPanGestureRecognizer(target:self, action:"handlePanGesture:")
addGestureRecognizer(panGestureRecognizer)
crossImageView_.addGestureRecognizer(panGestureRecognizer)
}
public func configurePinchGestureRecognizer() {
let pinchGestureRecognizer = UIPinchGestureRecognizer(target:self, action:"handlePinchGesture:")
addGestureRecognizer(pinchGestureRecognizer)
}
// MARK:- Drawing
public func diagonalLengthOfFrame() -> CGFloat {
return sqrt(frame.size.width * frame.size.width +
frame.size.height * frame.size.height)
}
public func normalizedOrtogonalVector() -> CGPoint {
let diffX = controllPoint2.x - controllPoint1.x
let diffY = controllPoint2.y - controllPoint1.y
let diffLength = sqrt(diffX * diffX + diffY * diffY)
return CGPointMake( -diffY / diffLength, diffX / diffLength)
}
public func distanceBetweenControlPoints() -> CGFloat {
let diffX = controllPoint2.x - controllPoint1.x
let diffY = controllPoint2.y - controllPoint1.y
return sqrt(diffX * diffX + diffY * diffY)
}
/*
This method appears a bit tricky, but its not.
We just take the vector that connects the control points,
and rotate it by 90 degrees. Then we normalize it and give it a total
lenghts that is the lenght of the diagonal, of the Frame.
That diagonal is the longest line that can be drawn in the Frame, therefore its a good orientation.
*/
public func lineForControlPoint(controlPoint:CGPoint) -> Line {
let ortogonalVector = normalizedOrtogonalVector()
let halfDiagonalLengthOfFrame = diagonalLengthOfFrame()
let scaledOrthogonalVector = CGPointMake(halfDiagonalLengthOfFrame * ortogonalVector.x,
halfDiagonalLengthOfFrame * ortogonalVector.y)
let lineStart = CGPointMake(controlPoint.x - scaledOrthogonalVector.x,
controlPoint.y - scaledOrthogonalVector.y)
let lineEnd = CGPointMake(controlPoint.x + scaledOrthogonalVector.x,
controlPoint.y + scaledOrthogonalVector.y)
return Line(start: lineStart, end: lineEnd);
}
public func addLineForControlPoint1ToPath(path:UIBezierPath) {
let line = lineForControlPoint(controllPoint1)
path.moveToPoint(line.start)
path.addLineToPoint(line.end)
}
public func addLineForControlPoint2ToPath(path:UIBezierPath) {
let line = lineForControlPoint(controllPoint2)
path.moveToPoint(line.start)
path.addLineToPoint(line.end)
}
public override func drawRect(rect: CGRect) {
let aPath = UIBezierPath()
UIColor(white: 0.8, alpha: 1.0).setStroke()
addLineForControlPoint1ToPath(aPath)
addLineForControlPoint2ToPath(aPath)
aPath.closePath()
aPath.lineWidth = 1
aPath.stroke()
}
// MARK:- gesture handling
public func calculateCenterPointFromOtherControlPoints() {
centerPoint = CGPointMake((controllPoint1.x + controllPoint2.x) / 2.0,
(controllPoint1.y + controllPoint2.y) / 2.0);
}
public func informDeletageAboutRecognizerStates(#recognizer: UIGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
if gradientViewDelegate != nil {
gradientViewDelegate!.userInteractionStarted()
}
}
if recognizer.state == UIGestureRecognizerState.Ended ||
recognizer.state == UIGestureRecognizerState.Cancelled {
if gradientViewDelegate != nil {
gradientViewDelegate!.userInteractionEnded()
}
}
}
public func handlePanGesture(recognizer: UIPanGestureRecognizer) {
let location = recognizer.locationInView(self)
informDeletageAboutRecognizerStates(recognizer: recognizer)
let diffX = location.x - centerPoint.x
let diffY = location.y - centerPoint.y
controllPoint1 = CGPointMake(controllPoint1.x + diffX, controllPoint1.y + diffY)
controllPoint2 = CGPointMake(controllPoint2.x + diffX, controllPoint2.y + diffY)
}
public func handlePinchGesture(recognizer:UIPinchGestureRecognizer) {
informDeletageAboutRecognizerStates(recognizer: recognizer)
if recognizer.numberOfTouches() > 1 {
controllPoint1 = recognizer.locationOfTouch(0, inView:self)
controllPoint2 = recognizer.locationOfTouch(1, inView:self)
}
}
public func isPoint(point:CGPoint, inRect rect:CGRect) -> Bool {
let top = rect.origin.y
let bottom = top + rect.size.height
let left = rect.origin.x
let right = left + rect.size.width
let inRectXAxis = point.x > left && point.x < right
let inRectYAxis = point.y > top && point.y < bottom
return (inRectXAxis && inRectYAxis)
}
public override func layoutSubviews() {
super.layoutSubviews()
layoutCrosshair()
setNeedsDisplay()
}
public func layoutCrosshair() {
crossImageView_.center = centerPoint
}
public func centerGUIElements() {
let x1 = frame.size.width * 0.5
let x2 = frame.size.width * 0.5
let y1 = frame.size.height * 0.25
let y2 = frame.size.height * 0.75
controllPoint1 = CGPointMake(x1, y1)
controllPoint2 = CGPointMake(x2, y2)
}
}
| apache-2.0 | d304a356661418e66da9518236bc2eed | 34.671053 | 142 | 0.651666 | 4.77569 | false | false | false | false |
we7ee/WBBubblePopUp | WBBubblePopUp/Classes/WBBubblePopUp.swift | 1 | 5462 | //
// WBBubblePopUp.swift
// Pods
//
// Created by Willy Breitenbach on 24.10.16.
//
// Copyright (c) 2016 Willy Breitenbach <[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
open class WBBubblePopUp: UIView {
// private properties
var popUpLabel : UILabel! // Label
var timeToDisappear = 2.0 // Default time to disappear
var colorBackground : UIColor = .blue
var colorText : UIColor = .white
var cornerRadius : CGFloat = 15
override init(frame : CGRect){
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience init() {
// init with frame, set background color and corner radius
self.init(frame: CGRect(x: 0, y: 70, width: 30, height: 30))
self.backgroundColor = colorBackground
self.layer.cornerRadius = cornerRadius
self.popUpLabel = UILabel(frame: CGRect(origin: CGPoint(x: 10,y: 5), size: CGSize(width: 100, height: 30)))
self.popUpLabel.textColor = colorText
self.popUpLabel.textAlignment = .center
self.popUpLabel.lineBreakMode = .byWordWrapping
self.addSubview(popUpLabel)
}
// show default bubble
open func showDefaultBubble(presentingView: UIView, text: String){
//setText(text)
updateFrame(withText: text)
//presentingView.addSubview(self)
showAnimated(presentigView: presentingView)
}
// show bubble with costum background color and duration time
open func showCostumBubble(presentingView: UIView, text: String, bckColor: UIColor, duration: Double){
//setText(text)
colorBackground = bckColor
self.timeToDisappear = duration
updateFrame(withText: text)
//presentingView.addSubview(self)
showAnimated(presentigView: presentingView)
}
// show costum bubble
open func showCostumBubble(presentingView: UIView, text: String, bckColor: UIColor, txtColor: UIColor, duration: Double, cornerRadius: CGFloat){
//setText(text)
colorText = txtColor
colorBackground = bckColor
self.cornerRadius = cornerRadius
self.timeToDisappear = duration
updateFrame(withText: text)
presentingView.addSubview(self)
}
// TODO: Remove bubble view
open func dismiss(){
}
// update size of buuble frame and text frame
func updateFrame(withText: String){
popUpLabel.text = withText
popUpLabel.sizeToFit()
self.backgroundColor = colorBackground
self.layer.cornerRadius = cornerRadius
self.popUpLabel.textColor = colorText
let screenSize = UIScreen.main.bounds
// line of text wider than screen
if self.popUpLabel.frame.size.width+20 >= screenSize.width {
self.popUpLabel.numberOfLines = 0
self.popUpLabel.frame.size.width = screenSize.width-40
self.popUpLabel.sizeToFit()
self.frame.size.width = screenSize.width-20
self.frame.size.height = (self.popUpLabel.frame.size.height) + 10
}
else{
self.frame.size.width = self.popUpLabel.frame.size.width+20
self.frame.size.height = self.popUpLabel.frame.size.height+10
}
self.frame.origin = CGPoint(x: screenSize.width/2-self.frame.size.width/2, y: 70)
}
// animate up to down
func showAnimated(presentigView: UIView){
presentigView.addSubview(self)
self.frame.origin.y = -50
UIView.animate(withDuration: 0.2, animations: {
self.frame.origin.y = 70
}, completion: {
(value: Bool) in
DispatchQueue.main.asyncAfter(deadline: .now() + self.timeToDisappear) { // in half a second...
self.removeAnimated()
}
})
}
// remove bubble animated
func removeAnimated(){
UIView.animate(withDuration: 0.2, animations: {
self.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.frame.origin.y = -70
}, completion: {
(value: Bool) in
self.removeFromSuperview()
})
}
}
| mit | 5d252fc1747ee80075577a9c260d694b | 33.352201 | 148 | 0.634932 | 4.502885 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | byuSuite/Apps/MyFinancialCenter/controller/MFCUnpaidChargesViewController.swift | 2 | 6174 | //
// MFCUnpaidChargesViewController.swift
// byuSuite
//
// Created by Eric Romrell on 5/4/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import UIKit
private let TABLE_FOOTER_TEXT = "No Current Unpaid Charges"
private let CHECKED_IMAGE = UIImage(named: "checkmark")
private let NOT_CHECKED_IMAGE = UIImage(named: "blank_checkmark")
class MFCUnpaidChargesViewController: ByuTableDataViewController {
//MARK: Outlets
@IBOutlet private weak var totalView: UIView!
@IBOutlet private weak var checkout: UIView!
@IBOutlet private weak var totalLabel: UILabel!
//MARK: Properties
private var refreshControl = UIRefreshControl()
private var selectedIndexPaths = [IndexPath]()
//This will return a tuple containing (interactionEnabled, alphaValue) for the checkout button
private var isEnabled: (Bool, CGFloat) {
return selectedIndexPaths.count == 0 ? (false, 0.5) : (true, 1)
}
override func viewDidLoad() {
super.viewDidLoad()
refreshControl = tableView.addDefaultRefreshControl(target: self, action: #selector(loadCharges))
tableView.variableHeightForRows()
tableView.registerNib(nibName: "MFCTransactionTableViewCell")
loadCharges()
NotificationCenter.default.addObserver(self, selector: #selector(self.loadCharges), name: PAYMENT_COMPLETED_NOTIFICATION, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.navigationItem.title = "Unpaid Charges"
}
deinit {
NotificationCenter.default.removeObserver(self, name: PAYMENT_COMPLETED_NOTIFICATION, object: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "choosePaymentSource",
let navVc = segue.destination as? UINavigationController,
let vc = navVc.topViewController as? PaymentSourceViewController {
let rows = tableData.rows(inSection: 0)
vc.feature = .mfc
vc.mfcCharges = selectedIndexPaths.map { rows[$0.row].object as! MFCCharge }
}
}
//MARK: ByuTableDataViewController Methods
override func getEmptyTableViewText() -> String {
return TABLE_FOOTER_TEXT
}
//MARK: UITableViewDatasoure/Delegate callbacks
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableData.dequeueCell(forTableView: tableView, atIndexPath: indexPath) as? MFCTransactionTableViewCell,
let charge = tableData.row(forIndexPath: indexPath).object as? MFCCharge {
cell.transaction = charge
//Change the color of the due date text if it's past due
if let dueDate = charge.dueDate, dueDate < Date() {
cell.dateLabel.textColor = .byuRed
}
let imageView = UIImageView(image: selectedIndexPaths.contains(indexPath) ? CHECKED_IMAGE : NOT_CHECKED_IMAGE)
imageView.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
cell.accessoryView = imageView
cell.selectionStyle = .none
return cell
} else { return UITableViewCell() }
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Allows for multiple selection of cells; adds the newly seleted cell to the array of selected cells if it isn't already part of the array
if let index = selectedIndexPaths.index(of: indexPath) {
selectedIndexPaths.remove(at: index)
} else {
selectedIndexPaths.append(indexPath)
}
updateTotal()
tableView.reloadData()
}
//MARK: Listeners
//This method cannot be private in order for the NotificationCenter to reach it
@objc func loadCharges() {
refreshControl.beginRefreshing()
//Reset the selections and bottom bar
selectedIndexPaths = []
updateTotal()
tableView.isUserInteractionEnabled = false
MFCClient.getUnpaidCharges { (charges, error, statusCode) in
self.refreshControl.endRefreshing()
if let charges = charges {
self.tableView.isUserInteractionEnabled = true
if charges.count == 0 {
self.tableData = TableData()
} else {
self.tableData = TableData(rows: charges.map { return Row(object: $0) })
}
self.tableView.reloadData()
} else {
if statusCode == 418 {
//MFC decided to return a status code of 418 if the tuition calc process had an error. If this is the case, display the error then retry the call
super.displayAlert(error: error, alertHandler: { (_) in
self.loadCharges()
})
} else if statusCode == 409 {
//MFC decided to return a status code of 409 if the tuition calc process needs to run. This will require a different title and popback.
super.displayAlert(error: error, title: "Recalculating Tuition...")
}else {
super.displayAlert(error: error)
}
}
}
}
//MARK: Private functions
private func updateTotal() {
//Because the interactionEnabled and alpha should always change in sync, we used a tuple variable to load each of them
(checkout.isUserInteractionEnabled, checkout.alpha) = isEnabled
//Sum the charges
let total = selectedIndexPaths.reduce(0.0, { (total, indexPath) -> Double in
let charge = tableData.rows(inSection: 0)[indexPath.row].object as? MFCCharge
return total + (charge?.amount ?? 0)
})
totalLabel.text = "Total: \(MFCUtils.convertToCurrency(value: total))"
}
}
| apache-2.0 | b85e810e3f45eccd40650fcd9281f191 | 38.318471 | 165 | 0.62336 | 5.006488 | false | false | false | false |
tredds/pixelthoughts | PixelThoughts/StarsView.swift | 1 | 2976 | //
// StarsView.swift
// PixelThoughts
//
// Created by Victor Tatarasanu on 22/12/15.
// Copyright © 2015 Victor Tatarasanu. All rights reserved.
//
import UIKit
class StarsView: UIView {
// MARK: - Properties -
var snowLayer: CAEmitterLayer? = nil
// MARK: - Initialization -
override init(frame: CGRect)
{
super.init(frame: frame)
self.initialize()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.initialize()
}
func initialize()
{
self.backgroundColor = UIColor(colorLiteralRed: 27/255.0, green: 39/255.0, blue: 53/255.0, alpha: 1)
}
// MARK: - UIView Methods -
override class func layerClass() -> AnyClass
{
return CAEmitterLayer.self
}
override func layoutSubviews() {
super.layoutSubviews()
self.prepare()
}
// MARK: - Private Methods -
private func prepare()
{
guard let
closeCell = self.star(speed: 80, lifetime: Float(self.frame.size.height) * 20, size: CGSize(width:10, height:10), birthRate: 1, color: UIColor.whiteColor()),
nearCell = self.star(speed: 24, lifetime: Float(self.frame.size.height), size: CGSize(width:6, height:6), birthRate: 3, color: UIColor.whiteColor()),
farCell = self.star(speed: 18, lifetime: Float(self.frame.size.height), size: CGSize(width:2, height:2), birthRate: 20, color: UIColor.whiteColor())
//TODO: add asteroid
else {
return
}
let snowLayer: CAEmitterLayer = self.makeEmitter()
snowLayer.emitterCells = [closeCell, nearCell, farCell]
self.snowLayer = snowLayer
self.layer.addSublayer(snowLayer)
}
private func makeEmitter() -> CAEmitterLayer
{
let emitterLayer: CAEmitterLayer = CAEmitterLayer()
emitterLayer.name = "starsLayer"
emitterLayer.emitterPosition = CGPoint(x: CGRectGetMidX(frame), y: self.frame.size.height)
emitterLayer.emitterSize = CGSizeMake(self.bounds.size.width, 2)
emitterLayer.emitterShape = kCAEmitterLayerLine
emitterLayer.emitterMode = kCAEmitterLayerSurface
return emitterLayer
}
func star(speed speed: CGFloat, lifetime: Float, size: CGSize, birthRate: Float, color: UIColor) -> CAEmitterCell?
{
guard let image = StarsService.sharedInstance.circleImage(size, color: color) else {
return nil
}
let emitterCell: CAEmitterCell = CAEmitterCell()
emitterCell.name = "star"
emitterCell.enabled = true
emitterCell.contents = image.CGImage
emitterCell.color = color.CGColor
emitterCell.lifetime = lifetime
emitterCell.birthRate = birthRate
emitterCell.velocity = speed
return emitterCell
}
}
| mit | bde5f3414dc85bc0d20a378d23ec929e | 29.357143 | 169 | 0.612101 | 4.528158 | false | false | false | false |
irisapp/das-quadrat | Demo/Demo-iOS/Demo-iOS/VenueTipsViewController.swift | 1 | 2012 | //
// VenueDetailViewController.swift
// Demo-iOS
//
// Created by Constantine Fry on 29/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
import UIKit
import QuadratTouch
/** Shows tips related to a venue. */
class VenueTipsViewController: UITableViewController {
var venueId: String?
var session: Session!
var tips: [JSONParameters]?
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44
let task = self.session.venues.get(self.venueId!) {
(result) -> Void in
if let response = result.response {
if let venue = response["venue"] as? JSONParameters,
let tips = venue["tips"] as? JSONParameters {
var tipItems = [JSONParameters]()
if let groups = tips["groups"] as? [JSONParameters] {
for group in groups {
if let item = group["items"] as? [JSONParameters] {
tipItems += item
}
}
}
self.tips = tipItems
}
} else {
// Show error.
}
self.tableView.reloadData()
}
task.start()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let tips = self.tips {
return tips.count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let tip = self.tips![indexPath.row]
cell.textLabel?.text = tip["text"] as? String
return cell
}
}
| bsd-2-clause | 909c4d5c9ae10e47f3782b3056c5b428 | 32.533333 | 118 | 0.544235 | 5.239583 | false | false | false | false |
bradhilton/August | Sources/Request/_RequestBuilder/_RequestBuilder+Url.swift | 1 | 2392 | //
// Request+UrlBuilder.swift
// Request
//
// Created by Bradley Hilton on 1/21/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
extension _RequestBuilder {
fileprivate func modify(_ handler: (inout Url) -> ()) -> Self {
return modify { (request: inout Request) in handler(&request.url) }
}
public func url(_ string: String) -> Self {
return modify { (url: inout Url) in url = Url(string) }
}
public func scheme(_ scheme: String?) -> Self {
return modify { (url: inout Url) in url.scheme = scheme }
}
public func user(_ user: String?) -> Self {
return modify { (url: inout Url) in url.user = user }
}
public func password(_ password: String?) -> Self {
return modify { (url: inout Url) in url.password = password }
}
public func host(_ host: String?) -> Self {
return modify { (url: inout Url) in url.host = host }
}
public func port(_ port: Int?) -> Self {
return modify { (url: inout Url) in url.port = port }
}
public func path(_ path: String) -> Self {
return modify { (url: inout Url) in url.path = path }
}
public func appendPath(_ path: String) -> Self {
return modify { (url: inout Url) in url.path += path }
}
public func query(_ query: String?) -> Self {
return modify { (url: inout Url) in url.query = query }
}
public func appendQuery(_ query: String) -> Self {
return modify { (url: inout Url) in
if let originalQuery = url.query, !originalQuery.isEmpty {
url.query = "\(originalQuery)&\(query)"
} else {
url.query = query
}
}
}
public func queryItems(_ queryItems: QueryItems?) -> Self {
return modify { (url: inout Url) in url.queryItems = queryItems?.items }
}
public func appendQueryItems(_ queryItems: QueryItems) -> Self {
return modify { (url: inout Url) in
if let originalQueryItems = url.queryItems {
url.queryItems = originalQueryItems + queryItems.items
} else {
url.queryItems = queryItems.items
}
}
}
public func fragment(_ fragment: String?) -> Self {
return modify { (url: inout Url) in url.fragment = fragment }
}
}
| mit | 566fd1ba411f1d23f3e845173cbbb42b | 29.265823 | 80 | 0.558762 | 4.216931 | false | false | false | false |
zhaobin19918183/zhaobinCode | HTK/HTK/HomeViewController/CarVIewController/CarViewController.swift | 1 | 4427 | //
// CarViewController.swift
// HTK
//
// Created by Zhao.bin on 16/5/20.
// Copyright © 2016年 赵斌. All rights reserved.
//
import UIKit
class CarViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var bustableview: UITableView!
var navigationItemtitle = String()
var detailDic = NSMutableDictionary()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "公交"
self.tabBarController?.tabBar.isHidden = true
let nextItem=UIBarButtonItem(title:" < 返回 ",style:.plain,target:self,action:#selector(backHomeView))
self.navigationItem.leftBarButtonItem = nextItem
busCarPresentationData()
}
func busCarPresentationData()
{
print(detailDic.value(forKey: "result")![0].allKeys)
}
func backHomeView()
{
self.navigationController!.popViewController(animated: true)
self.tabBarController?.tabBar.isHidden = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let initIdentifier : String = "BusCarTableViewCell"
var cell : BusCarTableViewCell? = tableView.dequeueReusableCell(withIdentifier: initIdentifier) as? BusCarTableViewCell
if cell == nil
{
let nibArray = Bundle.main.loadNibNamed("BusCarTableViewCell", owner: self, options: nil)
cell = nibArray?.first as? BusCarTableViewCell
}
cell?.busCarStationdesList(detailDic.value(forKey: "result")?.object(at: (indexPath as NSIndexPath).section).value(forKey: "stationdes") as! NSMutableArray, index: indexPath)
cell!.selectionStyle = UITableViewCellSelectionStyle.none
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return "\(((detailDic.value(forKey: "result")! as AnyObject).object(at: section) as AnyObject).value(forKey: "key_name") as! String ) 首班车:\(((detailDic.value(forKey: "result")! as AnyObject).object(at: section) as AnyObject).value(forKey: "start_time") as! String ) 末班车:\(((detailDic.value(forKey: "result")! as AnyObject).object(at: section) as AnyObject).value(forKey: "end_time") as! String) "
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return ((((detailDic.value(forKey: "result") as AnyObject).object(at: section) as AnyObject).value(forKey: "stationdes") as AnyObject).count)!
}
//MARK:HeaderTitle
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "HeaderTableViewCell") as! HeaderTableViewCell
headerCell.busNameLabel.text = ((detailDic.value(forKey: "result") as AnyObject).object(at: section) as AnyObject).value(forKey: "key_name") as? String
headerCell.fitstStationNameLabel.text = ((detailDic.value(forKey: "result") as AnyObject).object(at: section) as AnyObject).value(forKey: "terminal_name") as? String
headerCell.endStationNameLabel.text = ((detailDic.value(forKey: "result") as AnyObject).object(at: section) as AnyObject).value(forKey: "front_name") as? String
headerCell.firstBusTimeLabel.text = ((detailDic.value(forKey: "result") as AnyObject).object(at: section) as AnyObject).value(forKey: "start_time") as? String
headerCell.endBusTImeLabel.text = ((detailDic.value(forKey: "result") as AnyObject).object(at: section) as AnyObject).value(forKey: "end_time") as? String
return headerCell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
return 40
}
func numberOfSections(in tableView: UITableView) -> Int
{
return ((detailDic.value(forKey: "result") as AnyObject).count)!
}
}
| gpl-3.0 | b378489a6c24ce2b717030b6f159245c | 39.740741 | 413 | 0.662273 | 4.612159 | false | false | false | false |
omiz/In-Air | In Air/Source/WeatherManager.swift | 1 | 3133 | //
// WeatherManager.swift
// In Air
//
// Created by Omar Allaham on 3/29/17.
// Copyright © 2017 Bemaxnet. All rights reserved.
//
import Foundation
import ObjectMapper
import Alamofire
class WeatherManager {
static let shared = WeatherManager()
let base = "https://query.yahooapis.com/v1/public/yql?"
func forecast(for location: String, onUpdate: @escaping ((WeatherForecast?, Error?) -> Void)) {
Alamofire.request(base, parameters: parameter(for: location)).responseObject { (response: DataResponse<WeatherForecast>) in
switch response.result {
case .success(let value):
onUpdate(value, nil)
case .failure(let error):
onUpdate(nil, error)
}
}
}
fileprivate func parameter(for location: String) -> [String: Any] {
var param: [String:Any] = [:]
param["q"] = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"\(location)\")"
param["format"] = "json"
param["env"] = "store://datatables.org/alltableswithkeys"
return param
}
}
class WeatherForecast: Mappable {
var city: String?
var country: String?
var region: String?
var windDirection: Double = 0
var windSpeed: Double = 0
var pressure: Double = 0
var visibility: Double = 0
var link: String?
var imageURL: String?
var distanceUnit: String?
var pressureUnit: String?
var speedUnit: String?
var temperatureUnit: String?
let transform = TransformOf<Double, String>(fromJSON: { (value: String?) -> Double? in
guard let value = value else {
return nil
}
guard let double = Double(value) else {
return nil
}
return Darwin.floor(double * 10) / 10
}, toJSON: { (value: Double?) -> String? in
// transform value from Int? to String?
if let value = value {
return String(value)
}
return nil
})
required init?(map: Map) {
}
func mapping(map: Map) {
link <- map["query.results.channel.link"]
city <- map["query.results.channel.location.city"]
country <- map["query.results.channel.location.country"]
region <- map["query.results.channel.location.region"]
windDirection <- (map["query.results.channel.wind.direction"], transform)
windSpeed <- (map["query.results.channel.wind.speed"], transform)
pressure <- (map["query.results.channel.atmosphere.pressure"], transform)
visibility <- (map["query.results.channel.atmosphere.visibility"], transform)
imageURL <- map["query.results.channel.image.url"]
distanceUnit <- map["query.results.channel.units.distance"]
pressureUnit <- map["query.results.channel.units.pressure"]
speedUnit <- map["query.results.channel.units.speed"]
temperatureUnit <- map["query.results.channel.units.temperature"]
}
}
extension Double {
func roundTo(places:Int) -> Double {
let multiplier = pow(0, Double(places))
return Darwin.floor(self * multiplier) / multiplier
}
}
| apache-2.0 | 74cabb6b857f34fc21e69e87a1c28ef8 | 28 | 129 | 0.630907 | 4.025707 | false | false | false | false |
tardieu/swift | test/Interpreter/generic_casts.swift | 31 | 4642 | // RUN: %target-run-simple-swift | %FileCheck %s
// RUN: %target-build-swift -O %s -o %t/a.out.optimized
// RUN: %target-run %t/a.out.optimized | %FileCheck %s
// REQUIRES: executable_test
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
func allToInt<T>(_ x: T) -> Int {
return x as! Int
}
func allToIntOrZero<T>(_ x: T) -> Int {
if x is Int {
return x as! Int
}
return 0
}
func anyToInt(_ x: Any) -> Int {
return x as! Int
}
func anyToIntOrZero(_ x: Any) -> Int {
if x is Int {
return x as! Int
}
return 0
}
protocol Class : class {}
class C : Class {
func print() { Swift.print("C!") }
}
class D : C {
override func print() { Swift.print("D!") }
}
class E : C {
override func print() { Swift.print("E!") }
}
class X : Class {
}
func allToC<T>(_ x: T) -> C {
return x as! C
}
func allToCOrE<T>(_ x: T) -> C {
if x is C {
return x as! C
}
return E()
}
func anyToC(_ x: Any) -> C {
return x as! C
}
func anyToCOrE(_ x: Any) -> C {
if x is C {
return x as! C
}
return E()
}
func allClassesToC<T : Class>(_ x: T) -> C {
return x as! C
}
func allClassesToCOrE<T : Class>(_ x: T) -> C {
if x is C {
return x as! C
}
return E()
}
func anyClassToC(_ x: Class) -> C {
return x as! C
}
func anyClassToCOrE(_ x: Class) -> C {
if x is C {
return x as! C
}
return E()
}
func allToAll<T, U>(_ t: T, _: U.Type) -> Bool {
return t is U
}
func allMetasToAllMetas<T, U>(_: T.Type, _: U.Type) -> Bool {
return T.self is U.Type
}
print(allToInt(22)) // CHECK: 22
print(anyToInt(44)) // CHECK: 44
allToC(C()).print() // CHECK: C!
allToC(D()).print() // CHECK: D!
anyToC(C()).print() // CHECK: C!
anyToC(D()).print() // CHECK: D!
allClassesToC(C()).print() // CHECK: C!
allClassesToC(D()).print() // CHECK: D!
anyClassToC(C()).print() // CHECK: C!
anyClassToC(D()).print() // CHECK: D!
print(allToIntOrZero(55)) // CHECK: 55
print(allToIntOrZero("fifty-five")) // CHECK: 0
print(anyToIntOrZero(88)) // CHECK: 88
print(anyToIntOrZero("eighty-eight")) // CHECK: 0
allToCOrE(C()).print() // CHECK: C!
allToCOrE(D()).print() // CHECK: D!
allToCOrE(143).print() // CHECK: E!
allToCOrE(X()).print() // CHECK: E!
anyToCOrE(C()).print() // CHECK: C!
anyToCOrE(D()).print() // CHECK: D!
anyToCOrE(143).print() // CHECK: E!
anyToCOrE(X()).print() // CHECK: E!
allClassesToCOrE(C()).print() // CHECK: C!
allClassesToCOrE(D()).print() // CHECK: D!
allClassesToCOrE(X()).print() // CHECK: E!
anyClassToCOrE(C()).print() // CHECK: C!
anyClassToCOrE(D()).print() // CHECK: D!
anyClassToCOrE(X()).print() // CHECK: E!
// CHECK-LABEL: type comparisons:
print("type comparisons:\n")
print(allMetasToAllMetas(Int.self, Int.self)) // CHECK: true
print(allMetasToAllMetas(Int.self, Float.self)) // CHECK: false
print(allMetasToAllMetas(C.self, C.self)) // CHECK: true
print(allMetasToAllMetas(D.self, C.self)) // CHECK: true
print(allMetasToAllMetas(C.self, D.self)) // CHECK: false
print(C.self is D.Type) // CHECK: false
print((D.self as C.Type) is D.Type) // CHECK: true
let t: Any.Type = type(of: 1 as Any)
print(t is Int.Type) // CHECK: true
print(t is Float.Type) // CHECK: false
print(t is C.Type) // CHECK: false
let u: Any.Type = type(of: (D() as Any))
print(u is C.Type) // CHECK: true
print(u is D.Type) // CHECK: true
print(u is E.Type) // CHECK: false
print(u is Int.Type) // CHECK: false
// FIXME: Can't spell AnyObject.Protocol
// CHECK-LABEL: AnyObject casts:
print("AnyObject casts:")
print(allToAll(C(), AnyObject.self)) // CHECK-NEXT: true
print(allToAll(type(of: C()), AnyObject.self)) // CHECK-NEXT: true
// Bridging
print(allToAll(0, AnyObject.self)) // CHECK-NEXT: true
// This will get bridged using _SwiftValue.
struct NotBridged { var x: Int }
print(allToAll(NotBridged(x: 0), AnyObject.self)) // CHECK-NEXT: true
print(allToAll(NotBridged(x: 0), NSCopying.self)) // CHECK-NEXT: true
// These casts fail (intentionally) even though _SwiftValue does
// technically conform to these protocols through NSObject.
print(allToAll(NotBridged(x: 0), CustomStringConvertible.self)) // CHECK-NEXT: false
print(allToAll(NotBridged(x: 0), (AnyObject & CustomStringConvertible).self)) // CHECK-NEXT: false
//
// rdar://problem/19482567
//
func swiftOptimizesThisFunctionIncorrectly() -> Bool {
let anArray = [] as NSArray
if let whyThisIsNeverExecutedIfCalledFromFunctionAndNotFromMethod = anArray as? [NSObject] {
return true
}
return false
}
let result = swiftOptimizesThisFunctionIncorrectly()
print("Bridge cast result: \(result)") // CHECK-NEXT: Bridge cast result: true
| apache-2.0 | 5634c9341669ed5e74ad67a4a2e9fb2a | 23.956989 | 98 | 0.644334 | 3.039948 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.